@murky-web/typebuddy 1.1.1 → 1.3.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,21 +1,22 @@
1
+ import { throwsDeliberately } from "./deliberate_throw.js";
1
2
  //#region rules/maybe_promise_rule.ts
2
3
  function isNode(value) {
3
4
  return typeof value === "object" && value !== null && "type" in value;
4
5
  }
5
6
  function isAsyncFunction(node) {
6
- return node.async === true;
7
+ return node["async"] === true;
7
8
  }
8
9
  function hasTypeParameters(value) {
9
- return isNode(value) && Array.isArray(value.params);
10
+ return isNode(value) && Array.isArray(value["params"]);
10
11
  }
11
12
  function isCallArgumentCallback(node) {
12
13
  const parent = node.parent;
13
14
  if (!parent) return false;
14
15
  if (parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
15
- return Array.isArray(parent.arguments) && parent.arguments.includes(node);
16
+ return Array.isArray(parent["arguments"]) && parent["arguments"].includes(node);
16
17
  }
17
18
  function isIdentifierNamed(node, name) {
18
- return isNode(node) && node.type === "Identifier" && node.name === name;
19
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
19
20
  }
20
21
  function getProgram(node) {
21
22
  let current = node;
@@ -27,40 +28,40 @@ function isImportDeclaration(node) {
27
28
  }
28
29
  function getStringLiteralValue(node) {
29
30
  if (!isNode(node)) return null;
30
- if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
31
+ if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node["value"] === "string") return node["value"];
31
32
  return null;
32
33
  }
33
34
  function getProgramBody(node) {
34
- if (!Array.isArray(node.body)) return [];
35
- return node.body.filter(isNode);
35
+ if (!Array.isArray(node["body"])) return [];
36
+ return node["body"].filter(isNode);
36
37
  }
37
38
  function isResultHelperCall(node, name) {
38
- return isNode(node) && node.type === "CallExpression" && isIdentifierNamed(node.callee, name);
39
+ return isNode(node) && node.type === "CallExpression" && isIdentifierNamed(node["callee"], name);
39
40
  }
40
41
  function hasIsErrorFlag(node, expected) {
41
- if (!isNode(node) || node.type !== "ObjectExpression" || !Array.isArray(node.properties)) return false;
42
- return node.properties.some((property) => {
43
- return isNode(property) && property.type === "Property" && isIdentifierNamed(property.key, "isError") && isNode(property.value) && property.value.type === "Literal" && property.value.value === expected;
42
+ if (!isNode(node) || node.type !== "ObjectExpression" || !Array.isArray(node["properties"])) return false;
43
+ return node["properties"].some((property) => {
44
+ return isNode(property) && property.type === "Property" && isIdentifierNamed(property["key"], "isError") && isNode(property["value"]) && property["value"].type === "Literal" && property["value"]["value"] === expected;
44
45
  });
45
46
  }
46
47
  function getObjectPropertyValue(node, propertyName) {
47
- if (!isNode(node) || node.type !== "ObjectExpression" || !Array.isArray(node.properties)) return null;
48
- for (const property of node.properties) if (isNode(property) && property.type === "Property" && isIdentifierNamed(property.key, propertyName) && isNode(property.value)) return property.value;
48
+ if (!isNode(node) || node.type !== "ObjectExpression" || !Array.isArray(node["properties"])) return null;
49
+ for (const property of node["properties"]) if (isNode(property) && property.type === "Property" && isIdentifierNamed(property["key"], propertyName) && isNode(property["value"])) return property["value"];
49
50
  return null;
50
51
  }
51
52
  function isBooleanLiteral(node, expected) {
52
- return isNode(node) && node.type === "Literal" && node.value === expected;
53
+ return isNode(node) && node.type === "Literal" && node["value"] === expected;
53
54
  }
54
55
  function isNullLiteral(node) {
55
- return isNode(node) && node.type === "Literal" && node.value === null;
56
+ return isNode(node) && node.type === "Literal" && node["value"] === null;
56
57
  }
57
58
  function hasTypeBuddyHelperImport(program, helperName) {
58
59
  return getProgramBody(program).some((statement) => {
59
60
  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);
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);
64
65
  });
65
66
  });
66
67
  }
@@ -68,9 +69,9 @@ function getTypeBuddyImportInsertRange(program) {
68
69
  const body = getProgramBody(program);
69
70
  const imports = body.filter(isImportDeclaration);
70
71
  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]];
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]];
74
75
  }
75
76
  const rule = {
76
77
  create(context) {
@@ -80,12 +81,12 @@ const rule = {
80
81
  return isNode(node) && node.type === "TSTypeReference";
81
82
  }
82
83
  function getTypeName(node) {
83
- const typeName = node.typeName;
84
+ const typeName = node["typeName"];
84
85
  if (!isNode(typeName) || typeName.type !== "Identifier") return null;
85
- return typeof typeName.name === "string" ? typeName.name : null;
86
+ return typeof typeName["name"] === "string" ? typeName["name"] : null;
86
87
  }
87
88
  function getTypeArgument(node) {
88
- const typeArguments = node.typeArguments;
89
+ const typeArguments = node["typeArguments"];
89
90
  if (!hasTypeParameters(typeArguments)) return null;
90
91
  const [firstParam] = typeArguments.params;
91
92
  if (!isNode(firstParam)) return null;
@@ -108,11 +109,12 @@ const rule = {
108
109
  function checkReturnType(node) {
109
110
  if (!isAsyncFunction(node)) return;
110
111
  if (isCallArgumentCallback(node)) return;
111
- if (!isNode(node.returnType)) return;
112
- const typeAnnotation = node.returnType.typeAnnotation;
112
+ if (throwsDeliberately(node["body"])) return;
113
+ if (!isNode(node["returnType"])) return;
114
+ const typeAnnotation = node["returnType"]["typeAnnotation"];
113
115
  if (!isTypeReference(typeAnnotation)) return;
114
116
  if (getTypeName(typeAnnotation) !== "Promise") return;
115
- const typeName = typeAnnotation.typeName;
117
+ const typeName = typeAnnotation["typeName"];
116
118
  context.report({
117
119
  node: typeName,
118
120
  messageId: "replaceWithMaybePromise",
@@ -123,7 +125,7 @@ const rule = {
123
125
  }
124
126
  function wrapReturnValue(node, isAsync, returnType) {
125
127
  if (!isAsync) return;
126
- const argument = node.argument;
128
+ const argument = node["argument"];
127
129
  if (!isNode(argument)) {
128
130
  if (returnType?.type === "TSVoidKeyword") context.report({
129
131
  node,
@@ -134,7 +136,7 @@ const rule = {
134
136
  });
135
137
  return;
136
138
  }
137
- if (argument.type === "Identifier" && (argument.name === "VOID_PROMISE" || argument.name === "FAILED_PROMISE")) return;
139
+ if (argument.type === "Identifier" && (argument["name"] === "VOID_PROMISE" || argument["name"] === "FAILED_PROMISE")) return;
138
140
  if (isResultHelperCall(argument, "ok") || isResultHelperCall(argument, "err")) return;
139
141
  const isErrorValue = getObjectPropertyValue(argument, "isError");
140
142
  const objectValue = getObjectPropertyValue(argument, "value");
@@ -174,7 +176,7 @@ const rule = {
174
176
  let parentFunction = null;
175
177
  while (parent) {
176
178
  if (parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression" || parent.type === "ArrowFunctionExpression") {
177
- isAsync = parent.async === true;
179
+ isAsync = parent["async"] === true;
178
180
  parentFunction = parent;
179
181
  break;
180
182
  }
@@ -182,27 +184,28 @@ const rule = {
182
184
  }
183
185
  if (!isAsync || !parentFunction) return;
184
186
  if (isCallArgumentCallback(parentFunction)) return;
187
+ if (throwsDeliberately(parentFunction["body"])) return;
185
188
  let returnType = null;
186
- if (isNode(parentFunction.returnType)) {
187
- const typeAnnotation = parentFunction.returnType.typeAnnotation;
189
+ if (isNode(parentFunction["returnType"])) {
190
+ const typeAnnotation = parentFunction["returnType"]["typeAnnotation"];
188
191
  if (isTypeReference(typeAnnotation)) returnType = getPromiseTypeArgument(typeAnnotation);
189
192
  }
190
- const blockBody = isNode(node.block) && Array.isArray(node.block.body) ? node.block.body : [];
193
+ const blockBody = isNode(node["block"]) && Array.isArray(node["block"]["body"]) ? node["block"]["body"] : [];
191
194
  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,
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"],
197
200
  messageId: "returnFailedPromise",
198
201
  fix(fixer) {
199
202
  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;
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"];
202
205
  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(); ")];
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(); ")];
206
209
  }
207
210
  });
208
211
  }
@@ -233,4 +236,4 @@ const rule = {
233
236
  }
234
237
  };
235
238
  //#endregion
236
- export { rule };
239
+ export { rule as errorSafeAsyncRule };
@@ -31,4 +31,4 @@ const rule = {
31
31
  }
32
32
  };
33
33
  //#endregion
34
- export { rule };
34
+ export { rule as maybeRule };
@@ -32,4 +32,4 @@ const rule = {
32
32
  }
33
33
  };
34
34
  //#endregion
35
- export { rule };
35
+ export { rule as nullableRule };
@@ -28,4 +28,4 @@ const rule = {
28
28
  }
29
29
  };
30
30
  //#endregion
31
- export { rule };
31
+ export { rule as optionalRule };
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.1.1",
4
+ "version": "1.3.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.1.1",
3
+ "version": "1.3.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",
@@ -38,22 +68,21 @@
38
68
  "lint:fix": "oxlint -c ./.oxlintrc.jsonc --tsconfig ./tsconfig.lint.json --type-aware --fix src biome tsdown.config.ts vitest.config.ts",
39
69
  "format": "oxfmt -c ../config/oxc/.oxfmtrc.jsonc src rules biome tests tsdown.config.ts vitest.config.ts",
40
70
  "format:check": "oxfmt -c ../config/oxc/.oxfmtrc.jsonc --check src rules biome tests tsdown.config.ts vitest.config.ts",
41
- "smoke:globals": "bun run build && tsgo --project ./smoke/globals/tsconfig.json --noEmit",
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
- "typecheck": "tsgo --project ./tsconfig.json --noEmit && tsgo --project ./tsconfig.vitest.json --noEmit"
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",
@@ -72,6 +101,7 @@
72
101
  "provenance": true
73
102
  },
74
103
  "devDependencies": {
75
- "@murky-web/config": "workspace:*"
104
+ "@murky-web/config": "workspace:*",
105
+ "@types/node": "^25.5.0"
76
106
  }
77
107
  }
@@ -1,3 +1,5 @@
1
+ import { throwsDeliberately } from "./deliberate_throw.js";
2
+
1
3
  type AstNode = {
2
4
  type: string;
3
5
  body?: AstNode | AstNode[];
@@ -42,7 +44,7 @@ function getProgram(node: AstNode): AstNode | null {
42
44
  }
43
45
 
44
46
  function isIdentifierNamed(node: unknown, name: string): boolean {
45
- return isNode(node) && node.type === "Identifier" && node.name === name;
47
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
46
48
  }
47
49
 
48
50
  function isImportDeclaration(node: unknown): node is AstNode {
@@ -56,9 +58,9 @@ function getStringLiteralValue(node: unknown): string | null {
56
58
 
57
59
  if (
58
60
  (node.type === "Literal" || node.type === "StringLiteral") &&
59
- typeof node.value === "string"
61
+ typeof node["value"] === "string"
60
62
  ) {
61
- return node.value;
63
+ return node["value"];
62
64
  }
63
65
 
64
66
  return null;
@@ -79,24 +81,24 @@ function hasTypeBuddyHelperImport(program: AstNode, helperName: "err") {
79
81
  }
80
82
 
81
83
  if (
82
- getStringLiteralValue(statement.source) !== "@murky-web/typebuddy"
84
+ getStringLiteralValue(statement["source"]) !== "@murky-web/typebuddy"
83
85
  ) {
84
86
  return false;
85
87
  }
86
88
 
87
- if (statement.importKind === "type") {
89
+ if (statement["importKind"] === "type") {
88
90
  return false;
89
91
  }
90
92
 
91
- const specifiers = Array.isArray(statement.specifiers)
92
- ? statement.specifiers
93
+ const specifiers = Array.isArray(statement["specifiers"])
94
+ ? statement["specifiers"]
93
95
  : [];
94
96
 
95
97
  return specifiers.some((specifier) => {
96
98
  return (
97
99
  isNode(specifier) &&
98
100
  specifier.type === "ImportSpecifier" &&
99
- isIdentifierNamed(specifier.local, helperName)
101
+ isIdentifierNamed(specifier["local"], helperName)
100
102
  );
101
103
  });
102
104
  });
@@ -136,7 +138,7 @@ function isCallArgumentCallback(node: AstNode): boolean {
136
138
  return false;
137
139
  }
138
140
 
139
- return Array.isArray(parent.arguments) && parent.arguments.includes(node);
141
+ return Array.isArray(parent["arguments"]) && parent["arguments"].includes(node);
140
142
  }
141
143
 
142
144
  const rule = {
@@ -174,7 +176,9 @@ const rule = {
174
176
 
175
177
  function getIndentation(node: AstNode): string {
176
178
  const lines = sourceCode.getText(node).split("\n");
177
- const firstLine = lines[0];
179
+ // `split` always yields at least one element, but
180
+ // `noUncheckedIndexedAccess` cannot know that.
181
+ const firstLine = lines[0] ?? "";
178
182
  const match = /^\s*/.exec(firstLine);
179
183
  return match ? match[0] : "";
180
184
  }
@@ -213,6 +217,9 @@ ${indent}}
213
217
 
214
218
  const body = Array.isArray(bodyNode.body) ? bodyNode.body : [];
215
219
  if (hasTryCatch(body)) return;
220
+ // A function that throws has already decided its failure is not a
221
+ // value. Wrapping it in try/catch would swallow that decision.
222
+ if (throwsDeliberately(bodyNode)) return;
216
223
 
217
224
  context.report({
218
225
  node,
@@ -0,0 +1,73 @@
1
+ type AstNode = {
2
+ type: string;
3
+ [key: string]: unknown;
4
+ };
5
+
6
+ const FUNCTION_TYPES = new Set([
7
+ "ArrowFunctionExpression",
8
+ "FunctionDeclaration",
9
+ "FunctionExpression",
10
+ ]);
11
+
12
+ function isNode(value: unknown): value is AstNode {
13
+ return typeof value === "object" && value !== null && "type" in value;
14
+ }
15
+
16
+ /**
17
+ * Whether a function body throws on purpose.
18
+ *
19
+ * A `throw` in a function's own body is the author saying this failure is not a
20
+ * value to hand back. A missing manifest for a route the app is navigating to,
21
+ * an unreachable branch, a broken invariant — those should be loud. Turning them
22
+ * into `err()` converts a bug into a silently handled outcome, and the caller
23
+ * degrades politely instead of surfacing that something is wrong.
24
+ *
25
+ * So both async rules leave such a function alone. The rules exist to push
26
+ * *recoverable* failures into the return type, not to abolish throwing.
27
+ *
28
+ * Two boundaries matter. A throw inside a nested function belongs to that
29
+ * function, so the walk does not descend into one. A throw inside `catch` still
30
+ * counts: a rethrow is as deliberate as an original throw, and it is how code
31
+ * says "this one is not mine to handle".
32
+ *
33
+ * @param {unknown} body - The function body node to inspect.
34
+ * @returns {boolean} True when the body throws outside any nested function.
35
+ */
36
+ function throwsDeliberately(body: unknown): boolean {
37
+ if (!isNode(body)) {
38
+ return false;
39
+ }
40
+
41
+ const pending: AstNode[] = [body];
42
+ while (pending.length > 0) {
43
+ // `pop` on a non-empty array always yields a node; the length check above is
44
+ // the loop condition, but `noUncheckedIndexedAccess` cannot see that.
45
+ const current = pending.pop();
46
+ if (current === undefined) {
47
+ break;
48
+ }
49
+
50
+ if (current.type === "ThrowStatement") {
51
+ return true;
52
+ }
53
+
54
+ for (const [key, value] of Object.entries(current)) {
55
+ // `parent` points back up the tree; following it would never terminate.
56
+ if (key === "parent") {
57
+ continue;
58
+ }
59
+
60
+ const candidates = Array.isArray(value) ? value : [value];
61
+ for (const candidate of candidates) {
62
+ if (!isNode(candidate) || FUNCTION_TYPES.has(candidate.type)) {
63
+ continue;
64
+ }
65
+ pending.push(candidate);
66
+ }
67
+ }
68
+ }
69
+
70
+ return false;
71
+ }
72
+
73
+ export { throwsDeliberately };