Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): swizzle reports the npm packages a copy imports (#10502)

Cindy Zhang3231fc223d04
diff --git a/.changeset/swizzle-reports-npm-deps.md b/.changeset/swizzle-reports-npm-deps.md
new file mode 100644
index 0000000000..c61ce51168
--- /dev/null
+++ b/.changeset/swizzle-reports-npm-deps.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx swizzle` reports the npm packages a copy imports, such as `d3-scale` for a chart, with the version range the owner package declares, so the copy builds once you install them. The `swizzle.copy` receipt lists them in `dependencies`, and the text output names them to install. Node's built-in modules and the owner package itself are not listed.
+
+@cixzhang
diff --git a/packages/cli/api/swizzle/_moduleGraph.mjs b/packages/cli/api/swizzle/_moduleGraph.mjs
index 3bc9b8e566..7d4794a624 100644
--- a/packages/cli/api/swizzle/_moduleGraph.mjs
+++ b/packages/cli/api/swizzle/_moduleGraph.mjs
@@ -12,6 +12,8 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {isBuiltin} from 'node:module';
+import {packageOf} from '../../foundation/render/served-packages.mjs';
import {parse} from '@babel/parser';
import {
inspectPackageExport,
@@ -388,6 +390,9 @@ function publicSurfaceOf(packageDir, srcRoot, originsOf) {
* file the copy holds (absolute source path), with the edits its imports need
* @property {Map<string, Set<string>>} dependsOn file -> carried files its
* computed specifiers point at
+ * @property {Record<string, string>} dependencies each npm package the copied
+ * files import, other than the owner package and Node's built-in modules,
+ * with the range the owner package declares
*/
/**
@@ -454,6 +459,8 @@ export function planCopy({
const files = new Map();
/** @type {CopyPlan['dependsOn']} */
const dependsOn = new Map();
+ /** @type {Set<string>} */
+ const packages = new Set();
const queue = [...entries];
const queued = new Set(queue);
/** @param {string} file */
@@ -554,7 +561,12 @@ export function planCopy({
files.set(file, {code: parsed.code, edits});
if (!CODE_FILE.test(file)) continue;
for (const ref of parsed.references) {
- if (!ref.source.startsWith('.')) continue;
+ if (!ref.source.startsWith('.')) {
+ const builtin = ref.source.startsWith('node:') || isBuiltin(ref.source);
+ const name = packageOf(ref.source);
+ if (!builtin && name !== ownerPackage) packages.add(name);
+ continue;
+ }
const target = resolveRelative(file, ref.source, resolutions);
// A dangling import is left for the build to report.
if (!target) continue;
@@ -585,7 +597,7 @@ export function planCopy({
edits.push(planReference(file, parsed.code, ref, target));
}
}
- return {files, dependsOn};
+ return {files, dependsOn, dependencies: declaredRanges(packageDir, packages)};
/**
* Decide one reference that leaves the component folder.
@@ -669,6 +681,35 @@ export function planCopy({
}
}
+/**
+ * The version range the owner package declares for each npm package the copy
+ * imports, by name; `*` for one it does not declare.
+ * @param {string} packageDir
+ * @param {Iterable<string>} names
+ * @returns {Record<string, string>}
+ */
+function declaredRanges(packageDir, names) {
+ /** @type {Record<string, Record<string, string>>} */
+ let manifest = {};
+ try {
+ manifest = JSON.parse(
+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),
+ );
+ } catch {
+ // An unreadable manifest declares nothing.
+ }
+ /** @type {Record<string, string>} */
+ const ranges = {};
+ for (const name of [...names].sort()) {
+ ranges[name] =
+ manifest.dependencies?.[name] ??
+ manifest.optionalDependencies?.[name] ??
+ manifest.peerDependencies?.[name] ??
+ '*';
+ }
+ return ranges;
+}
+
/**
* An edit that replaces only the string literal of a reference.
* @param {string} code
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index af8408ca3c..1e6e445344 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -514,6 +514,7 @@ export async function swizzleCopy(component, options = {}) {
filesCopied: copied,
files: outputs.map(o => toPosix(path.relative(outputDir, o.dest))),
usesStyleX: outputs.some(o => o.content.includes('@stylexjs/stylex')),
+ dependencies: plan.dependencies,
};
if (feedback) data.feedback = feedback;
return {type: 'swizzle.copy', package: data.package, data};
diff --git a/packages/cli/api/swizzle/copy/copy.test.mjs b/packages/cli/api/swizzle/copy/copy.test.mjs
index 6ba6116e9c..b7770d0281 100644
--- a/packages/cli/api/swizzle/copy/copy.test.mjs
+++ b/packages/cli/api/swizzle/copy/copy.test.mjs
@@ -621,6 +621,51 @@ describe('swizzle.copy — helpers an earlier swizzle wrote (spec:AST-110 FR2)',
);
});
+describe('swizzle.copy — the npm packages a copy imports (spec:AST-110 FR1)', () => {
+ /** @type {string} */
+ let project;
+ beforeEach(() => {
+ project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-swizzle-deps-'));
+ fs.writeFileSync(path.join(project, 'package.json'), JSON.stringify({name: 'consumer', version: '1.0.0'}));
+ const core = path.join(project, 'node_modules/@astryxdesign/core');
+ fs.mkdirSync(path.join(core, 'src/Chart'), {recursive: true});
+ fs.writeFileSync(
+ path.join(core, 'package.json'),
+ JSON.stringify({
+ name: '@astryxdesign/core',
+ version: '1.0.0',
+ dependencies: {'d3-scale': '^4.0.2'},
+ peerDependencies: {react: '^19.0.0'},
+ }),
+ );
+ fs.writeFileSync(path.join(core, 'src/Chart/index.ts'), "export {Chart} from './Chart';\n");
+ fs.writeFileSync(
+ path.join(core, 'src/Chart/Chart.tsx'),
+ [
+ "import {scaleLinear} from 'd3-scale';",
+ "import type {ReactNode} from 'react';",
+ "import {readFileSync} from 'node:fs';",
+ "import {join} from 'path';",
+ "import {undeclared} from '@acme/undeclared/sub';",
+ 'export const Chart = (): ReactNode => [scaleLinear, readFileSync, join, undeclared] && null;',
+ '',
+ ].join('\n'),
+ );
+ });
+ afterEach(() => {
+ fs.rmSync(project, {recursive: true, force: true});
+ });
+
+ it('reports each package with the range the owner declares, and never Node built-ins', async () => {
+ const r = await swizzle('Chart', {cwd: project});
+ expect(r.data.dependencies).toEqual({
+ '@acme/undeclared': '*',
+ 'd3-scale': '^4.0.2',
+ react: '^19.0.0',
+ });
+ });
+});
+
describe('swizzle.copy — a name the package exports only as a type (spec:AST-110 FR1)', () => {
/** @type {string} */
let project;
diff --git a/packages/cli/api/swizzle/swizzle.doc.mjs b/packages/cli/api/swizzle/swizzle.doc.mjs
index e72a4e31dc..a712eee1ae 100644
--- a/packages/cli/api/swizzle/swizzle.doc.mjs
+++ b/packages/cli/api/swizzle/swizzle.doc.mjs
@@ -21,7 +21,8 @@ export const doc = {
'the owner package exports: names the package exports are imported from its ' +
'public paths, and every internal module the component needs is ' +
"copied beside it in the package's folder layout. Tests, stories and docs are not " +
- 'copied. The receipt flags whether any copied file uses StyleX. With no name ' +
+ 'copied. The receipt flags whether any copied file uses StyleX and lists each npm ' +
+ 'package the copy imports with the range the owner package declares. With no name ' +
'(or list) it returns the swizzlable component names instead. An integration ' +
'component that replaces a Core component is what that Core name copies; ' +
"options.package '@astryxdesign/core' copies the original. The list names Core " +
diff --git a/packages/cli/api/swizzle/swizzle.type.mjs b/packages/cli/api/swizzle/swizzle.type.mjs
index 9066d95137..75868e04c4 100644
--- a/packages/cli/api/swizzle/swizzle.type.mjs
+++ b/packages/cli/api/swizzle/swizzle.type.mjs
@@ -36,6 +36,7 @@
* @property {number} data.filesCopied
* @property {string[]} data.files Copied file names, relative to the component folder; the internal modules copied beside it start with `../` (spec:AST-110 FR2).
* @property {boolean} data.usesStyleX Whether any copied file uses StyleX (requires build-time setup).
+ * @property {Record<string, string>} data.dependencies Each npm package the copied files import, other than the owner package, with the version range the owner package declares (`*` when it declares none). The copy builds once the product installs them (spec:AST-110 FR1).
* @property {SwizzleFeedback} [data.feedback]
*/
diff --git a/packages/cli/clients/cli/commands/swizzle.doc.mjs b/packages/cli/clients/cli/commands/swizzle.doc.mjs
index 7407cc16a7..617917cd87 100644
--- a/packages/cli/clients/cli/commands/swizzle.doc.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.doc.mjs
@@ -20,7 +20,9 @@ export const doc = {
'names a file the copy holds or a path the package exports: names the package ' +
'exports come from the package, and every internal module the component needs ' +
"is copied beside it in the package's folder layout. " +
- 'Tests, stories and docs are not copied. With no name it lists the swizzlable components. ' +
+ 'Tests, stories and docs are not copied. It lists the npm packages the copy imports, ' +
+ 'with the ranges the owner package declares, to install if your project lacks them. ' +
+ 'With no name it lists the swizzlable components. ' +
'An integration component that replaces a Core component is what that Core name ' +
'copies; --package @astryxdesign/core copies the original. --list lists Core ' +
'components, including one an integration replaces.',
diff --git a/packages/cli/clients/cli/commands/swizzle.mjs b/packages/cli/clients/cli/commands/swizzle.mjs
index 73c7eb4e0c..7aca687ba2 100644
--- a/packages/cli/clients/cli/commands/swizzle.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.mjs
@@ -100,6 +100,19 @@ export function registerSwizzle(program) {
);
}
+ // npm packages the copy imports, each range quoted so the list pastes
+ // safely after an install command.
+ const dependencies = Object.entries(result.data.dependencies ?? {});
+ if (dependencies.length > 0) {
+ out.push(
+ text(
+ `It imports these npm packages; install any your project lacks: ${dependencies
+ .map(([name, range]) => (range === '*' ? name : `${name}@"${range}"`))
+ .join(' ')}`,
+ ),
+ );
+ }
+
// StyleX build requirement — swizzled StyleX source throws on import
// ("Unexpected 'stylex.create' call at runtime") unless the consumer's
// build runs a StyleX compiler, so the page does not render at all.
diff --git a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
index 3736cf900e..6528ce1543 100644
--- a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
@@ -177,6 +177,27 @@ describe('swizzle — core feedback routing via config', () => {
});
});
+describe('swizzle — the npm packages a copy imports', () => {
+ it('prints an install line with each range quoted for the shell', async () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ const core = path.join(project, 'node_modules', '@astryxdesign', 'core');
+ const manifest = JSON.parse(fs.readFileSync(path.join(core, 'package.json'), 'utf-8'));
+ manifest.dependencies = {'d3-scale': '^4.0.2'};
+ manifest.peerDependencies = {react: '>=19.0.0'};
+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify(manifest));
+ fs.writeFileSync(
+ path.join(core, 'src', 'Button', 'Button.tsx'),
+ `import {scaleLinear} from 'd3-scale';\nimport {useState} from 'react';\nexport const Button = () => [scaleLinear, useState];\n`,
+ );
+
+ const result = await runCli(['swizzle', 'Button', '-f'], project);
+ expect(result.code).toBe(0);
+ expect(result.stdout).toContain(`d3-scale@"^4.0.2"`);
+ expect(result.stdout).toContain(`react@">=19.0.0"`);
+ });
+});
+
describe('swizzle — integration-owned components', () => {
it('copies the component and the unexported helper it imports, without its test or doc, and routes feedback to the integration issuesUrl', async () => {
buildFakeCore(project);