@murky-web/typebuddy 2.0.0 → 3.0.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 (45) hide show
  1. package/README.md +184 -72
  2. package/dist/collections.js +1 -2
  3. package/dist/empty.js +34 -13
  4. package/dist/guards.js +33 -9
  5. package/dist/ids.js +6 -6
  6. package/dist/oxlint.js +7 -7
  7. package/dist/parse.js +39 -15
  8. package/dist/result.js +9 -8
  9. package/dist/rules/async_rule.js +45 -28
  10. package/dist/rules/deliberate_throw.js +5 -6
  11. package/dist/rules/maybe_promise_rule.js +109 -47
  12. package/dist/rules/maybe_rule.js +7 -5
  13. package/dist/rules/nullable_rule.js +7 -5
  14. package/dist/rules/optional_rule.js +8 -4
  15. package/dist/rules/own_subtree.js +1 -2
  16. package/dist/rules/test_file.js +63 -0
  17. package/dist/rules/typebuddy_import.js +242 -35
  18. package/dist/rules/use_server.js +63 -0
  19. package/globals.d.ts +49 -44
  20. package/jsr.json +3 -2
  21. package/oxlint/index.ts +7 -5
  22. package/package.json +92 -91
  23. package/rules/async_rule.ts +87 -67
  24. package/rules/deliberate_throw.ts +11 -11
  25. package/rules/maybe_promise_rule.ts +229 -98
  26. package/rules/maybe_rule.ts +74 -47
  27. package/rules/nullable_rule.ts +78 -50
  28. package/rules/optional_rule.ts +80 -51
  29. package/rules/own_subtree.ts +33 -33
  30. package/rules/test_file.ts +114 -0
  31. package/rules/typebuddy_import.ts +479 -87
  32. package/rules/use_server.ts +117 -0
  33. package/src/empty.ts +57 -19
  34. package/src/guards.ts +96 -30
  35. package/src/ids.ts +10 -4
  36. package/src/index.ts +1 -18
  37. package/src/parse.ts +104 -25
  38. package/src/public_api.ts +22 -0
  39. package/src/result.ts +11 -9
  40. package/src/types/globals.ts +11 -11
  41. package/src/types/index.ts +21 -21
  42. package/src/types/json.ts +48 -11
  43. package/src/types/maybe_promise.ts +17 -12
  44. package/src/types/nullable.ts +2 -2
  45. package/src/types/optional.ts +6 -6
package/dist/result.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/result.ts
1
+ // src/result.ts
2
2
  /**
3
3
  * Checks if the provided result is a `Success` type.
4
4
  *
@@ -6,16 +6,18 @@
6
6
  * ```typescript
7
7
  * const result = await someAsyncFunction();
8
8
  * if (isSuccess(result)) {
9
- * return result.value; // TypeScript knows `value` is of type `T`
9
+ * return result.value; // TypeScript knows `value` is of type `T`
10
10
  * }
11
11
  * ```
12
12
  *
13
- * @template T The type of the value contained in the `Success` type.
14
- * @param {Readonly<Result<T>>} result The result to check, which can
15
- * be either a `Success<T>` or `Failed`.
13
+ * @template R The result type passed in. The guard narrows it by its `isError`
14
+ * flag, so `value` keeps the success type without an extra `| null`. A
15
+ * `Result<T | null>`, a generic `Result<T>` and a `Result<any>` all work.
16
+ * @param {R} result The result to check, which can be either a `Success<T>` or
17
+ * `Failed`.
16
18
  * @returns {boolean} `true` if the result is a `Success<T>`, `false` if it is a
17
- * `Failed`. This function acts as a type guard, narrowing the type of
18
- * `result` to `Success<T>` when the condition is met.
19
+ * `Failed`. This function acts as a type guard, narrowing `result` to its
20
+ * `Success` member when the condition is met.
19
21
  */
20
22
  function isSuccess(result) {
21
23
  return !result.isError;
@@ -34,5 +36,4 @@ function err(...args) {
34
36
  value: value ?? null
35
37
  };
36
38
  }
37
- //#endregion
38
39
  export { err, isSuccess, ok };
@@ -1,6 +1,7 @@
1
1
  import { throwsDeliberately } from "./deliberate_throw.js";
2
- import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
3
- //#region rules/async_rule.ts
2
+ import { createImportPlanner, getBodyStartAfterDirectives } from "./typebuddy_import.js";
3
+ import { createUseServerGuard } from "./use_server.js";
4
+ // rules/async_rule.ts
4
5
  function hasTryCatch(nodes) {
5
6
  return nodes.some((node) => {
6
7
  return node.type === "TryStatement";
@@ -15,18 +16,12 @@ function isCallArgumentCallback(node) {
15
16
  const rule = {
16
17
  create(context) {
17
18
  const sourceCode = context.getSourceCode();
18
- let scheduledErrImport = false;
19
- function ensureErrImportFixes(node, fixer) {
20
- if (scheduledErrImport) return [];
21
- const insertion = getTypeBuddyImportInsertion(node, "err");
22
- if (!insertion) return [];
23
- scheduledErrImport = true;
24
- return [fixer.insertTextBeforeRange(insertion.range, insertion.text)];
25
- }
19
+ const imports = createImportPlanner(sourceCode);
26
20
  function wrapBlockFixes(bodyNode, fixer) {
27
21
  const range = bodyNode.range;
28
- if (!Array.isArray(range) || range.length < 2) return null;
29
- return [fixer.insertTextBeforeRange([range[0] + 1, range[0] + 1], "\ntry {"), fixer.insertTextBeforeRange([range[1] - 1, range[1] - 1], "} catch {\nreturn err();\n}\n")];
22
+ const tryStart = getBodyStartAfterDirectives(bodyNode);
23
+ if (!Array.isArray(range) || range.length < 2 || tryStart === null) return null;
24
+ return [fixer.insertTextBeforeRange([tryStart, tryStart], "\ntry {"), fixer.insertTextBeforeRange([range[1] - 1, range[1] - 1], "} catch {\nreturn err();\n}\n")];
30
25
  }
31
26
  /**
32
27
  * Wrap an expression-bodied arrow's value in a block with try/catch.
@@ -48,8 +43,30 @@ const rule = {
48
43
  if (start >= end) return null;
49
44
  return [fixer.insertTextBeforeRange([start, start], "{\ntry {\nreturn "), fixer.insertTextBeforeRange([end, end], ";\n} catch {\nreturn err();\n}\n}")];
50
45
  }
46
+ /**
47
+ * The wrap is a suggestion, never a fix. It turns every exception of
48
+ * the function into `err()`, so a failure nobody handled becomes a
49
+ * value somebody has to remember to check, and `catch { return err();
50
+ * }` hides what went wrong. Whether that is wanted is the author's
51
+ * call. `err` has to be free at that spot: a parameter or local called
52
+ * `err` would make `err()` call something else, and then there is no
53
+ * suggestion.
54
+ */
55
+ function suggestWrap(scopeNode, wrap) {
56
+ return [{
57
+ messageId: "suggestTryCatch",
58
+ fix(fixer) {
59
+ const wrapFixes = wrap(fixer);
60
+ if (!wrapFixes) return null;
61
+ const importFixes = imports.fixes(scopeNode, fixer, "err", "value");
62
+ if (importFixes === null) return null;
63
+ return [...importFixes, ...wrapFixes];
64
+ }
65
+ }];
66
+ }
51
67
  function checkFunction(node) {
52
68
  if (node.async !== true) return;
69
+ if (node["generator"] === true) return;
53
70
  if (isCallArgumentCallback(node)) return;
54
71
  const bodyNode = node.body;
55
72
  if (!bodyNode || Array.isArray(bodyNode)) return;
@@ -58,11 +75,9 @@ const rule = {
58
75
  context.report({
59
76
  node,
60
77
  messageId: "missingTryCatch",
61
- fix(fixer) {
62
- const wrapFixes = wrapExpressionBodyFixes(node, bodyNode, fixer);
63
- if (!wrapFixes) return null;
64
- return [...ensureErrImportFixes(node, fixer), ...wrapFixes];
65
- }
78
+ suggest: suggestWrap(node, (fixer) => {
79
+ return wrapExpressionBodyFixes(node, bodyNode, fixer);
80
+ })
66
81
  });
67
82
  return;
68
83
  }
@@ -70,27 +85,29 @@ const rule = {
70
85
  context.report({
71
86
  node,
72
87
  messageId: "missingTryCatch",
73
- fix(fixer) {
74
- const wrapFixes = wrapBlockFixes(bodyNode, fixer);
75
- if (!wrapFixes) return null;
76
- return [...ensureErrImportFixes(node, fixer), ...wrapFixes];
77
- }
88
+ suggest: suggestWrap(bodyNode, (fixer) => {
89
+ return wrapBlockFixes(bodyNode, fixer);
90
+ })
78
91
  });
79
92
  }
93
+ const { Program, guard } = createUseServerGuard();
80
94
  return {
81
- FunctionDeclaration: checkFunction,
82
- FunctionExpression: checkFunction,
83
- ArrowFunctionExpression: checkFunction
95
+ Program,
96
+ FunctionDeclaration: guard(checkFunction),
97
+ FunctionExpression: guard(checkFunction),
98
+ ArrowFunctionExpression: guard(checkFunction)
84
99
  };
85
100
  },
86
101
  defaultOptions: [],
87
102
  meta: {
88
103
  type: "suggestion",
104
+ hasSuggestions: true,
89
105
  docs: { description: "Async functions should have a try-catch block returning an error result." },
90
- fixable: "code",
91
106
  schema: [],
92
- messages: { missingTryCatch: "Async functions must have a try-catch block returning an error result." }
107
+ messages: {
108
+ missingTryCatch: "Async functions must have a try-catch block returning an error result.",
109
+ suggestTryCatch: "Wrap the body in try/catch and return err() from the catch."
110
+ }
93
111
  }
94
112
  };
95
- //#endregion
96
113
  export { rule as requireTryCatchAsyncRule };
@@ -1,16 +1,16 @@
1
1
  import { walkOwnSubtree } from "./own_subtree.js";
2
- //#region rules/deliberate_throw.ts
2
+ // rules/deliberate_throw.ts
3
3
  /**
4
4
  * Whether a function body throws on purpose.
5
5
  *
6
6
  * A `throw` in a function's own body is the author saying this failure is not a
7
7
  * value to hand back. A missing manifest for a route the app is navigating to,
8
- * an unreachable branch, a broken invariant — those should be loud. Turning them
9
- * into `err()` converts a bug into a silently handled outcome, and the caller
10
- * degrades politely instead of surfacing that something is wrong.
8
+ * an unreachable branch, a broken invariant — those should be loud. Turning
9
+ * them into `err()` converts a bug into a silently handled outcome, and the
10
+ * caller degrades politely instead of surfacing that something is wrong.
11
11
  *
12
12
  * So both async rules leave such a function alone. The rules exist to push
13
- * *recoverable* failures into the return type, not to abolish throwing.
13
+ * _recoverable_ failures into the return type, not to abolish throwing.
14
14
  *
15
15
  * Two boundaries matter. A throw inside a nested function belongs to that
16
16
  * function, so the walk does not descend into one. A throw inside `catch` still
@@ -27,5 +27,4 @@ function throwsDeliberately(body) {
27
27
  });
28
28
  return found;
29
29
  }
30
- //#endregion
31
30
  export { throwsDeliberately };
@@ -1,7 +1,8 @@
1
- import { walkOwnSubtree } from "./own_subtree.js";
2
1
  import { throwsDeliberately } from "./deliberate_throw.js";
3
- import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
4
- //#region rules/maybe_promise_rule.ts
2
+ import { walkOwnSubtree } from "./own_subtree.js";
3
+ import { canAddImport, createImportPlanner } from "./typebuddy_import.js";
4
+ import { createUseServerGuard } from "./use_server.js";
5
+ // rules/maybe_promise_rule.ts
5
6
  function isNode(value) {
6
7
  return typeof value === "object" && value !== null && "type" in value;
7
8
  }
@@ -53,6 +54,14 @@ function getObjectPropertyValue(node, propertyName) {
53
54
  for (const property of node["properties"]) if (isNode(property) && property.type === "Property" && isIdentifierNamed(property["key"], propertyName) && isNode(property["value"])) return property["value"];
54
55
  return null;
55
56
  }
57
+ const RESULT_PROPERTY_COUNT = 2;
58
+ /** An object literal with exactly `isError` and `value`: no spread, no extras. */
59
+ function hasOnlyResultProperties(node) {
60
+ if (!isNode(node) || node.type !== "ObjectExpression" || !Array.isArray(node["properties"]) || node["properties"].length !== RESULT_PROPERTY_COUNT) return false;
61
+ return node["properties"].every((property) => {
62
+ return isNode(property) && property.type === "Property" && property["computed"] !== true && (isIdentifierNamed(property["key"], "isError") || isIdentifierNamed(property["key"], "value"));
63
+ });
64
+ }
56
65
  function isBooleanLiteral(node, expected) {
57
66
  return isNode(node) && node.type === "Literal" && node["value"] === expected;
58
67
  }
@@ -62,7 +71,7 @@ function isNullLiteral(node) {
62
71
  const rule = {
63
72
  create(context) {
64
73
  const sourceCode = context.getSourceCode();
65
- const scheduledHelperImports = /* @__PURE__ */ new Set();
74
+ const imports = createImportPlanner(sourceCode);
66
75
  function isTypeReference(node) {
67
76
  return isNode(node) && node.type === "TSTypeReference";
68
77
  }
@@ -81,9 +90,9 @@ const rule = {
81
90
  /**
82
91
  * The awaited type behind an async function's return annotation.
83
92
  *
84
- * Every spelling counts. Matching only `Promise` meant the rule read the
85
- * return type of code it had not migrated yet and went blind the moment
86
- * `MaybePromise` was there — so a bare `return;` in a
93
+ * Every spelling counts. Matching only `Promise` meant the rule read
94
+ * the return type of code it had not migrated yet and went blind the
95
+ * moment `MaybePromise` was there — so a bare `return;` in a
87
96
  * `MaybePromise<void>` function never became `return ok();`, while the
88
97
  * identical `Promise<void>` function was fixed. It only ever worked
89
98
  * because the rename and this lookup happen in the same pass, off the
@@ -94,32 +103,76 @@ const rule = {
94
103
  if (typeName === null || !AWAITED_TYPE_NAMES.has(typeName)) return null;
95
104
  return getTypeArgument(node);
96
105
  }
97
- function ensureResultHelperImportFixes(node, fixer, helperName) {
98
- if (scheduledHelperImports.has(helperName)) return [];
99
- const insertion = getTypeBuddyImportInsertion(node, helperName);
100
- if (!insertion) return [];
101
- scheduledHelperImports.add(helperName);
102
- return [fixer.insertTextBeforeRange(insertion.range, insertion.text)];
106
+ /**
107
+ * The fixes that rewrite `at` and make `helperName` available there, or
108
+ * `null` when the name is something else at that spot (a catch
109
+ * parameter called `err`, a local called `ok`): the rule then reports
110
+ * without offering a fix, because a fix would call the wrong thing.
111
+ */
112
+ function withHelperFixes(at, fixer, helperName, rewrite) {
113
+ const importFixes = imports.fixes(at, fixer, helperName, "value");
114
+ if (importFixes === null) return null;
115
+ return [...importFixes, rewrite];
116
+ }
117
+ /**
118
+ * Same as `withHelperFixes`, as a suggestion. A suggestion is applied
119
+ * alone, so it carries its own import too.
120
+ */
121
+ function suggestWithHelper(at, messageId, helperName, rewrite) {
122
+ return [{
123
+ messageId,
124
+ fix(fixer) {
125
+ return withHelperFixes(at, fixer, helperName, rewrite(fixer));
126
+ }
127
+ }];
103
128
  }
104
- function reportPromiseReturnType(node) {
129
+ /**
130
+ * `Promise<T>` to `MaybePromise<T>`.
131
+ *
132
+ * Only on a function this file defines (`own`) is it a fix: the author
133
+ * is moving that function's contract to `MaybePromise`. A function
134
+ * type, an interface method or an overload describes a shape that other
135
+ * code, often a library's, has to match, so there it is a suggestion
136
+ * the author decides on.
137
+ */
138
+ function reportPromiseReturnType(node, own) {
105
139
  if (!isNode(node["returnType"])) return;
106
140
  const typeAnnotation = node["returnType"]["typeAnnotation"];
107
141
  if (!isTypeReference(typeAnnotation)) return;
108
142
  if (getTypeName(typeAnnotation) !== "Promise") return;
109
143
  const typeName = typeAnnotation["typeName"];
144
+ const rewrite = (fixer) => {
145
+ const typeImport = imports.fixes(typeName, fixer, "MaybePromise", "type");
146
+ if (typeImport === null) return null;
147
+ return [...typeImport, fixer.replaceText(typeName, "MaybePromise")];
148
+ };
149
+ if (own && canAddImport(node)) {
150
+ context.report({
151
+ node: typeName,
152
+ messageId: "replaceWithMaybePromise",
153
+ fix(fixer) {
154
+ return rewrite(fixer);
155
+ }
156
+ });
157
+ return;
158
+ }
110
159
  context.report({
111
160
  node: typeName,
112
161
  messageId: "replaceWithMaybePromise",
113
- fix(fixer) {
114
- return fixer.replaceText(typeName, "MaybePromise");
115
- }
162
+ suggest: [{
163
+ messageId: "suggestMaybePromise",
164
+ fix(fixer) {
165
+ return rewrite(fixer);
166
+ }
167
+ }]
116
168
  });
117
169
  }
118
170
  function checkReturnType(node) {
119
171
  if (!isAsyncFunction(node)) return;
172
+ if (node["generator"] === true) return;
120
173
  if (isCallArgumentCallback(node)) return;
121
174
  if (throwsDeliberately(node["body"])) return;
122
- reportPromiseReturnType(node);
175
+ reportPromiseReturnType(node, true);
123
176
  }
124
177
  /**
125
178
  * A type-level signature — an interface method, a function type, an
@@ -131,10 +184,14 @@ const rule = {
131
184
  * Ambient declarations are the exception: `declare` describes code the
132
185
  * project does not own, and rewriting a third-party framework's
133
186
  * callback shape to `MaybePromise` would be a lie about that API.
187
+ *
188
+ * Every other signature is a suggestion, never a fix: a function type
189
+ * or an interface method is often the shape a library hands in or
190
+ * expects back, and only the author knows which.
134
191
  */
135
192
  function checkSignatureReturnType(node) {
136
193
  if (isAmbient(node)) return;
137
- reportPromiseReturnType(node);
194
+ reportPromiseReturnType(node, false);
138
195
  }
139
196
  function wrapReturnValue(node, isAsync, returnType) {
140
197
  if (!isAsync) return;
@@ -144,7 +201,7 @@ const rule = {
144
201
  node,
145
202
  messageId: "returnVoidPromise",
146
203
  fix(fixer) {
147
- return [...ensureResultHelperImportFixes(node, fixer, "ok"), fixer.replaceText(node, "return ok()")];
204
+ return withHelperFixes(node, fixer, "ok", fixer.replaceText(node, "return ok();"));
148
205
  }
149
206
  });
150
207
  return;
@@ -153,23 +210,23 @@ const rule = {
153
210
  if (isResultHelperCall(argument, "ok") || isResultHelperCall(argument, "err")) return;
154
211
  const isErrorValue = getObjectPropertyValue(argument, "isError");
155
212
  const objectValue = getObjectPropertyValue(argument, "value");
156
- if (isBooleanLiteral(isErrorValue, false) && objectValue) {
213
+ if (isBooleanLiteral(isErrorValue, false) && objectValue && hasOnlyResultProperties(argument)) {
157
214
  context.report({
158
215
  node: argument,
159
216
  messageId: "preferOkResult",
160
217
  fix(fixer) {
161
218
  const valueText = sourceCode.getText(objectValue);
162
- return [...ensureResultHelperImportFixes(node, fixer, "ok"), fixer.replaceText(argument, `ok(${valueText})`)];
219
+ return withHelperFixes(node, fixer, "ok", fixer.replaceText(argument, `ok(${valueText})`));
163
220
  }
164
221
  });
165
222
  return;
166
223
  }
167
- if (isBooleanLiteral(isErrorValue, true) && isNullLiteral(objectValue)) {
224
+ if (isBooleanLiteral(isErrorValue, true) && isNullLiteral(objectValue) && hasOnlyResultProperties(argument)) {
168
225
  context.report({
169
226
  node: argument,
170
227
  messageId: "preferErrResult",
171
228
  fix(fixer) {
172
- return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.replaceText(argument, "err()")];
229
+ return withHelperFixes(node, fixer, "err", fixer.replaceText(argument, "err()"));
173
230
  }
174
231
  });
175
232
  return;
@@ -177,10 +234,10 @@ const rule = {
177
234
  if (!hasIsErrorFlag(argument, true) && !hasIsErrorFlag(argument, false)) context.report({
178
235
  node: argument,
179
236
  messageId: "wrapReturn",
180
- fix(fixer) {
237
+ suggest: suggestWithHelper(node, "suggestWrapReturn", "ok", (fixer) => {
181
238
  const argumentText = sourceCode.getText(argument);
182
- return [...ensureResultHelperImportFixes(node, fixer, "ok"), fixer.replaceText(argument, `ok(${argumentText})`)];
183
- }
239
+ return fixer.replaceText(argument, `ok(${argumentText})`);
240
+ })
184
241
  });
185
242
  }
186
243
  function collectOwnReturns(root) {
@@ -198,14 +255,14 @@ const rule = {
198
255
  /**
199
256
  * Push a single `return` inside a catch block towards `err()`.
200
257
  *
201
- * Only the lossless rewrites carry a fix. Replacing
202
- * `return ok("defaults")` with `return err()` would silently drop the
203
- * author's fallback, and the old behaviour — appending `return err()`
204
- * after it — produced unreachable code and a report that could never be
205
- * satisfied. Where the fallback matters, moving it into the try block is
206
- * a decision the author has to make, so the rule reports and stops.
258
+ * Only the lossless rewrites carry a fix. Replacing `return
259
+ * ok("defaults")` with `return err()` would silently drop the author's
260
+ * fallback, and the old behaviour — appending `return err()` after it —
261
+ * produced unreachable code and a report that could never be satisfied.
262
+ * Where the fallback matters, moving it into the try block is a
263
+ * decision the author has to make, so the rule reports and stops.
207
264
  */
208
- function reportCatchReturn(tryNode, statement) {
265
+ function reportCatchReturn(statement) {
209
266
  const argument = statement["argument"];
210
267
  if (isSettledFailure(argument)) return;
211
268
  if (!isNode(argument)) {
@@ -213,17 +270,17 @@ const rule = {
213
270
  node: statement,
214
271
  messageId: "returnFailedPromise",
215
272
  fix(fixer) {
216
- return [...ensureResultHelperImportFixes(tryNode, fixer, "err"), fixer.replaceText(statement, "return err()")];
273
+ return withHelperFixes(statement, fixer, "err", fixer.replaceText(statement, "return err();"));
217
274
  }
218
275
  });
219
276
  return;
220
277
  }
221
278
  if (hasIsErrorFlag(argument, true)) {
222
- if (isNullLiteral(getObjectPropertyValue(argument, "value"))) context.report({
279
+ if (isNullLiteral(getObjectPropertyValue(argument, "value")) && hasOnlyResultProperties(argument)) context.report({
223
280
  node: argument,
224
281
  messageId: "preferErrResult",
225
282
  fix(fixer) {
226
- return [...ensureResultHelperImportFixes(tryNode, fixer, "err"), fixer.replaceText(argument, "err()")];
283
+ return withHelperFixes(statement, fixer, "err", fixer.replaceText(argument, "err()"));
227
284
  }
228
285
  });
229
286
  return;
@@ -246,6 +303,7 @@ const rule = {
246
303
  parent = parent.parent;
247
304
  }
248
305
  if (!isAsync || !parentFunction) return;
306
+ if (parentFunction["generator"] === true) return;
249
307
  if (isCallArgumentCallback(parentFunction)) return;
250
308
  if (throwsDeliberately(parentFunction["body"])) return;
251
309
  let returnType = null;
@@ -257,7 +315,7 @@ const rule = {
257
315
  const handler = node["handler"];
258
316
  if (!isNode(handler) || !isNode(handler["body"])) return;
259
317
  const catchReturns = collectOwnReturns(handler["body"]);
260
- for (const statement of catchReturns) reportCatchReturn(node, statement);
318
+ for (const statement of catchReturns) reportCatchReturn(statement);
261
319
  let settlesItself = false;
262
320
  walkOwnSubtree(handler["body"], (candidate) => {
263
321
  if (candidate.type === "ReturnStatement") settlesItself = true;
@@ -269,18 +327,20 @@ const rule = {
269
327
  fix(fixer) {
270
328
  const handlerBody = handler["body"];
271
329
  if (!isNode(handlerBody) || !Array.isArray(handlerBody["range"])) return null;
272
- return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.insertTextBeforeRange([handlerBody["range"][1] - 1, handlerBody["range"][1] - 1], "\nreturn err();\n")];
330
+ return withHelperFixes(handlerBody, fixer, "err", fixer.insertTextBeforeRange([handlerBody["range"][1] - 1, handlerBody["range"][1] - 1], "\nreturn err();\n"));
273
331
  }
274
332
  });
275
333
  }
334
+ const { Program, guard } = createUseServerGuard();
276
335
  return {
277
- FunctionDeclaration: checkReturnType,
278
- FunctionExpression: checkReturnType,
279
- ArrowFunctionExpression: checkReturnType,
280
- TSDeclareFunction: checkSignatureReturnType,
281
- TSFunctionType: checkSignatureReturnType,
282
- TSMethodSignature: checkSignatureReturnType,
283
- TryStatement: processTryCatch
336
+ Program,
337
+ FunctionDeclaration: guard(checkReturnType),
338
+ FunctionExpression: guard(checkReturnType),
339
+ ArrowFunctionExpression: guard(checkReturnType),
340
+ TSDeclareFunction: guard(checkSignatureReturnType),
341
+ TSFunctionType: guard(checkSignatureReturnType),
342
+ TSMethodSignature: guard(checkSignatureReturnType),
343
+ TryStatement: guard(processTryCatch)
284
344
  };
285
345
  },
286
346
  defaultOptions: [],
@@ -288,10 +348,13 @@ const rule = {
288
348
  type: "suggestion",
289
349
  docs: { description: "Ensure async functions' return values follow the MaybePromise pattern." },
290
350
  fixable: "code",
351
+ hasSuggestions: true,
291
352
  schema: [],
292
353
  messages: {
293
354
  replaceWithMaybePromise: "Use 'MaybePromise' instead of 'Promise' as the return type in async functions.",
355
+ suggestMaybePromise: "Replace 'Promise' with 'MaybePromise'.",
294
356
  wrapReturn: "Wrap return value with ok(value).",
357
+ suggestWrapReturn: "Wrap the return value in ok(...).",
295
358
  preferOkResult: "Use ok(value) instead of an inline success result object.",
296
359
  preferErrResult: "Use err() instead of an inline error result object.",
297
360
  returnVoidPromise: "Return ok() for async functions with Promise<void> return type.",
@@ -299,5 +362,4 @@ const rule = {
299
362
  }
300
363
  }
301
364
  };
302
- //#endregion
303
365
  export { rule as errorSafeAsyncRule };
@@ -1,9 +1,11 @@
1
- //#region rules/maybe_rule.ts
1
+ import { createImportPlanner } from "./typebuddy_import.js";
2
+ // rules/maybe_rule.ts
2
3
  const rule = {
3
4
  create(context) {
5
+ const sourceCode = context.getSourceCode();
6
+ const imports = createImportPlanner(sourceCode);
4
7
  return { TSUnionType(node) {
5
8
  const types = node.types;
6
- const sourceCode = context.getSourceCode();
7
9
  const nullType = types.find((typeNode) => typeNode.type === "TSNullKeyword");
8
10
  const undefinedType = types.find((typeNode) => typeNode.type === "TSUndefinedKeyword");
9
11
  const otherTypes = types.filter((typeNode) => typeNode.type !== "TSNullKeyword" && typeNode.type !== "TSUndefinedKeyword");
@@ -14,7 +16,9 @@ const rule = {
14
16
  messageId: "useMaybe",
15
17
  data: { type: typeText },
16
18
  fix(fixer) {
17
- return fixer.replaceText(node, `Maybe<${typeText}>`);
19
+ const importFixes = imports.fixes(node, fixer, "Maybe", "type");
20
+ if (importFixes === null) return null;
21
+ return [...importFixes, fixer.replaceText(node, `Maybe<${typeText}>`)];
18
22
  }
19
23
  });
20
24
  }
@@ -23,12 +27,10 @@ const rule = {
23
27
  defaultOptions: [],
24
28
  meta: {
25
29
  type: "suggestion",
26
- hasSuggestions: true,
27
30
  docs: { description: "Use Maybe<T> for T | null" },
28
31
  fixable: "code",
29
32
  schema: [],
30
33
  messages: { useMaybe: "Use Maybe<{{type}}> instead of {{type}} | null" }
31
34
  }
32
35
  };
33
- //#endregion
34
36
  export { rule as maybeRule };
@@ -1,10 +1,12 @@
1
- //#region rules/nullable_rule.ts
1
+ import { createImportPlanner } from "./typebuddy_import.js";
2
+ // rules/nullable_rule.ts
2
3
  const rule = {
3
4
  create(context) {
5
+ const sourceCode = context.getSourceCode();
6
+ const imports = createImportPlanner(sourceCode);
4
7
  return { TSUnionType(node) {
5
8
  const types = node.types;
6
9
  if (types.length !== 3) return;
7
- const sourceCode = context.getSourceCode();
8
10
  const nullType = types.find((typeNode) => typeNode.type === "TSNullKeyword");
9
11
  const undefinedType = types.find((typeNode) => typeNode.type === "TSUndefinedKeyword");
10
12
  const otherType = types.find((typeNode) => typeNode.type !== "TSNullKeyword" && typeNode.type !== "TSUndefinedKeyword");
@@ -15,7 +17,9 @@ const rule = {
15
17
  messageId: "useNullable",
16
18
  data: { type: typeText },
17
19
  fix(fixer) {
18
- return fixer.replaceText(node, `Nullable<${typeText}>`);
20
+ const importFixes = imports.fixes(node, fixer, "Nullable", "type");
21
+ if (importFixes === null) return null;
22
+ return [...importFixes, fixer.replaceText(node, `Nullable<${typeText}>`)];
19
23
  }
20
24
  });
21
25
  }
@@ -24,12 +28,10 @@ const rule = {
24
28
  defaultOptions: [],
25
29
  meta: {
26
30
  type: "suggestion",
27
- hasSuggestions: true,
28
31
  docs: { description: "Use Nullable<T> instead of T | null | undefined" },
29
32
  fixable: "code",
30
33
  schema: [],
31
34
  messages: { useNullable: "Use Nullable<{{type}}> instead of {{type}} | null | undefined" }
32
35
  }
33
36
  };
34
- //#endregion
35
37
  export { rule as nullableRule };
@@ -1,18 +1,23 @@
1
- //#region rules/optional_rule.ts
1
+ import { createImportPlanner } from "./typebuddy_import.js";
2
+ // rules/optional_rule.ts
2
3
  const rule = {
3
4
  create(context) {
5
+ const sourceCode = context.getSourceCode();
6
+ const imports = createImportPlanner(sourceCode);
4
7
  return { TSUnionType(node) {
5
8
  if (node.types.length !== 2) return;
6
9
  const undefinedType = node.types.find((typeNode) => typeNode.type === "TSUndefinedKeyword");
7
10
  const otherType = node.types.find((typeNode) => typeNode.type !== "TSUndefinedKeyword" && typeNode.type !== "TSNullKeyword");
8
11
  if (undefinedType && otherType) {
9
- const typeText = context.getSourceCode().getText(otherType);
12
+ const typeText = sourceCode.getText(otherType);
10
13
  context.report({
11
14
  node,
12
15
  messageId: "preferOptional",
13
16
  data: { type: typeText },
14
17
  fix(fixer) {
15
- return fixer.replaceText(node, `Optional<${typeText}>`);
18
+ const importFixes = imports.fixes(node, fixer, "Optional", "type");
19
+ if (importFixes === null) return null;
20
+ return [...importFixes, fixer.replaceText(node, `Optional<${typeText}>`)];
16
21
  }
17
22
  });
18
23
  }
@@ -27,5 +32,4 @@ const rule = {
27
32
  messages: { preferOptional: "Use Optional<{{type}}> instead of {{type}} | undefined" }
28
33
  }
29
34
  };
30
- //#endregion
31
35
  export { rule as optionalRule };
@@ -1,4 +1,4 @@
1
- //#region rules/own_subtree.ts
1
+ // rules/own_subtree.ts
2
2
  const FUNCTION_TYPES = /* @__PURE__ */ new Set([
3
3
  "ArrowFunctionExpression",
4
4
  "FunctionDeclaration",
@@ -41,5 +41,4 @@ function walkOwnSubtree(root, visit) {
41
41
  }
42
42
  }
43
43
  }
44
- //#endregion
45
44
  export { walkOwnSubtree };