@stateward/plugin-errors 1.2.2 → 1.3.1

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 (54) hide show
  1. package/README.md +9 -8
  2. package/dist/catch-hides-unexpected.d.ts +4 -1
  3. package/dist/catch-hides-unexpected.js +12 -5
  4. package/dist/catch-misses-error.d.ts +1 -1
  5. package/dist/catch-misses-error.js +7 -4
  6. package/dist/finally-can-throw.js +3 -3
  7. package/dist/hover.js +6 -9
  8. package/dist/index.d.ts +3 -1
  9. package/dist/index.js +1 -0
  10. package/dist/inference/analysis.d.ts +109 -0
  11. package/dist/inference/analysis.js +170 -0
  12. package/dist/inference/builtins.d.ts +0 -2
  13. package/dist/inference/builtins.js +0 -33
  14. package/dist/inference/deps.d.ts +13 -2
  15. package/dist/inference/deps.js +24 -13
  16. package/dist/inference/needs.d.ts +16 -0
  17. package/dist/inference/needs.js +27 -0
  18. package/dist/inference/packages.d.ts +24 -32
  19. package/dist/inference/packages.js +156 -680
  20. package/dist/inference/project.d.ts +4 -4
  21. package/dist/inference/project.js +6 -17
  22. package/dist/inference/solve.d.ts +29 -4
  23. package/dist/inference/solve.js +42 -12
  24. package/dist/inference/summarize.d.ts +27 -15
  25. package/dist/inference/summarize.js +247 -130
  26. package/dist/inference/summary.d.ts +41 -5
  27. package/dist/inference/summary.js +84 -12
  28. package/dist/inference/unreachable.d.ts +5 -0
  29. package/dist/inference/unreachable.js +160 -0
  30. package/dist/inlay.d.ts +1 -5
  31. package/dist/inlay.js +1 -12
  32. package/dist/must-handle-error.d.ts +4 -3
  33. package/dist/must-handle-error.js +10 -13
  34. package/dist/plugin.d.ts +12 -2
  35. package/dist/plugin.js +4 -2
  36. package/dist/react/boundaries.d.ts +9 -7
  37. package/dist/react/boundaries.js +16 -24
  38. package/dist/react/tree.js +8 -4
  39. package/dist/refactors.js +1 -1
  40. package/dist/render-throw-without-boundary.d.ts +13 -4
  41. package/dist/render-throw-without-boundary.js +4 -2
  42. package/dist/result-ignored.d.ts +4 -1
  43. package/dist/result-type.js +2 -2
  44. package/dist/result-unchecked.d.ts +4 -1
  45. package/dist/result-unchecked.js +139 -61
  46. package/dist/rules.meta.d.ts +26 -14
  47. package/dist/rules.meta.js +18 -14
  48. package/dist/syntax.d.ts +0 -13
  49. package/dist/syntax.js +0 -79
  50. package/dist/text.d.ts +5 -2
  51. package/dist/text.js +11 -5
  52. package/dist/throws-doc-mismatch.d.ts +2 -2
  53. package/dist/throws-doc-mismatch.js +13 -5
  54. package/package.json +2 -2
@@ -1,237 +1,25 @@
1
- import { createHash } from "node:crypto";
2
- import { readFileSync, readdirSync, statSync } from "node:fs";
3
- import path from "node:path";
4
1
  import ts from "@stateward/core/typescript";
5
- import { findPackageRoot, openPackageSource, packageCodeId, readPackageCache, reparsedWithJsDoc, writePackageCache, } from "@stateward/core";
2
+ import { WILDCARD, factKeyOf, factLineOf, factSideOf, packageVersionOf, pathOf, } from "@stateward/core";
6
3
  import { BUILTIN_ERRORS, builtinId, isBuiltin } from "./builtins.js";
7
- import { solveFunctions } from "./solve.js";
8
- import { REASON, packageClassId, summarizeThrows } from "./summarize.js";
9
- import { readClass } from "./summary.js";
4
+ import { packageClassId } from "./summarize.js";
5
+ import { UNKNOWN_REASONS } from "./summary.js";
10
6
  /**
11
- * Library facts for the Errors pack: what a call into a
12
- * package throws, from the first source that answers:
7
+ * Library facts for the Errors pack: what a call into a package throws, from its contract only
8
+ * (0041), from the first source that answers:
13
9
  *
14
10
  * 1. the project's config (`facts`);
15
- * 2. curated fact files shipped with stateward (`curatedFacts` answers nothing yet);
16
- * 3. `@throws {X}` on the called declaration in the package's `.d.ts`;
17
- * 4. inferred from the package's JavaScript, with the summarizer of the project's own code, from
18
- * the called function to what it calls in the package (bounded), cached globally;
19
- * 5. unknown, with one of the reasons below.
20
- */
21
- /** Why a package's function is not (fully) known: fixed strings, shown as they are. */
22
- export const UNKNOWN_REASONS = [
23
- // The package as a whole cannot be read.
24
- "no readable source",
25
- "not found in its source",
26
- "native addon",
27
- "minified",
28
- "eval",
29
- "dynamic require",
30
- "too large to follow",
31
- // Read, but part of what the function does cannot be followed.
32
- "untyped @throws",
33
- "calls a callback",
34
- "calls code it cannot see",
35
- "dynamic call",
36
- "throws a value of unknown class",
37
- "awaits a promise it cannot follow",
38
- ];
39
- /**
40
- * At most this many functions are read per package function asked for.
41
- * The bounds count, never time: a verdict by time would differ between machines.
11
+ * 2. the facts the loaded packs ship (`Plugin.facts`);
12
+ * 3. else unknown: "its errors are not stated", with a hint that gives the `facts` line.
13
+ *
14
+ * A line names the call when its key resolves to the called declaration (`factLineOf`). The
15
+ * package's code and the doc comments of its declarations are never read.
42
16
  */
43
- export const MAX_FUNCTIONS = 200;
44
- /** A package whose entry reaches more files than this is not parsed further. */
45
- const MAX_FILES = 500;
46
- /** Folder entries looked at for a native addon (`.node`, `binding.gyp`). */
47
- const MAX_SCANNED = 5000;
48
- /** Average line length above which a file is minified. */
49
- const MINIFIED_LINE = 500;
17
+ export { UNKNOWN_REASONS };
50
18
  const NOTHING = { classes: [], unknown: [] };
51
- function isRecord(value) {
52
- return typeof value === "object" && value !== null && !Array.isArray(value);
53
- }
54
- function sha1(text) {
55
- return createHash("sha1").update(text).digest("hex");
56
- }
57
- /** The folder of the installed package a file in node_modules belongs to. */
58
- function installedRoot(file) {
59
- const marker = "/node_modules/";
60
- const at = file.lastIndexOf(marker);
61
- if (at < 0)
62
- return undefined;
63
- const parts = file.slice(at + marker.length).split("/");
64
- const [first = "", second = ""] = parts;
65
- const name = first.startsWith("@") ? `${first}/${second}` : first;
66
- return { root: `${file.slice(0, at + marker.length)}${name}`, name };
67
- }
68
- /**
69
- * What this process read of each package's package.json, with the file's size and time when it
70
- * was read: a package upgraded or reinstalled while the process runs (a language server) is read
71
- * again, and its new content hash keys every cache below, so no old fact is served for it.
72
- */
73
- const infos = new Map();
74
- let codeId;
75
- /** The size and time of a file, to tell a changed one; "" when it cannot be read. */
76
- function stampOf(file) {
77
- try {
78
- const stats = statSync(file);
79
- return `${String(stats.size)}:${String(stats.mtimeMs)}`;
80
- }
81
- catch {
82
- return "";
83
- }
84
- }
85
- /**
86
- * The package at `root`, from its package.json. `checked` holds what this resolver already read,
87
- * so a package.json is looked at (one stat) once per file summarized, not once per call.
88
- */
89
- function readInfo(name, root, checked) {
90
- if (checked.has(root))
91
- return checked.get(root);
92
- const manifestFile = path.join(root, "package.json");
93
- const stamp = stampOf(manifestFile);
94
- const known = infos.get(root);
95
- if (known?.stamp === stamp) {
96
- checked.set(root, known.info);
97
- return known.info;
98
- }
99
- let info;
100
- try {
101
- const text = readFileSync(manifestFile, "utf8");
102
- const parsed = JSON.parse(text);
103
- const manifest = isRecord(parsed) ? parsed : {};
104
- const version = typeof manifest.version === "string" ? manifest.version : "";
105
- codeId ??= packageCodeId(import.meta.url);
106
- info = {
107
- name,
108
- root,
109
- version,
110
- manifest,
111
- key: { name, version, integrity: sha1(text), implementation: codeId },
112
- };
113
- }
114
- catch {
115
- info = undefined;
116
- }
117
- infos.set(root, { stamp, info });
118
- checked.set(root, info);
119
- return info;
120
- }
121
- /** The per-process caches' key of a package: its folder and its package.json's content. */
122
- function packageKey(info) {
123
- return `${info.root}\u0000${info.key.integrity}`;
124
- }
125
- /** The package whose JavaScript a call reaches: next to its declaration, or found by name. */
126
- function packageOf(call, from, checked) {
127
- const installed = installedRoot(call.file.replaceAll("\\", "/"));
128
- if (installed?.name === call.name)
129
- return readInfo(call.name, installed.root, checked);
130
- // `@types/x`, a linked package, or `declare module "x"` in the project: the package by its
131
- // name, as Node finds it from the calling file (a package manager's store keeps `@types/x`
132
- // away from `x`), else from the declaration.
133
- const root = findPackageRoot(path.dirname(from), call.name) ??
134
- findPackageRoot(path.dirname(installed?.root ?? call.file), call.name);
135
- return root === undefined ? undefined : readInfo(call.name, root, checked);
136
- }
137
- const JAVASCRIPT_EXTENSIONS = [".js", ".mjs", ".cjs"];
138
- function existingFile(file) {
139
- const candidates = [
140
- file,
141
- ...JAVASCRIPT_EXTENSIONS.map((extension) => `${file}${extension}`),
142
- ...JAVASCRIPT_EXTENSIONS.map((extension) => path.join(file, `index${extension}`)),
143
- ];
144
- return candidates.find((candidate) => {
145
- try {
146
- return readdirSync(path.dirname(candidate)).includes(path.basename(candidate));
147
- }
148
- catch {
149
- return false;
150
- }
151
- });
152
- }
153
- /** The first file an `exports` value names for `import`, `default`, `require` or `node`. */
154
- function exportTarget(value) {
155
- if (typeof value === "string")
156
- return value;
157
- if (!isRecord(value))
158
- return undefined;
159
- for (const key of [".", "import", "default", "require", "node"]) {
160
- const found = exportTarget(value[key]);
161
- if (found !== undefined)
162
- return found;
163
- }
164
- return undefined;
165
- }
166
- /** The JavaScript file a declaration file describes: its sibling, else the package's entry. */
167
- function entryOf(declarationFile, info) {
168
- const file = declarationFile.replaceAll("\\", "/");
169
- if (file.startsWith(`${info.root}/`)) {
170
- const stem = file.replace(/\.d\.[mc]?ts$/, "");
171
- const sibling = JAVASCRIPT_EXTENSIONS.map((extension) => `${stem}${extension}`).find((candidate) => existingFile(candidate) === candidate);
172
- if (sibling !== undefined)
173
- return sibling;
174
- }
175
- const { manifest } = info;
176
- const named = exportTarget(manifest.exports) ??
177
- (typeof manifest.module === "string" ? manifest.module : undefined) ??
178
- (typeof manifest.main === "string" ? manifest.main : undefined) ??
179
- "index.js";
180
- return existingFile(path.join(info.root, named));
181
- }
182
- // ---- the called declaration ---------------------------------------------------------------------
183
- function declarationName(node) {
184
- if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) {
185
- if (node.name !== undefined)
186
- return node.name.text;
187
- return node.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) === true
188
- ? "default"
189
- : undefined;
190
- }
191
- if (ts.isExportAssignment(node))
192
- return "default";
193
- if (ts.isModuleDeclaration(node))
194
- return ts.isIdentifier(node.name) ? node.name.text : undefined;
195
- if (ts.isMethodDeclaration(node) ||
196
- ts.isMethodSignature(node) ||
197
- ts.isPropertyDeclaration(node) ||
198
- ts.isPropertySignature(node) ||
199
- ts.isVariableDeclaration(node) ||
200
- ts.isInterfaceDeclaration(node)) {
201
- return ts.isIdentifier(node.name) ? node.name.text : undefined;
202
- }
203
- return undefined;
204
- }
205
- /** The declaration's path in the package's types: `["Client", "get"]`. */
206
- export function pathOf(node) {
207
- const names = [];
208
- for (let at = node; !ts.isSourceFile(at); at = at.parent) {
209
- const name = declarationName(at);
210
- if (name !== undefined)
211
- names.unshift(name);
212
- }
213
- return names;
214
- }
215
- /** Whether the declaration says it returns a promise: its facts are what the promise rejects with. */
216
- function returnsPromise(node) {
217
- let type;
218
- if (ts.isFunctionDeclaration(node) ||
219
- ts.isMethodDeclaration(node) ||
220
- ts.isMethodSignature(node)) {
221
- type = node.type;
222
- }
223
- else if ((ts.isVariableDeclaration(node) ||
224
- ts.isPropertySignature(node) ||
225
- ts.isPropertyDeclaration(node)) &&
226
- node.type !== undefined &&
227
- ts.isFunctionTypeNode(node.type)) {
228
- type = node.type.type;
229
- }
230
- return (type !== undefined &&
231
- ts.isTypeReferenceNode(type) &&
232
- ts.isIdentifier(type.typeName) &&
233
- (type.typeName.text === "Promise" || type.typeName.text === "PromiseLike"));
234
- }
19
+ /** The reason a call into a package with no line, or none of the kind it needs, is unknown. */
20
+ const NOT_STATED = "its errors are not stated";
21
+ /** The reason a promise is unknown when its call's line states `throws` and no `rejects`. */
22
+ const REJECTS_NOT_STATED = "its `facts` line states no `rejects`, the kind its promise needs";
235
23
  /** A class a fact names: a built-in error, or the package's own class. */
236
24
  function classIdOf(packageName, name) {
237
25
  return BUILTIN_ERRORS.has(name) ? builtinId(name) : packageClassId(packageName, name);
@@ -239,491 +27,179 @@ function classIdOf(packageName, name) {
239
27
  function side(classes, unknown = []) {
240
28
  return { classes: [...new Set(classes)].sort(), unknown: [...new Set(unknown)].sort() };
241
29
  }
242
- function onSide(set, promise) {
243
- return promise ? { throws: NOTHING, rejects: set } : { throws: set, rejects: NOTHING };
244
- }
245
- // ---- 1. config ----------------------------------------------------------------------------------
246
- function configured(entry, packageName, promise) {
247
- const named = (list) => (list ?? []).map((name) => classIdOf(packageName, name));
248
- const thrown = side(named(entry.throws));
249
- const rejected = side(named(entry.rejects));
250
- // A promise's function "throws" what its promise rejects with, as a developer says it.
251
- return promise
252
- ? { throws: NOTHING, rejects: side([...thrown.classes, ...rejected.classes]) }
253
- : { throws: thrown, rejects: rejected };
254
- }
255
- // ---- 2. curated ---------------------------------------------------------------------------
256
30
  /**
257
- * Curated fact files shipped with stateward: none ship yet, so nothing answers between the config
258
- * and the declarations. Reading `facts/<package>@<major>.json` here would add the `curated`
259
- * source, and the resolver would ask it after the config.
31
+ * What a line says of a call. Kinds are strict: `throws` is what the call throws synchronously,
32
+ * `rejects` what the promise it returns rejects with. The kind the call needs (`rejects` for a
33
+ * call whose value is a promise, `throws` otherwise) is not stated when the line leaves it out,
34
+ * so a line of the other kind never settles the call. A call that returns no promise rejects with
35
+ * nothing.
260
36
  */
261
- export function curatedFacts() {
262
- return undefined;
263
- }
264
- // ---- 3. declared --------------------------------------------------------------------------------
265
- function sameNode(root, target) {
266
- if (root.pos === target.pos && root.end === target.end && root.kind === target.kind)
267
- return root;
268
- return ts.forEachChild(root, (child) => child.pos <= target.pos && target.end <= child.end ? sameNode(child, target) : undefined);
269
- }
270
- /** `@throws {X}` on the called declaration in the package's types, or undefined without a tag. */
271
- function declared(call) {
272
- const reparsed = reparsedWithJsDoc(call.node.getSourceFile());
273
- const node = sameNode(reparsed, call.node);
274
- if (node === undefined)
275
- return undefined;
276
- const tags = ts.getJSDocTags(node).filter(ts.isJSDocThrowsTag);
277
- if (tags.length === 0)
278
- return undefined;
279
- const classes = [];
280
- const unknown = [];
281
- const add = (type) => {
282
- if (ts.isParenthesizedTypeNode(type))
283
- add(type.type);
284
- else if (ts.isUnionTypeNode(type))
285
- for (const member of type.types)
286
- add(member);
287
- else if (type.kind === ts.SyntaxKind.NeverKeyword)
288
- return;
289
- else if (ts.isTypeReferenceNode(type)) {
290
- const name = ts.isIdentifier(type.typeName) ? type.typeName : type.typeName.right;
291
- classes.push(classIdOf(call.name, name.text));
292
- }
293
- else
294
- unknown.push("untyped @throws");
295
- };
296
- for (const tag of tags) {
297
- const type = tag.typeExpression?.type;
298
- if (type === undefined)
299
- unknown.push("untyped @throws");
300
- else
301
- add(type);
302
- }
303
- return onSide(side(classes, unknown), returnsPromise(node));
304
- }
305
- // ---- 4. inferred --------------------------------------------------------------------------------
306
- /** What makes a package's code not open to read, file by file. */
307
- function unreadable(sourceFile) {
308
- const text = sourceFile.text;
309
- const lines = text.split("\n").length;
310
- if (text.length / lines > MINIFIED_LINE)
311
- return "minified";
312
- let names = 0;
313
- let short = 0;
314
- let found;
315
- const isLiteral = (node) => node !== undefined && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node));
316
- const visit = (node) => {
317
- if (found !== undefined)
318
- return;
319
- if ((ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isFunctionDeclaration(node)) &&
320
- node.name !== undefined &&
321
- ts.isIdentifier(node.name)) {
322
- names++;
323
- if (node.name.text.length <= 2)
324
- short++;
325
- }
326
- if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
327
- const callee = node.expression;
328
- if (ts.isIdentifier(callee) && (callee.text === "eval" || callee.text === "Function")) {
329
- found = "eval";
330
- return;
331
- }
332
- const dynamicRequire = ts.isIdentifier(callee) && callee.text === "require";
333
- const dynamicImport = callee.kind === ts.SyntaxKind.ImportKeyword;
334
- if ((dynamicRequire || dynamicImport) && !isLiteral(node.arguments?.[0])) {
335
- found = "dynamic require";
336
- return;
337
- }
338
- }
339
- ts.forEachChild(node, visit);
340
- };
341
- visit(sourceFile);
342
- // Mostly one- and two-letter names: a minifier renamed them.
343
- if (names >= 20 && short * 2 > names)
344
- return "minified";
345
- return found;
346
- }
347
- const natives = new Map();
348
- /** Every entry under `dir`, relative; none when it cannot be read. */
349
- function listed(dir) {
350
- try {
351
- return readdirSync(dir, { recursive: true, encoding: "utf8" });
352
- }
353
- catch {
354
- return [];
355
- }
356
- }
357
- /** Whether the package ships a native addon (a `.node` file or a `binding.gyp`). */
358
- function hasNativeAddon(info) {
359
- const known = natives.get(packageKey(info));
360
- if (known !== undefined)
361
- return known;
362
- const entries = listed(info.root).slice(0, MAX_SCANNED);
363
- const found = entries.some((entry) => !entry.split(path.sep).includes("node_modules") &&
364
- (entry.endsWith(".node") || path.basename(entry) === "binding.gyp"));
365
- natives.set(packageKey(info), found);
366
- return found;
37
+ function configured(entry, packageName, promise) {
38
+ const named = (list) => list === undefined
39
+ ? side([], [NOT_STATED])
40
+ : side(list.map((name) => classIdOf(packageName, name)));
41
+ if (!promise)
42
+ return { throws: named(entry.throws), rejects: NOTHING };
43
+ const rejects = entry.rejects === undefined && entry.throws !== undefined
44
+ ? side([], [REJECTS_NOT_STATED])
45
+ : named(entry.rejects);
46
+ return { throws: side(named(entry.throws ?? []).classes), rejects };
367
47
  }
368
48
  /**
369
- * Package sources by package (root and content) and entry, most recently used last. Each holds a
370
- * program with its type checker, so only the last few stay open: what was inferred from them is
371
- * kept in `memo`, and a package needed again is opened again (it rarely is: a project's calls
372
- * into one package are mostly answered from `memo`).
49
+ * The error classes a table states a parent of (`extends`), from `named` up through their parents
50
+ * in the same table, so a reader can follow them: the config's line for a class wins. A class
51
+ * without such a line is left out, so it stays open.
373
52
  */
374
- const opened = new Map();
375
- /** How many package sources stay open at once. */
376
- const OPEN_PACKAGES = 4;
377
- function open(info, entry) {
378
- const key = `${packageKey(info)}\u0000${entry}`;
379
- const known = opened.get(key);
380
- if (known !== undefined) {
381
- opened.delete(key);
382
- opened.set(key, known);
383
- return known;
384
- }
385
- const source = openPackageSource(info.root, entry);
386
- let verdict;
387
- if (hasNativeAddon(info))
388
- verdict = "native addon";
389
- else if (source.files.length > MAX_FILES)
390
- verdict = "too large to follow";
391
- else {
392
- for (const file of source.files) {
393
- const sourceFile = source.sourceFile(file);
394
- verdict = sourceFile === undefined ? undefined : unreadable(sourceFile);
395
- if (verdict !== undefined)
396
- break;
397
- }
398
- }
399
- const made = { source, verdict, summaries: new Map() };
400
- opened.set(key, made);
401
- for (const oldest of opened.keys()) {
402
- if (opened.size <= OPEN_PACKAGES)
403
- break;
404
- opened.delete(oldest);
405
- }
406
- return made;
407
- }
408
- function summaryOf(state, file) {
409
- const known = state.summaries.get(file);
410
- if (known !== undefined)
411
- return known;
412
- const sourceFile = state.source.sourceFile(file);
413
- if (sourceFile === undefined)
414
- return undefined;
415
- const ctx = {
416
- file,
417
- options: {},
418
- sourceFile,
419
- types: state.source.types,
420
- addons: [],
421
- facts: {},
422
- shippedFacts: {},
423
- // A package's code has no stated declarations of the project: nothing to mark.
424
- ledger: [],
425
- read() {
426
- // Nothing is listed, so nothing is marked.
427
- },
428
- report() {
429
- // A package's source is read for facts, never reported on.
430
- },
431
- unknown() {
432
- // As above.
433
- },
434
- };
435
- const summary = summarizeThrows(ctx);
436
- state.summaries.set(file, summary);
437
- return summary;
438
- }
439
- function callIds(effects, into) {
440
- for (const effect of effects) {
441
- if (effect.k === "call")
442
- into.push(effect.id);
443
- else if (effect.k === "try") {
444
- callIds(effect.body, into);
445
- callIds(effect.fin, into);
446
- const handler = effect.handler;
447
- if (handler !== null) {
448
- callIds(handler.pre, into);
449
- for (const branch of handler.branches)
450
- callIds(branch.body, into);
451
- callIds(handler.otherwise ?? [], into);
452
- callIds(handler.after, into);
453
- }
454
- }
455
- }
456
- }
457
- /** Why part of a function read from source is unknown, as one of the fixed reasons. */
458
- function reasonOf(source) {
459
- switch (source.reason) {
460
- case REASON.callback:
461
- return "calls a callback";
462
- case REASON.dynamic:
463
- return "dynamic call";
464
- case REASON.promise:
465
- return "awaits a promise it cannot follow";
466
- case REASON.thrownValue:
467
- case REASON.madeError:
468
- return "throws a value of unknown class";
469
- default:
470
- return source.reason.includes("@throws") ? "untyped @throws" : "calls code it cannot see";
471
- }
472
- }
473
- /** Reads the function at `names` in the package's source, within the bounds. */
474
- function inferFrom(info, entry, names) {
475
- const state = open(info, entry);
476
- if (state.verdict !== undefined) {
477
- return { kind: "unknown", reason: state.verdict };
478
- }
479
- const notFound = { kind: "unknown", reason: "not found in its source" };
480
- const target = state.source.exported(entry, names);
481
- if (target === undefined)
482
- return notFound;
483
- const tooLarge = { kind: "unknown", reason: "too large to follow" };
484
- const functions = new Map();
485
- const classes = new Map();
486
- const files = new Set(state.source.files);
487
- const queue = [target.id];
488
- for (let id = queue.shift(); id !== undefined; id = queue.shift()) {
489
- if (functions.has(id))
53
+ function statedClasses(own, shipped, packageName, named) {
54
+ const lineOf = (name) => own?.[name]?.extends ?? (own?.[name] === undefined ? shipped?.[name]?.extends : undefined);
55
+ const found = new Map();
56
+ const queue = [...named];
57
+ for (let name = queue.shift(); name !== undefined; name = queue.shift()) {
58
+ const id = classIdOf(packageName, name);
59
+ const parent = lineOf(name);
60
+ if (found.has(id) || isBuiltin(id) || parent === undefined)
490
61
  continue;
491
- const file = path.join(info.root, id.slice(0, id.indexOf("#")));
492
- const summary = files.has(file.replaceAll("\\", "/")) ? summaryOf(state, file) : undefined;
493
- const fact = summary?.functions.find((one) => one.id === id);
494
- if (summary === undefined || fact === undefined)
495
- continue;
496
- functions.set(id, { file, fact });
497
- for (const one of summary.classes)
498
- classes.set(one.id, one);
499
- if (functions.size > MAX_FUNCTIONS)
500
- return tooLarge;
501
- const called = [];
502
- callIds(fact.body, called);
503
- callIds(fact.returns, called);
504
- queue.push(...called);
62
+ found.set(id, {
63
+ id,
64
+ name,
65
+ parent: classIdOf(packageName, parent),
66
+ open: false,
67
+ fields: [],
68
+ });
69
+ queue.push(parent);
505
70
  }
506
- const result = solveFunctions(functions, classes).get(target.id);
507
- if (result === undefined)
508
- return notFound;
509
- const mapped = (id) => isBuiltin(id)
510
- ? id
511
- : packageClassId(info.name, classes.get(id)?.name ?? id.slice(id.indexOf("#") + 1));
512
- const sideOf = (thrown) => side([...thrown.classes.keys()].map(mapped), [
513
- ...thrown.unknowns.map(reasonOf),
514
- ...(thrown.more ? ["calls code it cannot see"] : []),
515
- ]);
516
- const facts = [...classes.values()]
517
- .map((one) => ({
518
- id: mapped(one.id),
519
- name: one.name,
520
- parent: one.parent === null ? null : mapped(one.parent),
521
- open: one.open,
522
- }))
523
- .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
524
- return {
525
- kind: "known",
526
- sides: { throws: sideOf(result.throws), rejects: sideOf(result.rejects) },
527
- classes: facts,
528
- };
529
- }
530
- // ---- the global cache ---------------------------------------------------------------------------
531
- let inferences = 0;
532
- let cacheHits = 0;
533
- /** What this process computed and read back, for tests: inference runs and global-cache hits. */
534
- export function packageFactsStats() {
535
- return { inferences, cacheHits };
536
- }
537
- /** Forgets what this process knows about packages (tests: the next run reads the global cache). */
538
- export function forgetPackageFacts() {
539
- infos.clear();
540
- opened.clear();
541
- natives.clear();
542
- memo.clear();
543
- entries.clear();
544
- verified.clear();
71
+ return [...found.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
545
72
  }
546
- /** Inferred facts by package (root and content), entry and function, for this process. */
547
- const memo = new Map();
548
- /** The global cache's entry of each package (root and content), read once per process. */
549
- const entries = new Map();
550
- /** Whether the files behind a cached digest still hold what they held, by root and digest. */
551
- const verified = new Map();
552
73
  /**
553
- * The files inference read, by path relative to the package, with a hash of each; and one digest
554
- * of them all. A package.json says nothing of a linked workspace package's source, or of a
555
- * patched file in node_modules, so each inferred entry carries the digest of the files it was
556
- * inferred from, and a file that no longer matches makes the entry a miss.
74
+ * The classes of a table whose lines say `inheritedFacts: false` (TypeORM's `MongoRepository`):
75
+ * a call on one of them, or on a class that extends one, of a method it inherits takes none of
76
+ * the declaring class's facts.
557
77
  */
558
- function sourcesOf(info, files) {
559
- const hashes = {};
560
- for (const file of files) {
561
- const relative = path.relative(info.root, file).replaceAll("\\", "/");
562
- hashes[relative] = fileHash(file) ?? "";
563
- }
564
- const lines = Object.keys(hashes)
565
- .sort()
566
- .map((relative) => `${relative} ${hashes[relative] ?? ""}`);
567
- return { digest: sha1(lines.join("\n")), hashes };
78
+ function closedClasses(table) {
79
+ return new Set(Object.entries(table).flatMap(([name, line]) => (line.inheritedFacts === false ? [name] : [])));
568
80
  }
569
- function fileHash(file) {
570
- try {
571
- return createHash("sha1").update(readFileSync(file)).digest("hex");
572
- }
573
- catch {
81
+ /**
82
+ * The line of `facts` for a call: the one whose key resolves to the called declaration, unless
83
+ * the call's receiver is, or extends, a class of the same module whose line says
84
+ * `inheritedFacts: false`: then that class's own line for the method (`MongoRepository.save`), or
85
+ * for every method (`MongoRepository.*`), or none.
86
+ */
87
+ function lineFor(types, facts, call) {
88
+ const found = factLineOf(types, facts, call.node, receiverOf(call));
89
+ if (found === undefined)
574
90
  return undefined;
575
- }
576
- }
577
- /** Whether every file a cached digest lists still has the hash it had. */
578
- function stillTheSame(info, digest, cached) {
579
- const key = `${packageKey(info)}\u0000${digest}`;
580
- const known = verified.get(key);
581
- if (known !== undefined)
582
- return known;
583
- const hashes = fieldsOf(cached.get(`sources ${digest}`));
584
- const same = hashes !== undefined &&
585
- Object.entries(hashes).every(([relative, hash]) => typeof hash === "string" && fileHash(path.join(info.root, relative)) === hash);
586
- verified.set(key, same);
587
- return same;
588
- }
589
- /** An entry of the global cache; `sources`: the digest of the files it was inferred from. */
590
- function toJson(inferred, sources) {
591
- return inferred.kind === "unknown"
592
- ? { unknown: inferred.reason, sources }
593
- : {
594
- sources,
595
- throws: { classes: inferred.sides.throws.classes, unknown: inferred.sides.throws.unknown },
596
- rejects: {
597
- classes: inferred.sides.rejects.classes,
598
- unknown: inferred.sides.rejects.unknown,
599
- },
600
- classes: inferred.classes.map((one) => ({ ...one })),
601
- };
602
- }
603
- function isReason(value) {
604
- return UNKNOWN_REASONS.some((reason) => reason === value);
605
- }
606
- function isList(value) {
607
- return Array.isArray(value);
608
- }
609
- function fieldsOf(value) {
610
- if (value === undefined || typeof value !== "object" || value === null || isList(value)) {
91
+ const table = facts[found.package] ?? {};
92
+ const closed = closedClasses(table);
93
+ const names = pathOf(call.node);
94
+ const [owner] = names;
95
+ const last = names.at(-1);
96
+ if (closed.size === 0 || owner === undefined || last === undefined || names.length < 2) {
97
+ return found;
98
+ }
99
+ if (call.receiverClass === undefined)
100
+ return found;
101
+ const nearest = call.receiverClass(new Set([...closed, owner]));
102
+ // The receiver's class is not read: the declaring class's line is not known to hold for it.
103
+ if (nearest === undefined)
611
104
  return undefined;
105
+ if (nearest === owner)
106
+ return found;
107
+ // The class's own line for the method, else its line for every method (`MongoRepository.*`).
108
+ for (const name of [`${nearest}.${last}`, `${nearest}.${WILDCARD}`]) {
109
+ const fact = table[name];
110
+ if (fact !== undefined)
111
+ return { package: found.package, name, fact };
612
112
  }
613
- return value;
614
- }
615
- function listOf(value) {
616
- return Array.isArray(value) ? value : undefined;
113
+ return undefined;
617
114
  }
618
- function readSide(value) {
619
- const fields = fieldsOf(value);
620
- const classes = listOf(fields?.classes);
621
- const unknown = listOf(fields?.unknown);
622
- if (classes === undefined || unknown === undefined)
623
- return undefined;
624
- const ids = classes.filter((one) => typeof one === "string");
625
- const reasons = unknown.filter(isReason);
626
- return ids.length === classes.length && reasons.length === unknown.length
627
- ? { classes: ids, unknown: reasons }
115
+ /** The value a method is called on (`repo` in `repo.save()`); undefined for a bare call. */
116
+ function receiverOf(call) {
117
+ const { through } = call;
118
+ return through !== undefined && ts.isPropertyAccessExpression(through)
119
+ ? through.expression
628
120
  : undefined;
629
121
  }
630
- /** A cached entry as `toJson` wrote it; undefined (a miss) for anything else. */
631
- function fromJson(value) {
632
- const fields = fieldsOf(value);
633
- if (fields === undefined)
634
- return undefined;
635
- if (isReason(fields.unknown))
636
- return { kind: "unknown", reason: fields.unknown };
637
- const throws = readSide(fields.throws);
638
- const rejects = readSide(fields.rejects);
639
- const list = listOf(fields.classes);
640
- if (throws === undefined || rejects === undefined || list === undefined)
122
+ /** A line that states what the call throws or rejects with; other lines say nothing of it. */
123
+ function statesErrors(fact) {
124
+ return fact !== undefined && (fact.throws !== undefined || fact.rejects !== undefined);
125
+ }
126
+ function says(fact) {
127
+ if (fact === undefined)
641
128
  return undefined;
642
- const classes = [];
643
- for (const item of list) {
644
- const one = readClass(item);
645
- if (one === undefined)
646
- return undefined;
647
- classes.push(one);
648
- }
649
- return { kind: "known", sides: { throws, rejects }, classes };
129
+ return fact.throws?.length === 0 && (fact.rejects ?? []).length === 0 ? "nothing" : "something";
650
130
  }
651
- function inferred(info, entry, names) {
652
- const relative = path.relative(info.root, entry).replaceAll("\\", "/");
653
- const cacheKey = `throws ${relative} ${names.join(".")}`;
654
- const key = `${packageKey(info)}\u0000${cacheKey}`;
655
- const known = memo.get(key);
656
- if (known !== undefined)
657
- return known;
658
- let cached = entries.get(packageKey(info));
659
- if (cached === undefined) {
660
- cached = new Map(readPackageCache(info.key));
661
- entries.set(packageKey(info), cached);
662
- }
663
- const stored = cached.get(cacheKey);
664
- const digest = fieldsOf(stored)?.sources;
665
- const hit = typeof digest === "string" && stillTheSame(info, digest, cached) ? fromJson(stored) : undefined;
666
- if (hit !== undefined) {
667
- cacheHits++;
668
- memo.set(key, hit);
669
- return hit;
670
- }
671
- inferences++;
672
- const found = inferFrom(info, entry, names);
673
- memo.set(key, found);
674
- const { files } = open(info, entry).source;
675
- const sources = sourcesOf(info, files.length > MAX_FILES ? [] : files);
676
- const value = toJson(found, sources.digest);
677
- const written = new Map([
678
- [cacheKey, value],
679
- [`sources ${sources.digest}`, sources.hashes],
680
- ]);
681
- for (const [name, one] of written)
682
- cached.set(name, one);
683
- verified.set(`${packageKey(info)}\u0000${sources.digest}`, true);
684
- // A failure to write costs the next run time, not facts.
685
- writePackageCache(info.key, written);
686
- return found;
131
+ /**
132
+ * The calls into packages that the facts the packs ship say throw and reject with nothing
133
+ * (`throws: []`, as the React pack says of React's hooks), unless the config's own `facts` has a
134
+ * line for the function: that line is read instead, as the resolver reads it.
135
+ */
136
+ export function quietCalls(ctx) {
137
+ // Without a shipped line that says so, no call is quiet: nothing to look up.
138
+ const none = !Object.values(ctx.shippedFacts).some((functions) => Object.values(functions).some((fact) => says(fact) === "nothing"));
139
+ return {
140
+ test: (call) => !none &&
141
+ factLineOf(ctx.types, ctx.facts, call.node, receiverOf(call)) === undefined &&
142
+ says(factLineOf(ctx.types, ctx.shippedFacts, call.node, receiverOf(call))?.fact) ===
143
+ "nothing",
144
+ };
687
145
  }
688
146
  // ---- the resolver -------------------------------------------------------------------------------
689
147
  /** Finds the facts of the calls into packages of the file `ctx` summarizes. */
690
148
  export function packageResolver(ctx) {
691
- const checked = new Map();
149
+ const versions = new Map();
150
+ const versionOf = (name) => {
151
+ let known = versions.get(name);
152
+ if (known === undefined) {
153
+ const read = packageVersionOf({ file: ctx.file }, name);
154
+ known = read.kind === "exact" ? read.version : "";
155
+ versions.set(name, known);
156
+ }
157
+ return known;
158
+ };
692
159
  return (call) => {
693
- const info = packageOf(call, ctx.file, checked);
694
- const names = pathOf(call.node);
695
- const fn = names.join(".") || call.id.slice(call.id.indexOf("#") + 1);
696
- const base = { name: call.name, version: info?.version ?? "", fn };
160
+ const version = versionOf(call.name);
161
+ // The `facts` line a hint would give, and what it states: the function called decides it.
162
+ const lineSide = factSideOf(ctx.types, call, call.through);
163
+ const promise = lineSide === "rejects";
164
+ const key = factKeyOf(ctx.types, call, call.through);
165
+ const base = { name: call.name, version, key, side: lineSide };
697
166
  const facts = (source, sides) => ({
698
167
  ...base,
699
168
  source,
700
169
  ...sides,
701
170
  });
171
+ // Not known: on the side a line would state, so its hint gives that line (`configured`).
702
172
  const unknown = (reason) => {
703
173
  const set = side([], [reason]);
704
- return facts("unknown", { throws: set, rejects: set });
174
+ return facts("unknown", promise ? { throws: NOTHING, rejects: set } : { throws: set, rejects: set });
705
175
  };
706
- const fromConfig = ctx.facts[call.name];
707
- const entry = fromConfig?.[fn] ?? fromConfig?.[names.at(-1) ?? fn];
708
- if (entry !== undefined) {
709
- return {
710
- facts: facts("config", configured(entry, call.name, returnsPromise(call.node))),
711
- classes: [],
712
- };
713
- }
714
- // 2. Curated fact files: not shipped yet (`curatedFacts`).
715
- const tagged = declared(call);
716
- if (tagged !== undefined)
717
- return { facts: facts("declared", tagged), classes: [] };
718
- if (info === undefined)
719
- return { facts: unknown("no readable source"), classes: [] };
720
- const file = entryOf(call.file, info);
721
- if (file === undefined)
722
- return { facts: unknown("no readable source"), classes: [] };
723
- const read = inferred(info, file, names);
724
- return read.kind === "unknown"
725
- ? { facts: unknown(read.reason), classes: [] }
726
- : { facts: facts("inferred", read.sides), classes: read.classes };
176
+ const stated = (line, source) => {
177
+ const sides = configured(line.fact, call.name, promise);
178
+ const named = [...sides.throws.classes, ...sides.rejects.classes].flatMap((id) => id.startsWith(packageClassId(call.name, "")) ? [id.slice(id.indexOf("#") + 1)] : []);
179
+ const classes = statedClasses(ctx.facts[line.package], ctx.shippedFacts[line.package], call.name, named);
180
+ return { facts: facts(source, sides), classes };
181
+ };
182
+ // A line that states no kind of error (`external` alone) says nothing of what the call throws.
183
+ const own = lineFor(ctx.types, ctx.facts, call);
184
+ if (own !== undefined && statesErrors(own.fact))
185
+ return stated(own, "config");
186
+ // A line left out for this project's version: not checked, never read as another version's.
187
+ const withheld = (source) => ctx.withheldFacts.find((left) => {
188
+ if (left.source !== source)
189
+ return false;
190
+ const line = lineFor(ctx.types, { [left.package]: left.functions }, call);
191
+ return source === "config" ? line !== undefined : statesErrors(line?.fact);
192
+ });
193
+ const ownLeft = withheld("config");
194
+ if (ownLeft !== undefined)
195
+ return { facts: unknown(ownLeft.reason), classes: [] };
196
+ const shipped = lineFor(ctx.types, ctx.shippedFacts, call);
197
+ if (shipped !== undefined && statesErrors(shipped.fact))
198
+ return stated(shipped, "shipped");
199
+ const packLeft = withheld("shipped");
200
+ if (packLeft !== undefined)
201
+ return { facts: unknown(packLeft.reason), classes: [] };
202
+ return { facts: unknown(NOT_STATED), classes: [] };
727
203
  };
728
204
  }
729
205
  //# sourceMappingURL=packages.js.map