@murky-web/typebuddy 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -150,12 +150,34 @@ That makes these names available globally:
150
150
 
151
151
  ### Utility Functions
152
152
 
153
+ - `ok(value)` and `err()` helpers for `MaybePromise` result objects
153
154
  - `getKeys<T extends Record<string, unknown>>(object: T): Array<keyof T>`
154
155
  - `arrayContainsCommonValue<T>(array1: T[], array2: T[]): boolean`
155
156
  - `isEmptyString(value: unknown): boolean`
156
157
  - `isEmptyLike(value: unknown): boolean`
157
158
  - `hasEmptyValues(value: unknown): boolean`
158
159
 
160
+ ### Result Helpers
161
+
162
+ Use these when you want small Rust-like `Ok` and `Err` ergonomics without
163
+ hand-writing result objects:
164
+
165
+ ```typescript
166
+ import { err, ok } from "@murky-web/typebuddy";
167
+
168
+ export async function loadName(): MaybePromise<string> {
169
+ try {
170
+ return ok("murky");
171
+ } catch {
172
+ return err();
173
+ }
174
+ }
175
+
176
+ export async function flush(): MaybePromise<void> {
177
+ return ok();
178
+ }
179
+ ```
180
+
159
181
  ### Types
160
182
 
161
183
  - `Optional<T>`
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { arrayContainsCommonValue, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString } from "./src/type_helper.js";
2
- export { arrayContainsCommonValue, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
1
+ import { arrayContainsCommonValue, err, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, ok, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString } from "./src/type_helper.js";
2
+ export { arrayContainsCommonValue, err, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, ok, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
@@ -1,12 +1,70 @@
1
1
  //#region rules/async_rule.ts
2
+ function isNode(value) {
3
+ return typeof value === "object" && value !== null && "type" in value;
4
+ }
5
+ function getProgram(node) {
6
+ let current = node;
7
+ while (current?.parent) current = current.parent;
8
+ return current?.type === "Program" ? current : null;
9
+ }
10
+ function isIdentifierNamed(node, name) {
11
+ return isNode(node) && node.type === "Identifier" && node.name === name;
12
+ }
13
+ function isImportDeclaration(node) {
14
+ return isNode(node) && node.type === "ImportDeclaration";
15
+ }
16
+ function getStringLiteralValue(node) {
17
+ if (!isNode(node)) return null;
18
+ if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
19
+ return null;
20
+ }
21
+ function getProgramBody(node) {
22
+ if (!Array.isArray(node.body)) return [];
23
+ return node.body.filter(isNode);
24
+ }
25
+ function hasTypeBuddyHelperImport(program, helperName) {
26
+ return getProgramBody(program).some((statement) => {
27
+ if (!isImportDeclaration(statement)) return false;
28
+ if (getStringLiteralValue(statement.source) !== "@murky-web/typebuddy") return false;
29
+ if (statement.importKind === "type") return false;
30
+ return (Array.isArray(statement.specifiers) ? statement.specifiers : []).some((specifier) => {
31
+ return isNode(specifier) && specifier.type === "ImportSpecifier" && isIdentifierNamed(specifier.local, helperName);
32
+ });
33
+ });
34
+ }
35
+ function getTypeBuddyImportInsertRange(program) {
36
+ const body = getProgramBody(program);
37
+ const imports = body.filter(isImportDeclaration);
38
+ const anchor = imports.at(-1) ?? body[0] ?? program;
39
+ if (!Array.isArray(anchor.range) || anchor.range.length < 2) return null;
40
+ if (imports.length > 0) return [anchor.range[1], anchor.range[1]];
41
+ return [anchor.range[0], anchor.range[0]];
42
+ }
2
43
  function hasTryCatch(nodes) {
3
44
  return nodes.some((node) => {
4
45
  return node.type === "TryStatement";
5
46
  });
6
47
  }
48
+ function isCallArgumentCallback(node) {
49
+ const parent = node.parent;
50
+ if (!parent) return false;
51
+ if (parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
52
+ return Array.isArray(parent.arguments) && parent.arguments.includes(node);
53
+ }
7
54
  const rule = {
8
55
  create(context) {
9
56
  const sourceCode = context.getSourceCode();
57
+ let scheduledErrImport = false;
58
+ function ensureErrImportFixes(node, fixer) {
59
+ if (scheduledErrImport) return [];
60
+ const program = getProgram(node);
61
+ if (!program || hasTypeBuddyHelperImport(program, "err")) return [];
62
+ const insertRange = getTypeBuddyImportInsertRange(program);
63
+ if (!insertRange) return [];
64
+ scheduledErrImport = true;
65
+ const importText = insertRange[0] !== 0 ? "\nimport { err } from \"@murky-web/typebuddy\";" : "import { err } from \"@murky-web/typebuddy\";\n";
66
+ return [fixer.insertTextBeforeRange(insertRange, importText)];
67
+ }
10
68
  function getIndentation(node) {
11
69
  const firstLine = sourceCode.getText(node).split("\n")[0];
12
70
  const match = /^\s*/.exec(firstLine);
@@ -21,13 +79,14 @@ ${indent}try {
21
79
  ${body.map((statement) => {
22
80
  return `${innerIndent}${sourceCode.getText(statement).replaceAll(/^\s*/gm, "")}`;
23
81
  }).join("\n")}
24
- ${indent}} catch (err) {
25
- ${innerIndent}return FAILED_PROMISE;
82
+ ${indent}} catch {
83
+ ${innerIndent}return err();
26
84
  ${indent}}
27
85
  }`;
28
86
  }
29
87
  function checkFunction(node) {
30
88
  if (node.async !== true) return;
89
+ if (isCallArgumentCallback(node)) return;
31
90
  const bodyNode = node.body;
32
91
  if (!bodyNode || Array.isArray(bodyNode) || bodyNode.type !== "BlockStatement") return;
33
92
  if (hasTryCatch(Array.isArray(bodyNode.body) ? bodyNode.body : [])) return;
@@ -35,7 +94,7 @@ ${indent}}
35
94
  node,
36
95
  messageId: "missingTryCatch",
37
96
  fix(fixer) {
38
- return fixer.replaceText(bodyNode, wrapInTryCatch(bodyNode));
97
+ return [...ensureErrImportFixes(node, fixer), fixer.replaceText(bodyNode, wrapInTryCatch(bodyNode))];
39
98
  }
40
99
  });
41
100
  }
@@ -48,10 +107,10 @@ ${indent}}
48
107
  defaultOptions: [],
49
108
  meta: {
50
109
  type: "suggestion",
51
- docs: { description: "Async functions should have a try-catch block returning FAILED_PROMISE." },
110
+ docs: { description: "Async functions should have a try-catch block returning an error result." },
52
111
  fixable: "code",
53
112
  schema: [],
54
- messages: { missingTryCatch: "Async functions must have a try-catch block returning FAILED_PROMISE." }
113
+ messages: { missingTryCatch: "Async functions must have a try-catch block returning an error result." }
55
114
  }
56
115
  };
57
116
  //#endregion
@@ -8,9 +8,74 @@ function isAsyncFunction(node) {
8
8
  function hasTypeParameters(value) {
9
9
  return isNode(value) && Array.isArray(value.params);
10
10
  }
11
+ function isCallArgumentCallback(node) {
12
+ const parent = node.parent;
13
+ if (!parent) return false;
14
+ if (parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
15
+ return Array.isArray(parent.arguments) && parent.arguments.includes(node);
16
+ }
17
+ function isIdentifierNamed(node, name) {
18
+ return isNode(node) && node.type === "Identifier" && node.name === name;
19
+ }
20
+ function getProgram(node) {
21
+ 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;
32
+ }
33
+ function getProgramBody(node) {
34
+ if (!Array.isArray(node.body)) return [];
35
+ return node.body.filter(isNode);
36
+ }
37
+ function isResultHelperCall(node, name) {
38
+ return isNode(node) && node.type === "CallExpression" && isIdentifierNamed(node.callee, name);
39
+ }
40
+ 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;
44
+ });
45
+ }
46
+ 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;
49
+ return null;
50
+ }
51
+ function isBooleanLiteral(node, expected) {
52
+ return isNode(node) && node.type === "Literal" && node.value === expected;
53
+ }
54
+ function isNullLiteral(node) {
55
+ return isNode(node) && node.type === "Literal" && node.value === null;
56
+ }
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
+ }
11
75
  const rule = {
12
76
  create(context) {
13
77
  const sourceCode = context.getSourceCode();
78
+ const scheduledHelperImports = /* @__PURE__ */ new Set();
14
79
  function isTypeReference(node) {
15
80
  return isNode(node) && node.type === "TSTypeReference";
16
81
  }
@@ -30,8 +95,19 @@ const rule = {
30
95
  if (getTypeName(node) !== "Promise") return null;
31
96
  return getTypeArgument(node);
32
97
  }
98
+ function ensureResultHelperImportFixes(node, fixer, helperName) {
99
+ 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 [];
104
+ 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)];
107
+ }
33
108
  function checkReturnType(node) {
34
109
  if (!isAsyncFunction(node)) return;
110
+ if (isCallArgumentCallback(node)) return;
35
111
  if (!isNode(node.returnType)) return;
36
112
  const typeAnnotation = node.returnType.typeAnnotation;
37
113
  if (!isTypeReference(typeAnnotation)) return;
@@ -53,18 +129,42 @@ const rule = {
53
129
  node,
54
130
  messageId: "returnVoidPromise",
55
131
  fix(fixer) {
56
- return fixer.replaceText(node, "return VOID_PROMISE");
132
+ return [...ensureResultHelperImportFixes(node, fixer, "ok"), fixer.replaceText(node, "return ok()")];
57
133
  }
58
134
  });
59
135
  return;
60
136
  }
61
137
  if (argument.type === "Identifier" && (argument.name === "VOID_PROMISE" || argument.name === "FAILED_PROMISE")) return;
62
- if (!(argument.type === "ObjectExpression" && Array.isArray(argument.properties) && argument.properties.some((property) => isNode(property) && property.type === "Property" && isNode(property.key) && property.key.type === "Identifier" && property.key.name === "isError"))) context.report({
138
+ if (isResultHelperCall(argument, "ok") || isResultHelperCall(argument, "err")) return;
139
+ const isErrorValue = getObjectPropertyValue(argument, "isError");
140
+ const objectValue = getObjectPropertyValue(argument, "value");
141
+ if (isBooleanLiteral(isErrorValue, false) && objectValue) {
142
+ context.report({
143
+ node: argument,
144
+ messageId: "preferOkResult",
145
+ fix(fixer) {
146
+ const valueText = sourceCode.getText(objectValue);
147
+ return [...ensureResultHelperImportFixes(node, fixer, "ok"), fixer.replaceText(argument, `ok(${valueText})`)];
148
+ }
149
+ });
150
+ return;
151
+ }
152
+ if (isBooleanLiteral(isErrorValue, true) && isNullLiteral(objectValue)) {
153
+ context.report({
154
+ node: argument,
155
+ messageId: "preferErrResult",
156
+ fix(fixer) {
157
+ return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.replaceText(argument, "err()")];
158
+ }
159
+ });
160
+ return;
161
+ }
162
+ if (!hasIsErrorFlag(argument, true) && !hasIsErrorFlag(argument, false)) context.report({
63
163
  node: argument,
64
164
  messageId: "wrapReturn",
65
165
  fix(fixer) {
66
166
  const argumentText = sourceCode.getText(argument);
67
- return fixer.replaceText(argument, `{ value: ${argumentText}, isError: false }`);
167
+ return [...ensureResultHelperImportFixes(node, fixer, "ok"), fixer.replaceText(argument, `ok(${argumentText})`)];
68
168
  }
69
169
  });
70
170
  }
@@ -81,6 +181,7 @@ const rule = {
81
181
  parent = parent.parent;
82
182
  }
83
183
  if (!isAsync || !parentFunction) return;
184
+ if (isCallArgumentCallback(parentFunction)) return;
84
185
  let returnType = null;
85
186
  if (isNode(parentFunction.returnType)) {
86
187
  const typeAnnotation = parentFunction.returnType.typeAnnotation;
@@ -90,17 +191,18 @@ const rule = {
90
191
  for (const statement of blockBody) if (isNode(statement) && statement.type === "ReturnStatement") wrapReturnValue(statement, isAsync, returnType);
91
192
  if (!isNode(node.handler) || !isNode(node.handler.body)) return;
92
193
  const catchBody = Array.isArray(node.handler.body.body) ? node.handler.body.body.filter(isNode) : [];
93
- if (!catchBody.some((statement) => statement.type === "ReturnStatement" && isNode(statement.argument) && statement.argument.type === "Identifier" && statement.argument.name === "FAILED_PROMISE")) context.report({
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({
94
196
  node: node.handler,
95
197
  messageId: "returnFailedPromise",
96
198
  fix(fixer) {
97
199
  const lastStatement = catchBody.at(-1);
98
- if (lastStatement?.type === "ReturnStatement" && isNode(lastStatement.argument) && lastStatement.argument.type === "ObjectExpression") return fixer.replaceText(lastStatement, "return FAILED_PROMISE");
200
+ if (lastStatement?.type === "ReturnStatement" && isNode(lastStatement.argument) && lastStatement.argument.type === "ObjectExpression") return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.replaceText(lastStatement, "return err()")];
99
201
  const handler = node.handler;
100
202
  if (!isNode(handler)) return null;
101
203
  const bodyRange = handler.body;
102
204
  if (!isNode(bodyRange) || !Array.isArray(bodyRange.range)) return null;
103
- return fixer.insertTextBeforeRange([bodyRange.range[1] - 1, bodyRange.range[1] - 1], "return FAILED_PROMISE; ");
205
+ return [...ensureResultHelperImportFixes(node, fixer, "err"), fixer.insertTextBeforeRange([bodyRange.range[1] - 1, bodyRange.range[1] - 1], "return err(); ")];
104
206
  }
105
207
  });
106
208
  }
@@ -122,9 +224,11 @@ const rule = {
122
224
  schema: [],
123
225
  messages: {
124
226
  replaceWithMaybePromise: "Use 'MaybePromise' instead of 'Promise' as the return type in async functions.",
125
- wrapReturn: "Wrap return value with { value: value, isError: false }.",
126
- returnVoidPromise: "Return VOID_PROMISE for async functions with Promise<void> return type.",
127
- returnFailedPromise: "Return FAILED_PROMISE in catch block of async functions."
227
+ wrapReturn: "Wrap return value with ok(value).",
228
+ preferOkResult: "Use ok(value) instead of an inline success result object.",
229
+ preferErrResult: "Use err() instead of an inline error result object.",
230
+ returnVoidPromise: "Return ok() for async functions with Promise<void> return type.",
231
+ returnFailedPromise: "Return err() in the catch block of async functions."
128
232
  }
129
233
  }
130
234
  };
@@ -26,6 +26,20 @@ function cloneDefaultArray(defaultValue) {
26
26
  function isSuccess(result) {
27
27
  return !result.isError;
28
28
  }
29
+ function ok(...args) {
30
+ const [value] = args;
31
+ return {
32
+ isError: false,
33
+ value
34
+ };
35
+ }
36
+ function err(...args) {
37
+ const [value] = args;
38
+ return {
39
+ isError: true,
40
+ value: value ?? null
41
+ };
42
+ }
29
43
  function isString(value) {
30
44
  return typeof value === "string";
31
45
  }
@@ -292,4 +306,4 @@ function parseDomainName(url, defaultValue) {
292
306
  return domainName;
293
307
  }
294
308
  //#endregion
295
- export { arrayContainsCommonValue, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
309
+ export { arrayContainsCommonValue, err, fastIsArray, getKeys, hasEmptyValues, isArray, isBoolean, isDate, isEmptyArray, isEmptyLike, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSuccess, isSymbol, isUlidString, isUndefined, isUuidString, ok, parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
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.0.0",
4
+ "version": "1.1.1",
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.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "Your new best friend for simple typescript guards every project needs.",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",