@stateward/plugin-errors 1.2.0 → 1.2.2
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.
- package/dist/catch-hides-unexpected.js +75 -6
- package/dist/catch-misses-error.js +62 -19
- package/dist/finally-can-throw.js +43 -3
- package/dist/inference/builtins.d.ts +7 -0
- package/dist/inference/builtins.js +20 -0
- package/dist/inference/packages.js +5 -0
- package/dist/inference/summarize.d.ts +1 -0
- package/dist/inference/summarize.js +94 -7
- package/dist/inference/summary.d.ts +5 -0
- package/dist/inference/summary.js +5 -1
- package/dist/narrow-try.d.ts +2 -0
- package/dist/narrow-try.js +62 -7
- package/dist/react/fallbacks.js +35 -14
- package/dist/react/tree.d.ts +10 -0
- package/dist/react/tree.js +47 -4
- package/dist/refactors.js +35 -2
- package/dist/render-throw-without-boundary.js +100 -10
- package/dist/result-ignored.js +51 -10
- package/dist/result-type.d.ts +2 -0
- package/dist/result-type.js +6 -0
- package/dist/result-unchecked.js +185 -39
- package/dist/rules.meta.d.ts +3 -0
- package/dist/rules.meta.js +1 -0
- package/dist/text.d.ts +10 -0
- package/dist/text.js +17 -0
- package/dist/throws-doc-mismatch.js +53 -5
- package/dist/throws-reads.d.ts +3 -0
- package/dist/throws-reads.js +108 -0
- package/package.json +2 -2
package/dist/narrow-try.js
CHANGED
|
@@ -3,10 +3,12 @@ import { defineRule } from "@stateward/core";
|
|
|
3
3
|
import { summarizeOnce } from "./inference/project.js";
|
|
4
4
|
import { REASON } from "./inference/summarize.js";
|
|
5
5
|
import { analyse, collected, evaluate } from "./inference/solve.js";
|
|
6
|
+
import { catchName } from "./inference/format.js";
|
|
7
|
+
import { isBuiltin } from "./inference/builtins.js";
|
|
6
8
|
import { each, fieldsOf, isString, readStrings, spanOf } from "./inference/summary.js";
|
|
7
9
|
import { throwsOf } from "./react/boundaries.js";
|
|
8
10
|
import { handsOnCaught, isFunctionBoundary, someRunning, stripParentheses, testsCaught, } from "./syntax.js";
|
|
9
|
-
import { fitted, oneLine, shorten } from "./text.js";
|
|
11
|
+
import { codeList, fitted, oneLine, shorten } from "./text.js";
|
|
10
12
|
/** The group the rule belongs to in the docs and in `stateward status`. */
|
|
11
13
|
export const GROUP = "catch";
|
|
12
14
|
const EXPLAIN = `# errors/narrow-try
|
|
@@ -57,6 +59,8 @@ export async function submit(plan: string, close: () => void): Promise<void> {
|
|
|
57
59
|
|
|
58
60
|
The quick fix moves the lines after the \`try\`. It is offered only when the move keeps what runs the same for every outcome but a bug: the \`catch\` ends with \`return\` or \`throw\`, there is no \`finally\`, and the moved lines use nothing declared in the \`try\`. Where they use the result, declare it before the \`try\` (\`let plan: Plan;\`), assign it inside, and return from the \`catch\`.
|
|
59
61
|
|
|
62
|
+
The other reading keeps the line where it is and makes the \`catch\` pick its error: \`if (e instanceof RequestError) { … } else { throw e; }\`, with the classes the call throws (a \`TypeError\` is left out, since a bug throws it too). The rule then counts the \`catch\` as one that lets bugs through (see below), and the message shows this form with your names.
|
|
63
|
+
|
|
60
64
|
## Why it matters
|
|
61
65
|
|
|
62
66
|
The \`catch\` is for a failed save. When \`close\` has a bug (it reads a property of \`undefined\`, say), the \`TypeError\` is handled like a failed request: the user sees "Could not save", the console shows nothing useful, and the bug is never reported. With only the request inside the \`try\`, a bug in the code after it surfaces as the bug it is.
|
|
@@ -363,6 +367,9 @@ function shapeOf(node, sourceFile) {
|
|
|
363
367
|
return {
|
|
364
368
|
at: [node.getStart(sourceFile), node.getEnd()],
|
|
365
369
|
passesBugsOn: passesBugsOn(clause),
|
|
370
|
+
variable: clause.variableDeclaration !== undefined && ts.isIdentifier(clause.variableDeclaration.name)
|
|
371
|
+
? clause.variableDeclaration.name.text
|
|
372
|
+
: null,
|
|
366
373
|
catchExits: endsWithExit(clause.block),
|
|
367
374
|
hasFinally: node.finallyBlock !== undefined,
|
|
368
375
|
indent: indentationAt(node.getStart(sourceFile), text),
|
|
@@ -433,7 +440,18 @@ function readShape(value) {
|
|
|
433
440
|
!isString(inner)) {
|
|
434
441
|
return undefined;
|
|
435
442
|
}
|
|
436
|
-
|
|
443
|
+
const variable = isString(f.variable) ? f.variable : null;
|
|
444
|
+
return {
|
|
445
|
+
at,
|
|
446
|
+
passesBugsOn: passes,
|
|
447
|
+
variable,
|
|
448
|
+
catchExits,
|
|
449
|
+
hasFinally,
|
|
450
|
+
indent,
|
|
451
|
+
inner,
|
|
452
|
+
lines,
|
|
453
|
+
around,
|
|
454
|
+
};
|
|
437
455
|
}
|
|
438
456
|
function readTries(value) {
|
|
439
457
|
return each(fieldsOf(value)?.tries, readShape);
|
|
@@ -475,6 +493,8 @@ function spotsOf(analysis, file, effects, out) {
|
|
|
475
493
|
packageOnly: false,
|
|
476
494
|
unknown: false,
|
|
477
495
|
project: null,
|
|
496
|
+
classes: [],
|
|
497
|
+
imports: [],
|
|
478
498
|
});
|
|
479
499
|
continue;
|
|
480
500
|
}
|
|
@@ -493,6 +513,11 @@ function spotsOf(analysis, file, effects, out) {
|
|
|
493
513
|
: effect.k === "unknown" && effect.reason === REASON.callback
|
|
494
514
|
? "callback"
|
|
495
515
|
: null,
|
|
516
|
+
classes: [...into.classes.keys()].map((id) => catchName(id, analysis.classes)).sort(),
|
|
517
|
+
imports: [...into.classes.keys()]
|
|
518
|
+
.filter((id) => !isBuiltin(id))
|
|
519
|
+
.map((id) => catchName(id, analysis.classes))
|
|
520
|
+
.sort(),
|
|
496
521
|
});
|
|
497
522
|
if (effect.k === "try") {
|
|
498
523
|
visit(effect.body, effect.at);
|
|
@@ -541,6 +566,8 @@ function expectedIn(line, spots) {
|
|
|
541
566
|
packageOnly: false,
|
|
542
567
|
unknown: true,
|
|
543
568
|
project: null,
|
|
569
|
+
classes: [],
|
|
570
|
+
imports: [],
|
|
544
571
|
}
|
|
545
572
|
: undefined;
|
|
546
573
|
}
|
|
@@ -596,15 +623,43 @@ function nameOf(spot, line) {
|
|
|
596
623
|
function headline(line, expected) {
|
|
597
624
|
return fitted((cut) => `the \`try\` for \`${cut(expected)}\` also catches errors from \`${asCode(cut(line))}\``);
|
|
598
625
|
}
|
|
599
|
-
function hint(expected, fixable, count) {
|
|
626
|
+
function hint(expected, fixable, count, test) {
|
|
600
627
|
const [lines, them] = count === 1 ? ["the line", "it"] : ["the lines", "them"];
|
|
601
628
|
const why = `so a bug in ${them} is not handled like a failed \`${expected}\``;
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
629
|
+
const binding = test.bound ? "" : `, binding it as \`catch (${test.variable})\``;
|
|
630
|
+
const imports = test.imports.length === 0
|
|
631
|
+
? ""
|
|
632
|
+
: ` (import ${codeList(test.imports, oneLine)} if the file does not)`;
|
|
633
|
+
const leftOut = test.leftOut ? ", leaving out `TypeError`, which a bug throws too" : "";
|
|
634
|
+
return [
|
|
635
|
+
"one of",
|
|
636
|
+
fixable
|
|
637
|
+
? `- move ${lines} after the \`try\`, ${why} (quick fix)`
|
|
638
|
+
: `- move ${lines} after the \`try\` and return from the \`catch\` (declare what ${count === 1 ? "it uses" : "they use"} before the \`try\`), ${why}`,
|
|
639
|
+
test.classes.length === 0
|
|
640
|
+
? `- or test in the \`catch\` that the error is what \`${expected}\` fails with, and rethrow the rest with \`throw ${test.variable};\`${binding}, ${why}`
|
|
641
|
+
: `- or test the error in the \`catch\` and rethrow the rest${imports}${binding}${leftOut}:`,
|
|
642
|
+
...(test.classes.length === 0
|
|
643
|
+
? []
|
|
644
|
+
: [
|
|
645
|
+
` if (${test.classes.map((name) => `${test.variable} instanceof ${name}`).join(" || ")}) { … } else { throw ${test.variable}; }`,
|
|
646
|
+
]),
|
|
647
|
+
].join("\n");
|
|
605
648
|
}
|
|
606
649
|
/** A promise's own `resolve` and `reject` (excalidraw): they never throw. */
|
|
607
650
|
const SETTLES = new Set(["resolve(…)", "reject(…)"]);
|
|
651
|
+
/** The `instanceof` test the `catch` can make for the failure the `try` is for. */
|
|
652
|
+
function testWay(shape, expected) {
|
|
653
|
+
const kept = expected.classes.filter((name) => name !== "TypeError");
|
|
654
|
+
const many = kept.length > 3;
|
|
655
|
+
return {
|
|
656
|
+
variable: shape.variable ?? "error",
|
|
657
|
+
bound: shape.variable !== null,
|
|
658
|
+
classes: many ? [] : kept,
|
|
659
|
+
imports: many ? [] : expected.imports.filter((name) => kept.includes(name)),
|
|
660
|
+
leftOut: !many && kept.length < expected.classes.length,
|
|
661
|
+
};
|
|
662
|
+
}
|
|
608
663
|
function checkTry(shape, spots, file, report) {
|
|
609
664
|
if (shape.passesBugsOn)
|
|
610
665
|
return;
|
|
@@ -637,7 +692,7 @@ function checkTry(shape, spots, file, report) {
|
|
|
637
692
|
const fix = moveFix(shape, kept, moved, file);
|
|
638
693
|
report({
|
|
639
694
|
message: headline(first.text, target),
|
|
640
|
-
hint: hint(target, fix !== undefined, moved.length),
|
|
695
|
+
hint: hint(target, fix !== undefined, moved.length, testWay(shape, expected)),
|
|
641
696
|
at: first.at,
|
|
642
697
|
fixes: fix === undefined ? [] : [fix],
|
|
643
698
|
});
|
package/dist/react/fallbacks.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { matchesName } from "@stateward/core";
|
|
2
2
|
import { catchName, className } from "../inference/format.js";
|
|
3
3
|
import { relation } from "../inference/solve.js";
|
|
4
|
-
import { codeList, fitted,
|
|
4
|
+
import { codeList, fitted, waysHint } from "../text.js";
|
|
5
5
|
/**
|
|
6
6
|
* Error boundary fallbacks, checked as catches (`errors/catch-misses-error`; they were
|
|
7
7
|
* `errors/exhaustive-fallback` in earlier releases): a fallback that branches on the error with
|
|
8
8
|
* `instanceof` handles every class its boundary can catch, or has a branch for the rest.
|
|
9
9
|
*/
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* What the fallback does with any other error, as lines of code; undefined where the line depends
|
|
12
|
+
* on the boundary's own state, which is said in words.
|
|
13
|
+
*/
|
|
11
14
|
function restLine(kind, variable) {
|
|
12
15
|
switch (kind) {
|
|
13
16
|
case "FallbackComponent":
|
|
@@ -16,24 +19,42 @@ function restLine(kind, variable) {
|
|
|
16
19
|
case "onError":
|
|
17
20
|
return `console.error(${variable});`;
|
|
18
21
|
case "getDerivedStateFromError":
|
|
19
|
-
return
|
|
22
|
+
return undefined;
|
|
20
23
|
default: {
|
|
21
24
|
const unreachable = kind;
|
|
22
25
|
return unreachable;
|
|
23
26
|
}
|
|
24
27
|
}
|
|
25
28
|
}
|
|
26
|
-
|
|
27
|
-
|
|
29
|
+
/** The ways to handle the classes a fallback leaves out: a branch each, a branch for the rest, or the option. */
|
|
30
|
+
function hint(fallback, chain, handlers) {
|
|
31
|
+
const [handler = ""] = handlers;
|
|
32
|
+
const count = handlers.length;
|
|
28
33
|
const rest = restLine(fallback.kind, chain.variable);
|
|
29
|
-
|
|
30
|
-
?
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
const branch = chain.dispatch === "switch"
|
|
35
|
+
? [`case ${chain.variable} instanceof ${handler}:`, " …"]
|
|
36
|
+
: [`if (${chain.variable} instanceof ${handler}) {`, " …", "}"];
|
|
37
|
+
const other = chain.dispatch === "switch"
|
|
38
|
+
? ["default:", ...(rest === undefined ? [] : [` ${rest}`])]
|
|
39
|
+
: [rest];
|
|
40
|
+
const ignored = `{ ignoreClasses: [${handlers.map((one) => JSON.stringify(one)).join(", ")}] }`;
|
|
41
|
+
return waysHint([
|
|
42
|
+
{ text: `add a branch for ${count === 1 ? "it" : "each"}`, example: branch },
|
|
43
|
+
rest === undefined
|
|
44
|
+
? {
|
|
45
|
+
text: "end with one for any other error, returning the state the boundary shows for a failure",
|
|
46
|
+
}
|
|
47
|
+
: {
|
|
48
|
+
text: "end with one for any other error",
|
|
49
|
+
example: other.filter((line) => line !== undefined),
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
text: count === 1
|
|
53
|
+
? `if \`${handler}\` needs no branch, list it under the rule's \`ignoreClasses\` option`
|
|
54
|
+
: "if they need no branch, list them under the rule's `ignoreClasses` option",
|
|
55
|
+
example: [ignored],
|
|
56
|
+
},
|
|
57
|
+
]);
|
|
37
58
|
}
|
|
38
59
|
/** Reports each fallback that leaves out a class its boundary can catch. */
|
|
39
60
|
export function checkFallbacks(model, ignored, report) {
|
|
@@ -73,7 +94,7 @@ export function checkFallbacks(model, ignored, report) {
|
|
|
73
94
|
});
|
|
74
95
|
report({
|
|
75
96
|
message: fitted((cut) => `\`${cut(fallback.name)}\` does not handle ${codeList(missing.map((one) => one.name), cut)}, which its boundary can catch`),
|
|
76
|
-
hint: hint(fallback, chain, catchName(
|
|
97
|
+
hint: hint(fallback, chain, missing.map((one) => catchName(one.id, classes))),
|
|
77
98
|
location: { file, start: fallback.at[0], end: fallback.at[1] },
|
|
78
99
|
related,
|
|
79
100
|
});
|
package/dist/react/tree.d.ts
CHANGED
|
@@ -24,6 +24,16 @@ export type TreeRender = {
|
|
|
24
24
|
/** The tag as written. */
|
|
25
25
|
readonly name: string;
|
|
26
26
|
readonly at: Span;
|
|
27
|
+
/** The element as written when it is self-closing and short: what a hint wraps. */
|
|
28
|
+
readonly text?: string;
|
|
29
|
+
/**
|
|
30
|
+
* The nearest element around it, in the same component, that is named like an error boundary
|
|
31
|
+
* and comes from a package: an unlisted boundary, which the `boundaries` option would list.
|
|
32
|
+
*/
|
|
33
|
+
readonly wrapper?: {
|
|
34
|
+
readonly tag: string;
|
|
35
|
+
readonly package: string;
|
|
36
|
+
};
|
|
27
37
|
readonly around: readonly Around[];
|
|
28
38
|
/**
|
|
29
39
|
* The element goes where stateward cannot follow it (passed to a function, stored in an
|
package/dist/react/tree.js
CHANGED
|
@@ -80,6 +80,17 @@ function tagName(tag) {
|
|
|
80
80
|
return /^[a-z]/.test(tag.text) ? undefined : tag;
|
|
81
81
|
return ts.isPropertyAccessExpression(tag) ? tag.name : undefined;
|
|
82
82
|
}
|
|
83
|
+
/** What names a component that is likely an error boundary. */
|
|
84
|
+
const BOUNDARY_NAME = /boundary|catch/i;
|
|
85
|
+
/** The longest element a hint quotes whole. */
|
|
86
|
+
const TEXT_MAX = 60;
|
|
87
|
+
/** A self-closing element on one line as written, or undefined: what a hint can wrap as it is. */
|
|
88
|
+
function selfClosingText(element, sourceFile) {
|
|
89
|
+
if (!ts.isJsxSelfClosingElement(element))
|
|
90
|
+
return undefined;
|
|
91
|
+
const text = element.getText(sourceFile);
|
|
92
|
+
return text.length <= TEXT_MAX && !text.includes("\n") ? text : undefined;
|
|
93
|
+
}
|
|
83
94
|
function openingOf(element) {
|
|
84
95
|
return ts.isJsxElement(element) ? element.openingElement : element;
|
|
85
96
|
}
|
|
@@ -611,6 +622,22 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
|
|
|
611
622
|
};
|
|
612
623
|
walk(root);
|
|
613
624
|
};
|
|
625
|
+
/** The nearest element around `element`, up to `stop`, named like a boundary and from a package. */
|
|
626
|
+
const wrapperOf = (element, stop) => {
|
|
627
|
+
for (let node = element.parent; node !== stop && !ts.isSourceFile(node); node = node.parent) {
|
|
628
|
+
if (!ts.isJsxElement(node))
|
|
629
|
+
continue;
|
|
630
|
+
const name = tagName(node.openingElement.tagName);
|
|
631
|
+
const symbol = name === undefined ? undefined : types.symbolAt(name);
|
|
632
|
+
const declaration = symbol === undefined ? undefined : types.declarationOf(symbol);
|
|
633
|
+
if (symbol === undefined || declaration === undefined)
|
|
634
|
+
continue;
|
|
635
|
+
if (types.isOwnFile(declaration.file) || !BOUNDARY_NAME.test(symbol.name))
|
|
636
|
+
continue;
|
|
637
|
+
return { tag: symbol.name, package: packageNameOf(types, declaration.file) };
|
|
638
|
+
}
|
|
639
|
+
return undefined;
|
|
640
|
+
};
|
|
614
641
|
const rendersOf = (element, stop) => {
|
|
615
642
|
const opening = openingOf(element);
|
|
616
643
|
const tag = tagOf(opening);
|
|
@@ -619,6 +646,7 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
|
|
|
619
646
|
key: keyOf(element),
|
|
620
647
|
name: opening.tagName.getText(sourceFile),
|
|
621
648
|
at: spanOf(opening.tagName),
|
|
649
|
+
...(tag.boundary.own === null ? {} : { own: true }),
|
|
622
650
|
fallbacks: fallbacksOf(types, opening, tag, sourceFile),
|
|
623
651
|
});
|
|
624
652
|
}
|
|
@@ -626,6 +654,8 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
|
|
|
626
654
|
if (target === undefined)
|
|
627
655
|
return [];
|
|
628
656
|
const seen = new Set();
|
|
657
|
+
const text = selfClosingText(element, sourceFile);
|
|
658
|
+
const wrapper = wrapperOf(element, stop);
|
|
629
659
|
return placementsOf(element, stop).flatMap((around) => {
|
|
630
660
|
const key = JSON.stringify(around);
|
|
631
661
|
if (seen.has(key))
|
|
@@ -636,6 +666,8 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
|
|
|
636
666
|
target,
|
|
637
667
|
name: opening.tagName.getText(sourceFile),
|
|
638
668
|
at: spanOf(opening),
|
|
669
|
+
...(text === undefined ? {} : { text }),
|
|
670
|
+
...(wrapper === undefined ? {} : { wrapper }),
|
|
639
671
|
around: around ?? [],
|
|
640
672
|
unknown: around === null,
|
|
641
673
|
},
|
|
@@ -771,9 +803,20 @@ function readRender(value) {
|
|
|
771
803
|
return undefined;
|
|
772
804
|
if (typeof f.unknown !== "boolean")
|
|
773
805
|
return undefined;
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
806
|
+
if (!isString(f.target) || !isString(f.name))
|
|
807
|
+
return undefined;
|
|
808
|
+
const wrapper = f.wrapper === undefined ? undefined : fieldsOf(f.wrapper);
|
|
809
|
+
return {
|
|
810
|
+
target: f.target,
|
|
811
|
+
name: f.name,
|
|
812
|
+
at,
|
|
813
|
+
...(isString(f.text) ? { text: f.text } : {}),
|
|
814
|
+
...(isString(wrapper?.tag) && isString(wrapper.package)
|
|
815
|
+
? { wrapper: { tag: wrapper.tag, package: wrapper.package } }
|
|
816
|
+
: {}),
|
|
817
|
+
around,
|
|
818
|
+
unknown: f.unknown,
|
|
819
|
+
};
|
|
777
820
|
}
|
|
778
821
|
function readChain(value) {
|
|
779
822
|
if (value === null)
|
|
@@ -816,7 +859,7 @@ function readBoundary(value) {
|
|
|
816
859
|
if (f === undefined || at === undefined || fallbacks === undefined)
|
|
817
860
|
return undefined;
|
|
818
861
|
return isString(f.key) && isString(f.name)
|
|
819
|
-
? { key: f.key, name: f.name, at, fallbacks }
|
|
862
|
+
? { key: f.key, name: f.name, at, ...(f.own === true ? { own: true } : {}), fallbacks }
|
|
820
863
|
: undefined;
|
|
821
864
|
}
|
|
822
865
|
const KINDS = ["component", "hook", "class"];
|
package/dist/refactors.js
CHANGED
|
@@ -56,11 +56,44 @@ export const codeActions = (input) => {
|
|
|
56
56
|
location: { file: input.file, start: offset, end: offset },
|
|
57
57
|
newText,
|
|
58
58
|
});
|
|
59
|
+
const lineStart = sourceFile.text.lastIndexOf("\n", clause.getStart(sourceFile)) + 1;
|
|
60
|
+
const base = /^[ \t]*/.exec(sourceFile.text.slice(lineStart))?.[0] ?? "";
|
|
61
|
+
const [first] = clause.block.statements;
|
|
62
|
+
const firstIndent = first === undefined
|
|
63
|
+
? ""
|
|
64
|
+
: (/^[ \t]*/.exec(sourceFile.text.slice(sourceFile.text.lastIndexOf("\n", first.getStart(sourceFile)) + 1))?.[0] ?? "");
|
|
65
|
+
const unit = firstIndent.startsWith(base) && firstIndent.length > base.length
|
|
66
|
+
? firstIndent.slice(base.length)
|
|
67
|
+
: " ";
|
|
68
|
+
const inner = `${base}${unit}`;
|
|
69
|
+
const body = sourceFile.text.slice(open + 1, close - 1);
|
|
70
|
+
// A text that spans lines (a template literal) must keep its own lines: the body is then left
|
|
71
|
+
// as written, with only the lines around it indented.
|
|
72
|
+
const spansLines = (node) => ((ts.isTemplateLiteral(node) || ts.isStringLiteralLike(node)) &&
|
|
73
|
+
node.getText(sourceFile).includes("\n")) ||
|
|
74
|
+
ts.forEachChild(node, spansLines) === true;
|
|
75
|
+
if (spansLines(clause.block)) {
|
|
76
|
+
actions.push({
|
|
77
|
+
title: HANDLE_KNOWN_TITLE,
|
|
78
|
+
edits: [
|
|
79
|
+
at(open + 1, `\n${inner}if (${tests}) {`),
|
|
80
|
+
at(close - 1, `${inner}} else {\n${inner}${unit}throw ${variable};\n${inner}}\n${base}`),
|
|
81
|
+
],
|
|
82
|
+
});
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const indented = body
|
|
86
|
+
.split("\n")
|
|
87
|
+
.map((line) => (line.trim() === "" ? line : `${unit}${line}`))
|
|
88
|
+
.join("\n")
|
|
89
|
+
.replace(/\s+$/, "");
|
|
59
90
|
actions.push({
|
|
60
91
|
title: HANDLE_KNOWN_TITLE,
|
|
61
92
|
edits: [
|
|
62
|
-
|
|
63
|
-
|
|
93
|
+
{
|
|
94
|
+
location: { file: input.file, start: open + 1, end: close - 1 },
|
|
95
|
+
newText: `\n${inner}if (${tests}) {${indented}\n${inner}} else {\n${inner}${unit}throw ${variable};\n${inner}}\n${base}`,
|
|
96
|
+
},
|
|
64
97
|
],
|
|
65
98
|
});
|
|
66
99
|
}
|
|
@@ -2,7 +2,7 @@ import { defineRule, highestUncovered, option, shortestPath } from "@stateward/c
|
|
|
2
2
|
import { className } from "./inference/format.js";
|
|
3
3
|
import { modelOf, summarizeReact } from "./react/boundaries.js";
|
|
4
4
|
import { LIBRARY_BOUNDARIES } from "./react/tree.js";
|
|
5
|
-
import { codeList, fitted,
|
|
5
|
+
import { codeList, fitted, waysHint } from "./text.js";
|
|
6
6
|
/** The group the rule belongs to in the docs and in `stateward status`. */
|
|
7
7
|
export const GROUP = "render";
|
|
8
8
|
const EXPLAIN = `# errors/render-throw-without-boundary
|
|
@@ -60,6 +60,8 @@ createRoot(document.body).render(<App />);
|
|
|
60
60
|
|
|
61
61
|
There is no quick fix: where the boundary goes, and what it shows, is your call.
|
|
62
62
|
|
|
63
|
+
The message offers the ways it can be fixed, with your own element as it is written. When the finding is at the app's own render, it points to the render below it that throws (a boundary around the whole app is not counted, see below), and to \`rootBoundaryCounts\` for one fallback for the whole app. If a component around it from another package is an error boundary, it shows the \`boundaries\` option with that package added to the ones already there. Where the project already has an error boundary, it names that one; where it has none, react-error-boundary's \`ErrorBoundary\` (imported as a value) or a class of yours with \`getDerivedStateFromError\`.
|
|
64
|
+
|
|
63
65
|
## Why it matters
|
|
64
66
|
|
|
65
67
|
When a component throws while React renders it, or in one of its effects, React unmounts everything up to the nearest error boundary. With no boundary above, the whole app goes blank: a \`<UserPage>\` that throws \`NotFoundError\` for a wrong id takes the menu and every other route down with it, where a boundary could have shown "this user does not exist".
|
|
@@ -100,18 +102,104 @@ function headline(component, names) {
|
|
|
100
102
|
function rootHeadline(component, names) {
|
|
101
103
|
return fitted((cut) => `\`<${cut(component)}>\` can throw ${codeList(names, cut)} while rendering; only the app-wide boundary catches it`);
|
|
102
104
|
}
|
|
103
|
-
function rootHint(component) {
|
|
104
|
-
return withExample("add a boundary around it, or set `rootBoundaryCounts` if replacing the whole app is intended:", ["<ErrorBoundary FallbackComponent={ErrorPage}>", ` <${component} />`, "</ErrorBoundary>"]);
|
|
105
|
-
}
|
|
106
105
|
/** The reason `plan` gives when a root boundary makes the rule silent. */
|
|
107
106
|
export const ROOT_BOUNDARY_SILENT = "your app's root has an error boundary";
|
|
108
|
-
|
|
109
|
-
|
|
107
|
+
/** The error boundaries the project already renders, by name (its own classes and packages'). */
|
|
108
|
+
function boundaryNames(model) {
|
|
109
|
+
return [...new Set([...model.boundaries.values()].map((one) => one.element.name))].sort();
|
|
110
|
+
}
|
|
111
|
+
/** The `fallback` a wrapped example shows: the boundary's own prop, with the text left to the project. */
|
|
112
|
+
const FALLBACK = "fallback={<p>Something went wrong.</p>}";
|
|
113
|
+
/** `render` inside react-error-boundary's `ErrorBoundary`, or undefined when the element is too long to quote. */
|
|
114
|
+
function wrapped(render) {
|
|
115
|
+
return render.text === undefined
|
|
116
|
+
? undefined
|
|
117
|
+
: [`<ErrorBoundary ${FALLBACK}>`, ` ${render.text}`, "</ErrorBoundary>"];
|
|
118
|
+
}
|
|
119
|
+
/** Wrap `render` in an error boundary: the project's own when it has one, else react-error-boundary's. */
|
|
120
|
+
function wrapWay(model, render, where) {
|
|
121
|
+
const known = boundaryNames(model);
|
|
122
|
+
const [first] = known;
|
|
123
|
+
if (first !== undefined) {
|
|
124
|
+
return {
|
|
125
|
+
text: `wrap \`<${render.name}>\` in \`${first}\`, which the project already uses${where}`,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
const lines = wrapped(render);
|
|
129
|
+
const from = "react-error-boundary's `ErrorBoundary` (imported as a value), or a class of yours with `getDerivedStateFromError`";
|
|
130
|
+
return lines === undefined
|
|
131
|
+
? { text: `wrap \`<${render.name}>\` and what it contains in ${from}${where}` }
|
|
132
|
+
: { text: `wrap it in ${from}${where}`, example: lines };
|
|
133
|
+
}
|
|
134
|
+
/** An element around the render that is named like an error boundary from a package: list it under `boundaries`. */
|
|
135
|
+
function listedWay(render, listed) {
|
|
136
|
+
const wrapper = render.wrapper;
|
|
137
|
+
if (wrapper === undefined || (listed[wrapper.package] ?? []).includes(wrapper.tag)) {
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
const merged = {};
|
|
141
|
+
for (const [name, tags] of Object.entries(listed))
|
|
142
|
+
merged[name] = [...tags];
|
|
143
|
+
merged[wrapper.package] = [...(merged[wrapper.package] ?? []), wrapper.tag];
|
|
144
|
+
const entries = Object.entries(merged).map(([name, tags]) => ` ${JSON.stringify(name)}: [${tags.map((one) => JSON.stringify(one)).join(", ")}],`);
|
|
145
|
+
const text = `if \`<${wrapper.tag}>\` from \`${wrapper.package}\` is an error boundary, add it to the \`boundaries\` option, next to the ones already there`;
|
|
146
|
+
// The example is at most four lines: a longer list is described instead.
|
|
147
|
+
return entries.length <= 2
|
|
148
|
+
? { text, example: ["boundaries: {", ...entries, "}"] }
|
|
149
|
+
: { text: `${text}: ${JSON.stringify(wrapper.package)}: [${JSON.stringify(wrapper.tag)}]` };
|
|
150
|
+
}
|
|
151
|
+
/** Wrap an entry's own render: only a boundary the app-wide option counts. */
|
|
152
|
+
function rootWay(model, render) {
|
|
153
|
+
const lines = boundaryNames(model).length === 0 ? wrapped(render) : undefined;
|
|
154
|
+
const text = "if one fallback for the whole app is what you want, wrap it and set the `rootBoundaryCounts` option to `true`";
|
|
155
|
+
return lines === undefined ? { text } : { text, example: lines };
|
|
156
|
+
}
|
|
157
|
+
/** The ways to put an error boundary where the render has none above it. */
|
|
158
|
+
function ways(place, root) {
|
|
159
|
+
const { model, site, below, isEntry } = place;
|
|
160
|
+
const listed = (render) => {
|
|
161
|
+
const way = listedWay(render, place.options.boundaries);
|
|
162
|
+
return way === undefined ? [] : [way];
|
|
163
|
+
};
|
|
164
|
+
if (isEntry && below !== undefined) {
|
|
165
|
+
// A boundary around the whole app is not counted: the way out is the render below it.
|
|
166
|
+
const render = below.render;
|
|
167
|
+
return waysHint([
|
|
168
|
+
wrapWay(model, render, ", not around the whole app"),
|
|
169
|
+
rootWay(model, site.render),
|
|
170
|
+
...listed(render),
|
|
171
|
+
]);
|
|
172
|
+
}
|
|
173
|
+
if (isEntry) {
|
|
174
|
+
return waysHint([
|
|
175
|
+
{
|
|
176
|
+
text: "move what `<" +
|
|
177
|
+
site.render.name +
|
|
178
|
+
">` throws into a component it renders, and wrap that render in an error boundary",
|
|
179
|
+
},
|
|
180
|
+
rootWay(model, site.render),
|
|
181
|
+
]);
|
|
182
|
+
}
|
|
183
|
+
const own = wrapWay(model, site.render, ", at this render or nearer to what throws");
|
|
184
|
+
return waysHint([
|
|
185
|
+
own,
|
|
186
|
+
...(root
|
|
187
|
+
? [
|
|
188
|
+
{
|
|
189
|
+
text: "if replacing the whole app by its fallback is intended, set the `rootBoundaryCounts` option to `true`: the boundary around the app then counts",
|
|
190
|
+
},
|
|
191
|
+
]
|
|
192
|
+
: []),
|
|
193
|
+
...listed(site.render),
|
|
194
|
+
]);
|
|
195
|
+
}
|
|
196
|
+
/** The renders down from the site to the component that throws `cls`; undefined when none is found. */
|
|
197
|
+
function pathTo(model, site, cls) {
|
|
198
|
+
return shortestPath(site.to, (id) => model.edges(id), (edge) => model.nearest(edge) === undefined && model.needs(edge.to).has(cls), (id) => model.own(id).classes.get(cls)?.certain === true && !model.own(id).guarded.has(cls));
|
|
110
199
|
}
|
|
111
200
|
/** The renders down from the site to the component that throws `cls`, then the call that throws it. */
|
|
112
|
-
function pathNotes(model, site, cls) {
|
|
201
|
+
function pathNotes(model, site, cls, path) {
|
|
113
202
|
const classes = model.analysis.classes;
|
|
114
|
-
const path = shortestPath(site.to, (id) => model.edges(id), (edge) => model.nearest(edge) === undefined && model.needs(edge.to).has(cls), (id) => model.own(id).classes.get(cls)?.certain === true && !model.own(id).guarded.has(cls));
|
|
115
203
|
if (path === undefined)
|
|
116
204
|
return [];
|
|
117
205
|
const notes = path.map((edge) => ({
|
|
@@ -228,11 +316,13 @@ export const renderThrowWithoutBoundary = defineRule({
|
|
|
228
316
|
continue;
|
|
229
317
|
const component = model.functions.get(edge.to)?.fn.name ?? edge.render.name;
|
|
230
318
|
const names = named.map((one) => one.name);
|
|
319
|
+
const path = pathTo(model, edge, first.id);
|
|
320
|
+
const isEntry = model.entries.some((entry) => entry.file === edge.file && entry.render.at[0] === edge.render.at[0]);
|
|
231
321
|
ctx.report({
|
|
232
322
|
message: root ? rootHeadline(component, names) : headline(component, names),
|
|
233
|
-
hint:
|
|
323
|
+
hint: ways({ model, options: ctx.options, site: edge, below: path?.[0], isEntry }, root),
|
|
234
324
|
location: { file: edge.file, start: edge.render.at[0], end: edge.render.at[1] },
|
|
235
|
-
related: pathNotes(model, edge, first.id),
|
|
325
|
+
related: pathNotes(model, edge, first.id, path),
|
|
236
326
|
});
|
|
237
327
|
}
|
|
238
328
|
},
|
package/dist/result-ignored.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import ts from "@stateward/core/typescript";
|
|
2
2
|
import { defineRule, matchesName, option } from "@stateward/core";
|
|
3
|
-
import { example, resultShapeOf, shorten } from "./result-type.js";
|
|
3
|
+
import { example, freeName, resultShapeOf, shorten } from "./result-type.js";
|
|
4
4
|
const EXPLAIN = `# errors/result-ignored
|
|
5
5
|
|
|
6
6
|
A \`Result\` dropped as a statement discards its error, so a failed call looks the same as a successful one.
|
|
@@ -29,7 +29,7 @@ export async function rename(name: string): Promise<Result<void>> {
|
|
|
29
29
|
}
|
|
30
30
|
\`\`\`
|
|
31
31
|
|
|
32
|
-
The message shows how, with your names and your Result's shape. There is no quick fix.
|
|
32
|
+
The message shows how, with your names and your Result's shape: the check, and \`return\` of it only where the function returns that Result. If the drop is on purpose, it says so in the rule's options: \`allowVoid\` for \`void save()\`, \`ignore\` for a function that may always be dropped. There is no quick fix.
|
|
33
33
|
|
|
34
34
|
## Why it matters
|
|
35
35
|
|
|
@@ -92,14 +92,14 @@ function isVoided(expression) {
|
|
|
92
92
|
isVoided(expression.expression));
|
|
93
93
|
}
|
|
94
94
|
/** The line of the example that checks the result, in the Result's own shape. */
|
|
95
|
-
function checkLine(shape) {
|
|
95
|
+
function checkLine(shape, name, returnsIt) {
|
|
96
96
|
switch (shape) {
|
|
97
97
|
case "ok":
|
|
98
|
-
return
|
|
98
|
+
return returnsIt ? `if (!${name}.ok) return ${name};` : `if (!${name}.ok) { … }`;
|
|
99
99
|
case "success":
|
|
100
|
-
return
|
|
100
|
+
return returnsIt ? `if (!${name}.success) return ${name};` : `if (!${name}.success) { … }`;
|
|
101
101
|
case "isErr":
|
|
102
|
-
return
|
|
102
|
+
return returnsIt ? `if (${name}.isErr()) return ${name};` : `if (${name}.isErr()) { … }`;
|
|
103
103
|
case "named":
|
|
104
104
|
return "// handle its failure here, or return it";
|
|
105
105
|
default: {
|
|
@@ -108,6 +108,27 @@ function checkLine(shape) {
|
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
|
+
/** `Result<void, E>` of `Promise<Result<void, E>>`: the type of what the call gives once awaited. */
|
|
112
|
+
function awaitedText(text) {
|
|
113
|
+
const match = /^(?:Promise|PromiseLike)<(.*)>$/.exec(text.trim());
|
|
114
|
+
return (match?.[1] ?? text).trim();
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Whether returning the checked Result is valid code here: the function declares the type the
|
|
118
|
+
* call gives (once awaited), so the failed branch of it is what the function returns.
|
|
119
|
+
*/
|
|
120
|
+
function returnsSameResult(call, fn, ctx) {
|
|
121
|
+
if (fn?.type === undefined)
|
|
122
|
+
return false;
|
|
123
|
+
return awaitedText(ctx.types.typeTextOf(fn.type)) === awaitedText(ctx.types.typeTextOf(call));
|
|
124
|
+
}
|
|
125
|
+
/** Whether `await` is valid where the statement is: in an async function, or at a module's top. */
|
|
126
|
+
function canAwait(fn) {
|
|
127
|
+
if (fn === undefined)
|
|
128
|
+
return true;
|
|
129
|
+
const modifiers = ts.canHaveModifiers(fn) ? ts.getModifiers(fn) : undefined;
|
|
130
|
+
return modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) === true;
|
|
131
|
+
}
|
|
111
132
|
function checkStatement(statement, ctx) {
|
|
112
133
|
if (ctx.options.allowVoid && isVoided(statement.expression))
|
|
113
134
|
return;
|
|
@@ -126,14 +147,34 @@ function checkStatement(statement, ctx) {
|
|
|
126
147
|
const callText = whole.length > CALL_MAX
|
|
127
148
|
? `${shorten(call.expression.getText(ctx.sourceFile), CALL_MAX)}(…)`
|
|
128
149
|
: whole;
|
|
150
|
+
const fn = ts.findAncestor(statement.parent, ts.isFunctionLike);
|
|
151
|
+
const name = freeName(fn ?? ctx.sourceFile, ctx.sourceFile, [
|
|
152
|
+
"saved",
|
|
153
|
+
"result",
|
|
154
|
+
"outcome",
|
|
155
|
+
"checked",
|
|
156
|
+
]);
|
|
157
|
+
const returnsIt = returnsSameResult(call, fn, ctx);
|
|
158
|
+
const needsAsync = promised && !canAwait(fn);
|
|
159
|
+
const handled = returnsIt
|
|
160
|
+
? "check it, and pass it on"
|
|
161
|
+
: "check it, and handle its failure (report it, recover, or pass it on from a function that returns a Result)";
|
|
162
|
+
const ways = [
|
|
163
|
+
`- ${handled}${needsAsync ? "; `await` needs the function to be `async`" : ""}`,
|
|
164
|
+
example([
|
|
165
|
+
`const ${name} = ${promised ? "await " : ""}${callText};`,
|
|
166
|
+
checkLine(shape, name, returnsIt),
|
|
167
|
+
]),
|
|
168
|
+
isVoided(statement.expression)
|
|
169
|
+
? "- or, if dropping it is on purpose, set the rule's `allowVoid` option to `true`: a `void` drop is then stated"
|
|
170
|
+
: "- or, if dropping it is on purpose, write `void` before the call and set the rule's `allowVoid` option to `true`",
|
|
171
|
+
`- or, if \`${callee}\` may always be dropped, list it under the rule's \`ignore\` option`,
|
|
172
|
+
];
|
|
129
173
|
ctx.report({
|
|
130
174
|
node: statement,
|
|
131
175
|
about: statement,
|
|
132
176
|
message: `the \`Result\` of \`${calleeText(call, ctx)}(…)\` is dropped: its error is never handled`,
|
|
133
|
-
hint: [
|
|
134
|
-
"check it, or pass it on:",
|
|
135
|
-
example([`const saved = ${promised ? "await " : ""}${callText};`, checkLine(shape)]),
|
|
136
|
-
].join("\n"),
|
|
177
|
+
hint: ["one of", ...ways].join("\n"),
|
|
137
178
|
});
|
|
138
179
|
}
|
|
139
180
|
export const resultIgnored = defineRule({
|
package/dist/result-type.d.ts
CHANGED
|
@@ -15,4 +15,6 @@ export declare function resultShapeOf(node: ts.Node, types: TypeQueries, names:
|
|
|
15
15
|
export declare function shorten(text: string, max: number): string;
|
|
16
16
|
/** A hint's example: indented 4 spaces, one line per entry. */
|
|
17
17
|
export declare function example(lines: readonly string[]): string;
|
|
18
|
+
/** The first of `names` that the code under `scope` does not use already, so an example never shadows one. */
|
|
19
|
+
export declare function freeName(scope: ts.Node, sourceFile: ts.SourceFile, names: readonly string[]): string;
|
|
18
20
|
//# sourceMappingURL=result-type.d.ts.map
|
package/dist/result-type.js
CHANGED
|
@@ -52,4 +52,10 @@ export function shorten(text, max) {
|
|
|
52
52
|
export function example(lines) {
|
|
53
53
|
return lines.map((line) => ` ${line}`).join("\n");
|
|
54
54
|
}
|
|
55
|
+
/** The first of `names` that the code under `scope` does not use already, so an example never shadows one. */
|
|
56
|
+
export function freeName(scope, sourceFile, names) {
|
|
57
|
+
const text = scope.getText(sourceFile);
|
|
58
|
+
const free = names.find((name) => !new RegExp(`\\b${name}\\b`).test(text));
|
|
59
|
+
return free ?? `${names[0] ?? "result"}Checked`;
|
|
60
|
+
}
|
|
55
61
|
//# sourceMappingURL=result-type.js.map
|