@astryxdesign/cli 0.7.2-canary.01eab6a → 0.7.2-canary.0da784d

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 (179) hide show
  1. package/README.md +9 -8
  2. package/api/build/help/help.mjs +1 -1
  3. package/api/docs/_adapter.d.mts +11 -0
  4. package/api/docs/_adapter.mjs +244 -1
  5. package/api/docs/integrationDocs.test.mjs +124 -0
  6. package/api/doctor/doctor.mjs +27 -3
  7. package/api/doctor/doctor.test.mjs +43 -0
  8. package/api/doctor/theme-checks.mjs +1 -1
  9. package/api/index.d.mts +2 -0
  10. package/api/index.mjs +2 -0
  11. package/api/init/run/run.mjs +2 -2
  12. package/api/integration/add-contribution.mjs +1 -1
  13. package/api/integration/add-contribution.test.mjs +4 -2
  14. package/api/integration/check/check.d.mts +96 -0
  15. package/api/integration/check/check.mjs +357 -0
  16. package/api/integration/check/check.test.mjs +489 -0
  17. package/api/integration/integration-check.type.d.mts +118 -0
  18. package/api/integration/integration-check.type.mjs +84 -0
  19. package/api/integration/integrationCheck.doc.d.mts +10 -0
  20. package/api/integration/integrationCheck.doc.mjs +73 -0
  21. package/api/integration/integrationComponentConflicts.doc.mjs +27 -6
  22. package/api/integration/validate-integration.mjs +8 -0
  23. package/api/integration/validate-integration.test.mjs +11 -0
  24. package/api/integration/validate-integration.type.d.mts +8 -0
  25. package/api/integration/validate-integration.type.mjs +12 -1
  26. package/api/integration/validateIntegration.doc.mjs +19 -3
  27. package/api/search/search.d.mts +72 -12
  28. package/api/search/search.domain-priority.test.mjs +108 -18
  29. package/api/search/search.integration-check.test.mjs +24 -0
  30. package/api/search/search.mjs +501 -37
  31. package/api/search/search.test.mjs +139 -0
  32. package/api/theme/build/build.family.test.mjs +54 -6
  33. package/api/theme/build/build.mjs +114 -17
  34. package/api/theme/themeBuild.doc.mjs +4 -4
  35. package/assets/docs/README.md +10 -0
  36. package/assets/docs/author-a-theme.doc.mjs +1 -1
  37. package/assets/docs/getting-started.doc.mjs +3 -3
  38. package/assets/docs/styling-overview.doc.mjs +1 -1
  39. package/assets/docs/theme.doc.dense.mjs +1 -1
  40. package/assets/docs/theme.doc.mjs +1 -1
  41. package/assets/docs/theme.doc.zh.mjs +1 -1
  42. package/assets/docs/tree/add-a-component.doc.mjs +1 -1
  43. package/assets/docs/tree/add-a-theme.doc.mjs +1 -1
  44. package/assets/docs/tree/add-a-topic.doc.mjs +10 -7
  45. package/assets/docs/tree/agent-guidance.doc.mjs +2 -2
  46. package/assets/docs/tree/block-template.doc.mjs +8 -20
  47. package/assets/docs/tree/build-the-template.doc.mjs +1 -1
  48. package/assets/docs/tree/check-the-props.doc.mjs +52 -1
  49. package/assets/docs/tree/check-your-docs.doc.mjs +51 -5
  50. package/assets/docs/tree/checks.doc.mjs +21 -13
  51. package/assets/docs/tree/codemods.doc.mjs +4 -4
  52. package/assets/docs/tree/component-family.doc.mjs +3 -5
  53. package/assets/docs/tree/component-imports.doc.mjs +2 -2
  54. package/assets/docs/tree/components.doc.mjs +1 -1
  55. package/assets/docs/tree/debug-and-gap-reports.doc.mjs +7 -18
  56. package/assets/docs/tree/define-the-theme.doc.mjs +6 -5
  57. package/assets/docs/tree/describe-the-component.doc.mjs +1 -1
  58. package/assets/docs/tree/docs.doc.mjs +3 -3
  59. package/assets/docs/tree/document-the-template.doc.mjs +1 -1
  60. package/assets/docs/tree/document-the-theme.doc.mjs +1 -1
  61. package/assets/docs/tree/export-template-assets.doc.mjs +1 -1
  62. package/assets/docs/tree/extend-or-replace.doc.mjs +6 -6
  63. package/assets/docs/tree/fonts-and-assets.doc.mjs +2 -2
  64. package/assets/docs/tree/generate-a-palette.doc.mjs +5 -3
  65. package/assets/docs/tree/grade-template-with-agent.doc.mjs +1 -1
  66. package/assets/docs/tree/integrations.doc.mjs +8 -0
  67. package/assets/docs/tree/links.doc.mjs +6 -5
  68. package/assets/docs/tree/migration-setup.doc.mjs +1 -0
  69. package/assets/docs/tree/migration-verification.doc.mjs +0 -1
  70. package/assets/docs/tree/migration.doc.mjs +0 -1
  71. package/assets/docs/tree/package-and-test.doc.mjs +1 -1
  72. package/assets/docs/tree/page-template.doc.mjs +4 -8
  73. package/assets/docs/tree/publishing.doc.mjs +1 -1
  74. package/assets/docs/tree/quick-start.doc.mjs +37 -21
  75. package/assets/docs/tree/replace-a-core-component.doc.mjs +4 -6
  76. package/assets/docs/tree/replace-a-core-template.doc.mjs +6 -8
  77. package/assets/docs/tree/sections-and-placement.doc.mjs +4 -6
  78. package/assets/docs/tree/see-it-in-an-app.doc.mjs +4 -2
  79. package/assets/docs/tree/short-and-findable.doc.mjs +6 -5
  80. package/assets/docs/tree/single-component.doc.mjs +12 -4
  81. package/assets/docs/tree/start-a-template.doc.mjs +3 -3
  82. package/assets/docs/tree/subcomponent.doc.mjs +6 -6
  83. package/assets/docs/tree/template-assets.doc.mjs +2 -2
  84. package/assets/docs/tree/template-doc-overview.doc.mjs +4 -15
  85. package/assets/docs/tree/template-fonts.doc.mjs +1 -1
  86. package/assets/docs/tree/template-icons.doc.mjs +1 -1
  87. package/assets/docs/tree/template-images-media.doc.mjs +1 -1
  88. package/assets/docs/tree/template-styles.doc.mjs +2 -2
  89. package/assets/docs/tree/templates.doc.mjs +1 -1
  90. package/assets/docs/tree/test-in-an-app.doc.mjs +3 -3
  91. package/assets/docs/tree/test-template-in-app.doc.mjs +1 -1
  92. package/assets/docs/tree/tokens-and-setup.doc.mjs +19 -15
  93. package/assets/docs/tree/troubleshooting.doc.mjs +4 -4
  94. package/assets/docs/tree/type-scale.doc.mjs +3 -3
  95. package/assets/docs/tree/upgrading.doc.mjs +3 -3
  96. package/assets/docs/tree/use-a-theme-in-an-app.doc.mjs +3 -1
  97. package/assets/docs/tree/verify-packed-template.doc.mjs +1 -1
  98. package/assets/docs/tree/versioning.doc.mjs +6 -6
  99. package/assets/docs/tree/write-the-template-file.doc.mjs +4 -3
  100. package/assets/docs/use-a-theme.doc.mjs +2 -2
  101. package/assets/theme.template.ts +1 -1
  102. package/authoring/codemod/codemod.doc.mjs +7 -3
  103. package/authoring/config/config.doc.mjs +9 -6
  104. package/authoring/config/type.ts +4 -2
  105. package/authoring/discover/discover.doc.mjs +1 -1
  106. package/authoring/doctypes/base/graph-fields.doc.mjs +6 -4
  107. package/authoring/doctypes/command/command.doc.mjs +14 -12
  108. package/authoring/doctypes/component/component.doc.mjs +28 -25
  109. package/authoring/doctypes/component/type.ts +7 -5
  110. package/authoring/doctypes/enum/enum.doc.mjs +7 -4
  111. package/authoring/doctypes/function/function.doc.mjs +9 -8
  112. package/authoring/doctypes/hook/hook.doc.mjs +5 -4
  113. package/authoring/doctypes/namespace/namespace.doc.mjs +7 -6
  114. package/authoring/doctypes/reference/reference.doc.mjs +11 -10
  115. package/authoring/doctypes/schema/schema.doc.mjs +9 -9
  116. package/authoring/doctypes/template/integration-template.doc.d.mts +11 -0
  117. package/authoring/doctypes/template/integration-template.doc.mjs +49 -0
  118. package/authoring/doctypes/template/parse.d.mts +6 -2
  119. package/authoring/doctypes/template/parse.mjs +3 -1
  120. package/authoring/doctypes/template/template.doc.mjs +3 -3
  121. package/authoring/doctypes/template/type.ts +22 -0
  122. package/authoring/doctypes/theme/theme.doc.mjs +2 -2
  123. package/authoring/gap-report/gap-report.doc.mjs +2 -2
  124. package/authoring/identity/identity.doc.mjs +3 -3
  125. package/authoring/index.d.ts +1 -0
  126. package/authoring/integration/integration.doc.mjs +12 -4
  127. package/authoring/integration/parse.test.mjs +10 -0
  128. package/authoring/integration/schema.d.mts +2 -0
  129. package/authoring/integration/schema.mjs +1 -0
  130. package/authoring/integration/type.ts +4 -0
  131. package/clients/cli/commands/build-theme.batch-report.test.mjs +3 -1
  132. package/clients/cli/commands/build-theme.mjs +1 -1
  133. package/clients/cli/commands/build-theme.path-safety.test.mjs +155 -21
  134. package/clients/cli/commands/cli-postinstall.test.mjs +49 -1
  135. package/clients/cli/commands/doctor-integration-components.doc.mjs +11 -4
  136. package/clients/cli/commands/doctor-integration-validate.doc.mjs +13 -2
  137. package/clients/cli/commands/doctor-integration.test.mjs +512 -2
  138. package/clients/cli/commands/doctor.mjs +116 -0
  139. package/clients/cli/commands/integration-check.doc.mjs +85 -0
  140. package/clients/cli/commands/integration-check.test.mjs +267 -0
  141. package/clients/cli/commands/integration.doc.mjs +6 -2
  142. package/clients/cli/commands/integration.mjs +107 -1
  143. package/clients/cli/commands/setup-nudge.test.mjs +79 -1
  144. package/clients/cli/commands/swizzle.mjs +5 -3
  145. package/clients/cli/commands/swizzle.routing.test.mjs +18 -1
  146. package/clients/cli/commands/text-json-parity.test.mjs +5 -0
  147. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  148. package/clients/cli/index.mjs +30 -5
  149. package/foundation/agent-docs/agent-doc-state.d.mts +14 -0
  150. package/foundation/agent-docs/agent-doc-state.mjs +38 -0
  151. package/foundation/agent-docs/agent-docs.d.mts +2 -1
  152. package/foundation/agent-docs/agent-docs.mjs +8 -6
  153. package/foundation/config/project.mjs +82 -0
  154. package/foundation/discovery/authoring-self-docs.mjs +2 -1
  155. package/foundation/discovery/doc-types.d.mts +157 -0
  156. package/foundation/discovery/doc-types.mjs +1224 -0
  157. package/foundation/discovery/doc-types.test.mjs +700 -0
  158. package/foundation/discovery/docs-discovery.d.mts +81 -0
  159. package/foundation/discovery/docs-discovery.mjs +57 -0
  160. package/foundation/discovery/integration-doc-files.d.mts +22 -0
  161. package/foundation/discovery/integration-doc-files.mjs +231 -0
  162. package/foundation/discovery/integration-doc-files.test.mjs +246 -0
  163. package/foundation/discovery/project-typescript.d.mts +11 -2
  164. package/foundation/discovery/project-typescript.mjs +32 -4
  165. package/foundation/discovery/prop-drift.d.mts +62 -4
  166. package/foundation/discovery/prop-drift.mjs +561 -63
  167. package/foundation/discovery/prop-drift.test.mjs +1086 -11
  168. package/foundation/discovery/type-match.d.mts +53 -0
  169. package/foundation/discovery/type-match.mjs +660 -0
  170. package/foundation/discovery/type-match.test.mjs +169 -0
  171. package/foundation/discovery/type-text.d.mts +68 -0
  172. package/foundation/discovery/type-text.mjs +658 -0
  173. package/foundation/discovery/type-text.test.mjs +196 -0
  174. package/foundation/doc-compiler/doc-loads.test.mjs +8 -2
  175. package/foundation/doc-compiler/links.d.mts +9 -5
  176. package/foundation/doc-compiler/links.mjs +4 -2
  177. package/foundation/response/response-types.doc.mjs +7 -2
  178. package/package.json +9 -9
  179. package/scripts/postinstall.mjs +3 -3
@@ -2,8 +2,8 @@
2
2
 
3
3
  /**
4
4
  * @file Documented props against a component's TypeScript props: each kind
5
- * of finding, each component it cannot read, and the visible skip when the
6
- * project has no TypeScript.
5
+ * of finding, the loose type rules, the props a doc never needs, and the
6
+ * visible skip when the project has no TypeScript.
7
7
  */
8
8
 
9
9
  import * as fs from 'node:fs';
@@ -14,6 +14,7 @@ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
14
14
  import {
15
15
  comparePropDocs,
16
16
  comparePropTables,
17
+ PROPS_NOT_DOCUMENTED,
17
18
  TYPESCRIPT_MISSING_REASON,
18
19
  } from './prop-drift.mjs';
19
20
  import {unusableTypeScriptReason} from './project-typescript.mjs';
@@ -57,6 +58,37 @@ function withTypeScript() {
57
58
  );
58
59
  }
59
60
 
61
+ /**
62
+ * TypeScript 7 (no JavaScript compiler API) with the TypeScript 6 API package
63
+ * beside it, which re-exports a real TypeScript.
64
+ */
65
+ function withTypeScript7AndItsTypeScript6Api() {
66
+ const ts7 = path.join(pkg, 'node_modules', 'typescript');
67
+ fs.mkdirSync(ts7, {recursive: true});
68
+ fs.writeFileSync(
69
+ path.join(ts7, 'package.json'),
70
+ JSON.stringify({
71
+ name: 'typescript',
72
+ version: '7.0.2',
73
+ exports: {'./package.json': './package.json'},
74
+ }),
75
+ );
76
+ const ts6 = path.join(pkg, 'node_modules', '@typescript', 'typescript6');
77
+ fs.mkdirSync(ts6, {recursive: true});
78
+ fs.writeFileSync(
79
+ path.join(ts6, 'package.json'),
80
+ JSON.stringify({
81
+ name: '@typescript/typescript6',
82
+ version: '6.0.2',
83
+ main: 'index.js',
84
+ }),
85
+ );
86
+ fs.writeFileSync(
87
+ path.join(ts6, 'index.js'),
88
+ `module.exports = require(${JSON.stringify(TYPESCRIPT_DIR)});\n`,
89
+ );
90
+ }
91
+
60
92
  /**
61
93
  * Write `components/<name>.tsx` and its doc; returns its prop table, which
62
94
  * also carries the component record (name, docPath, sourcePath).
@@ -112,7 +144,174 @@ const kinds = report =>
112
144
  report.findings.map(f => `${f.component}.${f.prop} ${f.kind}`);
113
145
 
114
146
  describe('comparePropTables', () => {
115
- it("reports a prop missing from the code, one missing from the doc, and a wrong required flag, each component's together", async () => {
147
+ it('judges the type of a prop a mapped type of the package builds, and says why one another package builds is not judged', async () => {
148
+ withTypeScript();
149
+ const sizes = path.join(pkg, 'node_modules', '@acme', 'sizes');
150
+ fs.mkdirSync(sizes, {recursive: true});
151
+ fs.writeFileSync(
152
+ path.join(sizes, 'package.json'),
153
+ JSON.stringify({name: '@acme/sizes', types: 'index.d.ts'}),
154
+ );
155
+ fs.writeFileSync(
156
+ path.join(sizes, 'index.d.ts'),
157
+ "export type Sizes = Partial<Record<'sm' | 'md', string>>;\n",
158
+ );
159
+ const tables = [
160
+ component(
161
+ 'Mapped',
162
+ "export function Mapped(props: Partial<Record<'a' | 'b', 'x' | 'y'>>) { return null; }",
163
+ {props: [prop('a', "'x' | 'z'"), prop('b', "'x' | 'y'")]},
164
+ ),
165
+ component(
166
+ 'HandledCell',
167
+ "import type {Sizes} from '@acme/sizes';\nexport function HandledCell(props: Sizes) { return null; }",
168
+ {props: [prop('sm', 'number')]},
169
+ ),
170
+ // Keys the check can't trace, and a doc type that does not parse; and
171
+ // a name that starts with another's sorts after it.
172
+ component(
173
+ 'Handled',
174
+ "type A = string;\nexport function Handled(props: {[K in `on${'Open' | 'Close'}`]?: () => void} & {items?: ((items: A[]) => A)[]}) { return null; }",
175
+ {props: [prop('onOpen', '() => A'), prop('items', '((A[]) => A)[]')]},
176
+ ),
177
+ ];
178
+
179
+ const report = await compare(tables);
180
+
181
+ expect(kinds(report)).toEqual(['Mapped.a type_mismatch']);
182
+ expect(report.typesNotCompared).toEqual(
183
+ [
184
+ ['Handled', 'not a form the check judges exactly', ['items', 'onOpen']],
185
+ ['HandledCell', 'declared outside the package, not compared', ['sm']],
186
+ ].map(([component, reason, props]) => ({
187
+ component,
188
+ doc: `components/${component}.doc.mjs`,
189
+ reason,
190
+ props,
191
+ })),
192
+ );
193
+ });
194
+
195
+ it('judges no prop type, and says why, with a TypeScript older than 4.8', async () => {
196
+ const dir = path.join(pkg, 'node_modules', 'typescript');
197
+ fs.mkdirSync(dir, {recursive: true});
198
+ fs.writeFileSync(path.join(dir, 'package.json'), '{"version": "4.7.4"}');
199
+ const real = JSON.stringify(TYPESCRIPT_DIR);
200
+ fs.writeFileSync(
201
+ path.join(dir, 'index.js'),
202
+ `module.exports = {...require(${real}), version: '4.7.4'};`,
203
+ );
204
+ const source = 'export function Badge(p: {size?: string}) { return null; }';
205
+ const doc = {props: [prop('size', 'number')]};
206
+
207
+ expect(await compare([component('Badge', source, doc)])).toMatchObject({
208
+ findings: [],
209
+ typesCompared: 0,
210
+ typesSkipped:
211
+ 'TypeScript 4.7.4 is older than 4.8, the oldest the type comparison reads; install TypeScript 5.0 through 6 (`npm install -D typescript@6`), or on TypeScript 7 add `@typescript/typescript6`, to judge them',
212
+ });
213
+ });
214
+
215
+ it("judges a prop a package's mapping rewrites by its type, and keeps the text of one a mapping copies", async () => {
216
+ withTypeScript();
217
+ const types = `interface Base { size: 'sm' | 'md' }
218
+ interface Opt { tone?: 'info' | undefined }
219
+ type Many<T> = {[K in keyof T]: T[K][]};
220
+ type Nullable<T> = {[K in keyof T]: T[K] | null};
221
+ interface Pickable<T = string> { pick?: (value: T) => void }
222
+ type ChooserProps<T extends string = string> = {pick?: string} & {
223
+ change?: (value: readonly T[]) => void | Promise<void>;
224
+ };
225
+ interface ListProps<T> { value?: T; onChange?: (v: T) => void }
226
+ type MultiProps<T> = ListProps<T[]>;
227
+ import type {Item as Imported} from './item';
228
+ import type * as NS from './item';
229
+ interface Item { a: string }
230
+ interface ItemList<Item> { items?: Item[] }`;
231
+ const size = {props: [prop('size', "'sm' | 'md'", {required: true})]};
232
+ const pick = {props: [prop('pick', '(value: T) => void')]};
233
+ const tables = [
234
+ ['Many', 'Many<Base>', size],
235
+ ['Nulls', 'Nullable<Base>', size],
236
+ ['Picked', "Pick<Base, 'size'>", size],
237
+ [
238
+ 'Strict',
239
+ 'Required<Opt>',
240
+ {props: [prop('tone', "'info' | undefined", {required: true})]},
241
+ ],
242
+ // A generic component's prop keeps its declaration's text; one a
243
+ // concrete type instantiates does not.
244
+ ['Boxed', 'Pickable<number>', pick],
245
+ [
246
+ 'Chooser',
247
+ 'ChooserProps<T>',
248
+ {
249
+ props: [
250
+ prop('pick', 'string'),
251
+ prop('change', '(value: readonly T[]) => void | Promise<void>'),
252
+ ],
253
+ },
254
+ '<T extends string = string>',
255
+ ],
256
+ // Instantiated with a type built from the component's own parameter,
257
+ // the declaration's `T` is no longer the prop's type.
258
+ // A type argument that prints with the parameter's name elsewhere is
259
+ // still another type here.
260
+ ['Renamed', 'ItemList<Imported>', {props: [prop('items', 'Item[]')]}],
261
+ ['Spaced', 'ItemList<NS.Item>', {props: [prop('items', 'Item[]')]}],
262
+ ['Owned', 'ItemList<Item>', {props: [prop('items', 'Item[]')]}],
263
+ ...[
264
+ ['Listed', 'ListProps<T[]>', 'T', '(v: T) => void'],
265
+ ['Maybe', 'ListProps<T | null>', 'T', '(v: T) => void'],
266
+ ['Multi', 'MultiProps<T>', 'T[]', '(v: T[]) => void'],
267
+ ].map(([name, props, value, onChange]) => [
268
+ name,
269
+ props,
270
+ {props: [prop('value', value), prop('onChange', onChange)]},
271
+ '<T>',
272
+ ]),
273
+ ].map(([name, props, doc, generics = '']) =>
274
+ component(
275
+ name,
276
+ `${types}\nexport function ${name}${generics}(props: ${props}) { return null; }`,
277
+ doc,
278
+ ),
279
+ );
280
+
281
+ fs.writeFileSync(
282
+ path.join(pkg, 'components', 'item.ts'),
283
+ 'export interface Item { b: number }\n',
284
+ );
285
+ const report = await compare(tables);
286
+
287
+ expect(kinds(report)).toEqual([
288
+ 'Many.size type_mismatch',
289
+ 'Nulls.size type_mismatch',
290
+ 'Strict.tone type_mismatch',
291
+ ]);
292
+ // A message shows the type the mapping makes, not the source's text.
293
+ expect(report.findings.map(f => f.codeType)).toEqual([
294
+ "('sm' | 'md')[]",
295
+ "'sm' | 'md' | null",
296
+ "'info'",
297
+ ]);
298
+ expect(report.typesNotCompared).toEqual(
299
+ [
300
+ ['Boxed', ['pick']],
301
+ ['Listed', ['onChange', 'value']],
302
+ ['Maybe', ['onChange', 'value']],
303
+ ['Renamed', ['items']],
304
+ ['Spaced', ['items']],
305
+ ].map(([component, props]) => ({
306
+ component,
307
+ doc: `components/${component}.doc.mjs`,
308
+ reason: 'not a form the check judges exactly',
309
+ props,
310
+ })),
311
+ );
312
+ });
313
+
314
+ it("reports a prop missing from the code, one missing from the doc, a wrong required flag, and a wrong type, each component's together", async () => {
116
315
  withTypeScript();
117
316
  const badge = component(
118
317
  'Badge',
@@ -147,20 +346,873 @@ export function Badge(props: BadgeProps) { return null; }`,
147
346
  'Badge.count not_in_doc',
148
347
  'Badge.label required_mismatch',
149
348
  'Badge.size not_in_code',
349
+ 'Badge.tone type_mismatch',
150
350
  'BadgeCount.amount not_in_doc',
151
351
  ]);
152
352
  expect(report.findings.every(f => f.severity === 'warning')).toBe(true);
353
+ expect(report.findings.find(f => f.kind === 'type_mismatch')).toMatchObject(
354
+ {
355
+ docType: "'neutral' | 'info'",
356
+ codeType: 'Tone',
357
+ doc: 'components/Badge.doc.mjs',
358
+ source: 'components/Badge.tsx',
359
+ message: expect.stringContaining(
360
+ "Tone ('neutral' | 'info' | 'danger')",
361
+ ),
362
+ },
363
+ );
153
364
  expect(
154
365
  report.findings.find(f => f.kind === 'required_mismatch'),
155
- ).toMatchObject({
156
- docRequired: false,
157
- codeRequired: true,
158
- doc: 'components/Badge.doc.mjs',
159
- source: 'components/Badge.tsx',
160
- });
366
+ ).toMatchObject({docRequired: false, codeRequired: true});
161
367
  });
162
368
 
163
- it('reads every overload, one without props included, reads a prop only some members of a union require as optional, and holds every prop one entry names to its `required`', async () => {
369
+ it("judges a field, a name an index signature takes, and a prop declared in another file by the type's name where the prop is declared, not by the name the type was declared with", async () => {
370
+ withTypeScript();
371
+ const dir = path.join(pkg, 'components');
372
+ fs.mkdirSync(dir, {recursive: true});
373
+ fs.writeFileSync(
374
+ path.join(dir, 'base.ts'),
375
+ "export interface Item { id: string }\nexport type Size = 'sm' | 'md';\n",
376
+ );
377
+ // Another file imports the same types under other names, and declares
378
+ // its own `Item` and `Size`.
379
+ fs.writeFileSync(
380
+ path.join(dir, 'types.ts'),
381
+ [
382
+ "import type {Item as BaseItem, Size as BaseSize} from './base';",
383
+ 'interface Item { label: string }',
384
+ "type Size = 'lg';",
385
+ 'export type ElsewhereProps = { size?: BaseSize; item?: BaseItem; onPick?: (item: BaseItem) => void; cfg?: {item: BaseItem}; [key: `size-${string}`]: BaseSize | undefined } & Required<Partial<{tone: BaseSize; entry: BaseItem}>>;',
386
+ ].join('\n'),
387
+ );
388
+ const here = component(
389
+ 'Renamed',
390
+ [
391
+ "import type {Item as BaseItem, Size as BaseSize} from './base';",
392
+ 'interface Item { label: string }',
393
+ "type Size = 'lg';",
394
+ 'export function Renamed(props: {cfg?: {item: BaseItem}; [key: `size-${string}`]: BaseSize | undefined}) { return null; }',
395
+ ].join('\n'),
396
+ {props: [prop('cfg.item', 'Item'), prop('size-a', 'Size')]},
397
+ );
398
+ const elsewhere = component(
399
+ 'Elsewhere',
400
+ "import type {ElsewhereProps} from './types';\nexport function Elsewhere(props: ElsewhereProps) { return null; }",
401
+ {
402
+ props: [
403
+ prop('size', 'Size'),
404
+ prop('tone', 'Size', {required: true}),
405
+ prop('entry', 'Item', {required: true}),
406
+ prop('item', 'Item'),
407
+ prop('onPick', '(item: Item) => void'),
408
+ prop('cfg.item', 'Item'),
409
+ prop('size-a', 'Size'),
410
+ ],
411
+ },
412
+ );
413
+ // The same docs, naming the types as each file does, are judged matches.
414
+ const named = component(
415
+ 'Named',
416
+ [
417
+ "import type {Item as BaseItem, Size as BaseSize} from './base';",
418
+ 'export function Named(props: {cfg?: {item: BaseItem}; [key: `size-${string}`]: BaseSize | undefined}) { return null; }',
419
+ ].join('\n'),
420
+ {props: [prop('cfg.item', 'BaseItem'), prop('size-a', 'BaseSize')]},
421
+ );
422
+
423
+ const report = await compare([here, elsewhere, named]);
424
+
425
+ // `Size` is `'lg'` where each prop is declared, which TypeScript rejects
426
+ // for `'sm' | 'md'`; `Item` is an object type there, not compared.
427
+ expect(kinds(report)).toEqual([
428
+ 'Elsewhere.size type_mismatch',
429
+ 'Elsewhere.size-a type_mismatch',
430
+ 'Elsewhere.tone type_mismatch',
431
+ 'Renamed.size-a type_mismatch',
432
+ ]);
433
+ expect(report.typesNotCompared).toEqual([
434
+ expect.objectContaining({
435
+ component: 'Elsewhere',
436
+ props: ['cfg.item', 'entry', 'item', 'onPick'],
437
+ }),
438
+ expect.objectContaining({component: 'Renamed', props: ['cfg.item']}),
439
+ ]);
440
+ expect(report.typesCompared).toBe(6);
441
+ });
442
+
443
+ it("reads `React.X` as React's own where the prop is declared, never as a bare name that means another type there", async () => {
444
+ withTypeScript();
445
+ fs.mkdirSync(path.join(pkg, 'node_modules', '@types'), {recursive: true});
446
+ fs.symlinkSync(
447
+ path.dirname(require.resolve('@types/react/package.json')),
448
+ path.join(pkg, 'node_modules', '@types', 'react'),
449
+ 'dir',
450
+ );
451
+ const keys = component(
452
+ 'Keys',
453
+ [
454
+ "import * as React from 'react';",
455
+ "type Key = 'a' | 'b';",
456
+ 'export function Keys(props: {onKey?: (event: KeyboardEvent) => void; rowKey?: string | number | bigint; pick?: Key; native?: React.Key}) { return null; }',
457
+ ].join('\n'),
458
+ {
459
+ props: [
460
+ prop('onKey', '(event: React.KeyboardEvent) => void'),
461
+ prop('rowKey', 'React.Key'),
462
+ prop('pick', 'React.Key'),
463
+ prop('native', 'React.Key'),
464
+ ],
465
+ },
466
+ );
467
+ // React's global namespace, with no import.
468
+ const global = component(
469
+ 'GlobalKeys',
470
+ 'export function GlobalKeys(props: {rowKey?: string | number | bigint}) { return null; }',
471
+ {props: [prop('rowKey', 'React.Key')]},
472
+ );
473
+
474
+ const report = await compare([keys, global]);
475
+
476
+ // The DOM's `KeyboardEvent` is not React's, and the file's own `Key` is
477
+ // not `React.Key`.
478
+ expect(kinds(report)).toEqual(['Keys.pick type_mismatch']);
479
+ expect(report.typesNotCompared).toEqual([
480
+ expect.objectContaining({component: 'Keys', props: ['onKey']}),
481
+ ]);
482
+ expect(report.typesCompared).toBe(4);
483
+ });
484
+
485
+ it('judges primitives, literals, arrays, string enums, and names for them exactly, in any order', async () => {
486
+ withTypeScript();
487
+ const card = component(
488
+ 'Card',
489
+ [
490
+ "type Tone = 'neutral' | 'info';",
491
+ "export enum Color { Red = 'red', Blue = 'blue' } export enum Hue { Red = 'red', Blue = 'blue' }",
492
+ 'export interface CardProps {',
493
+ ' label: string;',
494
+ ' tone?: Tone;',
495
+ ' items?: ReadonlyArray<string>;',
496
+ ' isOpen?: boolean;',
497
+ " size?: 'sm' | 'md' | number;",
498
+ ' color?: Color;',
499
+ ' count?: number;',
500
+ ' ids?: string[];',
501
+ ' hue?: Color;',
502
+ " shade?: Color; shades?: Color[]; pick?: 'red' | 'blue';",
503
+ '}',
504
+ 'export function Card(props: CardProps) { return null; }',
505
+ ].join('\n'),
506
+ {
507
+ props: [
508
+ prop('label', 'string', {required: true}),
509
+ prop('tone', '\'info\' | "neutral"'),
510
+ prop('items', 'Array<string>'),
511
+ prop('isOpen', 'true | false'),
512
+ prop('size', "number | 'md' | 'sm'"),
513
+ prop('color', 'Color'),
514
+ prop('count', 'string'),
515
+ prop('ids', 'number[]'),
516
+ prop('hue', "'red' | 'blue'"),
517
+ prop('shade', 'Hue'),
518
+ prop('shades', 'Hue[]'),
519
+ prop('pick', 'Color'),
520
+ ],
521
+ },
522
+ );
523
+
524
+ const report = await compare([card]);
525
+
526
+ // TypeScript takes neither `'red'` nor another enum's `Hue.Red` where the
527
+ // enum `Color` is expected, and `Color` does not take the `'red'` `pick` does.
528
+ expect(kinds(report)).toEqual([
529
+ 'Card.count type_mismatch',
530
+ 'Card.hue type_mismatch',
531
+ 'Card.ids type_mismatch',
532
+ 'Card.pick type_mismatch',
533
+ 'Card.shade type_mismatch',
534
+ 'Card.shades type_mismatch',
535
+ ]);
536
+ expect(report.typesCompared).toBe(12);
537
+ expect(report.typesNotCompared).toEqual([]);
538
+ });
539
+
540
+ it('reads a union the way TypeScript reduces it, and a default after `=` as no alias', async () => {
541
+ withTypeScript();
542
+ const icon = component(
543
+ 'Icon',
544
+ [
545
+ "type IconName = 'add' | 'close';",
546
+ "export enum Color { Red = 'red', Blue = 'blue' }",
547
+ 'type Step = 1 | 2;',
548
+ "type Size = 'sm' | 'md' | 'lg';",
549
+ 'export interface IconProps {',
550
+ ' icon?: IconName | string;',
551
+ ' color?: Color | string;',
552
+ ' step?: Step | number;',
553
+ ' isOpen?: boolean;',
554
+ ' icons?: string[];',
555
+ ' size?: Size;',
556
+ ' limit?: 1000 | 2000;',
557
+ ' width?: number | string;',
558
+ '}',
559
+ 'export function Icon(props: IconProps) { return null; }',
560
+ ].join('\n'),
561
+ {
562
+ props: [
563
+ prop('icon', 'IconName | string'),
564
+ prop('color', 'Color | string'),
565
+ prop('step', 'Step | number'),
566
+ prop('isOpen', 'boolean = false'),
567
+ prop('icons', '(IconName | string)[]'),
568
+ prop('size', "Size = 'md'"),
569
+ prop('limit', '1_000 | 2_000'),
570
+ prop('width', 'number (or a CSS length)'),
571
+ ],
572
+ },
573
+ );
574
+
575
+ const report = await compare([icon]);
576
+
577
+ expect(report.findings).toEqual([]);
578
+ expect(report.typesCompared).toBe(7);
579
+ });
580
+
581
+ it('sets aside null and undefined when the project has no strict null checks', async () => {
582
+ withTypeScript();
583
+ fs.writeFileSync(
584
+ path.join(pkg, 'tsconfig.json'),
585
+ JSON.stringify({compilerOptions: {strict: false, jsx: 'react-jsx'}}),
586
+ );
587
+ const loose = component(
588
+ 'Loose',
589
+ [
590
+ 'type MaybeNum = number | null;',
591
+ 'export function Loose(props: {count?: MaybeNum; counts?: MaybeNum[]}) { return null; }',
592
+ ].join('\n'),
593
+ {
594
+ props: [
595
+ prop('count', 'number | null'),
596
+ prop('counts', '(number | null)[]'),
597
+ ],
598
+ },
599
+ );
600
+
601
+ const report = await compare([loose]);
602
+
603
+ expect(report.findings).toEqual([]);
604
+ expect(report.typesCompared).toBe(2);
605
+ });
606
+
607
+ it('respects exactOptionalPropertyTypes: an optional prop takes undefined only when its type says so', async () => {
608
+ withTypeScript();
609
+ const tsconfig = path.join(pkg, 'tsconfig.json');
610
+ const config = JSON.parse(fs.readFileSync(tsconfig, 'utf8'));
611
+ config.compilerOptions.exactOptionalPropertyTypes = true;
612
+ fs.writeFileSync(tsconfig, JSON.stringify(config));
613
+ const exact = component(
614
+ 'Exact',
615
+ "type MaybeTone = 'a' | 'b' | 'c' | undefined;\nexport function Exact(props: {size?: 'sm' | 'md'; tone?: 'a' | undefined; mode?: 'x'; status?: {tone?: 'a' | 'b' | undefined; mode?: 'x'}; labels?: Record<string, string | undefined>; hue?: 'a' | 'b' | undefined; t6?: MaybeTone; [key: `x${string}`]: string | undefined}) { return null; }\n",
616
+ {
617
+ props: [
618
+ prop('size', "'sm' | 'md' | undefined"),
619
+ prop('tone', "'a' | undefined"),
620
+ prop('mode', "'x'"),
621
+ prop('status.tone', "'a' | 'b'"),
622
+ prop('status.mode', "'x'"),
623
+ prop('labels.close', 'string'),
624
+ prop('xTone', 'string'),
625
+ prop('hue', "'a' | 'b'"),
626
+ prop('t6', "'a' | 'b' | 'c'"),
627
+ ],
628
+ },
629
+ );
630
+ const variant = component(
631
+ 'Variant',
632
+ "export function Variant(props: {kind: 'a'; size?: 'sm' | undefined} | {kind: 'b'; size?: 'md' | undefined}) { return null; }\n",
633
+ {
634
+ props: [
635
+ prop('kind', "'a' | 'b'", {required: true}),
636
+ prop('size', "'sm' | 'md'"),
637
+ ],
638
+ },
639
+ );
640
+
641
+ const report = await compare([exact, variant]);
642
+
643
+ // TypeScript rejects `size={undefined}` here, and takes the others; a
644
+ // field that declares `undefined` takes it too, unlike its doc. A name an
645
+ // index signature takes is held to the index's type the same way as a
646
+ // field or as a prop.
647
+ expect(kinds(report)).toEqual([
648
+ 'Exact.hue type_mismatch',
649
+ 'Exact.size type_mismatch',
650
+ 'Exact.status.tone type_mismatch',
651
+ 'Exact.t6 type_mismatch',
652
+ 'Variant.size type_mismatch',
653
+ ]);
654
+ expect(report.typesCompared).toBe(11);
655
+ // The message shows the `undefined` the code declares, written once or by
656
+ // each member of a union, in the type and in its expansion.
657
+ for (const finding of report.findings.filter(
658
+ f => f.component === 'Variant' || f.prop === 'hue',
659
+ )) {
660
+ expect(finding.codeType).toMatch(/undefined/);
661
+ const declared = finding.message.split('but the code declares ')[1];
662
+ expect(declared).toMatch(/undefined/);
663
+ expect(declared.match(/\((.*)\)\.$/)?.[1] ?? 'undefined').toMatch(
664
+ /undefined/,
665
+ );
666
+ }
667
+ // Through an alias, the expansion shows it.
668
+ expect(report.findings.find(f => f.prop === 't6')?.message).toMatch(
669
+ /declares MaybeTone \(.*undefined.*\)\.$/,
670
+ );
671
+ });
672
+
673
+ it('holds a name an index signature takes, a field a Record takes, and a readonly array to the type TypeScript checks, and lists a field only an index takes and an `a / b` entry whose one type does not split', async () => {
674
+ withTypeScript();
675
+ const held = component(
676
+ 'Held',
677
+ [
678
+ 'export function Held(props: {',
679
+ ' labels?: Record<string, string>;',
680
+ ' tags?: string[];',
681
+ ' ids?: ReadonlyArray<string>;',
682
+ ' keys?: readonly string[];',
683
+ ' grid?: readonly string[][];',
684
+ ' rows?: (readonly string[])[];',
685
+ ' onPick?: (values: readonly string[]) => void;',
686
+ ' onDrop?: (values: readonly string[]) => void;',
687
+ ' pinned?: {readonly ids: readonly string[]};',
688
+ ' item?: {tags: readonly string[]};',
689
+ ' mix?: string[] | readonly number[];',
690
+ ' min?: number; max?: number; status?: {a: number};',
691
+ ' [key: `x${string}`]: string; [key: `y${string}`]: {color: string};',
692
+ '}) { return null; }',
693
+ ].join('\n'),
694
+ {
695
+ props: [
696
+ prop('labels.close', 'string | undefined'),
697
+ prop('xTone', 'string | undefined'),
698
+ prop('tags', 'readonly string[]'),
699
+ prop('ids', 'readonly string[]'),
700
+ prop('keys', 'string[]'),
701
+ prop('grid', '(readonly string[])[]'),
702
+ prop('rows', 'readonly string[][]'),
703
+ prop('onPick', '(values: string[]) => void'),
704
+ prop('onDrop', '(values: readonly string[])=>void'),
705
+ prop('pinned', '{readonly ids: readonly string[]}'),
706
+ prop('item', '{tags: string[]}'),
707
+ prop('mix', 'readonly string[] | number[]'),
708
+ prop('min / max', 'number'),
709
+ prop('status.a / status.b', 'number'),
710
+ prop('yTone.color', 'string'),
711
+ ],
712
+ },
713
+ );
714
+
715
+ const report = await compare([held]);
716
+
717
+ // TypeScript passes no `undefined` through an index that does not take
718
+ // it, and no readonly array where a mutable one is taken; a mutable
719
+ // array passes where a readonly one is.
720
+ expect(kinds(report)).toEqual([
721
+ 'Held.labels.close type_mismatch',
722
+ 'Held.status.b not_in_code',
723
+ 'Held.tags type_mismatch',
724
+ 'Held.xTone type_mismatch',
725
+ ]);
726
+ expect(report.typesCompared).toBe(7);
727
+ // `readonly` written as the code writes it matches; written somewhere
728
+ // else, at another depth, in a callback's parameter, in an object's
729
+ // field, or on another union member, it is not placed: listed, never a
730
+ // match, as are a field only an index takes and `a / b` with one type.
731
+ expect(
732
+ report.typesNotCompared.map(e => `${e.reason}: ${e.props.join(' ')}`),
733
+ ).toEqual([
734
+ 'not a form the check judges exactly: grid item max min mix onPick rows status.a yTone.color',
735
+ ]);
736
+ });
737
+
738
+ it('reads strict null checks as the TypeScript version defaults them', async () => {
739
+ withTypeScript();
740
+ fs.writeFileSync(
741
+ path.join(pkg, 'tsconfig.json'),
742
+ JSON.stringify({compilerOptions: {jsx: 'react-jsx'}}),
743
+ );
744
+ // The TypeScript the test links in: 6 checks strict null by default.
745
+ const ts = require(TYPESCRIPT_DIR);
746
+ const strictByDefault = ts.getStrictOptionValue({}, 'strictNullChecks');
747
+ const maybe = component(
748
+ 'Maybe',
749
+ 'export function Maybe(props: {count?: number | null}) { return null; }\n',
750
+ {props: [prop('count', 'number')]},
751
+ );
752
+
753
+ const report = await compare([maybe]);
754
+
755
+ expect(kinds(report)).toEqual(
756
+ strictByDefault ? ['Maybe.count type_mismatch'] : [],
757
+ );
758
+ });
759
+
760
+ it("lists a name two index signatures take and a field documented with one variant's type, and reads a default for one union member", async () => {
761
+ withTypeScript();
762
+ const pick = component(
763
+ 'Pick',
764
+ [
765
+ "export enum SizeE { Sm = 'sm', Md = 'md' }",
766
+ 'type Sel = {kind: "single"; value: string} | {kind: "multi"; value: string[]};',
767
+ 'export type PickProps = {',
768
+ ' sizeE?: SizeE;',
769
+ ' sel?: Sel;',
770
+ ' tri?: {v: string} | {v: number} | {v: boolean};',
771
+ ' sev?: {v: 1} | {v: 2} | {v: 3} | {v: 4} | {v: 5} | {v: 6} | {v: 7};',
772
+ ' labels?: {close: string} | Record<string, number>;',
773
+ ' [key: `data-${string}`]: string | number | undefined;',
774
+ ' [key: `data-track${string}`]: string | undefined;',
775
+ '} & ({mode: "str"; [key: `x${string}`]: string} | {mode: "num"; [key: `x${string}`]: number});',
776
+ 'export function Pick(props: PickProps) { return null; }',
777
+ ].join('\n'),
778
+ {
779
+ props: [
780
+ prop('sizeE', 'SizeE = SizeE.Md'),
781
+ prop('sel.value', 'string'),
782
+ prop('tri.v', 'string | number'),
783
+ prop('sev.v', '1 | 2'),
784
+ prop('labels.close', 'string | number'),
785
+ prop('data-tracker', 'string'),
786
+ prop('mode', "'str' | 'num'", {required: true}),
787
+ prop('xValue', 'number'),
788
+ ],
789
+ },
790
+ );
791
+
792
+ const report = await compare([pick]);
793
+
794
+ // TypeScript holds `data-tracker` to both signatures that take it, and
795
+ // `xValue` to the one of the member it is passed with; `sel.value`,
796
+ // `tri.v` and `sev.v` (past six variants, never reported) take every
797
+ // variant's type, and `labels.close` is documented with both.
798
+ expect(report.findings).toEqual([]);
799
+ expect(report.typesNotCompared).toEqual([
800
+ expect.objectContaining({
801
+ props: ['data-tracker', 'xValue'],
802
+ reason: 'not a form the check judges exactly',
803
+ }),
804
+ expect.objectContaining({
805
+ props: ['sel.value', 'sev.v', 'tri.v'],
806
+ reason: "the prop's variants give this field different types",
807
+ }),
808
+ ]);
809
+ expect(report.typesCompared).toBe(3);
810
+ });
811
+
812
+ it('reads fields in arrays of unions, a name one member indexes, and names only where the code can mean them', async () => {
813
+ withTypeScript();
814
+ const rows = component(
815
+ 'Rows',
816
+ [
817
+ 'type Items = number[];',
818
+ 'export type RowsProps = {',
819
+ " items?: Array<{kind: 'a'; value: string} | {kind: 'b'; value: number}>;",
820
+ ' list?: Items;',
821
+ " behavior?: 'auto' | 'smooth';",
822
+ ' [key: `data-${string}`]: string | undefined;',
823
+ "} & ({mode: 'fixed'; xSize: number} | ({mode: 'free'} & {[k: `x${string}`]: string}));",
824
+ 'export function Rows(props: RowsProps) { return null; }',
825
+ ].join('\n'),
826
+ {
827
+ props: [
828
+ prop('items[].value', 'string | number'),
829
+ prop('list', 'Items = string[]'),
830
+ prop('behavior', 'ScrollBehavior'),
831
+ prop('data-section', 'string'),
832
+ prop('mode', "'fixed' | 'free'", {required: true}),
833
+ prop('xSize', 'number | string'),
834
+ ],
835
+ },
836
+ );
837
+
838
+ const report = await compare([rows]);
839
+
840
+ // `ScrollBehavior` is the DOM's, which the code never names.
841
+ expect(kinds(report)).toEqual(['Rows.list type_mismatch']);
842
+ expect(report.typesNotCompared).toEqual([
843
+ expect.objectContaining({props: ['behavior']}),
844
+ ]);
845
+ });
846
+
847
+ it('judges a prop two intersected types declare by the type they narrow it to, and undefined on a required prop', async () => {
848
+ withTypeScript();
849
+ const narrow = component(
850
+ 'Narrow',
851
+ [
852
+ "type A = {size?: 'sm'; tone?: 'a' | 'b'};",
853
+ "type B = {size?: 'sm' | 'md'; tone?: 'a' | 'b'};",
854
+ 'export type NarrowProps = B & A & {isOpen: boolean; label: string | undefined};',
855
+ 'export function Narrow(props: NarrowProps) { return null; }',
856
+ ].join('\n'),
857
+ {
858
+ props: [
859
+ prop('size', "'sm' | 'md'"),
860
+ prop('tone', "'b' | 'a'"),
861
+ prop('isOpen', 'boolean | undefined', {required: true}),
862
+ prop('label', 'string', {required: true}),
863
+ ],
864
+ },
865
+ );
866
+
867
+ const report = await compare([narrow]);
868
+
869
+ // TypeScript takes only 'sm' for `size`, rejects `isOpen={undefined}`,
870
+ // and accepts `label={undefined}`.
871
+ expect(kinds(report)).toEqual([
872
+ 'Narrow.isOpen type_mismatch',
873
+ 'Narrow.label type_mismatch',
874
+ 'Narrow.size type_mismatch',
875
+ ]);
876
+ expect(report.findings.find(f => f.prop === 'size')?.codeType).toBe("'sm'");
877
+ });
878
+
879
+ it('lists every other form of type as not compared, never as a mismatch', async () => {
880
+ withTypeScript();
881
+ const thread = component(
882
+ 'Thread',
883
+ [
884
+ 'interface IconShape { path: string }',
885
+ 'type MaybePromise<T> = T | Promise<T>;',
886
+ 'type Parts = {a?: string; b?: number};',
887
+ "type A = {a: string}; type B = {b: number}; enum Color { Red = 'red' } namespace Theme { export enum Color { Red = 'red' } }",
888
+ 'export interface ThreadProps {',
889
+ ' onSubmit?: (text: string, files?: File[]) => MaybePromise<void>;',
890
+ ' onPick?: (value: string, index: number) => void;',
891
+ ' item?: A & B;',
892
+ ' parts?: Partial<Parts>;',
893
+ ' key2?: keyof (A & B);',
894
+ ' key3?: keyof (A & B);',
895
+ " target?: '_self' | '_blank' | (string & {});",
896
+ ' range?: [number, number?];',
897
+ ' labels?: Record<string, string>;',
898
+ ' icon?: IconShape;',
899
+ ' data?: any;',
900
+ ' extra?: unknown; tint?: Theme.Color;',
901
+ '}',
902
+ 'export function Thread(props: ThreadProps) { return null; }',
903
+ ].join('\n'),
904
+ {
905
+ props: [
906
+ prop('onSubmit', '(text: string) => Promise<number>'),
907
+ prop('onPick', '(value: string, index: number) => void'),
908
+ prop('item', '{a: string; b: number}'),
909
+ prop('parts', 'Parts'),
910
+ prop('key2', 'keyof (A & B)'),
911
+ prop('key3', "'a' | 'b'"),
912
+ prop('target', "'_self' | '_blank'"),
913
+ prop('range', '[number]'),
914
+ prop('labels', '{[key: string]: number}'),
915
+ prop('icon', 'IconName'),
916
+ prop('data', 'string'),
917
+ prop('data.id', 'string'),
918
+ prop('extra.kind', 'string'),
919
+ prop('tint', 'Color'),
920
+ ],
921
+ },
922
+ );
923
+
924
+ const report = await compare([thread]);
925
+
926
+ expect(report.findings).toEqual([]);
927
+ // Written exactly as the source writes them, or a literal union the
928
+ // code's type resolves to (`keyof (A & B)` is `'a' | 'b'`).
929
+ expect(report.typesCompared).toBe(3);
930
+ expect(
931
+ report.typesNotCompared.map(e => `${e.reason}: ${e.props.join(' ')}`),
932
+ ).toEqual([
933
+ 'not a form the check judges exactly: data data.id extra.kind icon item labels onSubmit parts range target tint',
934
+ ]);
935
+ });
936
+
937
+ it("compares a documented field's type, and a name an index signature takes, with the type the code gives it", async () => {
938
+ withTypeScript();
939
+ const note = component(
940
+ 'Note',
941
+ [
942
+ 'export interface NoteProps {',
943
+ " status?: {type: 'error' | 'warning'; message?: string};",
944
+ ' items?: Array<{id: string; label: string}>;',
945
+ ' labels?: Record<string, string>;',
946
+ ' [key: `data-${string}`]: string | undefined;',
947
+ ' [key: `aria-${string}`]: string | number | undefined;',
948
+ '}',
949
+ 'export function Note(props: NoteProps) { return null; }',
950
+ ].join('\n'),
951
+ {
952
+ props: [
953
+ prop('status.type', "'error' | 'info'"),
954
+ prop('items[].label', 'number'),
955
+ prop('labels.open', 'string'),
956
+ prop('labels.close', 'number'),
957
+ prop('data-section', 'string'),
958
+ prop('data-count', 'number'),
959
+ prop('aria-busy', 'boolean'),
960
+ ],
961
+ },
962
+ );
963
+
964
+ const report = await compare([note]);
965
+
966
+ expect(kinds(report)).toEqual([
967
+ 'Note.aria-busy type_mismatch',
968
+ 'Note.data-count type_mismatch',
969
+ 'Note.items[].label type_mismatch',
970
+ 'Note.labels.close type_mismatch',
971
+ 'Note.status.type type_mismatch',
972
+ ]);
973
+ expect(report.typesCompared).toBe(7);
974
+ });
975
+
976
+ it('accepts an alias spelled out beside its name, and reports one whose spelled-out values are stale', async () => {
977
+ withTypeScript();
978
+ const links = ["'link' | 'token'", "'link' | 'token' | 'button'"].map(
979
+ (values, i) =>
980
+ component(
981
+ `Link${i}`,
982
+ `export type LinkVariant = ${values};\nexport function Link${i}(props: {variant?: LinkVariant; tone?: LinkVariant}) { return null; }`,
983
+ {
984
+ props: [
985
+ prop('variant', "LinkVariant = 'link' | 'token'"),
986
+ prop('tone', "LinkVariant ('link' | 'token')"),
987
+ ],
988
+ },
989
+ ),
990
+ );
991
+
992
+ expect(kinds(await compare(links))).toEqual([
993
+ 'Link1.tone type_mismatch',
994
+ 'Link1.variant type_mismatch',
995
+ ]);
996
+ });
997
+
998
+ it("reads an optional prop documented with `| undefined` as the code reads it, and names an alias's members in the source's order", async () => {
999
+ withTypeScript();
1000
+ const badge = component(
1001
+ 'Badge',
1002
+ [
1003
+ "type Tone = 'neutral' | 'info';",
1004
+ 'export function Badge(props: {tone?: Tone}) { return null; }',
1005
+ ].join('\n'),
1006
+ {props: [prop('tone', "'neutral' | 'info' | undefined")]},
1007
+ );
1008
+ const chip = component(
1009
+ 'Chip',
1010
+ "export function Chip(props: {tone?: 'a' | 'b' | undefined}) { return null; }\n",
1011
+ {props: [prop('tone', "'a' | 'c'")]},
1012
+ );
1013
+
1014
+ // The same literals, made first in another order, would set the
1015
+ // compiler's own order.
1016
+ const status = component(
1017
+ 'Status',
1018
+ [
1019
+ "type Other = 'detached' | 'attached' | 'tooltip';",
1020
+ 'export type Unrelated = Other;',
1021
+ "type StatusVariant = 'tooltip' | 'attached' | 'detached';",
1022
+ 'export function Status(props: {variant?: StatusVariant}) { return null; }',
1023
+ ].join('\n'),
1024
+ {props: [prop('variant', "'attached' | 'detached'")]},
1025
+ );
1026
+
1027
+ expect(kinds(await compare([badge]))).toEqual([]);
1028
+ // The optional prop's `undefined` the expansion sets aside is shown once.
1029
+ const [finding] = (await compare([chip])).findings;
1030
+ expect(finding.message).toMatch(/declares 'a' \| 'b' \| undefined\.$/);
1031
+ expect((await compare([status])).findings.map(f => f.message)).toEqual([
1032
+ `"variant" is documented as 'attached' | 'detached', but the code declares StatusVariant ('tooltip' | 'attached' | 'detached').`,
1033
+ ]);
1034
+ });
1035
+
1036
+ it('judges a className the package declares, and lists standard props and props from other packages as not compared', async () => {
1037
+ withTypeScript();
1038
+ const base = path.join(pkg, 'node_modules', '@acme', 'base');
1039
+ fs.mkdirSync(base, {recursive: true});
1040
+ fs.writeFileSync(
1041
+ path.join(base, 'package.json'),
1042
+ JSON.stringify({name: '@acme/base', types: 'index.d.ts'}),
1043
+ );
1044
+ fs.writeFileSync(
1045
+ path.join(base, 'index.d.ts'),
1046
+ 'export interface BaseProps { style?: object; id?: string; tone?: {level: number}; [key: `data-${string}`]: string | undefined }\n',
1047
+ );
1048
+ // A name only another package's index signature, or a mapped type's,
1049
+ // takes is not judged either.
1050
+ const card = component(
1051
+ 'Card',
1052
+ "import type {BaseProps} from '@acme/base';\nexport function Card(props: BaseProps & {className?: string} & Record<`aria-${string}`, string>) { return null; }\n",
1053
+ {
1054
+ props: [
1055
+ prop('className', 'number'),
1056
+ prop('style', 'string'),
1057
+ prop('id', 'number'),
1058
+ prop('tone.level', 'string'),
1059
+ prop('tone.missing', 'string'),
1060
+ prop('data-variant', "'solid' | 'outline'"),
1061
+ prop('aria-note', 'number'),
1062
+ ],
1063
+ },
1064
+ );
1065
+
1066
+ const report = await compare([card]);
1067
+
1068
+ expect(kinds(report)).toEqual([
1069
+ 'Card.className type_mismatch',
1070
+ 'Card.tone.missing not_in_code',
1071
+ ]);
1072
+ expect(report.typesCompared).toBe(1);
1073
+ expect(
1074
+ report.typesNotCompared.map(e => `${e.reason}: ${e.props.join(' ')}`),
1075
+ ).toEqual([
1076
+ 'declared outside the package, not compared: data-variant id tone.level',
1077
+ 'not a form the check judges exactly: aria-note',
1078
+ 'standard prop, not compared: style',
1079
+ ]);
1080
+ });
1081
+
1082
+ it('does not ask a doc for props from other packages, or for the props the authoring guidance skips', async () => {
1083
+ expect(PROPS_NOT_DOCUMENTED).toEqual([
1084
+ 'className',
1085
+ 'style',
1086
+ 'xstyle',
1087
+ 'data-testid',
1088
+ 'ref',
1089
+ 'key',
1090
+ ]);
1091
+ withTypeScript();
1092
+ const base = path.join(pkg, 'node_modules', '@acme', 'base');
1093
+ fs.mkdirSync(base, {recursive: true});
1094
+ fs.writeFileSync(
1095
+ path.join(base, 'package.json'),
1096
+ JSON.stringify({name: '@acme/base', types: 'index.d.ts'}),
1097
+ );
1098
+ fs.writeFileSync(
1099
+ path.join(base, 'index.d.ts'),
1100
+ [
1101
+ 'export interface BaseProps { id?: string; onBlur?: () => void }',
1102
+ "export type Sizes = Partial<Record<'sm' | 'md', string>>;",
1103
+ "export interface Spacing extends Partial<Record<'gap', number>> {}",
1104
+ "export type Tone = 'info' | 'danger';",
1105
+ 'export type Flags<K extends string> = {[P in K]?: boolean};',
1106
+ 'export type FC<P> = (props: P) => null;',
1107
+ "export type Responsive<T> = {[K in 'sm' | 'lg']?: T};",
1108
+ "export type Breakpoint = 'sm' | 'lg';",
1109
+ 'export declare const BREAKPOINTS: readonly Breakpoint[];',
1110
+ 'export declare function memo<T extends (p: any) => null>(c: T): {(p: Parameters<T>[0]): null; $$typeof: symbol; type: T};',
1111
+ 'export declare function forwardRef<P>(render: (props: P, ref: unknown) => null): (props: P) => null;',
1112
+ ].join('\n'),
1113
+ );
1114
+ const panel = component(
1115
+ 'Panel',
1116
+ [
1117
+ "import type {BaseProps} from '@acme/base';",
1118
+ 'export interface PanelProps extends BaseProps {',
1119
+ ' title?: string;',
1120
+ ' className?: string;',
1121
+ ' style?: {color?: string};',
1122
+ ' xstyle?: unknown;',
1123
+ " 'data-testid'?: string;",
1124
+ ' ref?: unknown;',
1125
+ ' key?: string;',
1126
+ ' /** @deprecated Use `title`. */',
1127
+ ' heading?: string;',
1128
+ ' /** @internal */',
1129
+ ' debugName?: string;',
1130
+ '}',
1131
+ 'export function Panel(props: PanelProps) { return null; }',
1132
+ ].join('\n'),
1133
+ {props: [prop('title', 'string'), prop('id', 'number')]},
1134
+ );
1135
+
1136
+ // A prop a mapped type builds is the package's own when its key traces
1137
+ // to the package's source: through aliases, `Exclude`, a generic's
1138
+ // arguments, and a component `memo` or `forwardRef` wraps. A key another
1139
+ // package defines, behind an alias or not, is that package's, and one
1140
+ // the check can't trace is listed, not asked for.
1141
+ const mapped = Object.entries({
1142
+ Styled:
1143
+ '(props: {[K in StyleKey]?: BaseProps[K]} & Partial<Record<StyleKey, number>>)',
1144
+ Inlined: '(props: {[K in keyof BaseProps]?: BaseProps[K]})',
1145
+ Spread: '(props: Responsive<number>)',
1146
+ Memoed: ' = memo(Inner)',
1147
+ Forwarded: ' = forwardRef(Impl)',
1148
+ Excluded: "(props: {[K in Exclude<'a' | 'b' | 'c', 'c'>]?: string})",
1149
+ Templated: "(props: {[K in `on${Capitalize<'open'>}`]?: () => void})",
1150
+ // Another package's keys through an own interface's property, an
1151
+ // `infer`, or a constant bound to its value stay that package's.
1152
+ Indexed: "(props: {[K in Opts['size']]?: number})",
1153
+ Inferred: '(props: {[K in KeysOf<Record<Breakpoint, 1>>]?: number})',
1154
+ Rebound: '(props: {[K in (typeof SIZES)[number]]?: number})',
1155
+ Inline: "(props: {[K in 'a' | 'b']?: string})",
1156
+ Recorded: "(props: Partial<Record<'a' | 'b', string>>)",
1157
+ Remapped: "(props: {[K in 'open' as `on${Capitalize<K>}`]?: () => void})",
1158
+ Toned:
1159
+ "(props: Partial<Record<Tone | 'xl', boolean>> & {[K in Tone]?: string} & Partial<Record<keyof BaseProps, string>> & {[K in keyof BaseProps as `x${Capitalize<K>}`]?: boolean})",
1160
+ Flagged: "(props: Flags<'bold'>)",
1161
+ Extended: '(props: ExtendedProps)',
1162
+ Sized: '(props: Spaced & Partial<Sizes>)',
1163
+ }).map(([name, props]) =>
1164
+ component(
1165
+ name,
1166
+ [
1167
+ "import {type BaseProps, type Sizes, type Spacing, type Tone, type Flags, type FC, type Responsive, type Breakpoint, BREAKPOINTS, memo, forwardRef} from '@acme/base';",
1168
+ "interface ExtendedProps extends Partial<Record<'a', string>> {}",
1169
+ 'interface Spaced extends Spacing {}',
1170
+ 'type StyleKey = keyof BaseProps;',
1171
+ 'interface Opts { size: Breakpoint }',
1172
+ 'type KeysOf<T> = T extends Record<infer K, unknown> ? K : never;',
1173
+ 'const SIZES = BREAKPOINTS;',
1174
+ "function Inner(props: {[K in 'top' | 'bottom']?: number}) { return null; }",
1175
+ "function Impl(props: Partial<Record<'left', number>>, ref: unknown) { return null; }",
1176
+ props.startsWith(' =')
1177
+ ? `export const ${name}${props};`
1178
+ : `export function ${name}${props} { return null; }`,
1179
+ `export const Typed: FC<Partial<Record<'a', string>>> = () => null;`,
1180
+ ].join('\n'),
1181
+ {props: []},
1182
+ ),
1183
+ );
1184
+
1185
+ // A deprecated prop is still a prop the component accepts.
1186
+ const typed = {...mapped[0], name: 'Typed'};
1187
+ const report = await compare([panel, ...mapped, typed]);
1188
+ expect(kinds(report)).toEqual([
1189
+ 'Excluded.a not_in_doc',
1190
+ 'Excluded.b not_in_doc',
1191
+ 'Extended.a not_in_doc',
1192
+ 'Flagged.bold not_in_doc',
1193
+ 'Forwarded.left not_in_doc',
1194
+ 'Inline.a not_in_doc',
1195
+ 'Inline.b not_in_doc',
1196
+ 'Memoed.bottom not_in_doc',
1197
+ 'Memoed.top not_in_doc',
1198
+ 'Panel.heading not_in_doc',
1199
+ 'Recorded.a not_in_doc',
1200
+ 'Recorded.b not_in_doc',
1201
+ 'Remapped.onOpen not_in_doc',
1202
+ 'Toned.xl not_in_doc',
1203
+ 'Typed.a not_in_doc',
1204
+ ]);
1205
+ expect(report.propsNotChecked).toEqual([
1206
+ expect.objectContaining({component: 'Templated', props: ['onOpen']}),
1207
+ expect.objectContaining({component: 'Inferred', props: ['lg', 'sm']}),
1208
+ ]);
1209
+ // The alias and the inline form give the same answer: nothing asked.
1210
+ for (const name of ['Styled', 'Inlined']) {
1211
+ expect(kinds(report).filter(kind => kind.startsWith(name))).toEqual([]);
1212
+ }
1213
+ });
1214
+
1215
+ it('reads every overload, one without props included, matches a doc that describes one member of a discriminated union, reads a prop only some members require as optional, and holds every prop one entry names to its `required`', async () => {
164
1216
  withTypeScript();
165
1217
  const picker = component(
166
1218
  'Picker',
@@ -1159,6 +2211,23 @@ export const Hoc = withName((props: {label?: string}) => null);`;
1159
2211
  ]);
1160
2212
  });
1161
2213
 
2214
+ it("compares with TypeScript 7's TypeScript 6 API package when the project has one", async () => {
2215
+ const badge = component(
2216
+ 'Badge',
2217
+ 'export function Badge(props: {label: string}) { return null; }\n',
2218
+ {props: [prop('label', 'number')]},
2219
+ );
2220
+ withTypeScript7AndItsTypeScript6Api();
2221
+
2222
+ const report = await compare([badge]);
2223
+
2224
+ expect(report.status).toBe('checked');
2225
+ // The comparison ran: the documented `number` is judged against `string`.
2226
+ expect(
2227
+ report.findings.map(f => `${f.component}.${f.prop} ${f.kind}`),
2228
+ ).toContain('Badge.label type_mismatch');
2229
+ });
2230
+
1162
2231
  it('skips with a reason, and compares nothing, without a TypeScript it can use', async () => {
1163
2232
  const badge = component(
1164
2233
  'Badge',
@@ -1169,11 +2238,14 @@ export const Hoc = withName((props: {label?: string}) => null);`;
1169
2238
  status: 'skipped',
1170
2239
  reason,
1171
2240
  components: 0,
2241
+ typesCompared: 0,
1172
2242
  findings: [],
1173
2243
  unchecked: [],
2244
+ typesNotCompared: [],
1174
2245
  });
1175
2246
 
1176
2247
  expect(await compare([badge])).toEqual(skipped(TYPESCRIPT_MISSING_REASON));
2248
+ expect(TYPESCRIPT_MISSING_REASON).toContain('npm install -D typescript@6');
1177
2249
  // TypeScript 7 has no JavaScript compiler API to load.
1178
2250
  const dir = path.join(pkg, 'node_modules', 'typescript');
1179
2251
  fs.mkdirSync(dir, {recursive: true});
@@ -1185,7 +2257,10 @@ export const Hoc = withName((props: {label?: string}) => null);`;
1185
2257
  exports: {'./package.json': './package.json'},
1186
2258
  }),
1187
2259
  );
1188
- expect(await compare([badge])).toEqual(
2260
+ const report = await compare([badge]);
2261
+ expect(report.reason).toContain('TypeScript 7.0.0');
2262
+ expect(report.reason).toContain('npm install -D @typescript/typescript6');
2263
+ expect(report).toEqual(
1189
2264
  skipped(
1190
2265
  unusableTypeScriptReason(
1191
2266
  '7.0.0',