Skip to content

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

TypeScript

fix(cli): swizzle copies the module graph a component reaches (#10197)

Cindy Zhang3c69236c12a5
diff --git a/.changeset/swizzle-copies-module-graph.md b/.changeset/swizzle-copies-module-graph.md
new file mode 100644
index 0000000000..a125e3a31f
--- /dev/null
+++ b/.changeset/swizzle-copies-module-graph.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Every import in an `astryx swizzle` copy now names a file the copy holds or a path the owner package exports. Before, the copy sent every import that left the component folder to the package's folder entry, which does not export the internal helpers most components use, so `Button`, `Dialog`, `Table` and about 100 other copies failed to type-check or bundle. Now the copy imports what the package exports from the package, carries every internal module it needs beside it in the package's folder layout, and copies the nested folders it imports (such as `Table`'s `plugins/`). Test helpers and notes are no longer copied. A helper an earlier swizzle wrote is reused when it is the same and is never replaced by a copy that carries it, even with `--overwrite`: a different one stays, and the new copy writes its own under a version-suffixed name. Swizzling the component whose folder holds that helper treats it as one of that component's own files, which `--overwrite` replaces. A private attribute owner module and the style modules it imports are the exception, as before: a changed copy fails the command without `--overwrite` and is replaced with it. Fixes #3506.
+
+@cixzhang @jiunshinn
diff --git a/packages/cli/api/swizzle/_adapter.mjs b/packages/cli/api/swizzle/_adapter.mjs
index 5417581393..708499d0e8 100644
--- a/packages/cli/api/swizzle/_adapter.mjs
+++ b/packages/cli/api/swizzle/_adapter.mjs
@@ -9,7 +9,8 @@
* for its "component not found" suggestions. Resolving core + listing lives
* here once so neither leaf re-walks the filesystem. Throws AstryxError
* (ERR_CORE_NOT_FOUND) when core can't be located. The copy receipt's `gh`
- * lookup is here too, on the shared search-path walk.
+ * lookup is here too, on the shared search-path walk, and so is the copy's
+ * module graph (_moduleGraph.mjs), which reads the owner package's source.
*/
import {executablesOnSearchPath} from '../../foundation/env/search-path.mjs';
@@ -18,6 +19,8 @@ import {resolveComponentReplacements} from '../../foundation/discovery/component
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {AstryxError} from '../error.mjs';
+export {planCopy, relativeSpecifierBetween, renderFile} from './_moduleGraph.mjs';
+
/**
* Whether an executable `gh` is on `PATH` (with a `PATHEXT` extension on
* Windows), found without running it. The copy receipt offers its
diff --git a/packages/cli/api/swizzle/_moduleGraph.mjs b/packages/cli/api/swizzle/_moduleGraph.mjs
new file mode 100644
index 0000000000..3bc9b8e566
--- /dev/null
+++ b/packages/cli/api/swizzle/_moduleGraph.mjs
@@ -0,0 +1,754 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file swizzle.copy module graph — decides, for each module a component
+ * reaches, whether the copy imports it from the owner package's public
+ * exports or carries it in the output.
+ *
+ * @input the owner package's source root and `exports` map, the component folder
+ * @output the files the copy holds, each with its rewritten source
+ * @position api/swizzle adapter helper; the copy leaf reaches it through _adapter.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {parse} from '@babel/parser';
+import {
+ inspectPackageExport,
+ sourceExportTarget,
+} from '../../foundation/discovery/package-exports.mjs';
+import {
+ moduleExportOrigins,
+ resolveLocalModule,
+} from '../../foundation/discovery/module-exports.mjs';
+import {
+ allTargets,
+ isRecord,
+ subpathDeclaration,
+} from '../../foundation/integrations/exports-subpaths.mjs';
+
+/** The extensions an extensionless import may name, in resolution order. */
+const CODE_FILE = /\.[cm]?[jt]sx?$/;
+const DECLARATION_FILE = /\.d\.[cm]?ts$/;
+const STYLEX_FILE = /\.stylex\.[cm]?[jt]sx?$/;
+
+/** @param {string} file */
+const toPosix = file => file.split(path.sep).join('/');
+
+/**
+ * The file an import names, or null when no file is there.
+ * @param {string} fromFile absolute path of the importing file
+ * @param {string} specifier a relative specifier
+ * @param {Map<string, string|null>} cache resolutions already made in this copy
+ * @returns {string|null}
+ */
+function resolveRelative(fromFile, specifier, cache) {
+ const base = path.resolve(path.dirname(fromFile), specifier);
+ const known = cache.get(base);
+ if (known !== undefined) return known;
+ const found = resolveLocalModule(specifier, fromFile);
+ cache.set(base, found);
+ return found;
+}
+
+/**
+ * @typedef {object} ImportSpecifier
+ * @property {string} imported the exported name (`default` for a default import)
+ * @property {string} local
+ * @property {boolean} typeOnly
+ *
+ * @typedef {object} ModuleReference
+ * @property {'named'|'namespace'|'sideEffect'|'dynamic'|'reexportAll'|'reexportNamed'} kind
+ * @property {string} source the specifier as written
+ * @property {number} start statement (or, for `import()`, string literal) start
+ * @property {number} end
+ * @property {boolean} typeOnly the whole statement is `import type` / `export type`
+ * @property {ImportSpecifier[]} specifiers
+ * @property {string} [namespace] the local name of `* as X`
+ *
+ * @typedef {object} ParsedModule
+ * @property {string} code
+ * @property {ModuleReference[]} references
+ * @property {Set<string>} declares names the module declares and exports
+
+ */
+
+/**
+ * A module's source and every module reference in it: static imports and
+ * re-exports, `import()` calls, and `import('…')` types.
+ * @param {string} file
+ * @returns {ParsedModule}
+ */
+function parseModule(file) {
+ const code = fs.readFileSync(file, 'utf-8');
+ /** @type {ParsedModule} */
+ const parsed = {code, references: [], declares: new Set()};
+ if (!CODE_FILE.test(file)) return parsed;
+ const ast = parse(code, {
+ sourceType: 'module',
+ errorRecovery: true,
+ plugins: /\.[cm]?tsx?$/.test(file) ? ['typescript', 'jsx'] : ['jsx'],
+ });
+ const {references} = parsed;
+ // Babel's node types mark positions optional; a parsed file always has them.
+ for (const node of /** @type {any[]} */ (ast.program.body)) {
+ for (const d of node.declaration?.declarations ?? [node.declaration]) {
+ if (node.type === 'ExportNamedDeclaration' && d?.id?.name)
+ parsed.declares.add(d.id.name);
+ }
+ if (node.type === 'ImportDeclaration') {
+ const typeOnly = node.importKind === 'type';
+ const base = {
+ source: node.source.value,
+ start: node.start,
+ end: node.end,
+ typeOnly,
+ };
+ const namespace = node.specifiers.find(
+ (/** @type {any} */ s) => s.type === 'ImportNamespaceSpecifier',
+ );
+ const named = node.specifiers.filter(
+ (/** @type {any} */ s) => s.type !== 'ImportNamespaceSpecifier',
+ );
+ if (node.specifiers.length === 0) {
+ references.push({...base, kind: 'sideEffect', specifiers: []});
+ } else if (namespace && named.length === 0) {
+ references.push({
+ ...base,
+ kind: 'namespace',
+ specifiers: [],
+ namespace: namespace.local.name,
+ });
+ } else if (!namespace) {
+ references.push({
+ ...base,
+ kind: 'named',
+ specifiers: named.map((/** @type {any} */ s) => ({
+ imported:
+ s.type === 'ImportDefaultSpecifier'
+ ? 'default'
+ : s.imported.type === 'StringLiteral'
+ ? s.imported.value
+ : s.imported.name,
+ local: s.local.name,
+ typeOnly: typeOnly || s.importKind === 'type',
+ })),
+ });
+ } else {
+ // `import X, * as Y from` names the whole module.
+ references.push({...base, kind: 'namespace', specifiers: []});
+ }
+ } else if (node.type === 'ExportAllDeclaration') {
+ references.push({
+ kind: 'reexportAll',
+ source: node.source.value,
+ start: node.start,
+ end: node.end,
+ typeOnly: node.exportKind === 'type',
+ specifiers: [],
+ });
+ } else if (node.type === 'ExportNamedDeclaration' && node.source) {
+ const typeOnly = node.exportKind === 'type';
+ references.push({
+ kind: 'reexportNamed',
+ source: node.source.value,
+ start: node.start,
+ end: node.end,
+ typeOnly,
+ specifiers: node.specifiers.map((/** @type {any} */ s) => ({
+ imported: s.type === 'ExportNamespaceSpecifier' ? '*' : s.local.name,
+ local:
+ s.exported.type === 'StringLiteral'
+ ? s.exported.value
+ : s.exported.name,
+ typeOnly: typeOnly || s.exportKind === 'type',
+ })),
+ });
+ }
+ }
+ visitDynamicReferences(ast.program, literal => {
+ references.push({
+ kind: 'dynamic',
+ source: literal.value,
+ start: literal.start,
+ end: literal.end,
+ typeOnly: false,
+ specifiers: [],
+ });
+ });
+ return parsed;
+}
+
+/**
+ * Call `onLiteral` with the string literal of every `import('…')` call and
+ * `import('…')` type under a node.
+ * @param {any} node
+ * @param {(literal: {value: string, start: number, end: number}) => void} onLiteral
+ */
+function visitDynamicReferences(node, onLiteral) {
+ if (node == null || typeof node !== 'object') return;
+ if (Array.isArray(node)) {
+ for (const child of node) visitDynamicReferences(child, onLiteral);
+ return;
+ }
+ if (
+ node.type === 'CallExpression' &&
+ node.callee?.type === 'Import' &&
+ node.arguments[0]?.type === 'StringLiteral'
+ ) {
+ onLiteral(node.arguments[0]);
+ } else if (
+ node.type === 'ImportExpression' &&
+ node.source?.type === 'StringLiteral'
+ ) {
+ onLiteral(node.source);
+ } else if (node.type === 'TSImportType') {
+ const literal =
+ node.argument?.type === 'TSLiteralType'
+ ? node.argument.literal
+ : node.argument;
+ if (literal?.type === 'StringLiteral') onLiteral(literal);
+ }
+ for (const key of Object.keys(node)) {
+ if (
+ key === 'loc' ||
+ key === 'leadingComments' ||
+ key === 'trailingComments' ||
+ key === 'innerComments'
+ )
+ continue;
+ const value = node[key];
+ if (value && typeof value === 'object')
+ visitDynamicReferences(value, onLiteral);
+ }
+}
+
+/**
+ * @typedef {'value' | 'type'} ExportKind `value` reads runtime exports only;
+ * `type` reads type-only exports too
+ *
+ * @typedef {(file: string, kind: ExportKind) => Map<string, {file: string, name: string}>} OriginsOf
+ * every name a module exports, with where it is declared
+ *
+ * @typedef {Map<string, Array<{subpath: string, name: string}>>} ExportersByOrigin
+ * `file#name` of a declaration -> the subpaths that export it, and as what
+ *
+ * @typedef {object} PublicSurface
+ * @property {Record<ExportKind, ExportersByOrigin>} byOrigin the subpaths
+ * that export each declaration as a value, and as a value or a type
+ * @property {Map<string, string>} byFile source file -> the subpath that
+ * exports exactly that file
+ * @property {Record<string, unknown>|undefined} exportsField
+ */
+
+/**
+ * Every public subpath of a package with the source file under `root` that
+ * the shared export readers give it. `./internal/*` is never public.
+ * @param {{exports?: unknown}} pkg
+ * @param {string} packageDir
+ * @param {string} root
+ * @returns {Array<[string, string]>}
+ */
+function exportedSourceFiles(pkg, packageDir, root) {
+ const exportsField = pkg.exports;
+ const subpathMap =
+ isRecord(exportsField) &&
+ Object.keys(exportsField).some(key => key.startsWith('.'));
+ const candidates = new Set(['.']);
+ if (subpathMap) {
+ for (const [key, value] of Object.entries(exportsField)) {
+ if (!key.includes('*')) {
+ candidates.add(key);
+ continue;
+ }
+ for (const subpath of wildcardSubpaths(packageDir, root, key, value)) {
+ candidates.add(subpath);
+ }
+ }
+ }
+ /** @type {Array<[string, string]>} */
+ const found = [];
+ for (const subpath of candidates) {
+ if (/^\.\/internal(\/|$)/.test(subpath)) continue;
+ const inspected = inspectPackageExport(pkg, packageDir, subpath);
+ if (!inspected.exported) continue;
+ const file =
+ sourceExportTarget(pkg, packageDir, subpath) ?? inspected.target;
+ if (
+ file &&
+ file.startsWith(root + path.sep) &&
+ !DECLARATION_FILE.test(file)
+ ) {
+ found.push([subpath, file]);
+ }
+ }
+ return found;
+}
+
+/**
+ * The subpaths a `*` key names: one per file its target patterns match.
+ * @param {string} packageDir
+ * @param {string} root
+ * @param {string} key
+ * @param {unknown} value
+ * @returns {string[]}
+ */
+function wildcardSubpaths(packageDir, root, key, value) {
+ /** @type {string[]} */
+ const subpaths = [];
+ for (const pattern of allTargets(value)) {
+ if (!pattern.startsWith('./') || !pattern.includes('*')) continue;
+ const fixed = pattern.slice(2, pattern.indexOf('*'));
+ const base = path.resolve(
+ packageDir,
+ fixed.slice(0, fixed.lastIndexOf('/') + 1),
+ );
+ if (!base.startsWith(root) || !fs.existsSync(base)) continue;
+ for (const entry of fs.readdirSync(base, {
+ recursive: true,
+ withFileTypes: true,
+ })) {
+ if (!entry.isFile()) continue;
+ const file = path.join(entry.parentPath, entry.name);
+ if (path.relative(base, file).split(path.sep).includes('node_modules'))
+ continue;
+ const rel = toPosix(path.relative(packageDir, file));
+ if (!rel.startsWith(fixed)) continue;
+ const rest = rel.slice(fixed.length);
+ for (let end = 1; end <= rest.length; end++) {
+ const star = rest.slice(0, end);
+ if (pattern.slice(2).replaceAll('*', star) === rel) {
+ subpaths.push(key.replace('*', star));
+ break;
+ }
+ }
+ }
+ }
+ return subpaths;
+}
+
+/**
+ * The owner package's public surface, read from its `exports` map: each
+ * subpath with a `source` condition under the source root, and the
+ * declarations it exports. `./internal/*` subpaths are not public.
+ * @param {string} packageDir
+ * @param {string} srcRoot
+ * @param {OriginsOf} originsOf
+ * @returns {PublicSurface}
+ */
+function publicSurfaceOf(packageDir, srcRoot, originsOf) {
+ /** @type {{exports?: unknown}} */
+ let pkg;
+ try {
+ pkg = JSON.parse(
+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),
+ );
+ } catch {
+ pkg = {};
+ }
+ const exportsField =
+ pkg.exports && typeof pkg.exports === 'object'
+ ? /** @type {Record<string, unknown>} */ (pkg.exports)
+ : undefined;
+ /** @type {PublicSurface['byOrigin']} */
+ const byOrigin = {value: new Map(), type: new Map()};
+ /** @type {PublicSurface['byFile']} */
+ const byFile = new Map();
+ for (const [subpath, sourceFile] of exportedSourceFiles(
+ pkg,
+ packageDir,
+ srcRoot,
+ )) {
+ byFile.set(sourceFile, subpath);
+ if (!CODE_FILE.test(sourceFile)) continue;
+ for (const kind of /** @type {const} */ (['value', 'type'])) {
+ for (const [name, origin] of originsOf(sourceFile, kind)) {
+ const key = `${origin.file}#${origin.name}`;
+ const list = byOrigin[kind].get(key) ?? [];
+ list.push({subpath, name});
+ byOrigin[kind].set(key, list);
+ }
+ }
+ }
+ return {byOrigin, byFile, exportsField};
+}
+
+/**
+ * A specifier that is either fixed (a public subpath) or computed from where
+ * two copied files land.
+ * @typedef {string | {from: string, to: string}} SpecifierChoice
+ *
+ * @typedef {object} PlannedEdit
+ * @property {number} start
+ * @property {number} end
+ * @property {(specifierOf: (choice: SpecifierChoice) => string) => string} render
+ *
+ * @typedef {object} CopyPlan
+ * @property {Map<string, {code: string, edits: PlannedEdit[]}>} files every
+ * 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
+ */
+
+/**
+ * Follow a component's module graph from its entry files and decide what the
+ * copy holds. A module inside the component folder is copied. A module
+ * outside it is reached through the owner package's public exports when every
+ * name taken from it is public there; otherwise the module that defines the
+ * name is copied, and imported by relative path. Tests, stories and docs are
+ * never reached, so they are never copied.
+ *
+ * @param {object} options
+ * @param {string} options.packageDir the owner package root
+ * @param {string} options.srcRoot its source root
+ * @param {string} options.componentDir
+ * @param {string} options.ownerPackage
+ * @param {string[]} options.entries absolute entry files of the component
+ * @returns {CopyPlan}
+ */
+export function planCopy({
+ packageDir,
+ srcRoot,
+ componentDir,
+ ownerPackage,
+ entries,
+}) {
+ // Every read is cached for this copy only, so a later copy sees the
+ // package as it is then.
+ const exportMemos = {value: new Map(), type: new Map()};
+ /** @type {OriginsOf} */
+ const originsOf = (file, kind) =>
+ moduleExportOrigins(file, {
+ types: kind === 'type',
+ memo: exportMemos[kind],
+ });
+ /** @param {string} file @param {string} name */
+ const originOf = (file, name) => originsOf(file, 'type').get(name) ?? null;
+ /**
+ * The subpaths that export a module's export: as a value when the import
+ * takes a value, since a type-only export is erased at runtime.
+ * @param {string} file
+ * @param {string} name
+ * @param {boolean} typeOnly
+ */
+ const exportersOf = (file, name, typeOnly) => {
+ const origin = originOf(file, name);
+ if (!origin) return [];
+ const kind = typeOnly ? 'type' : 'value';
+ return surface.byOrigin[kind].get(`${origin.file}#${origin.name}`) ?? [];
+ };
+ /**
+ * The name a module exports one of its own bindings under, or null.
+ * @param {{file: string, name: string}} origin
+ */
+ const exportNameOf = origin => {
+ for (const [name, found] of originsOf(origin.file, 'type')) {
+ if (found.file === origin.file && found.name === origin.name) return name;
+ }
+ return null;
+ };
+ /** @type {Map<string, string|null>} */
+ const resolutions = new Map();
+ const surface = publicSurfaceOf(packageDir, srcRoot, originsOf);
+ /** @type {CopyPlan['files']} */
+ const files = new Map();
+ /** @type {CopyPlan['dependsOn']} */
+ const dependsOn = new Map();
+ const queue = [...entries];
+ const queued = new Set(queue);
+ /** @param {string} file */
+ const enqueue = file => {
+ if (!queued.has(file)) {
+ queued.add(file);
+ queue.push(file);
+ }
+ };
+ /** @param {string} file */
+ const inComponent = file => file.startsWith(componentDir + path.sep);
+ /** @param {string} file */
+ const inSource = file => file.startsWith(srcRoot + path.sep);
+
+ /**
+ * The subpath that exports every name a module exports, with the same
+ * definition. An exactly exported file is its own subpath.
+ * @param {string} file
+ * @returns {string|null}
+ */
+ const subpathCoveringModule = file => {
+ const exact = surface.byFile.get(file);
+ if (exact) return exact;
+ const names = [...originsOf(file, 'type').keys()];
+ if (names.length === 0) return null;
+ const values = originsOf(file, 'value');
+ const options = names.map(name =>
+ exportersOf(file, name, !values.has(name))
+ .filter(o => o.name === name)
+ .map(o => o.subpath),
+ );
+ const common = options.reduce((acc, list) =>
+ acc.filter(s => list.includes(s)),
+ );
+ return STYLEX_FILE.test(file) ? null : pickSubpath(common, file);
+ };
+
+ /**
+ * The public subpath to take a name from. A StyleX module is imported by
+ * its own exported path, because the StyleX compiler resolves styles and
+ * variables from the real module; when that path is not exported, there is
+ * no public import.
+ * @param {string[]} subpaths subpaths that export the name
+ * @param {string} target the module the import names
+ * @param {string} [originFile] the module that defines the name
+ * @returns {string|null}
+ */
+ const choosePublic = (subpaths, target, originFile) => {
+ const exact = originFile ? surface.byFile.get(originFile) : undefined;
+ if (exact && subpaths.includes(exact)) return exact;
+ if (
+ STYLEX_FILE.test(target) ||
+ (originFile && STYLEX_FILE.test(originFile))
+ )
+ return null;
+ return pickSubpath(subpaths, target);
+ };
+
+ /**
+ * Prefer the subpath of the module's top folder, then the package root.
+ * @param {string[]} subpaths
+ * @param {string} file
+ * @returns {string|null}
+ */
+ const pickSubpath = (subpaths, file) => {
+ if (subpaths.length === 0) return null;
+ const top = `./${toPosix(path.relative(srcRoot, file)).split('/')[0]}`;
+ return (
+ subpaths.find(s => s === top) ??
+ subpaths.find(s => s === '.') ??
+ [...subpaths].sort((a, b) => a.length - b.length)[0]
+ );
+ };
+
+ /** @param {string} subpath */
+ const publicSpecifier = subpath =>
+ subpath === '.' ? ownerPackage : `${ownerPackage}/${subpath.slice(2)}`;
+
+ /**
+ * Carry a module in the copy.
+ * @param {string} from
+ * @param {string} to
+ * @returns {SpecifierChoice}
+ */
+ const carry = (from, to) => {
+ enqueue(to);
+ const deps = dependsOn.get(from) ?? new Set();
+ deps.add(to);
+ dependsOn.set(from, deps);
+ return {from, to};
+ };
+
+ while (queue.length > 0) {
+ const file = /** @type {string} */ (queue.shift());
+ const parsed = parseModule(file);
+ /** @type {PlannedEdit[]} */
+ const edits = [];
+ files.set(file, {code: parsed.code, edits});
+ if (!CODE_FILE.test(file)) continue;
+ for (const ref of parsed.references) {
+ if (!ref.source.startsWith('.')) continue;
+ const target = resolveRelative(file, ref.source, resolutions);
+ // A dangling import is left for the build to report.
+ if (!target) continue;
+ if (inComponent(target)) {
+ // Files of the component keep their relative imports of each other.
+ if (inComponent(file)) enqueue(target);
+ else edits.push(sourceEdit(parsed.code, ref, carry(file, target)));
+ continue;
+ }
+ if (!CODE_FILE.test(target) || !inSource(target)) {
+ // An asset, such as `../../locales/en.json` or a stylesheet, that the
+ // package exports by its own path is imported from the package.
+ const subpath = `./${toPosix(path.relative(packageDir, target))}`;
+ if (
+ subpathDeclaration(surface.exportsField, subpath).state === 'declared'
+ ) {
+ edits.push(
+ sourceEdit(parsed.code, ref, `${ownerPackage}/${subpath.slice(2)}`),
+ );
+ continue;
+ }
+ // An unexported asset in the source is carried; one outside it is
+ // left for the build to report.
+ if (!inSource(target)) continue;
+ edits.push(sourceEdit(parsed.code, ref, carry(file, target)));
+ continue;
+ }
+ edits.push(planReference(file, parsed.code, ref, target));
+ }
+ }
+ return {files, dependsOn};
+
+ /**
+ * Decide one reference that leaves the component folder.
+ * @param {string} file
+ * @param {string} code
+ * @param {ModuleReference} ref
+ * @param {string} target
+ * @returns {PlannedEdit}
+ */
+ function planReference(file, code, ref, target) {
+ if (ref.kind !== 'named' && ref.kind !== 'reexportNamed') {
+ const covering = subpathCoveringModule(target);
+ return sourceEdit(
+ code,
+ ref,
+ covering ? publicSpecifier(covering) : carry(file, target),
+ );
+ }
+ /** @type {Array<{choice: SpecifierChoice, specs: ImportSpecifier[]}>} */
+ const groups = [];
+ /** @param {SpecifierChoice} choice @param {ImportSpecifier} spec */
+ const add = (choice, spec) => {
+ const same = groups.find(g =>
+ typeof choice === 'string'
+ ? g.choice === choice
+ : typeof g.choice !== 'string' && g.choice.to === choice.to,
+ );
+ if (same) same.specs.push(spec);
+ else groups.push({choice, specs: [spec]});
+ };
+ for (const spec of ref.specifiers) {
+ if (spec.imported === '*') {
+ const covering = subpathCoveringModule(target);
+ add(covering ? publicSpecifier(covering) : carry(file, target), spec);
+ continue;
+ }
+ const origin = originOf(target, spec.imported);
+ const publicOptions = exportersOf(target, spec.imported, spec.typeOnly);
+ const chosen = choosePublic(
+ publicOptions.map(o => o.subpath),
+ target,
+ origin?.file,
+ );
+ if (chosen) {
+ const exported = /** @type {{name: string}} */ (
+ publicOptions.find(o => o.subpath === chosen)
+ ).name;
+ add(publicSpecifier(chosen), {...spec, imported: exported});
+ } else {
+ // Take the name from the module that defines it, so the copy carries
+ // that module and not a whole barrel. An origin names a binding, so
+ // the import uses the name that module exports it under.
+ // A module that declares the name itself, even as an alias, is carried.
+ const definingExport =
+ origin &&
+ origin.file !== target &&
+ inSource(origin.file) &&
+ !parseModule(target).declares.has(spec.imported)
+ ? exportNameOf(origin)
+ : null;
+ if (origin && definingExport != null) {
+ add(carry(file, origin.file), {...spec, imported: definingExport});
+ } else {
+ add(carry(file, target), spec);
+ }
+ }
+ }
+ // One source and the same names: keep the statement as written and swap
+ // only its specifier.
+ const unchangedNames =
+ groups.length === 1 &&
+ groups[0].specs.every(
+ (spec, i) => spec.imported === ref.specifiers[i].imported,
+ );
+ if (unchangedNames) return sourceEdit(code, ref, groups[0].choice);
+ return {
+ start: ref.start,
+ end: ref.end,
+ render: specifierOf => renderStatements(ref, groups, specifierOf),
+ };
+ }
+}
+
+/**
+ * An edit that replaces only the string literal of a reference.
+ * @param {string} code
+ * @param {ModuleReference} ref
+ * @param {SpecifierChoice} choice
+ * @returns {PlannedEdit}
+ */
+function sourceEdit(code, ref, choice) {
+ const slice = code.slice(ref.start, ref.end);
+ const quoted = new RegExp(
+ `(['"])${ref.source.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1`,
+ );
+ const m = slice.match(quoted);
+ const at = m && m.index != null ? ref.start + m.index : ref.start;
+ const length = m ? m[0].length : 0;
+ const quote = m ? m[1] : "'";
+ return {
+ start: at,
+ end: at + length,
+ render: specifierOf =>
+ m ? `${quote}${specifierOf(choice)}${quote}` : slice,
+ };
+}
+
+/**
+ * The statements that replace one named import or re-export, one per source.
+ * @param {ModuleReference} ref
+ * @param {Array<{choice: SpecifierChoice, specs: ImportSpecifier[]}>} groups
+ * @param {(choice: SpecifierChoice) => string} specifierOf
+ */
+function renderStatements(ref, groups, specifierOf) {
+ const keyword = ref.kind === 'reexportNamed' ? 'export' : 'import';
+ const statements = [];
+ for (const {choice, specs} of groups) {
+ const specifier = specifierOf(choice);
+ const star = specs.find(s => s.imported === '*');
+ if (star) statements.push(`export * as ${star.local} from '${specifier}';`);
+ const named = specs.filter(s => s.imported !== '*');
+ if (named.length === 0) continue;
+ const allType = ref.typeOnly || named.every(s => s.typeOnly);
+ const parts = named.map(s => {
+ const prefix = !allType && s.typeOnly ? 'type ' : '';
+ return s.imported === s.local
+ ? `${prefix}${s.local}`
+ : `${prefix}${s.imported} as ${s.local}`;
+ });
+ const head = `${keyword} ${allType ? 'type ' : ''}`;
+ const oneLine = `${head}{${parts.join(', ')}} from '${specifier}';`;
+ statements.push(
+ oneLine.length <= 80
+ ? oneLine
+ : `${head}{\n${parts.map(p => ` ${p},`).join('\n')}\n} from '${specifier}';`,
+ );
+ }
+ return statements.join('\n');
+}
+
+/**
+ * The source of a planned file with its edits applied.
+ * @param {{code: string, edits: PlannedEdit[]}} planned
+ * @param {(choice: SpecifierChoice) => string} specifierOf
+ */
+export function renderFile(planned, specifierOf) {
+ let out = planned.code;
+ for (const edit of [...planned.edits].sort((a, b) => b.start - a.start)) {
+ out =
+ out.slice(0, edit.start) + edit.render(specifierOf) + out.slice(edit.end);
+ }
+ return out;
+}
+
+/**
+ * The relative specifier from one written file to another.
+ * @param {string} fromDest
+ * @param {string} toDest
+ */
+export function relativeSpecifierBetween(fromDest, toDest) {
+ let rel = toPosix(path.relative(path.dirname(fromDest), toDest));
+ rel = DECLARATION_FILE.test(toDest)
+ ? rel.replace(/\.d\.[cm]?ts$/, '')
+ : rel.replace(/\.(?:[cm]?[jt]sx?)$/, '');
+ return rel.startsWith('.') ? rel : `./${rel}`;
+}
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index 20e21ebb69..af8408ca3c 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -2,13 +2,14 @@
/**
* @file swizzle.copy leaf — copy a component's source into the consumer project
- * for customization, rewriting escaping relative imports to the OWNER package's
- * subpaths.
+ * for customization: what the OWNER package exports is imported from it, and
+ * every internal module the component needs is copied beside it.
*
* Side-effecting: writes files and returns a `swizzle.copy` receipt describing
- * what it did. Shared core discovery + component listing come from
- * api/swizzle/_adapter.mjs; everything here (owner resolution, the copy, import
- * rewriting, StyleX detection, maintainer feedback) is copy-specific. Errors
+ * what it did. Shared core discovery, component listing and the module graph
+ * (which modules the copy holds and how each import reads) come from
+ * api/swizzle/_adapter.mjs; owner resolution, where each file lands, reuse of
+ * existing helpers, StyleX detection and maintainer feedback are here. Errors
* throw AstryxError (stable code + suggestions). All human prose /
* package-manager prefixing lives in the CLI renderer.
*/
@@ -17,11 +18,15 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {
checkGhCli,
+ planCopy,
+ relativeSpecifierBetween,
+ renderFile,
resolveComponentReplacement,
resolveCore,
} from '../_adapter.mjs';
import {assertWithin, sanitizeName, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
import {Project} from '../../../foundation/config/project.mjs';
+import {findPackageRoot} from '../../../foundation/fs/paths.mjs';
import {
CORE_PACKAGE,
docStem,
@@ -35,212 +40,71 @@ import {AstryxError, writeFailed} from '../../error.mjs';
/** Default issue tracker for maintainer feedback after swizzling. */
const DEFAULT_ISSUES_URL = 'https://github.com/meta/astryx/issues/new';
-/**
- * Rewrite relative imports that point outside the component directory to use
- * the OWNER package's subpaths. Imports within the copied directory (./x) are
- * left untouched.
- *
- * e.g. with ownerPackage '@astryxdesign/core':
- * '../theme/tokens.stylex' -> '@astryxdesign/core/theme/tokens.stylex'
- * '../utils/mergeProps' -> '@astryxdesign/core/utils'
- * '../../locales/en.json' -> '@astryxdesign/core/locales/en.json'
- * import('../Tooltip/Tooltip') -> import('@astryxdesign/core/Tooltip')
- *
- * Most sibling dirs are barrels, so the top-dir collapse (`../utils/x` ->
- * `<pkg>/utils`) resolves. Two shapes must NOT be collapsed to the top dir:
- * - Asset files (`.json`, `.css`): exported by full subpath (e.g.
- * `./locales/*.json`, `./reset.css`), and collapsing a two-levels-up
- * `../../locales/x.json` would emit the invalid `<pkg>/..`.
- * - StyleX modules (`*.stylex`): the StyleX compiler needs the real module
- * path so it can resolve the styles at compile time. The barrel re-export
- * loses the module identity. Core exports every `.stylex` file by its
- * deep subpath (e.g. `./utils/focusOutline.stylex`,
- * `./theme/tokens.stylex`).
- *
- * @param {string} content
- * @param {string} [ownerPackage]
- * @param {(importPath: string) => boolean} [keep] Imports to leave relative:
- * the modules the copy carries in the same layout (see `sharedModulesOf`).
- */
-export function rewriteImports(content, ownerPackage = CORE_PACKAGE, keep = () => false) {
- /** @param {string} importPath */
- const mapTarget = importPath => {
- // A module the copy carries beside the component keeps its relative path.
- if (keep(importPath)) {
- return importPath;
- }
- // Strip ALL leading `../` so a two-levels-up path never yields `<pkg>/..`.
- const rest = importPath.replace(/^(?:\.\.\/)+/, '');
- const parts = rest.split('/');
- const last = parts[parts.length - 1];
- // Asset files are resolved by exact export / wildcard, never a barrel.
- if (/\.(?:json|css)$/.test(last)) {
- return `${ownerPackage}/${rest}`;
- }
- // StyleX modules need the deep path so the compiler can resolve them.
- if (/\.stylex(?:\.[cm]?[jt]sx?)?$/.test(last)) {
- return `${ownerPackage}/${rest}`;
- }
- return `${ownerPackage}/${parts[0]}`;
- };
- return content
- .replace(
- /(from\s+['"])(\.\.\/[^'"]+)(['"])/g,
- (_m, prefix, importPath, suffix) =>
- `${prefix}${mapTarget(importPath)}${suffix}`,
- )
- .replace(
- /(import\(\s*['"])(\.\.\/[^'"]+)(['"])/g,
- (_m, prefix, importPath, suffix) =>
- `${prefix}${mapTarget(importPath)}${suffix}`,
- );
-}
-
/** A private data attribute's owner module (`architecture:public-component-api` INV23). */
const OWNER_MODULE = /^privateAttributes\/[^/]+\.stylex$/;
/** A StyleX module, with or without its file extension. */
const STYLEX_MODULE = /\.stylex(?:\.[cm]?[jt]sx?)?$/;
-/** The extensions an extensionless import may name, in resolution order. */
-const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mjs', '.js'];
+/** @param {string} packageDir */
+function packageVersionOf(packageDir) {
+ try {
+ return String(JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8')).version ?? '0');
+ } catch {
+ return '0';
+ }
+}
/**
- * The relative import specifiers in a module's source.
- * @param {string} content
+ * Where a component's module graph starts: its folder's index, or else every
+ * source file at the top of the folder.
+ * @param {string} componentDir
* @returns {string[]}
*/
-function relativeImportsOf(content) {
- const found = [];
- for (const re of [
- /from\s+['"](\.\.?\/[^'"]+)['"]/g,
- /import\(\s*['"](\.\.?\/[^'"]+)['"]/g,
- ]) {
- for (const m of content.matchAll(re)) found.push(m[1]);
+function entryFilesOf(componentDir) {
+ for (const name of ['index.ts', 'index.tsx', 'index.mjs', 'index.js']) {
+ const file = path.join(componentDir, name);
+ if (fs.existsSync(file)) return [file];
}
- return found;
+ return fs
+ .readdirSync(componentDir)
+ .filter(f => /\.[cm]?[jt]sx?$/.test(f) && !/\.(?:test|spec|stories|doc)\./.test(f) && !/\.d\.[cm]?ts$/.test(f))
+ .map(f => path.join(componentDir, f))
+ .filter(f => fs.statSync(f).isFile());
}
/**
- * The source file an import resolves to under `srcRoot`, as a path relative to
- * `srcRoot` without its extension (`privateAttributes/press.stylex`), and the
- * file's own relative path; null when it resolves outside `srcRoot` or to no
- * file.
+ * A module path relative to the source root, without its extension.
* @param {string} srcRoot
- * @param {string} fromDir directory of the importing file, relative to srcRoot
- * @param {string} importPath
- * @returns {{module: string, file: string} | null}
+ * @param {string} file
*/
-function resolveSourceModule(srcRoot, fromDir, importPath) {
- const module = path.posix.normalize(path.posix.join(fromDir, importPath));
- if (module.startsWith('..') || path.posix.isAbsolute(module)) return null;
- for (const ext of ['', ...SOURCE_EXTENSIONS]) {
- const file = module + ext;
- const abs = path.join(srcRoot, file);
- if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
- return {
- module: ext ? module : module.replace(/\.[cm]?[jt]sx?$/, ''),
- file,
- };
- }
- }
- return null;
+function toModulePath(srcRoot, file) {
+ return toPosix(path.relative(srcRoot, file)).replace(/\.[cm]?[jt]sx?$/, '');
}
-/**
- * The subpaths the owner package exports (`./theme/tokens.stylex`), read from
- * the nearest package.json above its source root.
- * @param {string} srcRoot
- * @returns {Set<string>}
- */
-function exportedSubpathsOf(srcRoot) {
- let dir = srcRoot;
- for (;;) {
- const manifest = path.join(dir, 'package.json');
- if (fs.existsSync(manifest)) {
- try {
- const {exports} = JSON.parse(fs.readFileSync(manifest, 'utf-8'));
- return new Set(
- exports && typeof exports === 'object' ? Object.keys(exports) : [],
- );
- } catch {
- return new Set();
- }
- }
- const parent = path.dirname(dir);
- if (parent === dir) return new Set();
- dir = parent;
- }
+/** @param {string} file */
+function toPosix(file) {
+ return file.split(path.sep).join('/');
}
/**
- * The modules a copy carries beside the component, in the package's own
- * layout under the output directory (`spec:AST-110` FR4): each private
- * attribute owner module the component imports, and every unexported StyleX
- * module such a carried module imports, transitively. The component's own
- * imports of them, and theirs of each other, stay relative.
- *
- * @param {string} srcRoot the owner package's source root
- * @param {string} componentDir
- * @param {string[]} componentFiles files of the component that are copied
- * @returns {Map<string, string>} module path (relative to srcRoot, no
- * extension) -> its file path relative to srcRoot
+ * @param {string} target
+ * @param {string} root
*/
-export function sharedModulesOf(srcRoot, componentDir, componentFiles) {
- const exported = exportedSubpathsOf(srcRoot);
- const componentRel = path
- .relative(srcRoot, componentDir)
- .split(path.sep)
- .join('/');
- /** @type {Map<string, string>} */
- const carried = new Map();
- /** @type {Array<{fromDir: string, content: string, owner: boolean}>} */
- const queue = componentFiles
- .filter(f => /\.[cm]?[jt]sx?$/.test(f))
- .map(f => ({
- fromDir: componentRel,
- content: fs.readFileSync(path.join(componentDir, f), 'utf-8'),
- owner: false,
- }));
- while (queue.length > 0) {
- const {fromDir, content, owner} = /** @type {typeof queue[number]} */ (
- queue.shift()
- );
- for (const importPath of relativeImportsOf(content)) {
- const target = resolveSourceModule(srcRoot, fromDir, importPath);
- if (target == null || carried.has(target.module)) continue;
- if (target.module.startsWith(componentRel + '/')) continue;
- const isOwner = OWNER_MODULE.test(target.module);
- // A carried module's unexported StyleX dependency travels with it; a
- // component's own imports of other modules are rewritten as before.
- const isPrivateStyle =
- owner &&
- STYLEX_MODULE.test(target.module) &&
- !exported.has(`./${target.module}`);
- if (!isOwner && !isPrivateStyle) continue;
- carried.set(target.module, target.file);
- queue.push({
- fromDir: path.posix.dirname(target.module),
- content: fs.readFileSync(path.join(srcRoot, target.file), 'utf-8'),
- owner: true,
- });
- }
- }
- return carried;
+function isWithin(target, root) {
+ const rel = path.relative(root, target);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
}
/**
- * A `keep` predicate for `rewriteImports`: true for an import that names one
- * of the carried modules from a file in `fromDir`.
- * @param {Map<string, string>} carried
- * @param {string} fromDir relative to the source root
- * @returns {(importPath: string) => boolean}
+ * A helper's file name with the owner version before its extension:
+ * `layerStack.ts` -> `layerStack.v0.7.9.ts`, or `layerStack.v0.7.9-2.ts`.
+ * @param {string} dest
+ * @param {string} version
+ * @param {number} n
*/
-function keepCarried(carried, fromDir) {
- return importPath => {
- const module = path.posix
- .normalize(path.posix.join(fromDir, importPath))
- .replace(/\.[cm]?[jt]sx?$/, '');
- return carried.has(module);
- };
+function versionedPath(dest, version, n) {
+ const ext = /(\.stylex)?\.[cm]?[jt]sx?$/.exec(dest)?.[0] ?? path.extname(dest);
+ const stem = dest.slice(0, dest.length - ext.length);
+ return `${stem}.v${version}${n > 1 ? `-${n}` : ''}${ext}`;
}
/**
@@ -339,20 +203,10 @@ function confineWrite(target, cwd, options) {
}
}
-/** @param {string} file */
-function isExcludedFromCopy(file) {
- return (
- file.includes('.test.') ||
- file.includes('.doc.') ||
- file === 'README.md' ||
- // Browser test harnesses import dev-only packages a consumer cannot resolve.
- /\.spec\.[cm]?[jt]sx?$/.test(file)
- );
-}
-
/**
* Copy one component's source into the consumer project for customization,
- * rewriting escaping relative imports to the owner package's subpaths.
+ * with the internal modules it needs and its imports of the owner package's
+ * public paths.
*
* @param {string} component bare or XDS-prefixed component name
* @param {{cwd?: string, output?: string, package?: string, overwrite?: boolean}} [options]
@@ -463,58 +317,146 @@ export async function swizzleCopy(component, options = {}) {
// writes anything.
const feedback = buildFeedback(dirName, owner.issuesUrl);
- // Pre-flight path and overwrite checks before any mkdir/writeFile.
- const sourceFiles = fs.readdirSync(componentDir).filter(file => {
- if (isExcludedFromCopy(file)) return false;
- return fs.statSync(path.join(componentDir, file)).isFile();
+ // The copy follows the component's module graph through the whole source
+ // root: `src/` when the package has one around the component, else the
+ // package itself.
+ const packageDir = findPackageRoot(componentDir) ?? componentDir;
+ const packageSrc = path.join(packageDir, 'src');
+ const inPackageSrc = componentDir.startsWith(packageSrc + path.sep);
+ const graphRoot = inPackageSrc ? packageSrc : packageDir;
+ // Carried modules keep their layout relative to this folder.
+ const srcRoot = inPackageSrc ? packageSrc : path.dirname(componentDir);
+ const plan = planCopy({
+ packageDir,
+ srcRoot: graphRoot,
+ componentDir,
+ ownerPackage: owner.ownerPackage,
+ entries: entryFilesOf(componentDir),
});
- for (const file of sourceFiles) {
- confineWrite(path.join(outputDir, file), cwd, {
- allowAbsolute: true,
- label: 'output file',
- });
+ const ownerVersion = packageVersionOf(packageDir);
+
+ // Carried modules keep the package's layout around the component folder.
+ const depth = path.relative(srcRoot, componentDir).split(path.sep).length;
+ const shiftedRoot = path.resolve(outputDir, ...Array(depth).fill('..'));
+ const layoutRoot = isWithin(shiftedRoot, outputBase) ? shiftedRoot : outputBase;
+ /** @param {string} file */
+ const isComponentFile = file => file.startsWith(componentDir + path.sep);
+ // A module above that folder, such as `lib/` beside an integration's
+ // `components/`, goes under the output folder by its path in the package.
+ /** @param {string} file */
+ const layoutDestOf = file => {
+ if (isComponentFile(file)) {
+ return path.join(outputDir, path.relative(componentDir, file));
+ }
+ if (file.startsWith(srcRoot + path.sep)) {
+ return path.join(layoutRoot, path.relative(srcRoot, file));
+ }
+ return null;
+ };
+ const allFiles = [...plan.files.keys()];
+ // Such a module takes a folder named after the package when its own path
+ // is already a destination, so two modules never share one file.
+ const takenDests = new Set(
+ allFiles.map(layoutDestOf).filter(dest => dest != null),
+ );
+ /** @type {Map<string, string>} */
+ const rootDests = new Map();
+ for (const file of [...allFiles].sort()) {
+ if (layoutDestOf(file) != null) continue;
+ const packagePath = path.relative(graphRoot, file);
+ let dest = path.join(outputBase, packagePath);
+ for (let n = 1; takenDests.has(dest); n++) {
+ const folder = n === 1 ? path.basename(packageDir) : `${path.basename(packageDir)}-${n}`;
+ dest = path.join(outputBase, folder, packagePath);
+ }
+ takenDests.add(dest);
+ rootDests.set(file, dest);
+ }
+ /** @param {string} file */
+ const baseDestOf = file =>
+ layoutDestOf(file) ?? /** @type {string} */ (rootDests.get(file));
+
+ const componentFiles = allFiles.filter(isComponentFile);
+ const helpers = allFiles.filter(f => !isComponentFile(f));
+ // A private attribute owner module and the unexported style modules it
+ // imports travel whole and are replaced only with --overwrite.
+ const ownerGroup = new Set();
+ const ownerQueue = helpers.filter(f =>
+ OWNER_MODULE.test(toModulePath(srcRoot, f)),
+ );
+ while (ownerQueue.length > 0) {
+ const file = /** @type {string} */ (ownerQueue.shift());
+ if (ownerGroup.has(file)) continue;
+ ownerGroup.add(file);
+ for (const dep of plan.dependsOn.get(file) ?? []) {
+ if (!isComponentFile(dep) && STYLEX_MODULE.test(toModulePath(srcRoot, dep))) {
+ ownerQueue.push(dep);
+ }
+ }
}
- // The owner modules the component imports, and their unexported StyleX
- // dependencies, travel with it in the package's layout (spec:AST-110 FR4).
- const srcRoot = path.dirname(componentDir);
- const componentRel = path
- .relative(srcRoot, componentDir)
- .split(path.sep)
- .join('/');
- const carried = sharedModulesOf(srcRoot, componentDir, sourceFiles);
- const shared = [...carried.values()].map(file => {
- const content = rewriteImports(
- fs.readFileSync(path.join(srcRoot, file), 'utf-8'),
- owner.ownerPackage,
- keepCarried(carried, path.posix.dirname(file)),
+
+ /** @type {Map<string, string>} helper -> the file it is written to instead */
+ const redirected = new Map();
+ /** @param {string} file */
+ const destOf = file => redirected.get(file) ?? baseDestOf(file);
+ /** @param {string} file */
+ const render = file =>
+ renderFile(/** @type {any} */ (plan.files.get(file)), choice =>
+ typeof choice === 'string'
+ ? choice
+ : relativeSpecifierBetween(destOf(choice.from), destOf(choice.to)),
);
- const dest = confineWrite(path.join(outputBase, file), cwd, {
+ /** @param {string} dest */
+ const readExisting = dest => {
+ if (!fs.existsSync(dest)) return null;
+ try {
+ return fs.readFileSync(dest, 'utf-8');
+ } catch {
+ return '';
+ }
+ };
+ // A helper an earlier swizzle wrote is reused when it is the same. A
+ // different file is never overwritten: this copy moves its own helper to
+ // the next free version-suffixed name. A move changes the import in every
+ // helper that imports it, so the check repeats until nothing moves.
+ /** @type {Map<string, number>} helper -> how many names it tried */
+ const attempts = new Map();
+ for (let moved = true; moved; ) {
+ moved = false;
+ for (const file of helpers) {
+ if (ownerGroup.has(file)) continue;
+ const existing = readExisting(destOf(file));
+ if (existing == null || existing === render(file)) continue;
+ const attempt = (attempts.get(file) ?? 0) + 1;
+ attempts.set(file, attempt);
+ redirected.set(
+ file,
+ versionedPath(baseDestOf(file), ownerVersion, attempt),
+ );
+ moved = true;
+ }
+ }
+
+ // The component's own files come first, then the helpers it carries.
+ const outputs = [...componentFiles, ...helpers].map(file => {
+ const dest = confineWrite(destOf(file), cwd, {
allowAbsolute: true,
label: 'output file',
});
- // Something that is not a readable file in its place counts as changed.
- let existing = null;
- if (fs.existsSync(dest)) {
- try {
- existing = fs.readFileSync(dest, 'utf-8');
- } catch {
- existing = '';
- }
- }
- // A copy another component's swizzle already wrote is reused when it is
- // the same; a changed one is a file this run would overwrite.
+ const content = render(file);
+ const existing = readExisting(dest);
return {
file,
dest,
content,
- unchanged: existing === content,
+ component: isComponentFile(file),
+ owner: ownerGroup.has(file),
exists: existing != null,
+ unchanged: existing === content,
};
});
- const existingFiles = sourceFiles.filter(f =>
- fs.existsSync(path.join(outputDir, f)),
- );
- const changedShared = shared.filter(s => s.exists && !s.unchanged);
+ const existingFiles = outputs.filter(o => o.component && o.exists);
+ const changedShared = outputs.filter(o => o.owner && o.exists && !o.unchanged);
if ((existingFiles.length > 0 || changedShared.length > 0) && !overwrite) {
const relOutputForMsg = path.relative(cwd, outputDir) || '.';
const sharedNote =
@@ -531,109 +473,47 @@ export async function swizzleCopy(component, options = {}) {
);
}
-
const outputDirExisted = fs.existsSync(outputDir);
- try {
- fs.mkdirSync(outputDir, {recursive: true});
- } catch (err) {
- throw writeFailed(outputDir, cwd, err);
- }
-
- const files = fs.readdirSync(componentDir);
- let copied = 0;
- let usesStyleX = false;
- // A copy that fails part-way undoes what it already wrote, so the report is
- // true and a retry does not trip over half a component. Each entry keeps
- // the bytes the file had before this run (null when the copy created it).
+ /** @type {string[]} folders this run created, outermost first */
+ const createdDirs = [];
/** @type {Array<{dest: string, original: Buffer|null}>} */
const written = [];
- for (const file of files) {
- if (isExcludedFromCopy(file)) continue;
- const srcPath = path.join(componentDir, file);
- if (!fs.statSync(srcPath).isFile()) continue;
- let content = fs.readFileSync(srcPath, 'utf-8');
- if (file.endsWith('.ts') || file.endsWith('.tsx')) {
- content = rewriteImports(content, owner.ownerPackage, keepCarried(carried, componentRel));
- }
- if (
- (file.endsWith('.ts') || file.endsWith('.tsx')) &&
- content.includes('@stylexjs/stylex')
- ) {
- usesStyleX = true;
- }
- const dest = path.join(outputDir, file);
- try {
- // The snapshot read is guarded too: a destination that cannot be read
- // back (no permission, or a directory with this name) must still undo
- // the earlier writes and report ERR_WRITE_FAILED.
- const original = fs.existsSync(dest) ? fs.readFileSync(dest) : null;
- written.push({dest, original});
- fs.writeFileSync(dest, content);
- } catch (err) {
- const unrestored = undoCopy(written);
- if (!outputDirExisted) {
- try {
- fs.rmdirSync(outputDir);
- } catch {
- // Not empty (something could not be undone), or already gone.
- }
- }
- throw writeFailed(dest, cwd, err, unrestored);
- }
- copied++;
- }
-
- /** @type {string[]} folders this run created for carried modules, outermost first */
- const createdDirs = [];
- for (const module of shared) {
- // An identical copy is already in place: it is part of this copy, unwritten.
- if (module.unchanged) {
+ let copied = 0;
+ for (const output of outputs) {
+ // An identical file is already in place: it is part of this copy, unwritten.
+ if (output.unchanged) {
copied++;
continue;
}
try {
- const original = fs.existsSync(module.dest)
- ? fs.readFileSync(module.dest)
- : null;
- const firstCreated = fs.mkdirSync(path.dirname(module.dest), {recursive: true});
+ const original = fs.existsSync(output.dest) ? fs.readFileSync(output.dest) : null;
+ const firstCreated = fs.mkdirSync(path.dirname(output.dest), {recursive: true});
if (firstCreated != null) createdDirs.push(firstCreated);
- written.push({dest: module.dest, original});
- fs.writeFileSync(module.dest, module.content);
+ written.push({dest: output.dest, original});
+ fs.writeFileSync(output.dest, output.content);
copied++;
} catch (err) {
const unrestored = undoCopy(written);
- // Remove the folders this run created, as a failed component-file write
- // does, so a retry finds the output as it was.
for (const dir of [...createdDirs].reverse()) {
fs.rmSync(dir, {recursive: true, force: true});
}
if (!outputDirExisted) {
fs.rmSync(outputDir, {recursive: true, force: true});
}
- throw writeFailed(module.dest, cwd, err, unrestored);
+ throw writeFailed(output.dest, cwd, err, unrestored);
}
}
- if (shared.length > 0) usesStyleX = true;
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, {recursive: true});
const relOutput = path.relative(cwd, outputDir);
- const copiedFiles = files.filter(
- f =>
- !isExcludedFromCopy(f) &&
- fs.statSync(path.join(componentDir, f)).isFile(),
- );
/** @type {import('../swizzle.type.mjs').SwizzleCopyResponse['data']} */
const data = {
component: dirName,
package: owner.package,
outputDir: relOutput,
filesCopied: copied,
- // The owner modules and their unexported style dependencies the copy
- // carries beside the component (spec:AST-110 FR4) are its files too.
- files: [
- ...copiedFiles.map(f => f),
- ...shared.map(m => path.relative(outputDir, m.dest).split(path.sep).join('/')),
- ],
- usesStyleX,
+ files: outputs.map(o => toPosix(path.relative(outputDir, o.dest))),
+ usesStyleX: outputs.some(o => o.content.includes('@stylexjs/stylex')),
};
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 7f6b3a1245..bb9a9d85b2 100644
--- a/packages/cli/api/swizzle/copy/copy.test.mjs
+++ b/packages/cli/api/swizzle/copy/copy.test.mjs
@@ -6,11 +6,12 @@
* becomes a path segment) must both be confined to cwd.
*/
-import {describe, it, expect, afterEach, vi} from 'vitest';
+import {describe, it, expect, afterEach, beforeEach, vi} from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
+import ts from 'typescript';
import {swizzle} from '../swizzle.mjs';
/** Set by a test to make the gh lookup throw an error it does not expect. */
@@ -299,3 +300,317 @@ describe('swizzle.copy — browser test harnesses', () => {
expect(r.data.files).toContain('Item.tsx');
}, SLOW);
});
+
+describe('swizzle.copy — the module graph (spec:AST-110 FR1, FR2)', () => {
+ const GRAPH_OUT = 'tmp-swizzle-graph-test';
+ const out = () => path.join(REPO, GRAPH_OUT);
+ const CORE = path.join(REPO, 'packages/core');
+ /** Every file under a folder, as paths relative to it. */
+ const filesUnder = dir =>
+ fs
+ .readdirSync(dir, {recursive: true, withFileTypes: true})
+ .filter(e => e.isFile())
+ .map(e => path.relative(dir, path.join(e.parentPath, e.name)));
+ /** Every `from '...'` and `import('...')` specifier in a file. */
+ const importsOf = file =>
+ [
+ ...fs
+ .readFileSync(file, 'utf-8')
+ .matchAll(/(?:from\s+|import\(\s*)['"]([^'"]+)['"]/g),
+ ].map(m => ({specifier: m[1]}));
+ /**
+ * Diagnostics TypeScript reports for the copied files when it resolves
+ * `@astryxdesign/core` the way a product does: through the package's
+ * `exports`. Only unresolved modules and missing exports count here.
+ */
+ const unresolvedImportsIn = files => {
+ // The product installs Core; the copy resolves it from its own folder.
+ const link = path.join(out(), 'node_modules/@astryxdesign/core');
+ fs.mkdirSync(path.dirname(link), {recursive: true});
+ fs.symlinkSync(CORE, link, 'dir');
+ const program = ts.createProgram(files, {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ customConditions: ['source'],
+ jsx: ts.JsxEmit.ReactJSX,
+ strict: true,
+ skipLibCheck: true,
+ noEmit: true,
+ resolveJsonModule: true,
+ });
+ const RESOLUTION = new Set([2305, 2307, 2614, 2724, 1192]);
+ const productInstalls = [
+ 'react',
+ '@stylexjs/stylex',
+ ...Object.keys(
+ JSON.parse(fs.readFileSync(path.join(CORE, 'package.json'), 'utf-8'))
+ .dependencies ?? {},
+ ),
+ ];
+ return files.flatMap(file =>
+ program
+ .getSemanticDiagnostics(program.getSourceFile(file))
+ .filter(d => RESOLUTION.has(d.code))
+ // The product installs React, StyleX and Core's own dependencies.
+ .filter(d => !productInstalls.some(name => ts.flattenDiagnosticMessageText(d.messageText, ' ').includes(`'${name}'`) || ts.flattenDiagnosticMessageText(d.messageText, ' ').includes(`'${name}/`)))
+ .map(d => `${path.relative(out(), file)}: TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, ' ')}`),
+ );
+ };
+
+ afterEach(() => {
+ fs.rmSync(out(), {recursive: true, force: true});
+ });
+
+ it(
+ 'copies the internal helpers a component reaches, and imports public names from public paths',
+ async () => {
+ const r = await swizzle('Button', {cwd: REPO, output: './' + GRAPH_OUT});
+ await swizzle('Dialog', {cwd: REPO, output: './' + GRAPH_OUT});
+ // InputGroupInternalContext is not exported, so the copy carries it.
+ expect(r.data.files).toContain(
+ '../InputGroup/InputGroupInternalContext.ts',
+ );
+ expect(r.data.filesCopied).toBe(r.data.files.length);
+ expect(r.data.files).not.toContain('../i18n/InternationalizationContext.ts');
+ const files = filesUnder(out())
+ .filter(rel => /\.tsx?$/.test(rel) && !rel.startsWith('node_modules'))
+ .map(rel => path.join(out(), rel));
+ for (const file of files) {
+ for (const {specifier} of importsOf(file)) {
+ expect(specifier, path.relative(out(), file)).not.toMatch(/^@astryxdesign\/core\/internal/);
+ if (specifier.startsWith('.')) {
+ expect(
+ path.resolve(path.dirname(file), specifier).startsWith(out()),
+ `${specifier} in ${path.relative(out(), file)} stays in the output`,
+ ).toBe(true);
+ }
+ }
+ }
+ expect(unresolvedImportsIn(files)).toEqual([]);
+ },
+ SLOW,
+ );
+
+ it(
+ 'imports a StyleX module by its own exported path',
+ async () => {
+ await swizzle('Button', {cwd: REPO, output: './' + GRAPH_OUT});
+ const source = fs.readFileSync(path.join(out(), 'Button/Button.tsx'), 'utf-8');
+ expect(source).toContain("from '@astryxdesign/core/theme/tokens.stylex'");
+ expect(source).not.toMatch(/from '@astryxdesign\/core\/theme'/);
+ },
+ SLOW,
+ );
+
+ it(
+ 'copies the nested folders a component imports',
+ async () => {
+ const r = await swizzle('Table', {cwd: REPO, output: './' + GRAPH_OUT});
+ expect(r.data.files).toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(/^plugins\/sortable\//),
+ expect.stringMatching(/^plugins\/selection\//),
+ ]),
+ );
+ },
+ SLOW,
+ );
+
+ it(
+ 'holds only source the component runs',
+ async () => {
+ for (const name of ['Badge', 'Field']) {
+ await swizzle(name, {cwd: REPO, output: './' + GRAPH_OUT});
+ }
+ const files = filesUnder(out());
+ expect(files.length).toBeGreaterThan(0);
+ for (const file of files) {
+ expect(file).not.toMatch(
+ /\.(?:test|spec|stories|story|doc|bench)\.|test-violations|render-testing|__tests__|__fixtures__|\.md$/,
+ );
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'reuses an identical helper, and never overwrites a different one',
+ async () => {
+ await swizzle('Button', {cwd: REPO, output: './' + GRAPH_OUT});
+ const helper = path.join(out(), 'InputGroup/groupStyles.ts');
+ const original = fs.readFileSync(helper, 'utf-8');
+
+ // An identical helper is part of the next copy, unwritten.
+ const second = await swizzle('TextInput', {cwd: REPO, output: './' + GRAPH_OUT});
+ expect(second.data.files).toContain('../InputGroup/groupStyles.ts');
+
+ // A changed helper stays as the product left it, even with --overwrite.
+ fs.writeFileSync(helper, original + '\n// edited\n');
+ const third = await swizzle('Button', {
+ cwd: REPO,
+ output: './' + GRAPH_OUT,
+ overwrite: true,
+ });
+ expect(fs.readFileSync(helper, 'utf-8')).toBe(original + '\n// edited\n');
+ const version = JSON.parse(
+ fs.readFileSync(path.join(CORE, 'package.json'), 'utf-8'),
+ ).version;
+ const suffixed = `../InputGroup/groupStyles.v${version}.ts`;
+ expect(third.data.files).toContain(suffixed);
+ expect(fs.readFileSync(path.join(out(), 'Button', suffixed), 'utf-8')).toBe(original);
+ // Only the new copy points at the suffixed helper.
+ expect(
+ fs.readFileSync(path.join(out(), 'Button/Button.tsx'), 'utf-8'),
+ ).toContain(`from '../InputGroup/groupStyles.v${version}'`);
+ expect(
+ fs.readFileSync(path.join(out(), 'TextInput/TextInput.tsx'), 'utf-8'),
+ ).not.toContain(`groupStyles.v${version}`);
+ },
+ SLOW,
+ );
+});
+
+describe('swizzle.copy — helpers an earlier swizzle wrote (spec:AST-110 FR2)', () => {
+ /** @type {string} */
+ let project;
+ const VERSION = '1.0.0';
+ /** A fake Core whose components share a helper that imports another. */
+ const buildCore = () => {
+ const src = path.join(project, 'node_modules/@astryxdesign/core/src');
+ const write = (rel, text) => {
+ fs.mkdirSync(path.dirname(path.join(src, rel)), {recursive: true});
+ fs.writeFileSync(path.join(src, rel), text);
+ };
+ write('utils/h.ts', 'export const h = 1;\n');
+ fs.writeFileSync(
+ path.join(src, '../package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version: VERSION}),
+ );
+ write('utils/a.ts', "import {h} from './h';\nexport const a = h;\n");
+ for (const name of ['Button', 'Card', 'Dialog']) {
+ write(
+ `${name}/${name}.tsx`,
+ `import {a} from '../utils/a';\nexport const ${name} = () => a;\n`,
+ );
+ write(`${name}/index.ts`, `export {${name}} from './${name}';\n`);
+ }
+ };
+ const out = rel => path.join(project, 'components/astryx', rel);
+ const read = rel => fs.readFileSync(out(rel), 'utf-8');
+
+ beforeEach(() => {
+ project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-swizzle-helpers-'));
+ fs.writeFileSync(
+ path.join(project, 'package.json'),
+ JSON.stringify({name: 'consumer', version: '1.0.0'}),
+ );
+ buildCore();
+ });
+ afterEach(() => {
+ fs.rmSync(project, {recursive: true, force: true});
+ });
+
+ it(
+ 'never rewrites a version-suffixed helper an earlier copy imports',
+ async () => {
+ await swizzle('Button', {cwd: project});
+ fs.appendFileSync(out('utils/a.ts'), '// edited by the product\n');
+ fs.appendFileSync(out('utils/h.ts'), '// edited by the product\n');
+
+ // The edited helpers stay; Card gets its own.
+ await swizzle('Card', {cwd: project});
+ expect(read('Card/Card.tsx')).toContain(`from '../utils/a.v${VERSION}'`);
+ const cardHelper = read(`utils/a.v${VERSION}.ts`);
+ expect(cardHelper).toContain(`from './h.v${VERSION}'`);
+ fs.appendFileSync(out(`utils/h.v${VERSION}.ts`), '// edited again\n');
+
+ const dialog = await swizzle('Dialog', {cwd: project});
+ // Card's copy is untouched: its helper still imports its own h.
+ expect(read(`utils/a.v${VERSION}.ts`)).toBe(cardHelper);
+ expect(read(`utils/h.v${VERSION}.ts`)).toContain('// edited again');
+ expect(read('utils/h.ts')).toContain('// edited by the product');
+ // Dialog points at helpers of its own.
+ expect(dialog.data.files).toEqual(
+ expect.arrayContaining([
+ `../utils/a.v${VERSION}-2.ts`,
+ `../utils/h.v${VERSION}-2.ts`,
+ ]),
+ );
+ expect(read(`utils/a.v${VERSION}-2.ts`)).toContain(
+ `from './h.v${VERSION}-2'`,
+ );
+ expect(read('Dialog/Dialog.tsx')).toContain(
+ `from '../utils/a.v${VERSION}-2'`,
+ );
+ },
+ SLOW,
+ );
+});
+
+describe('swizzle.copy — a name the package exports only as a type (spec:AST-110 FR1)', () => {
+ /** @type {string} */
+ let project;
+ beforeEach(() => {
+ project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-swizzle-kinds-'));
+ fs.writeFileSync(
+ path.join(project, 'package.json'),
+ JSON.stringify({name: 'consumer', version: '1.0.0'}),
+ );
+ const core = path.join(project, 'node_modules/@astryxdesign/core');
+ const write = (rel, text) => {
+ fs.mkdirSync(path.dirname(path.join(core, rel)), {recursive: true});
+ fs.writeFileSync(path.join(core, rel), text);
+ };
+ write(
+ 'package.json',
+ JSON.stringify({
+ name: '@astryxdesign/core',
+ version: '1.0.0',
+ exports: {'.': {source: './src/index.ts', default: './dist/index.js'}},
+ }),
+ );
+ write('src/utils/shape.ts', "export const shape = 'round';\n");
+ write('src/utils/size.ts', 'export const size = 1;\n');
+ // The package root re-exports `shape` as a type only, `size` as a value.
+ write(
+ 'src/index.ts',
+ [
+ "export type {shape} from './utils/shape';",
+ "export {size} from './utils/size';",
+ "export {Button} from './Button/Button';",
+ '',
+ ].join('\n'),
+ );
+ write(
+ 'src/Button/Button.tsx',
+ [
+ "import {shape} from '../utils/shape';",
+ "import {size} from '../utils/size';",
+ 'export const Button = () => `${shape} ${size}`;',
+ '',
+ ].join('\n'),
+ );
+ write('src/Button/index.ts', "export {Button} from './Button';\n");
+ });
+ afterEach(() => {
+ fs.rmSync(project, {recursive: true, force: true});
+ });
+
+ it(
+ 'carries a value the package exports only as a type, and imports a value export from the package',
+ async () => {
+ const r = await swizzle('Button', {cwd: project});
+ const source = fs.readFileSync(
+ path.join(project, 'components/astryx/Button/Button.tsx'),
+ 'utf-8',
+ );
+ // A type-only export is erased at runtime, so the copy carries `shape`.
+ expect(source).toContain("from '../utils/shape'");
+ expect(r.data.files).toContain('../utils/shape.ts');
+ expect(source).toContain("import {size} from '@astryxdesign/core';");
+ expect(r.data.files).not.toContain('../utils/size.ts');
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/api/swizzle/swizzle.doc.mjs b/packages/cli/api/swizzle/swizzle.doc.mjs
index eed6911177..e72a4e31dc 100644
--- a/packages/cli/api/swizzle/swizzle.doc.mjs
+++ b/packages/cli/api/swizzle/swizzle.doc.mjs
@@ -17,8 +17,11 @@ export const doc = {
description:
"Ejects a component's source into the consumer project for deep customization. " +
'It copies from the locally resolved @astryxdesign/core (or the owning integration) ' +
- 'package source, rewriting imports that escape the component directory to the owner ' +
- "package's subpaths and flagging whether any copied file uses StyleX. With no name " +
+ 'package source. Every import in the copy names a file the copy holds or a path ' +
+ '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 ' +
'(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 " +
@@ -63,7 +66,8 @@ export const doc = {
{
name: 'options.overwrite',
type: 'boolean',
- description: 'Overwrite existing files instead of erroring.',
+ description:
+ "Replace the component's existing files instead of erroring. A helper an earlier swizzle wrote is never replaced by a copy that carries it: a different one stays, and the new copy writes its own under a version-suffixed name. Swizzling the component whose folder holds that helper counts it as one of that component's own files. A changed private attribute owner module, or a style module it imports, throws ERR_FILE_EXISTS without overwrite and is replaced with it.",
default: 'false',
},
],
@@ -76,7 +80,7 @@ export const doc = {
{
type: 'swizzle.copy',
description:
- 'A receipt after copying the component into the project: the component name, owning package, output directory, files-copied count, the copied file names (relative to the component folder, including the private attribute owner modules and their unexported style modules copied beside it, e.g. `../privateAttributes/press.stylex.ts`), whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling.',
+ 'A receipt after copying the component into the project: the component name, owning package, output directory, files-copied count, the copied file names (relative to the component folder; the internal modules copied beside it start with `../`, e.g. `../InputGroup/groupStyles.ts`), whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling.',
},
],
throws: [
diff --git a/packages/cli/api/swizzle/swizzle.mjs b/packages/cli/api/swizzle/swizzle.mjs
index 2f9695ffcf..a3275a02d7 100644
--- a/packages/cli/api/swizzle/swizzle.mjs
+++ b/packages/cli/api/swizzle/swizzle.mjs
@@ -9,16 +9,12 @@
* - a component name -> api/swizzle/copy -> `swizzle.copy` receipt
*
* Errors throw AstryxError (stable code + suggestions). All human prose /
- * package-manager prefixing lives in the CLI renderer. Re-exports the copy
- * leaf's `rewriteImports` so existing importers keep this module as their entry
- * point (api/index.mjs, the CLI command, and the unit tests all import from
- * here).
+ * package-manager prefixing lives in the CLI renderer. api/index.mjs, the CLI
+ * command, and the unit tests import `swizzle` from here.
*/
import {swizzleList} from './list/list.mjs';
-import {swizzleCopy, rewriteImports} from './copy/copy.mjs';
-
-export {rewriteImports};
+import {swizzleCopy} from './copy/copy.mjs';
/**
* List swizzlable components, or copy one component's source for customization.
diff --git a/packages/cli/api/swizzle/swizzle.test.mjs b/packages/cli/api/swizzle/swizzle.test.mjs
index b12b42ca55..c7c20a8eec 100644
--- a/packages/cli/api/swizzle/swizzle.test.mjs
+++ b/packages/cli/api/swizzle/swizzle.test.mjs
@@ -4,103 +4,11 @@ import {afterEach, describe, it, expect} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
-import {rewriteImports, swizzle} from './swizzle.mjs';
+import {swizzle} from './swizzle.mjs';
// api/swizzle/ -> up 3 = packages/cli, up 4 = repo root (has packages/core).
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
-describe('rewriteImports', () => {
- it('preserves the theme token subpath (StyleX module is a dedicated export)', () => {
- const input = `import { tokens } from '../theme/tokens.stylex';`;
- const result = rewriteImports(input);
- expect(result).toBe(
- `import { tokens } from '@astryxdesign/core/theme/tokens.stylex';`,
- );
- });
-
- it('rewrites ../utils/mergeProps to @astryxdesign/core/utils', () => {
- const input = `import { mergeProps } from '../utils/mergeProps';`;
- const result = rewriteImports(input);
- expect(result).toBe(`import { mergeProps } from '@astryxdesign/core/utils';`);
- });
-
- it('leaves same-level relative imports untouched', () => {
- const input = `import { helper } from './helper';`;
- const result = rewriteImports(input);
- expect(result).toBe(`import { helper } from './helper';`);
- });
-
- it('rewrites export from statements', () => {
- const input = `export { foo } from '../hooks/useLayout';`;
- const result = rewriteImports(input);
- expect(result).toBe(`export { foo } from '@astryxdesign/core/hooks';`);
- });
-
- it('handles double quotes', () => {
- const input = `import { tokens } from "../theme/tokens.stylex";`;
- const result = rewriteImports(input);
- expect(result).toBe(
- `import { tokens } from "@astryxdesign/core/theme/tokens.stylex";`,
- );
- });
-
- it('handles multiple imports in one file', () => {
- const input = [
- `import { tokens } from '../theme/tokens.stylex';`,
- `import { mergeProps } from '../utils/mergeProps';`,
- `import { helper } from './helper';`,
- ].join('\n');
-
- const result = rewriteImports(input);
- expect(result).toBe(
- [
- `import { tokens } from '@astryxdesign/core/theme/tokens.stylex';`,
- `import { mergeProps } from '@astryxdesign/core/utils';`,
- `import { helper } from './helper';`,
- ].join('\n'),
- );
- });
-
- it('rewrites a dynamic import() of a sibling component', () => {
- const input = `const T = lazy(() => import('../Tooltip/Tooltip'));`;
- expect(rewriteImports(input)).toBe(
- `const T = lazy(() => import('@astryxdesign/core/Tooltip'));`,
- );
- });
-
- it('rewrites a two-levels-up asset import to a valid subpath (never /..)', () => {
- const input = `import en from '../../locales/en.json' with {type: 'json'};`;
- const out = rewriteImports(input);
- expect(out).not.toContain('@astryxdesign/core/..');
- expect(out).toBe(
- `import en from '@astryxdesign/core/locales/en.json' with {type: 'json'};`,
- );
- });
-
- it('rewrites ANY non-theme .stylex import to a deep path (not the barrel)', () => {
- // Every .stylex module needs the deep path so the StyleX compiler can
- // resolve styles at compile time. The barrel re-export loses identity.
- const input = `import { interactionOverlayStyles } from '../utils/interactionOverlay.stylex';`;
- expect(rewriteImports(input)).toBe(
- `import { interactionOverlayStyles } from '@astryxdesign/core/utils/interactionOverlay.stylex';`,
- );
- });
-
- it('rewrites a Layout .stylex import to a deep path', () => {
- const input = `import { container } from '../Layout/container.stylex';`;
- expect(rewriteImports(input)).toBe(
- `import { container } from '@astryxdesign/core/Layout/container.stylex';`,
- );
- });
-
- it('rewrites a two-levels-up .stylex import to a deep path', () => {
- const input = `import { focusOutlineProps } from '../../utils/focusOutline.stylex';`;
- expect(rewriteImports(input)).toBe(
- `import { focusOutlineProps } from '@astryxdesign/core/utils/focusOutline.stylex';`,
- );
- });
-});
-
describe('swizzle() API', () => {
it('no component → swizzle.list of core components', async () => {
const r = await swizzle(undefined, {cwd: REPO});
@@ -121,7 +29,7 @@ describe('swizzle() API', () => {
});
});
-describe('swizzle rewriteImports compiles for components with .stylex imports', () => {
+describe('swizzle imports resolve for components with .stylex imports', () => {
const OUT = 'tmp-swizzle-resolve-test';
afterEach(() => {
fs.rmSync(path.join(REPO, OUT), {recursive: true, force: true});
diff --git a/packages/cli/api/swizzle/swizzle.type.mjs b/packages/cli/api/swizzle/swizzle.type.mjs
index 038b20ded4..9066d95137 100644
--- a/packages/cli/api/swizzle/swizzle.type.mjs
+++ b/packages/cli/api/swizzle/swizzle.type.mjs
@@ -34,7 +34,7 @@
* @property {string} data.package Owner package the component source was copied from.
* @property {string} data.outputDir
* @property {number} data.filesCopied
- * @property {string[]} data.files Copied file names, relative to the component folder; owner modules and their unexported style modules copied beside it start with `../` (spec:AST-110 FR4).
+ * @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 {SwizzleFeedback} [data.feedback]
*/
@@ -46,7 +46,7 @@
* @property {string} [output] Output directory (must resolve inside cwd). Defaults to ./components/astryx.
* @property {string} [package] Scope to a specific owning package when a name is ambiguous.
* @property {boolean} [list] Force the list response even with a component argument.
- * @property {boolean} [overwrite] Overwrite existing files instead of erroring.
+ * @property {boolean} [overwrite] Replace the component's existing files instead of erroring. A copy that carries a helper an earlier swizzle wrote never replaces it, except a changed private attribute owner module and the style modules it imports; swizzling the component whose folder holds the helper counts it as that component's own file.
*/
export {};
diff --git a/packages/cli/clients/cli/commands/swizzle.doc.mjs b/packages/cli/clients/cli/commands/swizzle.doc.mjs
index 5fbd1f4633..7407cc16a7 100644
--- a/packages/cli/clients/cli/commands/swizzle.doc.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.doc.mjs
@@ -16,8 +16,11 @@ export const doc = {
summary: 'Copy component source for customization',
description:
"Ejects a component's source from the resolved @astryxdesign/core (or its owning " +
- 'integration) into your project for deep customization, rewriting imports that ' +
- 'escape the component directory. With no name it lists the swizzlable components. ' +
+ 'integration) into your project for deep customization. Every import in the copy ' +
+ '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. ' +
'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.',
@@ -46,7 +49,7 @@ export const doc = {
flag: '-f, --overwrite',
param: 'options.overwrite',
description:
- 'Replace existing files. Without it, existing files fail the command with ERR_FILE_EXISTS and nothing is written',
+ "Replace the component's existing files. Without it, existing files fail the command with ERR_FILE_EXISTS and nothing is written. A helper an earlier swizzle wrote is reused when it is the same and is never replaced by a copy that carries it: a different one stays, and this copy writes its own under a version-suffixed name. Swizzling the component whose folder holds that helper counts it as one of that component's own files. A changed private attribute owner module, or a style module it imports, fails the command without --overwrite and is replaced with it",
},
],
examples: [
diff --git a/packages/cli/clients/cli/commands/swizzle.mjs b/packages/cli/clients/cli/commands/swizzle.mjs
index 69f036bf55..73c7eb4e0c 100644
--- a/packages/cli/clients/cli/commands/swizzle.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.mjs
@@ -3,11 +3,10 @@
/**
* @file swizzle command — thin wrapper around api/swizzle.
*
- * Copies a component's source into the consumer project for customization
- * (imports rewritten to the owner package's subpaths). All logic — owner
- * resolution, copy, import rewriting, StyleX detection, maintainer feedback —
- * lives in api/swizzle; this file only parses flags, prints, and prefixes
- * commands for the caller's package manager.
+ * Copies a component's source into the consumer project for customization,
+ * with the internal modules it needs. All logic — owner resolution, the copy,
+ * StyleX detection, maintainer feedback — lives in api/swizzle; this file only
+ * parses flags, prints, and prefixes commands for the caller's package manager.
*/
import {jsonOut} from '../../../foundation/response/json.mjs';
@@ -85,18 +84,18 @@ export function registerSwizzle(program) {
text(`[ok] Copied ${filesCopied} files to ${outputDir}/`),
text(
[
- `Relative imports have been rewritten to use ${ownerPackage}.`,
+ `What ${ownerPackage} exports is imported from ${ownerPackage}; the internal modules the component needs are copied beside it.`,
'You can now customize the component source freely.',
].join('\n'),
),
];
- // Files the copy wrote outside the component folder: the owner modules
- // and their unexported style modules (spec:AST-110 FR4).
+ // Files the copy wrote outside the component folder: the internal
+ // modules it needs, in the package's folder layout.
const shared = (result.data.files ?? []).filter(f => f.startsWith('../'));
if (shared.length > 0) {
out.push(
text(
- `Shared modules: ${shared.join(', ')} (copied whole; their imports between each other stay relative)`,
+ `Copied beside it: ${shared.join(', ')} (in the package's folder layout; imported by relative path)`,
),
);
}
diff --git a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
index 4e81a39db5..3736cf900e 100644
--- a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
@@ -3,9 +3,9 @@
/**
* @file Integration-routing tests for `astryx swizzle`.
*
- * `rewriteImports` is unit-tested in swizzle.test.mjs. These tests exercise the
- * end-to-end command behavior by running the CLI in-process against hermetic
- * fixtures: a fake @astryxdesign/core under node_modules plus, for the
+ * The copy's module graph is tested in api/swizzle/copy/copy.test.mjs. These
+ * tests exercise the end-to-end command behavior by running the CLI in-process
+ * against hermetic fixtures: a fake @astryxdesign/core under node_modules plus, for the
* integration cases, a configured integration package (astryx.config.mjs +
* astryx.integration.mjs + a `components` dir) — all under node_modules so the
* config/manifest loaders resolve normally.
@@ -18,7 +18,6 @@ import * as os from 'node:os';
import {createRequire} from 'node:module';
import {fileURLToPath} from 'node:url';
import {runCli} from '../../../test-utils/run-cli.mjs';
-
/** The StyleX runtime that Core ships with, resolved the way Core resolves it. */
const CORE_PACKAGE = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -27,7 +26,8 @@ const CORE_PACKAGE = path.resolve(
/**
* Build a fake @astryxdesign/core under <project>/node_modules with a single
- * swizzleable Button component (bare `Button.tsx`, no doc).
+ * swizzleable Button component (bare `Button.tsx`, no doc) that imports an
+ * exported StyleX module.
*/
function buildFakeCore(project) {
const core = path.join(project, 'node_modules', '@astryxdesign', 'core');
@@ -35,7 +35,21 @@ function buildFakeCore(project) {
fs.mkdirSync(buttonDir, {recursive: true});
fs.writeFileSync(
path.join(core, 'package.json'),
- '{"name":"@astryxdesign/core","version":"0.0.13"}',
+ JSON.stringify({
+ name: '@astryxdesign/core',
+ version: '0.0.13',
+ exports: {
+ './theme/tokens.stylex': {
+ source: './src/theme/tokens.stylex.ts',
+ default: './dist/theme/tokens.stylex.js',
+ },
+ },
+ }),
+ );
+ fs.mkdirSync(path.join(core, 'src', 'theme'), {recursive: true});
+ fs.writeFileSync(
+ path.join(core, 'src', 'theme', 'tokens.stylex.ts'),
+ `export const tokens = {};\n`,
);
fs.writeFileSync(
path.join(buttonDir, 'Button.tsx'),
@@ -55,8 +69,8 @@ function buildFakeCore(project) {
/**
* Build a configured integration package `@test/meta` under
- * <project>/node_modules with a same-stem component (source + doc) and an
- * escaping import, plus a colocated test file. Writes astryx.config.mjs at the
+ * <project>/node_modules with a same-stem component (source + doc) that
+ * imports an unexported helper beside its folder, plus a colocated test file. Writes astryx.config.mjs at the
* project root listing the integration.
*
* @param {string} project
@@ -86,9 +100,12 @@ function buildIntegration(project, {issuesUrl, componentName = 'MetaAppShell'} =
'',
].join('\n'),
);
+ fs.writeFileSync(path.join(compDir, 'sibling.ts'), `export const sib = 1;\n`);
+ // An unexported helper beside the component folder.
+ fs.mkdirSync(path.join(compRoot, 'utils'), {recursive: true});
fs.writeFileSync(
- path.join(compDir, 'sibling.ts'),
- `export const sib = 1;\n`,
+ path.join(compRoot, 'utils', 'foo.ts'),
+ `export default 1;\n`,
);
fs.writeFileSync(
path.join(compDir, `${componentName}.doc.mjs`),
@@ -161,11 +178,10 @@ describe('swizzle — core feedback routing via config', () => {
});
describe('swizzle — integration-owned components', () => {
- it('copies the component dir (excluding test/doc), rewrites escaping imports to the owner package, routes feedback to the integration issuesUrl', async () => {
+ 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);
writeProjectPackageJson(project);
buildIntegration(project, {issuesUrl: 'https://example.com/meta/issues'});
-
const result = await runCli(['--json', 'swizzle', 'MetaAppShell', '-f'], project);
expect(result.code).toBe(0);
const env = JSON.parse(result.stdout);
@@ -182,15 +198,187 @@ describe('swizzle — integration-owned components', () => {
const outDir = path.join(project, 'components', 'astryx', 'MetaAppShell');
expect(fs.existsSync(path.join(outDir, 'MetaAppShell.doc.mjs'))).toBe(false);
const out = fs.readFileSync(path.join(outDir, 'MetaAppShell.tsx'), 'utf-8');
- expect(out).toContain(`from '@test/meta/utils'`);
+ // The helper is not exported, so the copy carries it in the same layout.
+ expect(out).toContain(`from '../utils/foo'`);
+ expect(env.data.files).toContain('../utils/foo.ts');
+ expect(
+ fs.existsSync(
+ path.join(project, 'components', 'astryx', 'utils', 'foo.ts'),
+ ),
+ ).toBe(true);
expect(out).toContain(`from './sibling'`);
});
+ it('carries a module beside the components folder, under the output folder by its package path', async () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ const {intDir, compDir} = buildIntegration(project, {
+ issuesUrl: 'https://example.com/meta/issues',
+ });
+ // A helper at the package root, beside `components/`.
+ fs.mkdirSync(path.join(intDir, 'lib'), {recursive: true});
+ fs.writeFileSync(path.join(intDir, 'lib', 'helper.ts'), `export const helper = 2;\n`);
+ fs.writeFileSync(
+ path.join(compDir, 'MetaAppShell.tsx'),
+ `import {helper} from '../../lib/helper';\nexport function MetaAppShell() { return helper; }\n`,
+ );
+ const result = await runCli(['--json', 'swizzle', 'MetaAppShell', '-f'], project);
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ const output = path.join(project, 'components', 'astryx');
+ const out = fs.readFileSync(
+ path.join(output, 'MetaAppShell', 'MetaAppShell.tsx'),
+ 'utf-8',
+ );
+ expect(out).toContain(`from '../lib/helper'`);
+ expect(env.data.files).toContain('../lib/helper.ts');
+ expect(
+ fs.readFileSync(path.join(output, 'lib', 'helper.ts'), 'utf-8'),
+ ).toBe(`export const helper = 2;\n`);
+ });
+
+ it('keeps a root module apart from a same-named one inside the components folder', async () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ const {intDir, compDir} = buildIntegration(project, {
+ issuesUrl: 'https://example.com/meta/issues',
+ });
+ fs.mkdirSync(path.join(intDir, 'utils'), {recursive: true});
+ fs.writeFileSync(path.join(intDir, 'utils', 'foo.ts'), `export const root = 3;\n`);
+ fs.writeFileSync(
+ path.join(compDir, 'MetaAppShell.tsx'),
+ `import x from '../utils/foo';\nimport {root} from '../../utils/foo';\nexport function MetaAppShell() { return x + root; }\n`,
+ );
+ const result = await runCli(['--json', 'swizzle', 'MetaAppShell', '-f'], project);
+ expect(result.code).toBe(0);
+ const output = path.join(project, 'components', 'astryx');
+ const out = fs.readFileSync(
+ path.join(output, 'MetaAppShell', 'MetaAppShell.tsx'),
+ 'utf-8',
+ );
+ // The module inside `components/` keeps its layout; the root one moves
+ // to a folder named after the package.
+ expect(out).toContain(`import x from '../utils/foo';`);
+ expect(out).toContain(`import {root} from '../meta/utils/foo';`);
+ expect(fs.readFileSync(path.join(output, 'utils', 'foo.ts'), 'utf-8')).toBe(
+ `export default 1;\n`,
+ );
+ expect(
+ fs.readFileSync(path.join(output, 'meta', 'utils', 'foo.ts'), 'utf-8'),
+ ).toBe(`export const root = 3;\n`);
+ });
+
+ it('imports a stylesheet the package exports from the package', async () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ const {intDir, compDir} = buildIntegration(project, {
+ issuesUrl: 'https://example.com/meta/issues',
+ });
+ fs.writeFileSync(
+ path.join(intDir, 'package.json'),
+ JSON.stringify({
+ name: '@test/meta',
+ version: '1.2.3',
+ exports: {'./styles.css': './styles.css'},
+ }),
+ );
+ fs.writeFileSync(path.join(intDir, 'styles.css'), `.meta {}\n`);
+ fs.writeFileSync(
+ path.join(compDir, 'MetaAppShell.tsx'),
+ `import '../../styles.css';\nexport function MetaAppShell() { return null; }\n`,
+ );
+ const result = await runCli(['--json', 'swizzle', 'MetaAppShell', '-f'], project);
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ const out = fs.readFileSync(
+ path.join(
+ project,
+ 'components',
+ 'astryx',
+ 'MetaAppShell',
+ 'MetaAppShell.tsx',
+ ),
+ 'utf-8',
+ );
+ expect(out).toContain(`import '@test/meta/styles.css';`);
+ expect(env.data.files.some(f => f.endsWith('styles.css'))).toBe(false);
+ });
+
+ it("refuses to replace an edited owner module in an integration's components folder without --overwrite", async () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ const {compDir} = buildIntegration(project, {
+ issuesUrl: 'https://example.com/meta/issues',
+ });
+ const ownerDir = path.join(path.dirname(compDir), 'privateAttributes');
+ fs.mkdirSync(ownerDir, {recursive: true});
+ fs.writeFileSync(path.join(ownerDir, 'row.stylex.ts'), `export const row = 1;\n`);
+ fs.writeFileSync(
+ path.join(compDir, 'MetaAppShell.tsx'),
+ `import {row} from '../privateAttributes/row.stylex';\nexport function MetaAppShell() { return row; }\n`,
+ );
+ const first = await runCli(['--json', 'swizzle', 'MetaAppShell'], project);
+ expect(first.code).toBe(0);
+ const owner = path.join(
+ project,
+ 'components',
+ 'astryx',
+ 'privateAttributes',
+ 'row.stylex.ts',
+ );
+ fs.appendFileSync(owner, '// edited\n');
+ fs.rmSync(path.join(project, 'components', 'astryx', 'MetaAppShell'), {
+ recursive: true,
+ force: true,
+ });
+
+ const again = await runCli(['--json', 'swizzle', 'MetaAppShell'], project);
+ expect(again.code).not.toBe(0);
+ expect(JSON.parse(again.stdout).code).toBe('ERR_FILE_EXISTS');
+ expect(fs.readFileSync(owner, 'utf-8')).toContain('// edited');
+ });
+ /** Swizzle `Foo`, which imports its sibling `Bar`, from `@test/meta` with these exports. */
+ async function swizzleFooBesideBar(exportsField) {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ const {intDir} = buildIntegration(project, {componentName: 'Foo'});
+ fs.writeFileSync(path.join(intDir, 'package.json'), JSON.stringify({name: '@test/meta', version: '1.2.3', exports: exportsField}));
+ fs.writeFileSync(path.join(intDir, 'components', 'index.ts'), `export {Bar} from './Bar/Bar';\n`);
+ const bar = path.join(intDir, 'components', 'Bar');
+ fs.mkdirSync(bar, {recursive: true});
+ fs.writeFileSync(path.join(bar, 'Bar.tsx'), `export function Bar() { return null; }\n`);
+ fs.writeFileSync(path.join(bar, 'index.ts'), `export {Bar} from './Bar';\n`);
+ fs.writeFileSync(path.join(intDir, 'components', 'Foo', 'Foo.tsx'), `import {Bar} from '../Bar';\nexport function Foo() { return Bar(); }\n`);
+ const result = await runCli(['--json', 'swizzle', 'Foo', '-f'], project);
+ expect(result.code).toBe(0);
+ return fs.readFileSync(path.join(project, 'components', 'astryx', 'Foo', 'Foo.tsx'), 'utf-8');
+ }
+
+ it.each([
+ ['a `./*` pattern with a source condition', {'./*': {source: './components/*/index.ts', default: './dist/*/index.js'}}],
+ ['a `./*` pattern with a plain string', {'./*': './components/*/index.ts'}],
+ ['a plain-string subpath', {'./Bar': './components/Bar/index.ts'}],
+ ['a `./*` pattern whose target repeats `*`', {'./*': './components/*/*.tsx'}],
+ ['a `./*` pattern with a fallback array', {'./*': ['./components/*/index.ts']}],
+ ])('imports another public component from the package when exports use %s', async (_shape, exportsField) => {
+ expect(await swizzleFooBesideBar(exportsField)).toContain(`from '@test/meta/Bar'`);
+ });
+
+ it('imports from the package root when exports are a single condition object', async () => {
+ const out = await swizzleFooBesideBar({source: './components/index.ts', default: './dist/index.js'});
+ expect(out).toContain(`from '@test/meta';`);
+ });
+
+ it('copies a component whose subpath exports block beside a `./*` pattern', async () => {
+ const out = await swizzleFooBesideBar({'./*': {source: './components/*/index.ts'}, './Bar': null});
+ expect(out).not.toContain('@test/meta');
+ expect(out).toContain(`from '../Bar`);
+ });
+
it('omits the feedback note when the integration ships no issuesUrl', async () => {
buildFakeCore(project);
writeProjectPackageJson(project);
buildIntegration(project, {issuesUrl: null});
-
const result = await runCli(['--json', 'swizzle', 'MetaAppShell', '-f'], project);
expect(result.code).toBe(0);
const env = JSON.parse(result.stdout);
@@ -238,7 +426,14 @@ describe('swizzle — ambiguous ownership', () => {
path.join(project, 'components', 'astryx', 'Button', 'Button.tsx'),
'utf-8',
);
- expect(out).toContain(`from '@test/meta/utils'`);
+ // The helper is not exported, so the copy carries it in the same layout.
+ expect(out).toContain(`from '../utils/foo'`);
+ expect(env.data.files).toContain('../utils/foo.ts');
+ expect(
+ fs.existsSync(
+ path.join(project, 'components', 'astryx', 'utils', 'foo.ts'),
+ ),
+ ).toBe(true);
});
it('--package resolves an ambiguous name to core', async () => {
@@ -275,7 +470,21 @@ function buildStyleXCore(project) {
fs.mkdirSync(styledDir, {recursive: true});
fs.writeFileSync(
path.join(core, 'package.json'),
- '{"name":"@astryxdesign/core","version":"0.0.13"}',
+ JSON.stringify({
+ name: '@astryxdesign/core',
+ version: '0.0.13',
+ exports: {
+ './theme/tokens.stylex': {
+ source: './src/theme/tokens.stylex.ts',
+ default: './dist/theme/tokens.stylex.js',
+ },
+ },
+ }),
+ );
+ fs.mkdirSync(path.join(core, 'src', 'theme'), {recursive: true});
+ fs.writeFileSync(
+ path.join(core, 'src', 'theme', 'tokens.stylex.ts'),
+ `export const tokens = {};\n`,
);
fs.writeFileSync(
path.join(styledDir, 'Styled.tsx'),
@@ -325,11 +534,9 @@ describe('swizzle — StyleX build setup note (#3373)', () => {
/Unexpected 'stylex\.create' call at runtime/,
);
});
-
it('does not print the StyleX note for components without StyleX', async () => {
buildStyleXCore(project);
writeProjectPackageJson(project);
-
const jsonResult = await runCli(['--json', 'swizzle', 'Plain', '-f'], project);
expect(jsonResult.code).toBe(0);
const env = JSON.parse(jsonResult.stdout);
@@ -340,7 +547,6 @@ describe('swizzle — StyleX build setup note (#3373)', () => {
expect(humanResult.stdout).not.toMatch(/StyleX compiler/i);
});
});
-
describe('swizzle — shared modules outside the component folder (spec:AST-110 FR4)', () => {
it('names the owner modules it copied beside the component', async () => {
const core = path.join(project, 'node_modules', '@astryxdesign', 'core');
@@ -369,7 +575,12 @@ describe('swizzle — shared modules outside the component folder (spec:AST-110
const humanResult = await runCli(['swizzle', 'Row', '-f'], project);
expect(humanResult.code).toBe(0);
expect(humanResult.stdout).toContain(
- 'Shared modules: ../privateAttributes/row.stylex.ts, ../motion/fade.stylex.ts (copied whole; their imports between each other stay relative)',
+ "Copied beside it: ../privateAttributes/row.stylex.ts, ../motion/fade.stylex.ts (in the package's folder layout; imported by relative path)",
+ );
+ // The copy keeps relative imports of the modules it carries.
+ expect(humanResult.stdout).toContain(
+ 'the internal modules the component needs are copied beside it',
);
+ expect(humanResult.stdout).not.toContain('have been rewritten');
});
});
diff --git a/packages/cli/clients/cli/commands/write-failure.test.mjs b/packages/cli/clients/cli/commands/write-failure.test.mjs
index cb4f06cbcf..9f71634c3d 100644
--- a/packages/cli/clients/cli/commands/write-failure.test.mjs
+++ b/packages/cli/clients/cli/commands/write-failure.test.mjs
@@ -106,10 +106,11 @@ function fromProject(file) {
describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', () => {
it('restores replaced files, removes created ones, and says nothing was written', async () => {
- // Learn the component's files, in copy order, from a successful swizzle.
+ // Learn the component's own files, in copy order, from a successful
+ // swizzle. The helpers it carries (`../…`) are written after them.
const probe = await json(['swizzle', 'Button', '--output', 'probe']);
expect(probe.status, JSON.stringify(probe.body).slice(0, 200)).toBe(0);
- const files = probe.body.data.files;
+ const files = probe.body.data.files.filter(f => !f.startsWith('../'));
expect(files.length).toBeGreaterThan(1);
const outDir = path.join(dir, 'out', path.basename(probe.body.data.outputDir));
@@ -150,7 +151,7 @@ describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', ()
it('undoes the copy when a destination cannot be read back', async () => {
const probe = await json(['swizzle', 'Button', '--output', 'probe']);
expect(probe.status, JSON.stringify(probe.body).slice(0, 200)).toBe(0);
- const files = probe.body.data.files;
+ const files = probe.body.data.files.filter(f => !f.startsWith('../'));
const outDir = path.join(dir, 'out', path.basename(probe.body.data.outputDir));
// A directory where the last file goes: the rollback snapshot cannot read
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index 87ffabaf02..3ae9bd5180 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -94,7 +94,7 @@ const STATIC_EXPORTS = {
},
// Cross-directory .stylex modules that swizzled components import. Each is
// an explicit public subpath so the StyleX compiler can resolve the deep
- // import rewriteImports emits (see api/swizzle/copy/copy.mjs). No wildcard —
+ // import a swizzled copy uses (see api/swizzle/_moduleGraph.mjs). No wildcard —
// a future cross-directory .stylex import needs a deliberate entry here.
// Precedent: ./theme/tokens.stylex and ./theme/dataTokens.stylex above.
'./DateInput/tokens.stylex': {