@stateward/plugin-errors 1.2.1 → 1.3.0

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 (56) 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 +87 -11
  4. package/dist/catch-misses-error.d.ts +1 -1
  5. package/dist/catch-misses-error.js +63 -20
  6. package/dist/finally-can-throw.js +46 -6
  7. package/dist/index.d.ts +3 -1
  8. package/dist/index.js +1 -0
  9. package/dist/inference/analysis.d.ts +109 -0
  10. package/dist/inference/analysis.js +170 -0
  11. package/dist/inference/builtins.d.ts +7 -2
  12. package/dist/inference/builtins.js +20 -33
  13. package/dist/inference/deps.js +2 -2
  14. package/dist/inference/needs.d.ts +16 -0
  15. package/dist/inference/needs.js +27 -0
  16. package/dist/inference/packages.d.ts +24 -32
  17. package/dist/inference/packages.js +156 -675
  18. package/dist/inference/project.d.ts +2 -2
  19. package/dist/inference/project.js +3 -2
  20. package/dist/inference/solve.d.ts +29 -4
  21. package/dist/inference/solve.js +34 -5
  22. package/dist/inference/summarize.d.ts +28 -15
  23. package/dist/inference/summarize.js +339 -135
  24. package/dist/inference/summary.d.ts +46 -5
  25. package/dist/inference/summary.js +89 -13
  26. package/dist/inference/unreachable.d.ts +5 -0
  27. package/dist/inference/unreachable.js +160 -0
  28. package/dist/must-handle-error.d.ts +2 -1
  29. package/dist/must-handle-error.js +4 -4
  30. package/dist/narrow-try.d.ts +2 -0
  31. package/dist/narrow-try.js +62 -7
  32. package/dist/plugin.d.ts +12 -2
  33. package/dist/plugin.js +4 -2
  34. package/dist/react/fallbacks.js +35 -14
  35. package/dist/react/tree.d.ts +10 -0
  36. package/dist/react/tree.js +54 -7
  37. package/dist/refactors.js +35 -2
  38. package/dist/render-throw-without-boundary.d.ts +13 -4
  39. package/dist/render-throw-without-boundary.js +100 -10
  40. package/dist/result-ignored.d.ts +4 -1
  41. package/dist/result-ignored.js +51 -10
  42. package/dist/result-type.d.ts +2 -0
  43. package/dist/result-type.js +8 -2
  44. package/dist/result-unchecked.d.ts +4 -1
  45. package/dist/result-unchecked.js +320 -96
  46. package/dist/rules.meta.d.ts +29 -14
  47. package/dist/rules.meta.js +19 -14
  48. package/dist/syntax.d.ts +0 -13
  49. package/dist/syntax.js +0 -79
  50. package/dist/text.d.ts +15 -2
  51. package/dist/text.js +28 -5
  52. package/dist/throws-doc-mismatch.d.ts +1 -1
  53. package/dist/throws-doc-mismatch.js +59 -5
  54. package/dist/throws-reads.d.ts +3 -0
  55. package/dist/throws-reads.js +108 -0
  56. package/package.json +2 -2
@@ -0,0 +1,170 @@
1
+ import { builtinName, builtinParent, isBuiltin } from "./builtins.js";
2
+ import { summarizeOnce } from "./project.js";
3
+ import { analyse } from "./solve.js";
4
+ function unknownOf(source) {
5
+ return {
6
+ location: { file: source.file, start: source.start, end: source.end },
7
+ text: source.text,
8
+ reason: source.reason,
9
+ ...(source.package === undefined ? {} : { package: source.package }),
10
+ ...(source.fact === undefined ? {} : { fact: source.fact }),
11
+ };
12
+ }
13
+ /** The function a call names, as written: `JSON.parse` for the leaf text `JSON.parse(…)`. */
14
+ function calledText(text) {
15
+ return text.endsWith("(…)") ? text.slice(0, -"(…)".length) : text;
16
+ }
17
+ /** The effects of a list and of everything nested in it (try bodies, catches, `finally`), in order. */
18
+ function* leaves(effects) {
19
+ for (const effect of effects) {
20
+ if (effect.k !== "try") {
21
+ yield effect;
22
+ continue;
23
+ }
24
+ yield* leaves(effect.body);
25
+ const { handler } = effect;
26
+ if (handler !== null) {
27
+ yield* leaves(handler.pre);
28
+ for (const branch of handler.branches)
29
+ yield* leaves(branch.body);
30
+ if (handler.otherwise !== null)
31
+ yield* leaves(handler.otherwise);
32
+ yield* leaves(handler.after);
33
+ }
34
+ yield* leaves(effect.fin);
35
+ }
36
+ }
37
+ /**
38
+ * Where a class a function throws is made, following the first call that brings it into the
39
+ * function it calls (`ThrownClass.origin`). Computed for the published analysis only: the solve's
40
+ * results hold no offsets, so an edit that only moves code does not re-solve the callers.
41
+ */
42
+ function originFinder(analysis) {
43
+ const memo = new Map();
44
+ const find = (fn, id, visiting) => {
45
+ const key = `${fn}\u0000${id}`;
46
+ const known = memo.get(key);
47
+ if (known !== undefined)
48
+ return known ?? undefined;
49
+ if (visiting.has(fn))
50
+ return undefined;
51
+ visiting.add(fn);
52
+ const entry = analysis.functions.get(fn);
53
+ let found;
54
+ for (const effect of leaves(entry === undefined ? [] : [...entry.fact.body, ...entry.fact.returns])) {
55
+ if (entry === undefined)
56
+ break;
57
+ const location = (at) => ({
58
+ file: entry.file,
59
+ start: at[0],
60
+ end: at[1],
61
+ });
62
+ if (effect.k === "class" && effect.id === id) {
63
+ // A class leaf with a call's text is a built-in call that throws it.
64
+ found =
65
+ effect.text === null
66
+ ? { kind: "throw", location: location(effect.at) }
67
+ : {
68
+ kind: "call",
69
+ location: location(effect.at),
70
+ text: calledText(effect.text),
71
+ side: "throws",
72
+ ...(effect.platform === true ? { platform: true } : {}),
73
+ };
74
+ }
75
+ else if (effect.k === "package" && effect.facts[effect.part].classes.includes(id)) {
76
+ found = {
77
+ kind: "call",
78
+ location: location(effect.at),
79
+ text: calledText(effect.text),
80
+ side: effect.part,
81
+ ...(effect.platform === true ? { platform: true } : {}),
82
+ };
83
+ }
84
+ else if (effect.k === "call") {
85
+ const result = analysis.results.get(effect.id);
86
+ const sides = effect.part === "both" ? [result?.throws, result?.rejects] : [result?.[effect.part]];
87
+ if (sides.some((side) => side?.classes.has(id) === true)) {
88
+ found = find(effect.id, id, visiting);
89
+ }
90
+ }
91
+ if (found !== undefined)
92
+ break;
93
+ }
94
+ visiting.delete(fn);
95
+ memo.set(key, found ?? null);
96
+ return found;
97
+ };
98
+ return (fn, id) => find(fn, id, new Set());
99
+ }
100
+ function errorsOf(set, origin) {
101
+ return {
102
+ classes: [...set.classes].map(([id, certain]) => {
103
+ const at = origin(id);
104
+ return at === undefined ? { id, certain } : { id, certain, origin: at };
105
+ }),
106
+ unknown: set.unknowns.map(unknownOf),
107
+ ...(set.more ? { more: true } : {}),
108
+ };
109
+ }
110
+ /** Solves the summaries into the published shape. */
111
+ export function throwsAnalysis(summaries) {
112
+ const analysis = analyse(summaries);
113
+ const originOf = originFinder(analysis);
114
+ const functions = {};
115
+ for (const id of [...analysis.results.keys()].sort()) {
116
+ const entry = analysis.functions.get(id);
117
+ const result = analysis.results.get(id);
118
+ if (entry === undefined || result === undefined)
119
+ continue;
120
+ functions[id] = {
121
+ name: entry.fact.name,
122
+ location: { file: entry.file, start: entry.fact.at[0], end: entry.fact.at[1] },
123
+ throws: errorsOf(result.throws, (one) => originOf(id, one)),
124
+ rejects: errorsOf(result.rejects, (one) => originOf(id, one)),
125
+ };
126
+ }
127
+ return { functions, classes: classesOf(functions, analysis.classes) };
128
+ }
129
+ /** What the analysis knows of a class id: a class of the platform, a summarized class, or neither. */
130
+ function classInfo(id, known) {
131
+ if (isBuiltin(id)) {
132
+ return { name: builtinName(id), parent: builtinParent(id), open: false, fields: [] };
133
+ }
134
+ const fact = known.get(id);
135
+ if (fact !== undefined) {
136
+ return {
137
+ name: fact.name,
138
+ parent: fact.parent,
139
+ open: fact.open,
140
+ fields: fact.fields,
141
+ ...(fact.declared === undefined ? {} : { declared: fact.declared }),
142
+ ...(fact.version === undefined ? {} : { version: fact.version }),
143
+ ...(fact.key === undefined ? {} : { key: fact.key }),
144
+ };
145
+ }
146
+ return { name: id.slice(id.lastIndexOf("#") + 1), parent: null, open: true, fields: [] };
147
+ }
148
+ /** Every class the functions name, with their ancestors, sorted by id. */
149
+ function classesOf(functions, known) {
150
+ const found = new Map();
151
+ const add = (start) => {
152
+ // A class that (wrongly) extends itself stops at the first id seen again.
153
+ for (let id = start; id !== null && !found.has(id);) {
154
+ const info = classInfo(id, known);
155
+ found.set(id, info);
156
+ id = info.parent;
157
+ }
158
+ };
159
+ for (const one of Object.values(functions)) {
160
+ for (const thrown of [...one.throws.classes, ...one.rejects.classes])
161
+ add(thrown.id);
162
+ }
163
+ return Object.fromEntries([...found].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
164
+ }
165
+ /** `Plugin.analyses.throws` of the errors pack. */
166
+ export const throws = {
167
+ summarize: (ctx) => summarizeOnce(ctx),
168
+ solve: throwsAnalysis,
169
+ };
170
+ //# sourceMappingURL=analysis.js.map
@@ -21,6 +21,13 @@ export declare function builtinName(id: string): string;
21
21
  export declare function builtinCatchName(id: string): string;
22
22
  /** Methods of the platform's interfaces, as `<interface>.<method>`, that throw synchronously. */
23
23
  export declare const THROWING_MEMBERS: ReadonlyMap<string, readonly string[]>;
24
+ /**
25
+ * Methods of the platform's interfaces, as `<interface>.<method>`, that return a promise which
26
+ * can reject. `Response.json()` rejects with a `SyntaxError` for a body that is not JSON; every
27
+ * way to read a body rejects with a `TypeError` when the body was already read or the connection
28
+ * fails while it is read.
29
+ */
30
+ export declare const REJECTING_MEMBERS: ReadonlyMap<string, readonly string[]>;
24
31
  /** Global functions that throw synchronously. */
25
32
  export declare const THROWING_GLOBALS: ReadonlyMap<string, readonly string[]>;
26
33
  /** Global constructors that throw. */
@@ -47,6 +54,4 @@ export declare const MAPPING_METHODS: ReadonlySet<string>;
47
54
  * the caller, so it is left out on purpose. Its own catches are still checked.
48
55
  */
49
56
  export declare const DEFERRED_CALLERS: ReadonlySet<string>;
50
- /** Whether a call into package `name`, written `callText`, is one of React's non-throwing hooks. */
51
- export declare function isNonThrowingReactHook(name: string, callText: string): boolean;
52
57
  //# sourceMappingURL=builtins.d.ts.map
@@ -61,6 +61,26 @@ export const THROWING_MEMBERS = new Map([
61
61
  ["JSON.stringify", [TYPE]],
62
62
  // A digit count outside 0 to 100.
63
63
  ["Number.toFixed", [RANGE]],
64
+ ["Number.toPrecision", [RANGE]],
65
+ ["Number.toExponential", [RANGE]],
66
+ // A radix outside 2 to 36 (with no radix it cannot throw).
67
+ ["Number.toString", [RANGE]],
68
+ // A name or value that is not a valid header, or headers that cannot be changed.
69
+ ["Headers.set", [TYPE]],
70
+ ["Headers.append", [TYPE]],
71
+ ]);
72
+ /**
73
+ * Methods of the platform's interfaces, as `<interface>.<method>`, that return a promise which
74
+ * can reject. `Response.json()` rejects with a `SyntaxError` for a body that is not JSON; every
75
+ * way to read a body rejects with a `TypeError` when the body was already read or the connection
76
+ * fails while it is read.
77
+ */
78
+ export const REJECTING_MEMBERS = new Map([
79
+ ["Body.json", [SYNTAX, TYPE]],
80
+ ...["text", "arrayBuffer", "blob", "formData", "bytes"].map((method) => [
81
+ `Body.${method}`,
82
+ [TYPE],
83
+ ]),
64
84
  ]);
65
85
  /** Global functions that throw synchronously. */
66
86
  export const THROWING_GLOBALS = new Map([
@@ -143,37 +163,4 @@ export const DEFERRED_CALLERS = new Set([
143
163
  "IntersectionObserver",
144
164
  "PerformanceObserver",
145
165
  ]);
146
- /**
147
- * React's built-in hooks do not throw in correct use (misuse, like a hook called conditionally, is
148
- * a bug the rules-of-hooks lint finds, not part of their contract), so a call to one adds nothing.
149
- * Without this, every component would carry "unknown (package react)". `use()` is left out: it
150
- * rethrows a rejected promise.
151
- */
152
- const NON_THROWING_REACT_HOOKS = new Set([
153
- "useState",
154
- "useReducer",
155
- "useEffect",
156
- "useLayoutEffect",
157
- "useInsertionEffect",
158
- "useMemo",
159
- "useCallback",
160
- "useRef",
161
- "useContext",
162
- "useId",
163
- "useTransition",
164
- "useDeferredValue",
165
- "useImperativeHandle",
166
- "useDebugValue",
167
- "useSyncExternalStore",
168
- "useOptimistic",
169
- "useActionState",
170
- "useFormStatus",
171
- ]);
172
- /** Whether a call into package `name`, written `callText`, is one of React's non-throwing hooks. */
173
- export function isNonThrowingReactHook(name, callText) {
174
- if (name !== "react" && name !== "react-dom")
175
- return false;
176
- const callee = /([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(?/.exec(callText.split(".").pop() ?? "")?.[1];
177
- return callee !== undefined && NON_THROWING_REACT_HOOKS.has(callee);
178
- }
179
166
  //# sourceMappingURL=builtins.js.map
@@ -47,11 +47,11 @@ export function packagesCalled(summaries) {
47
47
  functions: new Map(),
48
48
  };
49
49
  byPackage.set(key, entry);
50
- const fn = entry.functions.get(facts.fn) ?? {
50
+ const fn = entry.functions.get(facts.key.name) ?? {
51
51
  source: facts.source,
52
52
  unknown: new Set(),
53
53
  };
54
- entry.functions.set(facts.fn, fn);
54
+ entry.functions.set(facts.key.name, fn);
55
55
  for (const reason of [...facts.throws.unknown, ...facts.rejects.unknown])
56
56
  fn.unknown.add(reason);
57
57
  }
@@ -0,0 +1,16 @@
1
+ import type { FactNeed, UnnamedFact } from "@stateward/core";
2
+ import type { UnknownFact } from "./solve.js";
3
+ /** What a "not checked" finding carries for the places it depends on (`Finding.needs`, `unnamed`). */
4
+ export type DecidingFacts = {
5
+ needs?: readonly FactNeed[];
6
+ unnamed?: readonly UnnamedFact[];
7
+ };
8
+ /**
9
+ * The `facts` lines that decide a finding, one per call, from every unknown it depends on whose
10
+ * call no line states: a call met on both sides needs the one side `neededSides` picks. The
11
+ * package calls no key can name are listed apart, once each, with why.
12
+ */
13
+ export declare function decidingFacts(unknowns: Iterable<{
14
+ readonly fact?: UnknownFact | undefined;
15
+ }>): DecidingFacts;
16
+ //# sourceMappingURL=needs.d.ts.map
@@ -0,0 +1,27 @@
1
+ import { neededSides } from "@stateward/core";
2
+ /**
3
+ * The `facts` lines that decide a finding, one per call, from every unknown it depends on whose
4
+ * call no line states: a call met on both sides needs the one side `neededSides` picks. The
5
+ * package calls no key can name are listed apart, once each, with why.
6
+ */
7
+ export function decidingFacts(unknowns) {
8
+ const needs = new Map();
9
+ const unnamed = new Map();
10
+ for (const { fact } of unknowns) {
11
+ if (fact?.kind === "unstated") {
12
+ const { need } = fact;
13
+ const key = `${need.module}\u0000${need.name}`;
14
+ const known = needs.get(key);
15
+ const states = neededSides([...(known?.states ?? []), ...need.states]);
16
+ needs.set(key, { ...(known ?? need), states });
17
+ }
18
+ else if (fact?.kind === "unnamed") {
19
+ unnamed.set(`${fact.unnamed.name}\u0000${fact.unnamed.reason}`, fact.unnamed);
20
+ }
21
+ }
22
+ return {
23
+ ...(needs.size === 0 ? {} : { needs: [...needs.values()] }),
24
+ ...(unnamed.size === 0 ? {} : { unnamed: [...unnamed.values()] }),
25
+ };
26
+ }
27
+ //# sourceMappingURL=needs.js.map
@@ -1,40 +1,32 @@
1
- import ts from "@stateward/core/typescript";
2
- import type { FileContext } from "@stateward/core";
3
- import type { PackageResolver } from "./summarize.js";
1
+ import type { FileContext, TypeQueries } from "@stateward/core";
2
+ import type { PackageResolver, QuietCall } from "./summarize.js";
3
+ import { UNKNOWN_REASONS } from "./summary.js";
4
+ import type { UnknownReason } from "./summary.js";
4
5
  /**
5
- * Library facts for the Errors pack: what a call into a
6
- * package throws, from the first source that answers:
6
+ * Library facts for the Errors pack: what a call into a package throws, from its contract only
7
+ * (0041), from the first source that answers:
7
8
  *
8
9
  * 1. the project's config (`facts`);
9
- * 2. curated fact files shipped with stateward (`curatedFacts` answers nothing yet);
10
- * 3. `@throws {X}` on the called declaration in the package's `.d.ts`;
11
- * 4. inferred from the package's JavaScript, with the summarizer of the project's own code, from
12
- * the called function to what it calls in the package (bounded), cached globally;
13
- * 5. unknown, with one of the reasons below.
14
- */
15
- /** Why a package's function is not (fully) known: fixed strings, shown as they are. */
16
- export declare const UNKNOWN_REASONS: readonly ["no readable source", "not found in its source", "native addon", "minified", "eval", "dynamic require", "too large to follow", "untyped @throws", "calls a callback", "calls code it cannot see", "dynamic call", "throws a value of unknown class", "awaits a promise it cannot follow"];
17
- export type UnknownReason = (typeof UNKNOWN_REASONS)[number];
18
- /**
19
- * At most this many functions are read per package function asked for.
20
- * The bounds count, never time: a verdict by time would differ between machines.
10
+ * 2. the facts the loaded packs ship (`Plugin.facts`);
11
+ * 3. else unknown: "its errors are not stated", with a hint that gives the `facts` line.
12
+ *
13
+ * A line names the call when its key resolves to the called declaration (`factLineOf`). The
14
+ * package's code and the doc comments of its declarations are never read.
21
15
  */
22
- export declare const MAX_FUNCTIONS = 200;
23
- /** The declaration's path in the package's types: `["Client", "get"]`. */
24
- export declare function pathOf(node: ts.Node): string[];
16
+ export { UNKNOWN_REASONS };
17
+ export type { UnknownReason };
18
+ /** The calls the facts say throw nothing (`QuietCall`). */
19
+ export type Quiet = {
20
+ readonly test: QuietCall;
21
+ };
25
22
  /**
26
- * Curated fact files shipped with stateward: none ship yet, so nothing answers between the config
27
- * and the declarations. Reading `facts/<package>@<major>.json` here would add the `curated`
28
- * source, and the resolver would ask it after the config.
23
+ * The calls into packages that the facts the packs ship say throw and reject with nothing
24
+ * (`throws: []`, as the React pack says of React's hooks), unless the config's own `facts` has a
25
+ * line for the function: that line is read instead, as the resolver reads it.
29
26
  */
30
- export declare function curatedFacts(): undefined;
31
- /** What this process computed and read back, for tests: inference runs and global-cache hits. */
32
- export declare function packageFactsStats(): {
33
- inferences: number;
34
- cacheHits: number;
35
- };
36
- /** Forgets what this process knows about packages (tests: the next run reads the global cache). */
37
- export declare function forgetPackageFacts(): void;
27
+ export declare function quietCalls(ctx: Pick<FileContext, "facts" | "shippedFacts"> & {
28
+ readonly types: Pick<TypeQueries, "factTarget" | "isOrExtends">;
29
+ }): Quiet;
38
30
  /** Finds the facts of the calls into packages of the file `ctx` summarizes. */
39
- export declare function packageResolver(ctx: Pick<FileContext, "file" | "facts">): PackageResolver;
31
+ export declare function packageResolver(ctx: Pick<FileContext, "file" | "facts" | "shippedFacts" | "withheldFacts" | "types">): PackageResolver;
40
32
  //# sourceMappingURL=packages.d.ts.map