@astryxdesign/cli 0.7.14 → 0.7.15-canary.g06b7e61

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 (203) hide show
  1. package/CHANGELOG.md +3 -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 +3 -1
  11. package/api/doctor/_adapter.mjs +14 -1
  12. package/api/doctor/_authoring-audit.d.mts +42 -0
  13. package/api/doctor/_authoring-audit.mjs +106 -0
  14. package/api/doctor/doctor.d.mts +7 -0
  15. package/api/doctor/doctor.mjs +24 -39
  16. package/api/doctor/theme-checks.mjs +56 -21
  17. package/api/integration/add-helpers.mjs +5 -0
  18. package/api/integration/add-theme.mjs +15 -110
  19. package/api/integration/validate-integration.mjs +17 -3
  20. package/api/integration/validateIntegration.doc.mjs +1 -1
  21. package/api/search/_adapter.mjs +124 -3
  22. package/api/search/_candidate-score.mjs +63 -9
  23. package/api/search/_entries.d.mts +10 -0
  24. package/api/search/_entries.mjs +68 -1
  25. package/api/search/_gather-templates.d.mts +11 -0
  26. package/api/search/_gather-templates.mjs +22 -2
  27. package/api/search/_words.mjs +26 -6
  28. package/api/swizzle/copy/copy.mjs +1 -1
  29. package/api/theme/_adapter.d.mts +37 -5
  30. package/api/theme/_adapter.mjs +381 -57
  31. package/api/theme/_fork.d.mts +90 -0
  32. package/api/theme/_fork.mjs +246 -0
  33. package/api/theme/build/build.d.mts +40 -2
  34. package/api/theme/build/build.mjs +477 -66
  35. package/api/theme/eject/eject.mjs +36 -15
  36. package/api/theme/list/list.mjs +3 -6
  37. package/api/theme/palette/generate/generator.d.mts +13 -0
  38. package/api/theme/palette/generate/generator.mjs +32 -2
  39. package/api/theme/targets/targets.d.mts +8 -0
  40. package/api/theme/targets/targets.mjs +24 -4
  41. package/api/theme/template/template.mjs +48 -2
  42. package/api/theme/theme.type.d.mts +8 -0
  43. package/api/theme/theme.type.mjs +5 -1
  44. package/api/theme/themeBuild.doc.mjs +7 -4
  45. package/api/theme/themeEject.doc.mjs +3 -3
  46. package/api/theme/themeRemove.doc.mjs +5 -2
  47. package/api/theme/themeTargets.doc.mjs +1 -1
  48. package/api/theme/themeTemplate.doc.mjs +2 -2
  49. package/api/theme/themeUse.doc.mjs +8 -2
  50. package/api/theme-edit/_adapter.d.mts +46 -3
  51. package/api/theme-edit/_adapter.mjs +496 -112
  52. package/api/theme-edit/_catalog.d.mts +1 -6
  53. package/api/theme-edit/_catalog.mjs +5 -268
  54. package/api/theme-edit/_check.d.mts +9 -4
  55. package/api/theme-edit/_check.mjs +1232 -229
  56. package/api/theme-edit/_color.d.mts +19 -0
  57. package/api/theme-edit/_color.mjs +280 -34
  58. package/api/theme-edit/_compiler.d.mts +3 -1
  59. package/api/theme-edit/_compiler.mjs +52 -13
  60. package/api/theme-edit/_context.d.mts +4 -1
  61. package/api/theme-edit/_context.mjs +126 -13
  62. package/api/theme-edit/_css.d.mts +84 -0
  63. package/api/theme-edit/_css.mjs +700 -0
  64. package/api/theme-edit/_edit.d.mts +9 -3
  65. package/api/theme-edit/_edit.mjs +806 -103
  66. package/api/theme-edit/_how-commands.d.mts +38 -7
  67. package/api/theme-edit/_how-commands.mjs +64 -45
  68. package/api/theme-edit/_how-question.d.mts +33 -0
  69. package/api/theme-edit/_how-question.mjs +2553 -381
  70. package/api/theme-edit/_how.mjs +402 -31
  71. package/api/theme-edit/_overview.mjs +2 -7
  72. package/api/theme-edit/_palette.d.mts +60 -13
  73. package/api/theme-edit/_palette.mjs +826 -295
  74. package/api/theme-edit/_parts.d.mts +42 -10
  75. package/api/theme-edit/_parts.mjs +280 -69
  76. package/api/theme-edit/_png.d.mts +4 -4
  77. package/api/theme-edit/_png.mjs +4 -2
  78. package/api/theme-edit/_preview-app.d.mts +14 -0
  79. package/api/theme-edit/_preview-app.mjs +1675 -235
  80. package/api/theme-edit/_preview.d.mts +7 -16
  81. package/api/theme-edit/_preview.mjs +79 -86
  82. package/api/theme-edit/_project.d.mts +32 -2
  83. package/api/theme-edit/_project.mjs +80 -19
  84. package/api/theme-edit/_settings.d.mts +199 -52
  85. package/api/theme-edit/_settings.mjs +1422 -217
  86. package/api/theme-edit/_tables.d.mts +19 -6
  87. package/api/theme-edit/_tables.mjs +150 -92
  88. package/api/theme-edit/theme-edit.type.d.mts +20 -1
  89. package/api/theme-edit/theme-edit.type.mjs +6 -3
  90. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  91. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  92. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  93. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  94. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  95. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  96. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  97. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  98. package/api/upgrade/_adapter.d.mts +1 -0
  99. package/assets/codemods/run-codemod.mjs +61 -0
  100. package/assets/codemods/runner.mjs +5 -4
  101. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  102. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  103. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  104. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  105. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  106. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  107. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  108. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  109. package/assets/docs/tree/calendars.doc.mjs +1 -3
  110. package/assets/docs/tree/checks.doc.mjs +22 -1
  111. package/assets/docs/tree/publishing.doc.mjs +1 -0
  112. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  113. package/assets/docs.generated.json +2 -1
  114. package/assets/preview-app/next.config.mjs +7 -1
  115. package/assets/self-audit.generated.json +1 -0
  116. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  117. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  118. package/assets/templates/components.generated.json +1 -1
  119. package/authoring/integration/integration.doc.mjs +8 -0
  120. package/authoring/integration/schema.d.mts +8 -0
  121. package/authoring/integration/schema.mjs +1 -0
  122. package/authoring/integration/type.ts +9 -0
  123. package/clients/cli/bin/astryx.mjs +19 -15
  124. package/clients/cli/build-id.generated.json +1 -0
  125. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  126. package/clients/cli/commands/experimental/index.mjs +10 -10
  127. package/clients/cli/commands/experimental/theme.mjs +200 -81
  128. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  129. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  130. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  131. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  132. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  133. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  134. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  135. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  136. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  137. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  138. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  139. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  140. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  142. package/clients/cli/commands/integration.mjs +8 -0
  143. package/clients/cli/commands/manifest.mjs +5 -2
  144. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  145. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.mjs +439 -66
  148. package/clients/cli/index.mjs +27 -6
  149. package/clients/cli/lib/cli-error.mjs +118 -3
  150. package/clients/cli/lib/manifest.mjs +37 -0
  151. package/clients/cli/lib/resolve-theme.mjs +2 -1
  152. package/clients/cli/manifest.generated.json +1 -0
  153. package/foundation/config/project.mjs +34 -8
  154. package/foundation/config/theme-state.d.mts +16 -0
  155. package/foundation/config/theme-state.mjs +84 -13
  156. package/foundation/discovery/module-exports.mjs +16 -2
  157. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  158. package/foundation/discovery/stored-self-audit.mjs +119 -0
  159. package/foundation/discovery/template-adapter.d.mts +48 -2
  160. package/foundation/discovery/template-adapter.mjs +51 -19
  161. package/foundation/discovery/template-needs.d.mts +19 -0
  162. package/foundation/discovery/template-needs.mjs +50 -16
  163. package/foundation/discovery/template-source-tree.d.mts +7 -0
  164. package/foundation/discovery/template-source-tree.mjs +15 -0
  165. package/foundation/discovery/theme-discovery.d.mts +2 -1
  166. package/foundation/discovery/theme-discovery.mjs +16 -10
  167. package/foundation/discovery/theme-imports.d.mts +16 -0
  168. package/foundation/discovery/theme-imports.mjs +30 -2
  169. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  170. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  171. package/foundation/doc-compiler/import.mjs +22 -15
  172. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  173. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  174. package/foundation/env/private-dir.d.mts +17 -0
  175. package/foundation/env/private-dir.mjs +42 -0
  176. package/foundation/fs/gather-cache.d.mts +108 -0
  177. package/foundation/fs/gather-cache.mjs +783 -0
  178. package/foundation/fs/jiti-cache.d.mts +21 -0
  179. package/foundation/fs/jiti-cache.mjs +66 -0
  180. package/foundation/fs/module-loader.mjs +14 -3
  181. package/foundation/fs/read-record.d.mts +31 -1
  182. package/foundation/fs/read-record.mjs +100 -7
  183. package/foundation/integrations/autolink.d.mts +1 -24
  184. package/foundation/integrations/autolink.mjs +7 -60
  185. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  186. package/foundation/integrations/declared-dependencies.mjs +73 -0
  187. package/foundation/integrations/integrations.d.mts +8 -0
  188. package/foundation/integrations/integrations.mjs +4 -0
  189. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  190. package/foundation/integrations/may-have-integrations.mjs +47 -0
  191. package/foundation/integrations/validate-contributions.d.mts +62 -1
  192. package/foundation/integrations/validate-contributions.mjs +476 -40
  193. package/foundation/release/cache.d.mts +32 -4
  194. package/foundation/release/cache.mjs +105 -16
  195. package/foundation/release/folder-lock.d.mts +28 -0
  196. package/foundation/release/folder-lock.mjs +205 -0
  197. package/foundation/release/lock-lease.d.mts +2 -1
  198. package/foundation/release/lock-lease.mjs +7 -2
  199. package/foundation/response/error-codes.doc.mjs +1 -1
  200. package/foundation/response/response-types.doc.mjs +5 -5
  201. package/package.json +8 -6
  202. package/api/theme-edit/_css-properties.d.mts +0 -10
  203. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -67,7 +67,12 @@ import {
67
67
  discoverValidIntegrationComponents,
68
68
  } from '../discovery/component-discovery.mjs';
69
69
  import {resolveComponentReplacements} from '../discovery/component-replacement.mjs';
70
- import {CLI_ROOT, findCoreDir, findPackageRoot, findProjectCoreDir} from '../fs/paths.mjs';
70
+ import {
71
+ CLI_ROOT,
72
+ findCoreDir,
73
+ findPackageRoot,
74
+ findProjectCoreDir,
75
+ } from '../fs/paths.mjs';
71
76
  import {
72
77
  applyTemplateReplacements,
73
78
  effectiveTemplateDiscovery,
@@ -96,6 +101,8 @@ import {
96
101
  selectIntegrationCodemods,
97
102
  } from '../../assets/codemods/integration-discovery.mjs';
98
103
  import {validateLoadedIntegration} from '../integrations/validate-contributions.mjs';
104
+ import {persistedGather} from '../fs/gather-cache.mjs';
105
+
99
106
  import {recordDeclaredCliCommands} from '../env/cli-command.mjs';
100
107
  import {
101
108
  hostedRun,
@@ -107,6 +114,12 @@ import {
107
114
  configContentHash,
108
115
  } from './config-cache.mjs';
109
116
 
117
+ /** Issues are plain records, kept as they are. */
118
+ const ISSUES_CODEC = {
119
+ encode: (/** @type {any} */ value) => value,
120
+ decode: (/** @type {any} */ value) => value,
121
+ };
122
+
110
123
  export {CONFIG_BASENAMES, findConfigPath} from './config-path.mjs';
111
124
 
112
125
  /**
@@ -326,8 +339,7 @@ function readPackageJson(dir) {
326
339
  */
327
340
 
328
341
  /** Default issue tracker used when neither config nor integration routes one. */
329
- export const DEFAULT_ISSUES_URL =
330
- 'https://github.com/meta/astryx/issues/new';
342
+ export const DEFAULT_ISSUES_URL = 'https://github.com/meta/astryx/issues/new';
331
343
 
332
344
  /**
333
345
  * Whether this project accepts `debug` handlers contributed by the
@@ -475,7 +487,10 @@ export class Project {
475
487
  * @param {{cache?: import('./config-cache.mjs').ConfigCache, fresh?: boolean, core?: 'any' | 'project'}} [options]
476
488
  * @returns {Promise<Project>}
477
489
  */
478
- static async load(cwd = process.cwd(), {cache, fresh = false, core = 'any'} = {}) {
490
+ static async load(
491
+ cwd = process.cwd(),
492
+ {cache, fresh = false, core = 'any'} = {},
493
+ ) {
479
494
  const resolvedCache = fresh
480
495
  ? new InMemoryConfigCache()
481
496
  : (cache ?? new InMemoryConfigCache());
@@ -739,10 +754,21 @@ export class Project {
739
754
  try {
740
755
  // An experimental root is checked only in a project that opts in
741
756
  // (spec:AST-017 FR27); the package's own checks read it either way.
742
- const found = await validateLoadedIntegration(
743
- this.#config.experimental?.iconSet
744
- ? integration
745
- : {...integration, iconSets: undefined},
757
+ const checked = this.#config.experimental?.iconSet
758
+ ? integration
759
+ : {...integration, iconSets: undefined};
760
+ // A function of the files the checks read, which the kept gather
761
+ // stamps: a later run with every one unchanged reads the issues back.
762
+ const found = await persistedGather(
763
+ [
764
+ 'integration-issues',
765
+ this.#cwd,
766
+ integration.__packageDir ?? null,
767
+ integration.name ?? null,
768
+ Boolean(this.#config.experimental?.iconSet),
769
+ ],
770
+ () => validateLoadedIntegration(checked),
771
+ ISSUES_CODEC,
746
772
  );
747
773
  for (const issue of found ?? []) this.#pushIssue(pkg, issue);
748
774
  } catch (err) {
@@ -130,6 +130,22 @@ export const THEME_MODULE_BASENAME: "astryx-themes";
130
130
  export const THEME_MODULE_MARKER: "@generated by `astryx theme` \u2014 do not edit manually.";
131
131
  export const THEME_RECORD_MARKER: "@astryx-theme-record";
132
132
  export class ThemeStateError extends Error {
133
+ /**
134
+ * @param {string} message
135
+ * @param {{cause?: unknown, suggestions?: Array<{name: string, reason: string}>}} [options]
136
+ */
137
+ constructor(message: string, options?: {
138
+ cause?: unknown;
139
+ suggestions?: Array<{
140
+ name: string;
141
+ reason: string;
142
+ }>;
143
+ });
144
+ /** Commands that move past the refusal. */
145
+ suggestions: {
146
+ name: string;
147
+ reason: string;
148
+ }[];
133
149
  }
134
150
  export type ThemeState = {
135
151
  projectDir: string;
@@ -26,7 +26,54 @@ export const THEME_RECORD_MARKER = '@astryx-theme-record';
26
26
 
27
27
  const THEME_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;
28
28
 
29
- export class ThemeStateError extends Error {}
29
+ export class ThemeStateError extends Error {
30
+ /**
31
+ * @param {string} message
32
+ * @param {{cause?: unknown, suggestions?: Array<{name: string, reason: string}>}} [options]
33
+ */
34
+ constructor(message, options = {}) {
35
+ super(
36
+ message,
37
+ options.cause === undefined ? undefined : {cause: options.cause},
38
+ );
39
+ /** Commands that move past the refusal. */
40
+ this.suggestions = options.suggestions ?? [];
41
+ }
42
+ }
43
+
44
+ /**
45
+ * The refusal for a generated module whose record header cannot be read. No
46
+ * theme command can read the record to rewrite it, so the way out is to
47
+ * delete the module and add its themes again, named from its `themes` export.
48
+ * @param {string} label the module's project path
49
+ * @param {string} problem what is wrong with the header
50
+ * @param {string} source the module text
51
+ */
52
+ function damagedRecordError(label, problem, source) {
53
+ const slugs = [
54
+ ...source.matchAll(/^\s*"([a-z][a-z0-9-]*)":\s*_astryxTheme\d+,/gmu),
55
+ ].map(match => match[1]);
56
+ const adds = (slugs.length > 0 ? slugs : ['<slug>']).map(slug =>
57
+ formatCliCommand(`theme add ${slug}`),
58
+ );
59
+ return new ThemeStateError(
60
+ `${label} ${problem}, so no theme command can read or rewrite it. Delete ${label}, then add its themes again: ${adds.map(add => `\`${add}\``).join(', ')}.`,
61
+ {
62
+ suggestions:
63
+ slugs.length > 0
64
+ ? adds.map((name, index) => ({
65
+ name,
66
+ reason: `add ${slugs[index]} again once ${label} is deleted`,
67
+ }))
68
+ : [
69
+ {
70
+ name: formatCliCommand('theme list'),
71
+ reason: `the themes you can add, once ${label} is deleted`,
72
+ },
73
+ ],
74
+ },
75
+ );
76
+ }
30
77
 
31
78
  /** @param {unknown} value @returns {value is Record<string, unknown>} */
32
79
  function isRecord(value) {
@@ -123,10 +170,12 @@ export function themeModuleCandidates(projectDir) {
123
170
  * @param {unknown} value
124
171
  * @param {string} label
125
172
  */
126
- function validThemeRecord(value, label) {
173
+ function validThemeRecord(value, label, source = '') {
127
174
  if (!isRecord(value) || !isRecord(value.themes)) {
128
- throw new ThemeStateError(
129
- `${label} must carry a static ${THEME_RECORD_MARKER} header. Regenerate it with \`${formatCliCommand('theme add <slug>')}\`.`,
175
+ throw damagedRecordError(
176
+ label,
177
+ `has no static ${THEME_RECORD_MARKER} header`,
178
+ source,
130
179
  );
131
180
  }
132
181
  const keys = Object.keys(value);
@@ -158,8 +207,13 @@ function validThemeRecord(value, label) {
158
207
  typeof value.defaultThemeSlug !== 'string' ||
159
208
  !THEME_SLUG_RE.test(value.defaultThemeSlug)
160
209
  ) {
210
+ const first = Object.keys(themes)[0];
211
+ const use = formatCliCommand(`theme use ${first ?? '<slug>'}`);
161
212
  throw new ThemeStateError(
162
- `${label} defaultThemeSlug must be a lowercase kebab-case slug. Regenerate it with \`${formatCliCommand('theme use <slug>')}\`.`,
213
+ `${label} defaultThemeSlug must be a lowercase kebab-case slug. Choose a default with \`${use}\`.`,
214
+ first
215
+ ? {suggestions: [{name: use, reason: `make ${first} the default`}]}
216
+ : {},
163
217
  );
164
218
  }
165
219
  return {themes, defaultSlug: value.defaultThemeSlug};
@@ -178,8 +232,12 @@ export function parseThemeModuleRecord(source, label = 'theme module') {
178
232
  .split(/\r?\n/u)
179
233
  .filter(line => /^\s*\*\s*@astryx-theme-record\s+/u.test(line));
180
234
  if (recordLines.length !== 1) {
181
- throw new ThemeStateError(
182
- `${label} must carry exactly one static ${THEME_RECORD_MARKER} header. Regenerate it with \`${formatCliCommand('theme add <slug>')}\`.`,
235
+ throw damagedRecordError(
236
+ label,
237
+ recordLines.length === 0
238
+ ? `has no static ${THEME_RECORD_MARKER} header`
239
+ : `has more than one ${THEME_RECORD_MARKER} header`,
240
+ source,
183
241
  );
184
242
  }
185
243
  const payload = recordLines[0].replace(
@@ -189,13 +247,14 @@ export function parseThemeModuleRecord(source, label = 'theme module') {
189
247
  let record;
190
248
  try {
191
249
  record = JSON.parse(payload);
192
- } catch (error) {
193
- throw new ThemeStateError(
194
- `${label} has an invalid ${THEME_RECORD_MARKER} header: ${error instanceof Error ? error.message : String(error)}`,
195
- {cause: error},
250
+ } catch {
251
+ throw damagedRecordError(
252
+ label,
253
+ `has a ${THEME_RECORD_MARKER} header that is not valid JSON`,
254
+ source,
196
255
  );
197
256
  }
198
- return validThemeRecord(record, label);
257
+ return validThemeRecord(record, label, source);
199
258
  }
200
259
 
201
260
  /**
@@ -234,6 +293,11 @@ export function resolveThemeModule(projectDir, {forWrite = false} = {}) {
234
293
  }
235
294
  }
236
295
  let expectedOriginal;
296
+ if (fs.existsSync(file) && fs.statSync(file).isDirectory()) {
297
+ throw new ThemeStateError(
298
+ `${projectPath(path.relative(projectDir, file))} is a folder, where the generated theme module goes. Move or delete that folder, then run the same command again.`,
299
+ );
300
+ }
237
301
  if (fs.existsSync(file)) {
238
302
  expectedOriginal = fs.readFileSync(file);
239
303
  if (!expectedOriginal.toString('utf-8').includes(THEME_MODULE_MARKER)) {
@@ -337,8 +401,15 @@ export function readThemeState(cwd = process.cwd()) {
337
401
  */
338
402
  export function renderThemeModule(themes, defaultSlug, typescript) {
339
403
  if (!themes.some(theme => theme.slug === defaultSlug)) {
404
+ // The record's default names no added theme; choosing an added one as the
405
+ // default rewrites the record.
406
+ const first = themes[0]?.slug;
407
+ const use = formatCliCommand(`theme use ${first ?? '<slug>'}`);
340
408
  throw new ThemeStateError(
341
- `Default theme "${defaultSlug}" is not added. Run \`${formatCliCommand(`theme add ${defaultSlug}`)}\` first.`,
409
+ `Default theme "${defaultSlug}" is not added. Choose an added theme as the default with \`${use}\`.`,
410
+ first
411
+ ? {suggestions: [{name: use, reason: `make ${first} the default`}]}
412
+ : {},
342
413
  );
343
414
  }
344
415
  /** @type {string[]} */
@@ -19,7 +19,7 @@
19
19
 
20
20
  import * as fs from 'node:fs';
21
21
  import * as path from 'node:path';
22
- import {parse} from '@babel/parser';
22
+ import {createRequire} from 'node:module';
23
23
  import {findInstalledPackage} from '../fs/paths.mjs';
24
24
  import {inspectPackageExport} from './package-exports.mjs';
25
25
 
@@ -103,12 +103,26 @@ function moduleText(file) {
103
103
  return text;
104
104
  }
105
105
 
106
+ const requireFromHere = createRequire(import.meta.url);
107
+ /** @type {typeof import('@babel/parser') | undefined} */
108
+ let parser;
109
+
110
+ /**
111
+ * @babel/parser, loaded on first use: a run that reads no module's exports
112
+ * never loads it.
113
+ * @returns {typeof import('@babel/parser')}
114
+ */
115
+ function babelParser() {
116
+ parser ??= requireFromHere('@babel/parser');
117
+ return /** @type {typeof import('@babel/parser')} */ (parser);
118
+ }
119
+
106
120
  /** @param {string} file */
107
121
  function parseModule(file) {
108
122
  const stamp = fileStamp(file);
109
123
  const cached = parsedModules.get(file);
110
124
  if (cached?.stamp === stamp) return cached.ast;
111
- const ast = parse(moduleText(file), PARSE_OPTIONS);
125
+ const ast = babelParser().parse(moduleText(file), PARSE_OPTIONS);
112
126
  parsedModules.set(file, {stamp, ast});
113
127
  return ast;
114
128
  }
@@ -0,0 +1,31 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * A file's or folder's state as an audit read it: a file by its content
6
+ * (package.json by its packer-stable fields), a folder by the names it holds
7
+ * (but PACKING_NAMES), `-` when absent.
8
+ * @param {string} file
9
+ * @returns {string}
10
+ */
11
+ export function inputState(file: string): string;
12
+ /**
13
+ * The inputs an audit read, by path in the package, with their state. Code
14
+ * in node_modules is the package's dependencies, not its own files.
15
+ * Paths outside the package are where it runs (the package manager is found
16
+ * from the working folder, to spell commands in rendered docs); the
17
+ * generator proves the audit's answer is the same wherever it runs, so they
18
+ * are not inputs.
19
+ * @param {Iterable<string>} files every path the audit read
20
+ * @returns {Record<string, string>}
21
+ */
22
+ export function selfAuditInputs(files: Iterable<string>): Record<string, string>;
23
+ /**
24
+ * The stored value of the audit `name`, while every file and folder it read
25
+ * is unchanged, else undefined.
26
+ * @param {string} name
27
+ * @returns {unknown}
28
+ */
29
+ export function storedSelfAudit(name: string): unknown;
30
+ /** Where the stored audits are, in the published package. */
31
+ export const SELF_AUDIT_FILE: string;
@@ -0,0 +1,119 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Doctor's audits of the CLI's own shipped files, stored at publish.
5
+ * @input assets/self-audit.generated.json, written at `prepack` by
6
+ * scripts/generate-self-audit.mjs: for each audit, the value it found and
7
+ * the state of every file and folder it read.
8
+ * @output `storedSelfAudit(name)`: the stored value while the package version
9
+ * and every doc, type file and folder the audit read are as they were when
10
+ * stored, else undefined (the caller audits as before). The audit's own code
11
+ * is the package's and is not checked again. A checkout has no file, so it
12
+ * always audits.
13
+ * @position Read by api/doctor/doctor.mjs. These audits read only the
14
+ * package's own files, so their answer is fixed until one of them changes.
15
+ */
16
+
17
+ import * as fs from 'node:fs';
18
+ import * as path from 'node:path';
19
+ import {CLI_ROOT} from '../fs/paths.mjs';
20
+ import {readStore, storedKey} from '../doc-compiler/stored-docs.mjs';
21
+
22
+ /** Where the stored audits are, in the published package. */
23
+ export const SELF_AUDIT_FILE = path.join(
24
+ CLI_ROOT,
25
+ 'assets',
26
+ 'self-audit.generated.json',
27
+ );
28
+
29
+ /**
30
+ * Names a folder's state leaves out, being where and how the package is
31
+ * packed or installed rather than its content: what `prepack` writes (each
32
+ * `*.generated.json`, there or not depending on the order prepack writes
33
+ * in), dependencies placed inside it, and the files every packer adds to a
34
+ * package's root. No audit reads any of them.
35
+ */
36
+ const PACKING_NAMES =
37
+ /^(?:.*\.generated\.json|node_modules|(?:LICEN[CS]E|README|CHANGELOG|NOTICE)(?:\..*)?)$/i;
38
+
39
+ /** The package.json fields a packer leaves as written. */
40
+ const PACKAGE_FIELDS = [
41
+ 'name',
42
+ 'version',
43
+ 'type',
44
+ 'exports',
45
+ 'bin',
46
+ 'main',
47
+ 'types',
48
+ ];
49
+
50
+ /**
51
+ * A file's or folder's state as an audit read it: a file by its content
52
+ * (package.json by its packer-stable fields), a folder by the names it holds
53
+ * (but PACKING_NAMES), `-` when absent.
54
+ * @param {string} file
55
+ * @returns {string}
56
+ */
57
+ export function inputState(file) {
58
+ try {
59
+ if (fs.statSync(file).isDirectory()) {
60
+ const names = fs
61
+ .readdirSync(file)
62
+ .filter(name => !PACKING_NAMES.test(name))
63
+ .sort();
64
+ return `dir:${storedKey(names.join('\n'))}`;
65
+ }
66
+ if (path.basename(file) === 'package.json') {
67
+ // A packer rewrites package.json (pnpm resolves `catalog:` ranges and
68
+ // drops lifecycle scripts): only the fields that say what the package
69
+ // is and holds count.
70
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
71
+ return `pkg:${storedKey(
72
+ JSON.stringify(PACKAGE_FIELDS.map(field => pkg[field] ?? null)),
73
+ )}`;
74
+ }
75
+ return storedKey(fs.readFileSync(file));
76
+ } catch {
77
+ return '-';
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The inputs an audit read, by path in the package, with their state. Code
83
+ * in node_modules is the package's dependencies, not its own files.
84
+ * Paths outside the package are where it runs (the package manager is found
85
+ * from the working folder, to spell commands in rendered docs); the
86
+ * generator proves the audit's answer is the same wherever it runs, so they
87
+ * are not inputs.
88
+ * @param {Iterable<string>} files every path the audit read
89
+ * @returns {Record<string, string>}
90
+ */
91
+ export function selfAuditInputs(files) {
92
+ /** @type {Record<string, string>} */
93
+ const inputs = {};
94
+ for (const file of [...files].sort()) {
95
+ if (file.split(path.sep).includes('node_modules')) continue;
96
+ const rel = path.relative(CLI_ROOT, file);
97
+ if (rel.startsWith('..') || path.isAbsolute(rel)) continue;
98
+ inputs[rel.split(path.sep).join('/')] = inputState(file);
99
+ }
100
+ return inputs;
101
+ }
102
+
103
+ /**
104
+ * The stored value of the audit `name`, while every file and folder it read
105
+ * is unchanged, else undefined.
106
+ * @param {string} name
107
+ * @returns {unknown}
108
+ */
109
+ export function storedSelfAudit(name) {
110
+ /** @type {{inputs: Record<string, string>, value: unknown} | undefined} */
111
+ const entry = readStore(SELF_AUDIT_FILE).get(name);
112
+ if (!entry) return undefined;
113
+ for (const [rel, state] of Object.entries(entry.inputs)) {
114
+ if (inputState(path.join(CLI_ROOT, ...rel.split('/'))) !== state) {
115
+ return undefined;
116
+ }
117
+ }
118
+ return entry.value;
119
+ }
@@ -66,6 +66,33 @@ export function replaceDemoMedia(source: string, { videoPlaceholder }?: {
66
66
  source: string;
67
67
  demoMediaReplaced: number;
68
68
  };
69
+ /**
70
+ * One Astryx template fixture reference in template source.
71
+ * @typedef {object} FixtureRef
72
+ * @property {string} reference - The whole reference, query and fragment
73
+ * included.
74
+ * @property {'image' | 'video'} kind - What the suffix of its last path
75
+ * segment names.
76
+ * @property {boolean} isValue - Whether the reference is a whole quoted or
77
+ * `url()` value. False for a mention in text.
78
+ */
79
+ /**
80
+ * Replace each Astryx template fixture reference with what `map` returns for
81
+ * it. This is the one scanner for fixture references: a copy replaces them
82
+ * with placeholders ({@link replaceDemoMedia}), and the docsite's preview
83
+ * build points them at its image optimizer. It finds and refuses references
84
+ * as {@link stripTemplateAssetRefs} describes.
85
+ *
86
+ * @param {string} source - Template source code.
87
+ * @param {(ref: FixtureRef) => string | null} map - The replacement text, or
88
+ * null to keep the reference as written.
89
+ * @returns {{source: string, replaced: number}} `replaced` counts the
90
+ * references that `map` replaced.
91
+ */
92
+ export function mapFixtureRefs(source: string, map: (ref: FixtureRef) => string | null): {
93
+ source: string;
94
+ replaced: number;
95
+ };
69
96
  /**
70
97
  * Replace each JSX element imported from {@link DEMO_CONTENT_MODULE} with a
71
98
  * generic `<Text>` placeholder and remove that import, so emitted source never
@@ -273,8 +300,27 @@ export const MARKED_VIDEO_PLACEHOLDER: "data:,placeholder-video-add-your-own";
273
300
  * {@link replaceDemoContent}).
274
301
  */
275
302
  export const DEMO_CONTENT_MODULE: "@astryx-docs/demo-content";
276
- /** Where the component lists of the templates Astryx ships are stored. */
277
- export const TEMPLATE_COMPONENTS_FILE: string;
303
+ export { TEMPLATE_COMPONENTS_FILE } from "./template-source-tree.mjs";
304
+ /**
305
+ * One Astryx template fixture reference in template source.
306
+ */
307
+ export type FixtureRef = {
308
+ /**
309
+ * - The whole reference, query and fragment
310
+ * included.
311
+ */
312
+ reference: string;
313
+ /**
314
+ * - What the suffix of its last path
315
+ * segment names.
316
+ */
317
+ kind: "image" | "video";
318
+ /**
319
+ * - Whether the reference is a whole quoted or
320
+ * `url()` value. False for a mention in text.
321
+ */
322
+ isValue: boolean;
323
+ };
278
324
  /**
279
325
  * A discovered template (page or block), normalized across core, external, and
280
326
  * integration sources. Not every source populates every field, so
@@ -38,6 +38,7 @@ import {
38
38
  programPath,
39
39
  traverseTemplateSource,
40
40
  writtenNames,
41
+ TEMPLATE_COMPONENTS_FILE,
41
42
  } from './template-source-tree.mjs';
42
43
 
43
44
  const require = createRequire(import.meta.url);
@@ -358,10 +359,41 @@ export function stripTemplateAssetRefs(source) {
358
359
  * @returns {{source: string, demoMediaReplaced: number}}
359
360
  */
360
361
  export function replaceDemoMedia(source, {videoPlaceholder = ''} = {}) {
362
+ const {source: output, replaced} = mapFixtureRefs(source, ({kind}) =>
363
+ kind === 'video' ? videoPlaceholder : PLACEHOLDER_IMAGE,
364
+ );
365
+ return {source: output, demoMediaReplaced: replaced};
366
+ }
367
+
368
+ /**
369
+ * One Astryx template fixture reference in template source.
370
+ * @typedef {object} FixtureRef
371
+ * @property {string} reference - The whole reference, query and fragment
372
+ * included.
373
+ * @property {'image' | 'video'} kind - What the suffix of its last path
374
+ * segment names.
375
+ * @property {boolean} isValue - Whether the reference is a whole quoted or
376
+ * `url()` value. False for a mention in text.
377
+ */
378
+
379
+ /**
380
+ * Replace each Astryx template fixture reference with what `map` returns for
381
+ * it. This is the one scanner for fixture references: a copy replaces them
382
+ * with placeholders ({@link replaceDemoMedia}), and the docsite's preview
383
+ * build points them at its image optimizer. It finds and refuses references
384
+ * as {@link stripTemplateAssetRefs} describes.
385
+ *
386
+ * @param {string} source - Template source code.
387
+ * @param {(ref: FixtureRef) => string | null} map - The replacement text, or
388
+ * null to keep the reference as written.
389
+ * @returns {{source: string, replaced: number}} `replaced` counts the
390
+ * references that `map` replaced.
391
+ */
392
+ export function mapFixtureRefs(source, map) {
361
393
  const needle = `/${FIXTURE_SEGMENT}`;
362
394
  let output = '';
363
395
  let copied = 0;
364
- let demoMediaReplaced = 0;
396
+ let replaced = 0;
365
397
  /** @type {Array<[number, number]> | undefined} */
366
398
  let comments;
367
399
  let at = source.indexOf(needle);
@@ -373,7 +405,7 @@ export function replaceDemoMedia(source, {videoPlaceholder = ''} = {}) {
373
405
  /** @type {{text: string, end: number} | null} */
374
406
  let edit;
375
407
  try {
376
- edit = fixtureEdit(source, start, at, end, videoPlaceholder);
408
+ edit = fixtureEdit(source, start, at, end, map);
377
409
  } catch (err) {
378
410
  comments ??= commentRanges(source);
379
411
  if (!comments.some(([from, to]) => from <= at && at < to)) throw err;
@@ -382,11 +414,11 @@ export function replaceDemoMedia(source, {videoPlaceholder = ''} = {}) {
382
414
  if (edit) {
383
415
  output += source.slice(copied, start) + edit.text;
384
416
  copied = edit.end;
385
- demoMediaReplaced += 1;
417
+ replaced += 1;
386
418
  }
387
419
  at = source.indexOf(needle, end);
388
420
  }
389
- return {source: output + source.slice(copied), demoMediaReplaced};
421
+ return {source: output + source.slice(copied), replaced};
390
422
  }
391
423
 
392
424
  /**
@@ -911,15 +943,15 @@ function fixtureSegments(reference) {
911
943
  /**
912
944
  * The replacement for the fixture reference in the URL token [start, end),
913
945
  * which contains FIXTURE_SEGMENT's path at `at`; null when the token is not a
914
- * fixture reference or is a prose mention.
946
+ * fixture reference, is a prose mention, or `map` keeps it.
915
947
  * @param {string} source
916
948
  * @param {number} start
917
949
  * @param {number} at
918
950
  * @param {number} end
919
- * @param {string} videoPlaceholder
951
+ * @param {(ref: FixtureRef) => string | null} map
920
952
  * @returns {{text: string, end: number} | null}
921
953
  */
922
- function fixtureEdit(source, start, at, end, videoPlaceholder) {
954
+ function fixtureEdit(source, start, at, end, map) {
923
955
  const token = source.slice(start, end);
924
956
  if (ABSOLUTE_URL.test(token)) return null;
925
957
  if (!token.startsWith('/')) {
@@ -987,11 +1019,17 @@ function fixtureEdit(source, start, at, end, videoPlaceholder) {
987
1019
  .extname(segments[segments.length - 1])
988
1020
  .slice(1)
989
1021
  .toLowerCase();
990
- if (VIDEO_EXTENSIONS.has(ext)) {
991
- return {text: videoPlaceholder, end: referenceEnd};
992
- }
993
- if (IMAGE_EXTENSIONS.has(ext)) {
994
- return {text: PLACEHOLDER_IMAGE, end: referenceEnd};
1022
+ /** @type {FixtureRef['kind'] | null} */
1023
+ let kind = null;
1024
+ if (VIDEO_EXTENSIONS.has(ext)) kind = 'video';
1025
+ else if (IMAGE_EXTENSIONS.has(ext)) kind = 'image';
1026
+ if (kind) {
1027
+ const text = map({
1028
+ reference: source.slice(start, referenceEnd),
1029
+ kind,
1030
+ isValue: whole,
1031
+ });
1032
+ return text === null ? null : {text, end: referenceEnd};
995
1033
  }
996
1034
  if (whole || ext) {
997
1035
  throw new Error(
@@ -2109,13 +2147,7 @@ export function componentsInSource(src) {
2109
2147
  return parsedComponents(src);
2110
2148
  }
2111
2149
 
2112
- /** Where the component lists of the templates Astryx ships are stored. */
2113
- export const TEMPLATE_COMPONENTS_FILE = path.join(
2114
- CLI_ROOT,
2115
- 'assets',
2116
- 'templates',
2117
- 'components.generated.json',
2118
- );
2150
+ export {TEMPLATE_COMPONENTS_FILE} from './template-source-tree.mjs';
2119
2151
 
2120
2152
  /**
2121
2153
  * The components a template source composes, read from its syntax tree (see
@@ -16,6 +16,25 @@
16
16
  * `@scope/name`, unscoped to the first path segment).
17
17
  */
18
18
  export function extractImportedPackages(source: string): Set<string>;
19
+ /**
20
+ * moduleSpecifiers, read from the source's syntax tree.
21
+ * @param {string} source
22
+ * @returns {string[]}
23
+ */
24
+ export function parsedSpecifiers(source: string): string[];
25
+ /**
26
+ * The command that installs `packages` in the project at `cwd`, in its package
27
+ * manager and with the CLI workspace's version ranges. Null, with the reason,
28
+ * when several lockfiles leave the package manager undetermined; null with no
29
+ * reason when there is nothing to install.
30
+ * @param {string[]} packages
31
+ * @param {string} cwd
32
+ * @returns {{installCommand: string | null, noCommandReason: string | null}}
33
+ */
34
+ export function installCommandFor(packages: string[], cwd: string): {
35
+ installCommand: string | null;
36
+ noCommandReason: string | null;
37
+ };
19
38
  /**
20
39
  * Analyze what a template source needs that the target project lacks.
21
40
  *