@astryxdesign/cli 0.7.9-canary.ffa495b → 0.7.10-canary.010db3f

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 (91) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +1 -1
  3. package/api/component/__fixtures__/resolutions/modules.txt +5 -6
  4. package/api/search/_candidate-score.mjs +25 -23
  5. package/api/search/_gather-components.mjs +2 -1
  6. package/api/search/_words.d.mts +44 -7
  7. package/api/search/_words.mjs +113 -21
  8. package/api/swizzle/_adapter.d.mts +10 -0
  9. package/api/swizzle/_adapter.mjs +24 -1
  10. package/api/swizzle/copy/copy.d.mts +17 -1
  11. package/api/swizzle/copy/copy.mjs +249 -9
  12. package/api/swizzle/swizzle.doc.mjs +1 -1
  13. package/api/swizzle/swizzle.type.mjs +1 -1
  14. package/api/theme/build/build.mjs +363 -73
  15. package/api/theme/build/core-interception.mjs +92 -29
  16. package/api/theme/build/icon-imports.d.mts +35 -4
  17. package/api/theme/build/icon-imports.mjs +299 -38
  18. package/assets/discover/official-packages.json +16 -0
  19. package/assets/docs/author-a-theme.doc.mjs +3 -1
  20. package/assets/docs/getting-started.doc.mjs +20 -0
  21. package/assets/docs/icons.doc.mjs +29 -0
  22. package/assets/docs/motion.doc.mjs +1 -1
  23. package/assets/docs/tree/calendar-systems.doc.mjs +146 -0
  24. package/assets/docs/tree/calendars.doc.mjs +46 -0
  25. package/assets/docs/tree/i18n-calendars.doc.mjs +51 -0
  26. package/assets/docs/tree/internationalization.doc.mjs +3 -3
  27. package/assets/templates/blocks/components/Calendar/useCalendarDaysHookUsage.doc.mjs +14 -0
  28. package/assets/templates/blocks/components/Calendar/useCalendarDaysHookUsage.tsx +71 -0
  29. package/assets/templates/blocks/components/Carousel/CarouselSnapPaging.doc.mjs +14 -0
  30. package/assets/templates/blocks/components/Carousel/CarouselSnapPaging.tsx +49 -0
  31. package/assets/templates/blocks/components/Hooks/useInputContainerHookUsage.doc.mjs +15 -0
  32. package/assets/templates/blocks/components/Hooks/useInputContainerHookUsage.tsx +93 -0
  33. package/assets/templates/blocks/components/Hooks/useMergedRefsHookUsage.doc.mjs +14 -0
  34. package/assets/templates/blocks/components/Hooks/useMergedRefsHookUsage.tsx +78 -0
  35. package/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.doc.mjs +14 -0
  36. package/assets/templates/blocks/components/Hooks/useScrollLockHookUsage.tsx +80 -0
  37. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.doc.mjs +14 -0
  38. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.tsx +94 -0
  39. package/assets/templates/blocks/components/Icon/useIconHookUsage.doc.mjs +19 -0
  40. package/assets/templates/blocks/components/Icon/useIconHookUsage.tsx +68 -0
  41. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.doc.mjs +14 -0
  42. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.tsx +89 -0
  43. package/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.doc.mjs +23 -0
  44. package/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.tsx +164 -0
  45. package/assets/templates/blocks/components/Overlay/useOverlayHookUsage.doc.mjs +21 -0
  46. package/assets/templates/blocks/components/Overlay/useOverlayHookUsage.tsx +49 -0
  47. package/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.doc.mjs +14 -0
  48. package/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.tsx +61 -0
  49. package/assets/templates/blocks/components/createDragToSnapPoints/DragToSnapPointsCardVanilla.doc.mjs +14 -0
  50. package/assets/templates/blocks/components/createDragToSnapPoints/DragToSnapPointsCardVanilla.tsx +110 -0
  51. package/assets/templates/blocks/components/useDragToSnapPoints/DragToSnapPointsCard.doc.mjs +21 -0
  52. package/assets/templates/blocks/components/useDragToSnapPoints/DragToSnapPointsCard.tsx +74 -0
  53. package/assets/templates/blocks/components/usePanGesture/PanDraggableBox.doc.mjs +15 -0
  54. package/assets/templates/blocks/components/usePanGesture/PanDraggableBox.tsx +98 -0
  55. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs +14 -0
  56. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx +147 -0
  57. package/assets/templates/pages/ai-chat-landing/page.tsx +0 -9
  58. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +2 -2
  59. package/assets/templates/themes/neutral/neutralTheme.ts +30 -4
  60. package/assets/theme.template.ts +14 -2
  61. package/authoring/doctypes/base/type.ts +41 -0
  62. package/authoring/doctypes/component/component.doc.mjs +7 -1
  63. package/authoring/doctypes/component/type.ts +5 -0
  64. package/authoring/index.d.ts +2 -0
  65. package/clients/cli/commands/ensure-core-built.mjs +399 -43
  66. package/clients/cli/commands/swizzle.mjs +10 -0
  67. package/clients/cli/lib/component-format.mjs +49 -0
  68. package/foundation/config/project.mjs +27 -9
  69. package/foundation/discovery/authoring-self-docs.mjs +2 -2
  70. package/foundation/discovery/cli-self-docs.mjs +2 -1
  71. package/foundation/discovery/component-discovery.mjs +56 -10
  72. package/foundation/discovery/docs-discovery.mjs +6 -4
  73. package/foundation/discovery/icon-definition-discovery.mjs +3 -3
  74. package/foundation/discovery/template-adapter.mjs +5 -7
  75. package/foundation/discovery/theme-discovery.mjs +8 -10
  76. package/foundation/doc-compiler/tree.mjs +2 -2
  77. package/foundation/env/search-path.d.mts +12 -0
  78. package/foundation/env/search-path.mjs +71 -43
  79. package/foundation/fs/listing-cache.d.mts +3 -1
  80. package/foundation/fs/listing-cache.mjs +63 -11
  81. package/foundation/fs/paths.mjs +2 -1
  82. package/foundation/integrations/manifest-writer.d.mts +3 -4
  83. package/foundation/integrations/manifest-writer.mjs +5 -3
  84. package/foundation/release/cache.d.mts +11 -4
  85. package/foundation/release/cache.mjs +15 -7
  86. package/foundation/response/response-types.doc.mjs +1 -1
  87. package/foundation/text/levenshtein.d.mts +4 -1
  88. package/foundation/text/levenshtein.mjs +44 -1
  89. package/package.json +6 -18
  90. package/api/swizzle/_github.d.mts +0 -8
  91. package/api/swizzle/_github.mjs +0 -22
@@ -163,6 +163,34 @@ function getTargetStates(target) {
163
163
  return target.states || [];
164
164
  }
165
165
 
166
+ /**
167
+ * Format a component's icon slots: the `componentIcons` keys a theme sets,
168
+ * with each slot's state, fallback, and what `null` does.
169
+ * @param {any[]} slots - `theming.componentIcons` entries.
170
+ * @returns {string}
171
+ */
172
+ function formatComponentIconSlots(slots) {
173
+ const lines = [
174
+ '**Component icon slots** - set in `defineTheme({componentIcons})` to a shared icon name, `null`, a partial `{icon, variant, size}` request, or a function of the slot state.\n',
175
+ '| Slot | State | Fallback | Role | `null` |',
176
+ '|------|-------|----------|------|--------|',
177
+ ];
178
+ for (const slot of slots) {
179
+ const state = slot.state?.length
180
+ ? slot.state
181
+ .map(
182
+ (/** @type {any} */ field) =>
183
+ `\`${mdCell(field.name)}: ${mdCell(field.type)}\` ${mdCell(field.description)}`,
184
+ )
185
+ .join('<br>')
186
+ : 'none';
187
+ lines.push(
188
+ `| \`${mdCell(slot.slot)}\` | ${state} | ${mdCell(slot.fallback)} | ${mdCell(slot.description)} | ${mdCell(slot.whenNull)} |`,
189
+ );
190
+ }
191
+ return lines.join('\n') + '\n';
192
+ }
193
+
166
194
  /**
167
195
  * Format the theming targets table, merging in theme variants if available.
168
196
  *
@@ -351,6 +379,10 @@ export function formatFull(docs, options = {}) {
351
379
  }
352
380
  }
353
381
 
382
+ if (docs.theming.componentIcons?.length) {
383
+ sections.push(formatComponentIconSlots(docs.theming.componentIcons));
384
+ }
385
+
354
386
  // Legacy componentKey (for backward compatibility)
355
387
  if (docs.theming.componentKey) {
356
388
  sections.push(`Component key: \`${docs.theming.componentKey}\`\n`);
@@ -507,6 +539,11 @@ export function formatCompact(docs, componentName, importHint) {
507
539
  sections.push(propLines.join('\n') + '\n');
508
540
  }
509
541
 
542
+ if (docs.theming?.componentIcons?.length) {
543
+ sections.push('## Component Icon Slots\n');
544
+ sections.push(formatComponentIconSlots(docs.theming.componentIcons));
545
+ }
546
+
510
547
  return sections.join('\n');
511
548
  }
512
549
 
@@ -626,6 +663,18 @@ export function formatBrief(docs, componentName, importHint, options = {}) {
626
663
  output.push(` Derived: ${derivedNames}`);
627
664
  }
628
665
 
666
+ // Component icon slots, with the state each slot function receives
667
+ if (docs.theming?.componentIcons?.length) {
668
+ const slots = docs.theming.componentIcons
669
+ .map((/** @type {any} */ slot) =>
670
+ slot.state?.length
671
+ ? `${slot.slot} {${slot.state.map((/** @type {any} */ field) => `${field.name}: ${field.type}`).join(', ')}}`
672
+ : slot.slot,
673
+ )
674
+ .join('; ');
675
+ output.push(` Icon slots: ${slots}`);
676
+ }
677
+
629
678
  // Theme targets (component class, preferred data attrs, props, states) with theme variant merging
630
679
  if (docs.theming?.targets?.length) {
631
680
  const {themeData = null} = options;
@@ -383,6 +383,15 @@ export function providerLedgerOf(project) {
383
383
  return PROVIDER_LEDGERS.get(project) ?? new Map();
384
384
  }
385
385
 
386
+ /**
387
+ * True when an integration's templates root exists, the only place its
388
+ * templates come from (discoverIntegrationTemplatesForOne).
389
+ * @param {any} integration
390
+ * @returns {boolean}
391
+ */
392
+ const hasTemplatesRoot = integration =>
393
+ integration?.templates != null && fs.existsSync(integration.templates);
394
+
386
395
  /**
387
396
  * The single API for reading resolved project configuration. Construct via the
388
397
  * async {@link Project.load} factory.
@@ -1259,15 +1268,24 @@ export class Project {
1259
1268
  * @returns {Promise<ProjectIntegrationIssue[]>}
1260
1269
  */
1261
1270
  async issues() {
1262
- // Template replacement validity depends on the combined Core + integration
1263
- // catalog. Resolve it first so issue results never depend on which discovery
1264
- // method the caller happened to invoke earlier.
1265
- await this.templates();
1266
- // Component replacement validity likewise depends on Core plus every
1267
- // integration's components.
1268
- await this.componentReplacements();
1269
- for (const integration of this.#loadedIntegrations) {
1270
- await this.#collectIssues(integration);
1271
+ // Each issue these passes find belongs to an integration, because Core's
1272
+ // templates and components declare no replacement. A project with no
1273
+ // integration skips them.
1274
+ if (this.#loadedIntegrations.length > 0) {
1275
+ // Template replacement validity depends on the combined Core +
1276
+ // integration catalog. Resolve it first so issue results never depend
1277
+ // on which discovery method the caller happened to invoke earlier. Only
1278
+ // an integration's own templates can replace one, so with none, Core's
1279
+ // templates stay unread.
1280
+ if (this.#loadedIntegrations.some(hasTemplatesRoot)) {
1281
+ await this.templates();
1282
+ }
1283
+ // Component replacement validity likewise depends on Core plus every
1284
+ // integration's components.
1285
+ await this.componentReplacements();
1286
+ for (const integration of this.#loadedIntegrations) {
1287
+ await this.#collectIssues(integration);
1288
+ }
1271
1289
  }
1272
1290
  // Return a stable copy so callers can't mutate internal state.
1273
1291
  return this.#issues.map(i => ({...i}));
@@ -15,9 +15,9 @@
15
15
  * the self-doc tests fail.
16
16
  */
17
17
 
18
- import * as fs from 'node:fs';
19
18
  import * as path from 'node:path';
20
19
  import {CLI_ROOT} from '../fs/paths.mjs';
20
+ import {listDirEntries} from '../fs/listing-cache.mjs';
21
21
  import {readDocView} from '../doc-compiler/read.mjs';
22
22
  import {
23
23
  DOC_OUTPUT_BUDGET_BYTES,
@@ -75,7 +75,7 @@ export function discoverAuthoringSelfDocSources(root = AUTHORING_ROOT) {
75
75
  const found = [];
76
76
  /** @param {string} dir */
77
77
  const walk = dir => {
78
- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
78
+ for (const entry of listDirEntries(dir)) {
79
79
  if (entry.name === 'node_modules' || entry.name.startsWith('__'))
80
80
  continue;
81
81
  const full = path.join(dir, entry.name);
@@ -18,6 +18,7 @@
18
18
  import * as fs from 'node:fs';
19
19
  import * as path from 'node:path';
20
20
  import {CLI_ROOT} from '../fs/paths.mjs';
21
+ import {listDirEntries} from '../fs/listing-cache.mjs';
21
22
  import {readDocView} from '../doc-compiler/read.mjs';
22
23
  import {AUTHORING_SELF_DOCS, selfDocSection} from './authoring-self-docs.mjs';
23
24
  import {
@@ -66,7 +67,7 @@ export function discoverCliSelfDocSources(root = CLI_ROOT) {
66
67
  /** @param {string} dir */
67
68
  const walk = dir => {
68
69
  if (!fs.existsSync(dir)) return;
69
- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
70
+ for (const entry of listDirEntries(dir)) {
70
71
  if (
71
72
  entry.name === 'node_modules' ||
72
73
  entry.name.startsWith('__') ||
@@ -11,6 +11,7 @@ import {DOC_EXPORTS} from '../doc-compiler/read.mjs';
11
11
  import {
12
12
  listDir,
13
13
  listDirEntries,
14
+ listingCacheActive,
14
15
  oncePerListing,
15
16
  pathExists,
16
17
  withListingCache,
@@ -511,6 +512,42 @@ export function discoverComponents(coreDir) {
511
512
  return ordered;
512
513
  }
513
514
 
515
+ /**
516
+ * The folders of `srcDir`, in listing order, whose own listing holds one of
517
+ * `names`: the only folders a probe for `<folder>/<name>` can find. Inside an
518
+ * operation each listing is read once, for every name. Outside one, every
519
+ * folder is returned, so each probe reads the disk.
520
+ * @param {string} srcDir
521
+ * @param {fs.Dirent[]} entries `srcDir`'s listing
522
+ * @param {string[]} names
523
+ * @returns {fs.Dirent[]}
524
+ */
525
+ function foldersHolding(srcDir, entries, names) {
526
+ const folders = entries.filter(entry => entry.isDirectory());
527
+ if (!listingCacheActive()) return folders;
528
+ const byName = oncePerListing(`folder-names\0${srcDir}`, () => {
529
+ /** @type {Map<string, Set<string>>} */
530
+ const index = new Map();
531
+ for (const folder of folders) {
532
+ let listed;
533
+ try {
534
+ listed = listDir(path.join(srcDir, folder.name));
535
+ } catch {
536
+ continue;
537
+ }
538
+ for (const name of listed) {
539
+ let holders = index.get(name);
540
+ if (!holders) index.set(name, (holders = new Set()));
541
+ holders.add(folder.name);
542
+ }
543
+ }
544
+ return index;
545
+ });
546
+ return folders.filter(folder =>
547
+ names.some(name => byName.get(name)?.has(folder.name)),
548
+ );
549
+ }
550
+
514
551
  /**
515
552
  * Find the .doc.mjs file for a component.
516
553
  * For sub-components (e.g. StackItem), returns the parent's .doc.mjs
@@ -532,8 +569,7 @@ export function findComponentReadme(coreDir, name) {
532
569
 
533
570
  // Nested match: src/*/{name}/{Name}.doc.mjs or src/*/{name}/Astryx{Name}.doc.mjs
534
571
  const entries = listDirEntries(srcDir);
535
- for (const entry of entries) {
536
- if (!entry.isDirectory()) continue;
572
+ for (const entry of foldersHolding(srcDir, entries, [name])) {
537
573
  const nested = path.join(srcDir, entry.name, name, exactDoc);
538
574
  if (existsCaseExact(nested, srcDir)) return nested;
539
575
  const nestedXds = path.join(srcDir, entry.name, name, xdsDoc);
@@ -541,8 +577,7 @@ export function findComponentReadme(coreDir, name) {
541
577
  }
542
578
 
543
579
  // Per-component doc in a parent directory: src/*/{Name}.doc.mjs or src/*/Astryx{Name}.doc.mjs
544
- for (const entry of entries) {
545
- if (!entry.isDirectory()) continue;
580
+ for (const entry of foldersHolding(srcDir, entries, [exactDoc, xdsDoc])) {
546
581
  const perComp = path.join(srcDir, entry.name, exactDoc);
547
582
  if (existsCaseExact(perComp, srcDir)) return perComp;
548
583
  const perCompXds = path.join(srcDir, entry.name, xdsDoc);
@@ -731,12 +766,7 @@ function caseSpelledComponentSource(srcDir, name) {
731
766
  */
732
767
  export function resolveImportPath(coreDir, componentName) {
733
768
  const srcDir = path.join(coreDir, 'src');
734
- const pkgPath = path.join(coreDir, 'package.json');
735
- const pkg = pathExists(pkgPath)
736
- ? JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
737
- : null;
738
-
739
- const exportKeys = Object.keys(pkg?.exports || {});
769
+ const exportKeys = exportKeysOf(coreDir);
740
770
 
741
771
  // Priority 1: exact subpath export matching the component name (e.g. ./Heading)
742
772
  // This allows convenience re-export directories to win over the source directory.
@@ -764,6 +794,22 @@ export function resolveImportPath(coreDir, componentName) {
764
794
  return '@astryxdesign/core';
765
795
  }
766
796
 
797
+ /**
798
+ * The subpaths the package's `exports` map names, read once per operation:
799
+ * a search resolves the import of every component.
800
+ * @param {string} coreDir
801
+ * @returns {string[]}
802
+ */
803
+ function exportKeysOf(coreDir) {
804
+ const pkgPath = path.join(coreDir, 'package.json');
805
+ return oncePerListing(`export-keys\0${pkgPath}`, () => {
806
+ const pkg = pathExists(pkgPath)
807
+ ? JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
808
+ : null;
809
+ return Object.keys(pkg?.exports || {});
810
+ });
811
+ }
812
+
767
813
  /**
768
814
  * Does a package's `exports` map publish this subpath?
769
815
  *
@@ -32,6 +32,7 @@
32
32
  import * as fs from 'node:fs';
33
33
  import * as path from 'node:path';
34
34
  import {CLI_ROOT} from '../fs/paths.mjs';
35
+ import {listDir, listDirEntries} from '../fs/listing-cache.mjs';
35
36
  import {importDocModule} from '../doc-compiler/import.mjs';
36
37
  import {CLI_PROVIDER_ID} from '../identity/providers.mjs';
37
38
  import {parseReadableDoc} from '../doc-compiler/parse-readable.mjs';
@@ -135,7 +136,7 @@ export function discoverBuiltinTopics() {
135
136
  /** @type {Record<string, string>} */
136
137
  const topics = Object.create(null);
137
138
  if (!fs.existsSync(BUILTIN_DOCS_DIR)) return topics;
138
- for (const file of fs.readdirSync(BUILTIN_DOCS_DIR)) {
139
+ for (const file of listDir(BUILTIN_DOCS_DIR)) {
139
140
  const match = file.match(BUILTIN_TOPIC_FILE_RE);
140
141
  if (match) topics[match[1]] = path.join(BUILTIN_DOCS_DIR, file);
141
142
  }
@@ -152,7 +153,7 @@ export function builtinGuideFiles() {
152
153
  const files = Object.values(discoverBuiltinTopics());
153
154
  const tree = path.join(BUILTIN_DOCS_DIR, 'tree');
154
155
  if (fs.existsSync(tree)) {
155
- for (const file of fs.readdirSync(tree).sort()) {
156
+ for (const file of listDir(tree).sort()) {
156
157
  if (BUILTIN_TOPIC_FILE_RE.test(file)) files.push(path.join(tree, file));
157
158
  }
158
159
  }
@@ -524,7 +525,7 @@ export async function discoverIntegrationDocs(integration) {
524
525
  const files = [];
525
526
  /** @param {string} dirPath */
526
527
  function scanDir(dirPath) {
527
- for (const entry of fs.readdirSync(dirPath, {withFileTypes: true})) {
528
+ for (const entry of listDirEntries(dirPath)) {
528
529
  if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
529
530
  const full = path.join(dirPath, entry.name);
530
531
  if (entry.isDirectory()) {
@@ -737,7 +738,8 @@ export function mergeTopicReport(base, overlay) {
737
738
  // It also keeps the place an earlier `after` gave the one it replaces,
738
739
  // so sections placed after that key later still follow it.
739
740
  if (replaced[PLACED_AFTER] != null) {
740
- const placed = replacing === section ? withoutPosition({...section}) : replacing;
741
+ const placed =
742
+ replacing === section ? withoutPosition({...section}) : replacing;
741
743
  for (const symbol of Object.getOwnPropertySymbols(section)) {
742
744
  if (!(symbol in placed)) {
743
745
  Object.defineProperty(
@@ -15,10 +15,10 @@
15
15
  * surface reads
16
16
  */
17
17
 
18
- import * as fs from 'node:fs';
19
18
  import * as path from 'node:path';
20
19
  import {parseIconDefinition} from '../../authoring/doctypes/icon-definition/parse.mjs';
21
20
  import {CLI_ROOT} from '../fs/paths.mjs';
21
+ import {listDirEntries} from '../fs/listing-cache.mjs';
22
22
  import {readStaticDescriptorValue} from './theme-discovery.mjs';
23
23
 
24
24
  /** @typedef {import('../../authoring/doctypes/icon-definition/type').IconDefinitionDoc} IconDefinitionDoc */
@@ -53,10 +53,10 @@ export function readDefinitionsDir(dir, owner) {
53
53
  const definitions = [];
54
54
  /** @type {Array<{file: string, message: string}>} */
55
55
  const errors = [];
56
- /** @type {fs.Dirent[]} */
56
+ /** @type {import('node:fs').Dirent[]} */
57
57
  let entries;
58
58
  try {
59
- entries = fs.readdirSync(dir, {withFileTypes: true});
59
+ entries = listDirEntries(dir);
60
60
  } catch {
61
61
  return {definitions, errors};
62
62
  }
@@ -28,6 +28,7 @@ import {createRequire} from 'node:module';
28
28
  import {readDocView} from '../doc-compiler/read.mjs';
29
29
  import {importDocModule} from '../doc-compiler/import.mjs';
30
30
  import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';
31
+ import {listDirEntries} from '../fs/listing-cache.mjs';
31
32
  import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
32
33
  import {Project} from '../config/project.mjs';
33
34
  import {
@@ -1115,8 +1116,7 @@ export function listTemplates() {
1115
1116
  const all = [];
1116
1117
  if (fs.existsSync(PAGES_DIR)) {
1117
1118
  all.push(
1118
- ...fs
1119
- .readdirSync(PAGES_DIR, {withFileTypes: true})
1119
+ ...listDirEntries(PAGES_DIR)
1120
1120
  .filter(e => e.isDirectory())
1121
1121
  .map(e => e.name),
1122
1122
  );
@@ -1133,7 +1133,7 @@ function findDocFiles(dir, pattern) {
1133
1133
  /** @type {string[]} */
1134
1134
  const results = [];
1135
1135
  if (!fs.existsSync(dir)) return results;
1136
- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
1136
+ for (const entry of listDirEntries(dir)) {
1137
1137
  const full = path.join(dir, entry.name);
1138
1138
  if (entry.isDirectory()) {
1139
1139
  results.push(...findDocFiles(full, pattern));
@@ -1160,9 +1160,7 @@ export function findPageDocFile(dirPath) {
1160
1160
 
1161
1161
  async function discoverPages() {
1162
1162
  if (!fs.existsSync(PAGES_DIR)) return [];
1163
- const dirs = fs
1164
- .readdirSync(PAGES_DIR, {withFileTypes: true})
1165
- .filter(e => e.isDirectory());
1163
+ const dirs = listDirEntries(PAGES_DIR).filter(e => e.isDirectory());
1166
1164
 
1167
1165
  /** @type {DiscoveredTemplate[]} */
1168
1166
  const templates = [];
@@ -1602,7 +1600,7 @@ function findIntegrationDocFiles(root) {
1602
1600
  if (!fs.existsSync(root)) return results;
1603
1601
  /** @param {string} dir */
1604
1602
  const walk = dir => {
1605
- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
1603
+ for (const entry of listDirEntries(dir)) {
1606
1604
  const full = path.join(dir, entry.name);
1607
1605
  if (entry.isDirectory()) {
1608
1606
  walk(full);
@@ -22,6 +22,7 @@ import * as path from 'node:path';
22
22
  import {lowerDoc} from '../doc-compiler/compile.mjs';
23
23
  import {packageSource} from '../doc-compiler/source.mjs';
24
24
  import {CLI_ROOT} from '../fs/paths.mjs';
25
+ import {listDirEntries} from '../fs/listing-cache.mjs';
25
26
  import {formatCliCommand} from '../env/package-manager.mjs';
26
27
  import {LOCAL_THEME_ROOT} from '../config/theme-state.mjs';
27
28
  import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';
@@ -1187,7 +1188,7 @@ function listThemeFolder(folder) {
1187
1188
  const symlinks = [];
1188
1189
  /** @param {string} directory */
1189
1190
  function walk(directory) {
1190
- for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
1191
+ for (const entry of listDirEntries(directory)) {
1191
1192
  if (isIgnoredThemeEntry(entry.name)) continue;
1192
1193
  const full = path.join(directory, entry.name);
1193
1194
  const relative = path.relative(folder, full).split(path.sep).join('/');
@@ -1291,8 +1292,7 @@ export function discoverUnmigratedThemeCopies(
1291
1292
  ) {
1292
1293
  const root = path.resolve(projectDir, owner);
1293
1294
  if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];
1294
- return fs
1295
- .readdirSync(root, {withFileTypes: true})
1295
+ return listDirEntries(root)
1296
1296
  .filter(entry => entry.isDirectory() && !isIgnoredThemeEntry(entry.name))
1297
1297
  .map(entry => unmigratedThemeCopy(path.join(root, entry.name)))
1298
1298
  .filter(copy => copy !== null)
@@ -1369,9 +1369,9 @@ export function discoverThemeDirectory(
1369
1369
  /** @type {DiscoveredTheme[]} */
1370
1370
  const themes = [];
1371
1371
  const slugs = new Set();
1372
- const rootEntries = fs
1373
- .readdirSync(themeRoot, {withFileTypes: true})
1374
- .filter(entry => !isIgnoredThemeEntry(entry.name));
1372
+ const rootEntries = listDirEntries(themeRoot).filter(
1373
+ entry => !isIgnoredThemeEntry(entry.name),
1374
+ );
1375
1375
  const rootDescriptor = rootEntries.find(
1376
1376
  entry => entry.isFile() && entry.name.endsWith(THEME_DOC_SUFFIX),
1377
1377
  );
@@ -1614,8 +1614,7 @@ export function unreadThemeFolders(themeRoot, {packageDir, packageName} = {}) {
1614
1614
  if (!fs.existsSync(themeRoot) || !fs.statSync(themeRoot).isDirectory()) {
1615
1615
  return [];
1616
1616
  }
1617
- const folders = fs
1618
- .readdirSync(themeRoot, {withFileTypes: true})
1617
+ const folders = listDirEntries(themeRoot)
1619
1618
  .filter(entry => entry.isDirectory() && !isIgnoredThemeEntry(entry.name))
1620
1619
  .map(entry => path.join(themeRoot, entry.name))
1621
1620
  .sort();
@@ -1630,8 +1629,7 @@ export function unreadThemeFolders(themeRoot, {packageDir, packageName} = {}) {
1630
1629
  if (unread.length === 0) return [];
1631
1630
 
1632
1631
  const modules = [
1633
- ...fs
1634
- .readdirSync(themeRoot, {withFileTypes: true})
1632
+ ...listDirEntries(themeRoot)
1635
1633
  .filter(
1636
1634
  entry =>
1637
1635
  entry.isFile() &&
@@ -20,6 +20,7 @@
20
20
  import * as fs from 'node:fs';
21
21
  import * as path from 'node:path';
22
22
  import {CLI_ROOT} from '../fs/paths.mjs';
23
+ import {listDir} from '../fs/listing-cache.mjs';
23
24
  import {loadCliSelfDocs} from '../discovery/cli-self-docs.mjs';
24
25
  import {astryxIconDefinitions} from '../discovery/icon-definition-discovery.mjs';
25
26
  import {routeSegment} from '../discovery/docs-section-key.mjs';
@@ -812,8 +813,7 @@ function adoptionsFor(doc, declared, routeOf) {
812
813
  */
813
814
  export function treeDocFiles(dir = TREE_DOCS_DIR) {
814
815
  if (!fs.existsSync(dir)) return [];
815
- return fs
816
- .readdirSync(dir)
816
+ return listDir(dir)
817
817
  .filter(file => /^[\w-]+\.doc\.mjs$/u.test(file))
818
818
  .sort(byText)
819
819
  .map(file => path.join(dir, file));
@@ -7,6 +7,18 @@
7
7
  * @returns {string | null}
8
8
  */
9
9
  export function astryxCliRootOf(file: string): string | null;
10
+ /**
11
+ * The executable files on the search path named one of `names`, in the order
12
+ * a shell tries them. In each folder, it takes the first name that is a file
13
+ * this user may run. Nothing is started.
14
+ * @param {readonly string[]} names
15
+ * @param {{searchPath?: string, platform?: NodeJS.Platform}} [options]
16
+ * @returns {string[]}
17
+ */
18
+ export function executablesOnSearchPath(names: readonly string[], { searchPath, platform, }?: {
19
+ searchPath?: string;
20
+ platform?: NodeJS.Platform;
21
+ }): string[];
10
22
  /**
11
23
  * Every `astryx` command on the search path, in the order a shell tries
12
24
  * them. The first row is the one that runs.
@@ -13,9 +13,10 @@
13
13
  * package folder is read from the shim's text.
14
14
  *
15
15
  * @input the search path and, on Windows, its executable names
16
- * @output one row per `astryx` command found
17
- * @position packages/cli/foundation/env — read by doctor, init --user, and
18
- * the update notices.
16
+ * @output one row per `astryx` command found, and the executable files that
17
+ * any command name finds there
18
+ * @position packages/cli/foundation/env — read by doctor, init --user, the
19
+ * update notices, and swizzle's `gh` lookup.
19
20
  */
20
21
 
21
22
  import * as fs from 'node:fs';
@@ -146,6 +147,53 @@ function namesCliPackage(file) {
146
147
  }
147
148
  }
148
149
 
150
+ /**
151
+ * Whether `file` is a file this user may run. On Windows, any file counts.
152
+ * @param {string} file
153
+ * @param {boolean} windows
154
+ * @returns {boolean}
155
+ */
156
+ function isRunnableFile(file, windows) {
157
+ try {
158
+ if (!fs.statSync(file).isFile()) return false;
159
+ if (!windows) fs.accessSync(file, fs.constants.X_OK);
160
+ return true;
161
+ } catch {
162
+ // The shell skips a candidate the system cannot read: a missing folder, a
163
+ // stale mount, a symlink loop. `which` and execvp read PATH the same way.
164
+ return false;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * The executable files on the search path named one of `names`, in the order
170
+ * a shell tries them. In each folder, it takes the first name that is a file
171
+ * this user may run. Nothing is started.
172
+ * @param {readonly string[]} names
173
+ * @param {{searchPath?: string, platform?: NodeJS.Platform}} [options]
174
+ * @returns {string[]}
175
+ */
176
+ export function executablesOnSearchPath(
177
+ names,
178
+ {
179
+ searchPath = process.env.PATH ?? process.env.Path ?? '',
180
+ platform = process.platform,
181
+ } = {},
182
+ ) {
183
+ const windows = platform === 'win32';
184
+ /** @type {string[]} */
185
+ const files = [];
186
+ for (const dir of searchPath.split(windows ? ';' : path.delimiter)) {
187
+ if (!dir) continue;
188
+ // One command per folder: the shell runs the first name it finds.
189
+ const file = names
190
+ .map(name => path.join(dir, name))
191
+ .find(candidate => isRunnableFile(candidate, windows));
192
+ if (file !== undefined) files.push(file);
193
+ }
194
+ return files;
195
+ }
196
+
149
197
  /**
150
198
  * Every `astryx` command on the search path, in the order a shell tries
151
199
  * them. The first row is the one that runs.
@@ -156,50 +204,30 @@ export function astryxCommandsOnSearchPath({
156
204
  searchPath = process.env.PATH ?? process.env.Path ?? '',
157
205
  platform = process.platform,
158
206
  } = {}) {
159
- const windows = platform === 'win32';
160
- const names = windows
161
- ? ['astryx.cmd', 'astryx.exe', 'astryx.ps1', 'astryx']
162
- : [COMMAND];
207
+ const names =
208
+ platform === 'win32'
209
+ ? ['astryx.cmd', 'astryx.exe', 'astryx.ps1', 'astryx']
210
+ : [COMMAND];
163
211
  /** @type {SearchPathCommand[]} */
164
212
  const rows = [];
165
213
  const seen = new Set();
166
- for (const dir of searchPath.split(windows ? ';' : path.delimiter)) {
167
- if (!dir) continue;
168
- for (const name of names) {
169
- const file = path.join(dir, name);
170
- let stat;
171
- try {
172
- stat = fs.statSync(file);
173
- } catch {
174
- continue;
175
- }
176
- if (!stat.isFile()) continue;
177
- if (!windows) {
178
- try {
179
- fs.accessSync(file, fs.constants.X_OK);
180
- } catch {
181
- continue;
182
- }
183
- }
184
- let key = file;
185
- try {
186
- key = fs.realpathSync(file);
187
- } catch {
188
- // Keep the path as found.
189
- }
190
- if (seen.has(key)) break;
191
- seen.add(key);
192
- const cliRoot = astryxCliRootOf(file);
193
- rows.push({
194
- file,
195
- astryx: cliRoot !== null || namesCliPackage(file),
196
- cliRoot,
197
- version: cliRoot ? cliVersionAt(cliRoot) : null,
198
- handsOff: cliRoot ? handsOffAt(cliRoot) : null,
199
- });
200
- // One command per folder: the shell runs the first name it finds.
201
- break;
214
+ for (const file of executablesOnSearchPath(names, {searchPath, platform})) {
215
+ let key = file;
216
+ try {
217
+ key = fs.realpathSync(file);
218
+ } catch {
219
+ // Keep the path as found.
202
220
  }
221
+ if (seen.has(key)) continue;
222
+ seen.add(key);
223
+ const cliRoot = astryxCliRootOf(file);
224
+ rows.push({
225
+ file,
226
+ astryx: cliRoot !== null || namesCliPackage(file),
227
+ cliRoot,
228
+ version: cliRoot ? cliVersionAt(cliRoot) : null,
229
+ handsOff: cliRoot ? handsOffAt(cliRoot) : null,
230
+ });
203
231
  }
204
232
  return rows;
205
233
  }
@@ -25,7 +25,9 @@ export function oncePerListing<T>(key: string, compute: () => T): T;
25
25
  export function listingCacheActive(): boolean;
26
26
  /**
27
27
  * `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a
28
- * caller that sorts it cannot reorder another caller's listing.
28
+ * caller that sorts it cannot reorder another caller's listing. The names come
29
+ * from the same read as {@link listDirEntries}, so a folder listed both ways
30
+ * is read once.
29
31
  * @param {string} dir
30
32
  * @returns {string[]}
31
33
  */