@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.
@@ -0,0 +1,28 @@
1
+ import { isArray } from "./guards.js";
2
+ //#region src/collections.ts
3
+ /** Operations on collections rather than checks on them. */
4
+ /**
5
+ * Get the keys of an object.
6
+ *
7
+ * @param {unknown} object - The object to get the keys of.
8
+ * @returns {Array} Keys of object.
9
+ */
10
+ function getKeys(object) {
11
+ return Object.keys(object);
12
+ }
13
+ /**
14
+ * Compares two arrays and returns true if they have at least one common value.
15
+ *
16
+ * @param {readonly T[]} array1 - First array.
17
+ * @param {readonly T[]} array2 - Second array.
18
+ * @returns {boolean} True if the arrays have at least one common value.
19
+ */
20
+ function arrayContainsCommonValue(array1, array2) {
21
+ if (!isArray(array1) || !isArray(array2)) return false;
22
+ const valueOccurrences = new Set(array1);
23
+ return array2.some((value) => {
24
+ return valueOccurrences.has(value);
25
+ });
26
+ }
27
+ //#endregion
28
+ export { arrayContainsCommonValue, getKeys };
package/dist/empty.js ADDED
@@ -0,0 +1,53 @@
1
+ import { isArray, isBoolean, isEmptyObject, isEmptyString, isNull, isObject, isString, isUndefined } from "./guards.js";
2
+ //#region src/empty.ts
3
+ /**
4
+ * The recursive "is this effectively blank" checks. Split out because they walk
5
+ * arbitrary object graphs — far more code than the one-line guards they are
6
+ * filed next to, and needed far less often.
7
+ */
8
+ /**
9
+ * Returns true for values that behave like "empty" application input.
10
+ *
11
+ * @param {unknown} value - The value to check.
12
+ * @returns {boolean} True if the value is nullish, empty string, empty array,
13
+ * false, or a plain object whose values are all empty-like.
14
+ */
15
+ function isEmptyLike(value) {
16
+ if (isNull(value) || isUndefined(value)) return true;
17
+ if (isString(value)) return isEmptyString(value);
18
+ if (isArray(value)) return value.every((entry) => {
19
+ return isEmptyLike(entry);
20
+ });
21
+ if (isBoolean(value)) return !value;
22
+ if (isObject(value)) {
23
+ if (Object.getPrototypeOf(value) !== Object.prototype) return false;
24
+ return Object.values(value).every((entry) => {
25
+ return isEmptyLike(entry);
26
+ });
27
+ }
28
+ return false;
29
+ }
30
+ /**
31
+ * Checks if the provided value contains empty values.
32
+ *
33
+ * This function determines if the given value is either an empty string, an
34
+ * empty object, or a string representation of an empty object.
35
+ *
36
+ * @param {unknown} value - The value to check for emptiness. It can be of any
37
+ * type.
38
+ * @returns {boolean} `true` if the value is an empty string, an empty object,
39
+ * or a string representation of an empty object; otherwise, `false`.
40
+ */
41
+ function hasEmptyValues(value) {
42
+ if (isString(value)) {
43
+ try {
44
+ if (isEmptyObject(JSON.parse(value))) return true;
45
+ } catch {
46
+ return isEmptyString(value);
47
+ }
48
+ return isEmptyString(value);
49
+ }
50
+ return isEmptyObject(value);
51
+ }
52
+ //#endregion
53
+ export { hasEmptyValues, isEmptyLike };
package/dist/guards.js ADDED
@@ -0,0 +1,132 @@
1
+ //#region src/guards.ts
2
+ const EMPTY_LENGTH = 0;
3
+ function isString(value) {
4
+ return typeof value === "string";
5
+ }
6
+ /**
7
+ * Parses the input value as a boolean. Returns false if the value is no string.
8
+ *
9
+ * @param {unknown} value - The value to check.
10
+ * @returns {boolean} True if the value is a string.
11
+ */
12
+ function isEmptyString(value) {
13
+ if (!isString(value)) return false;
14
+ return value.trim() === "";
15
+ }
16
+ /**
17
+ * Returns true if the value is null.
18
+ *
19
+ * @param {unknown} value - The value to check.
20
+ * @returns {boolean} True if the value is null.
21
+ */
22
+ function isNull(value) {
23
+ return value === null;
24
+ }
25
+ /**
26
+ * Returns true if the value is undefined.
27
+ *
28
+ * @param {unknown} value - The value to check.
29
+ * @returns {boolean} True if the value is undefined.
30
+ */
31
+ function isUndefined(value) {
32
+ return typeof value === "undefined";
33
+ }
34
+ /**
35
+ * Checks whether an Optional value is currently in its missing state.
36
+ *
37
+ * @param {Optional<T>} value - The Optional value to check.
38
+ * @returns {boolean} True when the value is undefined.
39
+ */
40
+ function isOptional(value) {
41
+ return isUndefined(value);
42
+ }
43
+ /**
44
+ * Checks whether a Maybe value is currently in its missing state.
45
+ *
46
+ * @param {Maybe<T>} value - The Maybe value to check.
47
+ * @returns {boolean} True when the value is null.
48
+ */
49
+ function isMaybe(value) {
50
+ return isNull(value);
51
+ }
52
+ /**
53
+ * Checks whether a Nullable value is currently in its missing state.
54
+ *
55
+ * @param {Nullable<T>} value - The Nullable value to check.
56
+ * @returns {boolean} True when the value is null or undefined.
57
+ */
58
+ function isNullable(value) {
59
+ return isNull(value) || isUndefined(value);
60
+ }
61
+ function isArray(value) {
62
+ return Array.isArray(value);
63
+ }
64
+ function isEmptyArray(value) {
65
+ return Array.isArray(value) && value.length === EMPTY_LENGTH;
66
+ }
67
+ function fastIsArray(value) {
68
+ return Object.prototype.toString.call(value) === "[object Array]";
69
+ }
70
+ function isNumber(value) {
71
+ if (typeof value === "string" && value.trim() === "") return false;
72
+ return typeof value === "number" && !Number.isNaN(value) && Number.isFinite(value);
73
+ }
74
+ function isObject(value) {
75
+ if (typeof value !== "object" || value === null || isArray(value) || Object.prototype.toString.call(value) !== "[object Object]") return false;
76
+ return Object.getPrototypeOf(value) === Object.prototype;
77
+ }
78
+ function isBoolean(value) {
79
+ return typeof value === "boolean";
80
+ }
81
+ function isFunction(value) {
82
+ return typeof value === "function";
83
+ }
84
+ function isPromise(value) {
85
+ if (typeof value !== "object" || value === null) return false;
86
+ return typeof Reflect.get(value, "then") === "function";
87
+ }
88
+ function isError(value) {
89
+ return value instanceof Error;
90
+ }
91
+ function isDate(value) {
92
+ return value instanceof Date;
93
+ }
94
+ function isRegExp(value) {
95
+ return value instanceof RegExp;
96
+ }
97
+ function isSymbol(value) {
98
+ return typeof value === "symbol";
99
+ }
100
+ function isEmptyObject(value) {
101
+ return typeof value === "object" && !isNull(value) && !isUndefined(value) && !isEmptyArray(value) && Object.getPrototypeOf(value) === Object.prototype && Object.keys(value).length === EMPTY_LENGTH;
102
+ }
103
+ /**
104
+ * Check if a value is an instance of a class.
105
+ *
106
+ * @param {unknown} value - The value to check.
107
+ * @param {unknown} constructor - The class constructor to check against.
108
+ * @returns {boolean} True if the value is an instance of the class.
109
+ */
110
+ function isInstanceOf(value, constructor) {
111
+ return value instanceof constructor;
112
+ }
113
+ /**
114
+ * Check if a value is an integer.
115
+ *
116
+ * @param {unknown} value - The value to check.
117
+ * @returns {boolean} True if the value is an integer.
118
+ */
119
+ function isInteger(value) {
120
+ return typeof value === "number" && Number.isInteger(value);
121
+ }
122
+ /**
123
+ * Check if a value is a float.
124
+ *
125
+ * @param {unknown} value - The value to check.
126
+ * @returns {boolean} True if the value is a float.
127
+ */
128
+ function isFloat(value) {
129
+ return typeof value === "number" && !Number.isNaN(value) && !Number.isInteger(value);
130
+ }
131
+ //#endregion
132
+ export { fastIsArray, isArray, isBoolean, isDate, isEmptyArray, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSymbol, isUndefined };
package/dist/ids.js ADDED
@@ -0,0 +1,29 @@
1
+ import { isString } from "./guards.js";
2
+ //#region src/ids.ts
3
+ /**
4
+ * Identifier-format checks. Their two regex literals are the only module-level
5
+ * allocations in the package, which is the whole reason they live alone: a
6
+ * bundler that keeps anything in a module keeps those too.
7
+ */
8
+ const uuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
9
+ const ulidRegex = /^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/;
10
+ /**
11
+ * Returns true if the input is a UUID string.
12
+ *
13
+ * @param {string} input - The input to check.
14
+ * @returns {boolean} True if the input is a UUID string.
15
+ */
16
+ function isUuidString(input) {
17
+ return isString(input) && uuidRegex.test(input);
18
+ }
19
+ /**
20
+ * Returns true if the input is a ULID string.
21
+ *
22
+ * @param {string} input - The input to check.
23
+ * @returns {boolean} True if the input is a ULID string.
24
+ */
25
+ function isUlidString(input) {
26
+ return typeof input === "string" && ulidRegex.test(input);
27
+ }
28
+ //#endregion
29
+ export { isUlidString, isUuidString };
package/dist/index.js CHANGED
@@ -1,2 +1,7 @@
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";
1
+ import { fastIsArray, isArray, isBoolean, isDate, isEmptyArray, isEmptyObject, isEmptyString, isError, isFloat, isFunction, isInstanceOf, isInteger, isMaybe, isNull, isNullable, isNumber, isObject, isOptional, isPromise, isRegExp, isString, isSymbol, isUndefined } from "./guards.js";
2
+ import { arrayContainsCommonValue, getKeys } from "./collections.js";
3
+ import { hasEmptyValues, isEmptyLike } from "./empty.js";
4
+ import { isUlidString, isUuidString } from "./ids.js";
5
+ import { parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString } from "./parse.js";
6
+ import { err, isSuccess, ok } from "./result.js";
2
7
  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/dist/oxlint.js CHANGED
@@ -1,8 +1,8 @@
1
- import { rule } from "./rules/async_rule.js";
2
- import { rule as rule$1 } from "./rules/maybe_promise_rule.js";
3
- import { rule as rule$2 } from "./rules/maybe_rule.js";
4
- import { rule as rule$3 } from "./rules/nullable_rule.js";
5
- import { rule as rule$4 } from "./rules/optional_rule.js";
1
+ import { requireTryCatchAsyncRule as rule } from "./rules/async_rule.js";
2
+ import { errorSafeAsyncRule as rule$1 } from "./rules/maybe_promise_rule.js";
3
+ import { maybeRule as rule$2 } from "./rules/maybe_rule.js";
4
+ import { nullableRule as rule$3 } from "./rules/nullable_rule.js";
5
+ import { optionalRule as rule$4 } from "./rules/optional_rule.js";
6
6
  //#region oxlint/index.ts
7
7
  const plugin = {
8
8
  meta: { name: "typebuddy" },
package/dist/parse.js ADDED
@@ -0,0 +1,81 @@
1
+ import { isArray, isEmptyObject, isNull, isNumber, isString, isUndefined } from "./guards.js";
2
+ //#region src/parse.ts
3
+ /**
4
+ * Coercions from unknown input to a concrete type, each with a caller-supplied
5
+ * fallback. Separate from the guards because parsing is what you do _after_ a
6
+ * guard said no.
7
+ */
8
+ const EMPTY_LENGTH = 0;
9
+ function cloneDefaultArray(defaultValue) {
10
+ if (!defaultValue) return defaultValue;
11
+ return [...defaultValue];
12
+ }
13
+ function parseInteger(value, defaultValue) {
14
+ if (isNumber(value)) return Math.floor(value);
15
+ if (isString(value)) {
16
+ const parsed = Number(value.trim());
17
+ if (Number.isInteger(parsed)) return parsed;
18
+ }
19
+ return defaultValue;
20
+ }
21
+ function parseFloat(value, defaultValue) {
22
+ if (isNumber(value)) return value;
23
+ if (isString(value)) {
24
+ const normalizedValue = value.trim().replace(",", ".");
25
+ const parsed = Number.parseFloat(normalizedValue);
26
+ if (!Number.isNaN(parsed)) return parsed;
27
+ }
28
+ return defaultValue;
29
+ }
30
+ function parseNumber(value, defaultValue) {
31
+ if (isNumber(value)) return value;
32
+ if (isString(value)) {
33
+ const normalizedValue = value.trim().replace(",", ".");
34
+ const parsed = Number(normalizedValue);
35
+ if (Number.isFinite(parsed)) return parsed;
36
+ }
37
+ return defaultValue;
38
+ }
39
+ /**
40
+ * Parses the input value as a string. Returns an empty string if the value
41
+ * cannot be converted.
42
+ *
43
+ * @param {unknown} value - The value to check.
44
+ * @param {Optional<string>} defaultValue - Value gets returned if string could
45
+ * not be parsed.
46
+ * @returns {string} The parsed string.
47
+ */
48
+ function parseString(value, defaultValue = "") {
49
+ if (isString(value)) return value;
50
+ if (isNumber(value)) return value.toString();
51
+ if (typeof value === "boolean") return value.toString();
52
+ return defaultValue;
53
+ }
54
+ function parseArray(value, defaultValue) {
55
+ if (isArray(value)) return [...value];
56
+ if (isString(value)) return value.split(/[,|;\n\t ]+/).map((entry) => {
57
+ return entry.trim();
58
+ }).filter((entry) => {
59
+ return entry.length > EMPTY_LENGTH;
60
+ });
61
+ if (isNumber(value)) return [value];
62
+ if (isEmptyObject(value)) return [value];
63
+ if (isNull(value) || isUndefined(value)) return cloneDefaultArray(defaultValue);
64
+ return cloneDefaultArray(defaultValue);
65
+ }
66
+ function parseDomainName(url, defaultValue) {
67
+ const normalizedValue = url.trim();
68
+ if (normalizedValue === "" || normalizedValue.startsWith("/")) return defaultValue;
69
+ let urlCandidate = normalizedValue;
70
+ if (!normalizedValue.includes("://")) urlCandidate = `https://${normalizedValue}`;
71
+ try {
72
+ const { hostname } = new URL(urlCandidate);
73
+ const [domainName] = hostname.replace(/^www\d?\./i, "").split(".");
74
+ if (domainName === void 0 || domainName === "") return defaultValue;
75
+ return domainName;
76
+ } catch {
77
+ return defaultValue;
78
+ }
79
+ }
80
+ //#endregion
81
+ export { parseArray, parseDomainName, parseFloat, parseInteger, parseNumber, parseString };
package/dist/result.js ADDED
@@ -0,0 +1,38 @@
1
+ //#region src/result.ts
2
+ /**
3
+ * Checks if the provided result is a `Success` type.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * const result = await someAsyncFunction();
8
+ * if (isSuccess(result)) {
9
+ * return result.value; // TypeScript knows `value` is of type `T`
10
+ * }
11
+ * ```
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`.
16
+ * @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
+ */
20
+ function isSuccess(result) {
21
+ return !result.isError;
22
+ }
23
+ function ok(...args) {
24
+ const [value] = args;
25
+ return {
26
+ isError: false,
27
+ value
28
+ };
29
+ }
30
+ function err(...args) {
31
+ const [value] = args;
32
+ return {
33
+ isError: true,
34
+ value: value ?? null
35
+ };
36
+ }
37
+ //#endregion
38
+ export { err, isSuccess, ok };
@@ -1,3 +1,4 @@
1
+ import { throwsDeliberately } from "./deliberate_throw.js";
1
2
  //#region rules/async_rule.ts
2
3
  function isNode(value) {
3
4
  return typeof value === "object" && value !== null && "type" in value;
@@ -8,14 +9,14 @@ function getProgram(node) {
8
9
  return current?.type === "Program" ? current : null;
9
10
  }
10
11
  function isIdentifierNamed(node, name) {
11
- return isNode(node) && node.type === "Identifier" && node.name === name;
12
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
12
13
  }
13
14
  function isImportDeclaration(node) {
14
15
  return isNode(node) && node.type === "ImportDeclaration";
15
16
  }
16
17
  function getStringLiteralValue(node) {
17
18
  if (!isNode(node)) return null;
18
- if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node.value === "string") return node.value;
19
+ if ((node.type === "Literal" || node.type === "StringLiteral") && typeof node["value"] === "string") return node["value"];
19
20
  return null;
20
21
  }
21
22
  function getProgramBody(node) {
@@ -25,10 +26,10 @@ function getProgramBody(node) {
25
26
  function hasTypeBuddyHelperImport(program, helperName) {
26
27
  return getProgramBody(program).some((statement) => {
27
28
  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);
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);
32
33
  });
33
34
  });
34
35
  }
@@ -49,7 +50,7 @@ function isCallArgumentCallback(node) {
49
50
  const parent = node.parent;
50
51
  if (!parent) return false;
51
52
  if (parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
52
- return Array.isArray(parent.arguments) && parent.arguments.includes(node);
53
+ return Array.isArray(parent["arguments"]) && parent["arguments"].includes(node);
53
54
  }
54
55
  const rule = {
55
56
  create(context) {
@@ -66,7 +67,7 @@ const rule = {
66
67
  return [fixer.insertTextBeforeRange(insertRange, importText)];
67
68
  }
68
69
  function getIndentation(node) {
69
- const firstLine = sourceCode.getText(node).split("\n")[0];
70
+ const firstLine = sourceCode.getText(node).split("\n")[0] ?? "";
70
71
  const match = /^\s*/.exec(firstLine);
71
72
  return match ? match[0] : "";
72
73
  }
@@ -77,7 +78,8 @@ const rule = {
77
78
  return `{
78
79
  ${indent}try {
79
80
  ${body.map((statement) => {
80
- return `${innerIndent}${sourceCode.getText(statement).replaceAll(/^\s*/gm, "")}`;
81
+ const text = sourceCode.getText(statement);
82
+ return `${innerIndent}${text.replaceAll(/^\s*/gm, "")}`;
81
83
  }).join("\n")}
82
84
  ${indent}} catch {
83
85
  ${innerIndent}return err();
@@ -90,6 +92,7 @@ ${indent}}
90
92
  const bodyNode = node.body;
91
93
  if (!bodyNode || Array.isArray(bodyNode) || bodyNode.type !== "BlockStatement") return;
92
94
  if (hasTryCatch(Array.isArray(bodyNode.body) ? bodyNode.body : [])) return;
95
+ if (throwsDeliberately(bodyNode)) return;
93
96
  context.report({
94
97
  node,
95
98
  messageId: "missingTryCatch",
@@ -114,4 +117,4 @@ ${indent}}
114
117
  }
115
118
  };
116
119
  //#endregion
117
- export { rule };
120
+ export { rule as requireTryCatchAsyncRule };
@@ -0,0 +1,49 @@
1
+ //#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
+ /**
11
+ * Whether a function body throws on purpose.
12
+ *
13
+ * A `throw` in a function's own body is the author saying this failure is not a
14
+ * value to hand back. A missing manifest for a route the app is navigating to,
15
+ * an unreachable branch, a broken invariant — those should be loud. Turning them
16
+ * into `err()` converts a bug into a silently handled outcome, and the caller
17
+ * degrades politely instead of surfacing that something is wrong.
18
+ *
19
+ * So both async rules leave such a function alone. The rules exist to push
20
+ * *recoverable* failures into the return type, not to abolish throwing.
21
+ *
22
+ * Two boundaries matter. A throw inside a nested function belongs to that
23
+ * function, so the walk does not descend into one. A throw inside `catch` still
24
+ * counts: a rethrow is as deliberate as an original throw, and it is how code
25
+ * says "this one is not mine to handle".
26
+ *
27
+ * @param {unknown} body - The function body node to inspect.
28
+ * @returns {boolean} True when the body throws outside any nested function.
29
+ */
30
+ 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;
47
+ }
48
+ //#endregion
49
+ export { throwsDeliberately };