Skip to content

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

TypeScript

fix(cli): swizzle copies the private attribute owner modules a component imports (#10085)

Cindy Zhang87ed8d08195a
diff --git a/.changeset/swizzle-owner-modules.md b/.changeset/swizzle-owner-modules.md
new file mode 100644
index 0000000000..a2cbc57eb9
--- /dev/null
+++ b/.changeset/swizzle-owner-modules.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx swizzle` now copies the private attribute owner modules a component imports, and the unexported style modules they need, beside the copy in the package's layout. A swizzled `Item`, `CheckboxList`, `RadioList` or `TreeList` no longer imports a `privateAttributes/*.stylex` subpath that `@astryxdesign/core` does not export. A second swizzle reuses an identical copy and refuses a changed one without `--overwrite`. The receipt's `files` and `filesCopied` include the modules it copied.
+
+@cixzhang
diff --git a/docs/architecture/interaction-modality.md b/docs/architecture/interaction-modality.md
index 7126c82066..ca42a633a9 100644
--- a/docs/architecture/interaction-modality.md
+++ b/docs/architecture/interaction-modality.md
@@ -147,8 +147,7 @@ work.
no component writes the attribute or its selector itself. Implementation
gap: the module does not exist yet, and Item, Token, the clickable and
selectable cards, Thumbnail, the Selectors, SideNavItem, and ChatComposer's
- body write their own ring conditions. Swizzle does not yet carry an
- unexported owner module into an ejected copy.
+ body write their own ring conditions.
- **INV4 — Every modality has an operable path.** Keyboard, pointer, and touch or
pen can reach each supported interaction. Hover is never the only discovery or
activation path. A tooltip's scrolling overflow is the one exception, as
diff --git a/docs/specs/AST-110-swizzle-output/spec.md b/docs/specs/AST-110-swizzle-output/spec.md
index 86b5cf077c..76823392da 100644
--- a/docs/specs/AST-110-swizzle-output/spec.md
+++ b/docs/specs/AST-110-swizzle-output/spec.md
@@ -78,7 +78,8 @@ and the repository proves it before a change that could break it merges.
file is reused; a different file is never overwritten, even with
`--overwrite`, which replaces only the component's own files: the new helper
is written alongside under a version-suffixed name, and only the new copy's
- imports point at it.
+ imports point at it, except a private attribute owner module and the
+ unexported style modules it imports, which FR4 governs.
- **FR3 — Shared runtime state stays single.** A module whose state coordinates
components with each other (the layer stack, the modal outlet, interaction
modality, the bottom-sheet stack, the announcement channel of `spec:AST-086`
@@ -101,8 +102,13 @@ and the repository proves it before a change that could break it merges.
by a copy.
- **FR4 — Private attributes stay contained.** Each private data attribute's
owner module (`architecture:public-component-api` INV23) that the component
- imports is copied whole and unedited, so callers, the copy included, still
- never write the attribute by hand.
+ imports travels with the copy, so callers, the copy included, still never
+ write the attribute by hand. Swizzle copies an imported owner module, and any
+ unexported style module it imports, whole: the copy is unedited except that
+ imports of modules the package exports are rewritten to their package
+ subpaths, as the component's own files are; unexported dependencies keep
+ their relative imports in the same layout. Re-swizzling skips an identical
+ existing copy and refuses a changed one without `--overwrite`.
- **FR5 — Theme targets and class names are unchanged.** The copy answers to the
same theme targets and emits the same documented class names, data attributes,
and custom properties as the package component of that version, so a theme,
@@ -162,7 +168,9 @@ and the repository proves it before a change that could break it merges.
dependency the copy imports with the owner package's declared range (FR1).
An existing component file still fails with `ERR_FILE_EXISTS` unless
`--overwrite` is passed; an existing helper never fails the command and is
- never replaced, with or without `--overwrite` (FR2).
+ never replaced, with or without `--overwrite` (FR2), except an owner module
+ and its unexported style modules, which a changed copy refuses without
+ `--overwrite` and replaces with it (FR4).
- `@astryxdesign/build`'s Vite, PostCSS, Babel, and Next integrations compile
modules under an `astryx-swizzle.json` directory in the library pass (FR5).
- The styling overview states that a copy's rules land in `astryx-base` with
@@ -188,6 +196,9 @@ and the repository proves it before a change that could break it merges.
overlay do not see its layer boundary or modal: a package picker announces
outside the copied modal (`spec:AST-086` FR14), and package group context
crosses into it (`spec:AST-038` FR7) (FR3).
+- The result does not yet report whether each shared module was written,
+ reused or replaced (FR2's impact bullet); adding that receipt field is the CLI
+ owner's call.
- Core's private type additions, such as `focusVisible`, do not travel with a
copy, and a unique symbol splits identity between a copied and a package
AppShell (FR1, FR3).
@@ -196,7 +207,6 @@ and the repository proves it before a change that could break it merges.
(FR1).
- Some names `swizzle --list` offers differ from their folder's export names
(Chat, NavMenu, Indicator, Resizable) (`spec:AST-035` FR12).
-- No private data-attribute owner module exists yet (FR4).
- Products on the stock StyleX plugins have no library-pass setting, so a
copy's rules land above `astryx-theme` there and theme component overrides do
not reach it (FR5).
@@ -211,7 +221,7 @@ and the repository proves it before a change that could break it merges.
| Contract | Verification | Representative states | Mutation or failure expectation |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| FR1 | Eject every offered component into a clean project; type-check and bundle | Every component in `swizzle --list`; Core, Lab, Charts, RichText, Vega; a component that imports an npm dependency | A type or resolve error, or an import of a path the owner's `exports` lacks or of `./internal/*`, fails, or a dependency the copy imports goes unreported |
-| FR2 | Import graph of each output | Helpers in `utils`, `hooks`, `Layer`; nested folders; colocated tests and docs; a helper an earlier swizzle wrote, identical and different | A copied file imports a module that is neither in the output nor a public export, or a test, story, spec, or doc is copied, or an existing helper is overwritten |
+| FR2 | Import graph of each output | Helpers in `utils`, `hooks`, `Layer`; nested folders; colocated tests and docs; a helper an earlier swizzle wrote, identical and different | A copied file imports a module that is neither in the output nor a public export, or a test, story, spec, or doc is copied, or an existing helper other than an owner module (FR4) is overwritten |
| FR3 | Render a copied and a package layer component together; inspect stores; open, stack, and Escape | Dialog over package Popover; BottomSheet over package Dialog; modality; a copied `useToast` under the package `LayerProvider`; a symbol-branded object passed between copy and package; a copied Dialog announcing beside a package component; a package picker inside a copied Dialog announcing a result count; a package grouped control inside a copied overlay | In either direction (copy under package, package under copy): two stores of one protocol version exist in a document, Escape and focus return differ from the package alone, a copied consumer misses the package provider, a brand check fails, a second live region appears instead of one announcer (`spec:AST-086` FR9), an announcement escapes the open modal (`spec:AST-086` FR14), or group context crosses the layer boundary (`spec:AST-038` FR7) |
| FR4 | Scan each output for private data-attribute names and selectors; compare copied owner modules with the package's | Components that reach an owner module | A hand-written private attribute name or selector, or an edited owner module, in the output |
| FR5 | Render package and copy side by side under a theme with component overrides; compare | Default; each variant; a theme component override; a copy built by `@astryxdesign/build` | A theme override, documented class name, data attribute, or theme target reaches one and not the other |
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 9d214cae88..05fc3f979c 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -499,7 +499,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, 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. The envelope's package names the same owning package. |
+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the copied file names (relative to the component folder; owner modules copied beside it start with ../), 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. The envelope's package names the same owning package. |
| `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index fb8cdc07d7..710886a3c1 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -59,10 +59,16 @@ const DEFAULT_ISSUES_URL = 'https://github.com/meta/astryx/issues/new';
*
* @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) {
+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('/');
@@ -90,6 +96,153 @@ export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
);
}
+/** 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'];
+
+/**
+ * The relative import specifiers in a module's source.
+ * @param {string} content
+ * @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]);
+ }
+ return found;
+}
+
+/**
+ * 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.
+ * @param {string} srcRoot
+ * @param {string} fromDir directory of the importing file, relative to srcRoot
+ * @param {string} importPath
+ * @returns {{module: string, file: string} | null}
+ */
+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;
+}
+
+/**
+ * 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;
+ }
+}
+
+/**
+ * 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
+ */
+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;
+}
+
+/**
+ * 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}
+ */
+function keepCarried(carried, fromDir) {
+ return importPath => {
+ const module = path.posix
+ .normalize(path.posix.join(fromDir, importPath))
+ .replace(/\.[cm]?[jt]sx?$/, '');
+ return carried.has(module);
+ };
+}
+
/**
* Build the maintainer feedback note for a swizzled component.
* @param {string} component
@@ -317,19 +470,64 @@ export async function swizzleCopy(component, options = {}) {
label: 'output file',
});
}
+ // 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)),
+ );
+ const dest = confineWrite(path.join(outputBase, 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.
+ return {
+ file,
+ dest,
+ content,
+ unchanged: existing === content,
+ exists: existing != null,
+ };
+ });
const existingFiles = sourceFiles.filter(f =>
fs.existsSync(path.join(outputDir, f)),
);
- if (existingFiles.length > 0 && !overwrite) {
+ const changedShared = shared.filter(s => s.exists && !s.unchanged);
+ if ((existingFiles.length > 0 || changedShared.length > 0) && !overwrite) {
const relOutputForMsg = path.relative(cwd, outputDir) || '.';
+ const sharedNote =
+ changedShared.length > 0
+ ? ` and ${changedShared.length} changed shared module(s) (${changedShared
+ .map(s => path.relative(cwd, s.dest))
+ .join(', ')})`
+ : '';
throw new AstryxError(
- `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
+ `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/${sharedNote}. ` +
`Re-run with --overwrite (or -f) to replace them.`,
[],
ERROR_CODES.ERR_FILE_EXISTS,
);
}
+
const outputDirExisted = fs.existsSync(outputDir);
try {
fs.mkdirSync(outputDir, {recursive: true});
@@ -351,7 +549,7 @@ export async function swizzleCopy(component, options = {}) {
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);
+ content = rewriteImports(content, owner.ownerPackage, keepCarried(carried, componentRel));
}
if (
(file.endsWith('.ts') || file.endsWith('.tsx')) &&
@@ -381,6 +579,38 @@ export async function swizzleCopy(component, options = {}) {
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) {
+ copied++;
+ continue;
+ }
+ try {
+ const original = fs.existsSync(module.dest)
+ ? fs.readFileSync(module.dest)
+ : null;
+ const firstCreated = fs.mkdirSync(path.dirname(module.dest), {recursive: true});
+ if (firstCreated != null) createdDirs.push(firstCreated);
+ written.push({dest: module.dest, original});
+ fs.writeFileSync(module.dest, module.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);
+ }
+ }
+ if (shared.length > 0) usesStyleX = true;
+
const relOutput = path.relative(cwd, outputDir);
const copiedFiles = files.filter(
f =>
@@ -393,7 +623,12 @@ export async function swizzleCopy(component, options = {}) {
package: owner.package,
outputDir: relOutput,
filesCopied: copied,
- files: copiedFiles.map(f => f),
+ // 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,
};
if (feedback) data.feedback = feedback;
diff --git a/packages/cli/api/swizzle/copy/copy.test.mjs b/packages/cli/api/swizzle/copy/copy.test.mjs
index 86bb9060e7..bd9777ced9 100644
--- a/packages/cli/api/swizzle/copy/copy.test.mjs
+++ b/packages/cli/api/swizzle/copy/copy.test.mjs
@@ -140,3 +140,139 @@ describe('swizzle.copy — the gh feedback line', () => {
SLOW,
);
});
+
+describe('swizzle.copy — private attribute owner modules (spec:AST-110 FR4)', () => {
+ const OWNER_OUT = 'tmp-swizzle-owner-test';
+ const out = () => path.join(REPO, OWNER_OUT);
+ const exportKeys = () =>
+ new Set(
+ Object.keys(
+ JSON.parse(
+ fs.readFileSync(
+ path.join(REPO, 'packages/core/package.json'),
+ 'utf-8',
+ ),
+ ).exports,
+ ),
+ );
+ /** Every `@astryxdesign/core/*` import in a file. */
+ const coreImportsOf = file =>
+ [
+ ...fs
+ .readFileSync(file, 'utf-8')
+ .matchAll(/from ['"](@astryxdesign\/core\/[^'"]+)['"]/g),
+ ].map(m => m[1]);
+ /** A module's source with every import specifier blanked. */
+ const withoutSpecifiers = content =>
+ content.replace(/(from\s+['"])[^'"]+(['"])/g, '$1$2');
+
+ afterEach(() => {
+ fs.rmSync(out(), {recursive: true, force: true});
+ });
+
+ it(
+ 'copies the owner module a component imports, and its unexported style module, beside it',
+ async () => {
+ const r = await swizzle('Item', {cwd: REPO, output: './' + OWNER_OUT});
+ expect(r.type).toBe('swizzle.copy');
+ expect(r.data.files).toEqual(
+ expect.arrayContaining([
+ '../privateAttributes/press.stylex.ts',
+ '../motion/reducedMotion.stylex.ts',
+ ]),
+ );
+ expect(r.data.filesCopied).toBe(r.data.files.length);
+ // The component's import of the owner module stays relative.
+ expect(
+ fs.readFileSync(path.join(out(), 'Item/Item.tsx'), 'utf-8'),
+ ).toContain("from '../privateAttributes/press.stylex'");
+ // The owner module keeps its relative import of the unexported module,
+ // and every package import in any copied file resolves.
+ const owner = path.join(out(), 'privateAttributes/press.stylex.ts');
+ expect(fs.readFileSync(owner, 'utf-8')).toContain(
+ "from '../motion/reducedMotion.stylex'",
+ );
+ const keys = exportKeys();
+ for (const file of [
+ ...fs
+ .readdirSync(path.join(out(), 'Item'))
+ .map(f => path.join(out(), 'Item', f)),
+ owner,
+ path.join(out(), 'motion/reducedMotion.stylex.ts'),
+ ]) {
+ for (const specifier of coreImportsOf(file)) {
+ expect(
+ keys.has('./' + specifier.replace('@astryxdesign/core/', '')),
+ specifier,
+ ).toBe(true);
+ }
+ }
+ // Whole and unedited, except import specifiers.
+ expect(withoutSpecifiers(fs.readFileSync(owner, 'utf-8'))).toBe(
+ withoutSpecifiers(
+ fs.readFileSync(
+ path.join(
+ REPO,
+ 'packages/core/src/privateAttributes/press.stylex.ts',
+ ),
+ 'utf-8',
+ ),
+ ),
+ );
+ },
+ SLOW,
+ );
+
+ it(
+ 'reuses an identical copy for a second component, and refuses a changed one without --overwrite',
+ async () => {
+ await swizzle('Item', {cwd: REPO, output: './' + OWNER_OUT});
+ const second = await swizzle('CheckboxList', {
+ cwd: REPO,
+ output: './' + OWNER_OUT,
+ });
+ // The identical owner module is part of the second copy too.
+ expect(second.data.files).toContain('../privateAttributes/press.stylex.ts');
+ expect(second.data.filesCopied).toBe(second.data.files.length);
+
+ const owner = path.join(out(), 'privateAttributes/press.stylex.ts');
+ const copied = fs.readFileSync(owner, 'utf-8');
+ fs.writeFileSync(owner, copied + '\n// edited\n');
+ fs.rmSync(path.join(out(), 'CheckboxList'), {
+ recursive: true,
+ force: true,
+ });
+ await expect(
+ swizzle('CheckboxList', {cwd: REPO, output: './' + OWNER_OUT}),
+ ).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});
+ // The refusal wrote nothing.
+ expect(fs.existsSync(path.join(out(), 'CheckboxList'))).toBe(false);
+ expect(fs.readFileSync(owner, 'utf-8')).toBe(copied + '\n// edited\n');
+
+ await swizzle('CheckboxList', {
+ cwd: REPO,
+ output: './' + OWNER_OUT,
+ overwrite: true,
+ });
+ expect(fs.readFileSync(owner, 'utf-8')).toBe(copied);
+ },
+ SLOW,
+ );
+
+ it(
+ 'a failed shared-module write leaves no folder it created behind',
+ async () => {
+ // A folder where the owner module goes makes its write fail.
+ const blocked = path.join(out(), 'privateAttributes/press.stylex.ts');
+ fs.mkdirSync(blocked, {recursive: true});
+ await expect(
+ swizzle('Item', {cwd: REPO, output: './' + OWNER_OUT, overwrite: true}),
+ ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});
+ expect(fs.existsSync(path.join(out(), 'Item'))).toBe(false);
+ expect(fs.existsSync(path.join(out(), 'motion'))).toBe(false);
+ // The folder that was there before the run stays.
+ expect(fs.existsSync(blocked)).toBe(true);
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/api/swizzle/swizzle.doc.mjs b/packages/cli/api/swizzle/swizzle.doc.mjs
index 8caafc8785..eed6911177 100644
--- a/packages/cli/api/swizzle/swizzle.doc.mjs
+++ b/packages/cli/api/swizzle/swizzle.doc.mjs
@@ -76,7 +76,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 written file names, 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, 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.',
},
],
throws: [
diff --git a/packages/cli/api/swizzle/swizzle.test.mjs b/packages/cli/api/swizzle/swizzle.test.mjs
index 045e46b2e1..b12b42ca55 100644
--- a/packages/cli/api/swizzle/swizzle.test.mjs
+++ b/packages/cli/api/swizzle/swizzle.test.mjs
@@ -1,6 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
+import {afterEach, describe, it, expect} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
@@ -122,7 +122,12 @@ describe('swizzle() API', () => {
});
describe('swizzle rewriteImports compiles for components with .stylex imports', () => {
- it('Button: every rewritten import resolves in the core exports map', async () => {
+ const OUT = 'tmp-swizzle-resolve-test';
+ afterEach(() => {
+ fs.rmSync(path.join(REPO, OUT), {recursive: true, force: true});
+ });
+
+ it('Button: every import in the copy resolves, in the core exports map or to a copied file', async () => {
const corePkg = JSON.parse(
fs.readFileSync(
path.join(REPO, 'packages/core/package.json'),
@@ -131,27 +136,32 @@ describe('swizzle rewriteImports compiles for components with .stylex imports',
);
const exportKeys = new Set(Object.keys(corePkg.exports));
- const buttonDir = path.join(REPO, 'packages/core/src/Button');
- const files = fs.readdirSync(buttonDir).filter(
- f => (f.endsWith('.ts') || f.endsWith('.tsx')) && !f.includes('.test.') && !f.includes('.doc.'),
- );
-
- for (const file of files) {
- const content = fs.readFileSync(path.join(buttonDir, file), 'utf-8');
- const rewritten = rewriteImports(content);
+ const r = await swizzle('Button', {cwd: REPO, output: './' + OUT});
+ const outputDir = path.join(REPO, r.data.outputDir);
+ const copied = r.data.files
+ .filter(f => (f.endsWith('.ts') || f.endsWith('.tsx')) && !f.includes('.test.'))
+ .map(f => path.join(outputDir, f));
- // Extract all rewritten @astryxdesign/core/* imports
- const importRe = /from ['"](@astryxdesign\/core\/[^'"]+)['"]/g;
- let m;
- while ((m = importRe.exec(rewritten)) !== null) {
+ for (const file of copied) {
+ const content = fs.readFileSync(file, 'utf-8');
+ for (const m of content.matchAll(/from ['"]([^'"]+)['"]/g)) {
const specifier = m[1];
- const subpath = './' + specifier.replace('@astryxdesign/core/', '');
-
- expect(
- exportKeys.has(subpath),
- `${specifier} (subpath ${subpath}) must resolve in core exports`,
- ).toBe(true);
+ if (specifier.startsWith('@astryxdesign/core/')) {
+ const subpath = './' + specifier.replace('@astryxdesign/core/', '');
+ expect(
+ exportKeys.has(subpath),
+ `${specifier} (subpath ${subpath}) must resolve in core exports`,
+ ).toBe(true);
+ } else if (specifier.startsWith('.')) {
+ // A relative import names a file the copy wrote: one of the
+ // component's own, or an owner module carried beside it (FR4).
+ const target = path.resolve(path.dirname(file), specifier);
+ expect(
+ ['', '.ts', '.tsx', '.mjs', '.js'].some(ext => fs.existsSync(target + ext)),
+ `${specifier} in ${path.relative(outputDir, file)} must name a copied file`,
+ ).toBe(true);
+ }
}
}
- });
+ }, 30_000);
});
diff --git a/packages/cli/api/swizzle/swizzle.type.mjs b/packages/cli/api/swizzle/swizzle.type.mjs
index 74082cadc4..038b20ded4 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
+ * @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 {boolean} data.usesStyleX Whether any copied file uses StyleX (requires build-time setup).
* @property {SwizzleFeedback} [data.feedback]
*/
diff --git a/packages/cli/clients/cli/commands/swizzle.mjs b/packages/cli/clients/cli/commands/swizzle.mjs
index 0cd19c0bf1..69f036bf55 100644
--- a/packages/cli/clients/cli/commands/swizzle.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.mjs
@@ -90,6 +90,16 @@ export function registerSwizzle(program) {
].join('\n'),
),
];
+ // Files the copy wrote outside the component folder: the owner modules
+ // and their unexported style modules (spec:AST-110 FR4).
+ 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)`,
+ ),
+ );
+ }
// StyleX build requirement — swizzled StyleX source throws on import
// ("Unexpected 'stylex.create' call at runtime") unless the consumer's
diff --git a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
index 170e4b9d7a..4e81a39db5 100644
--- a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs
@@ -340,3 +340,36 @@ 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');
+ const rowDir = path.join(core, 'src', 'Row');
+ fs.mkdirSync(rowDir, {recursive: true});
+ fs.mkdirSync(path.join(core, 'src', 'privateAttributes'), {recursive: true});
+ fs.mkdirSync(path.join(core, 'src', 'motion'), {recursive: true});
+ fs.writeFileSync(
+ path.join(core, 'package.json'),
+ '{"name":"@astryxdesign/core","version":"0.0.13"}',
+ );
+ fs.writeFileSync(
+ path.join(rowDir, 'Row.tsx'),
+ `import {rowStyles} from '../privateAttributes/row.stylex';\nexport const Row = () => null;\n`,
+ );
+ fs.writeFileSync(
+ path.join(core, 'src', 'privateAttributes', 'row.stylex.ts'),
+ `import {fade} from '../motion/fade.stylex';\nexport const rowStyles = fade;\n`,
+ );
+ fs.writeFileSync(
+ path.join(core, 'src', 'motion', 'fade.stylex.ts'),
+ `export const fade = 1;\n`,
+ );
+ writeProjectPackageJson(project);
+
+ 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)',
+ );
+ });
+});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 5a37d999f6..de88615baa 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -262,7 +262,7 @@ export const doc = {
{
value: 'swizzle.copy',
description:
- "An eject receipt: component name, owning package, output directory, files-copied count, the written file names, 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. The envelope's package names the same owning package.",
+ "An eject receipt: component name, owning package, output directory, files-copied count, the copied file names (relative to the component folder; owner modules copied beside it start with ../), 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. The envelope's package names the same owning package.",
},
// gap reports