@astryxdesign/cli 0.7.14-canary.gfb823d9 → 0.7.14

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 (135) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/component/_adapter.d.mts +15 -0
  3. package/api/component/_adapter.mjs +76 -0
  4. package/api/component/component.mjs +8 -1
  5. package/api/search/_named-keywords.d.mts +31 -0
  6. package/api/search/_named-keywords.mjs +177 -0
  7. package/api/search/search-index.mjs +8 -1
  8. package/api/search/search.d.mts +6 -1
  9. package/api/search/search.mjs +49 -8
  10. package/api/theme/_adapter.d.mts +33 -0
  11. package/api/theme/_adapter.mjs +352 -16
  12. package/api/theme/build/build.mjs +261 -10
  13. package/api/theme/eject/eject.mjs +13 -1
  14. package/api/theme/list/list.mjs +11 -2
  15. package/api/theme/palette/generate/color.d.mts +2 -0
  16. package/api/theme/palette/generate/color.mjs +1 -1
  17. package/api/theme/template/template.mjs +139 -6
  18. package/api/theme/theme.type.d.mts +15 -1
  19. package/api/theme/theme.type.mjs +9 -3
  20. package/api/theme/themeAdd.doc.mjs +1 -1
  21. package/api/theme/themeBuild.doc.mjs +10 -2
  22. package/api/theme/themeEject.doc.mjs +2 -2
  23. package/api/theme/themeListAvailable.doc.mjs +1 -1
  24. package/api/theme/themeRemove.doc.mjs +1 -1
  25. package/api/theme/themeTemplate.doc.mjs +8 -0
  26. package/api/theme/themeUse.doc.mjs +1 -1
  27. package/api/theme-edit/_adapter.d.mts +36 -2
  28. package/api/theme-edit/_adapter.mjs +340 -12
  29. package/api/theme-edit/_check.d.mts +28 -25
  30. package/api/theme-edit/_check.mjs +876 -308
  31. package/api/theme-edit/_color.d.mts +53 -4
  32. package/api/theme-edit/_color.mjs +406 -79
  33. package/api/theme-edit/_compiler.d.mts +14 -6
  34. package/api/theme-edit/_compiler.mjs +89 -59
  35. package/api/theme-edit/_context.d.mts +28 -8
  36. package/api/theme-edit/_context.mjs +142 -19
  37. package/api/theme-edit/_edit.d.mts +3 -1
  38. package/api/theme-edit/_edit.mjs +746 -76
  39. package/api/theme-edit/_how-commands.d.mts +91 -0
  40. package/api/theme-edit/_how-commands.mjs +269 -0
  41. package/api/theme-edit/_how-question.d.mts +57 -0
  42. package/api/theme-edit/_how-question.mjs +2574 -0
  43. package/api/theme-edit/_how.d.mts +27 -8
  44. package/api/theme-edit/_how.mjs +776 -175
  45. package/api/theme-edit/_overview.d.mts +9 -0
  46. package/api/theme-edit/_overview.mjs +296 -0
  47. package/api/theme-edit/_palette.d.mts +155 -15
  48. package/api/theme-edit/_palette.mjs +1446 -262
  49. package/api/theme-edit/_parts.mjs +61 -5
  50. package/api/theme-edit/_png.d.mts +18 -6
  51. package/api/theme-edit/_png.mjs +135 -25
  52. package/api/theme-edit/_preview-app.d.mts +32 -11
  53. package/api/theme-edit/_preview-app.mjs +1976 -285
  54. package/api/theme-edit/_preview.d.mts +39 -8
  55. package/api/theme-edit/_preview.mjs +367 -41
  56. package/api/theme-edit/_settings.d.mts +147 -11
  57. package/api/theme-edit/_settings.mjs +908 -99
  58. package/api/theme-edit/_tables.d.mts +4 -16
  59. package/api/theme-edit/_tables.mjs +51 -117
  60. package/api/theme-edit/theme-edit.type.d.mts +102 -66
  61. package/api/theme-edit/theme-edit.type.mjs +58 -40
  62. package/api/theme-edit/themeEditHow.doc.mjs +17 -6
  63. package/api/theme-edit/themeEditNew.doc.mjs +21 -5
  64. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +18 -5
  65. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -9
  66. package/api/theme-edit/themeEditPreviewList.doc.mjs +11 -2
  67. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +29 -3
  68. package/api/theme-edit/themeEditSet.doc.mjs +14 -8
  69. package/api/theme-edit/themeEditShow.doc.mjs +10 -5
  70. package/api/theme-edit/themeEditUndo.doc.mjs +9 -4
  71. package/assets/discover/official-packages.json +4 -0
  72. package/assets/docs/tree/icon-sets.doc.mjs +3 -3
  73. package/assets/docs.generated.json +1 -0
  74. package/assets/icons/definitions/bookmarkAdd.doc.mjs +9 -0
  75. package/assets/icons/definitions/documentSearch.doc.mjs +9 -0
  76. package/assets/icons/definitions/keyboard.doc.mjs +9 -0
  77. package/assets/icons/definitions/paintBrush.doc.mjs +9 -0
  78. package/assets/icons/definitions/wallet.doc.mjs +9 -0
  79. package/assets/preview-app/gitignore +3 -0
  80. package/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs +1 -1
  81. package/assets/templates/blocks/components/Lightbox/LightboxGallery.tsx +1 -1
  82. package/assets/templates/components.generated.json +1 -0
  83. package/assets/templates/pages/gallery-hero/page.tsx +8 -2
  84. package/assets/templates/pages/settings-dialog/template.doc.mjs +3 -3
  85. package/assets/templates/pages/side-gallery/page.tsx +1 -1
  86. package/assets/templates/pages/table-filter/template.doc.mjs +2 -2
  87. package/assets/templates/pages/theme-showcase/template.doc.mjs +1 -1
  88. package/clients/cli/bin/astryx.mjs +37 -5
  89. package/clients/cli/commands/experimental/theme.mjs +422 -57
  90. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +22 -9
  91. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +103 -4
  92. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +13 -8
  93. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +5 -5
  94. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +5 -5
  95. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  96. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  97. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -8
  98. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  99. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  100. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  101. package/clients/cli/commands/experimental-theme.doc.mjs +3 -4
  102. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  103. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  104. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  105. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  106. package/clients/cli/commands/theme.mjs +145 -46
  107. package/clients/cli/commands.generated.json +1 -0
  108. package/clients/cli/index.mjs +96 -5
  109. package/clients/cli/lib/json-shim.mjs +29 -1
  110. package/foundation/config/project.d.mts +16 -2
  111. package/foundation/config/project.mjs +40 -6
  112. package/foundation/config/theme-state.d.mts +9 -0
  113. package/foundation/config/theme-state.mjs +20 -1
  114. package/foundation/discovery/template-adapter.d.mts +12 -1
  115. package/foundation/discovery/template-adapter.mjs +29 -4
  116. package/foundation/discovery/template-icons.d.mts +13 -0
  117. package/foundation/discovery/template-icons.mjs +76 -0
  118. package/foundation/discovery/template-needs.d.mts +7 -0
  119. package/foundation/discovery/template-needs.mjs +117 -8
  120. package/foundation/discovery/template-source-tree.d.mts +5 -1
  121. package/foundation/discovery/template-source-tree.mjs +6 -4
  122. package/foundation/discovery/theme-discovery.d.mts +14 -3
  123. package/foundation/discovery/theme-discovery.mjs +45 -12
  124. package/foundation/doc-compiler/import.mjs +68 -3
  125. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  126. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  127. package/foundation/fs/fs-error.d.mts +17 -0
  128. package/foundation/fs/fs-error.mjs +34 -0
  129. package/foundation/response/error-codes.d.mts +3 -1
  130. package/foundation/response/error-codes.doc.mjs +13 -1
  131. package/foundation/response/error-codes.mjs +11 -1
  132. package/foundation/response/response-types.doc.mjs +6 -6
  133. package/package.json +6 -7
  134. package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +0 -73
  135. package/clients/cli/commands/experimental-theme-palette.doc.mjs +0 -37
@@ -35,6 +35,7 @@
35
35
 
36
36
  import * as fs from 'node:fs';
37
37
  import * as path from 'node:path';
38
+ import {LOCAL_THEME_ROOT} from './theme-state.mjs';
38
39
  import {loadModuleWithParser} from '../fs/module-loader.mjs';
39
40
  import {findConfigPath} from './config-path.mjs';
40
41
  import {parseConfig} from '../../authoring/config/parse.mjs';
@@ -324,7 +325,6 @@ function readPackageJson(dir) {
324
325
  * @typedef {import('../integrations/issue').AstryxIntegrationIssue & {package: string}} ProjectIntegrationIssue
325
326
  */
326
327
 
327
-
328
328
  /** Default issue tracker used when neither config nor integration routes one. */
329
329
  export const DEFAULT_ISSUES_URL =
330
330
  'https://github.com/meta/astryx/issues/new';
@@ -364,7 +364,6 @@ function inheritsIntegrationDebug(projectDir) {
364
364
  }
365
365
  }
366
366
 
367
-
368
367
  /**
369
368
  * The provider ledger each loaded Project resolved, kept off the class so it
370
369
  * is not part of the Project API.
@@ -419,6 +418,8 @@ export class Project {
419
418
  #core = 'any';
420
419
  /** @type {ProjectIntegrationIssue[]} */
421
420
  #issues = [];
421
+ /** @type {Array<{slug: string, path: string, reason: string}>} */
422
+ #skippedLocalThemes = [];
422
423
  /**
423
424
  * Loaded integrations whose issues have already been collected (via a
424
425
  * discovery method or a direct issues() validation), so issues() can fill in
@@ -925,14 +926,39 @@ export class Project {
925
926
  * ejects share one discovery seam. A broken integration theme contribution is
926
927
  * reported without hiding the package's other valid kinds.
927
928
  *
928
- * @param {{includeLocal?: boolean}} [options]
929
+ * With `skipBrokenLocal`, a local theme folder that fails validation is
930
+ * left out and recorded for `skippedLocalThemes()`, so one broken folder
931
+ * does not hide every other theme.
932
+ *
933
+ * @param {{includeLocal?: boolean, skipBrokenLocal?: boolean}} [options]
929
934
  * @returns {Promise<import('../discovery/theme-discovery.mjs').DiscoveredTheme[]>}
930
935
  */
931
- async themes({includeLocal = true} = {}) {
932
- return this.#memo(includeLocal ? 'themes' : 'themes:external', async () => {
936
+ async themes({includeLocal = true, skipBrokenLocal = false} = {}) {
937
+ const kind = !includeLocal
938
+ ? 'themes:external'
939
+ : skipBrokenLocal
940
+ ? 'themes:skip-broken'
941
+ : 'themes';
942
+ return this.#memo(kind, async () => {
933
943
  const themes = discoverBundledThemes();
934
944
  const projectDir = findPackageRoot(this.#cwd) ?? this.#cwd;
935
- if (includeLocal) themes.push(...discoverLocalThemes(projectDir));
945
+ if (includeLocal) {
946
+ themes.push(
947
+ ...discoverLocalThemes(projectDir, undefined, {
948
+ onFolderError: skipBrokenLocal
949
+ ? (slug, error) =>
950
+ this.#skippedLocalThemes.push({
951
+ slug,
952
+ path: path.posix.join(
953
+ LOCAL_THEME_ROOT.replace(/^\.\//, ''),
954
+ slug,
955
+ ),
956
+ reason: error.message,
957
+ })
958
+ : undefined,
959
+ }),
960
+ );
961
+ }
936
962
 
937
963
  for (const integration of this.#loadedIntegrations) {
938
964
  await this.#collectIssues(integration);
@@ -953,6 +979,14 @@ export class Project {
953
979
  });
954
980
  }
955
981
 
982
+ /**
983
+ * Local theme folders `themes({skipBrokenLocal: true})` left out, with why.
984
+ * @returns {Array<{slug: string, path: string, reason: string}>}
985
+ */
986
+ skippedLocalThemes() {
987
+ return this.#skippedLocalThemes.map(entry => ({...entry}));
988
+ }
989
+
956
990
  /**
957
991
  * Installed icon sets, the sets withdrawn and why, and the project's icon
958
992
  * set (AST-084 FR7, FR8). Sets come from each loaded integration's
@@ -17,6 +17,15 @@ export function findThemeProject(cwd: string): {
17
17
  * @param {string} owner
18
18
  */
19
19
  export function isLocalThemeOwner(owner: string): boolean;
20
+ /**
21
+ * The theme editor's record for the theme in `dir`, when the editor made it:
22
+ * the folder `<slug>/` holds `<slug>.settings.json`. The editor owns every
23
+ * theme file in that folder and regenerates it from the record, so eject and
24
+ * template never write there. Another `*.settings.json` is not the editor's.
25
+ * @param {string} dir
26
+ * @returns {string | null} the record's file name
27
+ */
28
+ export function editorThemeRecord(dir: string): string | null;
20
29
  /** @param {string} projectDir */
21
30
  export function projectUsesTypeScript(projectDir: string): boolean;
22
31
  /**
@@ -62,7 +62,26 @@ export function findThemeProject(cwd) {
62
62
  * @param {string} owner
63
63
  */
64
64
  export function isLocalThemeOwner(owner) {
65
- return owner.startsWith('./') || owner.startsWith('../') || path.isAbsolute(owner);
65
+ return (
66
+ owner.startsWith('./') || owner.startsWith('../') || path.isAbsolute(owner)
67
+ );
68
+ }
69
+
70
+ /**
71
+ * The theme editor's record for the theme in `dir`, when the editor made it:
72
+ * the folder `<slug>/` holds `<slug>.settings.json`. The editor owns every
73
+ * theme file in that folder and regenerates it from the record, so eject and
74
+ * template never write there. Another `*.settings.json` is not the editor's.
75
+ * @param {string} dir
76
+ * @returns {string | null} the record's file name
77
+ */
78
+ export function editorThemeRecord(dir) {
79
+ const record = `${path.basename(path.resolve(dir))}.settings.json`;
80
+ try {
81
+ return fs.statSync(path.join(dir, record)).isFile() ? record : null;
82
+ } catch {
83
+ return null;
84
+ }
66
85
  }
67
86
 
68
87
  /** @param {string} projectDir */
@@ -234,11 +234,20 @@ export function extractComponents(pagePath: string): string[];
234
234
  /**
235
235
  * The components a template source composes. A surface that returns rewritten
236
236
  * source lists the components of that source, so a component the rewrite
237
- * removed is not listed.
237
+ * removed is not listed. A template Astryx ships answers from its stored list
238
+ * (TEMPLATE_COMPONENTS_FILE), which holds what parsing it returns; any other
239
+ * source, such as an integration's template, is parsed.
238
240
  * @param {string} src
239
241
  * @returns {string[]}
240
242
  */
241
243
  export function componentsInSource(src: string): string[];
244
+ /**
245
+ * The components a template source composes, read from its syntax tree (see
246
+ * componentsInSource).
247
+ * @param {string} src
248
+ * @returns {string[]}
249
+ */
250
+ export function parsedComponents(src: string): string[];
242
251
  /**
243
252
  * Every name componentsInSource can return for `src`, read without parsing
244
253
  * it, or null when it cannot be bounded so. It keeps the tag names a parse
@@ -264,6 +273,8 @@ export const MARKED_VIDEO_PLACEHOLDER: "data:,placeholder-video-add-your-own";
264
273
  * {@link replaceDemoContent}).
265
274
  */
266
275
  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;
267
278
  /**
268
279
  * A discovered template (page or block), normalized across core, external, and
269
280
  * integration sources. Not every source populates every field, so
@@ -27,6 +27,7 @@ import * as path from 'node:path';
27
27
  import {createRequire} from 'node:module';
28
28
  import {readDocView} from '../doc-compiler/read.mjs';
29
29
  import {importDocModule} from '../doc-compiler/import.mjs';
30
+ import {readStore, storedKey} from '../doc-compiler/stored-docs.mjs';
30
31
  import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';
31
32
  import {listDirEntries} from '../fs/listing-cache.mjs';
32
33
  import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
@@ -219,11 +220,13 @@ const BLOCKS_DIR = path.join(TEMPLATES_DIR, 'blocks');
219
220
  /**
220
221
  * Inline placeholder swapped in for demo imagery when scaffolding a template,
221
222
  * so scaffolded pages render with zero setup (see stripTemplateAssetRefs).
222
- * Neutral hex colors (not design tokens) so it renders in any project, themed
223
- * or not. Mirrors apps/docsite/public/template-assets/placeholder.svg.
223
+ * A gray at low opacity, not design tokens, so it renders in any project,
224
+ * themed or not, and takes its tone from the surface behind it: light on a
225
+ * light page, dark in dark mode. Mirrors
226
+ * apps/docsite/public/template-assets/placeholder.svg.
224
227
  */
225
228
  const PLACEHOLDER_IMAGE =
226
- 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20400%20300%22%20preserveAspectRatio%3D%22xMidYMid%20slice%22%3E%3Crect%20width%3D%22400%22%20height%3D%22300%22%20fill%3D%22%23f5f6f8%22%2F%3E%3Cg%20transform%3D%22translate%28200%20150%29%22%20fill%3D%22none%22%20stroke%3D%22%23c2cad6%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%22-44%22%20y%3D%22-44%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2216%22%2F%3E%3Ccircle%20cx%3D%2218%22%20cy%3D%22-18%22%20r%3D%222.5%22%20fill%3D%22%23c2cad6%22%20stroke%3D%22none%22%2F%3E%3Cpath%20d%3D%22M-34%2030%20L-8%200%20L10%2018%20L20%208%20L34%2024%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E';
229
+ 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20400%20300%22%20preserveAspectRatio%3D%22xMidYMid%20slice%22%3E%3Crect%20width%3D%22400%22%20height%3D%22300%22%20fill%3D%22%23808080%22%20fill-opacity%3D%220.12%22%2F%3E%3Cg%20transform%3D%22translate%28200%20150%29%22%20fill%3D%22none%22%20stroke%3D%22%23808080%22%20stroke-opacity%3D%220.55%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%22-44%22%20y%3D%22-44%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2216%22%2F%3E%3Ccircle%20cx%3D%2218%22%20cy%3D%22-18%22%20r%3D%222.5%22%20fill%3D%22%23808080%22%20fill-opacity%3D%220.55%22%20stroke%3D%22none%22%2F%3E%3Cpath%20d%3D%22M-34%2030%20L-8%200%20L10%2018%20L20%208%20L34%2024%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E';
227
230
 
228
231
  /**
229
232
  * Extensions that need a video-safe placeholder rather than the image data
@@ -2094,11 +2097,33 @@ export function extractComponents(pagePath) {
2094
2097
  /**
2095
2098
  * The components a template source composes. A surface that returns rewritten
2096
2099
  * source lists the components of that source, so a component the rewrite
2097
- * removed is not listed.
2100
+ * removed is not listed. A template Astryx ships answers from its stored list
2101
+ * (TEMPLATE_COMPONENTS_FILE), which holds what parsing it returns; any other
2102
+ * source, such as an integration's template, is parsed.
2098
2103
  * @param {string} src
2099
2104
  * @returns {string[]}
2100
2105
  */
2101
2106
  export function componentsInSource(src) {
2107
+ const known = readStore(TEMPLATE_COMPONENTS_FILE).get(storedKey(src));
2108
+ if (known) return [...known];
2109
+ return parsedComponents(src);
2110
+ }
2111
+
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
+ );
2119
+
2120
+ /**
2121
+ * The components a template source composes, read from its syntax tree (see
2122
+ * componentsInSource).
2123
+ * @param {string} src
2124
+ * @returns {string[]}
2125
+ */
2126
+ export function parsedComponents(src) {
2102
2127
  // Match JSX opening tags, e.g. `<Section` or the legacy `<XDSSection`.
2103
2128
  // Templates author bare component names post un-prefix migration,
2104
2129
  // so the `XDS` prefix is optional. Anchoring on the `<`
@@ -73,6 +73,19 @@ export function matchIcon(source: SourceIcon, target: DiscoveredIconSet): {
73
73
  * @returns {string[] | null}
74
74
  */
75
75
  export function iconsNotImported(source: string, declared: Record<string, string>): string[] | null;
76
+ /**
77
+ * The definitions that two different icons in one template's `icons` share.
78
+ * A set draws one icon for each definition, so two different icons with one
79
+ * definition draw the same icon in every set. Two keys that differ only by an
80
+ * `Icon` suffix (`Trash2` and `Trash2Icon`) are one icon and never conflict.
81
+ * @param {Record<string, string>} declared
82
+ * @returns {Array<{definition: string, keys: string[]}>} each shared
83
+ * definition with its keys, sorted by definition
84
+ */
85
+ export function sharedTemplateMeanings(declared: Record<string, string>): Array<{
86
+ definition: string;
87
+ keys: string[];
88
+ }>;
76
89
  /**
77
90
  * The value imports a template takes from other packages, as the keys its
78
91
  * `icons` uses: a named import by the name it imports, a default import by
@@ -21,6 +21,10 @@
21
21
  * a meaning that no set in the list has loses its library import: each of its
22
22
  * uses renders a placeholder component that the file declares once, with a
23
23
  * comment that names the meaning, so the copied code needs no new package.
24
+ * An import from the library a listed set wraps (its data's `source`) is an
25
+ * icon the project chose: the main set's own library keeps its imports as
26
+ * written, and another set's library keeps an icon no set maps instead of a
27
+ * placeholder.
24
28
  * A declared key names a named import by the name it imports
25
29
  * (`{Trash as TrashIcon}` is `Trash`) and a default import by its local name
26
30
  * (`import DeleteIcon from …` is `DeleteIcon`). A mapped named import and
@@ -476,6 +480,19 @@ function isAstryxModule(module) {
476
480
  return module.startsWith('@astryxdesign/');
477
481
  }
478
482
 
483
+ /**
484
+ * Whether a set wraps the library a module belongs to: the module is the
485
+ * package the set's data names as its `source`, or a subpath of it.
486
+ * @param {DiscoveredIconSet} set
487
+ * @param {string} module
488
+ */
489
+ function wrapsModule(set, module) {
490
+ const library = set.data.source?.package;
491
+ return (
492
+ library != null && (module === library || module.startsWith(`${library}/`))
493
+ );
494
+ }
495
+
479
496
  /**
480
497
  * The name an import specifier reads from its module: `default` for a
481
498
  * default import, `*` for a namespace import.
@@ -563,6 +580,30 @@ export function iconsNotImported(source, declared) {
563
580
  return Object.keys(declared).filter(key => !keys.has(key));
564
581
  }
565
582
 
583
+ /**
584
+ * The definitions that two different icons in one template's `icons` share.
585
+ * A set draws one icon for each definition, so two different icons with one
586
+ * definition draw the same icon in every set. Two keys that differ only by an
587
+ * `Icon` suffix (`Trash2` and `Trash2Icon`) are one icon and never conflict.
588
+ * @param {Record<string, string>} declared
589
+ * @returns {Array<{definition: string, keys: string[]}>} each shared
590
+ * definition with its keys, sorted by definition
591
+ */
592
+ export function sharedTemplateMeanings(declared) {
593
+ /** @type {Map<string, Map<string, string>>} definition → icon → first key */
594
+ const byDefinition = new Map();
595
+ for (const [key, definition] of Object.entries(declared)) {
596
+ const icons = byDefinition.get(definition) ?? new Map();
597
+ const icon = key.replace(/Icon$/u, '');
598
+ if (!icons.has(icon)) icons.set(icon, key);
599
+ byDefinition.set(definition, icons);
600
+ }
601
+ return [...byDefinition]
602
+ .filter(([, icons]) => icons.size > 1)
603
+ .map(([definition, icons]) => ({definition, keys: [...icons.values()]}))
604
+ .sort((a, b) => a.definition.localeCompare(b.definition));
605
+ }
606
+
566
607
  /**
567
608
  * Whether a module is a package import: not relative, not absolute, and not
568
609
  * a Node built-in.
@@ -847,6 +888,12 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {
847
888
  * @type {Map<any, {record: SourceIcon, set: DiscoveredIconSet, match: ReturnType<typeof matchIcon>}>}
848
889
  */
849
890
  const planned = new Map();
891
+ /**
892
+ * Each import specifier kept because it comes from the library a listed
893
+ * set wraps, and that set.
894
+ * @type {Map<any, DiscoveredIconSet>}
895
+ */
896
+ const wrapped = new Map();
850
897
  for (const node of ast.program.body) {
851
898
  if (node.type !== 'ImportDeclaration' || node.importKind === 'type')
852
899
  continue;
@@ -888,6 +935,14 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {
888
935
  }
889
936
  : null;
890
937
  if (!record || (record.set && targets.includes(record.set))) continue;
938
+ // An import from the library a listed set wraps is already an icon
939
+ // the project chose. The main set's own library keeps its icons as
940
+ // written; another set's library keeps an icon that no set maps.
941
+ const wrapper = targets.find(each => wrapsModule(each, module));
942
+ if (wrapper === target) {
943
+ wrapped.set(specifier, wrapper);
944
+ continue;
945
+ }
891
946
  /** @type {{set: DiscoveredIconSet, match: ReturnType<typeof matchIcon>}} */
892
947
  let found = {set: target, match: null};
893
948
  for (const each of targets) {
@@ -897,6 +952,10 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {
897
952
  break;
898
953
  }
899
954
  }
955
+ if (!found.match && wrapper) {
956
+ wrapped.set(specifier, wrapper);
957
+ continue;
958
+ }
900
959
  planned.set(specifier, {record, ...found});
901
960
  if (found.match || record.definitions.length > 0) {
902
961
  freed.add(specifier.local.name);
@@ -1096,6 +1155,23 @@ export function mapTemplateIcons(source, {sets, choice}, declared = {}) {
1096
1155
  }
1097
1156
  }
1098
1157
 
1158
+ for (const node of ast.program.body) {
1159
+ if (node.type !== 'ImportDeclaration') continue;
1160
+ for (const specifier of node.specifiers) {
1161
+ const wrapper = wrapped.get(specifier);
1162
+ if (!wrapper) continue;
1163
+ accounted.add(declaredKey(specifier));
1164
+ icons.kept.push({
1165
+ module: node.source.value,
1166
+ export: importedName(specifier),
1167
+ reason:
1168
+ wrapper === target
1169
+ ? `it already comes from ${node.source.value}, which ${icons.set} wraps`
1170
+ : `no set in your list maps its icon definition, and it already comes from ${node.source.value}, which ${wrapper.package}/${wrapper.name} wraps`,
1171
+ });
1172
+ }
1173
+ }
1174
+
1099
1175
  // Every other declared key is kept, with why it was not mapped (FR10).
1100
1176
  const bindings = iconBindings(ast);
1101
1177
  for (const key of Object.keys(declared)) {
@@ -4,6 +4,13 @@
4
4
  /**
5
5
  * Extract bare (non-relative) package names from ES import statements.
6
6
  *
7
+ * Only real module specifiers count: `import … from`, a side-effect
8
+ * `import '…'`, `export … from`, a dynamic `import('…')` or `require('…')`
9
+ * with a string, and a type `import('…')`.
10
+ * Words in comments, strings and JSX text never count, and a specifier that
11
+ * is not an npm package name (`@/components`, `~/lib`, `#internal`, a word
12
+ * with spaces) is an alias or a typo, not a package to install.
13
+ *
7
14
  * @param {string} source Template source code
8
15
  * @returns {Set<string>} Unique package names (scoped packages normalized to
9
16
  * `@scope/name`, unscoped to the first path segment).
@@ -18,6 +18,7 @@
18
18
  import * as fs from 'node:fs';
19
19
  import * as path from 'node:path';
20
20
  import module from 'node:module';
21
+ import {parseTemplateSource, walk} from './template-source-tree.mjs';
21
22
  import {CLI_ROOT, findWorkspaceRoot} from '../fs/paths.mjs';
22
23
  import {detectStylingSystem} from '../agent-docs/agent-docs.mjs';
23
24
  import {
@@ -35,34 +36,142 @@ const STYLEX_RUNTIME = '@stylexjs/stylex';
35
36
  // Node builtins: anything with a `node:` prefix or in builtinModules.
36
37
  const NODE_BUILTINS = new Set(module.builtinModules);
37
38
 
39
+ /**
40
+ * A package name npm accepts, optionally scoped. Legacy names keep capitals
41
+ * (`JSONStream`). A name has no `~`, so `~/lib` is a path alias, as are
42
+ * `@/components` and `#internal`.
43
+ */
44
+ const NPM_NAME = /^(?:@[\w.-]+\/[\w-][\w.-]*|[A-Za-z0-9][\w.-]*)$/;
45
+
38
46
  /**
39
47
  * Extract bare (non-relative) package names from ES import statements.
40
48
  *
49
+ * Only real module specifiers count: `import … from`, a side-effect
50
+ * `import '…'`, `export … from`, a dynamic `import('…')` or `require('…')`
51
+ * with a string, and a type `import('…')`.
52
+ * Words in comments, strings and JSX text never count, and a specifier that
53
+ * is not an npm package name (`@/components`, `~/lib`, `#internal`, a word
54
+ * with spaces) is an alias or a typo, not a package to install.
55
+ *
41
56
  * @param {string} source Template source code
42
57
  * @returns {Set<string>} Unique package names (scoped packages normalized to
43
58
  * `@scope/name`, unscoped to the first path segment).
44
59
  */
45
60
  export function extractImportedPackages(source) {
46
- // Matches `import … from '<specifier>'`, `import '<specifier>'`, and
47
- // dynamic `import('<specifier>')`. Only bare specifiers (not starting with
48
- // `.` or `/`).
49
- const re = /(?:from\s+|import\s*\(?)['"]((?:@[^/'"]+\/)?[^./'"@][^'"]*)['"]/g;
50
61
  /** @type {Set<string>} */
51
62
  const pkgs = new Set();
52
- let m;
53
- while ((m = re.exec(source)) !== null) {
54
- const spec = m[1];
63
+ for (const spec of moduleSpecifiers(source)) {
55
64
  // Skip Node builtins: `node:fs`, `fs`, `fs/promises`, etc.
56
65
  if (spec.startsWith('node:')) continue;
66
+ if (spec.startsWith('.') || spec.startsWith('/')) continue;
57
67
  const name = spec.startsWith('@')
58
68
  ? spec.split('/').slice(0, 2).join('/')
59
69
  : spec.split('/')[0];
60
- if (NODE_BUILTINS.has(name)) continue;
70
+ if (NODE_BUILTINS.has(name) || !NPM_NAME.test(name)) continue;
61
71
  pkgs.add(name);
62
72
  }
63
73
  return pkgs;
64
74
  }
65
75
 
76
+ /**
77
+ * The module specifiers a source imports or re-exports, read from its syntax
78
+ * tree. A source the parser cannot read is scanned line by line instead, with
79
+ * comments removed, so only statements that start a line count.
80
+ * @param {string} source
81
+ * @returns {string[]}
82
+ */
83
+ function moduleSpecifiers(source) {
84
+ let file;
85
+ try {
86
+ file = parseTemplateSource(source, {errorRecovery: true});
87
+ } catch {
88
+ return scannedSpecifiers(source);
89
+ }
90
+ /** @type {string[]} */
91
+ const specs = [];
92
+ /** @param {any} literal */
93
+ const add = literal => {
94
+ if (literal?.type === 'StringLiteral') specs.push(literal.value);
95
+ };
96
+ walk(file.program, (/** @type {any} */ node) => {
97
+ if (
98
+ node.type === 'ImportDeclaration' ||
99
+ node.type === 'ExportNamedDeclaration' ||
100
+ node.type === 'ExportAllDeclaration'
101
+ ) {
102
+ add(node.source);
103
+ } else if (
104
+ node.type === 'CallExpression' &&
105
+ node.callee?.type === 'Import'
106
+ ) {
107
+ add(node.arguments?.[0]);
108
+ } else if (
109
+ node.type === 'CallExpression' &&
110
+ node.callee?.type === 'Identifier' &&
111
+ node.callee.name === 'require'
112
+ ) {
113
+ add(node.arguments?.[0]);
114
+ } else if (node.type === 'ImportExpression') {
115
+ add(node.source);
116
+ } else if (node.type === 'TSImportType') {
117
+ // `type O = import('chart-lib').Options`
118
+ add(
119
+ node.argument?.type === 'TSLiteralType'
120
+ ? node.argument.literal
121
+ : node.argument,
122
+ );
123
+ }
124
+ });
125
+ return specs;
126
+ }
127
+
128
+ /**
129
+ * A source with its comments removed. Strings and template literals are kept
130
+ * whole, so a `/*` or `//` inside one (`'images/*'`) does not start a comment.
131
+ * @param {string} source
132
+ * @returns {string}
133
+ */
134
+ function withoutComments(source) {
135
+ let out = '';
136
+ for (let i = 0; i < source.length; i += 1) {
137
+ const ch = source[i];
138
+ const next = source[i + 1];
139
+ if (ch === '/' && next === '/') {
140
+ while (i < source.length && source[i] !== '\n') i += 1;
141
+ out += '\n';
142
+ } else if (ch === '/' && next === '*') {
143
+ const end = source.indexOf('*/', i + 2);
144
+ i = end === -1 ? source.length : end + 1;
145
+ } else if (ch === "'" || ch === '"' || ch === '`') {
146
+ let j = i + 1;
147
+ while (j < source.length && source[j] !== ch) {
148
+ if (source[j] === '\\') j += 1;
149
+ else if (ch !== '`' && source[j] === '\n') break;
150
+ j += 1;
151
+ }
152
+ out += source.slice(i, j + 1);
153
+ i = j;
154
+ } else {
155
+ out += ch;
156
+ }
157
+ }
158
+ return out;
159
+ }
160
+
161
+ /** @param {string} source @returns {string[]} */
162
+ function scannedSpecifiers(source) {
163
+ const code = withoutComments(source);
164
+ // A statement starts a line: `import '…'`, or `import`/`export` with a
165
+ // clause, which may span lines, then `from '…'`.
166
+ const re =
167
+ /^\s*import\s*['"]([^'"\n]+)['"]|^\s*(?:import|export)\b[^'";]*?\bfrom\s*['"]([^'"\n]+)['"]|\bimport\(\s*['"]([^'"\n]+)['"]\s*\)/gm;
168
+ /** @type {string[]} */
169
+ const specs = [];
170
+ let m;
171
+ while ((m = re.exec(code)) !== null) specs.push(m[1] ?? m[2] ?? m[3]);
172
+ return specs;
173
+ }
174
+
66
175
  /** @type {Record<string, string>} */
67
176
  const ADD_VERB = {
68
177
  pnpm: 'pnpm add',
@@ -5,9 +5,13 @@
5
5
  * Parse template source as TSX. Babel loads on first use, so a command that
6
6
  * only lists templates never pays for it.
7
7
  * @param {string} source
8
+ * @param {{errorRecovery?: boolean}} [options] `errorRecovery`: keep parsing
9
+ * past a recoverable error, for a reader that only needs part of the tree
8
10
  * @returns {any} The file node.
9
11
  */
10
- export function parseTemplateSource(source: string): any;
12
+ export function parseTemplateSource(source: string, { errorRecovery }?: {
13
+ errorRecovery?: boolean;
14
+ }): any;
11
15
  /**
12
16
  * The module scope of a parsed file. Its bindings, and the scope of each path
13
17
  * a traversal visits, resolve a name to the declaration it reads, so a rewrite
@@ -7,8 +7,8 @@
7
7
  *
8
8
  * @input Template source text
9
9
  * @output Its parsed tree, node visits, names, and module scope
10
- * @position packages/cli/foundation/discovery — read by template-icons and by
11
- * the demo-content replacement in template-adapter
10
+ * @position packages/cli/foundation/discovery — read by template-icons, by
11
+ * the demo-content replacement in template-adapter, and by template-needs
12
12
  */
13
13
 
14
14
  import {createRequire} from 'node:module';
@@ -24,16 +24,18 @@ let babelCore;
24
24
  * Parse template source as TSX. Babel loads on first use, so a command that
25
25
  * only lists templates never pays for it.
26
26
  * @param {string} source
27
+ * @param {{errorRecovery?: boolean}} [options] `errorRecovery`: keep parsing
28
+ * past a recoverable error, for a reader that only needs part of the tree
27
29
  * @returns {any} The file node.
28
30
  */
29
- export function parseTemplateSource(source) {
31
+ export function parseTemplateSource(source, {errorRecovery = false} = {}) {
30
32
  babelParser ??= /** @type {typeof import('@babel/parser')} */ (
31
33
  require('@babel/parser')
32
34
  );
33
35
  return babelParser.parse(source, {
34
36
  sourceType: 'module',
35
37
  plugins: ['jsx', 'typescript'],
36
- errorRecovery: false,
38
+ errorRecovery,
37
39
  });
38
40
  }
39
41
 
@@ -96,14 +96,20 @@ export function discoverUnmigratedThemeCopies(projectDir: string, owner?: string
96
96
  * Discover and validate one theme root.
97
97
  * @param {string} themeRoot absolute root containing one directory per slug
98
98
  * @param {string} owner package that owns the root
99
- * @param {{bundled?: boolean, allowUnmigrated?: boolean}} [options] a bundled root is the CLI's own; its
99
+ * @param {{bundled?: boolean, allowUnmigrated?: boolean, skip?: Set<string>, progress?: {slug?: string}}} [options] a bundled root is the CLI's own; its
100
100
  * sources are checked by the CLI's tests rather than on every read. A local
101
101
  * root may skip released source copies until `astryx upgrade` adds descriptors.
102
+ * `skip` names theme folders to leave out; `progress.slug` is set to the
103
+ * folder being read, so a caller can tell which folder an error is about.
102
104
  * @returns {DiscoveredTheme[]}
103
105
  */
104
- export function discoverThemeDirectory(themeRoot: string, owner: string, { bundled, allowUnmigrated }?: {
106
+ export function discoverThemeDirectory(themeRoot: string, owner: string, { bundled, allowUnmigrated, skip, progress }?: {
105
107
  bundled?: boolean;
106
108
  allowUnmigrated?: boolean;
109
+ skip?: Set<string>;
110
+ progress?: {
111
+ slug?: string;
112
+ };
107
113
  }): DiscoveredTheme[];
108
114
  /**
109
115
  * Folders under a themes root that look like themes (see looksLikeTheme)
@@ -125,9 +131,14 @@ export function discoverBundledThemes(): DiscoveredTheme[];
125
131
  * Discover authored themes in the app's conventional local themes root.
126
132
  * @param {string} projectDir
127
133
  * @param {string} [owner]
134
+ * @param {{onFolderError?: (slug: string, error: Error) => void}} [options]
135
+ * with `onFolderError`, a theme folder that fails validation is reported
136
+ * through it and left out, so one broken folder does not hide the others
128
137
  * @returns {DiscoveredTheme[]}
129
138
  */
130
- export function discoverLocalThemes(projectDir: string, owner?: string): DiscoveredTheme[];
139
+ export function discoverLocalThemes(projectDir: string, owner?: string, { onFolderError }?: {
140
+ onFolderError?: (slug: string, error: Error) => void;
141
+ }): DiscoveredTheme[];
131
142
  /**
132
143
  * @param {import('../integrations/integrations.mjs').LoadedIntegration} integration
133
144
  * @returns {Promise<DiscoveredTheme[]>}