@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.
- package/dist/collections.js +28 -0
- package/dist/empty.js +53 -0
- package/dist/guards.js +132 -0
- package/dist/ids.js +29 -0
- package/dist/index.js +6 -1
- package/dist/parse.js +81 -0
- package/dist/result.js +38 -0
- package/dist/rules/async_rule.js +45 -67
- package/dist/rules/deliberate_throw.js +31 -0
- package/dist/rules/maybe_promise_rule.js +131 -64
- package/dist/rules/optional_rule.js +1 -1
- package/dist/rules/own_subtree.js +45 -0
- package/dist/rules/typebuddy_import.js +79 -0
- package/jsr.json +1 -1
- package/package.json +35 -6
- package/rules/async_rule.ts +118 -141
- package/rules/deliberate_throw.ts +35 -0
- package/rules/maybe_promise_rule.ts +235 -187
- package/rules/optional_rule.ts +5 -1
- package/rules/own_subtree.ts +70 -0
- package/rules/typebuddy_import.ts +134 -0
- package/src/collections.ts +36 -0
- package/src/empty.ts +76 -0
- package/src/guards.ts +341 -0
- package/src/ids.ts +34 -0
- package/src/index.ts +2 -0
- package/src/parse.ts +215 -0
- package/src/result.ts +57 -0
- package/src/type_helper.ts +10 -666
- package/src/types/index.ts +9 -1
- package/src/types/maybe_promise.ts +24 -2
- package/dist/src/type_helper.js +0 -308
|
@@ -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 {
|
|
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/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 };
|
package/dist/rules/async_rule.js
CHANGED
|
@@ -1,45 +1,6 @@
|
|
|
1
|
+
import { throwsDeliberately } from "./deliberate_throw.js";
|
|
2
|
+
import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
|
|
1
3
|
//#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
|
-
}
|
|
43
4
|
function hasTryCatch(nodes) {
|
|
44
5
|
return nodes.some((node) => {
|
|
45
6
|
return node.type === "TryStatement";
|
|
@@ -57,45 +18,62 @@ const rule = {
|
|
|
57
18
|
let scheduledErrImport = false;
|
|
58
19
|
function ensureErrImportFixes(node, fixer) {
|
|
59
20
|
if (scheduledErrImport) return [];
|
|
60
|
-
const
|
|
61
|
-
if (!
|
|
62
|
-
const insertRange = getTypeBuddyImportInsertRange(program);
|
|
63
|
-
if (!insertRange) return [];
|
|
21
|
+
const insertion = getTypeBuddyImportInsertion(node, "err");
|
|
22
|
+
if (!insertion) return [];
|
|
64
23
|
scheduledErrImport = true;
|
|
65
|
-
|
|
66
|
-
return [fixer.insertTextBeforeRange(insertRange, importText)];
|
|
24
|
+
return [fixer.insertTextBeforeRange(insertion.range, insertion.text)];
|
|
67
25
|
}
|
|
68
|
-
function
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
return
|
|
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")];
|
|
72
30
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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}")];
|
|
87
50
|
}
|
|
88
51
|
function checkFunction(node) {
|
|
89
52
|
if (node.async !== true) return;
|
|
90
53
|
if (isCallArgumentCallback(node)) return;
|
|
91
54
|
const bodyNode = node.body;
|
|
92
|
-
if (!bodyNode || Array.isArray(bodyNode)
|
|
55
|
+
if (!bodyNode || Array.isArray(bodyNode)) return;
|
|
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
|
+
}
|
|
93
69
|
if (hasTryCatch(Array.isArray(bodyNode.body) ? bodyNode.body : [])) return;
|
|
94
70
|
context.report({
|
|
95
71
|
node,
|
|
96
72
|
messageId: "missingTryCatch",
|
|
97
73
|
fix(fixer) {
|
|
98
|
-
|
|
74
|
+
const wrapFixes = wrapBlockFixes(bodyNode, fixer);
|
|
75
|
+
if (!wrapFixes) return null;
|
|
76
|
+
return [...ensureErrImportFixes(node, fixer), ...wrapFixes];
|
|
99
77
|
}
|
|
100
78
|
});
|
|
101
79
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { walkOwnSubtree } from "./own_subtree.js";
|
|
2
|
+
//#region rules/deliberate_throw.ts
|
|
3
|
+
/**
|
|
4
|
+
* Whether a function body throws on purpose.
|
|
5
|
+
*
|
|
6
|
+
* A `throw` in a function's own body is the author saying this failure is not a
|
|
7
|
+
* value to hand back. A missing manifest for a route the app is navigating to,
|
|
8
|
+
* an unreachable branch, a broken invariant — those should be loud. Turning them
|
|
9
|
+
* into `err()` converts a bug into a silently handled outcome, and the caller
|
|
10
|
+
* degrades politely instead of surfacing that something is wrong.
|
|
11
|
+
*
|
|
12
|
+
* So both async rules leave such a function alone. The rules exist to push
|
|
13
|
+
* *recoverable* failures into the return type, not to abolish throwing.
|
|
14
|
+
*
|
|
15
|
+
* Two boundaries matter. A throw inside a nested function belongs to that
|
|
16
|
+
* function, so the walk does not descend into one. A throw inside `catch` still
|
|
17
|
+
* counts: a rethrow is as deliberate as an original throw, and it is how code
|
|
18
|
+
* says "this one is not mine to handle".
|
|
19
|
+
*
|
|
20
|
+
* @param {unknown} body - The function body node to inspect.
|
|
21
|
+
* @returns {boolean} True when the body throws outside any nested function.
|
|
22
|
+
*/
|
|
23
|
+
function throwsDeliberately(body) {
|
|
24
|
+
let found = false;
|
|
25
|
+
walkOwnSubtree(body, (node) => {
|
|
26
|
+
if (node.type === "ThrowStatement") found = true;
|
|
27
|
+
});
|
|
28
|
+
return found;
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { throwsDeliberately };
|