@murky-web/typebuddy 1.3.0 → 1.4.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.
@@ -1,46 +1,6 @@
1
1
  import { throwsDeliberately } from "./deliberate_throw.js";
2
+ import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
2
3
  //#region rules/async_rule.ts
3
- function isNode(value) {
4
- return typeof value === "object" && value !== null && "type" in value;
5
- }
6
- function getProgram(node) {
7
- let current = node;
8
- while (current?.parent) current = current.parent;
9
- return current?.type === "Program" ? current : null;
10
- }
11
- function isIdentifierNamed(node, name) {
12
- return isNode(node) && node.type === "Identifier" && node["name"] === name;
13
- }
14
- function isImportDeclaration(node) {
15
- return isNode(node) && node.type === "ImportDeclaration";
16
- }
17
- function getStringLiteralValue(node) {
18
- if (!isNode(node)) return null;
19
- if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node["value"] === "string") return node["value"];
20
- return null;
21
- }
22
- function getProgramBody(node) {
23
- if (!Array.isArray(node.body)) return [];
24
- return node.body.filter(isNode);
25
- }
26
- function hasTypeBuddyHelperImport(program, helperName) {
27
- return getProgramBody(program).some((statement) => {
28
- if (!isImportDeclaration(statement)) return false;
29
- if (getStringLiteralValue(statement["source"]) !== "@murky-web/typebuddy") return false;
30
- if (statement["importKind"] === "type") return false;
31
- return (Array.isArray(statement["specifiers"]) ? statement["specifiers"] : []).some((specifier) => {
32
- return isNode(specifier) && specifier.type === "ImportSpecifier" && isIdentifierNamed(specifier["local"], helperName);
33
- });
34
- });
35
- }
36
- function getTypeBuddyImportInsertRange(program) {
37
- const body = getProgramBody(program);
38
- const imports = body.filter(isImportDeclaration);
39
- const anchor = imports.at(-1) ?? body[0] ?? program;
40
- if (!Array.isArray(anchor.range) || anchor.range.length < 2) return null;
41
- if (imports.length > 0) return [anchor.range[1], anchor.range[1]];
42
- return [anchor.range[0], anchor.range[0]];
43
- }
44
4
  function hasTryCatch(nodes) {
45
5
  return nodes.some((node) => {
46
6
  return node.type === "TryStatement";
@@ -58,46 +18,62 @@ const rule = {
58
18
  let scheduledErrImport = false;
59
19
  function ensureErrImportFixes(node, fixer) {
60
20
  if (scheduledErrImport) return [];
61
- const program = getProgram(node);
62
- if (!program || hasTypeBuddyHelperImport(program, "err")) return [];
63
- const insertRange = getTypeBuddyImportInsertRange(program);
64
- if (!insertRange) return [];
21
+ const insertion = getTypeBuddyImportInsertion(node, "err");
22
+ if (!insertion) return [];
65
23
  scheduledErrImport = true;
66
- const importText = insertRange[0] !== 0 ? "\nimport { err } from \"@murky-web/typebuddy\";" : "import { err } from \"@murky-web/typebuddy\";\n";
67
- return [fixer.insertTextBeforeRange(insertRange, importText)];
24
+ return [fixer.insertTextBeforeRange(insertion.range, insertion.text)];
68
25
  }
69
- function getIndentation(node) {
70
- const firstLine = sourceCode.getText(node).split("\n")[0] ?? "";
71
- const match = /^\s*/.exec(firstLine);
72
- return match ? match[0] : "";
26
+ function wrapBlockFixes(bodyNode, fixer) {
27
+ 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")];
73
30
  }
74
- function wrapInTryCatch(node) {
75
- const body = Array.isArray(node.body) ? node.body : [];
76
- const indent = getIndentation(node);
77
- const innerIndent = `${indent} `;
78
- return `{
79
- ${indent}try {
80
- ${body.map((statement) => {
81
- const text = sourceCode.getText(statement);
82
- return `${innerIndent}${text.replaceAll(/^\s*/gm, "")}`;
83
- }).join("\n")}
84
- ${indent}} catch {
85
- ${innerIndent}return err();
86
- ${indent}}
87
- }`;
31
+ /**
32
+ * Wrap an expression-bodied arrow's value in a block with try/catch.
33
+ *
34
+ * The body node's range stops inside any wrapping parentheses, so
35
+ * replacing it in `async () => ({ a: 1 })` would leave the parentheses
36
+ * around a block and produce `({ try { ... } })`. Walking left over
37
+ * those parentheses first, then inserting on either side, keeps the
38
+ * expression itself untouched — parentheses and all.
39
+ */
40
+ function wrapExpressionBodyFixes(node, bodyNode, fixer) {
41
+ const arrowRange = node.range;
42
+ const bodyRange = bodyNode.range;
43
+ if (!Array.isArray(arrowRange) || arrowRange.length < 2 || !Array.isArray(bodyRange) || bodyRange.length < 2) return null;
44
+ let prefix = sourceCode.getText(node).slice(0, bodyRange[0] - arrowRange[0]);
45
+ while (prefix.trimEnd().endsWith("(")) prefix = prefix.trimEnd().slice(0, -1);
46
+ const start = arrowRange[0] + prefix.length;
47
+ const end = arrowRange[1];
48
+ if (start >= end) return null;
49
+ return [fixer.insertTextBeforeRange([start, start], "{\ntry {\nreturn "), fixer.insertTextBeforeRange([end, end], ";\n} catch {\nreturn err();\n}\n}")];
88
50
  }
89
51
  function checkFunction(node) {
90
52
  if (node.async !== true) return;
91
53
  if (isCallArgumentCallback(node)) return;
92
54
  const bodyNode = node.body;
93
- if (!bodyNode || Array.isArray(bodyNode) || bodyNode.type !== "BlockStatement") return;
94
- if (hasTryCatch(Array.isArray(bodyNode.body) ? bodyNode.body : [])) return;
55
+ if (!bodyNode || Array.isArray(bodyNode)) return;
95
56
  if (throwsDeliberately(bodyNode)) return;
57
+ if (bodyNode.type !== "BlockStatement") {
58
+ context.report({
59
+ node,
60
+ messageId: "missingTryCatch",
61
+ fix(fixer) {
62
+ const wrapFixes = wrapExpressionBodyFixes(node, bodyNode, fixer);
63
+ if (!wrapFixes) return null;
64
+ return [...ensureErrImportFixes(node, fixer), ...wrapFixes];
65
+ }
66
+ });
67
+ return;
68
+ }
69
+ if (hasTryCatch(Array.isArray(bodyNode.body) ? bodyNode.body : [])) return;
96
70
  context.report({
97
71
  node,
98
72
  messageId: "missingTryCatch",
99
73
  fix(fixer) {
100
- return [...ensureErrImportFixes(node, fixer), fixer.replaceText(bodyNode, wrapInTryCatch(bodyNode))];
74
+ const wrapFixes = wrapBlockFixes(bodyNode, fixer);
75
+ if (!wrapFixes) return null;
76
+ return [...ensureErrImportFixes(node, fixer), ...wrapFixes];
101
77
  }
102
78
  });
103
79
  }
@@ -1,12 +1,5 @@
1
+ import { walkOwnSubtree } from "./own_subtree.js";
1
2
  //#region rules/deliberate_throw.ts
2
- const FUNCTION_TYPES = /* @__PURE__ */ new Set([
3
- "ArrowFunctionExpression",
4
- "FunctionDeclaration",
5
- "FunctionExpression"
6
- ]);
7
- function isNode(value) {
8
- return typeof value === "object" && value !== null && "type" in value;
9
- }
10
3
  /**
11
4
  * Whether a function body throws on purpose.
12
5
  *
@@ -28,22 +21,11 @@ function isNode(value) {
28
21
  * @returns {boolean} True when the body throws outside any nested function.
29
22
  */
30
23
  function throwsDeliberately(body) {
31
- if (!isNode(body)) return false;
32
- const pending = [body];
33
- while (pending.length > 0) {
34
- const current = pending.pop();
35
- if (current === void 0) break;
36
- if (current.type === "ThrowStatement") return true;
37
- for (const [key, value] of Object.entries(current)) {
38
- if (key === "parent") continue;
39
- const candidates = Array.isArray(value) ? value : [value];
40
- for (const candidate of candidates) {
41
- if (!isNode(candidate) || FUNCTION_TYPES.has(candidate.type)) continue;
42
- pending.push(candidate);
43
- }
44
- }
45
- }
46
- return false;
24
+ let found = false;
25
+ walkOwnSubtree(body, (node) => {
26
+ if (node.type === "ThrowStatement") found = true;
27
+ });
28
+ return found;
47
29
  }
48
30
  //#endregion
49
31
  export { throwsDeliberately };
@@ -1,4 +1,6 @@
1
+ import { walkOwnSubtree } from "./own_subtree.js";
1
2
  import { throwsDeliberately } from "./deliberate_throw.js";
3
+ import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
2
4
  //#region rules/maybe_promise_rule.ts
3
5
  function isNode(value) {
4
6
  return typeof value === "object" && value !== null && "type" in value;
@@ -15,25 +17,27 @@ function isCallArgumentCallback(node) {
15
17
  if (parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
16
18
  return Array.isArray(parent["arguments"]) && parent["arguments"].includes(node);
17
19
  }
18
- function isIdentifierNamed(node, name) {
19
- return isNode(node) && node.type === "Identifier" && node["name"] === name;
20
- }
21
- function getProgram(node) {
20
+ /**
21
+ * Return-type names whose type argument is the value an async function settles
22
+ * on. `AsyncResult` is the preferred spelling of `MaybePromise`, so a function
23
+ * annotated with it has to be read the same way — otherwise the rule goes blind
24
+ * on exactly the code the package tells people to write.
25
+ */
26
+ const AWAITED_TYPE_NAMES = /* @__PURE__ */ new Set([
27
+ "AsyncResult",
28
+ "MaybePromise",
29
+ "Promise"
30
+ ]);
31
+ function isAmbient(node) {
22
32
  let current = node;
23
- while (current?.parent) current = current.parent;
24
- return current?.type === "Program" ? current : null;
25
- }
26
- function isImportDeclaration(node) {
27
- return isNode(node) && node.type === "ImportDeclaration";
28
- }
29
- function getStringLiteralValue(node) {
30
- if (!isNode(node)) return null;
31
- if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node["value"] === "string") return node["value"];
32
- return null;
33
+ while (current) {
34
+ if (current["declare"] === true) return true;
35
+ current = current.parent;
36
+ }
37
+ return false;
33
38
  }
34
- function getProgramBody(node) {
35
- if (!Array.isArray(node["body"])) return [];
36
- return node["body"].filter(isNode);
39
+ function isIdentifierNamed(node, name) {
40
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
37
41
  }
38
42
  function isResultHelperCall(node, name) {
39
43
  return isNode(node) && node.type === "CallExpression" && isIdentifierNamed(node["callee"], name);
@@ -55,24 +59,6 @@ function isBooleanLiteral(node, expected) {
55
59
  function isNullLiteral(node) {
56
60
  return isNode(node) && node.type === "Literal" && node["value"] === null;
57
61
  }
58
- function hasTypeBuddyHelperImport(program, helperName) {
59
- return getProgramBody(program).some((statement) => {
60
- if (!isImportDeclaration(statement)) return false;
61
- if (getStringLiteralValue(statement["source"]) !== "@murky-web/typebuddy") return false;
62
- if (statement["importKind"] === "type") return false;
63
- return (Array.isArray(statement["specifiers"]) ? statement["specifiers"] : []).some((specifier) => {
64
- return isNode(specifier) && specifier.type === "ImportSpecifier" && isIdentifierNamed(specifier["local"], helperName);
65
- });
66
- });
67
- }
68
- function getTypeBuddyImportInsertRange(program) {
69
- const body = getProgramBody(program);
70
- const imports = body.filter(isImportDeclaration);
71
- const anchor = imports.at(-1) ?? body[0] ?? program;
72
- if (!Array.isArray(anchor["range"]) || anchor["range"].length < 2) return null;
73
- if (imports.length > 0) return [anchor["range"][1], anchor["range"][1]];
74
- return [anchor["range"][0], anchor["range"][0]];
75
- }
76
62
  const rule = {
77
63
  create(context) {
78
64
  const sourceCode = context.getSourceCode();
@@ -92,24 +78,30 @@ const rule = {
92
78
  if (!isNode(firstParam)) return null;
93
79
  return firstParam;
94
80
  }
95
- function getPromiseTypeArgument(node) {
96
- if (getTypeName(node) !== "Promise") return null;
81
+ /**
82
+ * The awaited type behind an async function's return annotation.
83
+ *
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
87
+ * `MaybePromise<void>` function never became `return ok();`, while the
88
+ * identical `Promise<void>` function was fixed. It only ever worked
89
+ * because the rename and this lookup happen in the same pass, off the
90
+ * same AST.
91
+ */
92
+ function getAwaitedTypeArgument(node) {
93
+ const typeName = getTypeName(node);
94
+ if (typeName === null || !AWAITED_TYPE_NAMES.has(typeName)) return null;
97
95
  return getTypeArgument(node);
98
96
  }
99
97
  function ensureResultHelperImportFixes(node, fixer, helperName) {
100
98
  if (scheduledHelperImports.has(helperName)) return [];
101
- const program = getProgram(node);
102
- if (!program || hasTypeBuddyHelperImport(program, helperName)) return [];
103
- const insertRange = getTypeBuddyImportInsertRange(program);
104
- if (!insertRange) return [];
99
+ const insertion = getTypeBuddyImportInsertion(node, helperName);
100
+ if (!insertion) return [];
105
101
  scheduledHelperImports.add(helperName);
106
- const importText = insertRange[0] !== 0 ? `\nimport { ${helperName} } from "@murky-web/typebuddy";` : `import { ${helperName} } from "@murky-web/typebuddy";\n`;
107
- return [fixer.insertTextBeforeRange(insertRange, importText)];
102
+ return [fixer.insertTextBeforeRange(insertion.range, insertion.text)];
108
103
  }
109
- function checkReturnType(node) {
110
- if (!isAsyncFunction(node)) return;
111
- if (isCallArgumentCallback(node)) return;
112
- if (throwsDeliberately(node["body"])) return;
104
+ function reportPromiseReturnType(node) {
113
105
  if (!isNode(node["returnType"])) return;
114
106
  const typeAnnotation = node["returnType"]["typeAnnotation"];
115
107
  if (!isTypeReference(typeAnnotation)) return;
@@ -123,6 +115,27 @@ const rule = {
123
115
  }
124
116
  });
125
117
  }
118
+ function checkReturnType(node) {
119
+ if (!isAsyncFunction(node)) return;
120
+ if (isCallArgumentCallback(node)) return;
121
+ if (throwsDeliberately(node["body"])) return;
122
+ reportPromiseReturnType(node);
123
+ }
124
+ /**
125
+ * A type-level signature — an interface method, a function type, an
126
+ * overload — can never carry `async`, so routing it through
127
+ * `checkReturnType` meant these three visitors never fired at all.
128
+ * `Promise<T>` in a signature is the same contract the rule rewrites
129
+ * everywhere else, so it gets reported here without the async gate.
130
+ *
131
+ * Ambient declarations are the exception: `declare` describes code the
132
+ * project does not own, and rewriting a third-party framework's
133
+ * callback shape to `MaybePromise` would be a lie about that API.
134
+ */
135
+ function checkSignatureReturnType(node) {
136
+ if (isAmbient(node)) return;
137
+ reportPromiseReturnType(node);
138
+ }
126
139
  function wrapReturnValue(node, isAsync, returnType) {
127
140
  if (!isAsync) return;
128
141
  const argument = node["argument"];
@@ -170,6 +183,56 @@ const rule = {
170
183
  }
171
184
  });
172
185
  }
186
+ function collectOwnReturns(root) {
187
+ const returns = [];
188
+ walkOwnSubtree(root, (candidate) => {
189
+ if (candidate.type === "TryStatement") return false;
190
+ if (candidate.type === "ReturnStatement") returns.push(candidate);
191
+ return true;
192
+ });
193
+ return returns;
194
+ }
195
+ function isSettledFailure(argument) {
196
+ return isNode(argument) && argument.type === "Identifier" && argument["name"] === "FAILED_PROMISE" || isResultHelperCall(argument, "err");
197
+ }
198
+ /**
199
+ * Push a single `return` inside a catch block towards `err()`.
200
+ *
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.
207
+ */
208
+ function reportCatchReturn(tryNode, statement) {
209
+ const argument = statement["argument"];
210
+ if (isSettledFailure(argument)) return;
211
+ if (!isNode(argument)) {
212
+ context.report({
213
+ node: statement,
214
+ messageId: "returnFailedPromise",
215
+ fix(fixer) {
216
+ return [...ensureResultHelperImportFixes(tryNode, fixer, "err"), fixer.replaceText(statement, "return err()")];
217
+ }
218
+ });
219
+ return;
220
+ }
221
+ if (hasIsErrorFlag(argument, true)) {
222
+ if (isNullLiteral(getObjectPropertyValue(argument, "value"))) context.report({
223
+ node: argument,
224
+ messageId: "preferErrResult",
225
+ fix(fixer) {
226
+ return [...ensureResultHelperImportFixes(tryNode, fixer, "err"), fixer.replaceText(argument, "err()")];
227
+ }
228
+ });
229
+ return;
230
+ }
231
+ context.report({
232
+ node: statement,
233
+ messageId: "returnFailedPromise"
234
+ });
235
+ }
173
236
  function processTryCatch(node) {
174
237
  let parent = node.parent;
175
238
  let isAsync = false;
@@ -188,24 +251,25 @@ const rule = {
188
251
  let returnType = null;
189
252
  if (isNode(parentFunction["returnType"])) {
190
253
  const typeAnnotation = parentFunction["returnType"]["typeAnnotation"];
191
- if (isTypeReference(typeAnnotation)) returnType = getPromiseTypeArgument(typeAnnotation);
254
+ if (isTypeReference(typeAnnotation)) returnType = getAwaitedTypeArgument(typeAnnotation);
192
255
  }
193
- const blockBody = isNode(node["block"]) && Array.isArray(node["block"]["body"]) ? node["block"]["body"] : [];
194
- for (const statement of blockBody) if (isNode(statement) && statement.type === "ReturnStatement") wrapReturnValue(statement, isAsync, returnType);
195
- if (!isNode(node["handler"]) || !isNode(node["handler"]["body"])) return;
196
- const catchBody = Array.isArray(node["handler"]["body"]["body"]) ? node["handler"]["body"]["body"].filter(isNode) : [];
197
- for (const statement of catchBody) if (statement.type === "ReturnStatement" && isNode(statement["argument"])) wrapReturnValue(statement, isAsync, returnType);
198
- if (!catchBody.some((statement) => statement.type === "ReturnStatement" && isNode(statement["argument"]) && (statement["argument"].type === "Identifier" && statement["argument"]["name"] === "FAILED_PROMISE" || isResultHelperCall(statement["argument"], "err") || hasIsErrorFlag(statement["argument"], true)))) context.report({
199
- node: node["handler"],
256
+ for (const statement of collectOwnReturns(node["block"])) wrapReturnValue(statement, isAsync, returnType);
257
+ const handler = node["handler"];
258
+ if (!isNode(handler) || !isNode(handler["body"])) return;
259
+ const catchReturns = collectOwnReturns(handler["body"]);
260
+ for (const statement of catchReturns) reportCatchReturn(node, statement);
261
+ let settlesItself = false;
262
+ walkOwnSubtree(handler["body"], (candidate) => {
263
+ if (candidate.type === "ReturnStatement") settlesItself = true;
264
+ });
265
+ if (settlesItself) return;
266
+ context.report({
267
+ node: handler,
200
268
  messageId: "returnFailedPromise",
201
269
  fix(fixer) {
202
- const lastStatement = catchBody.at(-1);
203
- if (lastStatement?.type === "ReturnStatement" && isNode(lastStatement["argument"]) && lastStatement["argument"].type === "ObjectExpression") return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.replaceText(lastStatement, "return err()")];
204
- const handler = node["handler"];
205
- if (!isNode(handler)) return null;
206
- const bodyRange = handler["body"];
207
- if (!isNode(bodyRange) || !Array.isArray(bodyRange["range"])) return null;
208
- return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.insertTextBeforeRange([bodyRange["range"][1] - 1, bodyRange["range"][1] - 1], "return err(); ")];
270
+ const handlerBody = handler["body"];
271
+ 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")];
209
273
  }
210
274
  });
211
275
  }
@@ -213,9 +277,9 @@ const rule = {
213
277
  FunctionDeclaration: checkReturnType,
214
278
  FunctionExpression: checkReturnType,
215
279
  ArrowFunctionExpression: checkReturnType,
216
- TSDeclareFunction: checkReturnType,
217
- TSFunctionType: checkReturnType,
218
- TSMethodSignature: checkReturnType,
280
+ TSDeclareFunction: checkSignatureReturnType,
281
+ TSFunctionType: checkSignatureReturnType,
282
+ TSMethodSignature: checkSignatureReturnType,
219
283
  TryStatement: processTryCatch
220
284
  };
221
285
  },
@@ -4,7 +4,7 @@ const rule = {
4
4
  return { TSUnionType(node) {
5
5
  if (node.types.length !== 2) return;
6
6
  const undefinedType = node.types.find((typeNode) => typeNode.type === "TSUndefinedKeyword");
7
- const otherType = node.types.find((typeNode) => typeNode.type !== "TSUndefinedKeyword");
7
+ const otherType = node.types.find((typeNode) => typeNode.type !== "TSUndefinedKeyword" && typeNode.type !== "TSNullKeyword");
8
8
  if (undefinedType && otherType) {
9
9
  const typeText = context.getSourceCode().getText(otherType);
10
10
  context.report({
@@ -0,0 +1,45 @@
1
+ //#region rules/own_subtree.ts
2
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
3
+ "ArrowFunctionExpression",
4
+ "FunctionDeclaration",
5
+ "FunctionExpression"
6
+ ]);
7
+ function isNode(value) {
8
+ return typeof value === "object" && value !== null && "type" in value;
9
+ }
10
+ /**
11
+ * Visit every node that belongs to `root`, stopping at nested functions.
12
+ *
13
+ * Both async rules need the same notion of "this function's own code". A
14
+ * `throw` or a `return` inside a nested function belongs to that function, not
15
+ * to the one being linted, so the walk never descends into one — and `parent`
16
+ * points back up the tree, so following it would not terminate.
17
+ *
18
+ * `visit` may return `false` to keep the walk out of a node's children. That is
19
+ * how a rule declines a subtree that some other visitor already owns.
20
+ *
21
+ * @param {unknown} root - The node to start from. Visited itself, and never
22
+ * skipped for being a function.
23
+ * @param {(node: AstNode) => boolean | void} visit - Called once per node.
24
+ * Return `false` to skip that node's children.
25
+ * @returns {void}
26
+ */
27
+ function walkOwnSubtree(root, visit) {
28
+ if (!isNode(root)) return;
29
+ const pending = [root];
30
+ while (pending.length > 0) {
31
+ const current = pending.pop();
32
+ if (current === void 0) break;
33
+ if (visit(current) === false) continue;
34
+ for (const [key, value] of Object.entries(current)) {
35
+ if (key === "parent") continue;
36
+ const candidates = Array.isArray(value) ? value : [value];
37
+ for (const candidate of candidates) {
38
+ if (!isNode(candidate) || FUNCTION_TYPES.has(candidate.type)) continue;
39
+ pending.push(candidate);
40
+ }
41
+ }
42
+ }
43
+ }
44
+ //#endregion
45
+ export { walkOwnSubtree };
@@ -0,0 +1,79 @@
1
+ //#region rules/typebuddy_import.ts
2
+ const PACKAGE_NAME = "@murky-web/typebuddy";
3
+ function isNode(value) {
4
+ return typeof value === "object" && value !== null && "type" in value;
5
+ }
6
+ function isIdentifierNamed(node, name) {
7
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
8
+ }
9
+ function isImportDeclaration(node) {
10
+ return isNode(node) && node.type === "ImportDeclaration";
11
+ }
12
+ function getStringLiteralValue(node) {
13
+ if (!isNode(node)) return null;
14
+ if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node["value"] === "string") return node["value"];
15
+ return null;
16
+ }
17
+ function getProgram(node) {
18
+ if (!isNode(node)) return null;
19
+ let current = node;
20
+ while (current?.parent) current = current.parent;
21
+ return current?.type === "Program" ? current : null;
22
+ }
23
+ function getProgramBody(program) {
24
+ if (!Array.isArray(program["body"])) return [];
25
+ return program["body"].filter(isNode);
26
+ }
27
+ function importsHelper(program, helperName) {
28
+ return getProgramBody(program).some((statement) => {
29
+ if (!isImportDeclaration(statement)) return false;
30
+ if (getStringLiteralValue(statement["source"]) !== PACKAGE_NAME) return false;
31
+ if (statement["importKind"] === "type") return false;
32
+ return (Array.isArray(statement["specifiers"]) ? statement["specifiers"] : []).some((specifier) => {
33
+ return isNode(specifier) && specifier.type === "ImportSpecifier" && isIdentifierNamed(specifier["local"], helperName);
34
+ });
35
+ });
36
+ }
37
+ /**
38
+ * Where and what to insert so `helperName` is imported from the package.
39
+ *
40
+ * Both async rules add `ok`/`err` imports, and both used to carry their own
41
+ * copy of this — including the same bug. Whether the import lands after an
42
+ * existing one was inferred from the anchor's offset (`range[0] !== 0`), which
43
+ * is only the same question in a file whose first statement starts at byte
44
+ * zero. A leading comment moved the first statement off zero, the wrong branch
45
+ * won, and the fix emitted a leading newline instead of a trailing one:
46
+ *
47
+ * import { err } from "@murky-web/typebuddy";export async function load()
48
+ *
49
+ * The list of imports answers it directly, so that is what decides now.
50
+ *
51
+ * @param {unknown} node - Any node in the file; the program is found from it.
52
+ * @param {string} helperName - The named export to import, e.g. `"err"`.
53
+ * @returns {{ range: [number, number]; text: string } | null} The zero-width
54
+ * insertion to apply, or null when the helper is already imported or no
55
+ * anchor carries a usable range.
56
+ */
57
+ function getTypeBuddyImportInsertion(node, helperName) {
58
+ const program = getProgram(node);
59
+ if (!program || importsHelper(program, helperName)) return null;
60
+ const body = getProgramBody(program);
61
+ const imports = body.filter(isImportDeclaration);
62
+ const range = (imports.at(-1) ?? body[0] ?? program)["range"];
63
+ if (!Array.isArray(range) || range.length < 2) return null;
64
+ const statement = `import { ${helperName} } from "${PACKAGE_NAME}";`;
65
+ if (imports.length > 0) {
66
+ const end = range[1];
67
+ return {
68
+ range: [end, end],
69
+ text: `\n${statement}`
70
+ };
71
+ }
72
+ const start = range[0];
73
+ return {
74
+ range: [start, start],
75
+ text: `${statement}\n`
76
+ };
77
+ }
78
+ //#endregion
79
+ export { getTypeBuddyImportInsertion };
package/jsr.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://jsr.io/schema/config-file.v1.json",
3
3
  "name": "@murky-web/typebuddy",
4
- "version": "1.3.0",
4
+ "version": "1.4.0",
5
5
  "license": "ISC",
6
6
  "exports": {
7
7
  ".": "./src/index.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murky-web/typebuddy",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Your new best friend for simple typescript guards every project needs.",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",