@astryxdesign/cli 0.7.7 → 0.7.8-canary.0588a13

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 (98) hide show
  1. package/README.md +1 -1
  2. package/api/component/__fixtures__/resolutions/case-01.txt +30 -0
  3. package/api/component/__fixtures__/resolutions/case-02.txt +30 -0
  4. package/api/component/__fixtures__/resolutions/case-03.txt +30 -0
  5. package/api/component/__fixtures__/resolutions/case-04.txt +30 -0
  6. package/api/component/__fixtures__/resolutions/case-05.txt +30 -0
  7. package/api/component/__fixtures__/resolutions/case-06.txt +30 -0
  8. package/api/component/__fixtures__/resolutions/case-07.txt +30 -0
  9. package/api/component/__fixtures__/resolutions/case-08.txt +30 -0
  10. package/api/component/__fixtures__/resolutions/case-09.txt +30 -0
  11. package/api/component/__fixtures__/resolutions/case-10.txt +30 -0
  12. package/api/component/__fixtures__/resolutions/case-11.txt +30 -0
  13. package/api/component/__fixtures__/resolutions/case-12.txt +30 -0
  14. package/api/component/__fixtures__/resolutions/case-13.txt +25 -0
  15. package/api/component/__fixtures__/resolutions/modules.txt +308 -0
  16. package/api/component/component.mjs +11 -7
  17. package/api/doctor/_adapter.d.mts +6 -2
  18. package/api/doctor/_adapter.mjs +5 -3
  19. package/api/doctor/built-checks.d.mts +9 -4
  20. package/api/doctor/built-checks.mjs +15 -10
  21. package/api/gap-report/gap-report.mjs +9 -4
  22. package/api/integration/authoring-checks.mjs +31 -0
  23. package/api/integration/check/check.mjs +8 -3
  24. package/api/search/_candidate-score.d.mts +4 -1
  25. package/api/search/_candidate-score.mjs +27 -11
  26. package/api/search/_gather-components.mjs +5 -0
  27. package/api/search/_gather-templates.mjs +31 -6
  28. package/api/search/_lexical.d.mts +14 -0
  29. package/api/search/_lexical.mjs +4 -0
  30. package/api/search/_result.d.mts +1 -0
  31. package/api/search/_result.mjs +1 -0
  32. package/api/search/search.doc.mjs +1 -1
  33. package/api/search/search.type.d.mts +4 -0
  34. package/api/search/search.type.mjs +1 -0
  35. package/assets/codemods/transforms/next/index.mjs +11 -1
  36. package/assets/codemods/transforms/next/promote-tokenizer-presentation.mjs +191 -0
  37. package/assets/discover/official-packages.json +4 -8
  38. package/assets/docs/browser-support.doc.mjs +27 -1
  39. package/assets/docs/motion.doc.mjs +1 -1
  40. package/assets/docs/tree/tokens-duration.doc.mjs +4 -0
  41. package/assets/docs/tree/tokens.doc.mjs +1 -1
  42. package/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.doc.mjs +14 -0
  43. package/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.tsx +90 -0
  44. package/assets/templates/blocks/components/Hooks/useClipboardHookUsage.doc.mjs +14 -0
  45. package/assets/templates/blocks/components/Hooks/useClipboardHookUsage.tsx +35 -0
  46. package/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.doc.mjs +14 -0
  47. package/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.tsx +70 -0
  48. package/assets/templates/blocks/components/Hooks/useHotkeysHookUsage.doc.mjs +23 -0
  49. package/assets/templates/blocks/components/Hooks/useHotkeysHookUsage.tsx +90 -0
  50. package/assets/templates/blocks/components/Hooks/useInputStatusIconHookUsage.doc.mjs +14 -0
  51. package/assets/templates/blocks/components/Hooks/useInputStatusIconHookUsage.tsx +119 -0
  52. package/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.doc.mjs +3 -11
  53. package/assets/templates/blocks/components/Hooks/useKeyboardHintHookUsage.tsx +60 -45
  54. package/assets/templates/blocks/components/Hooks/useLocaleHookUsage.doc.mjs +20 -0
  55. package/assets/templates/blocks/components/Hooks/useLocaleHookUsage.tsx +72 -0
  56. package/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.doc.mjs +14 -0
  57. package/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.tsx +90 -0
  58. package/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.doc.mjs +15 -0
  59. package/assets/templates/blocks/components/Hooks/useTreeFocusHookUsage.tsx +98 -0
  60. package/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.doc.mjs +14 -0
  61. package/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.tsx +66 -0
  62. package/assets/templates/blocks/components/Lightbox/LightboxHookUsage.doc.mjs +15 -0
  63. package/assets/templates/blocks/components/Lightbox/LightboxHookUsage.tsx +62 -0
  64. package/assets/templates/blocks/components/Tokenizer/TokenizerClear.tsx +1 -0
  65. package/assets/templates/blocks/components/Tokenizer/TokenizerCreatable.tsx +1 -0
  66. package/assets/templates/blocks/components/Tokenizer/TokenizerEndContent.tsx +1 -0
  67. package/assets/templates/blocks/components/Tokenizer/TokenizerOverflow.tsx +2 -0
  68. package/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.doc.mjs +14 -0
  69. package/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.tsx +199 -0
  70. package/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs +21 -0
  71. package/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.tsx +210 -0
  72. package/assets/templates/pages/table-inbox/page.tsx +6 -0
  73. package/assets/templates/pages/work-item-detail/page.tsx +1 -0
  74. package/assets/theme.template.ts +2 -1
  75. package/authoring/doctypes/_schema.d.mts +16 -0
  76. package/authoring/doctypes/_schema.mjs +15 -0
  77. package/authoring/doctypes/component/component.doc.mjs +6 -0
  78. package/authoring/doctypes/component/type.ts +16 -0
  79. package/authoring/index.d.ts +1 -0
  80. package/clients/cli/commands/build.mjs +9 -3
  81. package/clients/cli/commands/component.mjs +18 -8
  82. package/clients/cli/commands/search.mjs +8 -2
  83. package/clients/cli/formatters/index.mjs +11 -0
  84. package/clients/cli/index.mjs +56 -11
  85. package/clients/cli/program.mjs +15 -0
  86. package/clients/cli/run.mjs +4 -1
  87. package/foundation/discovery/component-discovery.mjs +111 -16
  88. package/foundation/discovery/template-adapter.d.mts +10 -0
  89. package/foundation/discovery/template-adapter.mjs +94 -4
  90. package/foundation/fs/listing-cache.d.mts +25 -0
  91. package/foundation/fs/listing-cache.mjs +69 -2
  92. package/foundation/fs/paths.mjs +50 -5
  93. package/foundation/integrations/public-imports.d.mts +24 -0
  94. package/foundation/integrations/public-imports.mjs +2 -2
  95. package/foundation/response/response-types.doc.mjs +1 -1
  96. package/foundation/xle/registry.d.mts +1 -1
  97. package/foundation/xle/registry.mjs +11 -1
  98. package/package.json +9 -9
@@ -6,6 +6,7 @@
6
6
  * Global options: --detail full|compact|brief, --lang en|zh|dense
7
7
  */
8
8
 
9
+ import {withListingCache} from '../../../foundation/fs/listing-cache.mjs';
9
10
  import {findCoreDir} from '../../../foundation/fs/paths.mjs';
10
11
  import {
11
12
  resolveImportPath,
@@ -307,15 +308,18 @@ export function registerComponent(program) {
307
308
  }
308
309
  }
309
310
  }
311
+ // Each row resolves its import by walking the same source tree.
310
312
  emit(
311
313
  code(
312
- await formatBriefAll(coreDir, {
313
- zh,
314
- lang,
315
- themeData,
316
- replacements,
317
- categories: Object.keys(result.data.components),
318
- }),
314
+ await withListingCache(() =>
315
+ formatBriefAll(coreDir, {
316
+ zh,
317
+ lang,
318
+ themeData,
319
+ replacements,
320
+ categories: Object.keys(result.data.components),
321
+ }),
322
+ ),
319
323
  ),
320
324
  );
321
325
  break;
@@ -383,7 +387,13 @@ export function registerComponent(program) {
383
387
  ? section(firstGroup[0])
384
388
  : section(`Components (${sorted.length})`),
385
389
  records(
386
- sorted.map(item => ({name: item.name, import: importCell(item)})),
390
+ // Each row resolves its import by walking the same source tree.
391
+ withListingCache(() =>
392
+ sorted.map(item => ({
393
+ name: item.name,
394
+ import: importCell(item),
395
+ })),
396
+ ),
387
397
  {fields: ['name', 'import']},
388
398
  ),
389
399
  listFooter,
@@ -27,7 +27,7 @@ import {
27
27
  } from '../../../foundation/env/package-manager.mjs';
28
28
  import {jsonOut} from '../../../foundation/response/json.mjs';
29
29
  import {resultSetOf} from '../../../foundation/debug/index.mjs';
30
- import {emit, section, text, records} from '../formatters/index.mjs';
30
+ import {emit, formatDeprecation, section, text, records} from '../formatters/index.mjs';
31
31
  import {cliError} from '../lib/cli-error.mjs';
32
32
  import {defineCommand} from '../lib/define-command.mjs';
33
33
  import {search as searchApi} from '../../../api/search/search.mjs';
@@ -145,6 +145,7 @@ export function registerSearch(program) {
145
145
  'title',
146
146
  'displayName',
147
147
  'kind',
148
+ 'deprecated',
148
149
  'score',
149
150
  'reason',
150
151
  'import',
@@ -160,6 +161,7 @@ export function registerSearch(program) {
160
161
  'title',
161
162
  'displayName',
162
163
  'kind',
164
+ 'deprecated',
163
165
  'import',
164
166
  'description',
165
167
  'command',
@@ -177,7 +179,11 @@ export function registerSearch(program) {
177
179
  ),
178
180
  records(results, {
179
181
  fields,
180
- format: {command: formatCliCommand, parent: formatCliCommand},
182
+ format: {
183
+ command: formatCliCommand,
184
+ parent: formatCliCommand,
185
+ deprecated: formatDeprecation,
186
+ },
181
187
  }),
182
188
  ...note,
183
189
  ...discoverHint(run, q, options.type),
@@ -371,6 +371,17 @@ function isBlock(b) {
371
371
  return b instanceof Block;
372
372
  }
373
373
 
374
+ /**
375
+ * The text value of a deprecated component's `deprecated` field: the component
376
+ * to use instead, then the modernization route. Every command that prints a
377
+ * component result's fields prints it this way.
378
+ * @param {{replacement: string, description: string}} deprecation
379
+ * @returns {string}
380
+ */
381
+ export function formatDeprecation(deprecation) {
382
+ return `use ${deprecation.replacement}: ${deprecation.description}`;
383
+ }
384
+
374
385
  /**
375
386
  * The one sanctioned way to write human output to stdout. Joins blocks with a
376
387
  * single blank line and hands the result to `humanLog`, which is a no-op in
@@ -3,13 +3,13 @@
3
3
  /**
4
4
  * @file Astryx CLI — Commander program setup
5
5
  *
6
- * Registers all commands via lazy loading. If one command fails to load
7
- * (bad import, syntax error), the other commands still work.
6
+ * Commands load lazily: a bin run loads only the one its arguments name.
7
+ * One that fails to load (bad import, syntax error) leaves the rest working.
8
8
  *
9
9
  * The program is built by {@link createProgram} — a factory so tests can drive
10
10
  * a FRESH program in-process (via parseAsync) instead of spawning `node
11
- * bin/astryx.mjs` per assertion. `bin/astryx.mjs` and legacy importers use the
12
- * eager {@link program} singleton, which is just `await createProgram()`.
11
+ * bin/astryx.mjs` per assertion. Code that reads every command at once uses
12
+ * the full program in program.mjs.
13
13
  */
14
14
 
15
15
  import {Command, Option} from 'commander';
@@ -329,6 +329,52 @@ const commands = [
329
329
  {name: 'postinstall', path: './commands/postinstall.mjs', register: 'registerPostinstall'},
330
330
  ];
331
331
 
332
+ /** The name each registry entry registers, in registration order. */
333
+ export const COMMAND_NAMES = Object.freeze(commands.map(cmd => cmd.name));
334
+
335
+ /** Commands whose run reads every other command: the manifest lists them. */
336
+ const READS_EVERY_COMMAND = new Set(['manifest']);
337
+
338
+ /**
339
+ * The commands a run of the bin loads. Commander dispatches a run to its
340
+ * first operand after the root's own options, so this reads the arguments the
341
+ * same way. It returns that one command, no command for a run that only
342
+ * prints the version, or null for every command. These runs load every
343
+ * command: help, the manifest, `help <command>`, an unknown word, and a flag
344
+ * the root does not declare. They print or read the whole list.
345
+ *
346
+ * @param {import('commander').Command} program the root, with its options
347
+ * @param {string[]} argv the arguments after `astryx`
348
+ * @returns {Set<string> | null}
349
+ */
350
+ export function commandsForArgs(program, argv) {
351
+ let printsVersion = false;
352
+ for (let i = 0; i < argv.length; i += 1) {
353
+ const arg = argv[i];
354
+ // Commander reads a lone `-` as an operand, as it reads any word.
355
+ if (arg.length < 2 || arg[0] !== '-') {
356
+ return commands.some(cmd => cmd.name === arg) && !READS_EVERY_COMMAND.has(arg)
357
+ ? new Set([arg])
358
+ : null;
359
+ }
360
+ const equals = arg.startsWith('--') ? arg.indexOf('=') : -1;
361
+ const flag = equals === -1 ? arg : arg.slice(0, equals);
362
+ const option = program.options.find(o => o.long === flag || o.short === flag);
363
+ // Help flags, `--`, combined short flags and unknown flags read the whole
364
+ // list, or make Commander stop dispatching by name.
365
+ if (option == null) return null;
366
+ const takesValue = option.required || option.optional;
367
+ if (equals !== -1 && !takesValue) return null;
368
+ if (equals === -1 && option.required) i += 1;
369
+ const next = argv[i + 1];
370
+ if (equals === -1 && option.optional && next != null && !(next.length > 1 && next[0] === '-')) {
371
+ i += 1;
372
+ }
373
+ if (option.long === '--version') printsVersion = true;
374
+ }
375
+ return printsVersion ? new Set() : null;
376
+ }
377
+
332
378
  const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);
333
379
 
334
380
  /**
@@ -363,9 +409,12 @@ const INTEGRATION_MANIFEST_FILES = [
363
409
  * lazy-imported. Each call returns an independent Command so tests can
364
410
  * parseAsync repeatedly without commander state leaking between runs.
365
411
  *
412
+ * @param {{argv?: string[]}} [options] `argv`, the arguments after `astryx`:
413
+ * load only the commands a run of them needs (commandsForArgs). Without
414
+ * it, every command loads.
366
415
  * @returns {Promise<import('commander').Command>}
367
416
  */
368
- export async function createProgram() {
417
+ export async function createProgram({argv} = {}) {
369
418
  const program = new Command();
370
419
 
371
420
  // Deterministic, single-line help. Commander wraps each option/command
@@ -708,7 +757,9 @@ export async function createProgram() {
708
757
  }
709
758
  });
710
759
 
760
+ const loads = argv == null ? null : commandsForArgs(program, argv);
711
761
  for (const cmd of commands) {
762
+ if (loads != null && !loads.has(cmd.name)) continue;
712
763
  try {
713
764
  const mod = await import(cmd.path);
714
765
  mod[cmd.register](program, {jsonSupported: JSON_SUPPORTED, version: pkg.version});
@@ -740,9 +791,3 @@ export async function createProgram() {
740
791
 
741
792
  return program;
742
793
  }
743
-
744
- /**
745
- * Eager singleton program for `bin/astryx.mjs` and legacy importers. Tests
746
- * should call {@link createProgram} to get an isolated instance.
747
- */
748
- export const program = await createProgram();
@@ -0,0 +1,15 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The full Astryx CLI program, with every command loaded.
5
+ *
6
+ * @input createProgram (index.mjs).
7
+ * @output `program`, built once when this module loads.
8
+ * @position For code that reads every command at once, such as tests of the
9
+ * manifest and the docs drift check. A run of the bin builds its own
10
+ * program from its arguments (run.mjs), so it does not load this module.
11
+ */
12
+
13
+ import {createProgram} from './index.mjs';
14
+
15
+ export const program = await createProgram();
@@ -33,11 +33,14 @@ export async function runCli({cliRoot, argv, declinedProjectCli}) {
33
33
  if (answered) return answered;
34
34
 
35
35
  const {
36
- program,
36
+ createProgram,
37
37
  loadProjectDebugHandler,
38
38
  loadProjectForHelp,
39
39
  handleVersionJsonPreflight,
40
40
  } = await import('./index.mjs');
41
+ // Only the commands these arguments need load, before anything below runs,
42
+ // as the full program did.
43
+ const program = await createProgram({argv: process.argv.slice(2)});
41
44
  const {isJsonMode, toErrorEnvelope} =
42
45
  await import('../../foundation/response/json.mjs');
43
46
  const {handleCommanderError} = await import('./lib/json-shim.mjs');
@@ -8,7 +8,13 @@ import * as fs from 'node:fs';
8
8
  import {createRequire} from 'node:module';
9
9
  import * as path from 'node:path';
10
10
  import {DOC_EXPORTS} from '../doc-compiler/read.mjs';
11
- import {listDir, listDirEntries, pathExists} from '../fs/listing-cache.mjs';
11
+ import {
12
+ listDir,
13
+ listDirEntries,
14
+ oncePerListing,
15
+ pathExists,
16
+ withListingCache,
17
+ } from '../fs/listing-cache.mjs';
12
18
  import {existsCaseExact} from '../fs/paths.mjs';
13
19
  import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
14
20
  import {loadComponentDoc} from './component-loader.mjs';
@@ -579,36 +585,50 @@ export function findComponentReadme(coreDir, name) {
579
585
  * @returns {string | null}
580
586
  */
581
587
  export function findComponentSource(coreDir, name) {
588
+ const found = ownSourceFile(coreDir, name);
589
+ if (found == null) return null;
590
+ // A component's exact name in another case (`tokenizer` for Tokenizer) is
591
+ // that component's. A module that only shares the spelling, such as
592
+ // `CodeBlock/tokenizer.ts`, never stands for it.
593
+ return caseSpelledComponentSource(path.join(coreDir, 'src'), name) == null
594
+ ? found
595
+ : null;
596
+ }
597
+
598
+ /**
599
+ * The file named for `name` in `src/`, found as {@link findComponentSource}
600
+ * describes, before the case-spelling check.
601
+ * @param {string} coreDir
602
+ * @param {string} name
603
+ * @returns {string | null}
604
+ */
605
+ function ownSourceFile(coreDir, name) {
582
606
  const srcDir = path.join(coreDir, 'src');
583
- // Try the prefixed forms (`XDSButton.tsx`) first since that is the current
584
- // on-disk convention, then the bare forms (`Button.tsx`) that the Astryx-prefix
585
- // migration (P4) renames to. `.tsx` before `.ts` within each so a component's
586
- // `.tsx` wins over a same-named `.ts` helper; `.ts` covers hooks/functions.
587
- const candidateFiles = [
588
- `XDS${name}.tsx`,
589
- `${name}.tsx`,
590
- `XDS${name}.ts`,
591
- `${name}.ts`,
592
- ];
607
+ const candidateFiles = ownFileNames(name);
593
608
 
594
609
  /**
595
610
  * @param {string} dirPath
596
611
  * @returns {string | null}
597
612
  */
598
- function searchDir(dirPath) {
599
- if (!pathExists(dirPath)) return null;
613
+ function searchDir(dirPath, listed = false) {
614
+ // A folder from its parent's listing exists; only a starting folder
615
+ // needs the check.
616
+ if (!listed && !pathExists(dirPath)) return null;
600
617
  const entries = listDirEntries(dirPath);
601
618
 
602
- // Check for an exact match (prefixed or bare) first
619
+ // Check for an exact match (prefixed or bare) first. The listing in hand
620
+ // holds every name in the folder, so no name is probed on disk.
603
621
  for (const candidate of candidateFiles) {
622
+ const entry = entries.find(e => e.name === candidate);
623
+ if (!entry) continue;
604
624
  const exact = path.join(dirPath, candidate);
605
- if (existsCaseExact(exact, dirPath)) return exact;
625
+ if (!entry.isSymbolicLink() || pathExists(exact)) return exact;
606
626
  }
607
627
 
608
628
  // Recurse into subdirectories
609
629
  for (const entry of entries) {
610
630
  if (entry.isDirectory()) {
611
- const found = searchDir(path.join(dirPath, entry.name));
631
+ const found = searchDir(path.join(dirPath, entry.name), true);
612
632
  if (found) return found;
613
633
  }
614
634
  }
@@ -637,6 +657,71 @@ export function findComponentSource(coreDir, name) {
637
657
  return searchDir(srcDir);
638
658
  }
639
659
 
660
+ /**
661
+ * The file names a component's own source can have. The `XDS` forms come
662
+ * first, so an older prefixed file wins over a bare one. `.tsx` comes before
663
+ * `.ts`, so a component wins over a same-named helper. `.ts` covers hooks and
664
+ * functions.
665
+ * @param {string} name
666
+ * @returns {string[]}
667
+ */
668
+ function ownFileNames(name) {
669
+ return [`XDS${name}.tsx`, `${name}.tsx`, `XDS${name}.ts`, `${name}.ts`];
670
+ }
671
+
672
+ // A component's name (PascalCase) or a hook's (`use` followed by PascalCase).
673
+ const COMPONENT_OR_HOOK_NAME_RE = /^(?:use)?[A-Z][A-Za-z0-9]*$/;
674
+
675
+ /**
676
+ * Every component or hook file in `src/`, by its stem in lower case: its
677
+ * stem (without an `XDS` prefix) and its path. Built once per operation.
678
+ * @param {string} srcDir
679
+ * @returns {Map<string, Array<{stem: string, file: string}>>}
680
+ */
681
+ function caseStemIndex(srcDir) {
682
+ return oncePerListing(`case-stems\0${srcDir}`, () => {
683
+ /** @type {Map<string, Array<{stem: string, file: string}>>} */
684
+ const index = new Map();
685
+ /** @param {string} dirPath */
686
+ const visit = dirPath => {
687
+ for (const entry of listDirEntries(dirPath)) {
688
+ const entryPath = path.join(dirPath, entry.name);
689
+ if (entry.isDirectory()) {
690
+ if (entry.name !== '__tests__') visit(entryPath);
691
+ continue;
692
+ }
693
+ const stem = /^(?:XDS)?(.+)\.tsx?$/.exec(entry.name)?.[1];
694
+ if (stem == null || !COMPONENT_OR_HOOK_NAME_RE.test(stem)) continue;
695
+ const key = stem.toLowerCase();
696
+ index.set(key, [...(index.get(key) ?? []), {stem, file: entryPath}]);
697
+ }
698
+ };
699
+ if (pathExists(srcDir)) visit(srcDir);
700
+ return index;
701
+ });
702
+ }
703
+
704
+ /**
705
+ * The source of the component or hook whose exact name `name` spells in
706
+ * another case. A file named for it, anywhere in `src/`, exports it, as
707
+ * `TabList/Tab.tsx` exports Tab for `tab`. Null when no such file exists.
708
+ * @param {string} srcDir
709
+ * @param {string} name
710
+ * @returns {string | null}
711
+ */
712
+ function caseSpelledComponentSource(srcDir, name) {
713
+ for (const {stem, file} of caseStemIndex(srcDir).get(name.toLowerCase()) ??
714
+ []) {
715
+ if (
716
+ stem !== name &&
717
+ (moduleExportsName(file, stem) || moduleExportsName(file, `XDS${stem}`))
718
+ ) {
719
+ return file;
720
+ }
721
+ }
722
+ return null;
723
+ }
724
+
640
725
  /**
641
726
  * Compute the Levenshtein (edit) distance between two strings.
642
727
  * Used for fuzzy-matching component names. Dependency-free.
@@ -1703,6 +1788,16 @@ export function unscopedComponentOwners(owners) {
1703
1788
  * @returns {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>}
1704
1789
  */
1705
1790
  export function discoverOwnedComponents(coreDir, loadedIntegrations = []) {
1791
+ // Read-only: one listing of each folder serves the whole discovery.
1792
+ return withListingCache(() => ownedComponents(coreDir, loadedIntegrations));
1793
+ }
1794
+
1795
+ /**
1796
+ * @param {string} coreDir
1797
+ * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations
1798
+ * @returns {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>}
1799
+ */
1800
+ function ownedComponents(coreDir, loadedIntegrations) {
1706
1801
  /** @type {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>} */
1707
1802
  const records = [];
1708
1803
 
@@ -239,6 +239,16 @@ export function extractComponents(pagePath: string): string[];
239
239
  * @returns {string[]}
240
240
  */
241
241
  export function componentsInSource(src: string): string[];
242
+ /**
243
+ * Every name componentsInSource can return for `src`, read without parsing
244
+ * it, or null when it cannot be bounded so. It keeps the tag names a parse
245
+ * would drop as page-local. It adds each name an `imported as local` pair
246
+ * makes a tag stand for, wherever that text appears. An escaped name in an
247
+ * identifier or a string defeats the reading, so then it is null.
248
+ * @param {string} src
249
+ * @returns {string[] | null}
250
+ */
251
+ export function componentNameBound(src: string): string[] | null;
242
252
  /**
243
253
  * A video placeholder that names itself in the source, for a copy that has no
244
254
  * response to disclose the replacement in, such as the shadcn install. It is a
@@ -1976,6 +1976,41 @@ export async function findShowcase(componentName, cwd, options) {
1976
1976
  /** The npm scope of every Astryx package. */
1977
1977
  const ASTRYX_PACKAGE_SCOPE = '@astryxdesign/';
1978
1978
 
1979
+ /** A JSX opening tag; componentsInSource says why the pattern looks so. */
1980
+ const JSX_TAG = /(?<![\w$.])<(XDS)?([A-Z]\w+)/g;
1981
+
1982
+ /** Comments and line breaks that may sit between two words of an import. */
1983
+ // A block comment ends at its first `*/`, and a line comment at its line's
1984
+ // end. So each comment has one reading, and a failed match cannot backtrack
1985
+ // through every split of a comment run.
1986
+ const SPACE_OR_COMMENT = String.raw`\s|\/\*(?:[^*]|\*(?!\/))*\*\/|\/\/[^\n\r\u2028\u2029]*(?![^\n\r\u2028\u2029])`;
1987
+ const BETWEEN = `(?:${SPACE_OR_COMMENT})*`;
1988
+ const GAP = new RegExp(`(?:${SPACE_OR_COMMENT})+`, 'g');
1989
+ // The pair scan can start again at each word of a run of spaces and
1990
+ // comments, so a run costs up to its length squared. The longest run in the
1991
+ // bundled templates is about 10 KB.
1992
+ const MAX_GAP = 16 * 1024;
1993
+
1994
+ /**
1995
+ * One `imported as local` pair. The imported name is an identifier (group 1)
1996
+ * or a string (group 3); the local name is group 4.
1997
+ */
1998
+ const ALIAS = new RegExp(
1999
+ String.raw`(?:(?<![\p{ID_Continue}$])([\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*)|(['"])((?:\\[\s\S]|(?!\2)[^\\\n])*)\2)` +
2000
+ BETWEEN +
2001
+ String.raw`\bas\b` +
2002
+ BETWEEN +
2003
+ String.raw`([\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*)`,
2004
+ 'gu',
2005
+ );
2006
+ // What follows each `as`: the pair scan reads the same text after its `as`.
2007
+ const AS_LOCAL = new RegExp(
2008
+ String.raw`\bas\b` +
2009
+ BETWEEN +
2010
+ String.raw`([\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*)`,
2011
+ 'gu',
2012
+ );
2013
+
1979
2014
  const UBIQUITOUS = new Set([
1980
2015
  'Text',
1981
2016
  'Heading',
@@ -2079,7 +2114,7 @@ export function componentsInSource(src) {
2079
2114
  // and `Record<string, Phase>` no longer do. Those were being indexed as
2080
2115
  // rendered components, putting type names like `Record`, `SVGProps` and
2081
2116
  // `ReadonlySet` into template keyword and "components used" output.
2082
- const tagRegex = /(?<![\w$.])<(XDS)?([A-Z]\w+)/g;
2117
+ const tagRegex = new RegExp(JSX_TAG);
2083
2118
  /** @type {string[]} */
2084
2119
  const matches = [];
2085
2120
  let m;
@@ -2093,11 +2128,23 @@ export function componentsInSource(src) {
2093
2128
  // strings and type annotations cannot add or hide a name.
2094
2129
  const {declared: localDeclNames, astryxImports} = topLevelBindings(src);
2095
2130
 
2131
+ return catalogNames(
2132
+ matches
2133
+ .filter(n => !localDeclNames.has(n))
2134
+ .map(n => astryxImports.get(n) ?? n),
2135
+ );
2136
+ }
2137
+
2138
+ /**
2139
+ * Rendered component names as the catalog lists them: without theme wrappers
2140
+ * and ubiquitous parts, each part suffix stripped, each name once, sorted.
2141
+ * @param {string[]} names
2142
+ * @returns {string[]}
2143
+ */
2144
+ function catalogNames(names) {
2096
2145
  return [
2097
2146
  ...new Set(
2098
- matches
2099
- .filter(n => !localDeclNames.has(n))
2100
- .map(n => astryxImports.get(n) ?? n)
2147
+ names
2101
2148
  .filter(n => !['Theme', 'ThemeProvider'].includes(n))
2102
2149
  .filter(n => !UBIQUITOUS.has(n))
2103
2150
  .map(n =>
@@ -2112,3 +2159,46 @@ export function componentsInSource(src) {
2112
2159
  ),
2113
2160
  ].sort();
2114
2161
  }
2162
+
2163
+ /**
2164
+ * Every name componentsInSource can return for `src`, read without parsing
2165
+ * it, or null when it cannot be bounded so. It keeps the tag names a parse
2166
+ * would drop as page-local. It adds each name an `imported as local` pair
2167
+ * makes a tag stand for, wherever that text appears. An escaped name in an
2168
+ * identifier or a string defeats the reading, so then it is null.
2169
+ * @param {string} src
2170
+ * @returns {string[] | null}
2171
+ */
2172
+ export function componentNameBound(src) {
2173
+ if (src.includes('\\u')) return null;
2174
+ for (const gap of src.matchAll(GAP)) {
2175
+ if (gap[0].length > MAX_GAP) return null;
2176
+ }
2177
+ const tags = Array.from(src.matchAll(JSX_TAG), m => m[2]);
2178
+ const local = new Set(tags);
2179
+ // A pair adds a name only when its local name is a tag. Most sources have
2180
+ // no `as` before a tag's name, so they skip the slower pair scan. Each
2181
+ // match restarts one character on: a `/*` in a comment can hide a pair.
2182
+ const asLocal = new RegExp(AS_LOCAL);
2183
+ let pairs = false;
2184
+ for (let m = asLocal.exec(src); m && !pairs; m = asLocal.exec(src)) {
2185
+ asLocal.lastIndex = m.index + 1;
2186
+ pairs = local.has(m[1]);
2187
+ }
2188
+ if (!pairs) return catalogNames(tags);
2189
+ /** @type {string[]} */
2190
+ const imported = [];
2191
+ // Each match restarts one character on, so no pair hides inside another.
2192
+ const alias = new RegExp(ALIAS);
2193
+ for (let m = alias.exec(src); m; m = alias.exec(src)) {
2194
+ // Step one code point: a `u` regex moves an index inside a surrogate
2195
+ // pair back to the pair's start.
2196
+ alias.lastIndex =
2197
+ m.index + ((src.codePointAt(m.index) ?? 0) > 0xffff ? 2 : 1);
2198
+ if (!local.has(m[4])) continue;
2199
+ const name = m[1] ?? m[3];
2200
+ if (name.includes('\\')) return null;
2201
+ imported.push(name);
2202
+ }
2203
+ return catalogNames([...tags, ...imported]);
2204
+ }
@@ -9,6 +9,20 @@
9
9
  * @returns {T}
10
10
  */
11
11
  export function withListingCache<T>(fn: () => T): T;
12
+ /**
13
+ * `compute()` once per operation, under `key`. A later call in the same
14
+ * operation gets the first result; outside an operation it computes each time.
15
+ * @template T
16
+ * @param {string} key
17
+ * @param {() => T} compute
18
+ * @returns {T}
19
+ */
20
+ export function oncePerListing<T>(key: string, compute: () => T): T;
21
+ /**
22
+ * Whether an operation's listing cache is active.
23
+ * @returns {boolean}
24
+ */
25
+ export function listingCacheActive(): boolean;
12
26
  /**
13
27
  * `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a
14
28
  * caller that sorts it cannot reorder another caller's listing.
@@ -22,6 +36,15 @@ export function listDir(dir: string): string[];
22
36
  * @returns {fs.Dirent[]}
23
37
  */
24
38
  export function listDirEntries(dir: string): fs.Dirent[];
39
+ /**
40
+ * The entry named exactly `name` in `dir`'s listing, or null when the folder
41
+ * holds no such name or cannot be read. Inside an operation, a name the
42
+ * listing lacks costs no probe of the disk.
43
+ * @param {string} dir
44
+ * @param {string} name
45
+ * @returns {fs.Dirent | null}
46
+ */
47
+ export function findEntry(dir: string, name: string): fs.Dirent | null;
25
48
  /**
26
49
  * `fs.existsSync(target)`, probed once per operation.
27
50
  * @param {string} target
@@ -31,6 +54,8 @@ export function pathExists(target: string): boolean;
31
54
  export type ListingCache = {
32
55
  names: Map<string, string[]>;
33
56
  entries: Map<string, fs.Dirent[]>;
57
+ byName: Map<string, Map<string, fs.Dirent>>;
34
58
  exists: Map<string, boolean>;
59
+ memos: Map<string, unknown>;
35
60
  };
36
61
  import * as fs from 'node:fs';