@astryxdesign/cli 0.7.15-canary.gea16e8d → 0.7.15

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 (134) hide show
  1. package/CHANGELOG.md +353 -3
  2. package/README.md +63 -63
  3. package/api/build/_adapter.d.mts +4 -0
  4. package/api/build/_adapter.mjs +28 -2
  5. package/api/build/blocks/blocks.d.mts +10 -1
  6. package/api/build/blocks/blocks.mjs +84 -7
  7. package/api/build/build.mjs +6 -1
  8. package/api/build/tree.d.mts +4 -0
  9. package/api/build/tree.mjs +9 -2
  10. package/api/doctor/_adapter.d.mts +2 -1
  11. package/api/doctor/_adapter.mjs +6 -1
  12. package/api/doctor/doctor.mjs +2 -2
  13. package/api/doctor/theme-checks.mjs +56 -21
  14. package/api/integration/add-helpers.mjs +5 -0
  15. package/api/integration/add-theme.mjs +15 -110
  16. package/api/integration/validate-integration.mjs +17 -3
  17. package/api/integration/validateIntegration.doc.mjs +1 -1
  18. package/api/theme/_adapter.d.mts +37 -5
  19. package/api/theme/_adapter.mjs +363 -50
  20. package/api/theme/_fork.d.mts +90 -0
  21. package/api/theme/_fork.mjs +246 -0
  22. package/api/theme/build/build.d.mts +25 -1
  23. package/api/theme/build/build.mjs +352 -41
  24. package/api/theme/eject/eject.mjs +36 -15
  25. package/api/theme/list/list.mjs +3 -6
  26. package/api/theme/palette/generate/generator.d.mts +13 -0
  27. package/api/theme/palette/generate/generator.mjs +32 -2
  28. package/api/theme/targets/targets.mjs +10 -3
  29. package/api/theme/template/template.mjs +48 -2
  30. package/api/theme/theme.type.d.mts +8 -0
  31. package/api/theme/theme.type.mjs +5 -1
  32. package/api/theme/themeBuild.doc.mjs +2 -2
  33. package/api/theme/themeRemove.doc.mjs +5 -2
  34. package/api/theme/themeTemplate.doc.mjs +2 -2
  35. package/api/theme/themeUse.doc.mjs +8 -2
  36. package/api/theme-edit/_adapter.mjs +157 -36
  37. package/api/theme-edit/_catalog.d.mts +1 -6
  38. package/api/theme-edit/_catalog.mjs +5 -268
  39. package/api/theme-edit/_check.d.mts +3 -1
  40. package/api/theme-edit/_check.mjs +733 -308
  41. package/api/theme-edit/_color.d.mts +19 -0
  42. package/api/theme-edit/_color.mjs +277 -33
  43. package/api/theme-edit/_compiler.d.mts +1 -0
  44. package/api/theme-edit/_compiler.mjs +25 -0
  45. package/api/theme-edit/_context.d.mts +2 -0
  46. package/api/theme-edit/_context.mjs +83 -9
  47. package/api/theme-edit/_css.d.mts +84 -0
  48. package/api/theme-edit/_css.mjs +700 -0
  49. package/api/theme-edit/_edit.mjs +370 -85
  50. package/api/theme-edit/_how-commands.d.mts +5 -0
  51. package/api/theme-edit/_how-commands.mjs +20 -13
  52. package/api/theme-edit/_how-question.d.mts +29 -0
  53. package/api/theme-edit/_how-question.mjs +1573 -182
  54. package/api/theme-edit/_how.mjs +306 -22
  55. package/api/theme-edit/_overview.mjs +2 -7
  56. package/api/theme-edit/_palette.d.mts +27 -5
  57. package/api/theme-edit/_palette.mjs +231 -97
  58. package/api/theme-edit/_parts.d.mts +42 -10
  59. package/api/theme-edit/_parts.mjs +224 -69
  60. package/api/theme-edit/_preview-app.d.mts +8 -0
  61. package/api/theme-edit/_preview-app.mjs +549 -96
  62. package/api/theme-edit/_preview.d.mts +7 -16
  63. package/api/theme-edit/_preview.mjs +77 -84
  64. package/api/theme-edit/_project.d.mts +20 -1
  65. package/api/theme-edit/_project.mjs +43 -13
  66. package/api/theme-edit/_settings.d.mts +96 -20
  67. package/api/theme-edit/_settings.mjs +646 -141
  68. package/api/theme-edit/_tables.d.mts +18 -12
  69. package/api/theme-edit/_tables.mjs +144 -147
  70. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  71. package/api/theme-edit/theme-edit.type.mjs +3 -1
  72. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  73. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  74. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  75. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  76. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  77. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  78. package/assets/docs/tree/checks.doc.mjs +22 -1
  79. package/assets/docs/tree/publishing.doc.mjs +1 -0
  80. package/assets/docs.generated.json +2 -2
  81. package/assets/self-audit.generated.json +1 -1
  82. package/authoring/integration/integration.doc.mjs +8 -0
  83. package/authoring/integration/schema.d.mts +8 -0
  84. package/authoring/integration/schema.mjs +1 -0
  85. package/authoring/integration/type.ts +9 -0
  86. package/clients/cli/build-id.generated.json +1 -1
  87. package/clients/cli/commands/experimental/index.mjs +10 -10
  88. package/clients/cli/commands/experimental/theme.mjs +22 -3
  89. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  90. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  91. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  92. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  93. package/clients/cli/commands/integration.mjs +8 -0
  94. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  95. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  96. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  97. package/clients/cli/commands/theme.mjs +325 -48
  98. package/clients/cli/index.mjs +18 -3
  99. package/clients/cli/lib/cli-error.mjs +118 -3
  100. package/clients/cli/manifest.generated.json +1 -1
  101. package/foundation/config/project.mjs +34 -8
  102. package/foundation/config/theme-state.d.mts +16 -0
  103. package/foundation/config/theme-state.mjs +84 -13
  104. package/foundation/discovery/template-needs.d.mts +13 -0
  105. package/foundation/discovery/template-needs.mjs +30 -15
  106. package/foundation/discovery/theme-discovery.mjs +14 -2
  107. package/foundation/discovery/theme-imports.d.mts +16 -0
  108. package/foundation/discovery/theme-imports.mjs +30 -2
  109. package/foundation/doc-compiler/import.mjs +10 -4
  110. package/foundation/fs/gather-cache.mjs +82 -23
  111. package/foundation/fs/jiti-cache.d.mts +21 -0
  112. package/foundation/fs/jiti-cache.mjs +66 -0
  113. package/foundation/fs/module-loader.mjs +7 -2
  114. package/foundation/integrations/autolink.d.mts +1 -24
  115. package/foundation/integrations/autolink.mjs +7 -60
  116. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  117. package/foundation/integrations/declared-dependencies.mjs +73 -0
  118. package/foundation/integrations/integrations.d.mts +8 -0
  119. package/foundation/integrations/integrations.mjs +4 -0
  120. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  121. package/foundation/integrations/may-have-integrations.mjs +47 -0
  122. package/foundation/integrations/validate-contributions.d.mts +62 -1
  123. package/foundation/integrations/validate-contributions.mjs +452 -29
  124. package/foundation/release/cache.d.mts +21 -2
  125. package/foundation/release/cache.mjs +48 -8
  126. package/foundation/release/folder-lock.d.mts +7 -0
  127. package/foundation/release/folder-lock.mjs +60 -26
  128. package/foundation/release/lock-lease.d.mts +2 -1
  129. package/foundation/release/lock-lease.mjs +7 -2
  130. package/foundation/response/error-codes.doc.mjs +1 -1
  131. package/foundation/response/response-types.doc.mjs +5 -5
  132. package/package.json +6 -6
  133. package/api/theme-edit/_css-properties.d.mts +0 -10
  134. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -100,6 +100,10 @@ import {
100
100
  formatFontLoadingHelp,
101
101
  } from './font-warning.mjs';
102
102
  import {interceptCore} from './core-interception.mjs';
103
+ import {
104
+ installCommandFor,
105
+ parsedSpecifiers,
106
+ } from '../../../foundation/discovery/template-needs.mjs';
103
107
  import {generateFamilyCSS, resolveThemeFamily} from './family.mjs';
104
108
  import {resolveIconImports} from './icon-imports.mjs';
105
109
 
@@ -591,6 +595,72 @@ function rebuildLine(command, words) {
591
595
  return command.replace(/\btheme build\b/, `${words.group} ${words.build}`);
592
596
  }
593
597
 
598
+ /**
599
+ * The folder a build header names paths from: the project root (nearest
600
+ * package.json) of the outputs' folder, or `cwd` outside any project.
601
+ * @param {string} outDir
602
+ * @param {string} cwd
603
+ */
604
+ function headerRoot(outDir, cwd) {
605
+ return findPackageRoot(outDir) ?? path.resolve(cwd);
606
+ }
607
+
608
+ /**
609
+ * Whether a build refuses to replace, at a path `--out` names, the output of
610
+ * another theme source that still exists. False makes it warn and replace.
611
+ */
612
+ const OUT_REFUSES_OTHER_SOURCE = false;
613
+
614
+ /**
615
+ * Where a source name in a build header may point. A header names its source
616
+ * from the outputs' project root; older CLIs named it from the folder the
617
+ * build ran in, which is the output's folder or one above it, up to a
618
+ * monorepo root above the project. The project root comes first, then the
619
+ * output's folder and each folder above it.
620
+ * @param {string} outputFile absolute file the header is in
621
+ * @param {string} name the name the header gives
622
+ * @param {string} cwd
623
+ * @returns {string[]} absolute candidates, without repeats
624
+ */
625
+ function headerSourceCandidates(outputFile, name, cwd) {
626
+ const outDir = path.dirname(path.resolve(outputFile));
627
+ const candidates = [path.resolve(headerRoot(outDir, cwd), name)];
628
+ for (let dir = outDir; ; dir = path.dirname(dir)) {
629
+ candidates.push(path.resolve(dir, name));
630
+ if (path.dirname(dir) === dir) break;
631
+ }
632
+ return [...new Set(candidates)];
633
+ }
634
+
635
+ /**
636
+ * The file a build header's source name points at: the first candidate that
637
+ * exists, or the one from the project root when none does.
638
+ * @param {string} outputFile
639
+ * @param {string} name
640
+ * @param {string} cwd
641
+ */
642
+ function headerSourceFile(outputFile, name, cwd) {
643
+ const candidates = headerSourceCandidates(outputFile, name, cwd);
644
+ return (
645
+ candidates.find(file => {
646
+ try {
647
+ return fs.statSync(file).isFile();
648
+ } catch {
649
+ return false;
650
+ }
651
+ }) ?? candidates[0]
652
+ );
653
+ }
654
+
655
+ /**
656
+ * A path as a build header names it: relative to `base`, with `/`.
657
+ * @param {string} base
658
+ * @param {string} file absolute
659
+ */
660
+ function headerPath(base, file) {
661
+ return path.relative(base, file).split(path.sep).join('/');
662
+ }
663
+
594
664
  /**
595
665
  * Build a @generated attribution header for generated files.
596
666
  * @param {string} sourceFile - Relative path to the source theme file
@@ -623,12 +693,15 @@ function generatedHeader(sourceFile, lang = 'js', command, versions) {
623
693
  * the header and all real content — is compared verbatim. Used only by
624
694
  * `--check`: a differing command must NOT report a file as stale, but any real
625
695
  * content drift must. The `CLI:`/`Core:` provenance lines are deterministic
626
- * for a given toolchain, so they compare verbatim like real content.
696
+ * for a given toolchain, so they compare verbatim like real content. CRLF
697
+ * line endings read as LF.
627
698
  * @param {string} content
628
699
  * @returns {string}
629
700
  */
630
701
  export function normalizeThemeBuildForCompare(content) {
702
+ // A checkout may turn line endings into CRLF; the text is the same.
631
703
  return content
704
+ .replace(/\r\n/g, '\n')
632
705
  .split('\n')
633
706
  .filter(line => {
634
707
  const t = line.replace(/^\s*\*?\s?/, '');
@@ -846,6 +919,50 @@ function themeFilesIn(dir) {
846
919
  }
847
920
  }
848
921
 
922
+ /**
923
+ * The files a theme source is made of: the source and every local file it
924
+ * imports, directly or through other local files, read from their import
925
+ * statements. A watch rebuilds when any of them changes. Package imports and
926
+ * files that cannot be read are left out.
927
+ * @param {string} filePath absolute theme source
928
+ * @returns {string[]} absolute paths, the source first
929
+ */
930
+ export function themeSourceFiles(filePath) {
931
+ const seen = new Set([path.resolve(filePath)]);
932
+ const queue = [path.resolve(filePath)];
933
+ while (queue.length > 0 && seen.size < 500) {
934
+ const file = /** @type {string} */ (queue.shift());
935
+ let source;
936
+ try {
937
+ source = fs.readFileSync(file, 'utf8');
938
+ } catch {
939
+ continue;
940
+ }
941
+ for (const spec of parsedSpecifiers(source)) {
942
+ // Only relative and absolute imports are the theme's own files. A bare
943
+ // specifier names a package, which a workspace link can resolve to a
944
+ // real path outside node_modules.
945
+ if (!spec.startsWith('.') && !path.isAbsolute(spec)) continue;
946
+ // Resolved as the build resolves it.
947
+ let target;
948
+ try {
949
+ target = path.resolve(resolveThemeModule(spec, file));
950
+ } catch {
951
+ continue;
952
+ }
953
+ if (
954
+ target.split(path.sep).includes('node_modules') ||
955
+ seen.has(target) ||
956
+ !fs.existsSync(target)
957
+ )
958
+ continue;
959
+ seen.add(target);
960
+ queue.push(target);
961
+ }
962
+ }
963
+ return [...seen];
964
+ }
965
+
849
966
  /**
850
967
  * Theme sources a missing build input probably meant, relative to `cwd`: the
851
968
  * same path with `/` for `\`; or, for a bare theme name, the theme sources in
@@ -893,13 +1010,29 @@ function assertThemeSourceFile(filePath, cwd) {
893
1010
  const rel = (/** @type {string} */ file) => path.relative(cwd, file);
894
1011
  const sourceHead = fileHead(filePath);
895
1012
  if (sourceHead.includes(GENERATED_MARKER)) {
896
- const from = /Source: (.+)/.exec(sourceHead)?.[1]?.trim();
1013
+ const line = /Source: (.+)/.exec(sourceHead)?.[1]?.trim();
1014
+ // The header names its sources from the outputs' project root; the
1015
+ // command to build them names them from the working folder.
1016
+ const sources = line
1017
+ ? line.split(', ').map(name =>
1018
+ rel(headerSourceFile(filePath, name.trim(), cwd))
1019
+ .split(path.sep)
1020
+ .join('/'),
1021
+ )
1022
+ : [];
1023
+ const familyKey = /Command: .*--family-key (\S+)/.exec(sourceHead)?.[1];
1024
+ const build =
1025
+ sources.length > 1 && familyKey
1026
+ ? `theme build --family ${sources.map(shellWord).join(' ')} --family-key ${shellWord(familyKey)}`
1027
+ : sources.length > 0
1028
+ ? `theme build ${shellWord(sources[0])}`
1029
+ : null;
897
1030
  throw new AstryxError(
898
- `${rel(filePath)} is an output of \`theme build\`, not a theme source.${from ? ` It was built from ${from}.` : ''}`,
899
- from
1031
+ `${rel(filePath)} is an output of \`theme build\`, not a theme source.${sources.length > 0 ? ` It was built from ${sources.join(', ')}.` : ''}`,
1032
+ build
900
1033
  ? [
901
1034
  {
902
- name: formatCliCommand(`theme build ${shellWord(from)}`, cwd),
1035
+ name: formatCliCommand(build, cwd),
903
1036
  reason: 'build the theme source',
904
1037
  },
905
1038
  ]
@@ -929,9 +1062,10 @@ function assertThemeSourceFile(filePath, cwd) {
929
1062
  /**
930
1063
  * Refuse a build that would replace a file it does not own. A build never
931
1064
  * writes over its input, two of its own outputs at one path, or an output
932
- * another theme in the same run already wrote. With `refuseUnmarked`, it also
933
- * replaces only its own earlier outputs (they carry the `@generated` header)
934
- * and empty files, never another file such as `package.json` or app source.
1065
+ * another theme in the same run already wrote. With `refuseUnmarked` (a path
1066
+ * --out names), it also replaces only its own earlier outputs (their header
1067
+ * names this source, or a source that is gone) and empty files, never another
1068
+ * source's output or another file such as `package.json` or app source.
935
1069
  * @param {Array<{dest: string}>} writes
936
1070
  * @param {string} filePath the theme source
937
1071
  * @param {string} cwd
@@ -949,6 +1083,7 @@ function assertOutputsReplaceable(
949
1083
  const rel = (/** @type {string} */ file) => path.relative(cwd, file);
950
1084
  const sourceKey = outputKey(filePath);
951
1085
  const seen = new Set();
1086
+ let warnedOtherSource = false;
952
1087
  for (const write of writes) {
953
1088
  const key = outputKey(write.dest);
954
1089
  if (key === sourceKey) {
@@ -976,11 +1111,13 @@ function assertOutputsReplaceable(
976
1111
  seen.add(key);
977
1112
  const earlier = claimed?.get(key);
978
1113
  if (earlier !== undefined) {
979
- throw new AstryxError(
980
- `${earlier} already wrote ${rel(write.dest)} in this run. Two themes build the same outputs; give each theme its own name.`,
1114
+ const collision = new AstryxError(
1115
+ `${earlier} and ${rel(filePath)} both build ${rel(write.dest)}. Give each theme its own name; nothing was written.`,
981
1116
  undefined,
982
1117
  ERROR_CODES.ERR_THEME_INVALID,
983
1118
  );
1119
+ /** @type {any} */ (collision).outputCollision = true;
1120
+ throw collision;
984
1121
  }
985
1122
  let stat;
986
1123
  try {
@@ -995,6 +1132,33 @@ function assertOutputsReplaceable(
995
1132
  ERROR_CODES.ERR_INVALID_ARGUMENT,
996
1133
  );
997
1134
  }
1135
+ // Only a path --out names is checked: at the default paths beside the
1136
+ // source, a build replaces what is there, as it always has.
1137
+ const otherSource = refuseUnmarked
1138
+ ? builtFromOtherSource(write.dest, filePath, cwd)
1139
+ : null;
1140
+ if (otherSource && !OUT_REFUSES_OTHER_SOURCE) {
1141
+ // One warning per build: every output of that source goes together.
1142
+ if (warnedOtherSource) continue;
1143
+ warnedOtherSource = true;
1144
+ logger.warn(
1145
+ `Warning: ${rel(write.dest)} was built from ${otherSource}; this build of ${rel(filePath)} replaces it.`,
1146
+ );
1147
+ } else if (otherSource) {
1148
+ throw new AstryxError(
1149
+ `${rel(write.dest)} is the build output of another theme source, ${otherSource}, so this build does not replace it. Pick another ${elsewhere}.`,
1150
+ [
1151
+ {
1152
+ name: formatCliCommand(
1153
+ `theme build ${shellWord(rel(filePath))}`,
1154
+ cwd,
1155
+ ),
1156
+ reason: 'write the outputs beside this source',
1157
+ },
1158
+ ],
1159
+ ERROR_CODES.ERR_FILE_EXISTS,
1160
+ );
1161
+ }
998
1162
  // Outputs from CLIs before 0.6.7 have no header, so they read as files
999
1163
  // the build did not write; only the user can say they may go.
1000
1164
  if (
@@ -1018,6 +1182,46 @@ function assertOutputsReplaceable(
1018
1182
  }
1019
1183
  }
1020
1184
 
1185
+ /**
1186
+ * The other theme source a build output names in its `Source:` header, when
1187
+ * that source still exists and is not `source`. The name is resolved as
1188
+ * headerSourceCandidates says; a match is exact. A family output names
1189
+ * every member, and is this source's when any of them is. Null when the output is this source's,
1190
+ * names no source, or names one that is gone (an orphan a build may replace).
1191
+ * @param {string} dest
1192
+ * @param {string} source absolute theme source
1193
+ * @param {string} cwd
1194
+ * @returns {string | null}
1195
+ */
1196
+ function builtFromOtherSource(dest, source, cwd) {
1197
+ const head = fileHead(dest);
1198
+ if (!head.includes(GENERATED_MARKER)) return null;
1199
+ const line = /Source: (.+)/.exec(head)?.[1]?.trim();
1200
+ if (!line) return null;
1201
+ const names = line.split(', ').map(name => name.trim());
1202
+ const own = path.resolve(source);
1203
+ const candidates = names.flatMap(name =>
1204
+ headerSourceCandidates(dest, name, cwd),
1205
+ );
1206
+ if (candidates.includes(own)) return null;
1207
+ const existing = candidates.find(file => {
1208
+ try {
1209
+ return fs.statSync(file).isFile();
1210
+ } catch {
1211
+ return false;
1212
+ }
1213
+ });
1214
+ return existing ? path.relative(cwd, existing) || existing : null;
1215
+ }
1216
+
1217
+ /**
1218
+ * Publish the outputs a batch deferred, one theme at a time, in build order.
1219
+ * @param {Array<Array<{dest: string, content: string}>>} deferred
1220
+ */
1221
+ export function writeDeferredBuildOutputs(deferred) {
1222
+ for (const writes of deferred.splice(0)) writeBuildOutputs(writes);
1223
+ }
1224
+
1021
1225
  /** @param {Array<{dest: string, content: string}>} writes */
1022
1226
  function writeBuildOutputs(writes) {
1023
1227
  if (writes.length === 0) return;
@@ -2417,12 +2621,10 @@ function themeLoadReason(error) {
2417
2621
  ) {
2418
2622
  return `its default export is null or not an object.\n${THEME_EXPORT_FIX}`;
2419
2623
  }
2420
- const missing =
2421
- /Cannot find (?:module|package) '((?:@[^/']+\/)?[^/'.][^/']*)/.exec(
2422
- message,
2423
- )?.[1];
2624
+ const missing = missingThemePackage(error);
2424
2625
  if (missing) {
2425
- return `${message}\nThe theme imports ${missing}, which is not installed. Install it (for example \`npm install ${missing}\`), then build again.`;
2626
+ // Node's "Require stack" names absolute paths; the package is the fact.
2627
+ return `Cannot find module '${missing}'.\nThe theme imports ${missing}, which is not installed. Install it, then build again.`;
2426
2628
  }
2427
2629
  return `${message}\nMake sure all imports in the theme file are resolvable.`;
2428
2630
  }
@@ -2430,6 +2632,62 @@ function themeLoadReason(error) {
2430
2632
  /** A theme module that loaded but exports no theme object. */
2431
2633
  class ThemeShapeError extends Error {}
2432
2634
 
2635
+ /**
2636
+ * The command that moves a failed theme load forward: the install for a
2637
+ * package the theme imports and the app lacks, the same build for a file that
2638
+ * changed while it loaded, else the annotated template, which shows a theme
2639
+ * source that loads.
2640
+ * @param {Error} error
2641
+ * @param {string} shown the theme file as the message names it
2642
+ * @param {string} cwd
2643
+ * @returns {import('../../../foundation/response/base').Suggestion[]}
2644
+ */
2645
+ function themeLoadSuggestions(error, shown, cwd) {
2646
+ const missing = missingThemePackage(error.cause ?? error);
2647
+ if (missing) {
2648
+ const {installCommand} = installCommandFor(
2649
+ [missing],
2650
+ findPackageRoot(cwd) ?? cwd,
2651
+ );
2652
+ if (installCommand) {
2653
+ return [
2654
+ {
2655
+ name: installCommand,
2656
+ reason: `install ${missing}, which the theme imports`,
2657
+ },
2658
+ ];
2659
+ }
2660
+ }
2661
+ if (/changed while it was loading/.test(error.message)) {
2662
+ return [
2663
+ {
2664
+ name: formatCliCommand(`theme build ${shellWord(shown)}`, cwd),
2665
+ reason: 'build again once the file is saved',
2666
+ },
2667
+ ];
2668
+ }
2669
+ return [
2670
+ {
2671
+ name: formatCliCommand('theme template theme.template.ts', cwd),
2672
+ reason: 'an annotated theme source that loads, to compare with',
2673
+ },
2674
+ ];
2675
+ }
2676
+
2677
+ /**
2678
+ * The package a theme load failed on because it is not installed.
2679
+ * @param {unknown} error
2680
+ * @returns {string | null}
2681
+ */
2682
+ export function missingThemePackage(error) {
2683
+ const message = error instanceof Error ? error.message : String(error);
2684
+ return (
2685
+ /Cannot find (?:module|package) '((?:@[^/']+\/)?[^/'.][^/']*)/.exec(
2686
+ message,
2687
+ )?.[1] ?? null
2688
+ );
2689
+ }
2690
+
2433
2691
  /**
2434
2692
  * Load one theme through the build's real module loader and validate the raw
2435
2693
  * input captured from its defineTheme lineage. Used by doctor so it applies the
@@ -2670,7 +2928,7 @@ function importStatement({importPath, importedName, localName}, specifier) {
2670
2928
  * @param {any} themeDef
2671
2929
  * @param {import('./icon-imports.mjs').IconImports | null} iconInfo
2672
2930
  * @param {string} [iconsSpecifier] - Overrides the selected registry specifier.
2673
- * @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]
2931
+ * @param {{themeBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, cssFileName?: string, exportIcons?: boolean, componentIconInfo?: {imports: import('./icon-imports.mjs').IconImports['imports'], expression: string, mergeName?: string} | null}} [moduleOptions]
2674
2932
  * @returns {string}
2675
2933
  */
2676
2934
  function generateBuiltModule(
@@ -2682,6 +2940,7 @@ function generateBuiltModule(
2682
2940
  const themeBinding =
2683
2941
  moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
2684
2942
  const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;
2943
+ const cssFileName = moduleOptions.cssFileName ?? `${artifactBaseName}.css`;
2685
2944
  const exportIcons = moduleOptions.exportIcons ?? true;
2686
2945
  const iconImport = (iconInfo?.imports ?? [])
2687
2946
  .map(binding =>
@@ -2832,7 +3091,7 @@ function generateBuiltModule(
2832
3091
  * Import the CSS file alongside this module:
2833
3092
  *
2834
3093
  * import { ${themeBinding} } from './${artifactBaseName}';
2835
- * import './${artifactBaseName}.css';
3094
+ * import './${cssFileName}';
2836
3095
  */
2837
3096
  export const ${themeBinding} = {
2838
3097
  name: '${themeDef.name}',
@@ -3245,10 +3504,12 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
3245
3504
  * `logger` (silent by default).
3246
3505
  *
3247
3506
  * @param {string} file - Theme file path, resolved against `cwd`.
3248
- * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any, __onPrivateVarError?: () => void, __writeRoot?: string, __claimedOutputs?: Map<string, string>, __commandWords?: {group: string, build: string}}} [options] -
3507
+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any, __onPrivateVarError?: () => void, __writeRoot?: string, __claimedOutputs?: Map<string, string>, __deferredWrites?: Array<Array<{dest: string, content: string}>>, __commandWords?: {group: string, build: string}}} [options] -
3249
3508
  * `out` overrides the output CSS path, or names the folder for it; `check` compares against on-disk outputs
3250
3509
  * instead of writing. `__claimedOutputs` records the outputs earlier builds
3251
- * in one run wrote, so a later theme cannot replace them. `__writeRoot` replaces `cwd` as the directory every
3510
+ * in one run wrote, so a later theme cannot replace them; with
3511
+ * `__deferredWrites` the build adds its outputs to that list instead of
3512
+ * writing them, for writeDeferredBuildOutputs. `__writeRoot` replaces `cwd` as the directory every
3252
3513
  * output must stay inside, for a CLI-internal scratch build. `iconsSpecifier` overrides the icon registry import
3253
3514
  * specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
3254
3515
  * direct registry specifiers from the theme source are emitted unchanged.
@@ -3352,7 +3613,12 @@ async function themeBuildInternal(
3352
3613
  loadDegradation = loaded.degraded;
3353
3614
  } catch (e) {
3354
3615
  const err = /** @type {Error} */ (e);
3355
- throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_THEME_LOAD);
3616
+ const shown = path.relative(cwd, filePath) || filePath;
3617
+ throw new AstryxError(
3618
+ err.message.split(filePath).join(shown),
3619
+ themeLoadSuggestions(err, shown, cwd),
3620
+ ERROR_CODES.ERR_THEME_LOAD,
3621
+ );
3356
3622
  }
3357
3623
 
3358
3624
  // The marker is scoped to that isolated load: drop it before the theme
@@ -3382,9 +3648,15 @@ async function themeBuildInternal(
3382
3648
  interception && hasCoverageGap ? interception.unobservedIn(themeDef) : [];
3383
3649
  if (interception) interception.strip(themeDef);
3384
3650
  if (!ancestryObserved) {
3651
+ const shown = path.relative(cwd, filePath);
3385
3652
  throw new AstryxError(
3386
- `Theme "${themeDef.name ?? path.basename(filePath)}" exact family ancestry could not be observed during CLI loading.`,
3387
- undefined,
3653
+ `Theme "${themeDef.name ?? path.basename(filePath)}" in ${shown} is a plain object, so a family build cannot see which theme it extends. A family member is made with defineTheme(...) from @astryxdesign/core/theme; build a plain-object theme on its own.`,
3654
+ [
3655
+ {
3656
+ name: formatCliCommand(`theme build ${shellWord(shown)}`, cwd),
3657
+ reason: 'build this theme on its own',
3658
+ },
3659
+ ],
3388
3660
  ERROR_CODES.ERR_THEME_INVALID,
3389
3661
  );
3390
3662
  }
@@ -3794,7 +4066,8 @@ async function themeBuildInternal(
3794
4066
 
3795
4067
  // Source path relative to cwd — used in @generated headers
3796
4068
  const sourceRelative = path.relative(cwd, filePath);
3797
- const buildCommand = `astryx theme build ${sourceRelative}${options.out ? ' --out ' + path.relative(cwd, path.resolve(cwd, options.out)) : ''}`;
4069
+ // What `--check` prints to rebuild, from the working folder.
4070
+ const rebuildCommand = `astryx theme build ${sourceRelative}${options.out ? ' --out ' + path.relative(cwd, path.resolve(cwd, options.out)) : ''}`;
3798
4071
  // Stable provenance recorded in @generated headers — versions, not a
3799
4072
  // timestamp, so identical inputs produce byte-identical output.
3800
4073
  const versions = resolveToolVersions(cwd);
@@ -3813,6 +4086,18 @@ async function themeBuildInternal(
3813
4086
  if (/[\\/]$/.test(options.out) || isDirectorySync(outPath)) {
3814
4087
  outPath = path.join(outPath, `${baseName}.css`);
3815
4088
  }
4089
+ // The stylesheet is CSS whatever its name; a name that does not end in
4090
+ // .css still builds, and the module's import names the file as written.
4091
+ if (path.extname(outPath).toLowerCase() !== '.css') {
4092
+ const stem = path.basename(outPath).replace(/(?:\.d)?\.[^.]+$/, '');
4093
+ const fixed = path
4094
+ .join(path.dirname(options.out), `${stem}.css`)
4095
+ .split(path.sep)
4096
+ .join('/');
4097
+ logger.warn(
4098
+ `Warning: --out names the stylesheet, which is CSS; give it a .css name such as ${fixed}.`,
4099
+ );
4100
+ }
3816
4101
  // A build keeps the explicit output inside the write root, relative or
3817
4102
  // absolute. Check mode writes nothing, so it refuses only a relative path
3818
4103
  // that escapes cwd.
@@ -3822,6 +4107,12 @@ async function themeBuildInternal(
3822
4107
  } else {
3823
4108
  outPath = path.join(path.dirname(filePath), `${baseName}.css`);
3824
4109
  }
4110
+ // The header names the source and command from the project root of the
4111
+ // outputs, so a build from any folder writes the same bytes, `--check`
4112
+ // agrees with it, and a later build reads the source back exactly.
4113
+ const headerBase = headerRoot(path.dirname(outPath), cwd);
4114
+ const headerSource = headerPath(headerBase, filePath);
4115
+ const buildCommand = `astryx theme build ${headerSource}${options.out ? ' --out ' + headerPath(headerBase, outPath) : ''}`;
3825
4116
 
3826
4117
  const displayTheme = resolvedTheme || themeDef;
3827
4118
  const tokenCount =
@@ -3853,31 +4144,38 @@ async function themeBuildInternal(
3853
4144
  ? path.join(outDir, variantsFileName)
3854
4145
  : null;
3855
4146
  const variantContent = variantDecl
3856
- ? generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
3857
- variantDecl
4147
+ ? generatedHeader(headerSource, 'ts', buildCommand, versions) + variantDecl
3858
4148
  : null;
3859
4149
 
3860
4150
  // Generate all file contents in memory first. The main .d.ts references
3861
4151
  // the variants file (when present) via a triple-slash directive so
3862
4152
  // importing the theme also loads the custom-variant augmentations.
3863
4153
  const cssContent =
3864
- generatedHeader(sourceRelative, 'css', buildCommand, versions) + css;
4154
+ generatedHeader(headerSource, 'css', buildCommand, versions) + css;
3865
4155
  const cssDtsContent =
3866
- generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
4156
+ generatedHeader(headerSource, 'ts', buildCommand, versions) +
3867
4157
  'export {};\n';
3868
4158
  // A family member's module is generated by themeBuildFamily, which carries
3869
4159
  // its registries and slot functions through the family's own imports.
3870
4160
  const jsContent = options.__prepareFamily
3871
4161
  ? ''
3872
- : generatedHeader(sourceRelative, 'js', buildCommand, versions) +
4162
+ : generatedHeader(headerSource, 'js', buildCommand, versions) +
3873
4163
  generateBuiltModule(
3874
4164
  resolvedTheme || themeDef,
3875
4165
  iconInfo,
3876
4166
  options.iconsSpecifier,
3877
- {componentIconInfo},
4167
+ {
4168
+ componentIconInfo,
4169
+ // A stylesheet named other than `.css` is named as written. A
4170
+ // `.css` name keeps the theme's own name in the module, so the
4171
+ // module is the same whatever `--out` names the stylesheet.
4172
+ ...(path.extname(outPath).toLowerCase() === '.css'
4173
+ ? {}
4174
+ : {cssFileName: path.basename(outPath)}),
4175
+ },
3878
4176
  );
3879
4177
  const dtsContent =
3880
- generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
4178
+ generatedHeader(headerSource, 'ts', buildCommand, versions) +
3881
4179
  generateBuiltTypes(resolvedTheme || themeDef, iconInfo, variantsFileName);
3882
4180
 
3883
4181
  const unloadedFonts = [
@@ -3943,12 +4241,15 @@ async function themeBuildInternal(
3943
4241
  if (options.check) {
3944
4242
  const stale = staleBuildOutputs(writes, cwd);
3945
4243
  const upToDate = stale.length === 0;
4244
+ const checkedLine = ` checked: ${checkedBuildOutputs(writes, cwd).join(', ')}`;
3946
4245
  if (upToDate) {
3947
4246
  logger.log(`\n[ok] Theme outputs are up to date with ${sourceRelative}.`);
4247
+ logger.log(checkedLine);
3948
4248
  } else {
3949
4249
  logger.error(
3950
4250
  `\n[fail] ${stale.length} theme output(s) are out of date with ${sourceRelative}:`,
3951
4251
  );
4252
+ logger.error(checkedLine);
3952
4253
  for (const s of stale) {
3953
4254
  logger.error(
3954
4255
  ` ${s.reason === 'missing' ? 'missing' : 'stale'}: ${s.path}`,
@@ -3959,7 +4260,7 @@ async function themeBuildInternal(
3959
4260
  if (remedy) logger.error(`\n ${remedy.join('\n ')}`);
3960
4261
  else
3961
4262
  logger.error(
3962
- `\n Rebuild with: ${rebuildLine(buildCommand, options.__commandWords)}`,
4263
+ `\n Rebuild with: ${rebuildLine(rebuildCommand, options.__commandWords)}`,
3963
4264
  );
3964
4265
  }
3965
4266
  return {
@@ -3973,7 +4274,10 @@ async function themeBuildInternal(
3973
4274
  };
3974
4275
  }
3975
4276
 
3976
- writeBuildOutputs(writes);
4277
+ // A batch publishes every theme's outputs after all of them are built, so
4278
+ // two themes that build the same files are refused before either writes.
4279
+ if (options.__deferredWrites) options.__deferredWrites.push(writes);
4280
+ else writeBuildOutputs(writes);
3977
4281
  for (const write of writes) {
3978
4282
  options.__claimedOutputs?.set(outputKey(write.dest), sourceRelative);
3979
4283
  }
@@ -3996,9 +4300,8 @@ async function themeBuildInternal(
3996
4300
  }
3997
4301
 
3998
4302
  const relOutDir = path.relative(cwd, outDir) || '.';
3999
- const cssBase = path.basename(outPath, '.css');
4000
4303
  const jsImport = importSpecifier(relOutDir, baseName);
4001
- const cssImport = importSpecifier(relOutDir, cssBase) + '.css';
4304
+ const cssImport = importSpecifier(relOutDir, path.basename(outPath));
4002
4305
  const exportName = `${toIdentifier(baseName)}Theme`;
4003
4306
 
4004
4307
  // Fonts the theme names but nothing loads (#5015). Resolved tokens and
@@ -4477,9 +4780,15 @@ export async function themeBuildFamily(
4477
4780
  const sourceRelative = members
4478
4781
  .map(member => member.sourceRelative)
4479
4782
  .join(', ');
4480
- const buildCommand = `${getCliInvocation()} theme build --family ${members
4783
+ const rebuildCommand = `${getCliInvocation()} theme build --family ${members
4481
4784
  .map(member => member.sourceRelative)
4482
4785
  .join(' ')} --family-key ${baseName}`;
4786
+ const headerBase = headerRoot(outDir, cwd);
4787
+ const headerSources = members.map(member =>
4788
+ headerPath(headerBase, member.filePath),
4789
+ );
4790
+ const headerSource = headerSources.join(', ');
4791
+ const buildCommand = `astryx theme build --family ${headerSources.join(' ')} --family-key ${baseName}`;
4483
4792
  const bindings = allocateFamilyBindings(members);
4484
4793
  const css = generateFamilyCSS(members);
4485
4794
  /** @type {Array<{specifier: string, exportName: string}>} */
@@ -4558,25 +4867,24 @@ export async function themeBuildFamily(
4558
4867
  {
4559
4868
  dest: outPath,
4560
4869
  content:
4561
- generatedHeader(sourceRelative, 'css', buildCommand, root.versions) +
4562
- css,
4870
+ generatedHeader(headerSource, 'css', buildCommand, root.versions) + css,
4563
4871
  },
4564
4872
  {
4565
4873
  dest: cssDtsPath,
4566
4874
  allowMissingInCheck: true,
4567
4875
  content:
4568
- generatedHeader(sourceRelative, 'ts', buildCommand, root.versions) +
4876
+ generatedHeader(headerSource, 'ts', buildCommand, root.versions) +
4569
4877
  'export {};\n',
4570
4878
  },
4571
4879
  {
4572
4880
  dest: jsPath,
4573
4881
  content:
4574
- generatedHeader(sourceRelative, 'js', buildCommand, root.versions) + js,
4882
+ generatedHeader(headerSource, 'js', buildCommand, root.versions) + js,
4575
4883
  },
4576
4884
  {
4577
4885
  dest: dtsPath,
4578
4886
  content:
4579
- generatedHeader(sourceRelative, 'ts', buildCommand, root.versions) +
4887
+ generatedHeader(headerSource, 'ts', buildCommand, root.versions) +
4580
4888
  declarations +
4581
4889
  (augmentations ? `\n${augmentations}` : ''),
4582
4890
  },
@@ -4599,14 +4907,17 @@ export async function themeBuildFamily(
4599
4907
  if (options.check) {
4600
4908
  const stale = staleBuildOutputs(writes, cwd);
4601
4909
  const upToDate = stale.length === 0;
4910
+ const checkedLine = ` checked: ${checkedBuildOutputs(writes, cwd).join(', ')}`;
4602
4911
  if (upToDate) {
4603
4912
  logger.log(
4604
4913
  `\n[ok] Theme family outputs are up to date with ${sourceRelative}.`,
4605
4914
  );
4915
+ logger.log(checkedLine);
4606
4916
  } else {
4607
4917
  logger.error(
4608
4918
  `\n[fail] ${stale.length} theme family output(s) are out of date:`,
4609
4919
  );
4920
+ logger.error(checkedLine);
4610
4921
  for (const entry of stale) {
4611
4922
  logger.error(
4612
4923
  ` ${entry.reason === 'missing' ? 'missing' : 'stale'}: ${entry.path}`,
@@ -4617,7 +4928,7 @@ export async function themeBuildFamily(
4617
4928
  if (remedy) logger.error(`\n ${remedy.join('\n ')}`);
4618
4929
  else
4619
4930
  logger.error(
4620
- `\n Rebuild with: ${rebuildLine(buildCommand, options.__commandWords)}`,
4931
+ `\n Rebuild with: ${rebuildLine(rebuildCommand, options.__commandWords)}`,
4621
4932
  );
4622
4933
  }
4623
4934
  return {