@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
@@ -3,9 +3,18 @@ export declare const GROUP = "render";
3
3
  /** The reason `plan` gives when a root boundary makes the rule silent. */
4
4
  export declare const ROOT_BOUNDARY_SILENT = "your app's root has an error boundary";
5
5
  export declare const renderThrowWithoutBoundary: import("@stateward/core").ProjectRule<import("./react/boundaries.js").ReactSummary, {
6
- skipContextGuards: import("@stateward/core").BooleanOption;
7
- skipInputGuards: import("@stateward/core").BooleanOption;
8
- rootBoundaryCounts: import("@stateward/core").BooleanOption;
6
+ skipContextGuards: import("@stateward/core").BooleanOption & Pick<{
7
+ readonly default: true;
8
+ readonly description: "Leave out the usual check in a context hook: `if (!ctx) throw new Error(\"useAuth must be used within AuthProvider\")`.";
9
+ }, "internal">;
10
+ skipInputGuards: import("@stateward/core").BooleanOption & Pick<{
11
+ readonly default: true;
12
+ readonly description: "Leave out a throw when a prop or a parameter whose type rules it out, or a context hook's value, is missing (a mistake of the caller).";
13
+ }, "internal">;
14
+ rootBoundaryCounts: import("@stateward/core").BooleanOption & Pick<{
15
+ readonly default: false;
16
+ readonly description: "Count the error boundary around the whole app as handling the error. Off by default: the whole app is then replaced by its fallback, so the rule asks for a boundary nearer the page.";
17
+ }, "internal">;
9
18
  boundaries: import("@stateward/core").RecordOption;
10
- }, "render">;
19
+ }, "render", Readonly<Record<string, import("@stateward/core").Json>>>;
11
20
  //# sourceMappingURL=render-throw-without-boundary.d.ts.map
@@ -1,5 +1,6 @@
1
1
  import { defineRule, highestUncovered, option, shortestPath } from "@stateward/core";
2
2
  import { className } from "./inference/format.js";
3
+ import { THROWS_ANALYSIS } from "./inference/deps.js";
3
4
  import { modelOf, summarizeReact } from "./react/boundaries.js";
4
5
  import { LIBRARY_BOUNDARIES } from "./react/tree.js";
5
6
  import { codeList, fitted, waysHint } from "./text.js";
@@ -268,6 +269,7 @@ export const renderThrowWithoutBoundary = defineRule({
268
269
  },
269
270
  explain: EXPLAIN,
270
271
  },
272
+ reads: [THROWS_ANALYSIS],
271
273
  summarize: (ctx) => summarizeReact(ctx, ctx.options.boundaries, {
272
274
  contextGuards: ctx.options.skipContextGuards,
273
275
  inputGuards: ctx.options.skipInputGuards,
@@ -275,13 +277,13 @@ export const renderThrowWithoutBoundary = defineRule({
275
277
  silentReason(summaries, ctx) {
276
278
  if (!ctx.options.rootBoundaryCounts)
277
279
  return undefined;
278
- const model = modelOf(summaries);
280
+ const model = modelOf(summaries, ctx.analysisSummaries(THROWS_ANALYSIS));
279
281
  return model.entries.length > 0 && model.entries.every((entry) => rootBoundaryOf(model, entry))
280
282
  ? ROOT_BOUNDARY_SILENT
281
283
  : undefined;
282
284
  },
283
285
  check(summaries, ctx) {
284
- const model = modelOf(summaries);
286
+ const model = modelOf(summaries, ctx.analysisSummaries(THROWS_ANALYSIS));
285
287
  const classes = model.analysis.classes;
286
288
  const walk = (roots, open = []) => highestUncovered({
287
289
  roots,
@@ -1,5 +1,8 @@
1
1
  export declare const resultIgnored: import("@stateward/core").FileRule<{
2
- allowVoid: import("@stateward/core").BooleanOption;
2
+ allowVoid: import("@stateward/core").BooleanOption & Pick<{
3
+ readonly default: false;
4
+ readonly description: "Take `void save()` as dropping the Result on purpose, and stay quiet.";
5
+ }, "internal">;
3
6
  resultTypes: import("@stateward/core").StringsOption;
4
7
  ignore: import("@stateward/core").StringsOption;
5
8
  }, "callers">;
@@ -1,4 +1,4 @@
1
- import { matchesName } from "@stateward/core";
1
+ import { codeOnOneLine, matchesName } from "@stateward/core";
2
2
  /**
3
3
  * Whether a property tells the members of a union apart by `true` and `false`. An object with
4
4
  * `ok: boolean` (a fetch `Response`) is not a union, so it is not a Result.
@@ -45,7 +45,7 @@ export function resultShapeOf(node, types, names) {
45
45
  }
46
46
  /** Cuts `text` to `max` characters, ending in `…`, for a headline or an example line. */
47
47
  export function shorten(text, max) {
48
- const flat = text.replace(/\s+/g, " ").trim();
48
+ const flat = codeOnOneLine(text);
49
49
  return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
50
50
  }
51
51
  /** A hint's example: indented 4 spaces, one line per entry. */
@@ -1,2 +1,5 @@
1
- export declare const resultUnchecked: import("@stateward/core").FileRule<Readonly<Record<string, never>>, "callers">;
1
+ export declare const resultUnchecked: import("@stateward/core").FileRule<{
2
+ failureNames: import("@stateward/core").StringsOption;
3
+ successNames: import("@stateward/core").StringsOption;
4
+ }, "callers">;
2
5
  //# sourceMappingURL=result-unchecked.d.ts.map
@@ -1,7 +1,8 @@
1
1
  import ts from "@stateward/core/typescript";
2
- import { defineRule } from "@stateward/core";
2
+ import { codeOnOneLine, defineRule, matchesName, option, offByDefaultText } from "@stateward/core";
3
3
  import { example, freeName, resultShapeOf, shorten } from "./result-type.js";
4
- import { oneLine } from "./text.js";
4
+ /** Off by default since 1.3: 0 of 5 of its findings checked on real projects were right. */
5
+ const OFF_BY_DEFAULT = { since: "1.3", right: 0, checked: 5 };
5
6
  const EXPLAIN = `# errors/result-unchecked
6
7
 
7
8
  A call that returns its failure instead of throwing never reaches the \`catch\`; without a check, the code after it runs as if the call worked.
@@ -47,7 +48,7 @@ Some calls do not throw when they fail: they resolve to data or an error. An RTK
47
48
 
48
49
  ## When it says “not checked”
49
50
 
50
- An \`if\` that tests the result in a way stateward cannot read (\`if (result.error && isApiError(result.error))\`) is listed as a place not checked. Test it in one of the ways below, then narrow further inside.
51
+ An \`if\` that tests the result in a way stateward cannot read (\`if (result.error && isApiError(result.error))\`) is listed as a place not checked. Test it in one of the ways below, then narrow further inside. A test reads the names the result's type gives its parts: \`error\`, a trigger's \`data\`, a Result's \`ok\` or \`success\`, and the \`isOk()\` and \`isErr()\` methods. Another name (\`isError\`, \`isSuccess\`, \`value\`, a function such as \`isFailure(result)\`) says nothing by itself: list it in \`failureNames\` or \`successNames\`, and the test is read.
51
52
 
52
53
  ## What it does not catch
53
54
 
@@ -57,45 +58,63 @@ It looks at a call whose value is data or an error: a promise with an \`unwrap()
57
58
  - it is awaited as a statement inside a \`try\` after another call (an optimistic \`setFolders(…)\`), with more lines after it: when it fails, those lines run and the \`catch\` (the rollback) does not;
58
59
  - a trigger is awaited as a statement outside a \`try\`, with more lines after it (\`await sendReply(x); setText("")\`);
59
60
  - it is stored, then its data is read before it is checked;
60
- - it is stored, and its error is read in an \`if\` that does not \`return\` or \`throw\` (\`"error" in result\`, \`result.error\`, \`!result.ok\`, or an \`error\` or \`isError\` taken out of it), with more lines after that \`if\`.
61
+ - it is stored, and its error is read in an \`if\` that does not \`return\` or \`throw\` (\`"error" in result\`, \`result.error\`, \`!result.ok\`, or an \`error\` taken out of it), with more lines after that \`if\`.
61
62
 
62
63
  It is silent on:
63
64
 
64
65
  - a Result dropped as a statement: that is \`errors/result-ignored\`;
65
66
  - lines after the call that only set back a pending state set before it (\`setSaving(true)\` … \`setSaving(false)\`): they run either way on purpose;
66
67
  - a \`try\` with another \`await\` or a \`throw\` in it: the \`catch\` may be there for that;
68
+ - an \`if\` whose failure branch ends in a call declared to return \`never\` (\`process.exit(1)\`): the lines after it do not run;
67
69
  - a result passed on, returned, stored elsewhere, or checked in a callback;
68
70
  - a promise that rejects on failure (react-query's \`mutateAsync\`, \`fetch\`): it has no \`unwrap()\` that resolves to data or an error.
69
71
 
70
72
  ## Getting the best from it
71
73
 
72
- Code that says what it means is left alone: \`void trigger(…)\`, \`.unwrap()\`, a check (\`"error" in result\`, \`if (result.error) return\`, \`isOk(result)\`, \`const { data, isError } = await dispatch(…); if (isError) throw …\`) before the success path, an \`if\` with an \`else\` for the success path, and a component that reads the trigger's own \`isError\` or \`error\` from its hook (\`const [save, { isError }] = useSaveMutation()\`).
74
+ Code that says what it means is left alone: \`void trigger(…)\`, \`.unwrap()\`, a check (\`"error" in result\`, \`if (result.error) return\`, \`result.isErr()\`, \`const { data, error } = await dispatch(…); if (error) throw …\`) before the success path, an \`if\` with an \`else\` for the success path, and a component that reads the trigger's own \`error\` from its hook (\`const [save, { error }] = useSaveMutation()\`), or a name \`failureNames\` lists (\`isError\`).
73
75
 
74
76
  ## Turn it on or off
75
77
 
78
+ ${offByDefaultText(OFF_BY_DEFAULT)}
79
+
76
80
  \`\`\`ts
77
- rules: { "errors/result-unchecked": "off" } // or "error"
81
+ addons: ["errors/result-unchecked"]
82
+ rules: { "errors/result-unchecked": "error" } // on, as an error
83
+ rules: { "errors/result-unchecked": ["warning", { failureNames: ["isError"], successNames: ["isSuccess"] }] } // RTK Query's state flags
78
84
  \`\`\`
79
85
  `;
86
+ const OPTIONS = {
87
+ failureNames: option.strings({
88
+ default: [],
89
+ description: "Names (or globs like isErr*) that are true when the call failed, besides the result's own `error`: a property of the result (`isError`), or a function called with it (`isFailure(result)`). Its type does not say what such a name means.",
90
+ }),
91
+ successNames: option.strings({
92
+ default: [],
93
+ description: "Names (or globs) that are true when the call worked, besides the result's own `data`, `ok` and `success`: a property of the result (`isSuccess`, `value`), or a function called with it (`isOk(result)`).",
94
+ }),
95
+ };
80
96
  /** The longest call an example line shows before its arguments become `…`. */
81
97
  const CALL_MAX = 60;
82
98
  /** The longest condition the fix hint quotes. */
83
99
  const CONDITION_MAX = 50;
84
- // `isError` and `isSuccess`: an RTK Query state (`await dispatch(api.endpoints.x.initiate(…))`)
85
- // carries them next to `data` and `error`, and testing one is as much a check as testing `error`.
100
+ // The names the result's shape gives its parts (`error`, a trigger's `data`, a Result's `ok` or
101
+ // `success`): what testing one says is in the type. Any other name is read through the options.
86
102
  const ALIAS_KINDS = new Map([
87
103
  ["error", "error"],
88
- ["isError", "error"],
89
104
  ["data", "data"],
90
- ["value", "data"],
91
105
  ["ok", "ok"],
92
106
  ["success", "ok"],
93
- ["isSuccess", "ok"],
94
107
  ]);
95
- const DATA_PROPERTIES = new Set(["data", "value"]);
96
- const SUCCESS_PROPERTIES = new Set(["data", "value", "ok", "success"]);
97
- const FAILURE_GUARD = /^is(?:Err|Error|Failure|Failed)$/;
98
- const SUCCESS_GUARD = /^is(?:Ok|Success|Succeeded)$/;
108
+ const DATA_PROPERTIES = new Set(["data"]);
109
+ const SUCCESS_PROPERTIES = new Set(["data", "ok", "success"]);
110
+ /** What a name the options list says: `failure`, `success`, or nothing. */
111
+ function namedPolarity(name, names) {
112
+ if (matchesName(name, names.failure))
113
+ return "failure";
114
+ if (matchesName(name, names.success))
115
+ return "success";
116
+ return undefined;
117
+ }
99
118
  function strip(expression) {
100
119
  return ts.isParenthesizedExpression(expression) ? strip(expression.expression) : expression;
101
120
  }
@@ -328,6 +347,8 @@ function polarity(expression, tracked) {
328
347
  const alias = tracked.aliases.get(code.text);
329
348
  if (alias === "error")
330
349
  return "failure";
350
+ if (alias === "unknown")
351
+ return "undecided";
331
352
  if (alias !== undefined)
332
353
  return "success";
333
354
  return code.text === tracked.whole ? "undecided" : "none";
@@ -335,7 +356,9 @@ function polarity(expression, tracked) {
335
356
  if (ts.isPropertyAccessExpression(code) && isWhole(code.expression, tracked)) {
336
357
  if (code.name.text === "error")
337
358
  return "failure";
338
- return SUCCESS_PROPERTIES.has(code.name.text) ? "success" : "undecided";
359
+ if (SUCCESS_PROPERTIES.has(code.name.text))
360
+ return "success";
361
+ return namedPolarity(code.name.text, tracked.names) ?? "undecided";
339
362
  }
340
363
  if (ts.isCallExpression(code)) {
341
364
  const callee = strip(code.expression);
@@ -350,10 +373,9 @@ function polarity(expression, tracked) {
350
373
  code.arguments.length === 1 &&
351
374
  argument !== undefined &&
352
375
  isWhole(argument, tracked)) {
353
- if (FAILURE_GUARD.test(callee.text))
354
- return "failure";
355
- if (SUCCESS_GUARD.test(callee.text))
356
- return "success";
376
+ const named = namedPolarity(callee.text, tracked.names);
377
+ if (named !== undefined)
378
+ return named;
357
379
  }
358
380
  }
359
381
  if (ts.isBinaryExpression(code)) {
@@ -363,30 +385,44 @@ function polarity(expression, tracked) {
363
385
  isWhole(code.right, tracked)) {
364
386
  if (code.left.text === "error")
365
387
  return "failure";
366
- return DATA_PROPERTIES.has(code.left.text) ? "success" : "undecided";
388
+ if (DATA_PROPERTIES.has(code.left.text))
389
+ return "success";
390
+ return namedPolarity(code.left.text, tracked.names) ?? "undecided";
367
391
  }
368
392
  if (EQUAL.has(operator) || NOT_EQUAL.has(operator))
369
393
  return comparedPolarity(code, tracked);
370
394
  }
371
395
  return mentions(code, tracked) ? "undecided" : "none";
372
396
  }
373
- /** Whether a statement always leaves the block it is in: `return`, `throw`, `break`, `continue`. */
374
- function exits(statement) {
397
+ /**
398
+ * Whether a statement always leaves the block it is in: `return`, `throw`, `break`, `continue`,
399
+ * or a call whose declared return type is `never` (`process.exit(1)`), read from its type.
400
+ */
401
+ function exits(statement, ctx) {
375
402
  if (ts.isReturnStatement(statement) ||
376
403
  ts.isThrowStatement(statement) ||
377
404
  ts.isBreakStatement(statement) ||
378
405
  ts.isContinueStatement(statement)) {
379
406
  return true;
380
407
  }
408
+ if (ts.isExpressionStatement(statement))
409
+ return callsNever(statement.expression, ctx);
381
410
  if (ts.isBlock(statement))
382
- return statement.statements.some(exits);
411
+ return statement.statements.some((one) => exits(one, ctx));
383
412
  if (ts.isIfStatement(statement)) {
384
- return (exits(statement.thenStatement) &&
413
+ return (exits(statement.thenStatement, ctx) &&
385
414
  statement.elseStatement !== undefined &&
386
- exits(statement.elseStatement));
415
+ exits(statement.elseStatement, ctx));
387
416
  }
388
417
  return false;
389
418
  }
419
+ /** A call, awaited or not, whose type is `never`: it does not return to the next line. */
420
+ function callsNever(expression, ctx) {
421
+ let inner = strip(expression);
422
+ while (ts.isAwaitExpression(inner))
423
+ inner = strip(inner.expression);
424
+ return ts.isCallExpression(inner) && ctx.types.builtinTypeOf(inner, "as-is") === "never";
425
+ }
390
426
  function isFunctionLike(node) {
391
427
  return ts.isFunctionLike(node) || ts.isClassLike(node);
392
428
  }
@@ -397,15 +433,18 @@ function inBody(node, test) {
397
433
  return ts.forEachChild(node, (child) => !isFunctionLike(child) && inBody(child, test)) === true;
398
434
  }
399
435
  /**
400
- * Whether the component reads the trigger's own failure from its hook: `const [save, { isError }]
401
- * = useSaveMutation()`, or `const [save, saving] = …` and `saving.error` read. Failure is then
402
- * handled through the hook's result (stated intent), so code after the call may run either way.
436
+ * What the component reads of the trigger's own state from its hook: `const [save, { error }] =
437
+ * useSaveMutation()`, or `const [save, saving] = …` and `saving.error` read. `reads`: it reads the
438
+ * failure (the result's `error`, or a name `failureNames` lists), so failure is handled through the
439
+ * hook's result (stated intent) and code after the call may run either way. `unread`: it reads the
440
+ * state only by names nothing states (`isError`). `none`: it does not read it.
403
441
  */
404
- function hookStateRead(call, ctx) {
442
+ function hookState(call, ctx) {
405
443
  const callee = strip(call.expression);
406
444
  if (!ts.isIdentifier(callee))
407
- return false;
408
- const reads = new Set(["isError", "error"]);
445
+ return "none";
446
+ // The result's own `error`, and the names the `failureNames` option gives.
447
+ const reads = (name) => name === "error" || matchesName(name, ctx.options.failureNames);
409
448
  const hook = findNode(ctx.sourceFile, (node) => {
410
449
  if (!ts.isVariableDeclaration(node) || !ts.isArrayBindingPattern(node.name))
411
450
  return false;
@@ -416,26 +455,51 @@ function hookStateRead(call, ctx) {
416
455
  trigger.name.text === callee.text);
417
456
  });
418
457
  if (hook === undefined || !ts.isVariableDeclaration(hook))
419
- return false;
458
+ return "none";
420
459
  if (!ts.isArrayBindingPattern(hook.name))
421
- return false;
460
+ return "none";
422
461
  const second = hook.name.elements[1];
423
462
  if (second === undefined || !ts.isBindingElement(second))
424
- return false;
463
+ return "none";
425
464
  const found = second.name;
465
+ const names = [];
426
466
  if (ts.isObjectBindingPattern(found)) {
427
- return found.elements.some((element) => {
467
+ for (const element of found.elements) {
428
468
  const key = element.propertyName ?? element.name;
429
- return ts.isIdentifier(key) && reads.has(key.text);
469
+ if (ts.isIdentifier(key))
470
+ names.push(key.text);
471
+ }
472
+ }
473
+ else if (ts.isIdentifier(found)) {
474
+ const name = found.text;
475
+ someNode(ctx.sourceFile, (node) => {
476
+ if (ts.isPropertyAccessExpression(node) &&
477
+ ts.isIdentifier(node.expression) &&
478
+ node.expression.text === name) {
479
+ names.push(node.name.text);
480
+ }
481
+ return false;
430
482
  });
431
483
  }
432
- if (!ts.isIdentifier(found))
433
- return false;
434
- const name = found.text;
435
- return someNode(ctx.sourceFile, (node) => ts.isPropertyAccessExpression(node) &&
436
- ts.isIdentifier(node.expression) &&
437
- node.expression.text === name &&
438
- reads.has(node.name.text));
484
+ if (names.some(reads))
485
+ return "reads";
486
+ return names.length > 0 ? "unread" : "none";
487
+ }
488
+ /**
489
+ * Whether the component handles the trigger's failure through its hook, so nothing is reported:
490
+ * it reads it, or it reads the hook's state by names nothing states, and the call is "not
491
+ * checked" at `node`.
492
+ */
493
+ function handledByHook(call, node, ctx) {
494
+ const state = hookState(call, ctx);
495
+ if (state === "unread") {
496
+ ctx.unknown({
497
+ node,
498
+ message: `not checked: whether the component shows the failure of \`${calleeText(call, ctx)}(…)\` from its hook: no name it reads says so`,
499
+ hint: "list the name that is true when the call failed (`isError`) in the rule's `failureNames` option",
500
+ });
501
+ }
502
+ return state !== "none";
439
503
  }
440
504
  /** `await call(…);` as a statement: the call, or undefined. */
441
505
  function droppedAwait(statement) {
@@ -485,7 +549,7 @@ function checkTry(statement, ctx) {
485
549
  const after = statements.slice(index + 1);
486
550
  if (after.every((next) => undoesPending(next, statements.slice(0, index))))
487
551
  continue;
488
- if (hookStateRead(call, ctx))
552
+ if (handledByHook(call, inner, ctx))
489
553
  continue;
490
554
  ctx.report({
491
555
  node: inner,
@@ -603,7 +667,7 @@ function checkDropped(statement, ctx) {
603
667
  // The type questions after the syntax that rules most statements out.
604
668
  if (after.every((next) => undoesPending(next, before)))
605
669
  return;
606
- if (kindOf(call, true, ctx) !== "trigger" || hookStateRead(call, ctx))
670
+ if (kindOf(call, true, ctx) !== "trigger" || handledByHook(call, statement, ctx))
607
671
  return;
608
672
  ctx.report({
609
673
  node: statement,
@@ -615,26 +679,31 @@ function checkDropped(statement, ctx) {
615
679
  /** What a stored result is reached by: `const r = …` or `const { data, error } = …`. */
616
680
  function trackedOf(declaration, call, kind, ctx) {
617
681
  const callee = calleeText(call, ctx);
682
+ const names = { failure: ctx.options.failureNames, success: ctx.options.successNames };
618
683
  if (ts.isIdentifier(declaration.name)) {
619
- return { whole: declaration.name.text, aliases: new Map(), callee, kind };
684
+ return { whole: declaration.name.text, aliases: new Map(), callee, kind, names };
620
685
  }
621
686
  if (!ts.isObjectBindingPattern(declaration.name))
622
687
  return undefined;
623
688
  const aliases = new Map();
624
689
  let errorName;
690
+ let known = false;
625
691
  for (const element of declaration.name.elements) {
626
692
  if (element.dotDotDotToken !== undefined || !ts.isIdentifier(element.name))
627
693
  return undefined;
628
694
  const key = element.propertyName ?? element.name;
629
695
  if (!ts.isIdentifier(key))
630
696
  return undefined;
631
- const alias = ALIAS_KINDS.get(key.text);
632
- if (alias !== undefined)
633
- aliases.set(element.name.text, alias);
697
+ const named = namedPolarity(key.text, names);
698
+ const alias = ALIAS_KINDS.get(key.text) ??
699
+ (named === "failure" ? "error" : named === "success" ? "ok" : "unknown");
700
+ if (alias !== "unknown")
701
+ known = true;
702
+ aliases.set(element.name.text, alias);
634
703
  if (key.text === "error")
635
704
  errorName = element.name.text;
636
705
  }
637
- return aliases.size === 0
706
+ return !known
638
707
  ? undefined
639
708
  : {
640
709
  whole: undefined,
@@ -643,6 +712,7 @@ function trackedOf(declaration, call, kind, ctx) {
643
712
  pattern: declaration.name.getText(),
644
713
  callee,
645
714
  kind,
715
+ names,
646
716
  };
647
717
  }
648
718
  function goesOnHeadline(tracked, after) {
@@ -692,7 +762,7 @@ function returnsResult(statement, tracked) {
692
762
  * Case (b), read from syntax alone: the statements after a stored result, until it is checked,
693
763
  * passed on or read. `tracked.kind` matters only to `readsData` (a trigger's data).
694
764
  */
695
- function storedOutcome(rest, tracked) {
765
+ function storedOutcome(rest, tracked, ctx) {
696
766
  for (const [index, next] of rest.entries()) {
697
767
  if (ts.isIfStatement(next)) {
698
768
  const test = polarity(next.expression, tracked);
@@ -701,7 +771,7 @@ function storedOutcome(rest, tracked) {
701
771
  if (test !== "none") {
702
772
  const failed = test === "failure" ? next.thenStatement : next.elseStatement;
703
773
  const worked = test === "failure" ? next.elseStatement : next.thenStatement;
704
- if (failed === undefined || worked !== undefined || exits(failed))
774
+ if (failed === undefined || worked !== undefined || exits(failed, ctx))
705
775
  return { kind: "none" };
706
776
  const later = rest.slice(index + 1);
707
777
  return {
@@ -715,7 +785,7 @@ function storedOutcome(rest, tracked) {
715
785
  return { kind: "none" };
716
786
  if (readsData(next, tracked))
717
787
  return { kind: "reads-data" };
718
- if (mentions(next, tracked) || exits(next))
788
+ if (mentions(next, tracked) || exits(next, ctx))
719
789
  return { kind: "none" };
720
790
  }
721
791
  return { kind: "none" };
@@ -766,7 +836,7 @@ function goesOnHint(test, tracked, ctx) {
766
836
  }
767
837
  /** Case (b): reports what `storedOutcome` found. */
768
838
  function followStored(statement, before, rest, tracked, call, ctx) {
769
- const outcome = storedOutcome(rest, tracked);
839
+ const outcome = storedOutcome(rest, tracked, ctx);
770
840
  switch (outcome.kind) {
771
841
  case "none":
772
842
  return;
@@ -774,11 +844,16 @@ function followStored(statement, before, rest, tracked, call, ctx) {
774
844
  ctx.unknown({
775
845
  node: outcome.test,
776
846
  message: `not checked: whether the \`if\` tests that \`${tracked.callee}(…)\` failed: it does not test the result itself`,
777
- hint: `test the result itself, as in \`${checkLine(tracked, exitOf(outcome.test, ctx))}\`, so the check can be followed`,
847
+ hint: [
848
+ "one of",
849
+ `- test the result itself, as in \`${checkLine(tracked, exitOf(outcome.test, ctx))}\`, so the check can be followed`,
850
+ "- or, if a name the `if` tests says the call failed or worked (`isError`, `isFailure(result)`), list it in the rule's `failureNames` or `successNames` option",
851
+ ].join("\n"),
778
852
  });
779
853
  return;
780
854
  case "goes-on": {
781
- if (outcome.after.every((one) => undoesPending(one, before)) || hookStateRead(call, ctx)) {
855
+ if (outcome.after.every((one) => undoesPending(one, before)) ||
856
+ handledByHook(call, outcome.test, ctx)) {
782
857
  return;
783
858
  }
784
859
  ctx.report({
@@ -789,7 +864,7 @@ function followStored(statement, before, rest, tracked, call, ctx) {
789
864
  return;
790
865
  }
791
866
  case "reads-data": {
792
- if (hookStateRead(call, ctx))
867
+ if (handledByHook(call, statement, ctx))
793
868
  return;
794
869
  const data = tracked.whole === undefined
795
870
  ? ([...tracked.aliases].find(([, kind]) => kind === "data")?.[0] ?? "data")
@@ -810,7 +885,7 @@ function followStored(statement, before, rest, tracked, call, ctx) {
810
885
  }
811
886
  // Only `data` was taken out: there is nothing to test, so the whole result is kept first.
812
887
  const name = freeName(ts.findAncestor(statement.parent, ts.isFunctionLike) ?? ctx.sourceFile, ctx.sourceFile, ["result", "outcome", "response"]);
813
- const pattern = tracked.pattern === undefined ? "{ data }" : oneLine(tracked.pattern);
888
+ const pattern = tracked.pattern === undefined ? "{ data }" : codeOnOneLine(tracked.pattern);
814
889
  ctx.report({
815
890
  node: statement,
816
891
  message: goesOnHeadline(tracked, "statement"),
@@ -852,7 +927,7 @@ function checkDeclaration(statement, ctx) {
852
927
  // before any test, and then nothing is said whatever they give. The kind matters only to a
853
928
  // trigger's data, which only an awaited call can be; a trigger read finds the most.
854
929
  const probe = trackedOf(declaration, call, awaited ? "trigger" : "ok", ctx);
855
- if (probe === undefined || storedOutcome(rest, probe).kind === "none")
930
+ if (probe === undefined || storedOutcome(rest, probe, ctx).kind === "none")
856
931
  return;
857
932
  const kind = kindOf(call, awaited, ctx);
858
933
  if (kind === undefined)
@@ -868,9 +943,12 @@ export const resultUnchecked = defineRule({
868
943
  description: "A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked.",
869
944
  summary: "a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked",
870
945
  defaultSeverity: "warning",
871
- tier: "core",
946
+ tier: "addon",
947
+ addon: "result-unchecked",
948
+ offByDefault: OFF_BY_DEFAULT,
872
949
  group: "callers",
873
950
  heuristic: true,
951
+ options: OPTIONS,
874
952
  explain: EXPLAIN,
875
953
  },
876
954
  check(ctx) {
@@ -5,7 +5,13 @@ export declare const RULES: {
5
5
  readonly description: "A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.";
6
6
  readonly summary: "a `catch` that handles some error classes with `instanceof` and ignores the rest";
7
7
  readonly defaultSeverity: "error";
8
- readonly tier: "core";
8
+ readonly tier: "addon";
9
+ readonly addon: "catch-hides-unexpected";
10
+ readonly offByDefault: {
11
+ readonly since: "1.3";
12
+ readonly right: 4;
13
+ readonly checked: 7;
14
+ };
9
15
  readonly group: "catch";
10
16
  readonly options: {
11
17
  readonly restUsesError: {
@@ -137,18 +143,6 @@ export declare const RULES: {
137
143
  readonly listUnknowns: true;
138
144
  };
139
145
  };
140
- readonly "narrow-try": {
141
- readonly kind: "project";
142
- readonly meta: {
143
- readonly description: "A bug in code inside a `try` meant for another call is caught and reported as that call's failure; moving the code after the `try` keeps the two apart.";
144
- readonly summary: "calls to your own code inside a `try` after the call it is for, so their bugs look like its failure";
145
- readonly defaultSeverity: "warning";
146
- readonly tier: "addon";
147
- readonly addon: "narrow-try";
148
- readonly group: "catch";
149
- readonly needsJsDoc: true;
150
- };
151
- };
152
146
  readonly "result-ignored": {
153
147
  readonly kind: "file";
154
148
  readonly meta: {
@@ -183,9 +177,27 @@ export declare const RULES: {
183
177
  readonly description: "A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked.";
184
178
  readonly summary: "a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked";
185
179
  readonly defaultSeverity: "warning";
186
- readonly tier: "core";
180
+ readonly tier: "addon";
181
+ readonly addon: "result-unchecked";
182
+ readonly offByDefault: {
183
+ readonly since: "1.3";
184
+ readonly right: 0;
185
+ readonly checked: 5;
186
+ };
187
187
  readonly group: "callers";
188
188
  readonly heuristic: true;
189
+ readonly options: {
190
+ readonly failureNames: {
191
+ readonly kind: "strings";
192
+ readonly default: readonly [];
193
+ readonly description: "Names (or globs like isErr*) that are true when the call failed, besides the result's own `error`: a property of the result (`isError`), or a function called with it (`isFailure(result)`). Its type does not say what such a name means.";
194
+ };
195
+ readonly successNames: {
196
+ readonly kind: "strings";
197
+ readonly default: readonly [];
198
+ readonly description: "Names (or globs) that are true when the call worked, besides the result's own `data`, `ok` and `success`: a property of the result (`isSuccess`, `value`), or a function called with it (`isOk(result)`).";
199
+ };
200
+ };
189
201
  };
190
202
  };
191
203
  };
@@ -5,7 +5,9 @@ export const RULES = {
5
5
  description: "A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.",
6
6
  summary: "a `catch` that handles some error classes with `instanceof` and ignores the rest",
7
7
  defaultSeverity: "error",
8
- tier: "core",
8
+ tier: "addon",
9
+ addon: "catch-hides-unexpected",
10
+ offByDefault: { since: "1.3", right: 4, checked: 7 },
9
11
  group: "catch",
10
12
  options: {
11
13
  restUsesError: {
@@ -130,18 +132,6 @@ export const RULES = {
130
132
  listUnknowns: true,
131
133
  },
132
134
  },
133
- "narrow-try": {
134
- kind: "project",
135
- meta: {
136
- description: "A bug in code inside a `try` meant for another call is caught and reported as that call's failure; moving the code after the `try` keeps the two apart.",
137
- summary: "calls to your own code inside a `try` after the call it is for, so their bugs look like its failure",
138
- defaultSeverity: "warning",
139
- tier: "addon",
140
- addon: "narrow-try",
141
- group: "catch",
142
- needsJsDoc: true,
143
- },
144
- },
145
135
  "result-ignored": {
146
136
  kind: "file",
147
137
  meta: {
@@ -176,9 +166,23 @@ export const RULES = {
176
166
  description: "A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked.",
177
167
  summary: "a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked",
178
168
  defaultSeverity: "warning",
179
- tier: "core",
169
+ tier: "addon",
170
+ addon: "result-unchecked",
171
+ offByDefault: { since: "1.3", right: 0, checked: 5 },
180
172
  group: "callers",
181
173
  heuristic: true,
174
+ options: {
175
+ failureNames: {
176
+ kind: "strings",
177
+ default: [],
178
+ description: "Names (or globs like isErr*) that are true when the call failed, besides the result's own `error`: a property of the result (`isError`), or a function called with it (`isFailure(result)`). Its type does not say what such a name means.",
179
+ },
180
+ successNames: {
181
+ kind: "strings",
182
+ default: [],
183
+ description: "Names (or globs) that are true when the call worked, besides the result's own `data`, `ok` and `success`: a property of the result (`isSuccess`, `value`), or a function called with it (`isOk(result)`).",
184
+ },
185
+ },
182
186
  },
183
187
  },
184
188
  };
package/dist/syntax.d.ts CHANGED
@@ -25,17 +25,4 @@ export declare function sameFileFunction(callee: ts.Expression, ctx: FileContext
25
25
  export declare function isBuiltinGlobal(name: ts.Identifier, ctx: FileContext): boolean;
26
26
  /** Whether the function has a `throw` that no `try` / `catch` of its own catches. */
27
27
  export declare function throwsUncaught(fn: DeclaredFunction): boolean;
28
- /**
29
- * Whether a `catch` tests what it caught before handling it: `e instanceof X`, `e.name === …`,
30
- * `"status" in e`, or a type guard `isApiError(e)`, in an `if`, a `switch` or a `?:`. Such a catch
31
- * says which errors it expects; `errors/catch-hides-unexpected` checks what it does with the rest.
32
- */
33
- export declare function testsCaught(clause: ts.CatchClause): boolean;
34
- /**
35
- * Whether `call`, in `clause`, hands the caught error to a callback the function around it was
36
- * given (`reject(e)`, `next(e)`, `onError(e)`): the caller gets it, as with a rethrow.
37
- */
38
- export declare function handsOnCaught(call: ts.CallExpression, clause: ts.CatchClause): boolean;
39
- /** Whether `test` holds for `root` or a node under it, without entering nested functions or classes. */
40
- export declare function someRunning(root: ts.Node, test: (node: ts.Node) => boolean): boolean;
41
28
  //# sourceMappingURL=syntax.d.ts.map