@astryxdesign/cli 0.7.5-canary.ae842c8 → 0.7.5-canary.bc40b80

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.
@@ -49,12 +49,16 @@ import {
49
49
  synonymMatches,
50
50
  } from '../../foundation/text/suggest-order.mjs';
51
51
  import {AstryxError, coreDirOrThrow} from '../error.mjs';
52
+ import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
52
53
  import {
53
54
  componentLinkProvider,
54
55
  linkComponentDoc,
55
56
  loadDocsCatalog,
56
57
  } from '../docs/_adapter.mjs';
57
58
 
59
+ /** How far below the first suggestion's score a later one may be. */
60
+ const NEAR_FIRST = 10;
61
+
58
62
  /** @type {Record<string, {synonyms?: string[]}> | undefined} */
59
63
  let cards;
60
64
  /**
@@ -503,9 +507,20 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {
503
507
  Object.values(components).flat(),
504
508
  synonymMatches(dirName, searchCards()),
505
509
  ).slice(0, count);
510
+ // Past the first two suggestions, only the ones about as close as
511
+ // the first (within NEAR_FIRST points), or a close spelling of the
512
+ // whole typed name (a typo): a weaker match after a strong one reads
513
+ // as noise. The list only gets shorter and keeps at least two.
514
+ const typed = dirName.toLowerCase();
515
+ const nearFirst = candidates.filter(
516
+ (c, i) =>
517
+ i < 2 ||
518
+ c.score >= candidates[0].score - NEAR_FIRST ||
519
+ levenshteinDistance(c.name.toLowerCase(), typed) <= 2,
520
+ );
506
521
  throw new AstryxError(
507
522
  `No component named "${name}"`,
508
- candidates.map(c => ({name: c.name, reason: c.reason})),
523
+ nearFirst.map(c => ({name: c.name, reason: c.reason})),
509
524
  ERROR_CODES.ERR_UNKNOWN_COMPONENT,
510
525
  );
511
526
  }
@@ -499,3 +499,34 @@ describe('component dispatcher — detail levels on single component (text only)
499
499
  SLOW,
500
500
  );
501
501
  });
502
+
503
+ describe('component not-found suggestions', () => {
504
+ const suggested = async (/** @type {string} */ name) => {
505
+ const error = await component(name, {cwd}).catch(e => e);
506
+ expect(error).toBeInstanceOf(AstryxError);
507
+ expect(error.code).toBe('ERR_UNKNOWN_COMPONENT');
508
+ return error.suggestions.map((/** @type {{name: string}} */ s) => s.name);
509
+ };
510
+
511
+ it(
512
+ 'leaves out a weaker match after a strong first suggestion',
513
+ async () => {
514
+ // FieldLabel is another name for it; past the second suggestion, the
515
+ // matches on one word of the name ("input", "label") are weaker and add
516
+ // only noise.
517
+ const names = await suggested('InputLabel');
518
+ expect(names[0]).toBe('FieldLabel');
519
+ expect(names).toHaveLength(2);
520
+ },
521
+ SLOW,
522
+ );
523
+
524
+ it(
525
+ 'keeps a close spelling of the whole name after a stronger first match',
526
+ async () => {
527
+ expect(await suggested('Blockqoute')).toContain('Blockquote');
528
+ expect(await suggested('TextrAea')).toContain('TextArea');
529
+ },
530
+ SLOW,
531
+ );
532
+ });
@@ -335,8 +335,11 @@ export function holdsOwnName(tree: DocsTree, catalog: DocsCatalog, entry: import
335
335
  export function routeOwner(tree: DocsTree, entry: import("../../foundation/discovery/docs-discovery.mjs").DocsTopicEntry): TreeNode | null;
336
336
  /**
337
337
  * The error for a docs argument that names nothing. For a route, it suggests
338
- * the children of the deepest namespace the route reaches; otherwise, every
339
- * topic and every top-level namespace.
338
+ * every child of the deepest namespace the route reaches, closest first.
339
+ * Otherwise it suggests the docs the argument names in another spelling, or
340
+ * failing that the topics and top-level namespaces, closest first and cut
341
+ * where the matches get weaker (every one of them when none shares a word
342
+ * with the argument).
340
343
  * @param {unknown} topic
341
344
  * @param {DocsCatalog} catalog
342
345
  * @returns {Promise<AstryxError>}
@@ -77,6 +77,7 @@ import {
77
77
  discoverIntegrationTemplatesForOne,
78
78
  } from '../../foundation/discovery/template-adapter.mjs';
79
79
  import {findCoreDir} from '../../foundation/fs/paths.mjs';
80
+ import {reusedWhileUnchanged} from '../../foundation/fs/read-record.mjs';
80
81
  import {AstryxError} from '../error.mjs';
81
82
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
82
83
  import {orderRouteSuggestions} from '../../foundation/text/suggest-order.mjs';
@@ -393,8 +394,8 @@ export function projectTree(catalog, {fresh = false} = {}) {
393
394
  return tree;
394
395
  }
395
396
 
396
- /** @type {ReturnType<typeof loadTreeInputs> | undefined} */
397
- let cliTreeInputs;
397
+ /** The CLI's own tree files, loaded again after one of them changes. */
398
+ const cliTreeInputs = reusedWhileUnchanged(() => loadTreeInputs());
398
399
 
399
400
  /**
400
401
  * Every flat topic in the catalog, as the tree's topic levels read it.
@@ -441,8 +442,7 @@ async function flatTopicInputs(catalog) {
441
442
  */
442
443
  async function buildProjectTree(catalog, fresh) {
443
444
  const added = catalog.treeInputs;
444
- if (fresh || !cliTreeInputs) cliTreeInputs = loadTreeInputs();
445
- const cli = await cliTreeInputs;
445
+ const cli = await cliTreeInputs({fresh});
446
446
  const result = buildDocsTree({
447
447
  namespaces: [...cli.namespaces, ...added.flatMap(each => each.namespaces)],
448
448
  docs: [...cli.docs, ...added.flatMap(each => each.guides)],
@@ -573,11 +573,15 @@ function identitiesOf(tree) {
573
573
  /**
574
574
  * The CLI's authoring docs, by kind and name. The field reference under
575
575
  * `astryx docs authoring` reads each as one section keyed by its name, so a
576
- * link to one opens that section. Loaded once per process, like the CLI's
577
- * tree files.
578
- * @type {Promise<Map<string, any>> | undefined}
576
+ * link to one opens that section. Loaded again after one of them changes,
577
+ * like the CLI's tree files.
579
578
  */
580
- let authoringDocs;
579
+ const authoringDocs = reusedWhileUnchanged(() =>
580
+ loadAuthoringSelfDocs().then(
581
+ ({loaded}) =>
582
+ new Map(loaded.map(({doc}) => [`${doc.type}\u0000${doc.name}`, doc])),
583
+ ),
584
+ );
581
585
 
582
586
  /**
583
587
  * The CLI authoring doc a link names. The `authoring` namespace is the CLI's
@@ -587,11 +591,7 @@ let authoringDocs;
587
591
  * @returns {Promise<any | null>}
588
592
  */
589
593
  async function authoringDoc(kind, name) {
590
- authoringDocs ??= loadAuthoringSelfDocs().then(
591
- ({loaded}) =>
592
- new Map(loaded.map(({doc}) => [`${doc.type}\u0000${doc.name}`, doc])),
593
- );
594
- return (await authoringDocs).get(`${kind}\u0000${name}`) ?? null;
594
+ return (await authoringDocs()).get(`${kind}\u0000${name}`) ?? null;
595
595
  }
596
596
 
597
597
  /**
@@ -1844,8 +1844,11 @@ function movedRoute(topic, tree) {
1844
1844
 
1845
1845
  /**
1846
1846
  * The error for a docs argument that names nothing. For a route, it suggests
1847
- * the children of the deepest namespace the route reaches; otherwise, every
1848
- * topic and every top-level namespace.
1847
+ * every child of the deepest namespace the route reaches, closest first.
1848
+ * Otherwise it suggests the docs the argument names in another spelling, or
1849
+ * failing that the topics and top-level namespaces, closest first and cut
1850
+ * where the matches get weaker (every one of them when none shares a word
1851
+ * with the argument).
1849
1852
  * @param {unknown} topic
1850
1853
  * @param {DocsCatalog} catalog
1851
1854
  * @returns {Promise<AstryxError>}
@@ -1854,6 +1857,8 @@ export async function unknownTopicError(topic, catalog) {
1854
1857
  const tree = await projectTree(catalog);
1855
1858
  /** @type {Array<{name: string, reason: string}>} */
1856
1859
  let suggestions = [];
1860
+ // Route children stay whole (spec:AST-046); only the other lists are cut.
1861
+ let routeChildren = false;
1857
1862
  if (typeof topic === 'string' && topic.includes('/')) {
1858
1863
  const parts = topic.split('/');
1859
1864
  for (
@@ -1863,6 +1868,7 @@ export async function unknownTopicError(topic, catalog) {
1863
1868
  ) {
1864
1869
  const near = tree.get(parts.slice(0, depth).join('/'));
1865
1870
  if (near) {
1871
+ routeChildren = true;
1866
1872
  suggestions = near.slots.flatMap(slot =>
1867
1873
  slot.children.map(route => ({
1868
1874
  name: route,
@@ -1894,7 +1900,9 @@ export async function unknownTopicError(topic, catalog) {
1894
1900
  ];
1895
1901
  }
1896
1902
  if (typeof topic === 'string') {
1897
- suggestions = orderRouteSuggestions(topic, suggestions);
1903
+ suggestions = orderRouteSuggestions(topic, suggestions, {
1904
+ closest: !routeChildren,
1905
+ });
1898
1906
  }
1899
1907
  // A route that moved names where it went, ahead of the usual suggestions
1900
1908
  // (spec:AST-046 FR9, FR6).
@@ -254,6 +254,24 @@ describe('docs() dispatcher routing', () => {
254
254
  );
255
255
  }, SLOW);
256
256
 
257
+ it('an unknown route keeps every child of its namespace, closest first', async () => {
258
+ const error = await docs('tokens/usage').catch(e => e);
259
+ expect(error.code).toBe('ERR_UNKNOWN_TOPIC');
260
+ const names = error.suggestions.map(s => s.name);
261
+ expect(names[0]).toBe('tokens/tokens-usage');
262
+ const none = await docs('tokens/zzzz-nope').catch(e => e);
263
+ expect([...names].sort()).toEqual(none.suggestions.map(s => s.name).sort());
264
+ }, SLOW);
265
+
266
+ it('an unknown flat topic is cut where the matches get weaker', async () => {
267
+ const error = await docs('authoring-at-meta').catch(e => e);
268
+ expect(error.suggestions.map(s => s.name)).toEqual(['authoring']);
269
+ // One-letter words do not narrow it: `a11y` keeps the whole browse list.
270
+ const browse = await docs('zzzz-nope').catch(e => e);
271
+ const a11y = await docs('a11y').catch(e => e);
272
+ expect(a11y.suggestions.length).toBe(browse.suggestions.length);
273
+ }, SLOW);
274
+
257
275
  it('a section no guide of a namespace has -> ERR_UNKNOWN_SECTION, naming its guides', async () => {
258
276
  const err = await docs('cli', 'zzzz-nope').catch(e => e);
259
277
  expect(err).toBeInstanceOf(AstryxError);
@@ -450,11 +450,11 @@ describe('integration-contributed topics', () => {
450
450
 
451
451
  it('offers the contributed topics as suggestions on an unknown one', async () => {
452
452
  scaffold({'deploying.doc.mjs': topic()});
453
- await expect(docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true})).rejects.toBeInstanceOf(
453
+ await expect(docs('zzqx-qqzz', undefined, {cwd: tmpDir, full: true})).rejects.toBeInstanceOf(
454
454
  AstryxError,
455
455
  );
456
456
  try {
457
- await docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true});
457
+ await docs('zzqx-qqzz', undefined, {cwd: tmpDir, full: true});
458
458
  } catch (err) {
459
459
  expect(err.suggestions.map(s => s.name)).toContain('deploying');
460
460
  }
@@ -85,7 +85,7 @@ describe('gatherCandidatesReused', () => {
85
85
  );
86
86
 
87
87
  it(
88
- 'gathers again when a file the gather read changes, in a linked package too',
88
+ 'gathers again when a file the gather read or imported changes, in a linked package too',
89
89
  async () => {
90
90
  // A consumer whose integration is a symlink to a package folder
91
91
  // elsewhere, as a workspace package is.
@@ -162,7 +162,26 @@ describe('gatherCandidatesReused', () => {
162
162
  // An edited file the gather read: the linked package's manifest.
163
163
  const later = new Date(Date.now() + 5_000);
164
164
  fs.utimesSync(path.join(pkg, 'package.json'), later, later);
165
- expect(await gatherCandidatesReused(options)).not.toBe(second);
165
+ const third = await gatherCandidatesReused(options);
166
+ expect(third).not.toBe(second);
167
+
168
+ // An edited doc the gather imported: the next gather reads its new
169
+ // content, not the module this process imported first.
170
+ fs.writeFileSync(
171
+ path.join(pkg, 'components', 'FancyGizmo.doc.mjs'),
172
+ `export default {
173
+ type: 'component',
174
+ name: 'FancyGizmo',
175
+ keywords: ['gizmo'],
176
+ usage: {description: 'A shinier part, now with sprockets.'},
177
+ props: [],
178
+ };\n`,
179
+ );
180
+ const fourth = await gatherCandidatesReused(options);
181
+ expect(fourth).not.toBe(third);
182
+ expect(
183
+ JSON.stringify(fourth.all.find(c => c.name === 'FancyGizmo')),
184
+ ).toContain('A shinier part, now with sprockets.');
166
185
  } finally {
167
186
  fs.rmSync(dir, {recursive: true, force: true});
168
187
  fs.rmSync(pkg, {recursive: true, force: true});
@@ -190,7 +190,9 @@ export async function template(name, options = {}) {
190
190
  if (name && candidates.length === 0) {
191
191
  throw new AstryxError(
192
192
  `Unknown template "${name}"`,
193
- orderByAffinity(name, templates, t => [t.dirName, t.name]).map(t => ({
193
+ orderByAffinity(name, templates, t => [t.dirName, t.name], {
194
+ closest: true,
195
+ }).map(t => ({
194
196
  name: t.dirName,
195
197
  reason: `${t.type} template`,
196
198
  })),
@@ -0,0 +1,63 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The suggestions an unknown template name prints: the closest
5
+ * templates first, and the list stops where the matches get weaker. A name
6
+ * that shares no word with any template still lists every template.
7
+ */
8
+
9
+ import {describe, it, expect} from 'vitest';
10
+ import * as path from 'node:path';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {template} from './template.mjs';
13
+ import {nameWords} from '../../foundation/text/suggest-order.mjs';
14
+
15
+ const cwd = path.resolve(
16
+ path.dirname(fileURLToPath(import.meta.url)),
17
+ '../../../..',
18
+ );
19
+ const SLOW = 30_000;
20
+
21
+ /** @param {string} name */
22
+ async function suggested(name) {
23
+ const error = await template(name, {cwd}).catch(e => e);
24
+ expect(error.code).toBe('ERR_UNKNOWN_TEMPLATE');
25
+ return error.suggestions.map((/** @type {{name: string}} */ s) => s.name);
26
+ }
27
+
28
+ describe('unknown template suggestions', () => {
29
+ it(
30
+ 'lists only templates that carry the typed words when one carries them all',
31
+ async () => {
32
+ const all = await suggested('zzqx-nothing-like-it');
33
+ const near = await suggested('settings-panel');
34
+ expect(near.length).toBeGreaterThan(0);
35
+ expect(near.length).toBeLessThan(all.length);
36
+ for (const name of near.slice(1)) {
37
+ const words = nameWords(name);
38
+ expect(words).toContain('setting');
39
+ expect(words).toContain('panel');
40
+ }
41
+ },
42
+ SLOW,
43
+ );
44
+
45
+ it(
46
+ 'does not narrow the list on a one-letter word',
47
+ async () => {
48
+ const all = await suggested('zzqx-nothing-like-it');
49
+ expect(await suggested('a11y')).toHaveLength(all.length);
50
+ },
51
+ SLOW,
52
+ );
53
+
54
+ it(
55
+ 'lists every template when no template shares a word with the name',
56
+ async () => {
57
+ const all = await suggested('zzqx-nothing-like-it');
58
+ expect(new Set(all).size).toBe(all.length);
59
+ expect(all.length).toBeGreaterThan(100);
60
+ },
61
+ SLOW,
62
+ );
63
+ });
@@ -345,12 +345,12 @@ const RUNNERS = {
345
345
  sites: ['require(@babel/parser)', 'require(jscodeshift)'],
346
346
  },
347
347
  'foundation/doc-compiler/import.mjs': {
348
- runs: 'authored doc files, for the doc reader and discovery',
348
+ runs: 'authored doc files, for the doc reader and discovery, and again after an edit',
349
349
  sites: [
350
- '.import()',
351
- 'createJiti',
352
- 'import(<computed>) ×2',
353
- 'importUserModule',
350
+ '.import() ×2',
351
+ 'createJiti ×2',
352
+ 'import(<computed>) ×4',
353
+ 'importUserModule ×2',
354
354
  ],
355
355
  },
356
356
  'foundation/doc-compiler/read.mjs': {
@@ -5,7 +5,12 @@
5
5
  * authored doc file.
6
6
  *
7
7
  * @input An absolute path to a `.doc.{ts,mjs,js}` (or legacy template) file.
8
- * @output The module's namespace object.
8
+ * @output The module's namespace object: the one a plain import of the file
9
+ * gives, until the file changes; then the edited file's, read once by each
10
+ * importer, its own way, and shared until the next change. A long-running
11
+ * process (a docs site's search, an agent harness) thereby sees an edit to
12
+ * a doc file it already read, as a new process would read it. Only the doc
13
+ * file's own edits count: a module it imports stays as first loaded.
9
14
  * @position Called by ./read.mjs, which hands what comes back to the compiler,
10
15
  * and by discovery, which reads a contributed topic's name and relationships
11
16
  * to build the catalog. Doc files also run outside these importers: each CLI
@@ -20,10 +25,59 @@
20
25
  import {pathToFileURL} from 'node:url';
21
26
  import {createJiti} from 'jiti';
22
27
  import {importUserModule} from '../fs/module-loader.mjs';
28
+ import {fileStamp, recordContentRead} from '../fs/read-record.mjs';
23
29
 
24
30
  /** @type {ReturnType<typeof createJiti> | undefined} */
25
31
  let jsxJiti;
26
32
 
33
+ /**
34
+ * Each doc file imported in this process: its stamp at the last import and,
35
+ * once it changed, the module each importer read for that change.
36
+ * @type {Map<string, {stamp: string, changed: Record<string, Promise<any>> | null}>}
37
+ */
38
+ const imported = new Map();
39
+
40
+ /** Numbers each fresh native import's URL, so it names a new module. */
41
+ let changes = 0;
42
+
43
+ /**
44
+ * Import `file` with `load` until it changes, then once with `loadFresh` for
45
+ * each change, sharing that module until the next one. Each importer (`kind`)
46
+ * keeps its own module, as each has its own loader. The file counts as read
47
+ * by the running operation (see ../fs/read-record.mjs).
48
+ * @param {string} file
49
+ * @param {'doc' | 'template' | 'native'} kind
50
+ * @param {(file: string) => Promise<any>} load
51
+ * @param {(file: string) => Promise<any>} loadFresh
52
+ * @returns {Promise<any>}
53
+ */
54
+ function importCurrent(file, kind, load, loadFresh) {
55
+ recordContentRead(file);
56
+ const stamp = fileStamp(file);
57
+ let seen = imported.get(file);
58
+ if (!seen) {
59
+ imported.set(file, {stamp, changed: null});
60
+ return load(file);
61
+ }
62
+ if (seen.stamp !== stamp) {
63
+ seen = {stamp, changed: {}};
64
+ imported.set(file, seen);
65
+ }
66
+ if (!seen.changed) return load(file);
67
+ return (seen.changed[kind] ??= loadFresh(file));
68
+ }
69
+
70
+ /**
71
+ * The file's URL, naming a new module for each change.
72
+ * @param {string} file
73
+ * @returns {string}
74
+ */
75
+ function freshUrl(file) {
76
+ const url = pathToFileURL(file);
77
+ url.searchParams.set('astryx-doc', String(++changes));
78
+ return url.href;
79
+ }
80
+
27
81
  /**
28
82
  * Import a component, hook, topic, or self-doc module: `.ts` through jiti,
29
83
  * anything else natively.
@@ -31,7 +85,9 @@ let jsxJiti;
31
85
  * @returns {Promise<any>}
32
86
  */
33
87
  export function importDocModule(file) {
34
- return importUserModule(file);
88
+ return importCurrent(file, 'doc', importUserModule, changed =>
89
+ importUserModule(changed, {fresh: true}),
90
+ );
35
91
  }
36
92
 
37
93
  /**
@@ -41,11 +97,23 @@ export function importDocModule(file) {
41
97
  * @returns {Promise<any>}
42
98
  */
43
99
  export function importTemplateModule(file) {
44
- if (file.endsWith('.ts')) {
45
- jsxJiti ??= createJiti(import.meta.url, {jsx: true});
46
- return jsxJiti.import(file);
47
- }
48
- return import(`file://${file}`);
100
+ return importCurrent(
101
+ file,
102
+ 'template',
103
+ first => {
104
+ if (first.endsWith('.ts')) {
105
+ jsxJiti ??= createJiti(import.meta.url, {jsx: true});
106
+ return jsxJiti.import(first);
107
+ }
108
+ return import(`file://${first}`);
109
+ },
110
+ changed =>
111
+ changed.endsWith('.ts')
112
+ ? createJiti(import.meta.url, {jsx: true, moduleCache: false}).import(
113
+ changed,
114
+ )
115
+ : import(freshUrl(changed)),
116
+ );
49
117
  }
50
118
 
51
119
  /**
@@ -55,5 +123,10 @@ export function importTemplateModule(file) {
55
123
  * @returns {Promise<any>}
56
124
  */
57
125
  export function importNativeModule(file) {
58
- return import(pathToFileURL(file).href);
126
+ return importCurrent(
127
+ file,
128
+ 'native',
129
+ first => import(pathToFileURL(first).href),
130
+ changed => import(freshUrl(changed)),
131
+ );
59
132
  }
@@ -2,9 +2,10 @@
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
4
  /**
5
- * Lower one descriptor file. Memoized per file and options for the life of the
6
- * process; a file that failed to load is tried again on the next read, as a
7
- * fresh import would be.
5
+ * Lower one descriptor file. Memoized per file and options while the file is
6
+ * unchanged; an edited file is lowered again from its new content, and a file
7
+ * that failed to load is tried again on the next read, as a fresh import
8
+ * would be.
8
9
  * @param {string} file absolute path
9
10
  * @param {ReadOptions} options
10
11
  * @param {{node?: boolean}} [want] also build the sealed node
@@ -8,9 +8,9 @@
8
8
  * how strictly the reader checks.
9
9
  * @output The lowered doc for that file. Readers get the view they have always
10
10
  * read, lowered afresh on every read; a whole-project compile also gets the
11
- * sealed node, memoized per file for the life of the process. For doc
12
- * topics: the compiler input for a topic, with its extensions and overlays
13
- * loaded.
11
+ * sealed node, memoized per file while the file is unchanged. An edited file
12
+ * is read again in the same process (./import.mjs). For doc topics: the
13
+ * compiler input for a topic, with its extensions and overlays loaded.
14
14
  * @position Loads authored doc files for the readers in api/ and clients/ and
15
15
  * hands each to ./compile.mjs. Each reader keeps its own loader, export
16
16
  * order, and strictness, so what it prints is what it printed before.
@@ -30,6 +30,7 @@ import {
30
30
  importNativeModule,
31
31
  importTemplateModule,
32
32
  } from './import.mjs';
33
+ import {fileStamp, recordContentRead} from '../fs/read-record.mjs';
33
34
  import {lowerDoc, parserFor} from './compile.mjs';
34
35
  import {translationFor} from './overlays.mjs';
35
36
  import {parseReadableDoc} from './parse-readable.mjs';
@@ -82,13 +83,14 @@ const LOADERS = Object.freeze({
82
83
  * @property {boolean} [check] hold the doc to its kind's parser
83
84
  */
84
85
 
85
- /** @type {Map<string, Promise<import('./compile.mjs').LoweredDoc>>} */
86
+ /** @type {Map<string, {stamp: string, result: Promise<import('./compile.mjs').LoweredDoc>}>} */
86
87
  const lowered = new Map();
87
88
 
88
89
  /**
89
- * Lower one descriptor file. Memoized per file and options for the life of the
90
- * process; a file that failed to load is tried again on the next read, as a
91
- * fresh import would be.
90
+ * Lower one descriptor file. Memoized per file and options while the file is
91
+ * unchanged; an edited file is lowered again from its new content, and a file
92
+ * that failed to load is tried again on the next read, as a fresh import
93
+ * would be.
92
94
  * @param {string} file absolute path
93
95
  * @param {ReadOptions} options
94
96
  * @param {{node?: boolean}} [want] also build the sealed node
@@ -110,7 +112,10 @@ export function compileDocFile(file, options, {node = false} = {}) {
110
112
  check,
111
113
  node,
112
114
  ]);
113
- let result = lowered.get(key);
115
+ recordContentRead(file);
116
+ const stamp = fileStamp(file);
117
+ const hit = lowered.get(key);
118
+ let result = hit?.stamp === stamp ? hit.result : undefined;
114
119
  if (!result) {
115
120
  result = loadAuthored(file, options, lang).then(authored => {
116
121
  const provider = options.provider ?? packageOf(file);
@@ -130,11 +135,11 @@ export function compileDocFile(file, options, {node = false} = {}) {
130
135
  );
131
136
  if (out.node) deepFreeze(out.node);
132
137
  if (out.loadFailed || 'overlayError' in authored) {
133
- lowered.delete(key);
138
+ if (lowered.get(key)?.result === result) lowered.delete(key);
134
139
  }
135
140
  return out;
136
141
  });
137
- lowered.set(key, result);
142
+ lowered.set(key, {stamp, result});
138
143
  }
139
144
  return result;
140
145
  }
@@ -16,6 +16,7 @@ import {Project} from '../config/project.mjs';
16
16
  import {CLI_ROOT} from '../fs/paths.mjs';
17
17
  import {loadComponentDoc, loadDocs} from '../discovery/component-loader.mjs';
18
18
  import {compileDocFile, readDocView} from './read.mjs';
19
+ import {importDocModule, importNativeModule} from './import.mjs';
19
20
  import {collectDocInputs} from './inputs.mjs';
20
21
 
21
22
  const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');
@@ -151,7 +152,7 @@ describe('readDocView', () => {
151
152
  ).toBe('Legacy');
152
153
  });
153
154
 
154
- it('reads each file once per process, and retries a file that failed to load', async () => {
155
+ it('reads each file once while it is unchanged, and retries a file that failed to load', async () => {
155
156
  const file = write('Card.doc.mjs', card);
156
157
  const before = await compileDocFile(file, {root: 'components'});
157
158
  expect(await compileDocFile(file, {root: 'components'})).toBe(before);
@@ -320,3 +321,60 @@ catch (e) { console.log('threw', e.message.split('\\n')[0]); }`,
320
321
  expect(run('loadComponentDoc')).toMatch(/^(ok Typed|threw .*is invalid)/);
321
322
  });
322
323
  });
324
+
325
+ describe('an edited doc file, read again in the same process', () => {
326
+ /** @param {string} displayName */
327
+ const doc = displayName =>
328
+ `export default {type: 'component', name: 'Edited', displayName: ${JSON.stringify(displayName)}, usage: {description: 'd'}, props: []};\n`;
329
+
330
+ it('reads the new content, and shares each version while it is unchanged', async () => {
331
+ const file = write('Edited.doc.mjs', doc('First'));
332
+ const first = await loadDocs(file);
333
+ expect(first.displayName).toBe('First');
334
+ expect(await loadDocs(file)).toBe(first);
335
+ fs.writeFileSync(file, doc('Second, longer'));
336
+ const second = await loadDocs(file);
337
+ expect(second.displayName).toBe('Second, longer');
338
+ expect(await loadDocs(file)).toBe(second);
339
+ expect((await loadComponentDoc(file)).displayName).toBe('Second, longer');
340
+ });
341
+
342
+ it('reads an edited TypeScript doc again', async () => {
343
+ const file = write('Edited.doc.ts', doc('First'));
344
+ expect((await loadComponentDoc(file)).displayName).toBe('First');
345
+ fs.writeFileSync(file, doc('Second, longer'));
346
+ expect((await loadComponentDoc(file)).displayName).toBe('Second, longer');
347
+ });
348
+
349
+ it('gives each importer its own read of an edited TypeScript doc, as a new process would', async () => {
350
+ const file = write('Pair.doc.ts', doc('First'));
351
+ const nativeBefore = await importNativeModule(file);
352
+ expect(await importDocModule(file)).not.toBe(nativeBefore);
353
+ fs.writeFileSync(file, doc('Second, longer'));
354
+ // The unchecked reader (a plain import) first, then the checked one (jiti).
355
+ expect((await loadDocs(file)).displayName).toBe('Second, longer');
356
+ expect((await loadComponentDoc(file)).displayName).toBe('Second, longer');
357
+ const nativeAfter = await importNativeModule(file);
358
+ const docAfter = await importDocModule(file);
359
+ expect(docAfter).not.toBe(nativeAfter);
360
+ expect(await importNativeModule(file)).toBe(nativeAfter);
361
+ expect(await importDocModule(file)).toBe(docAfter);
362
+ });
363
+
364
+ it('lowers an edited file again for a whole-project compile', async () => {
365
+ const file = write('Edited.doc.mjs', doc('First'));
366
+ const read = () => compileDocFile(file, {root: 'components'});
367
+ expect((await read()).view.displayName).toBe('First');
368
+ fs.writeFileSync(file, doc('Second, longer'));
369
+ expect((await read()).view.displayName).toBe('Second, longer');
370
+ });
371
+
372
+ it('reads a fix after an edit that broke the file', async () => {
373
+ const file = write('Edited.doc.mjs', doc('First'));
374
+ expect((await loadDocs(file)).displayName).toBe('First');
375
+ fs.writeFileSync(file, 'export default {;\n');
376
+ await expect(loadDocs(file)).rejects.toThrow();
377
+ fs.writeFileSync(file, doc('Fixed again'));
378
+ expect((await loadDocs(file)).displayName).toBe('Fixed again');
379
+ });
380
+ });
@@ -7,8 +7,9 @@
7
7
  * no-cache jiti instance. A fresh CommonJS `.js` read evicts and reloads through
8
8
  * `require`; an ESM `.js` or `.mjs` read uses a cache-busted file URL. The
9
9
  * nearest package.json `type` decides `.js`, matching Node's package scopes.
10
- * Normal loads retain module caching. `fresh` is an explicit migration-only
11
- * escape hatch for rereading files that a codemod changed during this process.
10
+ * Normal loads retain module caching. `fresh` rereads a file that changed
11
+ * during this process: one a codemod rewrote, or an edited doc file (the doc
12
+ * importers in ../doc-compiler/import.mjs read each change once).
12
13
  * Anything the module writes to stdout while it loads goes to stderr.
13
14
  *
14
15
  * @param {string} file absolute path
@@ -104,8 +104,9 @@ async function withStdoutOnStderr(load) {
104
104
  * no-cache jiti instance. A fresh CommonJS `.js` read evicts and reloads through
105
105
  * `require`; an ESM `.js` or `.mjs` read uses a cache-busted file URL. The
106
106
  * nearest package.json `type` decides `.js`, matching Node's package scopes.
107
- * Normal loads retain module caching. `fresh` is an explicit migration-only
108
- * escape hatch for rereading files that a codemod changed during this process.
107
+ * Normal loads retain module caching. `fresh` rereads a file that changed
108
+ * during this process: one a codemod rewrote, or an edited doc file (the doc
109
+ * importers in ../doc-compiler/import.mjs read each change once).
109
110
  * Anything the module writes to stdout while it loads goes to stderr.
110
111
  *
111
112
  * @param {string} file absolute path
@@ -30,6 +30,8 @@ const fs = await import('node:fs');
30
30
 
31
31
  let tmpDir;
32
32
  beforeEach(() => {
33
+ // One mock serves both tests, so each counts only its own calls, in any order.
34
+ vi.mocked(fs.linkSync).mockClear();
33
35
  tmpDir = realFs.mkdtempSync(path.join(os.tmpdir(), 'astryx-publish-eperm-'));
34
36
  });
35
37
  afterEach(() => {
@@ -1,12 +1,27 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
+ /**
5
+ * One path's state: its size and modification time, plus its change time and
6
+ * inode, which change on a rewrite even when npm stamps the same size and
7
+ * modification time; or that it is absent.
8
+ * @param {string} file
9
+ * @returns {string}
10
+ */
11
+ export function fileStamp(file: string): string;
4
12
  /**
5
13
  * Whether every recorded path is still in the state it had when it was read.
6
14
  * @param {Map<string, string>} recorded - From recordReads.
7
15
  * @returns {boolean}
8
16
  */
9
17
  export function unchangedSince(recorded: Map<string, string>): boolean;
18
+ /**
19
+ * Count `file` as read by the running operation, as a content read through fs
20
+ * would be, for a read that does not go through fs: a module import. Outside
21
+ * `recordReads` it does nothing.
22
+ * @param {string} file
23
+ */
24
+ export function recordContentRead(file: string): void;
10
25
  /**
11
26
  * Run `fn`, adding to `seen` each path it reads, with that path's state when
12
27
  * it was first read (see the file header).
@@ -16,3 +31,15 @@ export function unchangedSince(recorded: Map<string, string>): boolean;
16
31
  * @returns {T}
17
32
  */
18
33
  export function recordReads<T>(seen: Map<string, string>, fn: () => T): T;
34
+ /**
35
+ * A loader whose value is kept while every file and folder it read is
36
+ * unchanged, and loaded again after a change, so a long-running process sees
37
+ * an edit. A failed load is tried again on the next call. What a kept value
38
+ * read counts as read by the operation that asks for it.
39
+ * @template T
40
+ * @param {() => Promise<T>} load
41
+ * @returns {(options?: {fresh?: boolean}) => Promise<T>}
42
+ */
43
+ export function reusedWhileUnchanged<T>(load: () => Promise<T>): (options?: {
44
+ fresh?: boolean;
45
+ }) => Promise<T>;
@@ -6,11 +6,16 @@
6
6
  *
7
7
  * @input An operation run inside `recordReads(seen, fn)`.
8
8
  * @output `seen` gets every file whose content the operation read through fs
9
- * and every folder it listed or probed, each with its state when first
10
- * read; `unchangedSince(seen)` says whether all are still in that state.
9
+ * or imported as a doc module (`recordContentRead`), and every folder it
10
+ * listed or probed, each with its state when first read;
11
+ * `unchangedSince(seen)` says whether all are still in that state.
11
12
  * @position Used by search's adapter to reuse a gathered catalog only while
12
- * it is exact. Outside `recordReads` nothing is recorded and every fs call
13
- * behaves as before.
13
+ * it is exact, by the docs adapter to rebuild the CLI's own docs tree after
14
+ * an edit (`reusedWhileUnchanged`), and by the doc importers and reader
15
+ * (../doc-compiler) to read an edited doc file again. A run inside another
16
+ * records into both, so an outer reuse sees what an inner one read.
17
+ * Outside `recordReads` nothing is recorded and every fs call behaves as
18
+ * before.
14
19
  */
15
20
 
16
21
  import {AsyncLocalStorage} from 'node:async_hooks';
@@ -19,12 +24,25 @@ import * as path from 'node:path';
19
24
  import {fileURLToPath} from 'node:url';
20
25
 
21
26
  /**
22
- * The paths the running operation touched: every file it read and every
23
- * folder it listed or probed.
24
- * @type {AsyncLocalStorage<Map<string, string>>}
27
+ * The paths the running operations touched, one map per enclosing
28
+ * `recordReads`: every file read and every folder listed or probed.
29
+ * @type {AsyncLocalStorage<Map<string, string>[]>}
25
30
  */
26
31
  const reads = new AsyncLocalStorage();
27
32
 
33
+ /**
34
+ * Add `file` to every running operation's map, with its state now, unless it
35
+ * is there already.
36
+ * @param {Map<string, string>[]} runs
37
+ * @param {string} file
38
+ */
39
+ function note(runs, file) {
40
+ let state;
41
+ for (const seen of runs) {
42
+ if (!seen.has(file)) seen.set(file, (state ??= stateOf(file)));
43
+ }
44
+ }
45
+
28
46
  /** node:fs's module object, whose functions every import of it shares. */
29
47
  const fs = createRequire(import.meta.url)('node:fs');
30
48
 
@@ -64,9 +82,9 @@ function installRecorder() {
64
82
  * @param {...any} args
65
83
  */
66
84
  const wrapped = function (...args) {
67
- const seen = reads.getStore();
85
+ const runs = reads.getStore();
68
86
  const target = args[0];
69
- if (seen && (typeof target === 'string' || target instanceof URL)) {
87
+ if (runs && (typeof target === 'string' || target instanceof URL)) {
70
88
  const file =
71
89
  typeof target === 'string'
72
90
  ? path.resolve(target)
@@ -80,7 +98,7 @@ function installRecorder() {
80
98
  : path.dirname(file);
81
99
  // Its state is taken when it is first read, before the read, so a
82
100
  // change made while the operation runs shows as a change afterwards.
83
- if (!seen.has(checked)) seen.set(checked, stateOf(checked));
101
+ note(runs, checked);
84
102
  }
85
103
  return original.apply(this, args);
86
104
  };
@@ -92,19 +110,23 @@ function installRecorder() {
92
110
  }
93
111
 
94
112
  /**
95
- * One path's state: its change time and size, or that it is absent.
113
+ * One path's state: its size and modification time, plus its change time and
114
+ * inode, which change on a rewrite even when npm stamps the same size and
115
+ * modification time; or that it is absent.
96
116
  * @param {string} file
97
117
  * @returns {string}
98
118
  */
99
- function stateOf(file) {
119
+ export function fileStamp(file) {
100
120
  try {
101
- const stat = statSyncRaw(file);
102
- return `${stat.mtimeMs}\0${stat.size}`;
121
+ const {size, mtimeMs, ctimeMs, ino} = statSyncRaw(file);
122
+ return `${size}:${mtimeMs}:${ctimeMs}:${ino}`;
103
123
  } catch {
104
124
  return '-';
105
125
  }
106
126
  }
107
127
 
128
+ const stateOf = fileStamp;
129
+
108
130
  /**
109
131
  * Whether every recorded path is still in the state it had when it was read.
110
132
  * @param {Map<string, string>} recorded - From recordReads.
@@ -117,6 +139,17 @@ export function unchangedSince(recorded) {
117
139
  return true;
118
140
  }
119
141
 
142
+ /**
143
+ * Count `file` as read by the running operation, as a content read through fs
144
+ * would be, for a read that does not go through fs: a module import. Outside
145
+ * `recordReads` it does nothing.
146
+ * @param {string} file
147
+ */
148
+ export function recordContentRead(file) {
149
+ const runs = reads.getStore();
150
+ if (runs) note(runs, path.resolve(file));
151
+ }
152
+
120
153
  /**
121
154
  * Run `fn`, adding to `seen` each path it reads, with that path's state when
122
155
  * it was first read (see the file header).
@@ -127,5 +160,40 @@ export function unchangedSince(recorded) {
127
160
  */
128
161
  export function recordReads(seen, fn) {
129
162
  installRecorder();
130
- return reads.run(seen, fn);
163
+ return reads.run([...(reads.getStore() ?? []), seen], fn);
164
+ }
165
+
166
+ /**
167
+ * A loader whose value is kept while every file and folder it read is
168
+ * unchanged, and loaded again after a change, so a long-running process sees
169
+ * an edit. A failed load is tried again on the next call. What a kept value
170
+ * read counts as read by the operation that asks for it.
171
+ * @template T
172
+ * @param {() => Promise<T>} load
173
+ * @returns {(options?: {fresh?: boolean}) => Promise<T>}
174
+ */
175
+ export function reusedWhileUnchanged(load) {
176
+ /** @type {{reads: Map<string, string>, value: Promise<T>} | undefined} */
177
+ let last;
178
+ return ({fresh = false} = {}) => {
179
+ if (!fresh && last && unchangedSince(last.reads)) {
180
+ const {reads: recorded, value} = last;
181
+ return value.then(result => {
182
+ const runs = reads.getStore();
183
+ if (runs) for (const [file, state] of recorded) {
184
+ for (const seen of runs) if (!seen.has(file)) seen.set(file, state);
185
+ }
186
+ return result;
187
+ });
188
+ }
189
+ /** @type {Map<string, string>} */
190
+ const seen = new Map();
191
+ const value = recordReads(seen, load);
192
+ const entry = {reads: seen, value};
193
+ last = entry;
194
+ value.catch(() => {
195
+ if (last === entry) last = undefined;
196
+ });
197
+ return value;
198
+ };
131
199
  }
@@ -9,7 +9,12 @@ import {describe, it, expect} from 'vitest';
9
9
  import * as fs from 'node:fs';
10
10
  import * as os from 'node:os';
11
11
  import * as path from 'node:path';
12
- import {recordReads, unchangedSince} from './read-record.mjs';
12
+ import {
13
+ recordContentRead,
14
+ recordReads,
15
+ reusedWhileUnchanged,
16
+ unchangedSince,
17
+ } from './read-record.mjs';
13
18
 
14
19
  function scratch() {
15
20
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-read-record-'));
@@ -72,6 +77,88 @@ describe('recordReads', () => {
72
77
  const seen = new Map();
73
78
  recordReads(seen, () => {});
74
79
  fs.readFileSync(file, 'utf8');
80
+ recordContentRead(file);
75
81
  expect(seen.size).toBe(0);
76
82
  });
83
+
84
+ it('records a file read without fs, such as an imported doc module, and sees it edited', () => {
85
+ const {file} = scratch();
86
+ /** @type {Map<string, string>} */
87
+ const seen = new Map();
88
+ recordReads(seen, () => recordContentRead(file));
89
+ expect([...seen.keys()]).toEqual([file]);
90
+ expect(unchangedSince(seen)).toBe(true);
91
+ fs.writeFileSync(file, 'two, longer');
92
+ expect(unchangedSince(seen)).toBe(false);
93
+ });
94
+
95
+ it('records a read in an operation inside another into both', async () => {
96
+ const {file} = scratch();
97
+ /** @type {Map<string, string>} */
98
+ const outer = new Map();
99
+ /** @type {Map<string, string>} */
100
+ const inner = new Map();
101
+ await recordReads(outer, async () => {
102
+ await recordReads(inner, async () => fs.readFileSync(file, 'utf8'));
103
+ });
104
+ expect([...inner.keys()]).toEqual([file]);
105
+ expect([...outer.keys()]).toEqual([file]);
106
+ });
107
+
108
+ it('sees a rewrite that keeps the size and modification time, as an npm reinstall does', () => {
109
+ const {file} = scratch();
110
+ const stamped = new Date('1985-10-26T08:15:00Z');
111
+ fs.utimesSync(file, stamped, stamped);
112
+ /** @type {Map<string, string>} */
113
+ const seen = new Map();
114
+ recordReads(seen, () => fs.readFileSync(file, 'utf8'));
115
+ // Same size, and the same modification time npm stamps on every file.
116
+ const replacement = `${file}.new`;
117
+ fs.writeFileSync(replacement, 'two');
118
+ fs.utimesSync(replacement, stamped, stamped);
119
+ fs.renameSync(replacement, file);
120
+ expect(unchangedSince(seen)).toBe(false);
121
+ });
122
+ });
123
+
124
+ describe('reusedWhileUnchanged', () => {
125
+ it('keeps a loaded value while what it read is unchanged, and loads again after an edit', async () => {
126
+ const {file} = scratch();
127
+ let loads = 0;
128
+ const get = reusedWhileUnchanged(async () => {
129
+ loads += 1;
130
+ return fs.readFileSync(file, 'utf8');
131
+ });
132
+ expect(await get()).toBe('one');
133
+ expect(await get()).toBe('one');
134
+ expect(loads).toBe(1);
135
+ fs.writeFileSync(file, 'two, longer');
136
+ expect(await get()).toBe('two, longer');
137
+ expect(loads).toBe(2);
138
+ expect(await get({fresh: true})).toBe('two, longer');
139
+ expect(loads).toBe(3);
140
+ });
141
+
142
+ it('counts what a kept value read as read by the operation that asks for it', async () => {
143
+ const {file} = scratch();
144
+ const get = reusedWhileUnchanged(async () => fs.readFileSync(file, 'utf8'));
145
+ await get();
146
+ /** @type {Map<string, string>} */
147
+ const seen = new Map();
148
+ await recordReads(seen, () => get());
149
+ expect([...seen.keys()]).toEqual([file]);
150
+ fs.writeFileSync(file, 'two, longer');
151
+ expect(unchangedSince(seen)).toBe(false);
152
+ });
153
+
154
+ it('tries a failed load again', async () => {
155
+ let calls = 0;
156
+ const get = reusedWhileUnchanged(async () => {
157
+ calls += 1;
158
+ if (calls === 1) throw new Error('first try');
159
+ return 'second try';
160
+ });
161
+ await expect(get()).rejects.toThrow('first try');
162
+ expect(await get()).toBe('second try');
163
+ });
77
164
  });
@@ -11,26 +11,40 @@ export function nameWords(text: string): string[];
11
11
  /**
12
12
  * The same items, closest to the typed name first; each item is as close as
13
13
  * its closest name. Equal matches keep their original order.
14
+ *
15
+ * With `closest`, the list also stops where the matches get weaker. Only
16
+ * typed words longer than one character count here. When the best item
17
+ * carries every such word, only the items that carry every one of them stay;
18
+ * when it carries some of them, the items that carry none are left out. When
19
+ * no item carries one, nothing is left out. The list only ever gets shorter,
20
+ * and its order does not change.
14
21
  * @template T
15
22
  * @param {string} typedName
16
23
  * @param {T[]} items
17
24
  * @param {(item: T) => Array<string | undefined>} namesOf
25
+ * @param {{closest?: boolean}} [options]
18
26
  * @returns {T[]}
19
27
  */
20
- export function orderByAffinity<T>(typedName: string, items: T[], namesOf: (item: T) => Array<string | undefined>): T[];
28
+ export function orderByAffinity<T>(typedName: string, items: T[], namesOf: (item: T) => Array<string | undefined>, options?: {
29
+ closest?: boolean;
30
+ }): T[];
21
31
  /**
22
32
  * Docs route suggestions, closest to the typed route first. When every
23
33
  * suggestion sits under one namespace the typed route also starts with, that
24
34
  * shared part is left out of the comparison: it says nothing about which page
25
- * was meant. Equal matches keep their order.
35
+ * was meant. Equal matches keep their order. `closest` stops the list where
36
+ * the matches get weaker, as in {@link orderByAffinity}.
26
37
  * @template {{name: string}} T
27
38
  * @param {string} topic - the typed route
28
39
  * @param {T[]} suggestions
40
+ * @param {{closest?: boolean}} [options]
29
41
  * @returns {T[]}
30
42
  */
31
43
  export function orderRouteSuggestions<T extends {
32
44
  name: string;
33
- }>(topic: string, suggestions: T[]): T[];
45
+ }>(topic: string, suggestions: T[], options?: {
46
+ closest?: boolean;
47
+ }): T[];
34
48
  /**
35
49
  * The components whose synonyms name what was typed. A synonym matches when
36
50
  * its words, with or without a leading library name, are the typed words
@@ -5,13 +5,15 @@
5
5
  *
6
6
  * A failed `component`, `template` or `docs` lookup already knows which
7
7
  * entries to suggest; this module decides their order, so the entry the
8
- * caller most likely meant comes first. It never makes a list longer.
8
+ * caller most likely meant comes first. Asked for the closest entries only,
9
+ * it also cuts a list where the matches get weaker. It never makes a list
10
+ * longer.
9
11
  *
10
12
  * Names are compared as words: `DropdownMenuItem`, `dropdown-menu-item` and
11
13
  * `Dropdown Menu Items` all read as `dropdown menu item`.
12
14
  *
13
15
  * @input the name the caller typed and the candidate entries
14
- * @output the entries, reordered
16
+ * @output the entries, reordered, and cut when asked
15
17
  * @position lib: shared by the component, template and docs lookup errors
16
18
  */
17
19
 
@@ -79,15 +81,15 @@ function affinityOf(typed, name) {
79
81
  }
80
82
 
81
83
  /**
82
- * The same items, closest to the typed name first; each item is as close as
83
- * its closest name. Equal matches keep their original order.
84
+ * The items scored against the typed name, closest first; equal matches keep
85
+ * their original order.
84
86
  * @template T
85
87
  * @param {string} typedName
86
88
  * @param {T[]} items
87
89
  * @param {(item: T) => Array<string | undefined>} namesOf
88
- * @returns {T[]}
90
+ * @returns {Array<{item: T, best: number}>}
89
91
  */
90
- export function orderByAffinity(typedName, items, namesOf) {
92
+ function scoreByAffinity(typedName, items, namesOf) {
91
93
  const typed = nameWords(typedName);
92
94
  const scored = items.map((item, index) => {
93
95
  let best = 0;
@@ -97,30 +99,73 @@ export function orderByAffinity(typedName, items, namesOf) {
97
99
  return {item, index, best};
98
100
  });
99
101
  scored.sort((a, b) => b.best - a.best || a.index - b.index);
100
- return scored.map(s => s.item);
102
+ return scored;
103
+ }
104
+
105
+ /**
106
+ * The same items, closest to the typed name first; each item is as close as
107
+ * its closest name. Equal matches keep their original order.
108
+ *
109
+ * With `closest`, the list also stops where the matches get weaker. Only
110
+ * typed words longer than one character count here. When the best item
111
+ * carries every such word, only the items that carry every one of them stay;
112
+ * when it carries some of them, the items that carry none are left out. When
113
+ * no item carries one, nothing is left out. The list only ever gets shorter,
114
+ * and its order does not change.
115
+ * @template T
116
+ * @param {string} typedName
117
+ * @param {T[]} items
118
+ * @param {(item: T) => Array<string | undefined>} namesOf
119
+ * @param {{closest?: boolean}} [options]
120
+ * @returns {T[]}
121
+ */
122
+ export function orderByAffinity(typedName, items, namesOf, options = {}) {
123
+ const scored = scoreByAffinity(typedName, items, namesOf);
124
+ if (!options.closest) return scored.map(s => s.item);
125
+ // One-letter words (`a` in `a11y`, `use-a-theme`) say nothing about which
126
+ // entry was meant, so the cut counts only the longer typed words.
127
+ const words = nameWords(typedName).filter(w => w.length > 1);
128
+ const tierOf = (/** @type {T} */ item) => {
129
+ let best = 0;
130
+ for (const name of namesOf(item)) {
131
+ if (name) best = Math.max(best, affinityOf(words, name));
132
+ }
133
+ // Tiers: 1 some typed word, 2 every typed word, 4 the same words.
134
+ return Math.floor(best / 10);
135
+ };
136
+ const tiers = scored.map(s => tierOf(s.item));
137
+ const top = Math.max(0, ...tiers);
138
+ if (top === 0) return scored.map(s => s.item);
139
+ const need = Math.min(top, 2);
140
+ return scored.filter((_, i) => tiers[i] >= need).map(s => s.item);
101
141
  }
102
142
 
103
143
  /**
104
144
  * Docs route suggestions, closest to the typed route first. When every
105
145
  * suggestion sits under one namespace the typed route also starts with, that
106
146
  * shared part is left out of the comparison: it says nothing about which page
107
- * was meant. Equal matches keep their order.
147
+ * was meant. Equal matches keep their order. `closest` stops the list where
148
+ * the matches get weaker, as in {@link orderByAffinity}.
108
149
  * @template {{name: string}} T
109
150
  * @param {string} topic - the typed route
110
151
  * @param {T[]} suggestions
152
+ * @param {{closest?: boolean}} [options]
111
153
  * @returns {T[]}
112
154
  */
113
- export function orderRouteSuggestions(topic, suggestions) {
155
+ export function orderRouteSuggestions(topic, suggestions, options = {}) {
114
156
  let shared = suggestions.length > 0 ? suggestions[0].name : '';
115
157
  for (const {name} of suggestions) {
116
158
  while (shared && !name.startsWith(shared)) shared = shared.slice(0, -1);
117
159
  }
118
160
  const namespace = shared.slice(0, shared.lastIndexOf('/') + 1);
119
161
  return namespace && topic.startsWith(namespace)
120
- ? orderByAffinity(topic.slice(namespace.length), suggestions, s => [
121
- s.name.slice(namespace.length),
122
- ])
123
- : orderByAffinity(topic, suggestions, s => [s.name]);
162
+ ? orderByAffinity(
163
+ topic.slice(namespace.length),
164
+ suggestions,
165
+ s => [s.name.slice(namespace.length)],
166
+ options,
167
+ )
168
+ : orderByAffinity(topic, suggestions, s => [s.name], options);
124
169
  }
125
170
 
126
171
  /** Library names a synonym may start with (`MUI TextField`). */
@@ -86,6 +86,50 @@ describe('orderByAffinity', () => {
86
86
  });
87
87
  });
88
88
 
89
+ describe('orderByAffinity with closest', () => {
90
+ const closest = (/** @type {string[]} */ list, /** @type {string} */ typed) =>
91
+ orderByAffinity(typed, list, n => [n], {closest: true});
92
+
93
+ it('keeps the items with every typed word after the same words, and drops the weaker ones', () => {
94
+ expect(
95
+ closest(
96
+ [
97
+ 'zeta-panel',
98
+ 'other',
99
+ 'wide-panel-grid',
100
+ 'panel-grid',
101
+ 'grid-panel-x',
102
+ ],
103
+ 'PanelGrid',
104
+ ),
105
+ ).toEqual(['panel-grid', 'wide-panel-grid', 'grid-panel-x']);
106
+ });
107
+
108
+ it('keeps every item with a typed word when the best has only some of them', () => {
109
+ expect(closest(['table', 'card-grid', 'list-view'], 'card list')).toEqual([
110
+ 'card-grid',
111
+ 'list-view',
112
+ ]);
113
+ });
114
+
115
+ it('does not count one-letter words', () => {
116
+ const list = ['use-a-theme', 'author-a-theme', 'card', 'table'];
117
+ expect(closest(list, 'a11y')).toEqual(list);
118
+ expect(closest(list, 'make-a-card')).toEqual(['card']);
119
+ });
120
+
121
+ it('keeps the whole list, in its order, when no item has a typed word', () => {
122
+ expect(closest(['c', 'b', 'a'], 'thing')).toEqual(['c', 'b', 'a']);
123
+ });
124
+
125
+ it('only ever shortens the list', () => {
126
+ const list = ['alpha-beta', 'beta', 'gamma', 'alpha'];
127
+ const out = closest(list, 'alpha beta');
128
+ expect(out.every(n => list.includes(n))).toBe(true);
129
+ expect(out.length).toBeLessThanOrEqual(list.length);
130
+ });
131
+ });
132
+
89
133
  describe('rankComponentSuggestions', () => {
90
134
  const all = [
91
135
  'Zebra',
@@ -250,6 +294,15 @@ describe('orderRouteSuggestions', () => {
250
294
  );
251
295
  });
252
296
 
297
+ it('with closest, keeps only the child the route names', () => {
298
+ expect(
299
+ names(orderRouteSuggestions('guide/ship-it', kids, {closest: true})),
300
+ ).toEqual(['guide/ship']);
301
+ expect(
302
+ names(orderRouteSuggestions('guide/theme', kids, {closest: true})),
303
+ ).toEqual(names(kids));
304
+ });
305
+
253
306
  it('compares whole routes when the suggestions share no namespace', () => {
254
307
  const roots = [{name: 'cli'}, {name: 'guide'}, {name: 'theme'}];
255
308
  expect(names(orderRouteSuggestions('theme/quick-start', roots))[0]).toBe(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.7.5-canary.ae842c8",
3
+ "version": "0.7.5-canary.bc40b80",
4
4
  "displayName": "CLI",
5
5
  "description": "Scaffold projects, browse templates, generate themes, and get agent-ready docs from the command line.",
6
6
  "author": "Meta Open Source",
@@ -111,10 +111,10 @@
111
111
  "zod": "^4.4.3"
112
112
  },
113
113
  "peerDependencies": {
114
- "@astryxdesign/charts": "0.7.5-canary.ae842c8",
115
- "@astryxdesign/core": "0.7.5-canary.ae842c8",
116
- "@astryxdesign/lab": "0.7.5-canary.ae842c8",
117
- "@astryxdesign/theme-neutral": "0.7.5-canary.ae842c8"
114
+ "@astryxdesign/charts": "0.7.5-canary.bc40b80",
115
+ "@astryxdesign/core": "0.7.5-canary.bc40b80",
116
+ "@astryxdesign/lab": "0.7.5-canary.bc40b80",
117
+ "@astryxdesign/theme-neutral": "0.7.5-canary.bc40b80"
118
118
  },
119
119
  "peerDependenciesMeta": {
120
120
  "@astryxdesign/charts": {
@@ -131,10 +131,10 @@
131
131
  }
132
132
  },
133
133
  "devDependencies": {
134
- "@astryxdesign/charts": "0.7.5-canary.ae842c8",
135
- "@astryxdesign/core": "0.7.5-canary.ae842c8",
136
- "@astryxdesign/lab": "0.7.5-canary.ae842c8",
137
- "@astryxdesign/theme-neutral": "0.7.5-canary.ae842c8",
134
+ "@astryxdesign/charts": "0.7.5-canary.bc40b80",
135
+ "@astryxdesign/core": "0.7.5-canary.bc40b80",
136
+ "@astryxdesign/lab": "0.7.5-canary.bc40b80",
137
+ "@astryxdesign/theme-neutral": "0.7.5-canary.bc40b80",
138
138
  "@heroicons/react": "^2.2.0",
139
139
  "@stylexjs/stylex": "^0.19.0",
140
140
  "@types/babel__core": "^7.20.5",