@murky-web/typebuddy 3.0.0 → 3.1.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/README.md +23 -10
- package/dist/oxlint.js +2 -0
- package/dist/rules/async_rule.js +18 -1
- package/dist/rules/maybe_promise_rule.js +25 -7
- package/dist/rules/maybe_rule.js +5 -2
- package/dist/rules/nullable_rule.js +5 -2
- package/dist/rules/optional_rule.js +5 -2
- package/dist/rules/useless_undefined_rule.js +512 -0
- package/globals.d.ts +7 -7
- package/jsr.json +24 -24
- package/oxlint/index.ts +8 -4
- package/package.json +3 -3
- package/rules/async_rule.ts +47 -20
- package/rules/maybe_promise_rule.ts +60 -40
- package/rules/maybe_rule.ts +17 -13
- package/rules/nullable_rule.ts +16 -16
- package/rules/optional_rule.ts +15 -15
- package/rules/own_subtree.ts +2 -2
- package/rules/test_file.ts +4 -4
- package/rules/typebuddy_import.ts +9 -9
- package/rules/use_server.ts +3 -3
- package/rules/useless_undefined_rule.ts +982 -0
- package/src/collections.ts +1 -1
- package/src/empty.ts +1 -1
- package/src/guards.ts +5 -5
- package/src/parse.ts +4 -4
- package/src/public_api.ts +1 -1
- package/src/result.ts +3 -5
- package/src/types/globals.ts +1 -1
- package/src/types/index.ts +2 -2
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
// rules/useless_undefined_rule.ts
|
|
2
|
+
const FUNCTION_TYPES = /* @__PURE__ */ new Set([
|
|
3
|
+
"ArrowFunctionExpression",
|
|
4
|
+
"FunctionDeclaration",
|
|
5
|
+
"FunctionExpression"
|
|
6
|
+
]);
|
|
7
|
+
const IGNORED_CALLEES = /* @__PURE__ */ new Set([
|
|
8
|
+
"add",
|
|
9
|
+
"createContext",
|
|
10
|
+
"equal",
|
|
11
|
+
"has",
|
|
12
|
+
"include",
|
|
13
|
+
"includes",
|
|
14
|
+
"is",
|
|
15
|
+
"not",
|
|
16
|
+
"notEqual",
|
|
17
|
+
"notPropertyVal",
|
|
18
|
+
"notSame",
|
|
19
|
+
"notStrictEqual",
|
|
20
|
+
"property",
|
|
21
|
+
"propertyVal",
|
|
22
|
+
"push",
|
|
23
|
+
"ref",
|
|
24
|
+
"same",
|
|
25
|
+
"set",
|
|
26
|
+
"strictEqual",
|
|
27
|
+
"strictNotSame",
|
|
28
|
+
"strictSame",
|
|
29
|
+
"toBe",
|
|
30
|
+
"toContain",
|
|
31
|
+
"toContainEqual",
|
|
32
|
+
"toEqual",
|
|
33
|
+
"toHaveBeenCalledWith",
|
|
34
|
+
"unshift",
|
|
35
|
+
"useRef"
|
|
36
|
+
]);
|
|
37
|
+
const TS_WRAPPERS = /* @__PURE__ */ new Set([
|
|
38
|
+
"TSAsExpression",
|
|
39
|
+
"TSInstantiationExpression",
|
|
40
|
+
"TSNonNullExpression",
|
|
41
|
+
"TSSatisfiesExpression",
|
|
42
|
+
"TSTypeAssertion"
|
|
43
|
+
]);
|
|
44
|
+
const RELATIONAL = /* @__PURE__ */ new Set([
|
|
45
|
+
"<",
|
|
46
|
+
"<=",
|
|
47
|
+
">",
|
|
48
|
+
">="
|
|
49
|
+
]);
|
|
50
|
+
const FLIPPED = {
|
|
51
|
+
"<": ">",
|
|
52
|
+
"<=": ">=",
|
|
53
|
+
">": "<",
|
|
54
|
+
">=": "<="
|
|
55
|
+
};
|
|
56
|
+
const UNSAFE_IN_ACCESS = /* @__PURE__ */ new Set([
|
|
57
|
+
"AssignmentExpression",
|
|
58
|
+
"AwaitExpression",
|
|
59
|
+
"CallExpression",
|
|
60
|
+
"ChainExpression",
|
|
61
|
+
"ClassExpression",
|
|
62
|
+
"ImportExpression",
|
|
63
|
+
"JSXElement",
|
|
64
|
+
"JSXFragment",
|
|
65
|
+
"MemberExpression",
|
|
66
|
+
"NewExpression",
|
|
67
|
+
"SpreadElement",
|
|
68
|
+
"TaggedTemplateExpression",
|
|
69
|
+
"UpdateExpression",
|
|
70
|
+
"YieldExpression"
|
|
71
|
+
]);
|
|
72
|
+
const STATEMENT_START_PARENTS = /* @__PURE__ */ new Set([
|
|
73
|
+
"AssignmentExpression",
|
|
74
|
+
"AwaitExpression",
|
|
75
|
+
"BinaryExpression",
|
|
76
|
+
"CallExpression",
|
|
77
|
+
"ChainExpression",
|
|
78
|
+
"ConditionalExpression",
|
|
79
|
+
"LogicalExpression",
|
|
80
|
+
"MemberExpression",
|
|
81
|
+
"SequenceExpression",
|
|
82
|
+
"TaggedTemplateExpression",
|
|
83
|
+
...TS_WRAPPERS
|
|
84
|
+
]);
|
|
85
|
+
const UNBRACED_BODY_PARENTS = /* @__PURE__ */ new Set([
|
|
86
|
+
"DoWhileStatement",
|
|
87
|
+
"ForInStatement",
|
|
88
|
+
"ForOfStatement",
|
|
89
|
+
"ForStatement",
|
|
90
|
+
"IfStatement",
|
|
91
|
+
"LabeledStatement",
|
|
92
|
+
"WhileStatement",
|
|
93
|
+
"WithStatement"
|
|
94
|
+
]);
|
|
95
|
+
function isNode(value) {
|
|
96
|
+
return typeof value === "object" && value !== null && "type" in value;
|
|
97
|
+
}
|
|
98
|
+
function children(node) {
|
|
99
|
+
const result = [];
|
|
100
|
+
for (const [key, value] of Object.entries(node)) {
|
|
101
|
+
if (key === "parent") continue;
|
|
102
|
+
if (Array.isArray(value)) result.push(...value.filter(isNode));
|
|
103
|
+
else if (isNode(value)) result.push(value);
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
function containsChain(node) {
|
|
108
|
+
return node.type === "ChainExpression" || children(node).some(containsChain);
|
|
109
|
+
}
|
|
110
|
+
function isSafeAccessPart(node) {
|
|
111
|
+
if (UNSAFE_IN_ACCESS.has(node.type)) return false;
|
|
112
|
+
if (node.type === "UnaryExpression" && node.operator === "delete") return false;
|
|
113
|
+
if (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return !containsChain(node);
|
|
114
|
+
return children(node).every(isSafeAccessPart);
|
|
115
|
+
}
|
|
116
|
+
function inner(node) {
|
|
117
|
+
let current = node;
|
|
118
|
+
while (TS_WRAPPERS.has(current.type) && current.expression) current = current.expression;
|
|
119
|
+
return current;
|
|
120
|
+
}
|
|
121
|
+
function staticNumber(node) {
|
|
122
|
+
const current = inner(node);
|
|
123
|
+
if (current.type === "Literal" && typeof current.value === "number") return current.value;
|
|
124
|
+
if (current.type === "UnaryExpression" && current.argument) {
|
|
125
|
+
const value = staticNumber(current.argument);
|
|
126
|
+
if (value === void 0) return void 0;
|
|
127
|
+
if (current.operator === "+") return value;
|
|
128
|
+
if (current.operator === "-") return -value;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function isNumberLiteral(node) {
|
|
132
|
+
return node.type === "Literal" && typeof node.value === "number";
|
|
133
|
+
}
|
|
134
|
+
function isBigIntLiteral(node) {
|
|
135
|
+
return node.type === "Literal" && typeof node.bigint === "string";
|
|
136
|
+
}
|
|
137
|
+
function singleQuasi(node) {
|
|
138
|
+
if (node.expressions?.length !== 0 || node.quasis?.length !== 1) return;
|
|
139
|
+
const [quasi] = node.quasis;
|
|
140
|
+
const value = quasi?.value;
|
|
141
|
+
if (typeof value === "object" && value !== null && "cooked" in value) return String(value.cooked);
|
|
142
|
+
}
|
|
143
|
+
function isSameSimpleExpression(left, right) {
|
|
144
|
+
if (left.type === "Identifier" && right.type === "Identifier") return left.name === right.name;
|
|
145
|
+
if (left.type === "ThisExpression" || left.type === "Super") return left.type === right.type;
|
|
146
|
+
if (left.type === "TemplateLiteral" || right.type === "TemplateLiteral") {
|
|
147
|
+
const leftText = left.type === "TemplateLiteral" ? singleQuasi(left) : left.value;
|
|
148
|
+
const rightText = right.type === "TemplateLiteral" ? singleQuasi(right) : right.value;
|
|
149
|
+
return typeof leftText === "string" && leftText === rightText;
|
|
150
|
+
}
|
|
151
|
+
if (left.type !== "Literal" || right.type !== "Literal") return false;
|
|
152
|
+
if (left.regex || right.regex) return left.regex?.pattern === right.regex?.pattern && left.regex?.flags === right.regex?.flags;
|
|
153
|
+
if (isNumberLiteral(left) || isNumberLiteral(right)) return left.raw === right.raw;
|
|
154
|
+
return left.value === right.value;
|
|
155
|
+
}
|
|
156
|
+
function isSameIndexReference(leftNode, rightNode) {
|
|
157
|
+
const left = inner(leftNode);
|
|
158
|
+
const right = inner(rightNode);
|
|
159
|
+
if (isNumberLiteral(left) && isNumberLiteral(right)) return left.value === right.value;
|
|
160
|
+
if (isBigIntLiteral(left) && isBigIntLiteral(right)) return BigInt(left.bigint ?? "") === BigInt(right.bigint ?? "");
|
|
161
|
+
return (left.type === "Literal" || left.type === "Identifier" || left.type === "ThisExpression" || left.type === "Super" || left.type === "TemplateLiteral" && left.expressions?.length === 0) && isSameSimpleExpression(left, right);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Whether `test` makes `access` an in-bounds read (`true`) or an out-of-bounds
|
|
165
|
+
* one (`false`) when it passes; `undefined` when it says nothing about that.
|
|
166
|
+
*/
|
|
167
|
+
function boundsTestValidity(testNode, access) {
|
|
168
|
+
const test = inner(testNode);
|
|
169
|
+
if (test.type !== "BinaryExpression" || !test.left || !test.right || !test.operator || !RELATIONAL.has(test.operator) || !access.property || !access.object) return;
|
|
170
|
+
let index = inner(access.property);
|
|
171
|
+
let offset = 0;
|
|
172
|
+
if (index.type === "BinaryExpression" && index.operator === "-" && index.left && index.right) {
|
|
173
|
+
const subtracted = staticNumber(index.right);
|
|
174
|
+
if (subtracted !== void 0 && Number.isSafeInteger(subtracted) && subtracted > 0) {
|
|
175
|
+
index = inner(index.left);
|
|
176
|
+
offset = subtracted;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
let operator = test.operator;
|
|
180
|
+
let boundary;
|
|
181
|
+
if (isSameIndexReference(test.left, index)) boundary = inner(test.right);
|
|
182
|
+
else if (isSameIndexReference(test.right, index)) {
|
|
183
|
+
operator = FLIPPED[operator] ?? operator;
|
|
184
|
+
boundary = inner(test.left);
|
|
185
|
+
} else return;
|
|
186
|
+
const bound = staticNumber(boundary);
|
|
187
|
+
if (bound !== void 0 && Number.isSafeInteger(bound)) {
|
|
188
|
+
if (operator === ">=" && bound === offset) return true;
|
|
189
|
+
if (operator === ">" && bound === offset - 1) return true;
|
|
190
|
+
if (operator === "<" && bound === offset) return false;
|
|
191
|
+
if (operator === "<=" && bound === offset - 1) return false;
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (offset !== 0) return void 0;
|
|
195
|
+
let length = boundary;
|
|
196
|
+
let minusOne = false;
|
|
197
|
+
if (boundary.type === "BinaryExpression" && boundary.operator === "-" && boundary.left && boundary.right && staticNumber(boundary.right) === 1) {
|
|
198
|
+
length = inner(boundary.left);
|
|
199
|
+
minusOne = true;
|
|
200
|
+
}
|
|
201
|
+
if (length.type !== "MemberExpression" || length.computed === true || length.optional === true || length.property?.name !== "length" || !length.object || !isSameIndexReference(length.object, access.object)) return;
|
|
202
|
+
if (operator === "<" && !minusOne || operator === "<=" && minusOne) return true;
|
|
203
|
+
if (operator === ">=" && !minusOne || operator === ">" && minusOne) return false;
|
|
204
|
+
}
|
|
205
|
+
/** `Optional<…>`, or a union with `undefined` (or an `Optional`) in it. */
|
|
206
|
+
function admitsUndefined(type) {
|
|
207
|
+
if (!type) return false;
|
|
208
|
+
if (type.type === "TSTypeReference") return type.typeName?.type === "Identifier" && type.typeName.name === "Optional";
|
|
209
|
+
if (type.type === "TSUnionType") return (type.types ?? []).some((member) => member.type === "TSUndefinedKeyword" || admitsUndefined(member));
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
function hasNonVoidReturnType(node) {
|
|
213
|
+
let current = node.parent;
|
|
214
|
+
while (current && current.type !== "Program") {
|
|
215
|
+
if (FUNCTION_TYPES.has(current.type)) {
|
|
216
|
+
const type = current.returnType?.typeAnnotation?.type;
|
|
217
|
+
return type !== void 0 && type !== "TSVoidKeyword" && type !== "TSUndefinedKeyword";
|
|
218
|
+
}
|
|
219
|
+
current = current.parent;
|
|
220
|
+
}
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
/** A default inside a destructuring assignment target, not a binding. */
|
|
224
|
+
function isInAssignmentTarget(pattern) {
|
|
225
|
+
let current = pattern;
|
|
226
|
+
for (;;) {
|
|
227
|
+
const { parent } = current;
|
|
228
|
+
if (parent.type === "ArrayPattern" || parent.type === "ObjectPattern" || parent.type === "RestElement" || parent.type === "AssignmentPattern" && parent.left === current || parent.type === "Property" && parent.parent.type === "ObjectPattern") {
|
|
229
|
+
current = parent;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
return (parent.type === "AssignmentExpression" || parent.type === "ForInStatement" || parent.type === "ForOfStatement") && parent.left === current;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function isOptionalParameter(parameter) {
|
|
236
|
+
return (parameter.type === "TSParameterProperty" && parameter.parameter ? parameter.parameter : parameter).optional === true;
|
|
237
|
+
}
|
|
238
|
+
function hasDefault(parameter) {
|
|
239
|
+
return (parameter.type === "TSParameterProperty" && parameter.parameter ? parameter.parameter : parameter).type === "AssignmentPattern";
|
|
240
|
+
}
|
|
241
|
+
const IDENTIFIER_START = /[\p{ID_Start}$_]/u;
|
|
242
|
+
const IDENTIFIER_PART = /[\p{ID_Continue}$]/u;
|
|
243
|
+
const rule = {
|
|
244
|
+
create(context) {
|
|
245
|
+
const sourceCode = context.sourceCode;
|
|
246
|
+
const text = sourceCode.text;
|
|
247
|
+
const options = context.options[0] ?? {};
|
|
248
|
+
const checkArguments = options.checkArguments ?? true;
|
|
249
|
+
const checkArrowFunctionBody = options.checkArrowFunctionBody ?? true;
|
|
250
|
+
const isTypeScript = /\.[cm]?tsx?$/u.test(context.filename);
|
|
251
|
+
function isGlobalUndefined(node) {
|
|
252
|
+
if (node?.type !== "Identifier" || node.name !== "undefined") return false;
|
|
253
|
+
for (let scope = sourceCode.getScope(node); scope; scope = scope.upper) {
|
|
254
|
+
const reference = scope.references.find((ref) => ref.identifier === node);
|
|
255
|
+
if (reference) return reference.resolved === null || reference.resolved.defs.length === 0;
|
|
256
|
+
}
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
function hasComments([start, end]) {
|
|
260
|
+
return sourceCode.getAllComments().some((comment) => comment.range[0] >= start && comment.range[0] < end);
|
|
261
|
+
}
|
|
262
|
+
/** `node`'s range including the parentheses around it. */
|
|
263
|
+
function parenthesized(node) {
|
|
264
|
+
let range = node.range;
|
|
265
|
+
for (;;) {
|
|
266
|
+
const before = sourceCode.getTokenBefore({ range });
|
|
267
|
+
const after = sourceCode.getTokenAfter({ range });
|
|
268
|
+
if (before?.value !== "(" || after?.value !== ")") return range;
|
|
269
|
+
range = [before.range[0], after.range[1]];
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function removeAfter(start, end) {
|
|
273
|
+
return (fixer) => hasComments([start, end]) ? null : fixer.removeRange([start, end]);
|
|
274
|
+
}
|
|
275
|
+
function couldBeAsiHazard(node) {
|
|
276
|
+
let statement;
|
|
277
|
+
for (let current = node.parent;; current = current.parent) {
|
|
278
|
+
if (current.type === "ExpressionStatement") {
|
|
279
|
+
if (UNBRACED_BODY_PARENTS.has(current.parent.type)) return false;
|
|
280
|
+
statement = current;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
if (!STATEMENT_START_PARENTS.has(current.type)) return false;
|
|
284
|
+
}
|
|
285
|
+
if (node.range[0] !== statement.range[0] || statement.range[0] === 0) return false;
|
|
286
|
+
const last = sourceCode.getTokenBefore(statement)?.value.at(-1);
|
|
287
|
+
return last !== void 0 && /[\p{L}\p{N}_$)\]}"'`+\-/.]/u.test(last);
|
|
288
|
+
}
|
|
289
|
+
function isReferenceContext(node) {
|
|
290
|
+
let expression = node;
|
|
291
|
+
for (let parent = node.parent;; parent = parent.parent) {
|
|
292
|
+
if (TS_WRAPPERS.has(parent.type)) {
|
|
293
|
+
expression = parent;
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (parent.type === "CallExpression") return parent.callee === expression;
|
|
297
|
+
if (parent.type === "TaggedTemplateExpression") return parent.tag === expression;
|
|
298
|
+
return parent.type === "UnaryExpression" && parent.operator === "delete";
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function reportParameter(node, pattern, item, fn) {
|
|
302
|
+
const params = fn.params ?? [];
|
|
303
|
+
const position = params.indexOf(item);
|
|
304
|
+
if (params.slice(0, position).some(isOptionalParameter)) return;
|
|
305
|
+
const left = pattern.left;
|
|
306
|
+
if (!left) return;
|
|
307
|
+
const annotation = left.typeAnnotation;
|
|
308
|
+
const canBeOptional = params.slice(position + 1).filter((parameter) => parameter.type !== "RestElement").every((parameter) => isOptionalParameter(parameter) || hasDefault(parameter));
|
|
309
|
+
const isIdentifier = left.type === "Identifier";
|
|
310
|
+
const name = isIdentifier ? left.name ?? "" : sourceCode.getText(left);
|
|
311
|
+
const typeText = annotation?.typeAnnotation ? sourceCode.getText(annotation.typeAnnotation) : void 0;
|
|
312
|
+
const descriptor = {
|
|
313
|
+
node,
|
|
314
|
+
messageId: "parameterUndefined",
|
|
315
|
+
data: {
|
|
316
|
+
name,
|
|
317
|
+
fix: isTypeScript && isIdentifier && !left.optional ? canBeOptional ? `${name}?: ${typeText ?? "T"}` : `${name}: ${typeText ?? "Optional<T>"}` : sourceCode.getText(left)
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
if (isTypeScript && (!isIdentifier || !annotation || item !== pattern)) {
|
|
321
|
+
context.report(descriptor);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const start = left.range[1];
|
|
325
|
+
const end = parenthesized(node)[1];
|
|
326
|
+
context.report({
|
|
327
|
+
...descriptor,
|
|
328
|
+
fix(fixer) {
|
|
329
|
+
if (hasComments([start, end])) return null;
|
|
330
|
+
const removal = fixer.removeRange([start, end]);
|
|
331
|
+
if (!isTypeScript || left.optional || !canBeOptional || !annotation) return removal;
|
|
332
|
+
const nameEnd = sourceCode.getTokenBefore(annotation)?.range[1];
|
|
333
|
+
if (nameEnd === void 0) return removal;
|
|
334
|
+
return [removal, fixer.insertTextAfterRange([nameEnd, nameEnd], "?")];
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
function onUndefined(node) {
|
|
339
|
+
const { parent } = node;
|
|
340
|
+
const outer = parenthesized(node);
|
|
341
|
+
switch (parent.type) {
|
|
342
|
+
case "ReturnStatement": {
|
|
343
|
+
if (hasNonVoidReturnType(parent)) return;
|
|
344
|
+
const before = sourceCode.getAllComments().filter((comment) => comment.range[0] >= parent.range[0] && comment.range[0] < outer[0]).at(-1);
|
|
345
|
+
const start = before ? before.range[1] : parent.range[0] + 6;
|
|
346
|
+
context.report({
|
|
347
|
+
node,
|
|
348
|
+
messageId: "returnUndefined",
|
|
349
|
+
fix: removeAfter(start, outer[1])
|
|
350
|
+
});
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
case "YieldExpression":
|
|
354
|
+
if (parent.delegate === true) return;
|
|
355
|
+
context.report({
|
|
356
|
+
node,
|
|
357
|
+
messageId: "yieldUndefined",
|
|
358
|
+
fix: (fixer) => hasComments(parent.range) ? null : fixer.replaceTextRange(parent.range, "yield")
|
|
359
|
+
});
|
|
360
|
+
return;
|
|
361
|
+
case "ArrowFunctionExpression":
|
|
362
|
+
if (parent.body !== node || !checkArrowFunctionBody || parent.returnType) return;
|
|
363
|
+
context.report({
|
|
364
|
+
node,
|
|
365
|
+
messageId: "arrowUndefined",
|
|
366
|
+
fix: (fixer) => hasComments(outer) ? null : fixer.replaceTextRange(outer, "{}")
|
|
367
|
+
});
|
|
368
|
+
return;
|
|
369
|
+
case "VariableDeclarator": {
|
|
370
|
+
const id = parent.id;
|
|
371
|
+
if (parent.init !== node || parent.parent.kind !== "let" || id?.type !== "Identifier" || admitsUndefined(id.typeAnnotation?.typeAnnotation)) return;
|
|
372
|
+
context.report({
|
|
373
|
+
node,
|
|
374
|
+
messageId: "letUndefined",
|
|
375
|
+
data: {
|
|
376
|
+
declarator: sourceCode.getText(parent),
|
|
377
|
+
name: id.name ?? ""
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
case "AssignmentPattern": {
|
|
383
|
+
if (parent.right !== node) return;
|
|
384
|
+
const owner = parent.parent;
|
|
385
|
+
if (FUNCTION_TYPES.has(owner.type)) {
|
|
386
|
+
reportParameter(node, parent, parent, owner);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (owner.type === "TSParameterProperty") {
|
|
390
|
+
reportParameter(node, parent, owner, owner.parent);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (isInAssignmentTarget(parent) || !parent.left) return;
|
|
394
|
+
const descriptor = {
|
|
395
|
+
node,
|
|
396
|
+
messageId: "defaultUndefined",
|
|
397
|
+
data: { name: sourceCode.getText(parent.left) }
|
|
398
|
+
};
|
|
399
|
+
context.report(isTypeScript ? descriptor : {
|
|
400
|
+
...descriptor,
|
|
401
|
+
fix: removeAfter(parent.left.range[1], outer[1])
|
|
402
|
+
});
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function onCall(node) {
|
|
408
|
+
const args = node.arguments ?? [];
|
|
409
|
+
const callee = node.callee;
|
|
410
|
+
if (!callee || !isTrailingUndefined(node, args.at(-1))) return;
|
|
411
|
+
const calleeName = callee.type === "Identifier" ? callee.name : callee.type === "MemberExpression" && callee.computed !== true && callee.property?.type === "Identifier" ? callee.property.name : void 0;
|
|
412
|
+
if (calleeName !== void 0 && (IGNORED_CALLEES.has(calleeName) || calleeName.startsWith("set"))) return;
|
|
413
|
+
if (node.optional !== true && callee.type === "MemberExpression" && staticPropertyName(callee) === "bind" && args.length !== 1) return;
|
|
414
|
+
let first = args.length - 1;
|
|
415
|
+
while (first > 0 && isTrailingUndefined(node, args[first - 1])) first -= 1;
|
|
416
|
+
const firstUndefined = args[first];
|
|
417
|
+
if (!firstUndefined) return;
|
|
418
|
+
context.report({
|
|
419
|
+
node: firstUndefined,
|
|
420
|
+
messageId: "argumentUndefined",
|
|
421
|
+
data: { callee: sourceCode.getText(callee) }
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
function isTrailingUndefined(call, argument) {
|
|
425
|
+
if (!isGlobalUndefined(argument)) return false;
|
|
426
|
+
const after = sourceCode.getTokenAfter(argument);
|
|
427
|
+
const last = sourceCode.getLastToken(call);
|
|
428
|
+
return !(after?.value === ")" && after.range[0] !== last?.range[0]);
|
|
429
|
+
}
|
|
430
|
+
function staticPropertyName(member) {
|
|
431
|
+
const property = member.property;
|
|
432
|
+
if (!property) return void 0;
|
|
433
|
+
if (member.computed !== true) return property.name;
|
|
434
|
+
if (property.type === "Literal" && typeof property.value === "string") return property.value;
|
|
435
|
+
if (property.type === "TemplateLiteral") return singleQuasi(property);
|
|
436
|
+
}
|
|
437
|
+
function onConditional(node) {
|
|
438
|
+
const { consequent, alternate, test } = node;
|
|
439
|
+
if (!consequent || !alternate || !test) return;
|
|
440
|
+
const consequentUndefined = isGlobalUndefined(consequent);
|
|
441
|
+
if (consequentUndefined === isGlobalUndefined(alternate)) return;
|
|
442
|
+
const [undefinedNode, branch] = consequentUndefined ? [consequent, alternate] : [alternate, consequent];
|
|
443
|
+
const access = inner(branch);
|
|
444
|
+
if (access.type !== "MemberExpression" || access.computed !== true || access.optional === true || !access.object || !access.property || boundsTestValidity(test, access) !== !consequentUndefined || !isSafeAccessPart(access.object) || !isSafeAccessPart(access.property)) return;
|
|
445
|
+
const branchRange = parenthesized(branch);
|
|
446
|
+
const accessText = text.slice(branchRange[0], branchRange[1]);
|
|
447
|
+
const descriptor = {
|
|
448
|
+
node: undefinedNode,
|
|
449
|
+
messageId: "guardedIndexedAccess",
|
|
450
|
+
data: { access: accessText }
|
|
451
|
+
};
|
|
452
|
+
if (hasComments(node.range) || isReferenceContext(node)) {
|
|
453
|
+
context.report(descriptor);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
let replacement = accessText;
|
|
457
|
+
const objectType = inner(access.object).type;
|
|
458
|
+
if ((replacement.startsWith("<") || objectType === "ObjectExpression" || objectType === "FunctionExpression") && !replacement.startsWith("(")) replacement = `(${replacement})`;
|
|
459
|
+
if (/^[[(/+\-`]/u.test(replacement) && couldBeAsiHazard(node)) replacement = `;${replacement}`;
|
|
460
|
+
const [start, end] = node.range;
|
|
461
|
+
if (start > 0 && IDENTIFIER_PART.test(text[start - 1] ?? "") && IDENTIFIER_PART.test(replacement[0] ?? "")) replacement = ` ${replacement}`;
|
|
462
|
+
if (end < text.length && IDENTIFIER_START.test(text[end] ?? "") && !/\s$/u.test(replacement)) replacement = `${replacement} `;
|
|
463
|
+
context.report({
|
|
464
|
+
...descriptor,
|
|
465
|
+
suggest: [{
|
|
466
|
+
messageId: "useIndexedAccess",
|
|
467
|
+
data: { access: accessText },
|
|
468
|
+
fix: (fixer) => fixer.replaceTextRange(node.range, replacement)
|
|
469
|
+
}]
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
return {
|
|
473
|
+
Identifier(node) {
|
|
474
|
+
if (isGlobalUndefined(node)) onUndefined(node);
|
|
475
|
+
},
|
|
476
|
+
CallExpression(node) {
|
|
477
|
+
if (checkArguments) onCall(node);
|
|
478
|
+
},
|
|
479
|
+
ConditionalExpression: onConditional
|
|
480
|
+
};
|
|
481
|
+
},
|
|
482
|
+
meta: {
|
|
483
|
+
type: "suggestion",
|
|
484
|
+
docs: { description: "Disallow useless `undefined`, except as the start value of an `Optional<T>` `let`" },
|
|
485
|
+
fixable: "code",
|
|
486
|
+
hasSuggestions: true,
|
|
487
|
+
defaultOptions: [{
|
|
488
|
+
checkArguments: true,
|
|
489
|
+
checkArrowFunctionBody: true
|
|
490
|
+
}],
|
|
491
|
+
schema: [{
|
|
492
|
+
type: "object",
|
|
493
|
+
additionalProperties: false,
|
|
494
|
+
properties: {
|
|
495
|
+
checkArguments: { type: "boolean" },
|
|
496
|
+
checkArrowFunctionBody: { type: "boolean" }
|
|
497
|
+
}
|
|
498
|
+
}],
|
|
499
|
+
messages: {
|
|
500
|
+
letUndefined: "`let {{declarator}}` starts `{{name}}` at `undefined`, but no `Optional<…>` type says `{{name}}` may hold it; without an annotation TypeScript types `{{name}}` from later assignments. Fix: annotate it, `let {{name}}: Optional<T> = undefined;` (`undefined` is the start value of an `Optional<T>`; a `Maybe<T>` starts at `null`: `let {{name}}: Maybe<T> = null;`), or give `{{name}}` its real default. Do not: drop the initializer (`let {{name}};`), `eslint/init-declarations` reports a `let` without one.",
|
|
501
|
+
returnUndefined: "`return undefined` spells out what a bare `return` already returns. Fix: `return;`, or annotate the function's return type as `Optional<T>` when `undefined` is one of its results (then the rule keeps the `undefined`).",
|
|
502
|
+
yieldUndefined: "`yield undefined` spells out what a bare `yield` already yields. Fix: `yield;`.",
|
|
503
|
+
arrowUndefined: "The arrow body `undefined` spells out what an empty body already returns. Fix: `=> {}`, or annotate the return type (`(): Optional<T> => undefined`) when `undefined` is the arrow's result.",
|
|
504
|
+
argumentUndefined: "The trailing `undefined` passed to `{{callee}}` is what an omitted argument already is. Fix: drop the trailing `undefined` arguments from the `{{callee}}(…)` call, unless `{{callee}}` reads `arguments.length` or a rest parameter (then keep them and disable the line).",
|
|
505
|
+
defaultUndefined: "The default `{{name}} = undefined` spells out what a missing property or element already is. Fix: `{{name}}`.",
|
|
506
|
+
parameterUndefined: "The default `= undefined` on `{{name}}` spells out what an omitted argument already is. Fix: `{{fix}}`.",
|
|
507
|
+
guardedIndexedAccess: "`{{access}}` is already `undefined` out of bounds, so this bounds check and its `undefined` branch repeat it. Fix: `{{access}}` on its own (the editor suggestion applies it).",
|
|
508
|
+
useIndexedAccess: "Use `{{access}}` directly."
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
export { rule as uselessUndefinedRule };
|
package/globals.d.ts
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
JsonifiedValue as JsonifiedValueImport,
|
|
3
|
-
Stringified as StringifiedImport
|
|
3
|
+
Stringified as StringifiedImport
|
|
4
4
|
} from "./src/types/json.js";
|
|
5
5
|
import type {
|
|
6
6
|
Maybe as MaybeImport,
|
|
7
|
-
ResolveMaybe as ResolveMaybeImport
|
|
7
|
+
ResolveMaybe as ResolveMaybeImport
|
|
8
8
|
} from "./src/types/maybe.js";
|
|
9
9
|
import type {
|
|
10
10
|
Failed as FailedImport,
|
|
11
11
|
MaybePromise as MaybePromiseImport,
|
|
12
|
-
Success as SuccessImport
|
|
12
|
+
Success as SuccessImport
|
|
13
13
|
} from "./src/types/maybe_promise.js";
|
|
14
14
|
import type {
|
|
15
15
|
Nullable as NullableImport,
|
|
16
|
-
ResolveNullable as ResolveNullableImport
|
|
16
|
+
ResolveNullable as ResolveNullableImport
|
|
17
17
|
} from "./src/types/nullable.js";
|
|
18
18
|
import type {
|
|
19
19
|
Optional as OptionalImport,
|
|
20
|
-
ResolveOptional as ResolveOptionalImport
|
|
20
|
+
ResolveOptional as ResolveOptionalImport
|
|
21
21
|
} from "./src/types/optional.js";
|
|
22
22
|
|
|
23
23
|
declare global {
|
|
@@ -43,7 +43,7 @@ declare global {
|
|
|
43
43
|
stringify<T>(
|
|
44
44
|
value: T,
|
|
45
45
|
replacer?: null,
|
|
46
|
-
space?: string | number
|
|
46
|
+
space?: string | number
|
|
47
47
|
): Stringified<T>;
|
|
48
48
|
|
|
49
49
|
parse<T>(str: Stringified<T>, replacer?: null): JsonifiedValueImport<T>;
|
|
@@ -61,5 +61,5 @@ export type {
|
|
|
61
61
|
ResolveNullableImport as ResolveNullable,
|
|
62
62
|
ResolveOptionalImport as ResolveOptional,
|
|
63
63
|
StringifiedImport as Stringified,
|
|
64
|
-
SuccessImport as Success
|
|
64
|
+
SuccessImport as Success
|
|
65
65
|
};
|
package/jsr.json
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
2
|
+
"$schema": "https://jsr.io/schema/config-file.v1.json",
|
|
3
|
+
"name": "@murky-web/typebuddy",
|
|
4
|
+
"version": "3.1.0",
|
|
5
|
+
"license": "ISC",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/public_api.ts",
|
|
8
|
+
"./oxlint": "./oxlint/index.ts"
|
|
9
|
+
},
|
|
10
|
+
"publish": {
|
|
11
|
+
"include": [
|
|
12
|
+
"README.md",
|
|
13
|
+
"src/**/*.ts",
|
|
14
|
+
"oxlint/**/*.ts",
|
|
15
|
+
"rules/**/*.ts"
|
|
16
|
+
],
|
|
17
|
+
"exclude": [
|
|
18
|
+
"tests/**",
|
|
19
|
+
"smoke/**",
|
|
20
|
+
"globals.d.ts",
|
|
21
|
+
"src/index.ts",
|
|
22
|
+
"dist/**",
|
|
23
|
+
"node_modules/**"
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
26
|
}
|
package/oxlint/index.ts
CHANGED
|
@@ -4,14 +4,18 @@ import { maybeRule } from "../rules/maybe_rule.js";
|
|
|
4
4
|
import { nullableRule } from "../rules/nullable_rule.js";
|
|
5
5
|
import { optionalRule } from "../rules/optional_rule.js";
|
|
6
6
|
import { withoutTestFiles } from "../rules/test_file.js";
|
|
7
|
+
import { uselessUndefinedRule } from "../rules/useless_undefined_rule.js";
|
|
7
8
|
|
|
8
|
-
// typebuddy
|
|
9
|
+
// The typebuddy conventions do not apply to test files: those rules are a no-op
|
|
10
|
+
// there. `no-useless-undefined` is a fork of unicorn's rule and lints test files
|
|
11
|
+
// as the unicorn rule it replaces did.
|
|
9
12
|
const rules = {
|
|
13
|
+
"no-useless-undefined": uselessUndefinedRule,
|
|
10
14
|
"prefer-maybe": withoutTestFiles(maybeRule),
|
|
11
15
|
"prefer-maybe-promise": withoutTestFiles(errorSafeAsyncRule),
|
|
12
16
|
"prefer-nullable": withoutTestFiles(nullableRule),
|
|
13
17
|
"prefer-optional": withoutTestFiles(optionalRule),
|
|
14
|
-
"require-try-catch": withoutTestFiles(requireTryCatchAsyncRule)
|
|
18
|
+
"require-try-catch": withoutTestFiles(requireTryCatchAsyncRule)
|
|
15
19
|
} as const satisfies Record<string, unknown>;
|
|
16
20
|
|
|
17
21
|
type TypebuddyOxlintPlugin = {
|
|
@@ -23,9 +27,9 @@ type TypebuddyOxlintPlugin = {
|
|
|
23
27
|
|
|
24
28
|
const plugin: TypebuddyOxlintPlugin = {
|
|
25
29
|
meta: {
|
|
26
|
-
name: "typebuddy"
|
|
30
|
+
name: "typebuddy"
|
|
27
31
|
},
|
|
28
|
-
rules
|
|
32
|
+
rules
|
|
29
33
|
};
|
|
30
34
|
|
|
31
35
|
export default plugin;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@murky-web/typebuddy",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Your new best friend for simple typescript guards every project needs.",
|
|
6
6
|
"homepage": "https://github.com/MurkyTheMurloc/web_dev_tools/tree/main/packages/typebuddy",
|
|
@@ -83,8 +83,8 @@
|
|
|
83
83
|
"clean": "rm -rf dist",
|
|
84
84
|
"lint": "oxlint -c ./.oxlintrc.jsonc --tsconfig ./tsconfig.lint.json --type-aware src tsdown.config.ts vitest.config.ts",
|
|
85
85
|
"lint:fix": "oxlint -c ./.oxlintrc.jsonc --tsconfig ./tsconfig.lint.json --type-aware --fix src tsdown.config.ts vitest.config.ts",
|
|
86
|
-
"format": "oxfmt -c
|
|
87
|
-
"format:check": "oxfmt -c
|
|
86
|
+
"format": "oxfmt -c ../oxc-config/.oxfmtrc.jsonc src rules tests tsdown.config.ts vitest.config.ts",
|
|
87
|
+
"format:check": "oxfmt -c ../oxc-config/.oxfmtrc.jsonc --check src rules tests tsdown.config.ts vitest.config.ts",
|
|
88
88
|
"smoke:globals": "bun run build && tsc --project ./smoke/globals/tsconfig.json --noEmit && mkdir -p ./smoke/globals/node_modules/@murky-web && ln -sfn ../../../.. ./smoke/globals/node_modules/@murky-web/typebuddy && tsc --project ./smoke/globals/tsconfig.types.json --noEmit",
|
|
89
89
|
"smoke:oxlint": "bun run build && bun ./smoke/oxlint/run-smoke.ts",
|
|
90
90
|
"smoke:oxlint:fix": "bun run build && bun ./smoke/oxlint/run-fix-smoke.ts",
|