@astryxdesign/cli 0.7.3-canary.641d08e → 0.7.3-canary.6856cfa

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 (95) hide show
  1. package/README.md +63 -63
  2. package/api/build/_adapter.mjs +37 -25
  3. package/api/build/blocks/blocks.d.mts +68 -18
  4. package/api/build/blocks/blocks.mjs +475 -116
  5. package/api/build/blocks/blocks.test.mjs +191 -61
  6. package/api/build/blocks/blocks.weights.json +1 -1
  7. package/api/build/build.type.mjs +1 -1
  8. package/api/build/kit/answer.d.mts +9 -5
  9. package/api/build/kit/answer.mjs +123 -13
  10. package/api/build/kit/answer.test.mjs +73 -3
  11. package/api/build/kit/signals.d.mts +19 -0
  12. package/api/build/kit/signals.mjs +18 -7
  13. package/api/build/tree.mjs +2 -1
  14. package/api/build/tree.test.mjs +36 -28
  15. package/api/component/_adapter.mjs +39 -5
  16. package/api/component/component-replacement.test.mjs +1 -0
  17. package/api/component/component.mjs +1 -1
  18. package/api/discover/_adapter.d.mts +1 -2
  19. package/api/discover/_adapter.mjs +6 -8
  20. package/api/discover/discover.mjs +0 -1
  21. package/api/docs/_adapter.mjs +4 -0
  22. package/api/doctor/_adapter.d.mts +24 -10
  23. package/api/doctor/_adapter.mjs +28 -25
  24. package/api/doctor/doctor.d.mts +7 -4
  25. package/api/doctor/doctor.mjs +52 -14
  26. package/api/doctor/doctor.test.mjs +58 -0
  27. package/api/hook/hook.mjs +1 -1
  28. package/api/integration/validate-integration-fixes.test.mjs +6 -5
  29. package/api/integration/validate-integration-gaps.test.mjs +12 -1
  30. package/api/integration/validate-integration.d.mts +4 -0
  31. package/api/integration/validate-integration.mjs +48 -7
  32. package/api/integration/validate-integration.type.d.mts +36 -5
  33. package/api/integration/validate-integration.type.mjs +27 -6
  34. package/api/integration/validateIntegration.doc.mjs +1 -1
  35. package/api/search/_adapter.d.mts +16 -0
  36. package/api/search/_adapter.mjs +39 -0
  37. package/api/search/_adapter.test.mjs +173 -0
  38. package/api/search/_entries.d.mts +11 -0
  39. package/api/search/_entries.mjs +35 -17
  40. package/api/search/_entries.test.mjs +48 -0
  41. package/api/search/search.mjs +6 -2
  42. package/api/template/template.mjs +5 -1
  43. package/assets/docs/tree/checks.doc.mjs +1 -1
  44. package/assets/docs/tree/versioning.doc.mjs +4 -0
  45. package/assets/docs/use-integrations.doc.mjs +120 -0
  46. package/clients/cli/command-result-coverage.test.mjs +6 -5
  47. package/clients/cli/commands/build-theme.color-scheme.test.mjs +1 -1
  48. package/clients/cli/commands/{component/index.mjs → component.mjs} +37 -37
  49. package/clients/cli/commands/component.test.mjs +6 -6
  50. package/clients/cli/commands/doctor-integration.test.mjs +49 -1
  51. package/clients/cli/commands/doctor.mjs +10 -0
  52. package/clients/cli/commands/{hook/index.mjs → hook.mjs} +22 -22
  53. package/clients/cli/commands/import-hint-correctness.test.mjs +1 -1
  54. package/clients/cli/commands/manifest.doc.mjs +1 -1
  55. package/clients/cli/commands/manifest.mjs +67 -0
  56. package/clients/cli/commands/postinstall.doc.mjs +23 -0
  57. package/clients/cli/commands/postinstall.mjs +31 -0
  58. package/clients/cli/commands/setup-nudge.test.mjs +17 -0
  59. package/clients/cli/commands/{build-theme.mjs → theme.mjs} +1 -1
  60. package/clients/cli/index.mjs +35 -93
  61. package/clients/cli/lib/component-format.mjs +1 -1
  62. package/clients/cli/lib/define-command.mjs +12 -7
  63. package/clients/cli/lib/exit-codes.test.mjs +5 -0
  64. package/clients/cli/lib/manifest.test.mjs +12 -0
  65. package/clients/cli/lib/welcome-box.mjs +50 -0
  66. package/foundation/agent-docs/agent-doc-state.d.mts +12 -0
  67. package/foundation/agent-docs/agent-doc-state.mjs +24 -2
  68. package/foundation/agent-docs/agent-docs.mjs +5 -5
  69. package/foundation/agent-docs/computer-agent-text.mjs +16 -1
  70. package/foundation/agent-docs/computer-agent-text.test.mjs +23 -2
  71. package/foundation/discovery/runner-commands.mjs +1 -0
  72. package/foundation/doc-compiler/doc-loads.test.mjs +21 -9
  73. package/foundation/fs/read-record.d.mts +18 -0
  74. package/foundation/fs/read-record.mjs +131 -0
  75. package/foundation/fs/read-record.test.mjs +77 -0
  76. package/foundation/integrations/cli-peer-version.d.mts +36 -0
  77. package/foundation/integrations/cli-peer-version.mjs +132 -0
  78. package/foundation/integrations/cli-peer-version.test.mjs +354 -0
  79. package/foundation/integrations/exports-subpaths.d.mts +57 -0
  80. package/foundation/integrations/exports-subpaths.mjs +113 -0
  81. package/foundation/integrations/public-imports.d.mts +118 -0
  82. package/foundation/integrations/public-imports.mjs +1769 -0
  83. package/foundation/integrations/public-imports.test.mjs +1793 -0
  84. package/foundation/release/global-state.d.mts +8 -4
  85. package/foundation/release/global-state.mjs +4 -2
  86. package/foundation/release/notices.d.mts +62 -8
  87. package/foundation/release/notices.mjs +136 -25
  88. package/foundation/release/notices.test.mjs +21 -0
  89. package/foundation/response/response-types.doc.mjs +1 -1
  90. package/foundation/text/string-utils.d.mts +2 -1
  91. package/foundation/text/string-utils.mjs +16 -5
  92. package/foundation/text/suggest-order.d.mts +72 -0
  93. package/foundation/text/suggest-order.mjs +363 -0
  94. package/foundation/text/suggest-order.test.mjs +259 -0
  95. package/package.json +9 -9
@@ -37,7 +37,9 @@ export type ValidateIntegrationResponse = {
37
37
  type: "integration.validate";
38
38
  /**
39
39
  * `notes`: information beside the issues that fails nothing, such as
40
- * `invalid_cli_command`, a `cliCommand` that was ignored as malformed, and
40
+ * `invalid_cli_command`, a `cliCommand` that was ignored as malformed;
41
+ * `cli_peer_version`, the running CLI outside the package's
42
+ * `@astryxdesign/cli` peer range; and
41
43
  * the package layout findings added after the last minor release, each with
42
44
  * its fix in the message: two docs for one component
43
45
  * (`duplicate_component_doc`), a root reached through a symlink
@@ -45,10 +47,11 @@ export type ValidateIntegrationResponse = {
45
47
  * (`unreadable_file`), a package.json without `name` or `version`
46
48
  * (`invalid_package_json`), no provider ID (`no_provider_id`), and a doc
47
49
  * whose file name differs from its source only in letter case where the two
48
- * still pair (`source_without_component_doc`); and `doc_name_mismatch` and
49
- * `unknown_block_component` (see `docNames` and `blockComponents`); they
50
- * become warnings in the next minor release; and `runner_command`, an
51
- * Astryx command a topic writes with a package runner
50
+ * still pair (`source_without_component_doc`); `doc_name_mismatch` and
51
+ * `unknown_block_component` (see `docNames` and `blockComponents`); and
52
+ * since 0.7.3 each public-import finding; they become warnings in the next
53
+ * minor release; and `runner_command`, an Astryx command a topic writes
54
+ * with a package runner
52
55
  */
53
56
  data: {
54
57
  validated: boolean;
@@ -62,6 +65,7 @@ export type ValidateIntegrationResponse = {
62
65
  docTypes?: DocTypesReport;
63
66
  docNames?: DocNamesReport;
64
67
  blockComponents?: BlockComponentsReport;
68
+ publicImports?: PublicImportsReport;
65
69
  };
66
70
  };
67
71
  /**
@@ -115,3 +119,30 @@ export type BlockComponentsReport = {
115
119
  reason: string;
116
120
  }>;
117
121
  };
122
+ /**
123
+ * An import the public-import check could not judge.
124
+ */
125
+ export type PublicImportUnchecked = {
126
+ /**
127
+ * package-relative file that names it
128
+ */
129
+ file: string;
130
+ /**
131
+ * the import specifier
132
+ */
133
+ specifier: string;
134
+ /**
135
+ * why it was not checked
136
+ */
137
+ reason: string;
138
+ };
139
+ /**
140
+ * The public-import check's report on validate's result: `unchecked` lists
141
+ * what it could not judge, never counted or failed on. Its findings are
142
+ * notes on the result (`data.notes`), so `findings` stays empty.
143
+ */
144
+ export type PublicImportsReport = {
145
+ status: "checked";
146
+ findings: never[];
147
+ unchecked: PublicImportUnchecked[];
148
+ };
@@ -39,9 +39,11 @@
39
39
  * "healthy" — the two are otherwise byte-identical.
40
40
  * @typedef {object} ValidateIntegrationResponse
41
41
  * @property {'integration.validate'} type
42
- * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string}>, docTypes?: DocTypesReport, docNames?: DocNamesReport, blockComponents?: BlockComponentsReport}} data
42
+ * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string}>, docTypes?: DocTypesReport, docNames?: DocNamesReport, blockComponents?: BlockComponentsReport, publicImports?: PublicImportsReport}} data
43
43
  * `notes`: information beside the issues that fails nothing, such as
44
- * `invalid_cli_command`, a `cliCommand` that was ignored as malformed, and
44
+ * `invalid_cli_command`, a `cliCommand` that was ignored as malformed;
45
+ * `cli_peer_version`, the running CLI outside the package's
46
+ * `@astryxdesign/cli` peer range; and
45
47
  * the package layout findings added after the last minor release, each with
46
48
  * its fix in the message: two docs for one component
47
49
  * (`duplicate_component_doc`), a root reached through a symlink
@@ -49,10 +51,11 @@
49
51
  * (`unreadable_file`), a package.json without `name` or `version`
50
52
  * (`invalid_package_json`), no provider ID (`no_provider_id`), and a doc
51
53
  * whose file name differs from its source only in letter case where the two
52
- * still pair (`source_without_component_doc`); and `doc_name_mismatch` and
53
- * `unknown_block_component` (see `docNames` and `blockComponents`); they
54
- * become warnings in the next minor release; and `runner_command`, an
55
- * Astryx command a topic writes with a package runner
54
+ * still pair (`source_without_component_doc`); `doc_name_mismatch` and
55
+ * `unknown_block_component` (see `docNames` and `blockComponents`); and
56
+ * since 0.7.3 each public-import finding; they become warnings in the next
57
+ * minor release; and `runner_command`, an Astryx command a topic writes
58
+ * with a package runner
56
59
  */
57
60
 
58
61
  /**
@@ -99,3 +102,21 @@
99
102
  */
100
103
 
101
104
  export {};
105
+
106
+ /**
107
+ * An import the public-import check could not judge.
108
+ * @typedef {object} PublicImportUnchecked
109
+ * @property {string} file package-relative file that names it
110
+ * @property {string} specifier the import specifier
111
+ * @property {string} reason why it was not checked
112
+ */
113
+
114
+ /**
115
+ * The public-import check's report on validate's result: `unchecked` lists
116
+ * what it could not judge, never counted or failed on. Its findings are
117
+ * notes on the result (`data.notes`), so `findings` stays empty.
118
+ * @typedef {object} PublicImportsReport
119
+ * @property {'checked'} status
120
+ * @property {never[]} findings
121
+ * @property {PublicImportUnchecked[]} unchecked
122
+ */
@@ -62,7 +62,7 @@ export const doc = {
62
62
  {
63
63
  type: 'integration.validate',
64
64
  description:
65
- 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. A `runner_command` note lists each Astryx command a topic writes with a package runner, with its file, line and the bare command to write. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed).',
65
+ "The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means \"not looked at\", not \"healthy\"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed and `cli_peer_version` when the running CLI is outside the `@astryxdesign/cli` peer range of the package, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. A `runner_command` note lists each Astryx command a topic writes with a package runner, with its file, line and the bare command to write. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed). Since 0.7.3 each import apps cannot use is a note in `data.notes`, its fix inside the message, listed only: it does not fail this command or `integration check --strict`, and fails `--strict` from the next minor release. The codes are `component_import_not_exported`, `component_import_other_package`, `component_import_missing_name`, `example_import_not_exported`, `example_import_missing_name`, `template_import_not_exported`, `template_import_outside_root`, `template_private_import`, `template_import_missing_name` and `template_no_default_export`. When the manifest loads, `data.publicImports` is `{status: 'checked', findings: [], unchecked}`: `unchecked` lists each import the check could not judge, as {file, specifier, reason}, the reason starting `example <label>:` for an import in a component example: an `exports` target not built yet; a module whose export list cannot be read in full (CommonJS, or a declaration file it cannot read); a root import in a package with no `exports` (the root module `main` names is not read); every name an import (other than a component doc's own component) names that its module does not export, while a TypeScript file in the package has a `declare module` block for a relative path or the package's own name or a subpath of it, which can add names to that module (a `declare module` in a comment, `declare global`, a wildcard such as `'*.css'`, and another package's name do not count; a file whose text has `declare module` but that cannot be parsed counts); the same for every such name when the package has more than 5,000 files to search for that block; a deep path into build output not built yet in a package with no `exports`; a template import of Core when `@astryxdesign/core` is not installed beside the package (a `packages/core` of the workspace under another name does not count); every import of the package's own name when package.json has no `name` or a `name` that is not a bare package name; one entry for the whole check when package.json cannot be read; and an import of a subpath whose `exports` entry has only a `types` target, unless it is `import type`, every binding is an inline `type`, or every name it imports is a type its types file declares: a value import of a name that file does not declare as a type, a namespace or side-effect import, or any import when the types file cannot be read (it may be build output). `integration check` counts the unchecked as not compared; they never fail it.",
66
66
  },
67
67
  ],
68
68
  examples: [
@@ -26,6 +26,21 @@ export function gatherCandidates(options: {
26
26
  outside: boolean;
27
27
  coreSkipped: string | null;
28
28
  }>;
29
+ /**
30
+ * gatherCandidates, reused within one process: a later search in the same
31
+ * folder, for the same `type`, ranks the candidates an earlier search
32
+ * gathered when none of the files that gather read, and none of the folders
33
+ * it listed or probed, changed since (each is checked by its change time and
34
+ * size, so an edited doc in a linked package is seen on the next call). A
35
+ * long-running caller (a docs site's search, an agent harness) then pays the
36
+ * gather once. A one-shot `astryx search` gathers once, as before.
37
+ * @param {{cwd?: string, type?: string}} options
38
+ * @returns {Promise<Gathered>}
39
+ */
40
+ export function gatherCandidatesReused(options: {
41
+ cwd?: string;
42
+ type?: string;
43
+ }): Promise<Gathered>;
29
44
  /**
30
45
  * The search tree's static data, read once: the entry cards and each node's
31
46
  * weights file.
@@ -38,6 +53,7 @@ export function gatherCandidates(options: {
38
53
  export function loadSearchData(): SearchData;
39
54
  export { componentKeywords } from "./_gather-components.mjs";
40
55
  export type Candidate = import("./_lexical.mjs").Candidate;
56
+ export type Gathered = Awaited<ReturnType<typeof gatherCandidates>>;
41
57
  export type SearcherWeights = {
42
58
  w: number[];
43
59
  mu: number[];
@@ -7,7 +7,9 @@
7
7
  */
8
8
 
9
9
  import {readFileSync} from 'node:fs';
10
+ import * as path from 'node:path';
10
11
  import {requireCoreDir} from '../../foundation/fs/paths.mjs';
12
+ import {recordReads, unchangedSince} from '../../foundation/fs/read-record.mjs';
11
13
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
12
14
  import {coreDirOrThrow} from '../error.mjs';
13
15
  import {CORELESS_DOMAINS} from './_query.mjs';
@@ -91,6 +93,43 @@ export async function gatherCandidates(options) {
91
93
  };
92
94
  }
93
95
 
96
+ /**
97
+ * @typedef {Awaited<ReturnType<typeof gatherCandidates>>} Gathered
98
+ * @type {Map<string, {reads: Map<string, string>, value: Promise<Gathered>}>}
99
+ */
100
+ const gathered = new Map();
101
+
102
+ /**
103
+ * gatherCandidates, reused within one process: a later search in the same
104
+ * folder, for the same `type`, ranks the candidates an earlier search
105
+ * gathered when none of the files that gather read, and none of the folders
106
+ * it listed or probed, changed since (each is checked by its change time and
107
+ * size, so an edited doc in a linked package is seen on the next call). A
108
+ * long-running caller (a docs site's search, an agent harness) then pays the
109
+ * gather once. A one-shot `astryx search` gathers once, as before.
110
+ * @param {{cwd?: string, type?: string}} options
111
+ * @returns {Promise<Gathered>}
112
+ */
113
+ export async function gatherCandidatesReused(options) {
114
+ const cwd = path.resolve(options.cwd ?? process.cwd());
115
+ const key = `${cwd}\0${options.type ?? ''}`;
116
+ const hit = gathered.get(key);
117
+ if (hit && unchangedSince(hit.reads)) return hit.value;
118
+ /** @type {Map<string, string>} */
119
+ const seen = new Map();
120
+ const value = recordReads(seen, () => gatherCandidates({...options, cwd}));
121
+ try {
122
+ await value;
123
+ } catch (error) {
124
+ if (gathered.get(key)?.value === value) gathered.delete(key);
125
+ throw error;
126
+ }
127
+ // Each path's state was taken as it was first read, so an edit made while
128
+ // the gather ran shows as a change on the next call.
129
+ gathered.set(key, {reads: seen, value});
130
+ return value;
131
+ }
132
+
94
133
  /**
95
134
  * @typedef {{w: number[], mu: number[], sd: number[]}} SearcherWeights
96
135
  * @typedef {object} SearchData
@@ -0,0 +1,173 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Tests for search's adapter: a long-running caller reuses the gathered
5
+ * candidates while their inputs are unchanged (gatherCandidatesReused), and
6
+ * gathers again when an input changes or for another folder or `type`.
7
+ *
8
+ * Whether inputs changed is read-record's answer (tested in
9
+ * read-record.test.mjs). Other tests running at the same time change shared
10
+ * folders a gather reads (the temp folder, the repository root), so here the
11
+ * reuse case holds that answer at "unchanged", and every other case only
12
+ * checks that a change forces a new gather, which concurrent changes cannot
13
+ * undo.
14
+ */
15
+
16
+ import {describe, it, expect, vi} from 'vitest';
17
+ import * as fs from 'node:fs';
18
+ import * as os from 'node:os';
19
+ import * as path from 'node:path';
20
+ import * as readRecord from '../../foundation/fs/read-record.mjs';
21
+ import {gatherCandidates, gatherCandidatesReused} from './_adapter.mjs';
22
+
23
+ vi.mock('../../foundation/fs/read-record.mjs', async original => {
24
+ const real = /** @type {typeof readRecord} */ (await original());
25
+ return {...real, unchangedSince: vi.fn(real.unchangedSince)};
26
+ });
27
+ const unchangedSince = vi.mocked(readRecord.unchangedSince);
28
+
29
+ const SLOW = 60_000;
30
+
31
+ /** A folder with only a package.json: a docs search there reads the CLI's docs. */
32
+ function scratchProject() {
33
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-gather-reuse-'));
34
+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}');
35
+ return dir;
36
+ }
37
+
38
+ describe('gatherCandidatesReused', () => {
39
+ it(
40
+ 'reuses the gathered candidates while the inputs are unchanged',
41
+ async () => {
42
+ const cwd = scratchProject();
43
+ const first = await gatherCandidatesReused({cwd, type: 'doc'});
44
+ unchangedSince.mockReturnValueOnce(true);
45
+ expect(await gatherCandidatesReused({cwd, type: 'doc'})).toBe(first);
46
+ expect(first.all.length).toBeGreaterThan(0);
47
+ // The same candidates a fresh gather finds.
48
+ expect(JSON.parse(JSON.stringify(first))).toEqual(
49
+ JSON.parse(JSON.stringify(await gatherCandidates({cwd, type: 'doc'}))),
50
+ );
51
+ },
52
+ SLOW,
53
+ );
54
+
55
+ it(
56
+ 'gathers again when an input file changes',
57
+ async () => {
58
+ const cwd = scratchProject();
59
+ const first = await gatherCandidatesReused({cwd, type: 'doc'});
60
+ const later = new Date(Date.now() + 5_000);
61
+ fs.utimesSync(path.join(cwd, 'package.json'), later, later);
62
+ expect(await gatherCandidatesReused({cwd, type: 'doc'})).not.toBe(first);
63
+ fs.writeFileSync(
64
+ path.join(cwd, 'astryx.config.mjs'),
65
+ 'export default {};\n',
66
+ );
67
+ expect(await gatherCandidatesReused({cwd, type: 'doc'})).not.toBe(first);
68
+ },
69
+ SLOW,
70
+ );
71
+
72
+ it(
73
+ 'keeps one entry per folder and type',
74
+ async () => {
75
+ const cwd = scratchProject();
76
+ const docs = await gatherCandidatesReused({cwd, type: 'doc'});
77
+ const themes = await gatherCandidatesReused({cwd, type: 'theme'});
78
+ expect(themes).not.toBe(docs);
79
+ expect(themes.all.every(c => c.domain === 'theme')).toBe(true);
80
+ expect(
81
+ await gatherCandidatesReused({cwd: scratchProject(), type: 'doc'}),
82
+ ).not.toBe(docs);
83
+ },
84
+ SLOW,
85
+ );
86
+
87
+ it(
88
+ 'gathers again when a file the gather read changes, in a linked package too',
89
+ async () => {
90
+ // A consumer whose integration is a symlink to a package folder
91
+ // elsewhere, as a workspace package is.
92
+ const dir = fs.mkdtempSync(
93
+ path.join(process.cwd(), '.astryx-gather-reuse-'),
94
+ );
95
+ const pkg = fs.mkdtempSync(
96
+ path.join(os.tmpdir(), 'astryx-linked-widgets-'),
97
+ );
98
+ try {
99
+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"consumer"}');
100
+ fs.writeFileSync(
101
+ path.join(dir, 'astryx.config.mjs'),
102
+ "export default { integrations: ['@acme/widgets'] };\n",
103
+ );
104
+ fs.mkdirSync(
105
+ path.join(dir, 'node_modules', '@astryxdesign', 'core', 'src'),
106
+ {
107
+ recursive: true,
108
+ },
109
+ );
110
+ fs.mkdirSync(path.join(pkg, 'components'));
111
+ fs.writeFileSync(
112
+ path.join(pkg, 'package.json'),
113
+ '{"name":"@acme/widgets","version":"1.0.0"}',
114
+ );
115
+ fs.writeFileSync(
116
+ path.join(pkg, 'astryx.integration.mjs'),
117
+ "export default { components: './components' };\n",
118
+ );
119
+ fs.writeFileSync(
120
+ path.join(pkg, 'components', 'FancyGizmo.doc.mjs'),
121
+ `export default {
122
+ type: 'component',
123
+ name: 'FancyGizmo',
124
+ keywords: ['gizmo'],
125
+ usage: {description: 'A fancy part.'},
126
+ props: [],
127
+ };\n`,
128
+ );
129
+ fs.writeFileSync(
130
+ path.join(pkg, 'components', 'FancyGizmo.tsx'),
131
+ 'export function FancyGizmo() { return null; }\n',
132
+ );
133
+ fs.mkdirSync(path.join(dir, 'node_modules', '@acme'));
134
+ fs.symlinkSync(
135
+ pkg,
136
+ path.join(dir, 'node_modules', '@acme', 'widgets'),
137
+ 'dir',
138
+ );
139
+ const options = {cwd: dir, type: 'component'};
140
+ const first = await gatherCandidatesReused(options);
141
+ expect(first.all.map(c => c.name)).toContain('FancyGizmo');
142
+
143
+ // A new component in the linked package: its folder changed.
144
+ fs.writeFileSync(
145
+ path.join(pkg, 'components', 'TinySprocket.doc.mjs'),
146
+ `export default {
147
+ type: 'component',
148
+ name: 'TinySprocket',
149
+ keywords: ['sprocket'],
150
+ usage: {description: 'A small part.'},
151
+ props: [],
152
+ };\n`,
153
+ );
154
+ fs.writeFileSync(
155
+ path.join(pkg, 'components', 'TinySprocket.tsx'),
156
+ 'export function TinySprocket() { return null; }\n',
157
+ );
158
+ const second = await gatherCandidatesReused(options);
159
+ expect(second).not.toBe(first);
160
+ expect(second.all.map(c => c.name)).toContain('TinySprocket');
161
+
162
+ // An edited file the gather read: the linked package's manifest.
163
+ const later = new Date(Date.now() + 5_000);
164
+ fs.utimesSync(path.join(pkg, 'package.json'), later, later);
165
+ expect(await gatherCandidatesReused(options)).not.toBe(second);
166
+ } finally {
167
+ fs.rmSync(dir, {recursive: true, force: true});
168
+ fs.rmSync(pkg, {recursive: true, force: true});
169
+ }
170
+ },
171
+ SLOW,
172
+ );
173
+ });
@@ -13,6 +13,16 @@ export function entryTable(all: any[], cards: Record<string, {
13
13
  synonyms?: string[];
14
14
  props?: string[];
15
15
  }>): EntryTable;
16
+ /**
17
+ * @param {any[]} all
18
+ * @param {Record<string, {what?: string, synonyms?: string[], props?: string[]}>} cards
19
+ * @returns {EntryTable}
20
+ */
21
+ export function buildTable(all: any[], cards: Record<string, {
22
+ what?: string;
23
+ synonyms?: string[];
24
+ props?: string[];
25
+ }>): EntryTable;
16
26
  export function entryOf(table: {
17
27
  index: Map<string, number>;
18
28
  }, res: {
@@ -22,6 +32,7 @@ export function entryOf(table: {
22
32
  section?: string;
23
33
  }): number | undefined;
24
34
  export function entryId(c: any): string;
35
+ export const HASHED_FIELDS: readonly string[];
25
36
  export type EntryTable = {
26
37
  /**
27
38
  * every returnable `<domain>:<name>`, in code-point order
@@ -77,6 +77,29 @@ let last = null;
77
77
  const cardIds = new WeakMap();
78
78
  let nextCardId = 0;
79
79
 
80
+ /**
81
+ * The candidate fields buildTable reads, all of them hashed by fingerprint;
82
+ * `_entries.test.mjs` fails if buildTable starts reading another.
83
+ */
84
+ /** How many guidance lines and prose paragraphs of a candidate the index reads. */
85
+ const GUIDANCE_LINES = 10;
86
+ const PROSE_PARAGRAPHS = 4;
87
+
88
+ export const HASHED_FIELDS = Object.freeze([
89
+ 'domain',
90
+ 'name',
91
+ '_topic',
92
+ '_section',
93
+ '_resultName',
94
+ '_package',
95
+ 'description',
96
+ 'keywords',
97
+ 'aliases',
98
+ 'titles',
99
+ 'guidance',
100
+ 'prose',
101
+ ]);
102
+
80
103
  /**
81
104
  * Everything the table reads from the catalog, hashed.
82
105
  * @param {any[]} all
@@ -89,20 +112,15 @@ function fingerprint(all, cards) {
89
112
  h.update(String(cardIds.get(cards)));
90
113
  for (const c of all) {
91
114
  h.update(
92
- JSON.stringify([
93
- c.domain,
94
- c.name,
95
- c._topic,
96
- c._section,
97
- c._resultName,
98
- c._package,
99
- c.description,
100
- c.keywords,
101
- c.aliases,
102
- c.titles,
103
- (c.guidance ?? []).slice(0, 10),
104
- (c.prose ?? []).slice(0, 4),
105
- ]),
115
+ JSON.stringify(
116
+ HASHED_FIELDS.map(f =>
117
+ f === 'guidance'
118
+ ? (c.guidance ?? []).slice(0, GUIDANCE_LINES)
119
+ : f === 'prose'
120
+ ? (c.prose ?? []).slice(0, PROSE_PARAGRAPHS)
121
+ : c[f],
122
+ ),
123
+ ),
106
124
  );
107
125
  }
108
126
  return h.digest('hex');
@@ -113,7 +131,7 @@ function fingerprint(all, cards) {
113
131
  * @param {Record<string, {what?: string, synonyms?: string[], props?: string[]}>} cards
114
132
  * @returns {EntryTable}
115
133
  */
116
- function buildTable(all, cards) {
134
+ export function buildTable(all, cards) {
117
135
  /** @type {Map<string, any[]>} */
118
136
  const by = new Map();
119
137
  /** @type {Map<string, string>} each id's first package */
@@ -164,8 +182,8 @@ function buildTable(all, cards) {
164
182
  ...(c.titles ?? []),
165
183
  );
166
184
  text.push(
167
- ...(c.guidance ?? []).slice(0, 10),
168
- ...(c.prose ?? []).slice(0, 4),
185
+ ...(c.guidance ?? []).slice(0, GUIDANCE_LINES),
186
+ ...(c.prose ?? []).slice(0, PROSE_PARAGRAPHS),
169
187
  );
170
188
  }
171
189
  const card =
@@ -0,0 +1,48 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The entry index is reused while the catalog's text is unchanged, so
5
+ * every field it reads must be part of the hash that decides reuse.
6
+ */
7
+
8
+ import {describe, it, expect} from 'vitest';
9
+ import * as path from 'node:path';
10
+ import {fileURLToPath} from 'node:url';
11
+ import {gatherCandidates, loadSearchData} from './_adapter.mjs';
12
+ import {HASHED_FIELDS, buildTable, entryTable} from './_entries.mjs';
13
+
14
+ const cwd = path.resolve(
15
+ path.dirname(fileURLToPath(import.meta.url)),
16
+ '../../../..',
17
+ );
18
+
19
+ describe('entry index cache', () => {
20
+ it('hashes every candidate field the index reads', async () => {
21
+ const {all} = await gatherCandidates({cwd});
22
+ /** @type {Set<string>} */
23
+ const read = new Set();
24
+ const watched = all.map(
25
+ c =>
26
+ new Proxy(c, {
27
+ get(target, key, receiver) {
28
+ if (typeof key === 'string') read.add(key);
29
+ return Reflect.get(target, key, receiver);
30
+ },
31
+ }),
32
+ );
33
+ buildTable(watched, loadSearchData().cards);
34
+ const unhashed = [...read].filter(k => !HASHED_FIELDS.includes(k));
35
+ expect(unhashed).toEqual([]);
36
+ }, 60_000);
37
+
38
+ it('rebuilds when a candidate text changes and reuses it otherwise', async () => {
39
+ const {all} = await gatherCandidates({cwd});
40
+ const {cards} = loadSearchData();
41
+ const first = entryTable([...all], cards);
42
+ expect(entryTable([...all], cards)).toBe(first);
43
+ const changed = all.map((c, i) =>
44
+ i === 0 ? {...c, description: `${c.description ?? ''} changed`} : c,
45
+ );
46
+ expect(entryTable(changed, cards)).not.toBe(first);
47
+ }, 60_000);
48
+ });
@@ -15,7 +15,11 @@
15
15
  */
16
16
 
17
17
  import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
18
- import {gatherCandidates, loadSearchData} from './_adapter.mjs';
18
+ import {
19
+ gatherCandidates,
20
+ gatherCandidatesReused,
21
+ loadSearchData,
22
+ } from './_adapter.mjs';
19
23
  import {rankLexical} from './_lexical.mjs';
20
24
  import {checkSearchArgs} from './_result.mjs';
21
25
  import {runTree} from '../../foundation/route/route.mjs';
@@ -56,7 +60,7 @@ export async function search(query, options = {}) {
56
60
  await runTree(
57
61
  SEARCH_TREE,
58
62
  {query, options},
59
- {...(await gatherCandidates(options)), data: loadSearchData()},
63
+ {...(await gatherCandidatesReused(options)), data: loadSearchData()},
60
64
  )
61
65
  ),
62
66
  options.cwd ?? process.cwd(),
@@ -24,6 +24,7 @@ import {
24
24
  } from '../../foundation/discovery/template-adapter.mjs';
25
25
  import {AstryxError} from '../error.mjs';
26
26
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
27
+ import {orderByAffinity} from '../../foundation/text/suggest-order.mjs';
27
28
  import {templateList} from './list/list.mjs';
28
29
  import {templateShow} from './show/show.mjs';
29
30
  import {templateSkeleton} from './skeleton/skeleton.mjs';
@@ -188,7 +189,10 @@ export async function template(name, options = {}) {
188
189
  if (name && candidates.length === 0) {
189
190
  throw new AstryxError(
190
191
  `Unknown template "${name}"`,
191
- templates.map(t => ({name: t.dirName, reason: `${t.type} template`})),
192
+ orderByAffinity(name, templates, t => [t.dirName, t.name]).map(t => ({
193
+ name: t.dirName,
194
+ reason: `${t.type} template`,
195
+ })),
192
196
  ERROR_CODES.ERR_UNKNOWN_TEMPLATE,
193
197
  );
194
198
  }
@@ -32,7 +32,7 @@ export const docs = {
32
32
  '`astryx doctor integration validate`',
33
33
  'The manifest loads, each root holds contributions the CLI can read, and each doc matches its authoring type. Notes, which fail nothing, list a malformed `cliCommand` and each command a topic writes with a package runner (`runner_command`)',
34
34
  'A declared root is missing (`missing_root`), a contribution does not load (`invalid_doc`, `invalid_component`, `invalid_theme`), or two templates in the package replace one Core id (`ambiguous_template_replacement`)',
35
- "The manifest has a key this CLI does not know (`unknown_manifest_key`), or a doc field does not match the doc's authoring type: a field the type does not have, a missing required field, or a value outside the field's type. It also warns on what no reader can serve: a prop listed twice (`duplicate_prop`), a `propDescriptions` key that names no documented prop (`unknown_translated_prop`), a section with no content (`empty_section`), two sections of a topic with one key (`duplicate_section_key`), or a `.doc.zh.mjs` or `.doc.dense.mjs` overlay beside no topic file (`orphan_doc_overlay`). It checks docs with your installed `typescript`, or, where that is missing or has no JavaScript compiler API (TypeScript 7), with an installed `@typescript/typescript6`; without either, it prints `[skip] Docs not type-checked`. With no `astryx.integration.mjs` it prints a hint and exits 0",
35
+ "The manifest has a key this CLI does not know (`unknown_manifest_key`), or a doc field does not match the doc's authoring type: a field the type does not have, a missing required field, or a value outside the field's type. It also warns on what no reader can serve: a prop listed twice (`duplicate_prop`), a `propDescriptions` key that names no documented prop (`unknown_translated_prop`), a section with no content (`empty_section`), two sections of a topic with one key (`duplicate_section_key`), or a `.doc.zh.mjs` or `.doc.dense.mjs` overlay beside no topic file (`orphan_doc_overlay`). Since 0.7.3 it also lists, from source and without failing, what the package tells apps to import that they cannot: a component's import (the doc's `import`, or the one the CLI derives) or a template's public import whose subpath package.json `exports` does not declare (`component_import_not_exported`, `template_import_not_exported`) or that names another package (`component_import_other_package`); an example that imports an undeclared subpath (`example_import_not_exported`); a template that imports a path outside the templates root (`template_import_outside_root`) or a path its package or Core does not export (`template_private_import`). It lists the same way a component's import whose module does not export the component (`component_import_missing_name`), an example or a template that imports a name its package does not export (`example_import_missing_name`, `template_import_missing_name`), and a template source with no default export (`template_no_default_export`). Each is a note, printed with its fix, that fails `--strict` from the next minor; an import it cannot judge, such as an `exports` target not built yet or a deep path into a `dist/` not built yet, is listed under `publicImports` as not checked. It checks docs with your installed `typescript`, or, where that is missing or has no JavaScript compiler API (TypeScript 7), with an installed `@typescript/typescript6`; without either, it prints `[skip] Docs not type-checked`. With no `astryx.integration.mjs` it prints a hint and exits 0",
36
36
  ],
37
37
  [
38
38
  '`astryx doctor integration components`',
@@ -120,6 +120,10 @@ export const docs = {
120
120
  type: 'prose',
121
121
  text: '`integration verify` fails a package that needs the CLI peer and lacks it, or whose range admits a stable CLI too old for what it ships. `integration add doc --parent` and `integration add theme` write the peer for you.',
122
122
  },
123
+ {
124
+ type: 'prose',
125
+ text: "When the CLI is outside that range, `doctor integration validate` and `integration check` list a `cli_peer_version` note naming your package. A note fails nothing, `--strict` included, and `integration verify` does not report it. Below the range the note gives the commands that install a newer Core and CLI together, as dev dependencies in your own package folder, and then run `upgrade --apply`. Above it, in an app the note asks for a release of your package that supports that CLI, and in your own package folder it asks you to test your package with that CLI and widen the range.",
126
+ },
123
127
  ],
124
128
  },
125
129
  {