Skip to content

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

TypeScript

fix(cli): preserve theme icon imports and inheritance (#5104)

Jiun Shineb0cef25b268
diff --git a/.changeset/theme-build-icon-detection-no-longer-reads-comme-knch.md b/.changeset/theme-build-icon-detection-no-longer-reads-comme-knch.md
new file mode 100644
index 0000000000..24b3a4bf78
--- /dev/null
+++ b/.changeset/theme-build-icon-detection-no-longer-reads-comme-knch.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `theme build` resolves real icon imports from the selected theme instead of matching comment or string contents. Generated modules preserve named, aliased, default, and namespace registry imports, plus inherited icons with child overrides. Normal builds and `--check` reject unsupported inline registries with `ERR_THEME_INVALID` before generating or writing output. Move such a registry into its own module and import it into the theme file.
+
+@jiunshinn
diff --git a/packages/cli/api/theme/build/build.icon-lineage.test.mjs b/packages/cli/api/theme/build/build.icon-lineage.test.mjs
new file mode 100644
index 0000000000..0e53e52a74
--- /dev/null
+++ b/packages/cli/api/theme/build/build.icon-lineage.test.mjs
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Icon preservation through multiple generations of built themes.
+ * @input Real themeBuild calls and registries imported under the same local
+ * binding name from separate base and child theme directories.
+ * @output A native ESM load verifies inherited and overridden React icons
+ * survive when a grandchild extends the child's generated artifact.
+ * @position Direct API regression for persisted icon inheritance in #5058.
+ * The node project's global setup supplies the compiled core package.
+ */
+
+import {expect, it} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {themeBuild} from './build.mjs';
+
+it('preserves merged icon lineage through a built child with colliding import names', async () => {
+ const tmpDir = fs.mkdtempSync(
+ path.resolve(import.meta.dirname, '../../..', '.tmp-icon-lineage-'),
+ );
+ try {
+ for (const directory of ['base', 'child']) {
+ fs.mkdirSync(path.join(tmpDir, directory));
+ }
+ const write = (file, source) =>
+ fs.writeFileSync(path.join(tmpDir, file), source);
+ const writeRegistry = (file, labels) => {
+ write(
+ file,
+ `import {createElement} from 'react';
+export const icons = {
+${Object.entries(labels)
+ .map(
+ ([key, label]) =>
+ ` ${JSON.stringify(key)}: createElement('svg', {'data-icon': ${JSON.stringify(label)}}),`,
+ )
+ .join('\n')}
+};
+`,
+ );
+ };
+
+ writeRegistry('base/icons.mjs', {
+ check: 'base-check',
+ close: 'base-close',
+ });
+ writeRegistry('child/icons.mjs', {
+ add: 'child-add',
+ close: 'child-close',
+ });
+ write(
+ 'base/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {icons} from './icons.mjs';
+export const baseTheme = defineTheme({
+ name: 'base', tokens: {'--color-bg': '#fff'}, icons,
+});
+`,
+ );
+ write(
+ 'child/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '../base/source.mjs';
+import {icons} from './icons.mjs';
+export default defineTheme({
+ name: 'child', extends: baseTheme, tokens: {}, icons,
+});
+`,
+ );
+ const child = await themeBuild('child/source.mjs', {}, {cwd: tmpDir});
+ expect(child?.type).toBe('theme.build');
+
+ write(
+ 'grandchild.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {childTheme} from './child/child.js';
+export default defineTheme({name: 'grandchild', extends: childTheme, tokens: {}});
+`,
+ );
+ const grandchild = await themeBuild('grandchild.mjs', {}, {cwd: tmpDir});
+ expect(grandchild?.type).toBe('theme.build');
+ const checked = await themeBuild(
+ 'grandchild.mjs',
+ {check: true},
+ {cwd: tmpDir},
+ );
+ expect(checked?.data.upToDate).toBe(true);
+
+ // Native imports catch invalid aliases and incorrect relative specifiers
+ // that the source loader could otherwise resolve or transform away.
+ execFileSync(
+ process.execPath,
+ [
+ '--input-type=module',
+ '--eval',
+ `import assert from 'node:assert/strict';
+import {isValidElement} from 'react';
+import {childTheme} from './child/child.js';
+import {grandchildTheme} from './grandchild.js';
+const expected = {check: 'base-check', close: 'child-close', add: 'child-add'};
+assert.deepEqual(Object.keys(grandchildTheme.icons).sort(), Object.keys(expected).sort());
+for (const [key, label] of Object.entries(expected)) {
+ const icon = grandchildTheme.icons[key];
+ assert.ok(isValidElement(icon), key + ' must remain a React element');
+ assert.equal(icon.type, 'svg');
+ assert.equal(icon.props['data-icon'], label);
+ assert.equal(icon, childTheme.icons[key], key + ' must retain its imported identity');
+}`,
+ ],
+ {cwd: tmpDir, stdio: 'pipe', timeout: 10000},
+ );
+ } finally {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ }
+});
diff --git a/packages/cli/api/theme/build/build.icon-preservation.test.mjs b/packages/cli/api/theme/build/build.icon-preservation.test.mjs
new file mode 100644
index 0000000000..4d51e91672
--- /dev/null
+++ b/packages/cli/api/theme/build/build.icon-preservation.test.mjs
@@ -0,0 +1,639 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Regression coverage for icon registry preservation in theme builds.
+ * @input Real themeBuild calls, imported React icon registries, and source or
+ * built themes supplied to defineTheme's extends option.
+ * @output Checks generated ESM with Node's native loader, retained React
+ * elements, inherited paths and precedence, TypeScript binding provenance,
+ * and rejection before output writes.
+ * @position Direct API regression suite for the icon import bug in #5058.
+ * The node project's global setup supplies the compiled core package.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {themeBuild} from './build.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ // Keeping fixtures under the CLI package makes real core/React imports
+ // resolve in both the theme loader and the native Node artifact check.
+ tmpDir = fs.mkdtempSync(
+ path.resolve(import.meta.dirname, '../../..', '.tmp-icon-preservation-'),
+ );
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+function write(file, source) {
+ fs.writeFileSync(path.join(tmpDir, file), source);
+}
+
+function writeRegistry(file, exportName, icons) {
+ write(
+ file,
+ `import {createElement} from 'react';
+const registry = {
+${Object.entries(icons)
+ .map(
+ ([key, label]) =>
+ ` ${JSON.stringify(key)}: createElement('svg', {'data-icon': ${JSON.stringify(label)}}, createElement('path', {d: 'M0 0h1'})),`,
+ )
+ .join('\n')}
+};
+${exportName === 'default' ? 'export default registry;' : `export {registry as ${exportName}};`}
+`,
+ );
+}
+
+/**
+ * Load the artifact with native Node, without jiti/Vite resolving nonexistent
+ * imports or transforming its syntax. Valid React elements prove symbols and
+ * element contents survived, which JSON-only registry assertions cannot do.
+ */
+function readBuiltIcons(name, registryExport) {
+ const output = execFileSync(
+ process.execPath,
+ [
+ '--input-type=module',
+ '--eval',
+ `import assert from 'node:assert/strict';
+import {isValidElement} from 'react';
+const mod = await import(${JSON.stringify(`./${name}.js`)});
+const theme = Object.values(mod).find(value => value?.name === ${JSON.stringify(name)});
+assert.ok(theme?.icons, 'generated theme must retain its icons');
+${registryExport ? `assert.equal(mod[${JSON.stringify(registryExport)}], theme.icons, 'registry re-export must match the theme');` : ''}
+const icons = Object.fromEntries(Object.entries(theme.icons).map(([key, icon]) => {
+ assert.ok(isValidElement(icon), key + ' must remain a React element');
+ assert.equal(icon.type, 'svg');
+ assert.ok(isValidElement(icon.props.children));
+ assert.equal(icon.props.children.props.d, 'M0 0h1');
+ return [key, icon.props['data-icon']];
+}));
+process.stdout.write(JSON.stringify(icons));`,
+ ],
+ {cwd: tmpDir, encoding: 'utf8', timeout: 10000},
+ );
+ return JSON.parse(output);
+}
+
+async function buildAndCheck(file) {
+ const built = await themeBuild(file, {}, {cwd: tmpDir});
+ expect(built?.type).toBe('theme.build');
+ const checked = await themeBuild(file, {check: true}, {cwd: tmpDir});
+ expect(checked?.type).toBe('theme.build.check');
+ expect(checked?.data.upToDate).toBe(true);
+ expect(checked?.data.stale).toEqual([]);
+}
+
+describe('themeBuild() — actual icon imports', () => {
+ it.each([
+ ['named', 'liveIcons', "import {liveIcons} from './icons.mjs';"],
+ ['default', 'default', "import liveIcons from './icons.mjs';"],
+ [
+ 'aliased named',
+ 'originalIcons',
+ "import {originalIcons as liveIcons} from './icons.mjs';",
+ ],
+ ])(
+ 'preserves a %s registry import and its re-export',
+ async (_label, exportName, statement) => {
+ writeRegistry('icons.mjs', exportName, {close: 'close'});
+ write(
+ 'live.mjs',
+ `${statement}
+export default {name: 'live', tokens: {'--color-bg': '#fff'}, icons: liveIcons};
+`,
+ );
+
+ await buildAndCheck('live.mjs');
+
+ expect(readBuiltIcons('live', 'liveIcons')).toEqual({close: 'close'});
+ if (exportName === 'liveIcons') {
+ const generated = fs.readFileSync(path.join(tmpDir, 'live.js'), 'utf8');
+ expect(generated).toContain("import { liveIcons } from './icons.mjs';");
+ expect(generated).toContain('icons: liveIcons,');
+ expect(generated).toContain('export { liveIcons };');
+ }
+ },
+ );
+
+ it('preserves a namespace used directly as the icon registry', async () => {
+ write(
+ 'icons.mjs',
+ `import {createElement} from 'react';
+export const close = createElement('svg', {'data-icon': 'close'}, createElement('path', {d: 'M0 0h1'}));
+`,
+ );
+ write(
+ 'live.mjs',
+ `import * as liveIcons from './icons.mjs';
+export default {name: 'live', tokens: {'--color-bg': '#fff'}, icons: liveIcons};
+`,
+ );
+
+ await buildAndCheck('live.mjs');
+
+ expect(readBuiltIcons('live', 'liveIcons')).toEqual({close: 'close'});
+ });
+
+ it('uses the selected export instead of an unrelated earlier icons field', async () => {
+ writeRegistry('icons.mjs', 'liveIcons', {close: 'selected'});
+ write(
+ 'selected.mjs',
+ `import {liveIcons} from './icons.mjs';
+const inlineIcons = {close: 'unrelated'};
+const metadata = {icons: inlineIcons};
+export const otherTheme = {name: 'other', tokens: {}, icons: inlineIcons};
+export default {name: 'selected', tokens: {'--color-bg': '#fff'}, icons: liveIcons};
+`,
+ );
+
+ await buildAndCheck('selected.mjs');
+
+ expect(readBuiltIcons('selected', 'liveIcons')).toEqual({
+ close: 'selected',
+ });
+ expect(fs.existsSync(path.join(tmpDir, 'other.js'))).toBe(false);
+ });
+
+ it('rejects the selected inline registry even when another theme imports icons', async () => {
+ writeRegistry('icons.mjs', 'liveIcons', {close: 'unselected'});
+ write(
+ 'selected.mjs',
+ `import {liveIcons} from './icons.mjs';
+export const otherTheme = {name: 'other', tokens: {}, icons: liveIcons};
+const inlineIcons = {close: 'selected'};
+export default {name: 'selected', tokens: {'--color-bg': '#fff'}, icons: inlineIcons};
+`,
+ );
+
+ await expect(
+ themeBuild('selected.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ expect(fs.readdirSync(tmpDir).sort()).toEqual([
+ 'icons.mjs',
+ 'selected.mjs',
+ ]);
+ });
+
+ it('unwraps TypeScript assertions around an aliased defineTheme call', async () => {
+ writeRegistry('icons.mjs', 'liveIcons', {close: 'wrapped-close'});
+ write(
+ 'wrapped.ts',
+ `import {defineTheme as createTheme} from '@astryxdesign/core/theme';
+import {liveIcons} from './icons.mjs';
+export default createTheme(({
+ name: 'wrapped', tokens: {'--color-bg': '#fff'}, icons: liveIcons,
+} as const) satisfies Parameters<typeof createTheme>[0]);
+`,
+ );
+
+ await buildAndCheck('wrapped.ts');
+
+ expect(readBuiltIcons('wrapped', 'liveIcons')).toEqual({
+ close: 'wrapped-close',
+ });
+ });
+
+ it('ignores an icons field mentioned only in a string', async () => {
+ write(
+ 'plain.mjs',
+ `const note = 'icons: retired';
+export default {name: 'plain', tokens: {'--color-bg': '#fff'}};
+`,
+ );
+
+ await buildAndCheck('plain.mjs');
+
+ const generated = fs.readFileSync(path.join(tmpDir, 'plain.js'), 'utf8');
+ expect(generated).not.toMatch(/^import /m);
+ expect(generated).not.toContain('icons:');
+ });
+
+ it('avoids collisions between the icon binding and the generated theme export', async () => {
+ writeRegistry('icons.mjs', 'collisionTheme', {close: 'collision-close'});
+ write(
+ 'collision.mjs',
+ `import {collisionTheme} from './icons.mjs';
+export default {name: 'collision', tokens: {'--color-bg': '#fff'}, icons: collisionTheme};
+`,
+ );
+
+ await buildAndCheck('collision.mjs');
+
+ expect(readBuiltIcons('collision')).toEqual({close: 'collision-close'});
+ });
+
+ it('does not treat a type-only import as a runtime icon binding', async () => {
+ writeRegistry('icons.mjs', 'inlineIcons', {close: 'type-only'});
+ write(
+ 'inline.ts',
+ `import type {inlineIcons} from './icons.mjs';
+const inlineIcons = {close: 'inline'};
+export default {name: 'inline', tokens: {'--color-bg': '#fff'}, icons: inlineIcons};
+`,
+ );
+
+ for (const check of [false, true]) {
+ await expect(
+ themeBuild('inline.ts', {check}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ }
+ expect(fs.readdirSync(tmpDir).sort()).toEqual(['icons.mjs', 'inline.ts']);
+ });
+
+ it.each([
+ ['an empty object', '{}'],
+ ['only empty spreads', '{...null, ...undefined}'],
+ ])(
+ 'builds a root theme whose registry is %s without an icon import or field',
+ async (_label, registry) => {
+ write(
+ 'empty.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export default defineTheme({
+ name: 'empty', tokens: {'--color-bg': '#fff'}, icons: ${registry},
+});
+`,
+ );
+
+ const fresh = await themeBuild('empty.mjs', {check: true}, {cwd: tmpDir});
+ expect(fresh?.data.upToDate).toBe(false);
+ await buildAndCheck('empty.mjs');
+
+ const generated = fs.readFileSync(path.join(tmpDir, 'empty.js'), 'utf8');
+ expect(generated).not.toMatch(/^import /m);
+ expect(generated).not.toContain('icons');
+ expect(
+ fs.readFileSync(path.join(tmpDir, 'empty.d.ts'), 'utf8'),
+ ).not.toContain('IconRegistry');
+ },
+ );
+});
+
+describe.each([false, true])('fake icon imports (check: %s)', check => {
+ it.each([
+ [
+ 'string',
+ `const note = "import { inlineIcons } from './ghost-icons.mjs'";`,
+ ],
+ [
+ 'template',
+ "const note = `import { inlineIcons } from './ghost-icons.mjs'`;",
+ ],
+ [
+ 'regular expression',
+ "const note = /import { inlineIcons } from 'ghost-icons.mjs'/;",
+ ],
+ ])(
+ 'rejects an import inside a %s before creating or replacing outputs',
+ async (_label, decoy) => {
+ write(
+ 'inline.mjs',
+ `${decoy}
+const inlineIcons = {close: 'inline'};
+export default {name: 'inline', tokens: {'--color-bg': '#fff'}, icons: inlineIcons};
+`,
+ );
+ const originalFiles = fs.readdirSync(tmpDir);
+ await expect(
+ themeBuild(
+ 'inline.mjs',
+ {check, out: 'dist/inline.css'},
+ {cwd: tmpDir},
+ ),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ expect(fs.readdirSync(tmpDir)).toEqual(originalFiles);
+
+ fs.mkdirSync(path.join(tmpDir, 'dist'));
+ const outputs = ['inline.css', 'inline.js', 'inline.d.ts'];
+ for (const file of outputs) write(`dist/${file}`, `previous ${file}\n`);
+ await expect(
+ themeBuild(
+ 'inline.mjs',
+ {check, out: 'dist/inline.css'},
+ {cwd: tmpDir},
+ ),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ expect(fs.readdirSync(path.join(tmpDir, 'dist')).sort()).toEqual(
+ outputs.sort(),
+ );
+ for (const file of outputs) {
+ expect(fs.readFileSync(path.join(tmpDir, 'dist', file), 'utf8')).toBe(
+ `previous ${file}\n`,
+ );
+ }
+ },
+ );
+});
+
+describe.each(['source', 'built'])(
+ 'icons inherited from an imported %s base',
+ baseKind => {
+ async function writeBase() {
+ writeRegistry('base-icons.mjs', 'baseIcons', {
+ close: 'base-close',
+ check: 'base-check',
+ });
+ write(
+ 'base.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseIcons} from './base-icons.mjs';
+export const baseTheme = defineTheme({
+ name: 'base', tokens: {'--color-bg': '#fff'}, icons: baseIcons,
+});
+`,
+ );
+ if (baseKind === 'built') await buildAndCheck('base.mjs');
+ return `./base.${baseKind === 'built' ? 'js' : 'mjs'}`;
+ }
+
+ it('retains all base icons when the child has no local registry', async () => {
+ const baseSpecifier = await writeBase();
+ write(
+ 'child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '${baseSpecifier}';
+export default defineTheme({name: 'child', extends: baseTheme, tokens: {}});
+`,
+ );
+
+ await buildAndCheck('child.mjs');
+
+ expect(readBuiltIcons('child')).toEqual({
+ close: 'base-close',
+ check: 'base-check',
+ });
+ });
+
+ it('keeps all base icons when the child sets an empty registry', async () => {
+ const baseSpecifier = await writeBase();
+ write(
+ 'child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '${baseSpecifier}';
+export default defineTheme({
+ name: 'child', extends: baseTheme, tokens: {}, icons: {},
+});
+`,
+ );
+
+ const fresh = await themeBuild('child.mjs', {check: true}, {cwd: tmpDir});
+ expect(fresh?.data.upToDate).toBe(false);
+ await buildAndCheck('child.mjs');
+
+ expect(readBuiltIcons('child')).toEqual({
+ close: 'base-close',
+ check: 'base-check',
+ });
+ });
+
+ it('merges imported child icons over the base without dropping untouched keys', async () => {
+ const baseSpecifier = await writeBase();
+ writeRegistry('child-icons.mjs', 'childIcons', {
+ close: 'child-close',
+ add: 'child-add',
+ });
+ write(
+ 'child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseTheme} from '${baseSpecifier}';
+import {childIcons} from './child-icons.mjs';
+export default defineTheme({
+ name: 'child', extends: baseTheme, tokens: {}, icons: childIcons,
+});
+`,
+ );
+
+ await buildAndCheck('child.mjs');
+
+ expect(readBuiltIcons('child')).toEqual({
+ close: 'child-close',
+ check: 'base-check',
+ add: 'child-add',
+ });
+ });
+ },
+);
+
+describe('themeBuild() — inherited icon module resolution', () => {
+ it.each(['named', 'namespace'])(
+ 'redirects only the child registry when %s imports share a module',
+ async importKind => {
+ writeRegistry('base-icons.mjs', 'baseIcons', {
+ close: 'base-close',
+ check: 'base-check',
+ });
+ writeRegistry('child-icons.mjs', 'childIcons', {
+ close: 'child-close',
+ add: 'child-add',
+ });
+ write(
+ 'icons.mjs',
+ `export {baseIcons} from './base-icons.mjs';
+export {childIcons} from './child-icons.mjs';
+`,
+ );
+ // The emitted child sidecar deliberately has no baseIcons export.
+ writeRegistry('built-icons.mjs', 'childIcons', {
+ close: 'child-close',
+ add: 'child-add',
+ });
+ write(
+ 'child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+${importKind === 'named' ? "import {baseIcons, childIcons} from './icons.mjs';" : "import * as registries from './icons.mjs';"}
+const baseTheme = defineTheme({
+ name: 'base', tokens: {'--color-bg': '#fff'}, icons: ${importKind === 'named' ? 'baseIcons' : 'registries.baseIcons'},
+});
+export default defineTheme({
+ name: 'child', extends: baseTheme, tokens: {}, icons: ${importKind === 'named' ? 'childIcons' : 'registries.childIcons'},
+});
+`,
+ );
+
+ const options = {iconsSpecifier: './built-icons.mjs'};
+ const built = await themeBuild('child.mjs', options, {cwd: tmpDir});
+ expect(built?.type).toBe('theme.build');
+ const checked = await themeBuild(
+ 'child.mjs',
+ {...options, check: true},
+ {cwd: tmpDir},
+ );
+ expect(checked?.data.upToDate).toBe(true);
+ expect(readBuiltIcons('child')).toEqual({
+ close: 'child-close',
+ check: 'base-check',
+ add: 'child-add',
+ });
+ },
+ );
+
+ it('rebases a source base registry from its subdirectory to the child output', async () => {
+ fs.mkdirSync(path.join(tmpDir, 'brand'));
+ writeRegistry('brand/icons.mjs', 'brandIcons', {close: 'brand-close'});
+ write(
+ 'brand/source.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {brandIcons} from './icons.mjs';
+export const brandTheme = defineTheme({
+ name: 'brand', tokens: {'--color-bg': '#fff'}, icons: brandIcons,
+});
+`,
+ );
+ write(
+ 'child.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {brandTheme} from './brand/source.mjs';
+export default defineTheme({name: 'child', extends: brandTheme, tokens: {}});
+`,
+ );
+
+ await buildAndCheck('child.mjs');
+
+ expect(readBuiltIcons('child')).toEqual({close: 'brand-close'});
+ });
+
+ it('resolves an extensionless TypeScript base before its generated JS sibling', async () => {
+ writeRegistry('icons.mjs', 'brandIcons', {close: 'source-close'});
+ write(
+ 'base.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {brandIcons} from './icons.mjs';
+export const brandTheme = defineTheme({
+ name: 'base', tokens: {'--color-bg': '#fff'}, icons: brandIcons,
+});
+`,
+ );
+ // The generated sibling exports baseTheme, while the source's public
+ // export is brandTheme. Selecting base.js would erase the child base.
+ await buildAndCheck('base.ts');
+ write(
+ 'child.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {brandTheme} from './base';
+export default defineTheme({name: 'child', extends: brandTheme, tokens: {}});
+`,
+ );
+
+ await buildAndCheck('child.ts');
+
+ expect(readBuiltIcons('child')).toEqual({close: 'source-close'});
+ });
+});
+
+describe.each([false, true])(
+ 'unsupported icon provenance (check: %s)',
+ check => {
+ it('fails to load a missing registry import instead of dropping its icons', async () => {
+ write(
+ 'missing.mjs',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {missingIcons} from './missing-icons.mjs';
+export default defineTheme({
+ name: 'missing', tokens: {'--color-bg': '#fff'}, icons: missingIcons,
+});
+`,
+ );
+
+ await expect(
+ themeBuild(
+ 'missing.mjs',
+ {check, out: 'dist/missing.css'},
+ {cwd: tmpDir},
+ ),
+ ).rejects.toMatchObject({code: 'ERR_THEME_LOAD'});
+ expect(fs.readdirSync(tmpDir)).toEqual(['missing.mjs']);
+ });
+
+ it('rejects a registry mutated through a destructured theme alias before writing', async () => {
+ writeRegistry('icons.mjs', 'importedIcons', {
+ close: 'original-close',
+ check: 'retained-check',
+ });
+ write(
+ 'mutated.mjs',
+ `import {importedIcons} from './icons.mjs';
+const config = {
+ name: 'mutated', tokens: {'--color-bg': '#fff'}, icons: importedIcons,
+};
+const {icons} = config;
+delete icons.close;
+export default config;
+`,
+ );
+
+ await expect(
+ themeBuild(
+ 'mutated.mjs',
+ {check, out: 'dist/mutated.css'},
+ {cwd: tmpDir},
+ ),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ expect(fs.readdirSync(tmpDir).sort()).toEqual([
+ 'icons.mjs',
+ 'mutated.mjs',
+ ]);
+ });
+
+ it.each([
+ [
+ 'a defineTheme argument',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {config} from '@fixture/raw-theme';
+export default defineTheme(config);
+`,
+ ],
+ [
+ 'the selected re-export',
+ `export {config as default} from '@fixture/raw-theme';
+`,
+ ],
+ ])(
+ 'rejects an opaque package raw config used as %s before writing',
+ async (_label, source) => {
+ const packageDirectory = 'node_modules/@fixture/raw-theme';
+ fs.mkdirSync(path.join(tmpDir, packageDirectory), {recursive: true});
+ write(
+ `${packageDirectory}/package.json`,
+ JSON.stringify({
+ name: '@fixture/raw-theme',
+ type: 'module',
+ exports: './index.mjs',
+ }),
+ );
+ writeRegistry(`${packageDirectory}/icons.mjs`, 'baseIcons', {
+ close: 'inherited-close',
+ });
+ write(
+ `${packageDirectory}/index.mjs`,
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {baseIcons} from './icons.mjs';
+const baseTheme = defineTheme({
+ name: 'package-base', tokens: {'--color-bg': '#fff'}, icons: baseIcons,
+});
+export const config = {name: 'raw-package', extends: baseTheme, tokens: {}};
+`,
+ );
+ write('package-config.mjs', source);
+
+ await expect(
+ themeBuild(
+ 'package-config.mjs',
+ {check, out: 'dist/raw-package.css'},
+ {cwd: tmpDir},
+ ),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ expect(fs.readdirSync(tmpDir).sort()).toEqual([
+ 'node_modules',
+ 'package-config.mjs',
+ ]);
+ },
+ );
+ },
+);
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 8d09263a69..7026e5dcc8 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -2,6 +2,9 @@
/**
* @file theme build API — compile standalone themes or one selected family.
+ * @input JS/TS theme modules, build/check options, and the installed Core.
+ * @output Generated artifacts preserving imported and inherited icon registries.
+ * @position CLI theme compiler; standalone icon provenance is icon-imports.mjs.
*
* `themeBuild` and `themeBuildFamily` share the same loader, compiler,
* serializers, check, and writer. They read defineTheme() sources and, via
@@ -12,11 +15,14 @@
* - A .d.ts (plus an optional .variants.d.ts for custom prop values)
*
* It performs the writes and returns a `theme.build` receipt — its `warnings`
- * carry override problems, every declaration core's generator dropped because
- * its value could not stay one CSS declaration, and any fonts the theme names
- * but does not load (font-warning.mjs) — or `null` when the theme produced no
- * CSS (nothing to build). Errors throw AstryxError (with
- * a stable code). Human progress is emitted through the shared `logger`
+ * carry override problems and every declaration core's generator dropped
+ * because its value could not stay one CSS declaration; `notices` carry fonts
+ * the theme names but does not load (font-warning.mjs) — or `null` when the
+ * theme produced no CSS (nothing to build). Standalone icon imports come from
+ * the selected theme's parsed bindings and inheritance, never from comment or
+ * string contents. A registry that cannot be preserved fails before output
+ * generation, including in check mode. Errors throw AstryxError (with a stable
+ * code). Human progress is emitted through the shared `logger`
* (silent by default), so the CLI keeps its exact output while a programmatic
* caller stays quiet.
*
@@ -67,6 +73,7 @@ import {
import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
import {interceptCore} from './core-interception.mjs';
import {generateFamilyCSS, resolveThemeFamily} from './family.mjs';
+import {resolveIconImports} from './icon-imports.mjs';
// Import shared theme processing from core. `astryx theme build` MUST produce the
// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
@@ -1506,6 +1513,19 @@ async function validateRegistryGraphs(/** @type {Array<{specifier: string, expor
if (!(root.exportName in exports)) throw registryGraphError(`Family registry ${root.file} does not export "${root.exportName}".`);
}
}
+/**
+ * Resolve inherited source with exactly the loader's extension precedence.
+ * This reads module locations only; icon discovery never executes a second load.
+ * @param {string} specifier
+ * @param {string} fromFile
+ * @returns {string}
+ */
+function resolveThemeModule(specifier, fromFile) {
+ return createJiti(fromFile, {extensions: THEME_MODULE_EXTENSIONS}).resolve(
+ specifier,
+ );
+}
+
/**
* Errors that mean "the synchronous loader cannot evaluate this module", as
* opposed to "this module is broken". Only the former may fall back to the
@@ -1553,7 +1573,7 @@ function isSyncLoaderLimitation(error) {
*
* @param {string} filePath
* @param {import('./core-interception.mjs').CoreInterception} [interception]
- * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
+ * @returns {Promise<{theme: any, exportName: string, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
*/
// prettier-ignore
async function importThemeModule(filePath, interception, /** @type {any} */ loader = undefined) {
@@ -1603,12 +1623,14 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
mod = await jiti.import(filePath, {default: true});
}
- if (isThemeObject(mod)) return {theme: mod, degraded};
+ if (isThemeObject(mod)) return {theme: mod, exportName: 'default', degraded};
if (mod && typeof mod === 'object') {
- if (isThemeObject(mod.default)) return {theme: mod.default, degraded};
- for (const value of Object.values(mod)) {
- if (isThemeObject(value)) return {theme: value, degraded};
+ if (isThemeObject(mod.default)) {
+ return {theme: mod.default, exportName: 'default', degraded};
+ }
+ for (const [exportName, value] of Object.entries(mod)) {
+ if (isThemeObject(value)) return {theme: value, exportName, degraded};
}
}
@@ -1642,7 +1664,7 @@ function isThemeObject(value) {
*
* @param {string} filePath
* @param {import('./core-interception.mjs').CoreInterception} [interception]
- * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
+ * @returns {Promise<{theme: any, exportName?: string, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
*/
// prettier-ignore
async function extractThemeDefinition(filePath, interception, /** @type {any} */ loader = undefined) {
@@ -1667,6 +1689,8 @@ async function extractThemeDefinition(filePath, interception, /** @type {any} */
/**
* Fallback extraction via regex + eval.
* Only works for plain object literals — can't follow imports or variables.
+ * Never erase icon references: an unresolved registry must preserve the loader
+ * error instead of turning an incomplete theme into a successful build.
* @param {string} filePath
* @returns {any}
*/
@@ -1688,10 +1712,6 @@ function extractThemeDefinitionLegacy(filePath) {
let objStr = defineMatch[1];
objStr = objStr.replace(/\s+as\s+const/g, '');
- objStr = objStr.replace(
- /icons:\s*[a-zA-Z_][a-zA-Z0-9_]*/g,
- 'icons: undefined',
- );
try {
return eval(`(${objStr})`);
@@ -1706,30 +1726,19 @@ function extractThemeDefinitionLegacy(filePath) {
}
/**
- * Extract icon import info from a theme source file.
- * Returns { importPath, exportName } or null if no icons.
+ * Extract a family member's named registry import from its source file.
+ * Returns { importPath, exportName } or null when the theme names none.
+ * Standalone builds resolve icons through `resolveIconImports` instead.
*
* Looks for patterns like:
* import { defaultIconRegistry } from './icons';
* icons: defaultIconRegistry,
* @param {string} filePath
+ * @param {'icons' | 'indicators'} field
* @returns {{exportName: string, importPath: string} | null}
*/
-function extractRegistryInfo(filePath, field = 'icons', familyMode = false) {
+function extractRegistryInfo(filePath, field) {
const content = fs.readFileSync(filePath, 'utf8');
- if (!familyMode) {
- const fieldMatch = content.match(
- new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)`),
- );
- if (!fieldMatch) return null;
- const varName = fieldMatch[1];
- const match = content.match(
- new RegExp(
- `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,
- ),
- );
- return match ? {exportName: varName, importPath: match[1]} : null;
- }
const defineIndex = content.indexOf('defineTheme(');
if (defineIndex < 0) return null;
const themeSource = content.slice(defineIndex);
@@ -1769,17 +1778,18 @@ function extractRegistryInfo(filePath, field = 'icons', familyMode = false) {
* override it had.
*
* The icon registry is imported rather than inlined because it holds React
- * elements, which cannot be serialized. `extractIconInfo` lifts the specifier
- * out of the TypeScript source, where an extensionless `./icons` is resolved by
+ * elements, which cannot be serialized. `resolveIconImports` reads actual
+ * imports from the selected theme's source, where extensionless `./icons` uses
* the TypeScript resolver — but the artifact here is ESM JavaScript, which
* requires a fully specified path. Only the caller knows what its own build
* will emit and under what name, so `iconsSpecifier` lets it say. When it is
- * not given, the scraped specifier is emitted unchanged.
+ * not given, direct registry specifiers are preserved, and inherited relative
+ * imports are rebased from the base module to the theme entry's directory.
*
* @param {any} themeDef
- * @param {{exportName: string, importPath: string} | null} iconInfo
- * @param {string} [iconsSpecifier] - Overrides the scraped icon import specifier.
- * @param {{themeBinding?: string, iconBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
+ * @param {import('./icon-imports.mjs').IconImports | null} iconInfo
+ * @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
+ * @param {{themeBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
* @returns {string}
*/
function generateBuiltModule(
@@ -1790,29 +1800,46 @@ function generateBuiltModule(
) {
const themeBinding =
moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
- const iconBinding = moduleOptions.iconBinding ?? iconInfo?.exportName;
const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;
const exportIcons = moduleOptions.exportIcons ?? true;
- // Preserve the historical generated bytes when no override is supplied.
- // User-provided specifiers need string-literal encoding so quotes and
- // backslashes cannot produce invalid JavaScript.
- const renderedSpecifier =
- iconsSpecifier === undefined
- ? `'${iconInfo?.importPath}'`
- : JSON.stringify(iconsSpecifier);
- const iconImport = iconInfo
- ? `import { ${iconInfo.exportName}${iconBinding === iconInfo.exportName ? '' : ` as ${iconBinding}`} } from ${renderedSpecifier};\n`
- : '';
- const iconsExpression =
- moduleOptions.iconsExpression ?? (iconInfo ? iconBinding : undefined);
+ // Keep ordinary direct named imports byte-compatible, while encoding paths
+ // with quotes/escapes and retaining default, namespace, and aliased bindings.
+ const iconImport = (iconInfo?.imports ?? [])
+ .map(({importPath, importedName, localName}) => {
+ const overridden =
+ iconsSpecifier !== undefined &&
+ importPath === iconInfo?.iconsSpecifierImportPath &&
+ localName === iconInfo?.iconsSpecifierLocalName;
+ const specifier = overridden
+ ? JSON.stringify(iconsSpecifier)
+ : /['\\\r\n]/u.test(importPath)
+ ? JSON.stringify(importPath)
+ : `'${importPath}'`;
+ const imported = /^[$\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(
+ importedName,
+ )
+ ? importedName
+ : JSON.stringify(importedName);
+ const binding =
+ importedName === 'default'
+ ? localName
+ : importedName === '*'
+ ? `* as ${localName}`
+ : `{ ${imported}${importedName === localName ? '' : ` as ${localName}`} }`;
+ return `import ${binding} from ${specifier};\n`;
+ })
+ .join('');
+ const iconDeclaration =
+ iconInfo && iconInfo.expression !== iconInfo.exportName
+ ? `const ${iconInfo.exportName} = ${iconInfo.expression};\n`
+ : '';
+ const iconsExpression = moduleOptions.iconsExpression ?? iconInfo?.exportName;
const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';
const indicatorsField = moduleOptions.indicatorsExpression
? `\n indicators: ${moduleOptions.indicatorsExpression},`
: '';
const iconReExport =
- iconInfo && exportIcons
- ? `\nexport { ${iconBinding}${iconBinding === iconInfo.exportName ? '' : ` as ${iconInfo.exportName}`} };\n`
- : '';
+ iconInfo && exportIcons ? `\nexport { ${iconInfo.exportName} };\n` : '';
// Resolve token values — tuples become light-dark() strings
/** @type {Record<string, unknown>} */
@@ -1871,7 +1898,7 @@ function generateBuiltModule(
serializeField('__adaptations', themeDef.__adaptations) +
serializeField('__axes', themeDef.__axes ?? {}, true);
- return `${iconImport}/**
+ return `${iconImport}${iconDeclaration}/**
* ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
* Import the CSS file alongside this module:
*
@@ -1890,7 +1917,7 @@ ${iconReExport}`;
/**
* Generate TypeScript declarations for a built theme module.
* @param {any} themeDef
- * @param {{exportName: string, importPath: string} | null} iconInfo
+ * @param {{exportName: string} | null} iconInfo - The re-exported registry, if any.
* @param {string | null} variantsFileName
* @param {{themeBinding?: string, includeIconExport?: boolean, includeThemeImport?: boolean}} [typeOptions]
* @returns {string}
@@ -2316,7 +2343,7 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
* `out` overrides the output CSS path; `check` compares against on-disk outputs
* instead of writing. `iconsSpecifier` overrides the icon registry import
* specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
- * specifier scraped from the theme source is emitted unchanged.
+ * direct registry specifiers from the theme source are emitted unchanged.
* @param {{cwd?: string}} [ctx]
* @returns {Promise<any>}
*/
@@ -2351,6 +2378,8 @@ async function themeBuildInternal(
// Extract theme definition
let themeDef;
+ /** The export actually selected by the loader, not the first AST match. */
+ let themeExportName;
/** Paths through the load that interception could not fully observe. */
let loadDegradation;
try {
@@ -2360,6 +2389,7 @@ async function themeBuildInternal(
options.__familyLoader,
);
themeDef = loaded.theme;
+ themeExportName = loaded.exportName;
loadDegradation = loaded.degraded;
} catch (e) {
const err = /** @type {Error} */ (e);
@@ -2425,6 +2455,25 @@ async function themeBuildInternal(
throw err;
}
+ // A generated module must preserve the registry through an import: it may
+ // contain React elements, which cannot be serialized. Validate before CSS
+ // generation so neither the no-CSS return nor --check can bypass the error.
+ // Family preparation keeps its own named-import registry contract, which
+ // themeBuildFamily checks against the selected members' graph.
+ const standaloneIcons = !options.__prepareFamily;
+ const iconResolution = {
+ readSource: (/** @type {string} */ file) => fs.readFileSync(file, 'utf8'),
+ resolveModule: resolveThemeModule,
+ reservedNames: [`${toIdentifier(themeDef.name)}Theme`],
+ rawInput: 'extends' in themeDef,
+ hasIcons:
+ Object.keys(themeDef.icons ?? {}).length > 0 ||
+ Object.keys(themeDef.extends?.icons ?? {}).length > 0,
+ };
+ let iconInfo = standaloneIcons
+ ? await resolveIconImports(filePath, themeExportName, iconResolution)
+ : null;
+
// Validate component overrides
const warnings = await validateComponentOverrides(themeDef);
const warningMessages = [];
@@ -2531,6 +2580,40 @@ async function themeBuildInternal(
resolvedTheme = themeDef;
}
+ // Raw object exports can acquire icons only when Core resolves `extends`.
+ // Recheck an unresolved provenance result before any generator runs.
+ if (
+ standaloneIcons &&
+ !iconInfo &&
+ Object.keys(resolvedTheme.icons ?? {}).length > 0
+ ) {
+ iconInfo = await resolveIconImports(filePath, themeExportName, {
+ ...iconResolution,
+ hasIcons: true,
+ });
+ }
+ // An opaque package base can legitimately have no icons. Its .icons
+ // reference is unnecessary; direct empty registry imports remain intact.
+ if (
+ iconInfo &&
+ iconInfo.iconsSpecifierLocalName === undefined &&
+ Object.keys(resolvedTheme.icons ?? {}).length === 0
+ ) {
+ iconInfo = null;
+ }
+ if (
+ iconInfo &&
+ options.iconsSpecifier !== undefined &&
+ iconInfo.iconsSpecifierImportPath === undefined
+ ) {
+ throw new AstryxError(
+ 'The icon registry is inherited through a theme import. ' +
+ 'To use --icons-specifier, import the registry directly and set icons to that binding.',
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+ }
+
// Cores that predate adaptations can still resolve typography, color,
// radius, and motion into root tokens, but they do not retain the raw axis
// inputs. Keep the effective metadata captured from the same defineTheme
@@ -2756,15 +2839,6 @@ async function themeBuildInternal(
const jsPath = path.join(outDir, `${baseName}.js`);
const dtsPath = path.join(outDir, `${baseName}.d.ts`);
- const iconInfo = extractRegistryInfo(
- filePath,
- 'icons',
- options.__prepareFamily,
- );
- const indicatorInfo = options.__prepareFamily
- ? extractRegistryInfo(filePath, 'indicators', true)
- : null;
-
// Type augmentation .d.ts if theme has custom prop values. Computed
// before the main .d.ts so the latter can reference it (see below).
const augmentationSource = resolvedTheme || themeDef;
@@ -2812,8 +2886,8 @@ async function themeBuildInternal(
theme: displayTheme,
sourceTheme: themeDef,
sourceParent,
- iconInfo,
- indicatorInfo,
+ iconInfo: extractRegistryInfo(filePath, 'icons'),
+ indicatorInfo: extractRegistryInfo(filePath, 'indicators'),
variantDecl,
css: cssPlan,
versions,
@@ -3157,11 +3231,14 @@ export async function themeBuildFamily(
const indicatorImport = indicator.info
? `import { ${indicator.info.exportName} as ${ownIndicators} } from ${JSON.stringify(indicator.specifier ?? indicator.info.importPath)};\n`
: '';
+ // The member's own registry import, bound to its family-unique name; a
+ // rebased or overridden specifier replaces the scraped one.
+ // prettier-ignore
+ const iconImports = icon.info && ownIcons ? {imports: [{importPath: icon.info.importPath, importedName: icon.info.exportName, localName: ownIcons}], expression: ownIcons, exportName: ownIcons, iconsSpecifierImportPath: icon.info.importPath, iconsSpecifierLocalName: ownIcons} : null;
return (
indicatorImport +
- generateBuiltModule(member.theme, icon.info, icon.specifier, {
+ generateBuiltModule(member.theme, iconImports, icon.specifier, {
themeBinding,
- iconBinding: ownIcons ?? undefined,
iconsExpression: expression(ownIcons, inheritedIcons),
indicatorsExpression: expression(ownIndicators, inheritedIndicators),
artifactBaseName: baseName,
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
index ee05717cd3..2e5a5c3187 100644
--- a/packages/cli/api/theme/build/build.test.mjs
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -8,7 +8,8 @@
* end-to-end; these assert the API contract you get calling `themeBuild()` in
* code: the typed `theme.build` receipt (with files actually written to disk),
* that it honors the `cwd` option, stays SILENT under the default noopLogger,
- * and returns `null` when there is nothing to build.
+ * returns `null` when there is nothing to build, and rejects unsupported icon
+ * registries without creating or changing outputs in build and check modes.
*
* `themeBuild` compiles via @astryxdesign/core's generator, so it needs a built
* core — the `node` project's globalSetup (vitest.global-setup.node.mjs) builds
@@ -611,6 +612,194 @@ describe('themeBuild() — the shipped theme template', () => {
});
});
+describe('themeBuild() — icon registry detection', () => {
+ /**
+ * The emitted icon import statement, or null. Reads the statement rather
+ * than the whole file: the `@generated` header quotes a usage example, so a
+ * substring search over the file would match comment text too.
+ */
+ function iconImportLine(generated) {
+ const match = generated.match(/^import .*$/m);
+ return match ? match[0] : null;
+ }
+
+ it('emits the import, icons key and re-export for a registry that arrives via an import', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'icons.mjs'),
+ 'export const liveIcons = {};\n',
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'live.mjs'),
+ `import {liveIcons} from './icons';\n` +
+ `export default {name: 'live', icons: liveIcons, tokens: {'--color-bg': '#fff'}};\n`,
+ );
+
+ const result = await themeBuild('live.mjs', {}, {cwd: tmpDir});
+
+ const generated = fs.readFileSync(path.join(tmpDir, 'live.js'), 'utf8');
+ expect(iconImportLine(generated)).toBe(
+ "import { liveIcons } from './icons';",
+ );
+ expect(generated).toContain('icons: liveIcons,');
+ expect(generated).toContain('export { liveIcons };');
+ expect(result?.data.warnings).toEqual([]);
+ });
+
+ it('does not re-emit an import that only appears inside a comment (#5058)', async () => {
+ // The reported repro: the registry was inlined into the theme source, and
+ // a doc comment kept the old import line for context. The comment's
+ // specifier was scraped and emitted as live code in the built module,
+ // pointing at a file that no longer exists.
+ fs.writeFileSync(
+ path.join(tmpDir, 'commented.mjs'),
+ `/**\n` +
+ ` * The scaffold put this in a sibling icons file, so the built module\n` +
+ ` * carried \`import { ghostIcons } from './icons'\` — which Node\n` +
+ ` * cannot resolve.\n` +
+ ` */\n` +
+ `const ghostIcons = {close: 'inline'};\n` +
+ `export default {name: 'commented', icons: ghostIcons, tokens: {'--color-bg': '#fff'}};\n`,
+ );
+
+ await expect(
+ themeBuild('commented.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({
+ code: 'ERR_THEME_INVALID',
+ message: expect.stringContaining('icons: ghostIcons'),
+ });
+ expect(fs.readdirSync(tmpDir)).toEqual(['commented.mjs']);
+ });
+
+ it('scrapes the live import even when a comment quotes a stale one', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'icons.mjs'),
+ 'export const realIcons = {};\n',
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'both.mjs'),
+ `// was: import { realIcons } from './old-icons';\n` +
+ `import {realIcons} from './icons';\n` +
+ `export default {name: 'both', icons: realIcons, tokens: {'--color-bg': '#fff'}};\n`,
+ );
+
+ const result = await themeBuild('both.mjs', {}, {cwd: tmpDir});
+
+ // The comment comes first in the source, so the old scan matched it first
+ // and emitted `./old-icons` — the live import must win.
+ const generated = fs.readFileSync(path.join(tmpDir, 'both.js'), 'utf8');
+ expect(iconImportLine(generated)).toBe(
+ "import { realIcons } from './icons';",
+ );
+ expect(generated).not.toContain('old-icons');
+ expect(result?.data.warnings).toEqual([]);
+ });
+
+ it('ignores a commented-out icons: field entirely', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'nofield.mjs'),
+ `// icons: retiredIcons,\n` +
+ `export default {name: 'nofield', tokens: {'--color-bg': '#fff'}};\n`,
+ );
+
+ const result = await themeBuild('nofield.mjs', {}, {cwd: tmpDir});
+
+ const generated = fs.readFileSync(path.join(tmpDir, 'nofield.js'), 'utf8');
+ expect(iconImportLine(generated)).toBeNull();
+ expect(generated).not.toContain('icons:');
+ // No icons field means nothing was dropped — no warning either.
+ expect(result?.data.warnings).toEqual([]);
+ });
+
+ describe.each([false, true])('unsupported registries (check: %s)', check => {
+ it('rejects before the generator can return no CSS', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'inline.mjs'),
+ `const inlineIcons = {chevron: 'stub'};\n` +
+ `export default {name: 'inline', icons: inlineIcons, tokens: {}};\n`,
+ );
+
+ await mockGenerateThemeRulesSplit.withImplementation(
+ () => ({component: [], prose: []}),
+ async () => {
+ await mockGenerateOnMediaCSS.withImplementation(
+ () => '',
+ async () => {
+ await expect(
+ themeBuild('inline.mjs', {check}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: 'ERR_THEME_INVALID'});
+ },
+ );
+ },
+ );
+ expect(mockGenerateThemeRulesSplit).not.toHaveBeenCalled();
+ expect(fs.readdirSync(tmpDir)).toEqual(['inline.mjs']);
+ });
+
+ it.each([
+ ['local binding', 'icons: inlineIcons'],
+ ['object literal', "icons: {chevron: 'stub'}"],
+ ['shorthand', 'icons'],
+ ])('rejects a %s without creating output files', async (_label, field) => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'inline.mjs'),
+ `const inlineIcons = {chevron: 'stub'};\n` +
+ `const icons = inlineIcons;\n` +
+ `export default {name: 'inline', ${field}, tokens: {'--color-bg': '#fff'}};\n`,
+ );
+
+ await expect(
+ themeBuild(
+ 'inline.mjs',
+ {check, out: 'dist/inline.css'},
+ {cwd: tmpDir},
+ ),
+ ).rejects.toMatchObject({
+ code: 'ERR_THEME_INVALID',
+ message: expect.stringContaining(
+ 'Move the registry to its own module and import it',
+ ),
+ });
+ expect(fs.readdirSync(tmpDir)).toEqual(['inline.mjs']);
+ });
+
+ it('rejects even when committed output already matches the missing-icons result', async () => {
+ const themeFile = path.join(tmpDir, 'inline.mjs');
+ const withoutIcons =
+ `export default {name: 'inline', tokens: {'--color-bg': '#fff'}, ` +
+ `components: {button: {'variant:custom': {color: 'red'}}}};\n`;
+ fs.writeFileSync(themeFile, withoutIcons);
+ const built = await themeBuild('inline.mjs', {}, {cwd: tmpDir});
+ expect(built?.data.outputs.variantsDts).toBe('inline.variants.d.ts');
+ const outputs = Object.values(built.data.outputs);
+ const before = outputs.map(file =>
+ fs.readFileSync(path.join(tmpDir, file), 'utf8'),
+ );
+ // This source used to emit exactly the same output as the icon-free
+ // theme, so --check passed after the incomplete artifacts were committed.
+ fs.writeFileSync(
+ themeFile,
+ `const inlineIcons = {chevron: 'stub'};\n` +
+ withoutIcons.replace(
+ "name: 'inline',",
+ "name: 'inline', icons: inlineIcons,",
+ ),
+ );
+ const filesBefore = fs.readdirSync(tmpDir).sort();
+
+ await expect(
+ themeBuild('inline.mjs', {check}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({
+ code: 'ERR_THEME_INVALID',
+ message: expect.stringContaining('icons: inlineIcons'),
+ });
+ expect(
+ outputs.map(file => fs.readFileSync(path.join(tmpDir, file), 'utf8')),
+ ).toEqual(before);
+ expect(fs.readdirSync(tmpDir).sort()).toEqual(filesBefore);
+ });
+ });
+});
+
describe('themeBuild() — extends', () => {
// These fixtures `import {defineTheme} from '@astryxdesign/core/theme'` the
// way a real theme file does, so they have to sit somewhere that specifier
diff --git a/packages/cli/api/theme/build/icon-imports.mjs b/packages/cli/api/theme/build/icon-imports.mjs
new file mode 100644
index 0000000000..6d641d1553
--- /dev/null
+++ b/packages/cli/api/theme/build/icon-imports.mjs
@@ -0,0 +1,691 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Resolve importable icon registries for the selected theme export.
+ *
+ * @input Loaded theme export identity, plus the caller's source reader and the
+ * theme loader's resolver (this module performs no environment access).
+ * @output Import bindings and an expression preserving inherited icon registries.
+ * @position Private theme-build packaging helper; never evaluates authored source.
+ */
+
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {AstryxError} from '../../error.mjs';
+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
+
+/**
+ * @typedef {object} IconImports
+ * @property {{importPath: string, importedName: string, localName: string}[]} imports
+ * @property {string} expression
+ * @property {string} exportName
+ * @property {string} [iconsSpecifierImportPath]
+ * @property {string} [iconsSpecifierLocalName]
+ */
+
+/** @typedef {{kind: 'reference', module: any, binding: any, members: string[]}} RegistryReference */
+/** @typedef {{kind: 'registry', ref: RegistryReference, preferredName: string, override?: boolean} | {kind: 'merge', base: RegistryPlan, own: RegistryPlan}} RegistryPlan */
+
+/** @param {any} node */
+function unwrap(node) {
+ while (
+ node &&
+ [
+ 'TSAsExpression',
+ 'TSSatisfiesExpression',
+ 'TSNonNullExpression',
+ 'TSTypeAssertion',
+ 'TypeCastExpression',
+ 'ParenthesizedExpression',
+ ].includes(node.type)
+ ) {
+ node = node.expression;
+ }
+ return node;
+}
+
+/** @param {any} node */
+function propertyName(node) {
+ if (!node) return null;
+ if (node.type === 'Identifier') return node.name;
+ if (typeof node.value === 'string') return node.value;
+ return null;
+}
+
+/** @param {any} node */
+function rootIdentifier(node) {
+ node = unwrap(node);
+ while (
+ node?.type === 'MemberExpression' ||
+ node?.type === 'OptionalMemberExpression'
+ ) {
+ node = unwrap(node.object);
+ }
+ return node?.type === 'Identifier' ? node.name : null;
+}
+
+/** @param {any} pattern @returns {string[]} */
+function bindingNames(pattern) {
+ if (!pattern) return [];
+ if (pattern.type === 'Identifier') return [pattern.name];
+ if (pattern.type === 'AssignmentPattern') return bindingNames(pattern.left);
+ if (pattern.type === 'RestElement') return bindingNames(pattern.argument);
+ if (pattern.type === 'ObjectPattern')
+ return pattern.properties.flatMap((/** @type {any} */ item) =>
+ bindingNames(item.type === 'RestElement' ? item.argument : item.value),
+ );
+ if (pattern.type === 'ArrayPattern')
+ return pattern.elements.flatMap(bindingNames);
+ return [];
+}
+
+/** @param {string} [name] @param {string} [reason] @returns {never} */
+function invalidRegistry(name, reason = '') {
+ const registry = name ? `\`icons: ${name}\`` : 'an icon registry';
+ throw new AstryxError(
+ `Theme sets ${registry} but no import for the registry was found. ` +
+ 'The generated module cannot preserve inline registries because they ' +
+ 'may contain React elements, which cannot be serialized. ' +
+ (reason ? `${reason} ` : '') +
+ 'Move the registry to its own module and import it into the theme file.',
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+}
+
+/**
+ * Parse only real module declarations and follow the export chosen by the loader.
+ * Local base themes are traced to their registry imports. Package bases remain
+ * public theme imports, so their implementation and private files stay private.
+ *
+ * @param {string} filePath
+ * @param {string | undefined} exportName
+ * @param {{hasIcons: boolean, readSource: (filename: string) => string, resolveModule: (specifier: string, fromFile: string) => string | Promise<string>, reservedNames?: string[], rawInput?: boolean}} options
+ * @returns {Promise<IconImports | null>}
+ */
+export async function resolveIconImports(
+ filePath,
+ exportName,
+ {hasIcons, readSource, resolveModule, reservedNames = [], rawInput = false},
+) {
+ if (exportName === undefined) {
+ if (!hasIcons) return null;
+ invalidRegistry(
+ undefined,
+ 'The selected theme export could not be identified.',
+ );
+ }
+
+ const jscodeshift = (await import('jscodeshift')).default;
+ const entryDirectory = path.dirname(filePath);
+ /** @type {Map<string, any>} */
+ const modules = new Map();
+ const active = new Set();
+ let inspectedRegistry = false;
+
+ /** @param {string} key @param {() => Promise<any>} visit */
+ async function guarded(key, visit) {
+ if (active.has(key))
+ invalidRegistry(undefined, 'The icon reference contains a cycle.');
+ active.add(key);
+ try {
+ return await visit();
+ } finally {
+ active.delete(key);
+ }
+ }
+
+ /** @param {any} module @param {any} node @param {Set<string>} [seen] */
+ function isDefineTheme(module, node, seen = new Set()) {
+ node = unwrap(node);
+ if (node?.type === 'Identifier') {
+ if (seen.has(node.name)) return false;
+ seen.add(node.name);
+ const binding = module.bindings.get(node.name);
+ if (binding?.kind === 'const')
+ return isDefineTheme(module, binding.node, seen);
+ return (
+ binding?.kind === 'import' &&
+ ['@astryxdesign/core', '@astryxdesign/core/theme'].includes(
+ binding.source,
+ ) &&
+ binding.importedName === 'defineTheme'
+ );
+ }
+ if (
+ node?.type === 'MemberExpression' &&
+ !node.computed &&
+ node.property.name === 'defineTheme'
+ ) {
+ const binding = module.bindings.get(node.object?.name);
+ return (
+ binding?.kind === 'import' &&
+ binding.importedName === '*' &&
+ ['@astryxdesign/core', '@astryxdesign/core/theme'].includes(
+ binding.source,
+ )
+ );
+ }
+ return false;
+ }
+
+ /** @param {string} filename */
+ function readModule(filename) {
+ if (modules.has(filename)) return modules.get(filename);
+ const parser = /\.[cm]?ts$/u.test(filename) ? 'ts' : 'tsx';
+ const j = jscodeshift.withParser(parser);
+ let root;
+ try {
+ root = j(readSource(filename));
+ } catch {
+ invalidRegistry(
+ undefined,
+ 'The selected theme module could not be parsed.',
+ );
+ }
+ const first = root.nodes()[0];
+ const statements = (first.program ?? first).body;
+ /** @type {{filename: string, bindings: Map<string, any>, exports: Map<string, any>, stars: string[], mutated: Set<string>, aliases: Map<string, string>}} */
+ const module = {
+ filename,
+ bindings: new Map(),
+ exports: new Map(),
+ stars: [],
+ mutated: new Set(),
+ aliases: new Map(),
+ };
+ modules.set(filename, module);
+
+ for (const statement of statements) {
+ if (
+ statement.type === 'ImportDeclaration' &&
+ statement.importKind !== 'type'
+ ) {
+ for (const specifier of statement.specifiers ?? []) {
+ if (specifier.importKind === 'type') continue;
+ module.bindings.set(specifier.local.name, {
+ kind: 'import',
+ source: statement.source.value,
+ importedName:
+ specifier.type === 'ImportDefaultSpecifier'
+ ? 'default'
+ : specifier.type === 'ImportNamespaceSpecifier'
+ ? '*'
+ : propertyName(specifier.imported),
+ localName: specifier.local.name,
+ });
+ }
+ }
+ const declaration =
+ statement.type === 'ExportNamedDeclaration'
+ ? statement.declaration
+ : statement;
+ if (declaration?.type === 'VariableDeclaration') {
+ for (const item of declaration.declarations) {
+ const original = rootIdentifier(item.init);
+ if (original) {
+ for (const name of bindingNames(item.id))
+ module.aliases.set(name, original);
+ }
+ if (item.id.type !== 'Identifier') continue;
+ module.bindings.set(item.id.name, {
+ kind: declaration.kind === 'const' ? 'const' : 'unsupported',
+ node: item.init,
+ });
+ if (statement.type === 'ExportNamedDeclaration') {
+ module.exports.set(item.id.name, {node: item.id});
+ }
+ }
+ }
+ if (statement.type === 'ExportDefaultDeclaration') {
+ module.exports.set('default', {node: statement.declaration});
+ }
+ if (
+ statement.type === 'ExportNamedDeclaration' &&
+ statement.exportKind !== 'type'
+ ) {
+ for (const specifier of statement.specifiers ?? []) {
+ if (specifier.exportKind === 'type') continue;
+ const exportedName = propertyName(specifier.exported);
+ module.exports.set(
+ exportedName,
+ statement.source
+ ? {
+ binding: {
+ kind: 'import',
+ source: statement.source.value,
+ importedName:
+ specifier.type === 'ExportNamespaceSpecifier'
+ ? '*'
+ : propertyName(specifier.local),
+ localName: propertyName(specifier.local) ?? exportedName,
+ },
+ }
+ : {node: specifier.local},
+ );
+ }
+ }
+ if (
+ statement.type === 'ExportAllDeclaration' &&
+ statement.exportKind !== 'type'
+ ) {
+ module.stars.push(statement.source.value);
+ }
+ }
+
+ /** @param {any} node @param {any} nodePath */
+ const markMutation = (node, nodePath) => {
+ const name = rootIdentifier(node);
+ if (name && nodePath.scope.lookup(name)?.path.node.type === 'Program')
+ module.mutated.add(name);
+ };
+ root
+ .find(j.AssignmentExpression)
+ .forEach((/** @type {any} */ p) => markMutation(p.node.left, p));
+ root
+ .find(j.UpdateExpression)
+ .forEach((/** @type {any} */ p) => markMutation(p.node.argument, p));
+ root
+ .find(j.UnaryExpression, {operator: 'delete'})
+ .forEach((/** @type {any} */ p) => markMutation(p.node.argument, p));
+ root.find(j.CallExpression).forEach((/** @type {any} */ p) => {
+ if (isDefineTheme(module, p.node.callee)) return;
+ if (p.node.callee.type === 'MemberExpression')
+ markMutation(p.node.callee.object, p);
+ for (const argument of p.node.arguments) markMutation(argument, p);
+ });
+ // Mutating an alias also mutates the object that supplied its value.
+ for (const name of module.mutated) {
+ const original = module.aliases.get(name);
+ if (original) module.mutated.add(original);
+ }
+ return module;
+ }
+
+ /** @param {any} module @param {string} name */
+ function checkedBinding(module, name) {
+ if (module.mutated.has(name))
+ invalidRegistry(
+ name,
+ 'The referenced binding is mutated or passed to unsupported code.',
+ );
+ const binding = module.bindings.get(name);
+ if (!binding || binding.kind === 'unsupported') invalidRegistry(name);
+ return binding;
+ }
+
+ /** @param {any} module @param {any} binding @param {string[]} [members] @returns {RegistryReference} */
+ function importedReference(module, binding, members = []) {
+ return {kind: 'reference', module, binding, members};
+ }
+
+ /** @param {any} module @param {any} node @returns {Promise<RegistryReference | null>} */
+ async function reference(module, node) {
+ node = unwrap(node);
+ if (node?.type === 'Identifier') {
+ return guarded(`${module.filename}:reference:${node.name}`, async () => {
+ const binding = checkedBinding(module, node.name);
+ if (binding.kind === 'import')
+ return importedReference(module, binding);
+ return reference(module, binding.node);
+ });
+ }
+ if (node?.type === 'MemberExpression' && !node.optional) {
+ const name = node.computed
+ ? typeof node.property.value === 'string'
+ ? node.property.value
+ : null
+ : propertyName(node.property);
+ if (name === null) invalidRegistry();
+ const object = await reference(module, node.object);
+ if (!object) return null;
+ return {...object, members: [...object.members, name]};
+ }
+ return null;
+ }
+
+ /** @param {RegistryReference} ref */
+ async function importedExport(ref) {
+ if (!ref.binding.source.startsWith('.')) return null;
+ let filename;
+ try {
+ filename = await resolveModule(ref.binding.source, ref.module.filename);
+ if (filename.startsWith('file:')) filename = fileURLToPath(filename);
+ } catch {
+ invalidRegistry(
+ ref.binding.localName,
+ 'The inherited theme module could not be resolved.',
+ );
+ }
+ let name = ref.binding.importedName;
+ const members = [...ref.members];
+ if (name === '*') name = members.shift();
+ if (!name || members.length > 0)
+ invalidRegistry(
+ ref.binding.localName,
+ 'The inherited theme must name a module export.',
+ );
+ return {module: readModule(filename), name};
+ }
+
+ /** @param {any} module @param {string} name */
+ async function selectedExport(module, name) {
+ const selected = module.exports.get(name);
+ if (selected) return selected;
+ // Follow explicit local barrels without choosing another arbitrary theme.
+ for (const source of module.stars) {
+ if (name === 'default') continue;
+ const binding = {source, importedName: name, localName: name};
+ const target = await importedExport(importedReference(module, binding));
+ if (
+ target &&
+ (target.module.exports.has(name) || target.module.stars.length > 0)
+ )
+ return {binding};
+ }
+ invalidRegistry(
+ undefined,
+ `The selected export "${name}" has no statically resolved declaration.`,
+ );
+ }
+
+ /** @param {RegistryReference} ref @returns {RegistryPlan} */
+ function packageTheme(ref) {
+ return {
+ kind: 'registry',
+ ref: {...ref, members: [...ref.members, 'icons']},
+ preferredName: 'themeIcons',
+ };
+ }
+
+ /** @param {any} module @param {string} name @param {boolean} [rejectOpaque] @returns {Promise<RegistryPlan | null>} */
+ async function exportedTheme(module, name, rejectOpaque = false) {
+ return guarded(`${module.filename}:theme-export:${name}`, async () => {
+ const selected = await selectedExport(module, name);
+ return selected.binding
+ ? themeReference(
+ importedReference(module, selected.binding),
+ rejectOpaque,
+ )
+ : theme(module, selected.node, rejectOpaque);
+ });
+ }
+
+ /** @param {RegistryReference} ref @param {boolean} [rejectOpaque] @returns {Promise<RegistryPlan | null>} */
+ async function themeReference(ref, rejectOpaque = false) {
+ const target = await importedExport(ref);
+ if (target) return exportedTheme(target.module, target.name, rejectOpaque);
+ if (rejectOpaque)
+ invalidRegistry(
+ ref.binding.localName,
+ 'A raw package configuration cannot supply a resolved theme registry.',
+ );
+ return packageTheme(ref);
+ }
+
+ /** @param {any} module @param {any} node @param {string} [preferredName] @returns {Promise<RegistryPlan | null>} */
+ async function registry(module, node, preferredName) {
+ inspectedRegistry = true;
+ node = unwrap(node);
+ if (
+ node?.type === 'NullLiteral' ||
+ (node?.type === 'Literal' && node.value === null) ||
+ (node?.type === 'UnaryExpression' && node.operator === 'void')
+ )
+ return null;
+ if (node?.type === 'Identifier') {
+ if (node.name === 'undefined' && !module.bindings.has(node.name))
+ return null;
+ return guarded(`${module.filename}:registry:${node.name}`, async () => {
+ const binding = checkedBinding(module, node.name);
+ if (binding.kind === 'const')
+ return registry(module, binding.node, preferredName ?? node.name);
+ return {
+ kind: 'registry',
+ ref: importedReference(module, binding),
+ preferredName: preferredName ?? node.name,
+ override: true,
+ };
+ });
+ }
+ if (node?.type === 'MemberExpression') {
+ const ref = await reference(module, node);
+ if (ref)
+ return {
+ kind: 'registry',
+ ref,
+ preferredName: preferredName ?? 'themeIcons',
+ // A namespace's exported registry can be redirected to an icon module;
+ // a named theme's .icons cannot be imported from that sidecar.
+ override:
+ ref.binding.importedName === '*' && ref.members.length === 1,
+ };
+ }
+ // Spreads merge in order. An object adding no entries, such as `{}`, is no
+ // local registry: a child keeps its inherited icons and a root emits none.
+ if (
+ node?.type === 'ObjectExpression' &&
+ node.properties.every((/** @type {any} */ item) =>
+ ['SpreadElement', 'SpreadProperty'].includes(item.type),
+ )
+ ) {
+ /** @type {RegistryPlan | null} */
+ let result = null;
+ for (const item of node.properties) {
+ const next = await registry(module, item.argument);
+ if (next)
+ result = result ? {kind: 'merge', base: result, own: next} : next;
+ }
+ return result;
+ }
+ invalidRegistry(preferredName ?? rootIdentifier(node) ?? undefined);
+ }
+
+ /** @param {any} module @param {any} node @returns {Promise<Map<string, any>>} */
+ async function fields(module, node) {
+ node = unwrap(node);
+ if (node?.type === 'Identifier') {
+ return guarded(`${module.filename}:fields:${node.name}`, async () => {
+ const binding = checkedBinding(module, node.name);
+ if (binding.kind === 'const') return fields(module, binding.node);
+ return referenceFields(importedReference(module, binding));
+ });
+ }
+ if (node?.type === 'MemberExpression') {
+ const ref = await reference(module, node);
+ if (ref) return referenceFields(ref);
+ }
+ if (node?.type === 'CallExpression' && isDefineTheme(module, node.callee)) {
+ return new Map([['icons', {plan: await theme(module, node)}]]);
+ }
+ if (node?.type !== 'ObjectExpression') invalidRegistry();
+ const result = new Map();
+ for (const item of node.properties) {
+ if (item.type === 'SpreadElement' || item.type === 'SpreadProperty') {
+ for (const [key, value] of await fields(module, item.argument))
+ result.set(key, value);
+ continue;
+ }
+ const key = item.computed
+ ? typeof item.key?.value === 'string'
+ ? item.key.value
+ : null
+ : propertyName(item.key);
+ if (key === null)
+ invalidRegistry(undefined, 'Computed theme keys cannot be resolved.');
+ if (!['icons', 'extends'].includes(key)) continue;
+ if (
+ !['ObjectProperty', 'Property'].includes(item.type) ||
+ item.method ||
+ (item.kind && item.kind !== 'init')
+ )
+ invalidRegistry();
+ result.set(key, {module, node: item.value});
+ }
+ return result;
+ }
+
+ /** @param {RegistryReference} ref @returns {Promise<Map<string, any>>} */
+ async function referenceFields(ref) {
+ const target = await importedExport(ref);
+ if (!target)
+ invalidRegistry(
+ ref.binding.localName,
+ 'A package configuration cannot be inspected for inherited registries.',
+ );
+ return guarded(
+ `${target.module.filename}:fields-export:${target.name}`,
+ async () => {
+ const selected = await selectedExport(target.module, target.name);
+ return selected.binding
+ ? referenceFields(importedReference(target.module, selected.binding))
+ : fields(target.module, selected.node);
+ },
+ );
+ }
+
+ /** @param {any} module @param {any} node @param {boolean} [rejectOpaque] @returns {Promise<RegistryPlan | null>} */
+ async function theme(module, node, rejectOpaque = false) {
+ node = unwrap(node);
+ if (node?.type === 'Identifier') {
+ return guarded(`${module.filename}:theme:${node.name}`, async () => {
+ const binding = checkedBinding(module, node.name);
+ return binding.kind === 'const'
+ ? theme(module, binding.node, rejectOpaque)
+ : themeReference(importedReference(module, binding), rejectOpaque);
+ });
+ }
+ if (node?.type === 'MemberExpression') {
+ const ref = await reference(module, node);
+ if (ref) return themeReference(ref, rejectOpaque);
+ }
+ if (node?.type === 'CallExpression') {
+ if (!isDefineTheme(module, node.callee) || node.arguments.length !== 1)
+ invalidRegistry();
+ node = unwrap(node.arguments[0]);
+ }
+ const config = await fields(module, node);
+ const baseField = config.get('extends');
+ const iconField = config.get('icons');
+ const base = baseField
+ ? await theme(baseField.module, baseField.node)
+ : null;
+ const own = iconField
+ ? 'plan' in iconField
+ ? iconField.plan
+ : await registry(iconField.module, iconField.node)
+ : null;
+ return base && own ? {kind: 'merge', base, own} : (own ?? base);
+ }
+
+ let plan;
+ try {
+ plan = await exportedTheme(readModule(filePath), exportName, rawInput);
+ } catch (error) {
+ // No registry needs packaging when the loaded theme has none. This also
+ // keeps arbitrary icon-free authoring helpers outside this static resolver.
+ if (!hasIcons && !inspectedRegistry && error instanceof AstryxError)
+ return null;
+ throw error;
+ }
+ if (!plan) {
+ if (hasIcons) invalidRegistry();
+ return null;
+ }
+
+ const used = new Set(reservedNames);
+ /** @type {IconImports['imports']} */
+ const imports = [];
+ const emitted = new Map();
+
+ /** @param {string} preferred */
+ function allocate(preferred) {
+ const stem =
+ /^[A-Za-z_$][\w$]*$/u.test(preferred) &&
+ !['default', 'await', 'yield'].includes(preferred)
+ ? preferred
+ : 'themeIcons';
+ let name = stem;
+ let counter = 1;
+ while (used.has(name)) name = `${stem}${counter++}`;
+ used.add(name);
+ return name;
+ }
+
+ /** @param {any} ref */
+ function importPath(ref) {
+ const source = ref.binding.source;
+ if (
+ !source.startsWith('.') ||
+ path.dirname(ref.module.filename) === entryDirectory
+ )
+ return source;
+ const relative = path
+ .relative(
+ entryDirectory,
+ path.resolve(path.dirname(ref.module.filename), source),
+ )
+ .split(path.sep)
+ .join('/');
+ return relative.startsWith('.') ? relative : `./${relative}`;
+ }
+
+ /** @param {RegistryPlan} value @returns {{expression: string, preferredName: string, overridePath?: string, overrideLocalName?: string}} */
+ function render(value) {
+ if (value.kind === 'merge') {
+ const base = render(value.base);
+ const own = render(value.own);
+ return {
+ expression: `{...${base.expression}, ...${own.expression}}`,
+ preferredName: 'themeIcons',
+ overridePath: own.overridePath,
+ overrideLocalName: own.overrideLocalName,
+ };
+ }
+ const {ref} = value;
+ const source = importPath(ref);
+ const identity = `${source}\0${ref.binding.importedName}\0${JSON.stringify(ref.members)}`;
+ let localName = emitted.get(identity);
+ if (!localName) {
+ localName = allocate(ref.binding.localName);
+ emitted.set(identity, localName);
+ imports.push({
+ importPath: source,
+ importedName: ref.binding.importedName,
+ localName,
+ });
+ }
+ const expression = ref.members.reduce(
+ (result, member) => `${result}[${JSON.stringify(member)}]`,
+ localName,
+ );
+ return {
+ expression,
+ preferredName:
+ ref.members.length === 0 &&
+ value.preferredName === ref.binding.localName
+ ? localName
+ : value.preferredName,
+ overridePath: value.override ? source : undefined,
+ overrideLocalName: value.override ? localName : undefined,
+ };
+ }
+
+ const rendered = render(plan);
+ const name =
+ rendered.preferredName === rendered.expression &&
+ imports.some(item => item.localName === rendered.expression)
+ ? rendered.expression
+ : allocate(rendered.preferredName);
+ return {
+ imports,
+ expression: rendered.expression,
+ exportName: name,
+ ...(rendered.overridePath
+ ? {
+ iconsSpecifierImportPath: rendered.overridePath,
+ iconsSpecifierLocalName: rendered.overrideLocalName,
+ }
+ : {}),
+ };
+}
diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjs
index 99966aadc7..d1b42e1d42 100644
--- a/packages/cli/api/theme/themeBuild.doc.mjs
+++ b/packages/cli/api/theme/themeBuild.doc.mjs
@@ -3,7 +3,10 @@
/**
* @file FunctionDoc for `themeBuild()` / `astryx theme build`. Colocated with
* the API function it documents; the response-shape source of truth stays in
- * `theme.type.mjs`.
+ * `theme.type.mjs`. Documents imported/inherited icons and atomic rejection
+ * of registries that cannot be preserved in build/check modes.
+ * @input themeBuild's build/check and icon-import behavior.
+ * @output Consumer API documentation for generated theme artifacts.
* @position packages/cli/api/theme — function documentation
*/
@@ -21,6 +24,14 @@ export const doc = {
'writes a scoped CSS file, a JS module that re-exports the built theme, and a .d.ts ' +
'(plus an optional .variants.d.ts when the theme adds custom prop values). It uses ' +
"@astryxdesign/core's own generator, so the CSS matches what the <Theme> runtime emits. " +
+ 'When another build step emits the icon registry, ' +
+ '{iconsSpecifier} declares the fully specified module path for the generated JS import. ' +
+ 'Real registry imports are preserved, including aliases, default imports, and namespace ' +
+ 'imports. Icons inherited through extends are retained, with child entries taking precedence. ' +
+ 'Comment and string contents do not affect import detection. ' +
+ 'An inline registry that cannot be preserved fails with ERR_THEME_INVALID before any ' +
+ 'output is written, including in check mode. Move the registry to its own module and ' +
+ 'import it into the theme file. ' +
'With {check: true} it writes nothing and instead compares ' +
'each output against disk, returning the drift: the CI guard for committed, generated theme CSS.',
importPath: '@astryxdesign/cli/api',
@@ -60,7 +71,7 @@ export const doc = {
name: 'options.iconsSpecifier',
type: 'string',
description:
- 'Override the import specifier of the icon registry in the generated JS module, for example ./icons.mjs. Takes effect only when the theme sets icons: to a named import; when omitted, the source specifier is kept.',
+ 'Override the selected icon-registry import specifier in the generated JS module, for example ./icons.mjs. With child and inherited registries, this changes the child registry import. When omitted, direct source specifiers are preserved; relative imports followed through a local base are rebased to the theme file. A registry inherited through a package theme must be imported directly to use this option.',
},
{
name: 'ctx.cwd',
@@ -90,7 +101,7 @@ export const doc = {
},
{
code: 'ERR_THEME_INVALID',
- when: 'the resolved theme is invalid, for example it has no name, or a custom Heading type has no standalone rule with a declaration the compiler can emit',
+ when: 'the resolved theme is invalid, for example it has no name, a custom Heading type has no standalone rule with a declaration the compiler can emit, or its icon registry cannot be preserved through an import (also rejected in check mode)',
},
{
code: 'ERR_PATH_TRAVERSAL',
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 15aae25e26..aec8084766 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -65,7 +65,7 @@ const RUNNERS = {
sites: [
'.evalModule() ×2',
'.import()',
- 'createJiti ×4',
+ 'createJiti ×5',
'eval ×2',
'import(<computed>) ×3',
],