@astryxdesign/cli 0.7.9-canary.ffa495b → 0.7.9

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 (70) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +1 -1
  3. package/api/component/__fixtures__/resolutions/modules.txt +5 -5
  4. package/api/search/_candidate-score.mjs +25 -23
  5. package/api/search/_words.d.mts +44 -7
  6. package/api/search/_words.mjs +113 -21
  7. package/api/swizzle/_adapter.d.mts +10 -0
  8. package/api/swizzle/_adapter.mjs +24 -1
  9. package/api/swizzle/copy/copy.d.mts +17 -1
  10. package/api/swizzle/copy/copy.mjs +249 -9
  11. package/api/swizzle/swizzle.doc.mjs +1 -1
  12. package/api/swizzle/swizzle.type.mjs +1 -1
  13. package/api/theme/build/build.mjs +363 -73
  14. package/api/theme/build/core-interception.mjs +92 -29
  15. package/api/theme/build/icon-imports.d.mts +35 -4
  16. package/api/theme/build/icon-imports.mjs +299 -38
  17. package/assets/discover/official-packages.json +12 -0
  18. package/assets/docs/author-a-theme.doc.mjs +3 -1
  19. package/assets/docs/icons.doc.mjs +29 -0
  20. package/assets/docs/motion.doc.mjs +1 -1
  21. package/assets/docs/tree/calendar-systems.doc.mjs +146 -0
  22. package/assets/docs/tree/calendars.doc.mjs +46 -0
  23. package/assets/docs/tree/i18n-calendars.doc.mjs +51 -0
  24. package/assets/docs/tree/internationalization.doc.mjs +3 -3
  25. package/assets/templates/blocks/components/Calendar/useCalendarDaysHookUsage.doc.mjs +14 -0
  26. package/assets/templates/blocks/components/Calendar/useCalendarDaysHookUsage.tsx +71 -0
  27. package/assets/templates/blocks/components/Hooks/useInputContainerHookUsage.doc.mjs +15 -0
  28. package/assets/templates/blocks/components/Hooks/useInputContainerHookUsage.tsx +93 -0
  29. package/assets/templates/blocks/components/Hooks/useMergedRefsHookUsage.doc.mjs +14 -0
  30. package/assets/templates/blocks/components/Hooks/useMergedRefsHookUsage.tsx +78 -0
  31. package/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.doc.mjs +14 -0
  32. package/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.tsx +80 -0
  33. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.doc.mjs +14 -0
  34. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.tsx +94 -0
  35. package/assets/templates/blocks/components/Icon/useIconHookUsage.doc.mjs +19 -0
  36. package/assets/templates/blocks/components/Icon/useIconHookUsage.tsx +68 -0
  37. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.doc.mjs +14 -0
  38. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.tsx +89 -0
  39. package/assets/templates/blocks/components/Overlay/useOverlayHookUsage.doc.mjs +21 -0
  40. package/assets/templates/blocks/components/Overlay/useOverlayHookUsage.tsx +49 -0
  41. package/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.doc.mjs +14 -0
  42. package/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.tsx +61 -0
  43. package/assets/templates/blocks/components/usePanGesture/PanDraggableBox.doc.mjs +15 -0
  44. package/assets/templates/blocks/components/usePanGesture/PanDraggableBox.tsx +98 -0
  45. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs +14 -0
  46. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx +147 -0
  47. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +2 -2
  48. package/assets/templates/themes/neutral/neutralTheme.ts +30 -4
  49. package/assets/theme.template.ts +14 -2
  50. package/authoring/doctypes/base/type.ts +41 -0
  51. package/authoring/doctypes/component/component.doc.mjs +7 -1
  52. package/authoring/doctypes/component/type.ts +5 -0
  53. package/authoring/index.d.ts +2 -0
  54. package/clients/cli/commands/ensure-core-built.mjs +399 -43
  55. package/clients/cli/commands/swizzle.mjs +10 -0
  56. package/clients/cli/lib/component-format.mjs +49 -0
  57. package/foundation/config/project.mjs +27 -9
  58. package/foundation/discovery/component-discovery.mjs +56 -10
  59. package/foundation/env/search-path.d.mts +12 -0
  60. package/foundation/env/search-path.mjs +71 -43
  61. package/foundation/integrations/manifest-writer.d.mts +3 -4
  62. package/foundation/integrations/manifest-writer.mjs +5 -3
  63. package/foundation/release/cache.d.mts +11 -4
  64. package/foundation/release/cache.mjs +15 -7
  65. package/foundation/response/response-types.doc.mjs +1 -1
  66. package/foundation/text/levenshtein.d.mts +4 -1
  67. package/foundation/text/levenshtein.mjs +44 -1
  68. package/package.json +9 -9
  69. package/api/swizzle/_github.d.mts +0 -8
  70. package/api/swizzle/_github.mjs +0 -22
@@ -1013,31 +1013,44 @@ function resolveCoreRoot() {
1013
1013
  const _componentDeclCache = new Map();
1014
1014
  /**
1015
1015
  * @param {string} pascalName
1016
+ * @param {{includeTypes?: boolean}} [options]
1016
1017
  * @returns {string}
1017
1018
  */
1018
- function readComponentDeclarations(pascalName) {
1019
- if (_componentDeclCache.has(pascalName)) {
1020
- return _componentDeclCache.get(pascalName) ?? '';
1019
+ function readComponentDeclarations(pascalName, options = {}) {
1020
+ const includeTypes = options.includeTypes === true;
1021
+ const cacheKey = `${pascalName}:${includeTypes ? 'with-types' : 'index-only'}`;
1022
+ if (_componentDeclCache.has(cacheKey)) {
1023
+ return _componentDeclCache.get(cacheKey) ?? '';
1021
1024
  }
1022
1025
  let contents = '';
1023
1026
  const coreRoot = resolveCoreRoot();
1024
1027
  if (coreRoot) {
1025
- const candidates = [
1026
- path.join(coreRoot, 'dist', pascalName, 'index.d.ts'),
1027
- path.join(coreRoot, 'src', pascalName, 'index.ts'),
1028
+ const candidateSets = [
1029
+ [path.join(coreRoot, 'dist', pascalName, 'index.d.ts')],
1030
+ [path.join(coreRoot, 'src', pascalName, 'index.ts')],
1028
1031
  ];
1029
- for (const file of candidates) {
1030
- try {
1031
- if (fs.existsSync(file)) {
1032
- contents = fs.readFileSync(file, 'utf-8');
1033
- break;
1032
+ if (includeTypes) {
1033
+ candidateSets[0].push(
1034
+ path.join(coreRoot, 'dist', pascalName, 'types.d.ts'),
1035
+ );
1036
+ candidateSets[1].push(path.join(coreRoot, 'src', pascalName, 'types.ts'));
1037
+ }
1038
+ for (const files of candidateSets) {
1039
+ if (fs.existsSync(files[0])) {
1040
+ for (const file of files) {
1041
+ try {
1042
+ if (fs.existsSync(file)) {
1043
+ contents += fs.readFileSync(file, 'utf-8') + '\n';
1044
+ }
1045
+ } catch {
1046
+ // ignore
1047
+ }
1034
1048
  }
1035
- } catch {
1036
- // ignore and try the next candidate
1049
+ if (contents) break;
1037
1050
  }
1038
1051
  }
1039
1052
  }
1040
- _componentDeclCache.set(pascalName, contents);
1053
+ _componentDeclCache.set(cacheKey, contents);
1041
1054
  return contents;
1042
1055
  }
1043
1056
 
@@ -1163,10 +1176,11 @@ async function resolveAugmentationTargetCandidates(componentName) {
1163
1176
  * re-exported) as a type/interface.
1164
1177
  * @param {string} pascalName
1165
1178
  * @param {string} interfaceName
1179
+ * @param {{includeTypes?: boolean}} [options]
1166
1180
  * @returns {boolean}
1167
1181
  */
1168
- function componentHasAugmentableInterface(pascalName, interfaceName) {
1169
- const decl = readComponentDeclarations(pascalName);
1182
+ function componentHasAugmentableInterface(pascalName, interfaceName, options) {
1183
+ const decl = readComponentDeclarations(pascalName, options);
1170
1184
  if (!decl) return false;
1171
1185
  // Require an actual interface declaration in this public subpath, not just a
1172
1186
  // type re-export. Module augmentation only widens consumers that import the
@@ -1199,6 +1213,56 @@ function isComponentValueAugmentationPoint(pascalName, interfaceName) {
1199
1213
  );
1200
1214
  }
1201
1215
 
1216
+ /**
1217
+ * Extension points whose public module and interface do not follow the usual
1218
+ * `<Component><Prop>Map` convention. TextType reads CustomTextTypes from the
1219
+ * theme module, so both classification and declaration emission must resolve
1220
+ * this same public augmentation point.
1221
+ *
1222
+ * @type {Record<string, {moduleName: string, interfaceName: string, includeTypes?: boolean}>}
1223
+ */
1224
+ const AUGMENTATION_OVERRIDES = {
1225
+ 'text.type': {
1226
+ moduleName: 'theme',
1227
+ interfaceName: 'CustomTextTypes',
1228
+ includeTypes: true,
1229
+ },
1230
+ };
1231
+
1232
+ /**
1233
+ * Resolve the public module/interface that can widen a component prop value.
1234
+ * @param {string} component
1235
+ * @param {string} prop
1236
+ * @returns {Promise<{moduleName: string, interfaceName: string}|null>}
1237
+ */
1238
+ async function resolveAugmentationTarget(component, prop) {
1239
+ const override = AUGMENTATION_OVERRIDES[`${component}.${prop}`];
1240
+ if (override) {
1241
+ return componentHasAugmentableInterface(
1242
+ override.moduleName,
1243
+ override.interfaceName,
1244
+ {includeTypes: override.includeTypes},
1245
+ )
1246
+ ? {moduleName: override.moduleName, interfaceName: override.interfaceName}
1247
+ : null;
1248
+ }
1249
+
1250
+ const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
1251
+ const target = (await resolveAugmentationTargetCandidates(component)).find(
1252
+ candidate =>
1253
+ isComponentValueAugmentationPoint(
1254
+ candidate.moduleName,
1255
+ `${candidate.interfacePrefix}${propPascal}Map`,
1256
+ ),
1257
+ );
1258
+ return target
1259
+ ? {
1260
+ moduleName: target.moduleName,
1261
+ interfaceName: `${target.interfacePrefix}${propPascal}Map`,
1262
+ }
1263
+ : null;
1264
+ }
1265
+
1202
1266
  /**
1203
1267
  * Adaptation values from resolved runtime rules, raw input, or normalized built
1204
1268
  * metadata. Built modules intentionally omit `__adaptationRules`, so every CLI
@@ -1503,14 +1567,7 @@ async function classifyComponentValue(component, prop, value) {
1503
1567
  return 'builtin';
1504
1568
  }
1505
1569
 
1506
- const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
1507
- const target = (await resolveAugmentationTargetCandidates(component)).find(
1508
- candidate =>
1509
- isComponentValueAugmentationPoint(
1510
- candidate.moduleName,
1511
- `${candidate.interfacePrefix}${propPascal}Map`,
1512
- ),
1513
- );
1570
+ const target = await resolveAugmentationTarget(component, prop);
1514
1571
  return target ? 'enrollment' : 'unresolved';
1515
1572
  }
1516
1573
 
@@ -1668,15 +1725,7 @@ async function generateVariantDeclarationsAsync(themeDef) {
1668
1725
  for (const [prop, values] of Object.entries(props)) {
1669
1726
  if (values.size === 0) continue;
1670
1727
 
1671
- const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
1672
- const target = (
1673
- await resolveAugmentationTargetCandidates(component)
1674
- ).find(candidate =>
1675
- isComponentValueAugmentationPoint(
1676
- candidate.moduleName,
1677
- `${candidate.interfacePrefix}${propPascal}Map`,
1678
- ),
1679
- );
1728
+ const target = await resolveAugmentationTarget(component, prop);
1680
1729
 
1681
1730
  // Resolve the augmentation point again to name it. Classification has
1682
1731
  // already established that one exists (that is what `enrollment` means),
@@ -1687,7 +1736,7 @@ async function generateVariantDeclarationsAsync(themeDef) {
1687
1736
  if (!target) continue;
1688
1737
 
1689
1738
  const modulePath = `@astryxdesign/core/${target.moduleName}`;
1690
- const interfaceName = `${target.interfacePrefix}${propPascal}Map`;
1739
+ const {interfaceName} = target;
1691
1740
 
1692
1741
  sections.push(`declare module '${modulePath}' {`);
1693
1742
  sections.push(` interface ${interfaceName} {`);
@@ -1924,7 +1973,6 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1924
1973
  // A frozen require(esm) namespace cannot be patched, so retain that gap and
1925
1974
  // let the selected lineage decide whether it matters.
1926
1975
  const commonJsPatch = interception.patchCommonJs(filePath);
1927
- degraded.commonJs = !commonJsPatch.covered;
1928
1976
  try {
1929
1977
  try {
1930
1978
  mod = jiti(filePath);
@@ -1946,6 +1994,8 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1946
1994
  });
1947
1995
  }
1948
1996
  } finally {
1997
+ // Read after the load: the root is wrapped when the load requires it.
1998
+ degraded.commonJs = !commonJsPatch.covered;
1949
1999
  commonJsPatch.undo();
1950
2000
  }
1951
2001
  } else {
@@ -2120,7 +2170,7 @@ export async function validateThemePrivateInputs(
2120
2170
  * import { defaultIconRegistry } from './icons';
2121
2171
  * icons: defaultIconRegistry,
2122
2172
  * @param {string} filePath
2123
- * @param {'icons' | 'indicators'} field
2173
+ * @param {'icons' | 'indicators' | 'componentIcons'} field
2124
2174
  * @returns {{exportName: string, importPath: string} | null}
2125
2175
  */
2126
2176
  function extractRegistryInfo(filePath, field) {
@@ -2198,6 +2248,83 @@ function iconNodesExpression(entries, entriesName, nodesName) {
2198
2248
  })()`;
2199
2249
  }
2200
2250
 
2251
+ /**
2252
+ * A theme's component icon slot values: a theme from defineTheme keeps them
2253
+ * in `__componentIcons` when any is a function (its `componentIcons` is the
2254
+ * static view); otherwise `componentIcons` holds them.
2255
+ * @param {any} theme
2256
+ * @returns {Record<string, unknown> | undefined}
2257
+ */
2258
+ function themeComponentIcons(theme) {
2259
+ return theme?.__componentIcons ?? theme?.componentIcons;
2260
+ }
2261
+
2262
+ /**
2263
+ * The generated function that merges a theme's own slot values over its
2264
+ * base's, as `defineTheme` does: an own slot replaces the inherited one whole,
2265
+ * and an `undefined` own slot leaves it in place. It reads no global.
2266
+ * @param {string} name - A reserved function name.
2267
+ * @returns {string}
2268
+ */
2269
+ function componentIconMergeFunction(name) {
2270
+ return `function ${name}(base, own) {
2271
+ const merged = {...base};
2272
+ for (const slot in own) {
2273
+ if (own[slot] !== undefined) merged[slot] = own[slot];
2274
+ }
2275
+ return merged;
2276
+ }
2277
+ `;
2278
+ }
2279
+
2280
+ /**
2281
+ * The generated code that reads the static view of a theme's slot values:
2282
+ * every slot without a function. Like the icon node view, it reads no global
2283
+ * and declares only reserved local names.
2284
+ * @param {string} valuesName - A reserved local name bound to the values.
2285
+ * @param {string} viewName - A reserved local name.
2286
+ * @returns {string}
2287
+ */
2288
+ function componentIconViewExpression(valuesName, viewName) {
2289
+ return `(() => {
2290
+ const ${viewName} = {};
2291
+ for (const slot in ${valuesName}) {
2292
+ const value = ${valuesName}[slot];
2293
+ if (value !== undefined && typeof value !== 'function') ${viewName}[slot] = value;
2294
+ }
2295
+ return ${viewName};
2296
+ })()`;
2297
+ }
2298
+
2299
+ /**
2300
+ * One import statement for a carried registry or slot binding. Ordinary named
2301
+ * imports stay byte-compatible; paths with quotes or escapes are encoded, and
2302
+ * default, namespace, and aliased bindings are kept.
2303
+ * @param {{importPath: string, importedName: string, localName: string}} binding
2304
+ * @param {string} [specifier] - Replaces the import path when given.
2305
+ * @returns {string}
2306
+ */
2307
+ function importStatement({importPath, importedName, localName}, specifier) {
2308
+ const source =
2309
+ specifier !== undefined
2310
+ ? JSON.stringify(specifier)
2311
+ : /['\\\r\n]/u.test(importPath)
2312
+ ? JSON.stringify(importPath)
2313
+ : `'${importPath}'`;
2314
+ const imported = /^[$\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(
2315
+ importedName,
2316
+ )
2317
+ ? importedName
2318
+ : JSON.stringify(importedName);
2319
+ const binding =
2320
+ importedName === 'default'
2321
+ ? localName
2322
+ : importedName === '*'
2323
+ ? `* as ${localName}`
2324
+ : `{ ${imported}${importedName === localName ? '' : ` as ${localName}`} }`;
2325
+ return `import ${binding} from ${source};\n`;
2326
+ }
2327
+
2201
2328
  /**
2202
2329
  * Generate a minimal JS module for a built theme.
2203
2330
  * Includes the theme name, marker, and re-exports the icon registry.
@@ -2224,10 +2351,15 @@ function iconNodesExpression(entries, entriesName, nodesName) {
2224
2351
  * renders, and the theme's `icons` and the re-exported registry are the node
2225
2352
  * view, each function read at `{size: 'md'}` as `DefinedTheme['icons']` is.
2226
2353
  *
2354
+ * Component icon slots without a function are written as JSON. When a slot
2355
+ * value is a function, the module keeps the values, carried through
2356
+ * `componentIconInfo`'s imports, as `__componentIcons`, and the theme's
2357
+ * `componentIcons` is the static view, as `DefinedTheme['componentIcons']` is.
2358
+ *
2227
2359
  * @param {any} themeDef
2228
2360
  * @param {import('./icon-imports.mjs').IconImports | null} iconInfo
2229
2361
  * @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
2230
- * @param {{themeBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
2362
+ * @param {{themeBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean, componentIconInfo?: {imports: import('./icon-imports.mjs').IconImports['imports'], expression: string, mergeName?: string} | null}} [moduleOptions]
2231
2363
  * @returns {string}
2232
2364
  */
2233
2365
  function generateBuiltModule(
@@ -2240,32 +2372,17 @@ function generateBuiltModule(
2240
2372
  moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
2241
2373
  const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;
2242
2374
  const exportIcons = moduleOptions.exportIcons ?? true;
2243
- // Keep ordinary direct named imports byte-compatible, while encoding paths
2244
- // with quotes/escapes and retaining default, namespace, and aliased bindings.
2245
2375
  const iconImport = (iconInfo?.imports ?? [])
2246
- .map(({importPath, importedName, localName}) => {
2247
- const overridden =
2376
+ .map(binding =>
2377
+ importStatement(
2378
+ binding,
2248
2379
  iconsSpecifier !== undefined &&
2249
- importPath === iconInfo?.iconsSpecifierImportPath &&
2250
- localName === iconInfo?.iconsSpecifierLocalName;
2251
- const specifier = overridden
2252
- ? JSON.stringify(iconsSpecifier)
2253
- : /['\\\r\n]/u.test(importPath)
2254
- ? JSON.stringify(importPath)
2255
- : `'${importPath}'`;
2256
- const imported = /^[$\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(
2257
- importedName,
2258
- )
2259
- ? importedName
2260
- : JSON.stringify(importedName);
2261
- const binding =
2262
- importedName === 'default'
2263
- ? localName
2264
- : importedName === '*'
2265
- ? `* as ${localName}`
2266
- : `{ ${imported}${importedName === localName ? '' : ` as ${localName}`} }`;
2267
- return `import ${binding} from ${specifier};\n`;
2268
- })
2380
+ binding.importPath === iconInfo?.iconsSpecifierImportPath &&
2381
+ binding.localName === iconInfo?.iconsSpecifierLocalName
2382
+ ? iconsSpecifier
2383
+ : undefined,
2384
+ ),
2385
+ )
2269
2386
  .join('');
2270
2387
  const iconDeclaration =
2271
2388
  iconInfo && iconInfo.expression !== iconInfo.exportName
@@ -2295,6 +2412,29 @@ function generateBuiltModule(
2295
2412
  : `\nexport { ${iconInfo.exportName} };\n`
2296
2413
  : '';
2297
2414
 
2415
+ const componentIconValues = themeComponentIcons(themeDef);
2416
+ const componentIconInfo = moduleOptions.componentIconInfo ?? null;
2417
+ const carriesSlotFunctions = hasFunctionIconEntry(componentIconValues);
2418
+ if (carriesSlotFunctions && !componentIconInfo) {
2419
+ throw new AstryxError(
2420
+ `Theme "${themeDef.name}" has componentIcons slot functions that the build cannot carry. ` +
2421
+ 'Import the slot functions from their own module into the theme file.',
2422
+ undefined,
2423
+ ERROR_CODES.ERR_THEME_INVALID,
2424
+ );
2425
+ }
2426
+ const componentIconValuesName = `${themeBinding}ComponentIconValues`;
2427
+ const componentIconPrelude =
2428
+ carriesSlotFunctions && componentIconInfo
2429
+ ? componentIconInfo.imports
2430
+ .map(binding => importStatement(binding))
2431
+ .join('') +
2432
+ (componentIconInfo.mergeName
2433
+ ? componentIconMergeFunction(componentIconInfo.mergeName)
2434
+ : '') +
2435
+ `const ${componentIconValuesName} = ${componentIconInfo.expression};\n`
2436
+ : '';
2437
+
2298
2438
  // Resolve token values — tuples become light-dark() strings
2299
2439
  /** @type {Record<string, unknown>} */
2300
2440
  const resolvedTokens = {};
@@ -2365,9 +2505,18 @@ function generateBuiltModule(
2365
2505
  list ?? [],
2366
2506
  ]),
2367
2507
  ),
2368
- );
2508
+ ) +
2509
+ (carriesSlotFunctions
2510
+ ? ` componentIcons: ${componentIconViewExpression(
2511
+ componentIconValuesName,
2512
+ `${themeBinding}ComponentIconView`,
2513
+ )
2514
+ .split('\n')
2515
+ .map((line, i) => (i === 0 ? line : ' ' + line))
2516
+ .join('\n')},\n __componentIcons: ${componentIconValuesName},\n`
2517
+ : serializeField('componentIcons', componentIconValues, true));
2369
2518
 
2370
- return `${iconImport}${iconDeclaration}${iconNodesDeclaration}/**
2519
+ return `${iconImport}${componentIconPrelude}${iconDeclaration}${iconNodesDeclaration}/**
2371
2520
  * ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
2372
2521
  * Import the CSS file alongside this module:
2373
2522
  *
@@ -2844,12 +2993,29 @@ async function themeBuildInternal(
2844
2993
  let themeExportName;
2845
2994
  /** Paths through the load that interception could not fully observe. */
2846
2995
  let loadDegradation;
2996
+ /**
2997
+ * The theme file's bytes as loaded: read before and after the load, and the
2998
+ * registry scan below reads these rather than the file again. An editor's
2999
+ * in-place save truncates before it writes, so a later read can find an
3000
+ * empty file the load never saw; a file that changed while it loaded is not
3001
+ * built from.
3002
+ * @type {string}
3003
+ */
3004
+ let themeSource;
2847
3005
  try {
3006
+ const before = fs.readFileSync(filePath, 'utf8');
2848
3007
  const loaded = await extractThemeDefinition(
2849
3008
  filePath,
2850
3009
  interception,
2851
3010
  options.__familyLoader,
2852
3011
  );
3012
+ const after = fs.readFileSync(filePath, 'utf8');
3013
+ if (before !== after || before === '') {
3014
+ throw new Error(
3015
+ `${filePath} changed while it was loading. Build again once it is saved.`,
3016
+ );
3017
+ }
3018
+ themeSource = before;
2853
3019
  themeDef = loaded.theme;
2854
3020
  themeExportName = loaded.exportName;
2855
3021
  loadDegradation = loaded.degraded;
@@ -2938,10 +3104,20 @@ async function themeBuildInternal(
2938
3104
  ]
2939
3105
  : []),
2940
3106
  ];
3107
+ // Names the slot values, their static view, and their merge function take
3108
+ // in the built module.
3109
+ const componentIconNames = [
3110
+ `${toIdentifier(themeDef.name)}ThemeComponentIconValues`,
3111
+ `${toIdentifier(themeDef.name)}ThemeComponentIconView`,
3112
+ `${toIdentifier(themeDef.name)}ThemeMergeComponentIcons`,
3113
+ ];
2941
3114
  const iconResolution = {
2942
- readSource: (/** @type {string} */ file) => fs.readFileSync(file, 'utf8'),
3115
+ readSource: (/** @type {string} */ file) =>
3116
+ path.resolve(file) === path.resolve(filePath)
3117
+ ? themeSource
3118
+ : fs.readFileSync(file, 'utf8'),
2943
3119
  resolveModule: resolveThemeModule,
2944
- reservedNames: reservedNames(functionEntries),
3120
+ reservedNames: [...reservedNames(functionEntries), ...componentIconNames],
2945
3121
  functionEntries,
2946
3122
  rawInput: 'extends' in themeDef,
2947
3123
  hasIcons:
@@ -2951,6 +3127,8 @@ async function themeBuildInternal(
2951
3127
  let iconInfo = standaloneIcons
2952
3128
  ? await resolveIconImports(filePath, themeExportName, iconResolution)
2953
3129
  : null;
3130
+ /** @type {import('./icon-imports.mjs').IconImports | null} */
3131
+ let componentIconInfo = null;
2954
3132
 
2955
3133
  // Validate component overrides
2956
3134
  const warnings = await validateComponentOverrides(themeDef);
@@ -3073,7 +3251,10 @@ async function themeBuildInternal(
3073
3251
  ...iconResolution,
3074
3252
  hasIcons: true,
3075
3253
  functionEntries: resolvedFunctionEntries,
3076
- reservedNames: reservedNames(resolvedFunctionEntries),
3254
+ reservedNames: [
3255
+ ...reservedNames(resolvedFunctionEntries),
3256
+ ...componentIconNames,
3257
+ ],
3077
3258
  });
3078
3259
  }
3079
3260
  // An opaque package base can legitimately have no icons. Its .icons
@@ -3098,6 +3279,27 @@ async function themeBuildInternal(
3098
3279
  );
3099
3280
  }
3100
3281
 
3282
+ // A slot function cannot be serialized, so the module imports it from
3283
+ // where the theme source does. Static slot values are written as JSON.
3284
+ if (
3285
+ standaloneIcons &&
3286
+ hasFunctionIconEntry(themeComponentIcons(resolvedTheme))
3287
+ ) {
3288
+ componentIconInfo = await resolveIconImports(filePath, themeExportName, {
3289
+ ...iconResolution,
3290
+ field: 'componentIcons',
3291
+ mergeName: `${toIdentifier(themeDef.name)}ThemeMergeComponentIcons`,
3292
+ hasIcons: true,
3293
+ functionEntries: true,
3294
+ reservedNames: [
3295
+ ...reservedNames(true),
3296
+ ...componentIconNames,
3297
+ ...(iconInfo?.imports.map(binding => binding.localName) ?? []),
3298
+ ...(iconInfo ? [iconInfo.exportName] : []),
3299
+ ],
3300
+ });
3301
+ }
3302
+
3101
3303
  // Cores that predate adaptations can still resolve typography, color,
3102
3304
  // radius, and motion into root tokens, but they do not retain the raw axis
3103
3305
  // inputs. Keep the effective metadata captured from the same defineTheme
@@ -3327,13 +3529,17 @@ async function themeBuildInternal(
3327
3529
  const cssDtsContent =
3328
3530
  generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
3329
3531
  'export {};\n';
3330
- const jsContent =
3331
- generatedHeader(sourceRelative, 'js', buildCommand, versions) +
3332
- generateBuiltModule(
3333
- resolvedTheme || themeDef,
3334
- iconInfo,
3335
- options.iconsSpecifier,
3336
- );
3532
+ // A family member's module is generated by themeBuildFamily, which carries
3533
+ // its registries and slot functions through the family's own imports.
3534
+ const jsContent = options.__prepareFamily
3535
+ ? ''
3536
+ : generatedHeader(sourceRelative, 'js', buildCommand, versions) +
3537
+ generateBuiltModule(
3538
+ resolvedTheme || themeDef,
3539
+ iconInfo,
3540
+ options.iconsSpecifier,
3541
+ {componentIconInfo},
3542
+ );
3337
3543
  const dtsContent =
3338
3544
  generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
3339
3545
  generateBuiltTypes(resolvedTheme || themeDef, iconInfo, variantsFileName);
@@ -3356,6 +3562,7 @@ async function themeBuildInternal(
3356
3562
  sourceParent,
3357
3563
  iconInfo: extractRegistryInfo(filePath, 'icons'),
3358
3564
  indicatorInfo: extractRegistryInfo(filePath, 'indicators'),
3565
+ componentIconInfo: extractRegistryInfo(filePath, 'componentIcons'),
3359
3566
  variantDecl,
3360
3567
  css: cssPlan,
3361
3568
  versions,
@@ -3675,6 +3882,81 @@ function allocateFamilyBindings(members) {
3675
3882
  const used = new Map();
3676
3883
  return new Map(members.map(member => { const base = familyThemeBinding(member.theme.name), count = used.get(base) ?? 0; used.set(base, count + 1); return [member.theme.name, count === 0 ? base : `${base}${count + 1}`]; }));
3677
3884
  }
3885
+ /**
3886
+ * How a family member's module carries slot functions: its parent's values,
3887
+ * then its own. A member supplies its own slot functions through a named
3888
+ * import of its whole `componentIcons` map, merged as `defineTheme` merges;
3889
+ * own static values are written as JSON. Null when the member has no slot
3890
+ * function, so its static values are written as JSON alone.
3891
+ * @param {any} member
3892
+ * @param {any} parent - The member's parent in the family, if any.
3893
+ * @param {{themeBinding: string | undefined, parentBinding: string | null | undefined, outDir: string, registryImports: Array<{specifier: string, exportName: string}>, expression: (own: string | null, inherited: string | null) => string | undefined}} context
3894
+ * @returns {{imports: Array<{importPath: string, importedName: string, localName: string}>, expression: string, mergeName?: string} | null}
3895
+ */
3896
+ function familyComponentIcons(member, parent, context) {
3897
+ const values = themeComponentIcons(member.theme);
3898
+ if (!hasFunctionIconEntry(values)) return null;
3899
+ const inheritedValues = themeComponentIcons(parent?.theme);
3900
+ const inherited =
3901
+ context.parentBinding && inheritedValues
3902
+ ? `${context.parentBinding}.${hasFunctionIconEntry(inheritedValues) ? '__componentIcons' : 'componentIcons'}`
3903
+ : null;
3904
+ /** @type {Array<{importPath: string, importedName: string, localName: string}>} */
3905
+ const imports = [];
3906
+ let own = null;
3907
+ const binding =
3908
+ context.themeBinding ?? `${toIdentifier(member.theme.name)}Theme`;
3909
+ const info = member.componentIconInfo;
3910
+ if (info) {
3911
+ const input = familyRegistryInput(
3912
+ info,
3913
+ member.filePath,
3914
+ context.outDir,
3915
+ undefined,
3916
+ );
3917
+ const importPath = input.specifier ?? info.importPath;
3918
+ own = `${binding}ComponentIconSource`;
3919
+ imports.push({importPath, importedName: info.exportName, localName: own});
3920
+ context.registryImports.push({
3921
+ specifier: importPath,
3922
+ exportName: info.exportName,
3923
+ });
3924
+ } else {
3925
+ // Without an import, a member's own slots are the ones that differ from
3926
+ // its parent's; they must all be static.
3927
+ /** @type {Record<string, unknown>} */
3928
+ const ownValues = {};
3929
+ for (const [slot, value] of Object.entries(values ?? {})) {
3930
+ if (
3931
+ inheritedValues &&
3932
+ Object.hasOwn(inheritedValues, slot) &&
3933
+ inheritedValues[slot] === value
3934
+ )
3935
+ continue;
3936
+ if (typeof value === 'function') {
3937
+ throw new AstryxError(
3938
+ `Theme "${member.theme.name}" must supply its componentIcons slot functions through a named import of its whole componentIcons map for family output.`,
3939
+ undefined,
3940
+ ERROR_CODES.ERR_THEME_INVALID,
3941
+ );
3942
+ }
3943
+ ownValues[slot] = value;
3944
+ }
3945
+ if (Object.keys(ownValues).length > 0) own = JSON.stringify(ownValues);
3946
+ }
3947
+ if (info) {
3948
+ // An imported map can hold an `undefined` slot: it keeps the parent's,
3949
+ // and a root drops it, as `defineTheme` does.
3950
+ const mergeName = `${binding}MergeComponentIcons`;
3951
+ return {
3952
+ imports,
3953
+ expression: `${mergeName}(${inherited ?? '{}'}, ${own})`,
3954
+ mergeName,
3955
+ };
3956
+ }
3957
+ const expression = context.expression(own, inherited);
3958
+ return expression ? {imports, expression} : null;
3959
+ }
3678
3960
  /** Rebase a scraped relative registry import to the aggregate module. @param {any} info @param {string} filePath @param {string} outDir @param {string | undefined} override */
3679
3961
  // prettier-ignore
3680
3962
  function familyRegistryInput(info, filePath, outDir, override) {
@@ -3887,6 +4169,13 @@ export async function themeBuildFamily(
3887
4169
  // rebased or overridden specifier replaces the scraped one.
3888
4170
  // prettier-ignore
3889
4171
  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;
4172
+ const componentIconInfo = familyComponentIcons(member, parent, {
4173
+ themeBinding,
4174
+ parentBinding,
4175
+ outDir,
4176
+ registryImports,
4177
+ expression,
4178
+ });
3890
4179
  return (
3891
4180
  indicatorImport +
3892
4181
  generateBuiltModule(member.theme, iconImports, icon.specifier, {
@@ -3895,6 +4184,7 @@ export async function themeBuildFamily(
3895
4184
  indicatorsExpression: expression(ownIndicators, inheritedIndicators),
3896
4185
  artifactBaseName: baseName,
3897
4186
  exportIcons: false,
4187
+ componentIconInfo,
3898
4188
  })
3899
4189
  );
3900
4190
  })