@astryxdesign/cli 0.7.7 → 0.7.8-canary.15a98a1

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 (45) hide show
  1. package/api/component/__fixtures__/resolutions/case-01.txt +30 -0
  2. package/api/component/__fixtures__/resolutions/case-02.txt +30 -0
  3. package/api/component/__fixtures__/resolutions/case-03.txt +30 -0
  4. package/api/component/__fixtures__/resolutions/case-04.txt +30 -0
  5. package/api/component/__fixtures__/resolutions/case-05.txt +30 -0
  6. package/api/component/__fixtures__/resolutions/case-06.txt +30 -0
  7. package/api/component/__fixtures__/resolutions/case-07.txt +30 -0
  8. package/api/component/__fixtures__/resolutions/case-08.txt +30 -0
  9. package/api/component/__fixtures__/resolutions/case-09.txt +30 -0
  10. package/api/component/__fixtures__/resolutions/case-10.txt +30 -0
  11. package/api/component/__fixtures__/resolutions/case-11.txt +30 -0
  12. package/api/component/__fixtures__/resolutions/case-12.txt +30 -0
  13. package/api/component/__fixtures__/resolutions/case-13.txt +25 -0
  14. package/api/component/__fixtures__/resolutions/modules.txt +309 -0
  15. package/api/component/component.mjs +11 -7
  16. package/api/gap-report/gap-report.mjs +9 -4
  17. package/api/integration/authoring-checks.mjs +31 -0
  18. package/api/integration/check/check.mjs +8 -3
  19. package/assets/codemods/transforms/next/index.mjs +11 -1
  20. package/assets/codemods/transforms/next/promote-tokenizer-presentation.mjs +174 -0
  21. package/assets/discover/official-packages.json +4 -8
  22. package/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.doc.mjs +14 -0
  23. package/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.tsx +90 -0
  24. package/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.doc.mjs +14 -0
  25. package/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.tsx +70 -0
  26. package/assets/templates/blocks/components/Tokenizer/TokenizerClear.tsx +1 -0
  27. package/assets/templates/blocks/components/Tokenizer/TokenizerCreatable.tsx +1 -0
  28. package/assets/templates/blocks/components/Tokenizer/TokenizerEndContent.tsx +1 -0
  29. package/assets/templates/blocks/components/Tokenizer/TokenizerOverflow.tsx +2 -0
  30. package/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.doc.mjs +14 -0
  31. package/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.tsx +199 -0
  32. package/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs +21 -0
  33. package/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.tsx +210 -0
  34. package/assets/templates/pages/table-inbox/page.tsx +6 -0
  35. package/assets/templates/pages/work-item-detail/page.tsx +1 -0
  36. package/clients/cli/commands/component.mjs +18 -8
  37. package/foundation/discovery/component-discovery.mjs +111 -16
  38. package/foundation/fs/listing-cache.d.mts +25 -0
  39. package/foundation/fs/listing-cache.mjs +69 -2
  40. package/foundation/fs/paths.mjs +50 -5
  41. package/foundation/integrations/public-imports.d.mts +24 -0
  42. package/foundation/integrations/public-imports.mjs +2 -2
  43. package/foundation/xle/registry.d.mts +1 -1
  44. package/foundation/xle/registry.mjs +11 -1
  45. package/package.json +9 -9
@@ -0,0 +1,210 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {useRef, useState} from 'react';
6
+ import type {PointerEvent} from 'react';
7
+ import {Button} from '@astryxdesign/core/Button';
8
+ import {Card} from '@astryxdesign/core/Card';
9
+ import {useAnimator} from '@astryxdesign/core/hooks';
10
+ import {HStack, VStack} from '@astryxdesign/core/Layout';
11
+ import {Text} from '@astryxdesign/core/Text';
12
+ import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
13
+
14
+ const DECK = [
15
+ {rank: 'A', suit: '\u2660', name: 'Ace of spades'},
16
+ {rank: 'K', suit: '\u2665', name: 'King of hearts'},
17
+ {rank: 'Q', suit: '\u2663', name: 'Queen of clubs'},
18
+ {rank: 'J', suit: '\u2666', name: 'Jack of diamonds'},
19
+ ];
20
+
21
+ /** A release faster than this (px/s) throws the card away. */
22
+ const THROW_SPEED = 1000;
23
+ /** The slowest throw, so a thrown card always leaves the table. */
24
+ const MIN_THROW = 1600;
25
+
26
+ interface Sample {
27
+ t: number;
28
+ x: number;
29
+ y: number;
30
+ }
31
+
32
+ /**
33
+ * The release velocity in px/s, over the 80 ms before the release: a finger
34
+ * that held still before letting go releases at rest.
35
+ */
36
+ function releaseVelocity(
37
+ samples: Sample[],
38
+ releasedAt: number,
39
+ ): {x: number; y: number} {
40
+ const recent = samples.filter(s => releasedAt - s.t <= 80);
41
+ const first = recent[0];
42
+ const last = recent.at(-1);
43
+ if (last == null || first == null || last.t === first.t) {
44
+ return {x: 0, y: 0};
45
+ }
46
+ const seconds = (last.t - first.t) / 1000;
47
+ return {x: (last.x - first.x) / seconds, y: (last.y - first.y) / seconds};
48
+ }
49
+
50
+ export default function AnimatorPlayingCards() {
51
+ const ref = useRef<HTMLDivElement>(null);
52
+ const animator = useAnimator(ref);
53
+ const [top, setTop] = useState(0);
54
+ const [status, setStatus] = useState('');
55
+ const drag = useRef<{start: Sample; samples: Sample[]} | null>(null);
56
+ // One discard at a time: a press while a card leaves deals no second card.
57
+ const discarding = useRef(false);
58
+ const card = DECK[top % DECK.length];
59
+
60
+ // Announces the discard and deals the next card in place of the old one.
61
+ const dealNext = async () => {
62
+ setStatus(`${card.name} discarded`);
63
+ setTop(index => index + 1);
64
+ animator.set({x: 0, y: 0, rotate: 0, scale: 0.9, opacity: 0});
65
+ discarding.current = false;
66
+ await animator.animate({scale: 1, opacity: 1});
67
+ };
68
+
69
+ // Starts a discard unless one runs. It also ends a drag in progress: the
70
+ // drag's next move would take the discard's motion over and drag the dealt
71
+ // card.
72
+ const startDiscard = () => {
73
+ if (discarding.current) {
74
+ return false;
75
+ }
76
+ discarding.current = true;
77
+ drag.current = null;
78
+ return true;
79
+ };
80
+
81
+ // Throws the card away on its release velocity, then deals the next one.
82
+ const discard = async (velocity: {x: number; y: number}) => {
83
+ if (!startDiscard()) {
84
+ return;
85
+ }
86
+ const speed = Math.hypot(velocity.x, velocity.y);
87
+ const boost = speed < MIN_THROW ? MIN_THROW / Math.max(speed, 1) : 1;
88
+ const throwX = speed < 1 ? MIN_THROW : velocity.x * boost;
89
+ // The card coasts on while it fades; once it is gone, the next card is
90
+ // dealt in place, which ends the coast. A coast continues the person's
91
+ // throw, so Reduce Motion keeps it.
92
+ void animator.decay({x: throwX, y: velocity.y * boost});
93
+ await animator.animate({opacity: 0});
94
+ await dealNext();
95
+ };
96
+
97
+ // The button moves the card off on the state-change motion: a planned
98
+ // move, which Reduce Motion turns into a fade where the card is.
99
+ const discardWithButton = async () => {
100
+ if (!startDiscard()) {
101
+ return;
102
+ }
103
+ await animator.animate({x: 400, opacity: 0});
104
+ await dealNext();
105
+ };
106
+
107
+ const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
108
+ // A leaving card takes no press. Pinning it would end its discard and deal
109
+ // the next card under the finger.
110
+ if (discarding.current) {
111
+ return;
112
+ }
113
+ event.currentTarget.setPointerCapture(event.pointerId);
114
+ // Pins the card where it shows, so the drag starts there. Only the
115
+ // position stops, so a card fading in keeps fading in.
116
+ const {x, y, rotate} = animator.get();
117
+ animator.set({x, y, rotate});
118
+ const start = {
119
+ t: event.timeStamp,
120
+ x: event.clientX - x,
121
+ y: event.clientY - y,
122
+ };
123
+ drag.current = {start, samples: []};
124
+ };
125
+
126
+ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
127
+ const current = drag.current;
128
+ if (current == null) {
129
+ return;
130
+ }
131
+ const x = event.clientX - current.start.x;
132
+ const y = event.clientY - current.start.y;
133
+ current.samples.push({t: event.timeStamp, x, y});
134
+ // The card follows the finger, turning a little with the drag.
135
+ animator.set({x, y, rotate: x / 18});
136
+ };
137
+
138
+ // A cancelled pointer was not let go, so the card springs back.
139
+ const onPointerCancel = () => {
140
+ if (drag.current == null) {
141
+ return;
142
+ }
143
+ drag.current = null;
144
+ void animator.animate({x: 0, y: 0, rotate: 0});
145
+ };
146
+
147
+ const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
148
+ const current = drag.current;
149
+ drag.current = null;
150
+ if (current == null) {
151
+ return;
152
+ }
153
+ const velocity = releaseVelocity(current.samples, event.timeStamp);
154
+ if (Math.abs(velocity.x) > THROW_SPEED) {
155
+ void discard(velocity);
156
+ } else {
157
+ // A gentle release springs back, carrying on as it was let go.
158
+ void animator.animate({x: 0, y: 0, rotate: 0}, {velocity});
159
+ }
160
+ };
161
+
162
+ return (
163
+ <VStack gap={4} style={{maxWidth: 360, padding: 16}}>
164
+ <Text type="body">
165
+ Drag the card and let go. A gentle release springs it back; a quick
166
+ flick throws it away.
167
+ </Text>
168
+ <div style={{height: 200, display: 'grid', placeItems: 'center'}}>
169
+ <Card
170
+ ref={ref}
171
+ width={120}
172
+ minHeight={170}
173
+ onPointerDown={onPointerDown}
174
+ onPointerMove={onPointerMove}
175
+ onPointerUp={onPointerUp}
176
+ onPointerCancel={onPointerCancel}
177
+ style={{touchAction: 'none', cursor: 'grab', userSelect: 'none'}}
178
+ role="img"
179
+ aria-label={card.name}>
180
+ <VStack gap={1} hAlign="center" style={{paddingBlock: 40}}>
181
+ <Text type="display-2" weight="bold">
182
+ {card.rank}
183
+ </Text>
184
+ <Text type="display-3">{card.suit}</Text>
185
+ </VStack>
186
+ </Card>
187
+ </div>
188
+ <HStack gap={2}>
189
+ <Button
190
+ label={`Discard ${card.name}`}
191
+ variant="secondary"
192
+ onClick={() => void discardWithButton()}
193
+ />
194
+ <Button
195
+ label="Shake"
196
+ variant="ghost"
197
+ onClick={() =>
198
+ void animator.animate(
199
+ {x: 0, rotate: 0},
200
+ {velocity: {x: 900, rotate: 300}},
201
+ )
202
+ }
203
+ />
204
+ </HStack>
205
+ <VisuallyHidden as="div" aria-live="polite">
206
+ {status}
207
+ </VisuallyHidden>
208
+ </VStack>
209
+ );
210
+ }
@@ -1874,6 +1874,10 @@ function ComposeWindow({
1874
1874
  )}
1875
1875
  </>
1876
1876
  }
1877
+ // The recipient rows read as one header, so all three stay
1878
+ // inline fields on every device; the sheet has no end lane
1879
+ // for the Cc and Bcc buttons.
1880
+ presentation="popover"
1877
1881
  />
1878
1882
  {hasCc ? (
1879
1883
  <Tokenizer
@@ -1884,6 +1888,7 @@ function ComposeWindow({
1884
1888
  value={cc}
1885
1889
  onChange={items => setCc(items)}
1886
1890
  hasCreate
1891
+ presentation="popover"
1887
1892
  />
1888
1893
  ) : null}
1889
1894
  {hasBcc ? (
@@ -1895,6 +1900,7 @@ function ComposeWindow({
1895
1900
  value={bcc}
1896
1901
  onChange={items => setBcc(items)}
1897
1902
  hasCreate
1903
+ presentation="popover"
1898
1904
  />
1899
1905
  ) : null}
1900
1906
  <TextInput
@@ -463,6 +463,7 @@ function PageHeader({
463
463
  onRemove={onRemove}
464
464
  />
465
465
  )}
466
+ presentation="popover"
466
467
  />
467
468
  </HStack>
468
469
  </VStack>
@@ -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,
@@ -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
 
@@ -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';
@@ -7,7 +7,8 @@
7
7
  * @input A read-only operation (`withListingCache(fn)`), and directory paths
8
8
  * its discovery helpers list or probe.
9
9
  * @output The same answers `fs.readdirSync` / `fs.existsSync` give, read from
10
- * disk once per path while the operation runs.
10
+ * disk once per path while the operation runs, and `oncePerListing`, a
11
+ * value computed once per operation.
11
12
  * @position Used by the name resolvers in foundation/discovery and by
12
13
  * `existsCaseExact`. A search or build resolves ~160 components and their
13
14
  * hooks, and each resolution walks the same source tree again; inside one
@@ -23,7 +24,9 @@ import * as fs from 'node:fs';
23
24
  * @typedef {{
24
25
  * names: Map<string, string[]>,
25
26
  * entries: Map<string, fs.Dirent[]>,
27
+ * byName: Map<string, Map<string, fs.Dirent>>,
26
28
  * exists: Map<string, boolean>,
29
+ * memos: Map<string, unknown>,
27
30
  * }} ListingCache
28
31
  */
29
32
 
@@ -40,11 +43,40 @@ const scope = new AsyncLocalStorage();
40
43
  export function withListingCache(fn) {
41
44
  if (scope.getStore()) return fn();
42
45
  return scope.run(
43
- {names: new Map(), entries: new Map(), exists: new Map()},
46
+ {
47
+ names: new Map(),
48
+ entries: new Map(),
49
+ byName: new Map(),
50
+ exists: new Map(),
51
+ memos: new Map(),
52
+ },
44
53
  fn,
45
54
  );
46
55
  }
47
56
 
57
+ /**
58
+ * `compute()` once per operation, under `key`. A later call in the same
59
+ * operation gets the first result; outside an operation it computes each time.
60
+ * @template T
61
+ * @param {string} key
62
+ * @param {() => T} compute
63
+ * @returns {T}
64
+ */
65
+ export function oncePerListing(key, compute) {
66
+ const cache = scope.getStore();
67
+ if (!cache) return compute();
68
+ if (!cache.memos.has(key)) cache.memos.set(key, compute());
69
+ return /** @type {T} */ (cache.memos.get(key));
70
+ }
71
+
72
+ /**
73
+ * Whether an operation's listing cache is active.
74
+ * @returns {boolean}
75
+ */
76
+ export function listingCacheActive() {
77
+ return scope.getStore() != null;
78
+ }
79
+
48
80
  /**
49
81
  * `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a
50
82
  * caller that sorts it cannot reorder another caller's listing.
@@ -78,6 +110,41 @@ export function listDirEntries(dir) {
78
110
  return entries.slice();
79
111
  }
80
112
 
113
+ /**
114
+ * The entry named exactly `name` in `dir`'s listing, or null when the folder
115
+ * holds no such name or cannot be read. Inside an operation, a name the
116
+ * listing lacks costs no probe of the disk.
117
+ * @param {string} dir
118
+ * @param {string} name
119
+ * @returns {fs.Dirent | null}
120
+ */
121
+ export function findEntry(dir, name) {
122
+ const cache = scope.getStore();
123
+ if (!cache) {
124
+ try {
125
+ return (
126
+ fs
127
+ .readdirSync(dir, {withFileTypes: true})
128
+ .find(entry => entry.name === name) ?? null
129
+ );
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+ let byName = cache.byName.get(dir);
135
+ if (!byName) {
136
+ let entries;
137
+ try {
138
+ entries = listDirEntries(dir);
139
+ } catch {
140
+ return null;
141
+ }
142
+ byName = new Map(entries.map(entry => [entry.name, entry]));
143
+ cache.byName.set(dir, byName);
144
+ }
145
+ return byName.get(name) ?? null;
146
+ }
147
+
81
148
  /**
82
149
  * `fs.existsSync(target)`, probed once per operation.
83
150
  * @param {string} target
@@ -13,7 +13,12 @@ import {createRequire} from 'node:module';
13
13
  import * as os from 'node:os';
14
14
  import * as path from 'node:path';
15
15
  import {fileURLToPath} from 'node:url';
16
- import {listDir, pathExists} from './listing-cache.mjs';
16
+ import {
17
+ findEntry,
18
+ listDir,
19
+ listingCacheActive,
20
+ pathExists,
21
+ } from './listing-cache.mjs';
17
22
  import {ERROR_CODES} from '../response/error-codes.mjs';
18
23
  import {carriedCore, runChoice} from '../release/run-context.mjs';
19
24
  import {findDeclaringPackage} from '../release/project.mjs';
@@ -867,6 +872,31 @@ export function listComponents(coreDir) {
867
872
  .sort();
868
873
  }
869
874
 
875
+ /**
876
+ * `path.relative(root, target)`, read straight off the string when `target`
877
+ * is a plain path under `root`. A resolver probes tens of thousands of such
878
+ * paths, and `path.relative` normalizes both on every call.
879
+ * @param {string} root
880
+ * @param {string} target
881
+ * @returns {string}
882
+ */
883
+ function relativeInside(root, target) {
884
+ const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
885
+ if (path.isAbsolute(root) && target.startsWith(prefix)) {
886
+ const rest = target.slice(prefix.length);
887
+ const plain =
888
+ rest !== '' &&
889
+ !(path.sep === '\\' && rest.includes('/')) &&
890
+ rest
891
+ .split(path.sep)
892
+ .every(
893
+ segment => segment !== '' && segment !== '.' && segment !== '..',
894
+ );
895
+ if (plain) return rest;
896
+ }
897
+ return path.relative(root, target);
898
+ }
899
+
870
900
  /**
871
901
  * Does `targetPath` exist with EXACTLY this spelling?
872
902
  *
@@ -883,13 +913,28 @@ export function listComponents(coreDir) {
883
913
  * @returns {boolean}
884
914
  */
885
915
  export function existsCaseExact(targetPath, rootDir) {
886
- if (!pathExists(targetPath)) return false;
887
-
888
- const rel = path.relative(rootDir, targetPath);
889
- if (rel === '') return true;
916
+ const rel = relativeInside(rootDir, targetPath);
917
+ if (rel === '') return pathExists(targetPath);
890
918
  if (path.isAbsolute(rel) || rel === '..' || rel.startsWith(`..${path.sep}`))
891
919
  return false;
892
920
 
921
+ if (listingCacheActive()) {
922
+ // Inside an operation the folders' listings answer, so a name that a
923
+ // listing lacks costs no probe of the disk. A symbolic link still needs
924
+ // its target.
925
+ let folder = rootDir;
926
+ let entry = null;
927
+ for (const segment of rel.split(path.sep)) {
928
+ entry = findEntry(folder, segment);
929
+ if (!entry) return false;
930
+ folder = folder.endsWith(path.sep)
931
+ ? `${folder}${segment}`
932
+ : `${folder}${path.sep}${segment}`;
933
+ }
934
+ return !entry?.isSymbolicLink() || pathExists(targetPath);
935
+ }
936
+
937
+ if (!pathExists(targetPath)) return false;
893
938
  let dir = rootDir;
894
939
  for (const segment of rel.split(path.sep)) {
895
940
  let entries;