Skip to content

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

TypeScript

fix(cli): add `theme build --icons-specifier` for the generated icon import (#4631)

Xinzi Zhoua2459e5fcdbc
diff --git a/.changeset/theme-build-icons-specifier.md b/.changeset/theme-build-icons-specifier.md
new file mode 100644
index 0000000000..11879618b3
--- /dev/null
+++ b/.changeset/theme-build-icons-specifier.md
@@ -0,0 +1,13 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] cli: add `theme build --icons-specifier` so the generated module's icon import can be fully specified (#4620)
+
+The generated theme module imports the icon registry rather than inlining it, because the registry holds React elements. `astryx theme build` scraped that specifier out of the TypeScript source and emitted it verbatim, so `./icons` — valid TypeScript, invalid ESM — reached the generated `.js`. Every published theme's `/built` entry therefore failed to load in Node, including under Vite SSR and Next.js Pages Router, while bundlers papered over it by guessing the extension.
+
+No single extension is correct: the same source compiled by tsup lands at `icons.mjs` in a package with no `"type"` field and at `icons.js` in one with `"type": "module"`, and the generator runs before the compile step that produces either. The caller knows; now it can say so. Without the flag the specifier is emitted unchanged, so the default no-`--out` flow — where the neighbour is an uncompiled `icons.tsx` that only a bundler can resolve — is unaffected.
+
+The seven theme packages now declare `--icons-specifier ./icons.mjs` in their build scripts.
+
+@imdreamrunner
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index d2c5ff25e4..8c4719b439 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -726,13 +726,30 @@ function extractIconInfo(filePath) {
* Generate a minimal JS module for a built theme.
* Includes the theme name, marker, and re-exports the icon registry.
* All styling is in the CSS file.
+ *
+ * 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
+ * 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.
+ *
* @param {any} themeDef
* @param {{exportName: string, importPath: string} | null} iconInfo
+ * @param {string} [iconsSpecifier] - Overrides the scraped icon import specifier.
* @returns {string}
*/
-function generateBuiltModule(themeDef, iconInfo) {
+function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
+ // 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} } from '${iconInfo.importPath}';\n`
+ ? `import { ${iconInfo.exportName} } from ${renderedSpecifier};\n`
: '';
const iconsField = iconInfo ? ` icons: ${iconInfo.exportName},` : '';
const iconReExport = iconInfo ? `\nexport { ${iconInfo.exportName} };\n` : '';
@@ -970,7 +987,11 @@ function validatePrivateVars(themeDef) {
* `logger` (silent by default).
*
* @param {string} file - Theme file path, resolved against `cwd`.
- * @param {{out?: string, check?: boolean}} [options] - `out` overrides the output CSS path; `check` compares against on-disk outputs instead of writing.
+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] -
+ * `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.
* @param {{cwd?: string}} [ctx]
* @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>}
*/
@@ -1185,7 +1206,11 @@ export async function themeBuild(
generatedHeader(sourceRelative, 'css', buildCommand, versions) + css;
const jsContent =
generatedHeader(sourceRelative, 'js', buildCommand, versions) +
- generateBuiltModule(resolvedTheme || themeDef, iconInfo);
+ generateBuiltModule(
+ resolvedTheme || themeDef,
+ iconInfo,
+ options.iconsSpecifier,
+ );
const dtsContent =
generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
generateBuiltTypes(themeDef, iconInfo, variantsFileName);
diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjs
index 542481abb8..e5adec2fe2 100644
--- a/packages/cli/api/theme/themeBuild.doc.mjs
+++ b/packages/cli/api/theme/themeBuild.doc.mjs
@@ -19,11 +19,13 @@ export const doc = {
"via @astryxdesign/core's shared generator (the single source of truth, so the build " +
'emits the exact CSS the <Theme> runtime does), 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). With {check: true} it writes nothing and instead compares ' +
+ 'theme adds custom prop values). When another build step emits the icon registry, ' +
+ '{iconsSpecifier} declares the fully specified module path for the generated JS import. ' +
+ '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',
signature:
- 'themeBuild(file: string, options?: {out?: string, check?: boolean}, ctx?: {cwd?: string}): Promise<ThemeBuildResponse | ThemeBuildCheckResponse | null>',
+ 'themeBuild(file: string, options?: {out?: string, check?: boolean, iconsSpecifier?: string}, ctx?: {cwd?: string}): Promise<ThemeBuildResponse | ThemeBuildCheckResponse | null>',
keywords: [
'theme',
'build',
@@ -54,6 +56,12 @@ export const doc = {
'Compile in memory and compare each output against what is on disk instead of writing: the CI drift guard.',
default: 'false',
},
+ {
+ name: 'options.iconsSpecifier',
+ type: 'string',
+ description:
+ 'Override the icon-registry import specifier in the generated JS module, for example ./icons.mjs. When omitted, the source specifier is preserved.',
+ },
{
name: 'ctx.cwd',
type: 'string',
@@ -102,6 +110,10 @@ export const doc = {
label: 'Check for drift (CI)',
code: "const r = await themeBuild('src/themes/ocean.ts', {check: true});",
},
+ {
+ label: 'Use a separately compiled icon registry',
+ code: "const r = await themeBuild('src/themes/ocean.ts', {iconsSpecifier: './icons.mjs'});",
+ },
],
command: 'theme build',
related: ['themeAdd', 'themeList', 'listThemes'],
diff --git a/packages/cli/clients/cli/commands/build-theme.icons-specifier.test.mjs b/packages/cli/clients/cli/commands/build-theme.icons-specifier.test.mjs
new file mode 100644
index 0000000000..c130d9dfc4
--- /dev/null
+++ b/packages/cli/clients/cli/commands/build-theme.icons-specifier.test.mjs
@@ -0,0 +1,225 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Regression tests for `astryx theme build --icons-specifier`.
+ *
+ * The generated module imports the icon registry rather than inlining it,
+ * because the registry holds React elements. `extractIconInfo` lifts that
+ * specifier out of the TypeScript source, where an extensionless `./icons` is
+ * resolved by the TypeScript resolver — but the artifact is ESM JavaScript,
+ * which requires a fully specified path, so Node cannot load it. See #4620.
+ *
+ * Only the caller knows what its own build emits and under what name (the same
+ * source compiled by tsup lands at `icons.mjs` in a package with no `"type"`
+ * field and at `icons.js` in one with `"type": "module"`), so the specifier is
+ * declared rather than inferred. Absent the flag, output is byte-for-byte what
+ * it was before, which keeps the default no-`--out` flow — where the neighbour
+ * is an uncompiled `icons.tsx` that only a bundler can resolve — working.
+ */
+
+import {describe, it, expect, beforeAll, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {ensureCoreBuilt} from './ensure-core-built.mjs';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+/**
+ * The emitted icon import, or null. Reads the statement rather than the whole
+ * file: the `@generated` header quotes the source filename and a usage example,
+ * so a substring search over the file matches comment text too.
+ */
+function iconImportLine(generated) {
+ const match = generated.match(/^import .*$/m);
+ return match ? match[0] : null;
+}
+
+/** A theme whose registry arrives via a relative import, plus that module. */
+function writeThemeWithIcons(dir, name) {
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'icons.mjs'),
+ 'export const testIcons = {};\n',
+ );
+ const file = path.join(dir, `${name}.mjs`);
+ fs.writeFileSync(
+ file,
+ `import {testIcons} from './icons';\n` +
+ `export default {\n` +
+ ` name: ${JSON.stringify(name)},\n` +
+ ` icons: testIcons,\n` +
+ ` tokens: {'--color-bg': '#fff'},\n` +
+ `};\n`,
+ );
+ return file;
+}
+
+beforeAll(() => {
+ ensureCoreBuilt();
+}, 200_000);
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icons-specifier-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('theme build --icons-specifier', () => {
+ it('emits the declared specifier', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeThemeWithIcons(project, 'declared');
+
+ const result = await runCli(
+ [
+ 'theme',
+ 'build',
+ path.relative(project, themeFile),
+ '--icons-specifier',
+ './icons.mjs',
+ ],
+ project,
+ );
+ expect(result.code).toBe(0);
+
+ const generated = fs.readFileSync(
+ path.join(project, 'declared.js'),
+ 'utf8',
+ );
+ expect(iconImportLine(generated)).toBe(
+ 'import { testIcons } from "./icons.mjs";',
+ );
+ });
+
+ it('accepts a specifier the generator could never have inferred', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeThemeWithIcons(project, 'custom');
+
+ const result = await runCli(
+ [
+ 'theme',
+ 'build',
+ path.relative(project, themeFile),
+ '--icons-specifier',
+ '../build/registry/icons.js',
+ ],
+ project,
+ );
+ expect(result.code).toBe(0);
+
+ const generated = fs.readFileSync(path.join(project, 'custom.js'), 'utf8');
+ expect(iconImportLine(generated)).toBe(
+ 'import { testIcons } from "../build/registry/icons.js";',
+ );
+ });
+
+ it('encodes the declared specifier as a valid JavaScript string', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeThemeWithIcons(project, 'encoded');
+
+ const result = await runCli(
+ [
+ 'theme',
+ 'build',
+ path.relative(project, themeFile),
+ '--icons-specifier',
+ "./icon's.mjs",
+ ],
+ project,
+ );
+ expect(result.code).toBe(0);
+
+ const generated = fs.readFileSync(path.join(project, 'encoded.js'), 'utf8');
+ expect(iconImportLine(generated)).toBe(
+ 'import { testIcons } from "./icon\'s.mjs";',
+ );
+ });
+
+ it('combines with the current --check flow', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeThemeWithIcons(project, 'checked');
+ const relativeTheme = path.relative(project, themeFile);
+
+ const built = await runCli(
+ [
+ 'theme',
+ 'build',
+ relativeTheme,
+ '--icons-specifier',
+ './icons.mjs',
+ ],
+ project,
+ );
+ expect(built.code).toBe(0);
+
+ const withoutSpecifier = await runCli(
+ ['theme', 'build', relativeTheme, '--check'],
+ project,
+ );
+ expect(withoutSpecifier.code).toBe(1);
+
+ const withSpecifier = await runCli(
+ [
+ 'theme',
+ 'build',
+ relativeTheme,
+ '--check',
+ '--icons-specifier',
+ './icons.mjs',
+ ],
+ project,
+ );
+ expect(withSpecifier.code).toBe(0);
+ });
+
+ it('leaves the scraped specifier untouched when the flag is absent', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themeFile = writeThemeWithIcons(project, 'untouched');
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+ expect(result.code).toBe(0);
+
+ // The pre-flag behaviour, preserved: no extension is invented. In this
+ // layout the neighbour is a source file only a bundler can resolve, so
+ // adding one would break a build that works today.
+ const generated = fs.readFileSync(
+ path.join(project, 'untouched.js'),
+ 'utf8',
+ );
+ expect(iconImportLine(generated)).toBe(
+ "import { testIcons } from './icons';",
+ );
+ });
+
+ it('is inert for a theme with no icons field', async () => {
+ const project = path.join(tmpDir, 'project');
+ fs.mkdirSync(project, {recursive: true});
+ const themeFile = path.join(project, 'plain.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {name: 'plain', tokens: {'--color-bg': '#fff'}};\n`,
+ );
+
+ const result = await runCli(
+ [
+ 'theme',
+ 'build',
+ path.relative(project, themeFile),
+ '--icons-specifier',
+ './icons.mjs',
+ ],
+ project,
+ );
+ expect(result.code).toBe(0);
+
+ // No icons field means no import to rewrite, so the flag has nothing to act
+ // on and must not introduce one.
+ const generated = fs.readFileSync(path.join(project, 'plain.js'), 'utf8');
+ expect(iconImportLine(generated)).toBeNull();
+ expect(generated).not.toContain('icons:');
+ });
+});
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index bfbb5a2fa1..6907a989f2 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -57,13 +57,15 @@ function resolveCliBin() {
* Resolves with the child's exit code; never rejects.
*
* @param {string} file - The theme file argument, as the user passed it.
- * @param {{out?: string}} options - Parsed command options (only `out` is forwarded).
+ * @param {{out?: string, iconsSpecifier?: string}} options - Parsed command
+ * options that affect generated output.
* @returns {Promise<number>}
*/
function runThemeBuildOnceChild(file, options) {
const cliBin = resolveCliBin();
const args = [cliBin, 'theme', 'build', file];
if (options.out) args.push('--out', options.out);
+ if (options.iconsSpecifier) args.push('--icons-specifier', options.iconsSpecifier);
return new Promise((/** @type {(code: number) => void} */ resolve) => {
const child = spawn(process.execPath, args, {
stdio: 'inherit',
@@ -83,7 +85,7 @@ function runThemeBuildOnceChild(file, options) {
*
* @param {string} file - The theme file argument, as the user passed it.
* @param {string} filePath - Absolute path to the theme file.
- * @param {{out?: string}} options - Parsed command options.
+ * @param {{out?: string, iconsSpecifier?: string}} options - Parsed command options.
* @returns {Promise<void>} Resolves when the watcher is stopped (Ctrl-C).
*/
async function runThemeBuildWatch(file, filePath, options) {
@@ -204,7 +206,7 @@ export function registerTheme(program) {
fn: themeBuildFn,
action: async (
/** @type {string} */ file,
- /** @type {{out?: string, watch?: boolean, check?: boolean}} */ options,
+ /** @type {{out?: string, watch?: boolean, check?: boolean, iconsSpecifier?: string}} */ options,
) => {
const filePath = path.resolve(process.cwd(), file);
const json = program.opts().json || false;
@@ -247,7 +249,11 @@ export function registerTheme(program) {
try {
const result = await themeBuild(
file,
- {out: options.out, check: options.check},
+ {
+ out: options.out,
+ check: options.check,
+ iconsSpecifier: options.iconsSpecifier,
+ },
{cwd: process.cwd()},
);
if (json && result) jsonOut(result);
diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjs
index aa3baceda2..52da736c4b 100644
--- a/packages/cli/clients/cli/commands/theme-build.doc.mjs
+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs
@@ -18,11 +18,19 @@ export const doc = {
description:
'Compiles a file that calls defineTheme() into a scoped CSS file, a JS module, and ' +
'type declarations: the exact CSS the <Theme> runtime emits. With --check it writes ' +
- 'nothing and instead reports whether the committed outputs have drifted from source.',
+ 'nothing and instead reports whether the committed outputs have drifted from source. ' +
+ 'When a separate build step emits the icon registry, --icons-specifier declares the ' +
+ 'fully specified module path that the generated JS should import.',
fn: 'themeBuild',
args: [{name: 'file', param: 'file', required: true}],
options: [
{flag: '-o, --out <path>', param: 'options.out', description: 'Output CSS file path'},
+ {
+ flag: '--icons-specifier <specifier>',
+ param: 'options.iconsSpecifier',
+ description:
+ 'Override the icon-registry import in the generated JS module (for example, ./icons.mjs)',
+ },
{
flag: '-w, --watch',
description: 'Rebuild automatically when the theme file changes (Ctrl-C to stop)',
@@ -43,6 +51,10 @@ export const doc = {
label: 'Check for drift (CI)',
cli: 'astryx theme build ./src/themes/ocean.ts --check',
},
+ {
+ label: 'Build against a separately compiled icon registry',
+ cli: 'astryx theme build ./src/themes/ocean.ts --icons-specifier ./icons.mjs',
+ },
],
exitCodes: [
{
diff --git a/packages/themes/butter/package.json b/packages/themes/butter/package.json
index fedfd5741c..ce043d1520 100644
--- a/packages/themes/butter/package.json
+++ b/packages/themes/butter/package.json
@@ -46,7 +46,7 @@
"src"
],
"scripts": {
- "build": "astryx theme build src/butterTheme.ts -o dist/theme.css && tsup && tsc --project tsconfig.build.json"
+ "build": "astryx theme build src/butterTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json"
},
"dependencies": {
"lucide-react": "^1.18.0"
diff --git a/packages/themes/chocolate/package.json b/packages/themes/chocolate/package.json
index 15c9433e0b..33daeaa796 100644
--- a/packages/themes/chocolate/package.json
+++ b/packages/themes/chocolate/package.json
@@ -46,7 +46,7 @@
"src"
],
"scripts": {
- "build": "astryx theme build src/chocolateTheme.ts -o dist/theme.css && tsup && tsc --project tsconfig.build.json"
+ "build": "astryx theme build src/chocolateTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json"
},
"dependencies": {
"lucide-react": "^1.18.0"
diff --git a/packages/themes/gothic/package.json b/packages/themes/gothic/package.json
index 0def70fe2c..d04f45223e 100644
--- a/packages/themes/gothic/package.json
+++ b/packages/themes/gothic/package.json
@@ -46,7 +46,7 @@
"src"
],
"scripts": {
- "build": "astryx theme build src/gothicTheme.ts -o dist/theme.css && tsup && tsc --project tsconfig.build.json"
+ "build": "astryx theme build src/gothicTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json"
},
"dependencies": {
"lucide-react": "^1.18.0"
diff --git a/packages/themes/matcha/package.json b/packages/themes/matcha/package.json
index 415fcd4b2a..e5e78e22b2 100644
--- a/packages/themes/matcha/package.json
+++ b/packages/themes/matcha/package.json
@@ -45,7 +45,7 @@
"src"
],
"scripts": {
- "build": "astryx theme build src/matchaTheme.ts -o dist/theme.css && tsup && tsc --project tsconfig.build.json"
+ "build": "astryx theme build src/matchaTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json"
},
"dependencies": {
"lucide-react": "^1.18.0"
diff --git a/packages/themes/neutral/package.json b/packages/themes/neutral/package.json
index 9271334576..6e6cf9c3b8 100644
--- a/packages/themes/neutral/package.json
+++ b/packages/themes/neutral/package.json
@@ -46,7 +46,7 @@
"src"
],
"scripts": {
- "build": "astryx theme build src/neutralTheme.ts -o dist/theme.css && tsup && tsc --project tsconfig.build.json"
+ "build": "astryx theme build src/neutralTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json"
},
"dependencies": {
"lucide-react": "^1.18.0"
diff --git a/packages/themes/stone/package.json b/packages/themes/stone/package.json
index 699083a154..29937123f6 100644
--- a/packages/themes/stone/package.json
+++ b/packages/themes/stone/package.json
@@ -46,7 +46,7 @@
"src"
],
"scripts": {
- "build": "astryx theme build src/stoneTheme.ts -o dist/theme.css && tsup && tsc --project tsconfig.build.json"
+ "build": "astryx theme build src/stoneTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json"
},
"dependencies": {
"lucide-react": "^1.18.0"
diff --git a/packages/themes/y2k/package.json b/packages/themes/y2k/package.json
index 5590e20c1b..661c85635b 100644
--- a/packages/themes/y2k/package.json
+++ b/packages/themes/y2k/package.json
@@ -46,7 +46,7 @@
"src"
],
"scripts": {
- "build": "astryx theme build src/y2kTheme.ts -o dist/theme.css && tsup && tsc --project tsconfig.build.json"
+ "build": "astryx theme build src/y2kTheme.ts -o dist/theme.css --icons-specifier ./icons.mjs && tsup && tsc --project tsconfig.build.json"
},
"dependencies": {
"lucide-react": "^1.18.0"
diff --git a/scripts/verify-exports.mjs b/scripts/verify-exports.mjs
index eb3a05f2de..f5ff089944 100644
--- a/scripts/verify-exports.mjs
+++ b/scripts/verify-exports.mjs
@@ -9,12 +9,28 @@
* resolve to files that actually exist on disk. Designed to run AFTER `pnpm build`
* to catch cases where packages point to dist files that weren't produced.
*
+ * Existence is necessary but not sufficient: an entry file can exist and still be
+ * unloadable, because nothing here opens it. That is how #4620 shipped — every
+ * theme's `./built` entry existed while carrying an extensionless relative import
+ * that Node cannot resolve. So explicit `import`-condition ESM targets and
+ * unconditional ESM targets are also imported. This runs after the build, so a
+ * forward reference to something a later pipeline stage produces is already
+ * satisfied.
+ *
+ * Scope, deliberately: importing a module only exercises the specifiers that are
+ * evaluated when it loads — its static import graph. A bad specifier inside a
+ * `lazy(() => import('...'))` is never reached, so this would NOT have caught
+ * #4569 (`await import('@astryxdesign/core/Text')` succeeds on the unfixed bytes
+ * even though the Tooltip specifier inside it is broken). Catching that needs a
+ * static scan; see scripts/check-fully-specified.mjs.
+ *
* Exit code 1 if any exports are broken.
*/
import { readFileSync, existsSync, readdirSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
import { join, resolve, dirname, relative } from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { fileURLToPath, pathToFileURL } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = resolve(__dirname, '..');
@@ -92,6 +108,20 @@ function checkWildcard(pkgDir, exportValue) {
return matches > 0;
}
+/**
+ * ESM targets worth actually importing. `.cjs` and `require`-condition targets
+ * are skipped (loading CJS here would fire side effects under a different
+ * module system), as are type declarations and assets, which Node cannot import
+ * as modules anyway. `default` targets are deliberately outside this probe:
+ * many are browser-focused, and evaluating every default entry would broaden
+ * this packaging check beyond the explicit ESM import surface it protects.
+ */
+const IMPORTABLE = /\.(js|mjs)$/;
+const NON_PROBED_CONDITIONS = new Set(['types', 'require', 'default']);
+
+/** Targets collected during the existence pass, imported afterwards. */
+const importTargets = [];
+
/**
* Recursively check an exports map value.
* Handles string paths, conditional objects, and nested structures.
@@ -108,6 +138,19 @@ function checkExportsValue(pkgDir, pkgName, exportKey, value, parentCondition) {
? `exports["${exportKey}"].${parentCondition}`
: `exports["${exportKey}"]`;
errors.push(` ✗ ${label} → ${value} (${isWildcard ? 'no files match pattern' : 'file not found'})`);
+ } else if (
+ !isWildcard &&
+ IMPORTABLE.test(value) &&
+ !NON_PROBED_CONDITIONS.has(parentCondition)
+ ) {
+ importTargets.push({
+ pkgName,
+ label: parentCondition
+ ? `exports["${exportKey}"].${parentCondition}`
+ : `exports["${exportKey}"]`,
+ value,
+ abs: resolve(pkgDir, value),
+ });
}
} else if (typeof value === 'object' && value !== null) {
for (const [condition, conditionValue] of Object.entries(value)) {
@@ -165,9 +208,72 @@ for (const pkgJsonPath of packageJsons) {
console.log(`\n${packagesChecked} packages checked.`);
-if (totalErrors > 0) {
- console.error(`\n${totalErrors} broken export(s) found. Fix the paths above.`);
+// Second pass: actually load each runtime ESM target. A target can exist and
+// still be unresolvable — see #4620, where every theme's `./built` entry was
+// present but imported an extensionless `./icons` that Node rejects.
+//
+// Each import runs in a child process. Importing a module evaluates it, and some
+// export targets are executables — `@astryxdesign/cli` maps "." to its bin, so an
+// in-process import runs the CLI and prints its help. A child keeps side effects,
+// stdout and any process.exit() out of this run, and the timeout contains a hang.
+const RESOLUTION_CODES = new Set([
+ 'ERR_MODULE_NOT_FOUND',
+ 'ERR_UNSUPPORTED_DIR_IMPORT',
+ 'ERR_UNKNOWN_FILE_EXTENSION',
+ 'ERR_REQUIRE_ESM',
+ 'SyntaxError',
+]);
+
+/** Sentinel exit code, distinct from anything an executable entry might use. */
+const IMPORT_FAILED = 9;
+
+let importFailures = 0;
+
+for (const target of importTargets) {
+ const probe =
+ `import(${JSON.stringify(pathToFileURL(target.abs).href)})` +
+ `.then(() => process.exit(0))` +
+ `.catch(e => { process.stderr.write(String((e && e.code) || (e && e.name) || e)); process.exit(${IMPORT_FAILED}); })`;
+
+ const run = spawnSync(process.execPath, ['--input-type=module', '-e', probe], {
+ encoding: 'utf-8',
+ timeout: 20_000,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ });
+
+ // Anything other than our sentinel is the module's own business: an
+ // executable entry that printed help and exited 0, or one that failed for a
+ // reason unrelated to packaging. Only resolution defects concern us here.
+ if (run.status !== IMPORT_FAILED) continue;
+
+ const code = (run.stderr || '').trim().split('\n')[0];
+ if (!RESOLUTION_CODES.has(code)) continue;
+
+ if (importFailures === 0) {
+ console.error('\n❌ Export targets that exist but cannot be imported:\n');
+ }
+ console.error(` ✗ ${target.pkgName} ${target.label} → ${target.value}`);
+ console.error(` ${code}`);
+ importFailures++;
+}
+
+if (importFailures === 0 && importTargets.length > 0) {
+ console.log(`${importTargets.length} ESM export target(s) imported cleanly.`);
+}
+
+const failures = totalErrors + importFailures;
+
+if (failures > 0) {
+ if (totalErrors > 0) {
+ console.error(`\n${totalErrors} broken export(s) found. Fix the paths above.`);
+ }
+ if (importFailures > 0) {
+ console.error(
+ `\n${importFailures} export target(s) exist but fail to load. A consumer importing ` +
+ `them from Node gets the same error.`,
+ );
+ }
process.exit(1);
} else {
- console.log('All exports resolve to existing files.');
+ console.log('All exports resolve to existing files; probed ESM targets load cleanly.');
}