@astryxdesign/cli 0.7.5-canary.fccd771 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +91 -3
  2. package/README.md +2 -2
  3. package/api/hook/detail/detail.test.mjs +11 -0
  4. package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
  5. package/api/integration/pack-check.mjs +10 -4
  6. package/api/integration/pack-check.test.mjs +5 -1
  7. package/api/swizzle/copy/copy.mjs +1 -1
  8. package/api/template/tokenizer-showcase.test.mjs +47 -0
  9. package/api/theme/build/build.adaptation-enrollment.test.mjs +4 -0
  10. package/api/theme/build/build.icon-entry-variants.test.mjs +134 -0
  11. package/api/theme/build/build.icon-function-entries.test.mjs +499 -0
  12. package/api/theme/build/build.icon-variants.test.mjs +105 -0
  13. package/api/theme/build/build.mjs +371 -113
  14. package/api/theme/build/build.project-core.test.mjs +63 -8
  15. package/api/theme/build/build.test.mjs +77 -0
  16. package/api/theme/build/icon-imports.d.mts +12 -2
  17. package/api/theme/build/icon-imports.mjs +36 -11
  18. package/api/upgrade/_adapter.d.mts +47 -2
  19. package/api/upgrade/_adapter.mjs +58 -2
  20. package/api/upgrade/run/failure-receipt.test.mjs +212 -0
  21. package/api/upgrade/run/outcomes.test.mjs +646 -0
  22. package/api/upgrade/run/run.d.mts +36 -0
  23. package/api/upgrade/run/run.mjs +670 -44
  24. package/api/upgrade/upgrade.doc.mjs +4 -4
  25. package/api/upgrade/upgrade.mjs +19 -4
  26. package/api/upgrade/upgrade.type.d.mts +36 -1
  27. package/api/upgrade/upgrade.type.mjs +29 -4
  28. package/assets/codemods/__tests__/registry.test.mjs +1 -0
  29. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  30. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  31. package/assets/codemods/integration-runner.mjs +8 -2
  32. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  33. package/assets/codemods/outcome.mjs +79 -0
  34. package/assets/codemods/outcome.test.mjs +40 -0
  35. package/assets/codemods/parse.mjs +94 -0
  36. package/assets/codemods/registry.mjs +1 -0
  37. package/assets/codemods/run-codemod.mjs +109 -5
  38. package/assets/codemods/runner.mjs +119 -13
  39. package/assets/codemods/transform-prop.mjs +99 -49
  40. package/assets/codemods/transform-prop.test.mjs +36 -1
  41. package/assets/codemods/transforms/v0.1.2/rename-text-color-active-to-accent.mjs +1 -1
  42. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  43. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  44. package/assets/codemods/transforms/v0.1.5/rename-switch-label-spacing-default-to-hug.mjs +1 -1
  45. package/assets/codemods/transforms/v0.1.7/migrate-table-tableprops-to-direct-props.mjs +1 -1
  46. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +1 -1
  47. package/assets/codemods/transforms/v0.2.0/remove-tablist-orientation.mjs +1 -1
  48. package/assets/codemods/transforms/v0.2.1/migrate-dialog-position-to-logical.mjs +1 -1
  49. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  50. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  51. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +143 -70
  52. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  53. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
  54. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +23 -78
  55. package/assets/codemods/transforms/v0.7.5/__tests__/migrate-codeblock-tokenizer-to-language.test.mjs +130 -0
  56. package/assets/codemods/transforms/v0.7.5/index.mjs +20 -0
  57. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +315 -0
  58. package/assets/docs/README.md +13 -13
  59. package/assets/docs/author-a-theme.doc.mjs +5 -1
  60. package/assets/docs/getting-started.doc.mjs +5 -5
  61. package/assets/docs/icons.doc.mjs +82 -1
  62. package/assets/docs/motion.doc.mjs +1 -1
  63. package/assets/docs/theme.doc.dense.mjs +8 -0
  64. package/assets/docs/theme.doc.mjs +16 -0
  65. package/assets/docs/theme.doc.zh.mjs +11 -0
  66. package/assets/docs/tree/i18n-library-integration.doc.mjs +1 -1
  67. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  68. package/assets/docs/tree/template-styles.doc.mjs +1 -1
  69. package/assets/docs/tree/tokens-color.doc.mjs +145 -1
  70. package/assets/docs/tree/tokens-ease.doc.mjs +4 -0
  71. package/assets/docs/tree/tokens.doc.mjs +1 -1
  72. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +6 -4
  73. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx +61 -55
  74. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs +6 -4
  75. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx +68 -37
  76. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  77. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  78. package/assets/templates/blocks/components/Thumbnail/ThumbnailDisabled.doc.mjs +1 -1
  79. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +13 -6
  80. package/assets/templates/pages/dashboard-alert-rail/page.tsx +3 -3
  81. package/assets/templates/pages/library/page.tsx +1 -2
  82. package/assets/templates/pages/table-comparison/page.tsx +12 -3
  83. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +3 -2
  84. package/assets/templates/themes/butter/butterTheme.ts +47 -44
  85. package/assets/templates/themes/chocolate/chocolateTheme.ts +15 -2
  86. package/assets/templates/themes/gothic/gothicTheme.ts +21 -16
  87. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +1 -1
  88. package/assets/templates/themes/matcha/matchaTheme.ts +15 -2
  89. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +4 -4
  90. package/assets/templates/themes/neutral/neutralTheme.ts +24 -119
  91. package/assets/templates/themes/stone/stoneTheme.ts +46 -21
  92. package/assets/templates/themes/y2k/y2kTheme.ts +20 -16
  93. package/assets/theme.template.ts +19 -6
  94. package/authoring/codemod/type.ts +10 -0
  95. package/authoring/config/config.doc.mjs +1 -1
  96. package/clients/cli/commands/build-theme.adaptations.test.mjs +110 -0
  97. package/clients/cli/commands/build-theme.outside-project.test.mjs +140 -0
  98. package/clients/cli/commands/swizzle.routing.test.mjs +1 -1
  99. package/clients/cli/commands/upgrade.doc.mjs +47 -2
  100. package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
  101. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  102. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  103. package/clients/cli/commands/upgrade.mjs +9 -2
  104. package/clients/cli/commands/upgrade.outcomes.test.mjs +350 -0
  105. package/foundation/agent-docs/agent-docs.mjs +1 -0
  106. package/foundation/agent-docs/agent-docs.test.mjs +5 -0
  107. package/foundation/config/project.d.mts +1 -1
  108. package/foundation/config/project.mjs +1 -1
  109. package/foundation/debug/redact.test.mjs +1 -1
  110. package/foundation/doc-compiler/doc-loads.test.mjs +2 -6
  111. package/foundation/response/base.d.ts +7 -0
  112. package/foundation/response/error-codes.doc.mjs +3 -2
  113. package/foundation/response/error-codes.mjs +1 -1
  114. package/foundation/response/json.d.mts +10 -3
  115. package/foundation/response/json.mjs +16 -4
  116. package/foundation/response/response-types.doc.mjs +1 -1
  117. package/package.json +13 -12
@@ -12,8 +12,10 @@
12
12
  * build emits the exact CSS the `<Theme>` runtime does), writes:
13
13
  * - A CSS file with token overrides and component styles
14
14
  * - A CSS declaration module for strict side-effect imports
15
- * - A JS module that re-exports the built theme (+ icon registry)
16
- * - A .d.ts (plus an optional .variants.d.ts for custom prop values)
15
+ * - A JS module that re-exports the built theme (+ icon registry); function
16
+ * icon entries stay functions for `Icon`, beside a node view of the registry
17
+ * - A .d.ts (plus an optional .variants.d.ts for custom prop values and the
18
+ * theme's icon variant names)
17
19
  *
18
20
  * It performs the writes and returns a `theme.build` receipt — its `warnings`
19
21
  * carry override problems and every declaration core's generator dropped
@@ -58,7 +60,7 @@
58
60
 
59
61
  import * as fs from 'node:fs';
60
62
  import * as path from 'node:path';
61
- import {isBuiltin} from 'node:module';
63
+ import {createRequire, isBuiltin} from 'node:module';
62
64
  import {fileURLToPath, pathToFileURL} from 'node:url';
63
65
  import {parse} from '@babel/parser';
64
66
  import {createJiti} from 'jiti';
@@ -306,7 +308,9 @@ function realLocation(target) {
306
308
  * Core, so building with it keeps the CSS identical; and a CLI run one-off
307
309
  * (`npx @astryxdesign/cli`) has no Core beside it at all. Null when there is
308
310
  * nothing better than the CLI's own import: no installed Core (the Astryx
309
- * repository, a bare directory), the same Core, or one that does not load.
311
+ * repository, a bare directory) or the same Core. A Core that is there but
312
+ * does not load, or lacks the functions the build calls, throws, naming it:
313
+ * building with another Core would not match the app's `<Theme>`.
310
314
  *
311
315
  * @param {string} cwd
312
316
  * @param {CoreBindings} cliCore - The CLI's own Core, from {@link loadCliCore}.
@@ -316,29 +320,36 @@ function realLocation(target) {
316
320
  */
317
321
  async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
318
322
  // Outside a project, the Core the answering copy carries (spec AST-081 FR3).
319
- const dir =
320
- findInstalledPackage(cwd, '@astryxdesign/core') ??
321
- (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));
323
+ const installed = findInstalledPackage(cwd, '@astryxdesign/core');
324
+ const dir = installed ?? (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));
322
325
  const themeFile = dir ? importTarget(dir, './theme') : null;
323
326
  if (!dir || !themeFile) return null;
324
327
  if (cliCore.themeModule) {
325
- try {
326
- const own = fileURLToPath(
327
- import.meta.resolve('@astryxdesign/core/theme'),
328
- );
329
- if (realOrSelf(own) === realOrSelf(themeFile)) return null;
330
- } catch {
331
- // The CLI's own Core cannot be located; load the project's.
332
- }
328
+ const own = cliCoreThemeFile();
329
+ if (own != null && realOrSelf(own) === realOrSelf(themeFile)) return null;
333
330
  }
334
331
  let themeModule;
335
332
  try {
336
333
  themeModule = await import(pathToFileURL(themeFile).href);
337
- } catch {
338
- return null;
334
+ } catch (error) {
335
+ throw new AstryxError(
336
+ installed == null
337
+ ? carriedCoreMessage(dir, /** @type {Error} */ (error))
338
+ : coreUnavailableMessage(cwd, /** @type {Error} */ (error)),
339
+ undefined,
340
+ ERROR_CODES.ERR_CORE_NOT_FOUND,
341
+ );
342
+ }
343
+ const missing = ['defineTheme', 'generateThemeRulesSplit'].filter(
344
+ name => typeof themeModule[name] !== 'function',
345
+ );
346
+ if (missing.length > 0) {
347
+ throw new AstryxError(
348
+ `The @astryxdesign/core at ${path.relative(cwd, dir) || '.'} does not export ${missing.join(' or ')} from its \`./theme\` entry, which \`${formatCliCommand('theme build')}\` calls. Update it.`,
349
+ undefined,
350
+ ERROR_CODES.ERR_CORE_INCOMPATIBLE,
351
+ );
339
352
  }
340
- if (!themeModule.defineTheme || !themeModule.generateThemeRulesSplit)
341
- return null;
342
353
  let rootModule = null;
343
354
  const rootFile = importTarget(dir, '.');
344
355
  if (rootFile) {
@@ -359,6 +370,40 @@ async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
359
370
  };
360
371
  }
361
372
 
373
+ /**
374
+ * The file the CLI's own `@astryxdesign/core/theme` resolves to, or null when
375
+ * the CLI has no Core of its own (a one-off `npx` run).
376
+ * @returns {string | null}
377
+ */
378
+ function cliCoreThemeFile() {
379
+ try {
380
+ return fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));
381
+ } catch (error) {
382
+ const {code} = /** @type {NodeJS.ErrnoException} */ (error);
383
+ if (
384
+ code === 'ERR_MODULE_NOT_FOUND' ||
385
+ code === 'ERR_PACKAGE_PATH_NOT_EXPORTED'
386
+ ) {
387
+ return null;
388
+ }
389
+ throw error;
390
+ }
391
+ }
392
+
393
+ /**
394
+ * The error for a Core the answering copy carries (outside a project) that
395
+ * does not load.
396
+ * @param {string} dir
397
+ * @param {Error} importError
398
+ * @returns {string}
399
+ */
400
+ function carriedCoreMessage(dir, importError) {
401
+ return (
402
+ `Could not load the @astryxdesign/core this CLI release carries, at ${dir}.` +
403
+ `\n Import error: ${importError.message}`
404
+ );
405
+ }
406
+
362
407
  /** @type {Map<string, Awaited<ReturnType<typeof loadProjectCore>>>} */
363
408
  const _projectCores = new Map();
364
409
 
@@ -379,7 +424,7 @@ async function selectCore(cwd, {projectOnly = false} = {}) {
379
424
  // A global or cached copy's own Core is the carried one.
380
425
  if (projectOnly && !projectCore && carriesCore() && !cliCoreIsProjects(cwd)) {
381
426
  throw new AstryxError(
382
- "The project's Core isn't installed or does not load.",
427
+ "The project's Core isn't installed.",
383
428
  undefined,
384
429
  ERROR_CODES.ERR_CORE_NOT_FOUND,
385
430
  );
@@ -405,13 +450,11 @@ function carriesCore() {
405
450
  function cliCoreIsProjects(cwd) {
406
451
  const dir = findProjectCoreDir(cwd);
407
452
  if (!dir) return false;
408
- try {
409
- const own = fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));
410
- const theirs = importTarget(dir, './theme');
411
- return theirs != null && realOrSelf(own) === realOrSelf(theirs);
412
- } catch {
413
- return false;
414
- }
453
+ const own = cliCoreThemeFile();
454
+ const theirs = importTarget(dir, './theme');
455
+ return (
456
+ own != null && theirs != null && realOrSelf(own) === realOrSelf(theirs)
457
+ );
415
458
  }
416
459
 
417
460
  /**
@@ -1103,6 +1146,28 @@ function componentHasAugmentableInterface(pascalName, interfaceName) {
1103
1146
  return re.test(decl);
1104
1147
  }
1105
1148
 
1149
+ /**
1150
+ * Public augmentable maps whose axis requests artwork instead of styling.
1151
+ * `Icon.variant` selects a theme's icon artwork, so it has no component styling
1152
+ * map (architecture:component-theming-surface INV14): a `components` key on it
1153
+ * never enrolls a value or generates an augmentation of its map.
1154
+ */
1155
+ const ARTWORK_REQUEST_MAPS = new Set(['IconVariantMap']);
1156
+
1157
+ /**
1158
+ * Whether a theme's component styling keys may enroll values in `interfaceName`
1159
+ * on `@astryxdesign/core/<Component>`.
1160
+ * @param {string} pascalName
1161
+ * @param {string} interfaceName
1162
+ * @returns {boolean}
1163
+ */
1164
+ function isComponentValueAugmentationPoint(pascalName, interfaceName) {
1165
+ return (
1166
+ !ARTWORK_REQUEST_MAPS.has(interfaceName) &&
1167
+ componentHasAugmentableInterface(pascalName, interfaceName)
1168
+ );
1169
+ }
1170
+
1106
1171
  /**
1107
1172
  * Adaptation values from resolved runtime rules, raw input, or normalized built
1108
1173
  * metadata. Built modules intentionally omit `__adaptationRules`, so every CLI
@@ -1410,7 +1475,7 @@ async function classifyComponentValue(component, prop, value) {
1410
1475
  const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
1411
1476
  const target = (await resolveAugmentationTargetCandidates(component)).find(
1412
1477
  candidate =>
1413
- componentHasAugmentableInterface(
1478
+ isComponentValueAugmentationPoint(
1414
1479
  candidate.moduleName,
1415
1480
  `${candidate.interfacePrefix}${propPascal}Map`,
1416
1481
  ),
@@ -1514,12 +1579,21 @@ async function validateAdaptationEnrollment(themeDef) {
1514
1579
  * generating a `declare module` block for them would be dead code — those are
1515
1580
  * skipped.
1516
1581
  *
1517
- * @param {{components?: Record<string, Record<string, Record<string, unknown>>>}} themeDef - Theme definition (resolved by defineTheme)
1582
+ * A theme that lists `iconVariants` also augments `IconVariantMap` in
1583
+ * `@astryxdesign/core/Icon` with those names, when the installed core declares
1584
+ * it, so `<Icon variant>` accepts them (spec:AST-087 FR3).
1585
+ *
1586
+ * @param {{components?: Record<string, Record<string, Record<string, unknown>>>, iconVariants?: readonly string[]}} themeDef - Theme definition (resolved by defineTheme)
1518
1587
  * @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed
1519
1588
  */
1520
1589
  async function generateVariantDeclarationsAsync(themeDef) {
1521
1590
  const componentLayers = getThemeComponentLayers(themeDef);
1522
- if (componentLayers.length === 0) {
1591
+ const iconVariantNames =
1592
+ Array.isArray(themeDef.iconVariants) &&
1593
+ componentHasAugmentableInterface('Icon', 'IconVariantMap')
1594
+ ? [...new Set(themeDef.iconVariants)]
1595
+ : [];
1596
+ if (componentLayers.length === 0 && iconVariantNames.length === 0) {
1523
1597
  return null;
1524
1598
  }
1525
1599
 
@@ -1555,7 +1629,7 @@ async function generateVariantDeclarationsAsync(themeDef) {
1555
1629
  const hasCustom = Object.values(customValues).some(props =>
1556
1630
  Object.values(props).some(values => values.size > 0),
1557
1631
  );
1558
- if (!hasCustom) return null;
1632
+ if (!hasCustom && iconVariantNames.length === 0) return null;
1559
1633
 
1560
1634
  const sections = ['// Generated by astryx theme build', 'export {};', ''];
1561
1635
 
@@ -1567,7 +1641,7 @@ async function generateVariantDeclarationsAsync(themeDef) {
1567
1641
  const target = (
1568
1642
  await resolveAugmentationTargetCandidates(component)
1569
1643
  ).find(candidate =>
1570
- componentHasAugmentableInterface(
1644
+ isComponentValueAugmentationPoint(
1571
1645
  candidate.moduleName,
1572
1646
  `${candidate.interfacePrefix}${propPascal}Map`,
1573
1647
  ),
@@ -1595,6 +1669,17 @@ async function generateVariantDeclarationsAsync(themeDef) {
1595
1669
  }
1596
1670
  }
1597
1671
 
1672
+ if (iconVariantNames.length > 0) {
1673
+ sections.push(`declare module '@astryxdesign/core/Icon' {`);
1674
+ sections.push(' interface IconVariantMap {');
1675
+ for (const name of iconVariantNames) {
1676
+ sections.push(` ${tsStringLiteral(name)}: true;`);
1677
+ }
1678
+ sections.push(' }');
1679
+ sections.push('}');
1680
+ sections.push('');
1681
+ }
1682
+
1598
1683
  // If every custom value targeted a non-augmentable prop, there's nothing to
1599
1684
  // emit beyond the header — return null so no `.variants.d.ts` is written.
1600
1685
  const hasEmittedAugmentation = sections.some(line =>
@@ -1833,19 +1918,43 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1833
1918
  commonJsPatch.undo();
1834
1919
  }
1835
1920
  } else {
1836
- mod = await jiti.import(filePath, {default: true});
1921
+ mod = await jiti.import(filePath);
1837
1922
  }
1838
1923
 
1839
- if (isThemeObject(mod)) return {theme: mod, exportName: 'default', degraded};
1840
-
1841
- if (mod && typeof mod === 'object') {
1842
- if (isThemeObject(mod.default)) {
1843
- return {theme: mod.default, exportName: 'default', degraded};
1844
- }
1924
+ // Both loads hand back the module. The theme is read from the module's own
1925
+ // exports, never from the module object itself: jiti's interop answers a
1926
+ // property the module lacks from its default export (and a missing
1927
+ // `default` with the module), so the module can pass for the theme while
1928
+ // its own keys hide the theme's fields.
1929
+ const isModule = mod != null && typeof mod === 'object';
1930
+ const hasDefault = isModule && Object.hasOwn(mod, 'default');
1931
+ const defaultExport = hasDefault ? mod.default : undefined;
1932
+ if (isThemeObject(defaultExport)) {
1933
+ return {theme: defaultExport, exportName: 'default', degraded};
1934
+ }
1935
+ if (isModule) {
1845
1936
  for (const [exportName, value] of Object.entries(mod)) {
1937
+ if (exportName === 'default' || exportName === 'module.exports') continue;
1846
1938
  if (isThemeObject(value)) return {theme: value, exportName, degraded};
1847
1939
  }
1848
1940
  }
1941
+ // A plain-object default export is the module's theme even when it has
1942
+ // no tokens of its own (local tokens, typography or component styles may
1943
+ // be all it defines), or no name: the build's validation says what it
1944
+ // lacks.
1945
+ if (isPlainObject(defaultExport)) {
1946
+ return {theme: defaultExport, exportName: 'default', degraded};
1947
+ }
1948
+ // A CommonJS module whose exports are the theme (`module.exports =
1949
+ // theme`) has no default of its own: interop answers `default` with
1950
+ // those exports, and without interop (a family build's loader) the module
1951
+ // is them.
1952
+ if (isModule && !hasDefault) {
1953
+ const exportsObject = mod.default ?? mod;
1954
+ if (isThemeObject(exportsObject)) {
1955
+ return {theme: exportsObject, exportName: 'default', degraded};
1956
+ }
1957
+ }
1849
1958
 
1850
1959
  throw new Error(
1851
1960
  `Could not find a defineTheme() result in ${filePath}.\n` +
@@ -1853,6 +1962,45 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1853
1962
  );
1854
1963
  }
1855
1964
 
1965
+ /**
1966
+ * Whether the theme file's own folder resolves Core's theme entry, as the
1967
+ * theme's own `import ... from '@astryxdesign/core/theme'` would. A theme
1968
+ * outside any project (an empty folder, a fresh clone) does not, and is
1969
+ * handed the Core the CLI answers with instead, as a new project with that
1970
+ * Core would build it (`theme build` runs the same outside a project, spec
1971
+ * AST-081 FR3). Only a Core not installed there (MODULE_NOT_FOUND) reads as
1972
+ * no: an installed Core whose entry does not resolve is the theme's own, and
1973
+ * its load reports that.
1974
+ * @param {string} filePath
1975
+ * @returns {boolean}
1976
+ */
1977
+ function themeFolderResolvesCore(filePath) {
1978
+ try {
1979
+ createRequire(filePath).resolve('@astryxdesign/core/theme');
1980
+ return true;
1981
+ } catch (error) {
1982
+ const {code} = /** @type {NodeJS.ErrnoException} */ (error);
1983
+ if (code === 'MODULE_NOT_FOUND') return false;
1984
+ if (code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') return true;
1985
+ throw error;
1986
+ }
1987
+ }
1988
+
1989
+ /**
1990
+ * A plain object, not an array or a module namespace: a theme module's
1991
+ * default export, read as its theme.
1992
+ * @param {any} value
1993
+ * @returns {boolean}
1994
+ */
1995
+ function isPlainObject(value) {
1996
+ return (
1997
+ value != null &&
1998
+ typeof value === 'object' &&
1999
+ !Array.isArray(value) &&
2000
+ value[Symbol.toStringTag] !== 'Module'
2001
+ );
2002
+ }
2003
+
1856
2004
  /**
1857
2005
  * @param {any} value
1858
2006
  * @returns {boolean}
@@ -1868,12 +2016,9 @@ function isThemeObject(value) {
1868
2016
  }
1869
2017
 
1870
2018
  /**
1871
- * Extract the theme definition from a JS/TS file.
1872
- * Tries jiti first (full TS support), falls back to regex+eval.
1873
- *
1874
- * The legacy fallback needs no interception: it evaluates the `defineTheme()`
1875
- * ARGUMENT, so what it returns is raw authored input with `adaptations` still
1876
- * on it — nothing has erased anything yet. It is therefore never degraded.
2019
+ * Extract the theme definition from a JS/TS file, through jiti (full TS
2020
+ * support). A module that does not load fails with its own error: the theme
2021
+ * is never read from the file's text instead.
1877
2022
  *
1878
2023
  * @param {string} filePath
1879
2024
  * @param {import('./core-interception.mjs').CoreInterception} [interception]
@@ -1884,18 +2029,12 @@ async function extractThemeDefinition(filePath, interception, /** @type {any} */
1884
2029
  try {
1885
2030
  return await importThemeModule(filePath, interception, loader);
1886
2031
  } catch (jitiError) {
1887
- try {
1888
- return {
1889
- theme: extractThemeDefinitionLegacy(filePath),
1890
- degraded: {topLevelAwait: false, commonJs: false},
1891
- };
1892
- } catch {
1893
- const je = /** @type {Error} */ (jitiError);
1894
- throw new Error(
1895
- `Failed to load theme from ${filePath}: ${je.message}\n` +
1896
- `Make sure all imports in the theme file are resolvable.`,
1897
- );
1898
- }
2032
+ const je = /** @type {Error} */ (jitiError);
2033
+ throw new Error(
2034
+ `Failed to load theme from ${filePath}: ${je.message}\n` +
2035
+ `Make sure all imports in the theme file are resolvable.`,
2036
+ {cause: jitiError},
2037
+ );
1899
2038
  }
1900
2039
  }
1901
2040
 
@@ -1941,45 +2080,6 @@ export async function validateThemePrivateInputs(
1941
2080
  }
1942
2081
  }
1943
2082
 
1944
- /**
1945
- * Fallback extraction via regex + eval.
1946
- * Only works for plain object literals — can't follow imports or variables.
1947
- * Never erase icon references: an unresolved registry must preserve the loader
1948
- * error instead of turning an incomplete theme into a successful build.
1949
- * @param {string} filePath
1950
- * @returns {any}
1951
- */
1952
- function extractThemeDefinitionLegacy(filePath) {
1953
- const content = fs.readFileSync(filePath, 'utf8');
1954
-
1955
- const defineMatch = content.match(/defineTheme\s*\(\s*({[\s\S]*?})\s*\)/);
1956
- if (!defineMatch) {
1957
- const defaultMatch = content.match(/export\s+default\s+({[\s\S]*?});/);
1958
- if (!defaultMatch) {
1959
- throw new Error(
1960
- `Could not find defineTheme() call or default export in ${filePath}.\n` +
1961
- `Expected: defineTheme({ name: '...', tokens: {...} })`,
1962
- );
1963
- }
1964
-
1965
- return eval(`(${defaultMatch[1]})`);
1966
- }
1967
-
1968
- let objStr = defineMatch[1];
1969
- objStr = objStr.replace(/\s+as\s+const/g, '');
1970
-
1971
- try {
1972
- return eval(`(${objStr})`);
1973
- } catch (e) {
1974
- const err = /** @type {Error} */ (e);
1975
- throw new Error(
1976
- `Failed to parse theme definition in ${filePath}: ${err.message}\n` +
1977
- `Make sure the defineTheme() argument is a plain object literal.`,
1978
- {cause: e},
1979
- );
1980
- }
1981
- }
1982
-
1983
2083
  /**
1984
2084
  * Extract a family member's named registry import from its source file.
1985
2085
  * Returns { importPath, exportName } or null when the theme names none.
@@ -2020,6 +2120,53 @@ function extractRegistryInfo(filePath, field) {
2020
2120
  return null;
2021
2121
  }
2022
2122
 
2123
+ /**
2124
+ * Whether a theme's icon entries include a function of `{size, variant}`.
2125
+ * @param {Record<string, unknown> | null | undefined} entries
2126
+ * @returns {boolean}
2127
+ */
2128
+ function hasFunctionIconEntry(entries) {
2129
+ return Object.values(entries ?? {}).some(
2130
+ entry => typeof entry === 'function',
2131
+ );
2132
+ }
2133
+
2134
+ /**
2135
+ * A built theme's icon entries: a theme from defineTheme keeps them in
2136
+ * `__icons` when any is a function (its `icons` is the node view); otherwise
2137
+ * `icons` holds them.
2138
+ * @param {any} theme
2139
+ * @returns {Record<string, unknown> | undefined}
2140
+ */
2141
+ function themeIconEntries(theme) {
2142
+ return theme?.__icons ?? theme?.icons;
2143
+ }
2144
+
2145
+ /**
2146
+ * The generated code that reads a registry's entries as React nodes, each
2147
+ * function entry read at `{size: 'md'}` like core's public reads. It never
2148
+ * passes the registry to a call, so a theme extending the built module can
2149
+ * still trace the registry through its `__icons` field, and it reads no
2150
+ * global, which a registry import could shadow. The registry expression runs
2151
+ * where only `entriesName` and `nodesName` are declared, both names the
2152
+ * registry imports cannot use.
2153
+ * @param {string} entries - Expression for the registry's entries.
2154
+ * @param {string} entriesName - A reserved local name.
2155
+ * @param {string} nodesName - A reserved local name.
2156
+ * @returns {string}
2157
+ */
2158
+ function iconNodesExpression(entries, entriesName, nodesName) {
2159
+ return `(() => {
2160
+ const ${entriesName} = ${entries};
2161
+ const ${nodesName} = {};
2162
+ for (const name in ${entriesName}) {
2163
+ const entry = ${entriesName}[name];
2164
+ ${nodesName}[name] = typeof entry === 'function' ? entry({size: 'md'}) : entry;
2165
+ }
2166
+ return ${nodesName};
2167
+ })()`;
2168
+ }
2169
+
2023
2170
  /**
2024
2171
  * Generate a minimal JS module for a built theme.
2025
2172
  * Includes the theme name, marker, and re-exports the icon registry.
@@ -2041,6 +2188,11 @@ function extractRegistryInfo(filePath, field) {
2041
2188
  * not given, direct registry specifiers are preserved, and inherited relative
2042
2189
  * imports are rebased from the base module to the theme entry's directory.
2043
2190
  *
2191
+ * When an icon entry is a function of `{size, variant}`, the module keeps the
2192
+ * registry as `__icons`, which `Icon` resolves at the size and variant it
2193
+ * renders, and the theme's `icons` and the re-exported registry are the node
2194
+ * view, each function read at `{size: 'md'}` as `DefinedTheme['icons']` is.
2195
+ *
2044
2196
  * @param {any} themeDef
2045
2197
  * @param {import('./icon-imports.mjs').IconImports | null} iconInfo
2046
2198
  * @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
@@ -2089,12 +2241,28 @@ function generateBuiltModule(
2089
2241
  ? `const ${iconInfo.exportName} = ${iconInfo.expression};\n`
2090
2242
  : '';
2091
2243
  const iconsExpression = moduleOptions.iconsExpression ?? iconInfo?.exportName;
2092
- const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';
2244
+ const iconNodes =
2245
+ iconsExpression && hasFunctionIconEntry(themeIconEntries(themeDef))
2246
+ ? `${themeBinding}IconNodes`
2247
+ : null;
2248
+ const iconNodesDeclaration =
2249
+ iconNodes && iconsExpression
2250
+ ? `const ${iconNodes} = ${iconNodesExpression(iconsExpression, `${themeBinding}IconEntries`, iconNodes)};\n`
2251
+ : '';
2252
+ const iconsField = iconNodes
2253
+ ? ` icons: ${iconNodes},\n __icons: ${iconsExpression},`
2254
+ : iconsExpression
2255
+ ? ` icons: ${iconsExpression},`
2256
+ : '';
2093
2257
  const indicatorsField = moduleOptions.indicatorsExpression
2094
2258
  ? `\n indicators: ${moduleOptions.indicatorsExpression},`
2095
2259
  : '';
2096
2260
  const iconReExport =
2097
- iconInfo && exportIcons ? `\nexport { ${iconInfo.exportName} };\n` : '';
2261
+ iconInfo && exportIcons
2262
+ ? iconNodes
2263
+ ? `\nexport { ${iconNodes} as ${iconInfo.exportName} };\n`
2264
+ : `\nexport { ${iconInfo.exportName} };\n`
2265
+ : '';
2098
2266
 
2099
2267
  // Resolve token values — tuples become light-dark() strings
2100
2268
  /** @type {Record<string, unknown>} */
@@ -2151,9 +2319,24 @@ function generateBuiltModule(
2151
2319
  serializeField('__onDark', themeDef.__onDark) +
2152
2320
  serializeField('__onLight', themeDef.__onLight) +
2153
2321
  serializeField('__adaptations', themeDef.__adaptations) +
2154
- serializeField('__axes', themeDef.__axes ?? {}, true);
2322
+ serializeField('__axes', themeDef.__axes ?? {}, true) +
2323
+ // An explicit empty list replaces an inherited one, so keep `[]`.
2324
+ serializeField('iconVariants', themeDef.iconVariants, true) +
2325
+ // Each inherited function entry keeps its defining theme's list. JSON
2326
+ // drops `undefined`, so a defining theme with no list is written as `[]`,
2327
+ // which no variant matches either.
2328
+ serializeField(
2329
+ '__iconEntryVariants',
2330
+ themeDef.__iconEntryVariants &&
2331
+ Object.fromEntries(
2332
+ Object.entries(themeDef.__iconEntryVariants).map(([name, list]) => [
2333
+ name,
2334
+ list ?? [],
2335
+ ]),
2336
+ ),
2337
+ );
2155
2338
 
2156
- return `${iconImport}${iconDeclaration}/**
2339
+ return `${iconImport}${iconDeclaration}${iconNodesDeclaration}/**
2157
2340
  * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
2158
2341
  * Import the CSS file alongside this module:
2159
2342
  *
@@ -2203,7 +2386,39 @@ export declare const ${iconInfo.exportName}: IconRegistry;
2203
2386
  (typeOptions.includeThemeImport ?? true)
2204
2387
  ? `import type { DefinedTheme } from '@astryxdesign/core/theme';\n`
2205
2388
  : '';
2206
- return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: DefinedTheme;\n`;
2389
+ return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: ${builtThemeType(themeDef)};\n`;
2390
+ }
2391
+
2392
+ /**
2393
+ * A TypeScript string literal type for `value`.
2394
+ * @param {string} value
2395
+ * @returns {string}
2396
+ */
2397
+ function tsStringLiteral(value) {
2398
+ const inner = JSON.stringify(value)
2399
+ .slice(1, -1)
2400
+ .replace(/\\"/g, '"')
2401
+ .replace(/'/g, "\\'");
2402
+ return `'${inner}'`;
2403
+ }
2404
+
2405
+ /**
2406
+ * The declared type of a built theme. A theme that lists icon variants
2407
+ * carries core's type-only `__iconVariant` marker with those names, so a theme
2408
+ * that extends the built one types its icon entries' `variant` by the list,
2409
+ * exactly as it would extending the source theme.
2410
+ * SYNC: packages/core/src/theme/defineTheme.ts (ResolvedDefinedTheme)
2411
+ * @param {any} themeDef
2412
+ * @returns {string}
2413
+ */
2414
+ function builtThemeType(themeDef) {
2415
+ const names = themeDef.iconVariants;
2416
+ if (!Array.isArray(names)) return 'DefinedTheme';
2417
+ const variant =
2418
+ names.length > 0
2419
+ ? [...new Set(names)].map(tsStringLiteral).join(' | ')
2420
+ : 'never';
2421
+ return `DefinedTheme & { __iconVariant?(variant: ${variant}): void }`;
2207
2422
  }
2208
2423
 
2209
2424
  // =============================================================================
@@ -2580,13 +2795,15 @@ async function themeBuildInternal(
2580
2795
  }
2581
2796
  await selectCore(cwd, {projectOnly: projectCore});
2582
2797
 
2583
- // Standalone builds only need interception when an older Core could erase
2584
- // adaptations. Family preparation always supplies the same recorder as its
2798
+ // Standalone builds need interception when an older Core could erase
2799
+ // adaptations, and when the theme's folder has no Core of its own: its
2800
+ // imports of Core are then handed the Core this build selected, as family
2801
+ // builds' are. Family preparation always supplies the same recorder as its
2585
2802
  // shared loader so exact authored parent identity stays CLI-private instead
2586
2803
  // of becoming a public DefinedTheme field.
2587
2804
  const interception =
2588
2805
  options.__familyInterception ??
2589
- (_generateAdaptationCSS
2806
+ (_generateAdaptationCSS && themeFolderResolvesCore(filePath)
2590
2807
  ? undefined
2591
2808
  : interceptCore(_coreThemeModule, _coreRootModule));
2592
2809
 
@@ -2675,10 +2892,26 @@ async function themeBuildInternal(
2675
2892
  // Family preparation keeps its own named-import registry contract, which
2676
2893
  // themeBuildFamily checks against the selected members' graph.
2677
2894
  const standaloneIcons = !options.__prepareFamily;
2895
+ // Function icon entries stay functions in the built module, beside a node
2896
+ // view bound to `<theme>IconNodes` and computed from `<theme>IconEntries`.
2897
+ const functionEntries =
2898
+ hasFunctionIconEntry(themeIconEntries(themeDef)) ||
2899
+ hasFunctionIconEntry(themeIconEntries(themeDef.extends));
2900
+ /** @param {boolean} reserveIconNodes */
2901
+ const reservedNames = reserveIconNodes => [
2902
+ `${toIdentifier(themeDef.name)}Theme`,
2903
+ ...(reserveIconNodes
2904
+ ? [
2905
+ `${toIdentifier(themeDef.name)}ThemeIconNodes`,
2906
+ `${toIdentifier(themeDef.name)}ThemeIconEntries`,
2907
+ ]
2908
+ : []),
2909
+ ];
2678
2910
  const iconResolution = {
2679
2911
  readSource: (/** @type {string} */ file) => fs.readFileSync(file, 'utf8'),
2680
2912
  resolveModule: resolveThemeModule,
2681
- reservedNames: [`${toIdentifier(themeDef.name)}Theme`],
2913
+ reservedNames: reservedNames(functionEntries),
2914
+ functionEntries,
2682
2915
  rawInput: 'extends' in themeDef,
2683
2916
  hasIcons:
2684
2917
  Object.keys(themeDef.icons ?? {}).length > 0 ||
@@ -2802,9 +3035,14 @@ async function themeBuildInternal(
2802
3035
  !iconInfo &&
2803
3036
  Object.keys(resolvedTheme.icons ?? {}).length > 0
2804
3037
  ) {
3038
+ const resolvedFunctionEntries = hasFunctionIconEntry(
3039
+ themeIconEntries(resolvedTheme),
3040
+ );
2805
3041
  iconInfo = await resolveIconImports(filePath, themeExportName, {
2806
3042
  ...iconResolution,
2807
3043
  hasIcons: true,
3044
+ functionEntries: resolvedFunctionEntries,
3045
+ reservedNames: reservedNames(resolvedFunctionEntries),
2808
3046
  });
2809
3047
  }
2810
3048
  // An opaque package base can legitimately have no icons. Its .icons
@@ -2870,10 +3108,15 @@ async function themeBuildInternal(
2870
3108
  /** @type {string[]} */
2871
3109
  const droppedDeclarations = [];
2872
3110
 
2873
- const {component, prose} = _generateThemeRulesSplit(
2874
- resolvedTheme,
2875
- droppedDeclarations,
2876
- );
3111
+ let themeRules;
3112
+ try {
3113
+ themeRules = _generateThemeRulesSplit(resolvedTheme, droppedDeclarations);
3114
+ } catch (error) {
3115
+ const message =
3116
+ error instanceof Error ? error.message : 'Theme normalization failed.';
3117
+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
3118
+ }
3119
+ const {component, prose} = themeRules;
2877
3120
  const cssParts = [];
2878
3121
  // Prose element defaults always ship — the `<Theme>` runtime
2879
3122
  // (generateThemeCSS) always emits them, so the build must too, or the
@@ -3062,7 +3305,7 @@ async function themeBuildInternal(
3062
3305
  );
3063
3306
  const dtsContent =
3064
3307
  generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
3065
- generateBuiltTypes(themeDef, iconInfo, variantsFileName);
3308
+ generateBuiltTypes(resolvedTheme || themeDef, iconInfo, variantsFileName);
3066
3309
 
3067
3310
  const unloadedFonts = [
3068
3311
  ...new Set([
@@ -3509,8 +3752,16 @@ export async function themeBuildFamily(
3509
3752
  ['icons', member.iconInfo],
3510
3753
  ['indicators', member.indicatorInfo],
3511
3754
  ]) {
3512
- const value = member.theme[field];
3513
- const inherited = member.sourceParent?.[field];
3755
+ // A theme with a function entry gets its own node view of `icons`, so
3756
+ // an inherit-only member is recognized by its entries.
3757
+ const value =
3758
+ field === 'icons'
3759
+ ? themeIconEntries(member.theme)
3760
+ : member.theme[field];
3761
+ const inherited =
3762
+ field === 'icons'
3763
+ ? themeIconEntries(member.sourceParent)
3764
+ : member.sourceParent?.[field];
3514
3765
  if (
3515
3766
  value &&
3516
3767
  Object.keys(value).length > 0 &&
@@ -3581,7 +3832,14 @@ export async function themeBuildFamily(
3581
3832
  // prettier-ignore
3582
3833
  for (const registry of [icon, indicator]) if (registry.info) registryImports.push({specifier: registry.specifier ?? registry.info.importPath, exportName: registry.info.exportName});
3583
3834
  const ownIcons = icon.info ? `${themeBinding}Icons` : null;
3584
- const inheritedIcons = parentBinding ? `${parentBinding}.icons` : null;
3835
+ // A parent with function entries keeps them in `__icons`; its `icons`
3836
+ // is the node view.
3837
+ const parent = members.find(
3838
+ other => other.theme.name === member.parentName,
3839
+ );
3840
+ const inheritedIcons = parentBinding
3841
+ ? `${parentBinding}.${hasFunctionIconEntry(themeIconEntries(parent?.theme)) ? '__icons' : 'icons'}`
3842
+ : null;
3585
3843
  const ownIndicators = indicator.info ? `${themeBinding}Indicators` : null;
3586
3844
  const inheritedIndicators = parentBinding
3587
3845
  ? `${parentBinding}.indicators`