@murky-web/typebuddy 3.0.1 → 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.
@@ -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/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": "3.0.1",
4
+ "version": "3.1.0",
5
5
  "license": "ISC",
6
6
  "exports": {
7
7
  ".": "./src/public_api.ts",
package/oxlint/index.ts CHANGED
@@ -4,9 +4,13 @@ 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 does not apply to test files: every rule is a no-op there.
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),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murky-web/typebuddy",
3
- "version": "3.0.1",
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 ../../config/oxc/.oxfmtrc.jsonc src rules tests tsdown.config.ts vitest.config.ts",
87
- "format:check": "oxfmt -c ../../config/oxc/.oxfmtrc.jsonc --check src rules tests tsdown.config.ts vitest.config.ts",
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",
@@ -27,6 +27,7 @@ type RuleContext = {
27
27
  report(descriptor: {
28
28
  node: unknown;
29
29
  messageId: string;
30
+ data: { name: string };
30
31
  suggest?: {
31
32
  messageId: string;
32
33
  fix(fixer: RuleFixer): unknown;
@@ -40,6 +41,29 @@ function hasTryCatch(nodes: AstNode[]): boolean {
40
41
  });
41
42
  }
42
43
 
44
+ /**
45
+ * What the message calls the function: its own name, the name it is bound to,
46
+ * or else the first line of its source.
47
+ */
48
+ function functionLabel(node: AstNode, getText: (node: unknown) => string) {
49
+ const candidates = [node["id"], node.parent?.["id"], node.parent?.["key"]];
50
+ for (const candidate of candidates) {
51
+ if (
52
+ typeof candidate === "object" &&
53
+ candidate !== null &&
54
+ "type" in candidate &&
55
+ candidate.type === "Identifier" &&
56
+ "name" in candidate &&
57
+ typeof candidate.name === "string"
58
+ ) {
59
+ return candidate.name;
60
+ }
61
+ }
62
+
63
+ const [firstLine = ""] = getText(node).split("\n");
64
+ return firstLine.trim();
65
+ }
66
+
43
67
  function isCallArgumentCallback(node: AstNode): boolean {
44
68
  const parent = node.parent;
45
69
  if (!parent) {
@@ -59,6 +83,7 @@ const rule = {
59
83
  create(context: RuleContext) {
60
84
  const sourceCode = context.getSourceCode();
61
85
  const imports = createImportPlanner(sourceCode);
86
+ const getText = (node: unknown) => sourceCode.getText(node);
62
87
 
63
88
  // Two zero-width insertions leave the body's own text untouched, byte
64
89
  // for byte. Rebuilding it statement by statement used to strip leading
@@ -201,6 +226,7 @@ const rule = {
201
226
  context.report({
202
227
  node,
203
228
  messageId: "missingTryCatch",
229
+ data: { name: functionLabel(node, getText) },
204
230
  suggest: suggestWrap(node, (fixer) => {
205
231
  return wrapExpressionBodyFixes(node, bodyNode, fixer);
206
232
  })
@@ -214,6 +240,7 @@ const rule = {
214
240
  context.report({
215
241
  node,
216
242
  messageId: "missingTryCatch",
243
+ data: { name: functionLabel(node, getText) },
217
244
  suggest: suggestWrap(bodyNode, (fixer) => {
218
245
  return wrapBlockFixes(bodyNode, fixer);
219
246
  })
@@ -240,7 +267,7 @@ const rule = {
240
267
  schema: [],
241
268
  messages: {
242
269
  missingTryCatch:
243
- "Async functions must have a try-catch block returning an error result.",
270
+ '`{{name}}` is async without a `try`/`catch`, so a throw inside it rejects the promise and callers that check `isError` never see the failure. Fix: put the body in `try { … } catch { return err(); }` (after a directive such as `"use cache"`) with `import { err } from "@murky-web/typebuddy";` and `return ok(value)` in the `try`; if the failure is a bug rather than an outcome for the caller, `throw` instead, which the rule accepts. Do not wrap only part of the body, and do not return `ok(...)` from the `catch`.',
244
271
  suggestTryCatch:
245
272
  "Wrap the body in try/catch and return err() from the catch."
246
273
  }