@murky-web/typebuddy 1.2.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,3 +1,6 @@
1
+ import { walkOwnSubtree } from "./own_subtree.js";
2
+ import { throwsDeliberately } from "./deliberate_throw.js";
3
+ import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
1
4
  //#region rules/maybe_promise_rule.ts
2
5
  function isNode(value) {
3
6
  return typeof value === "object" && value !== null && "type" in value;
@@ -14,25 +17,27 @@ function isCallArgumentCallback(node) {
14
17
  if (parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
15
18
  return Array.isArray(parent["arguments"]) && parent["arguments"].includes(node);
16
19
  }
17
- function isIdentifierNamed(node, name) {
18
- return isNode(node) && node.type === "Identifier" && node["name"] === name;
19
- }
20
- 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) {
21
32
  let current = node;
22
- while (current?.parent) current = current.parent;
23
- return current?.type === "Program" ? current : null;
24
- }
25
- function isImportDeclaration(node) {
26
- return isNode(node) && node.type === "ImportDeclaration";
27
- }
28
- function getStringLiteralValue(node) {
29
- if (!isNode(node)) return null;
30
- if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node["value"] === "string") return node["value"];
31
- return null;
33
+ while (current) {
34
+ if (current["declare"] === true) return true;
35
+ current = current.parent;
36
+ }
37
+ return false;
32
38
  }
33
- function getProgramBody(node) {
34
- if (!Array.isArray(node["body"])) return [];
35
- return node["body"].filter(isNode);
39
+ function isIdentifierNamed(node, name) {
40
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
36
41
  }
37
42
  function isResultHelperCall(node, name) {
38
43
  return isNode(node) && node.type === "CallExpression" && isIdentifierNamed(node["callee"], name);
@@ -54,24 +59,6 @@ function isBooleanLiteral(node, expected) {
54
59
  function isNullLiteral(node) {
55
60
  return isNode(node) && node.type === "Literal" && node["value"] === null;
56
61
  }
57
- function hasTypeBuddyHelperImport(program, helperName) {
58
- return getProgramBody(program).some((statement) => {
59
- if (!isImportDeclaration(statement)) return false;
60
- if (getStringLiteralValue(statement["source"]) !== "@murky-web/typebuddy") return false;
61
- if (statement["importKind"] === "type") return false;
62
- return (Array.isArray(statement["specifiers"]) ? statement["specifiers"] : []).some((specifier) => {
63
- return isNode(specifier) && specifier.type === "ImportSpecifier" && isIdentifierNamed(specifier["local"], helperName);
64
- });
65
- });
66
- }
67
- function getTypeBuddyImportInsertRange(program) {
68
- const body = getProgramBody(program);
69
- const imports = body.filter(isImportDeclaration);
70
- const anchor = imports.at(-1) ?? body[0] ?? program;
71
- if (!Array.isArray(anchor["range"]) || anchor["range"].length < 2) return null;
72
- if (imports.length > 0) return [anchor["range"][1], anchor["range"][1]];
73
- return [anchor["range"][0], anchor["range"][0]];
74
- }
75
62
  const rule = {
76
63
  create(context) {
77
64
  const sourceCode = context.getSourceCode();
@@ -91,23 +78,30 @@ const rule = {
91
78
  if (!isNode(firstParam)) return null;
92
79
  return firstParam;
93
80
  }
94
- function getPromiseTypeArgument(node) {
95
- 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;
96
95
  return getTypeArgument(node);
97
96
  }
98
97
  function ensureResultHelperImportFixes(node, fixer, helperName) {
99
98
  if (scheduledHelperImports.has(helperName)) return [];
100
- const program = getProgram(node);
101
- if (!program || hasTypeBuddyHelperImport(program, helperName)) return [];
102
- const insertRange = getTypeBuddyImportInsertRange(program);
103
- if (!insertRange) return [];
99
+ const insertion = getTypeBuddyImportInsertion(node, helperName);
100
+ if (!insertion) return [];
104
101
  scheduledHelperImports.add(helperName);
105
- const importText = insertRange[0] !== 0 ? `\nimport { ${helperName} } from "@murky-web/typebuddy";` : `import { ${helperName} } from "@murky-web/typebuddy";\n`;
106
- return [fixer.insertTextBeforeRange(insertRange, importText)];
102
+ return [fixer.insertTextBeforeRange(insertion.range, insertion.text)];
107
103
  }
108
- function checkReturnType(node) {
109
- if (!isAsyncFunction(node)) return;
110
- if (isCallArgumentCallback(node)) return;
104
+ function reportPromiseReturnType(node) {
111
105
  if (!isNode(node["returnType"])) return;
112
106
  const typeAnnotation = node["returnType"]["typeAnnotation"];
113
107
  if (!isTypeReference(typeAnnotation)) return;
@@ -121,6 +115,27 @@ const rule = {
121
115
  }
122
116
  });
123
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
+ }
124
139
  function wrapReturnValue(node, isAsync, returnType) {
125
140
  if (!isAsync) return;
126
141
  const argument = node["argument"];
@@ -168,6 +183,56 @@ const rule = {
168
183
  }
169
184
  });
170
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
+ }
171
236
  function processTryCatch(node) {
172
237
  let parent = node.parent;
173
238
  let isAsync = false;
@@ -182,27 +247,29 @@ const rule = {
182
247
  }
183
248
  if (!isAsync || !parentFunction) return;
184
249
  if (isCallArgumentCallback(parentFunction)) return;
250
+ if (throwsDeliberately(parentFunction["body"])) return;
185
251
  let returnType = null;
186
252
  if (isNode(parentFunction["returnType"])) {
187
253
  const typeAnnotation = parentFunction["returnType"]["typeAnnotation"];
188
- if (isTypeReference(typeAnnotation)) returnType = getPromiseTypeArgument(typeAnnotation);
254
+ if (isTypeReference(typeAnnotation)) returnType = getAwaitedTypeArgument(typeAnnotation);
189
255
  }
190
- const blockBody = isNode(node["block"]) && Array.isArray(node["block"]["body"]) ? node["block"]["body"] : [];
191
- for (const statement of blockBody) if (isNode(statement) && statement.type === "ReturnStatement") wrapReturnValue(statement, isAsync, returnType);
192
- if (!isNode(node["handler"]) || !isNode(node["handler"]["body"])) return;
193
- const catchBody = Array.isArray(node["handler"]["body"]["body"]) ? node["handler"]["body"]["body"].filter(isNode) : [];
194
- for (const statement of catchBody) if (statement.type === "ReturnStatement" && isNode(statement["argument"])) wrapReturnValue(statement, isAsync, returnType);
195
- 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({
196
- 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,
197
268
  messageId: "returnFailedPromise",
198
269
  fix(fixer) {
199
- const lastStatement = catchBody.at(-1);
200
- if (lastStatement?.type === "ReturnStatement" && isNode(lastStatement["argument"]) && lastStatement["argument"].type === "ObjectExpression") return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.replaceText(lastStatement, "return err()")];
201
- const handler = node["handler"];
202
- if (!isNode(handler)) return null;
203
- const bodyRange = handler["body"];
204
- if (!isNode(bodyRange) || !Array.isArray(bodyRange["range"])) return null;
205
- 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")];
206
273
  }
207
274
  });
208
275
  }
@@ -210,9 +277,9 @@ const rule = {
210
277
  FunctionDeclaration: checkReturnType,
211
278
  FunctionExpression: checkReturnType,
212
279
  ArrowFunctionExpression: checkReturnType,
213
- TSDeclareFunction: checkReturnType,
214
- TSFunctionType: checkReturnType,
215
- TSMethodSignature: checkReturnType,
280
+ TSDeclareFunction: checkSignatureReturnType,
281
+ TSFunctionType: checkSignatureReturnType,
282
+ TSMethodSignature: checkSignatureReturnType,
216
283
  TryStatement: processTryCatch
217
284
  };
218
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.2.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.2.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",
@@ -12,6 +12,36 @@
12
12
  "import": "./dist/index.js",
13
13
  "default": "./dist/index.js"
14
14
  },
15
+ "./guards": {
16
+ "types": "./src/guards.ts",
17
+ "import": "./dist/guards.js",
18
+ "default": "./dist/guards.js"
19
+ },
20
+ "./result": {
21
+ "types": "./src/result.ts",
22
+ "import": "./dist/result.js",
23
+ "default": "./dist/result.js"
24
+ },
25
+ "./parse": {
26
+ "types": "./src/parse.ts",
27
+ "import": "./dist/parse.js",
28
+ "default": "./dist/parse.js"
29
+ },
30
+ "./empty": {
31
+ "types": "./src/empty.ts",
32
+ "import": "./dist/empty.js",
33
+ "default": "./dist/empty.js"
34
+ },
35
+ "./ids": {
36
+ "types": "./src/ids.ts",
37
+ "import": "./dist/ids.js",
38
+ "default": "./dist/ids.js"
39
+ },
40
+ "./collections": {
41
+ "types": "./src/collections.ts",
42
+ "import": "./dist/collections.js",
43
+ "default": "./dist/collections.js"
44
+ },
15
45
  "./globals": {
16
46
  "types": "./globals.ts",
17
47
  "import": "./dist/globals.js",
@@ -41,19 +71,18 @@
41
71
  "smoke:globals": "bun run build && tsc --project ./smoke/globals/tsconfig.json --noEmit",
42
72
  "smoke:oxlint": "bun run build && bun ./smoke/oxlint/run-smoke.ts",
43
73
  "smoke:oxlint:fix": "bun run build && bun ./smoke/oxlint/run-fix-smoke.ts",
74
+ "smoke:subpath": "bun run build && bun ./smoke/subpath/run.ts",
44
75
  "smoke:treeshake": "bun run build && bun ./smoke/treeshake/run.ts",
45
76
  "typecheck": "tsc --project ./tsconfig.json --noEmit && tsc --project ./tsconfig.vitest.json --noEmit"
46
77
  },
47
78
  "files": [
79
+ "biome",
48
80
  "dist",
49
81
  "globals.ts",
50
82
  "jsr.json",
51
- "src/index.ts",
52
- "src/type_helper.ts",
53
- "src/types",
54
83
  "oxlint/index.ts",
55
- "biome",
56
- "rules"
84
+ "rules",
85
+ "src"
57
86
  ],
58
87
  "repository": {
59
88
  "type": "git",