eslint 9.33.0 → 9.35.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.
Files changed (42) hide show
  1. package/README.md +1 -1
  2. package/lib/cli-engine/file-enumerator.js +1 -1
  3. package/lib/cli.js +62 -266
  4. package/lib/config/flat-config-schema.js +1 -1
  5. package/lib/eslint/eslint-helpers.js +426 -6
  6. package/lib/eslint/eslint.js +381 -313
  7. package/lib/eslint/worker.js +164 -0
  8. package/lib/languages/js/source-code/source-code.js +3 -4
  9. package/lib/linter/esquery.js +3 -0
  10. package/lib/linter/interpolate.js +1 -1
  11. package/lib/linter/linter.js +3 -4
  12. package/lib/options.js +23 -9
  13. package/lib/rule-tester/rule-tester.js +3 -0
  14. package/lib/rules/array-callback-return.js +0 -1
  15. package/lib/rules/dot-notation.js +1 -1
  16. package/lib/rules/grouped-accessor-pairs.js +8 -7
  17. package/lib/rules/indent-legacy.js +1 -1
  18. package/lib/rules/index.js +1 -0
  19. package/lib/rules/no-alert.js +1 -1
  20. package/lib/rules/no-empty-function.js +20 -1
  21. package/lib/rules/no-empty-static-block.js +25 -1
  22. package/lib/rules/no-empty.js +37 -0
  23. package/lib/rules/no-eval.js +3 -1
  24. package/lib/rules/no-irregular-whitespace.js +2 -2
  25. package/lib/rules/no-loss-of-precision.js +26 -3
  26. package/lib/rules/no-mixed-spaces-and-tabs.js +1 -0
  27. package/lib/rules/no-octal.js +1 -4
  28. package/lib/rules/no-trailing-spaces.js +2 -1
  29. package/lib/rules/no-useless-escape.js +1 -1
  30. package/lib/rules/prefer-regex-literals.js +1 -1
  31. package/lib/rules/preserve-caught-error.js +509 -0
  32. package/lib/rules/strict.js +2 -1
  33. package/lib/rules/utils/ast-utils.js +1 -1
  34. package/lib/rules/utils/char-source.js +1 -1
  35. package/lib/rules/yoda.js +2 -2
  36. package/lib/services/suppressions-service.js +3 -0
  37. package/lib/services/warning-service.js +13 -0
  38. package/lib/shared/naming.js +1 -1
  39. package/lib/shared/translate-cli-options.js +281 -0
  40. package/lib/types/index.d.ts +7 -0
  41. package/lib/types/rules.d.ts +22 -14
  42. package/package.json +3 -3
@@ -0,0 +1,509 @@
1
+ /**
2
+ * @fileoverview Rule to preserve caught errors when re-throwing exceptions
3
+ * @author Amnish Singh Arora
4
+ */
5
+ "use strict";
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Requirements
9
+ //------------------------------------------------------------------------------
10
+
11
+ const astUtils = require("./utils/ast-utils");
12
+
13
+ //----------------------------------------------------------------------
14
+ // Helpers
15
+ //----------------------------------------------------------------------
16
+
17
+ /*
18
+ * This is an indicator of an error cause node, that is too complicated to be detected and fixed.
19
+ * Eg, when error options is an `Identifier` or a `SpreadElement`.
20
+ */
21
+ const UNKNOWN_CAUSE = Symbol("unknown_cause");
22
+
23
+ const BUILT_IN_ERROR_TYPES = new Set([
24
+ "Error",
25
+ "EvalError",
26
+ "RangeError",
27
+ "ReferenceError",
28
+ "SyntaxError",
29
+ "TypeError",
30
+ "URIError",
31
+ "AggregateError",
32
+ ]);
33
+
34
+ /**
35
+ * Finds and returns the ASTNode that is used as the `cause` of the Error being thrown
36
+ * @param {ASTNode} throwStatement `ThrowStatement` to be checked.
37
+ * @returns {ASTNode | UNKNOWN_CAUSE | null} The `cause` of `Error` being thrown, `null` if not set.
38
+ */
39
+ function getErrorCause(throwStatement) {
40
+ const throwExpression = throwStatement.argument;
41
+ /*
42
+ * Determine which argument index holds the options object
43
+ * `AggregateError` is a special case as it accepts the `options` object as third argument.
44
+ */
45
+ const optionsIndex =
46
+ throwExpression.callee.name === "AggregateError" ? 2 : 1;
47
+
48
+ /*
49
+ * Make sure there is no `SpreadElement` at or before the `optionsIndex`
50
+ * as this messes up the effective order of arguments and makes it complicated
51
+ * to track where the actual error options need to be at
52
+ */
53
+ const spreadExpressionIndex = throwExpression.arguments.findIndex(
54
+ arg => arg.type === "SpreadElement",
55
+ );
56
+ if (spreadExpressionIndex >= 0 && spreadExpressionIndex <= optionsIndex) {
57
+ return UNKNOWN_CAUSE;
58
+ }
59
+
60
+ const errorOptions = throwExpression.arguments[optionsIndex];
61
+
62
+ if (errorOptions) {
63
+ if (errorOptions.type === "ObjectExpression") {
64
+ if (
65
+ errorOptions.properties.some(
66
+ prop => prop.type === "SpreadElement",
67
+ )
68
+ ) {
69
+ /*
70
+ * If there is a spread element as part of error options, it is too complicated
71
+ * to verify if the cause is used properly and auto-fix.
72
+ */
73
+ return UNKNOWN_CAUSE;
74
+ }
75
+
76
+ const causeProperty = errorOptions.properties.find(
77
+ prop =>
78
+ prop.type === "Property" &&
79
+ prop.key.type === "Identifier" &&
80
+ prop.key.name === "cause" &&
81
+ !prop.computed, // It is hard to accurately identify the value of computed props
82
+ );
83
+
84
+ return causeProperty ? causeProperty.value : null;
85
+ }
86
+
87
+ // Error options exist, but too complicated to be analyzed/fixed
88
+ return UNKNOWN_CAUSE;
89
+ }
90
+
91
+ return null;
92
+ }
93
+
94
+ /**
95
+ * Finds and returns the `CatchClause` node, that the `node` is part of.
96
+ * @param {ASTNode} node The AST node to be evaluated.
97
+ * @returns {ASTNode | null } The closest parent `CatchClause` node, `null` if the `node` is not in a catch block.
98
+ */
99
+ function findParentCatch(node) {
100
+ let currentNode = node;
101
+
102
+ while (currentNode && currentNode.type !== "CatchClause") {
103
+ if (
104
+ [
105
+ "FunctionDeclaration",
106
+ "FunctionExpression",
107
+ "ArrowFunctionExpression",
108
+ "StaticBlock",
109
+ ].includes(currentNode.type)
110
+ ) {
111
+ /*
112
+ * Make sure the ThrowStatement is not made inside a function definition or a static block inside a high level catch.
113
+ * In such cases, the caught error is not directly related to the Throw.
114
+ *
115
+ * For example,
116
+ * try {
117
+ * } catch (error) {
118
+ * foo = {
119
+ * bar() {
120
+ * throw new Error();
121
+ * }
122
+ * };
123
+ * }
124
+ */
125
+ return null;
126
+ }
127
+ currentNode = currentNode.parent;
128
+ }
129
+
130
+ return currentNode;
131
+ }
132
+
133
+ //------------------------------------------------------------------------------
134
+ // Rule Definition
135
+ //------------------------------------------------------------------------------
136
+
137
+ /** @type {import('../types').Rule.RuleModule} */
138
+ module.exports = {
139
+ meta: {
140
+ type: "suggestion",
141
+ docs: {
142
+ description:
143
+ "Disallow losing originally caught error when re-throwing custom errors",
144
+ recommended: false,
145
+ url: "https://eslint.org/docs/latest/rules/preserve-caught-error", // URL to the documentation page for this rule
146
+ },
147
+ /*
148
+ * TODO: We should allow passing `customErrorTypes` option once something like `typescript-eslint`'s
149
+ * `TypeOrValueSpecifier` is implemented in core Eslint.
150
+ * See:
151
+ * 1. https://typescript-eslint.io/packages/type-utils/type-or-value-specifier/
152
+ * 2. https://github.com/eslint/eslint/pull/19913#discussion_r2192608593
153
+ * 3. https://github.com/eslint/eslint/discussions/16540
154
+ */
155
+ schema: [
156
+ {
157
+ type: "object",
158
+ properties: {
159
+ requireCatchParameter: {
160
+ type: "boolean",
161
+ default: false,
162
+ description:
163
+ "Requires the catch blocks to always have the caught error parameter so it is not discarded.",
164
+ },
165
+ },
166
+ additionalProperties: false,
167
+ },
168
+ ],
169
+ messages: {
170
+ missingCause:
171
+ "There is no `cause` attached to the symptom error being thrown.",
172
+ incorrectCause:
173
+ "The symptom error is being thrown with an incorrect `cause`.",
174
+ includeCause:
175
+ "Include the original caught error as the `cause` of the symptom error.",
176
+ missingCatchErrorParam:
177
+ "The caught error is not accessible because the catch clause lacks the error parameter. Start referencing the caught error using the catch parameter.",
178
+ partiallyLostError:
179
+ "Re-throws cannot preserve the caught error as a part of it is being lost due to destructuring.",
180
+ caughtErrorShadowed:
181
+ "The caught error is being attached as `cause`, but is shadowed by a closer scoped redeclaration.",
182
+ },
183
+ hasSuggestions: true,
184
+ },
185
+
186
+ create(context) {
187
+ const sourceCode = context.sourceCode;
188
+ const options = context.options[0] || {};
189
+
190
+ //----------------------------------------------------------------------
191
+ // Helpers
192
+ //----------------------------------------------------------------------
193
+
194
+ /**
195
+ * Checks if a `ThrowStatement` is constructing and throwing a new `Error` object.
196
+ *
197
+ * Covers all the error types on `globalThis` that support `cause` property:
198
+ * https://github.com/microsoft/TypeScript/blob/main/src/lib/es2022.error.d.ts
199
+ * @param {ASTNode} throwStatement The `ThrowStatement` that needs to be checked.
200
+ * @returns {boolean} `true` if a new "Error" is being thrown, else `false`.
201
+ */
202
+ function isThrowingNewError(throwStatement) {
203
+ return (
204
+ (throwStatement.argument.type === "NewExpression" ||
205
+ throwStatement.argument.type === "CallExpression") &&
206
+ throwStatement.argument.callee.type === "Identifier" &&
207
+ BUILT_IN_ERROR_TYPES.has(throwStatement.argument.callee.name) &&
208
+ /*
209
+ * Make sure the thrown Error is instance is one of the built-in global error types.
210
+ * Custom imports could shadow this, which would lead to false positives.
211
+ * e.g. import { Error } from "./my-custom-error.js";
212
+ * throw Error("Failed to perform error prone operations");
213
+ */
214
+ sourceCode.isGlobalReference(throwStatement.argument.callee)
215
+ );
216
+ }
217
+
218
+ /**
219
+ * Inserts `cause: <caughtErrorName>` into an inline options object expression.
220
+ * @param {RuleFixer} fixer The fixer object.
221
+ * @param {ASTNode} optionsNode The options object node.
222
+ * @param {string} caughtErrorName The name of the caught error (e.g., "err").
223
+ * @returns {Fix} The fix object.
224
+ */
225
+ function insertCauseIntoOptions(fixer, optionsNode, caughtErrorName) {
226
+ const properties = optionsNode.properties;
227
+
228
+ if (properties.length === 0) {
229
+ // Insert inside empty braces: `{}` → `{ cause: err }`
230
+ return fixer.insertTextAfter(
231
+ sourceCode.getFirstToken(optionsNode),
232
+ `cause: ${caughtErrorName}`,
233
+ );
234
+ }
235
+
236
+ const lastProp = properties.at(-1);
237
+ return fixer.insertTextAfter(
238
+ lastProp,
239
+ `, cause: ${caughtErrorName}`,
240
+ );
241
+ }
242
+
243
+ //----------------------------------------------------------------------
244
+ // Public
245
+ //----------------------------------------------------------------------
246
+ return {
247
+ ThrowStatement(node) {
248
+ // Check if the throw is inside a catch block
249
+ const parentCatch = findParentCatch(node);
250
+ const throwStatement = node;
251
+
252
+ // Check if a new error is being thrown in a catch block
253
+ if (parentCatch && isThrowingNewError(throwStatement)) {
254
+ if (
255
+ parentCatch.param &&
256
+ parentCatch.param.type !== "Identifier"
257
+ ) {
258
+ /*
259
+ * When a part of the caught error is being lost at the parameter level, commonly due to destructuring.
260
+ * e.g. catch({ message, ...rest })
261
+ */
262
+ context.report({
263
+ messageId: "partiallyLostError",
264
+ node: parentCatch,
265
+ });
266
+ return;
267
+ }
268
+
269
+ const caughtError =
270
+ parentCatch.param?.type === "Identifier"
271
+ ? parentCatch.param
272
+ : null;
273
+
274
+ // Check if there are throw statements and caught error is being ignored
275
+ if (!caughtError) {
276
+ if (options.requireCatchParameter) {
277
+ context.report({
278
+ node: throwStatement,
279
+ messageId: "missingCatchErrorParam",
280
+ });
281
+ return;
282
+ }
283
+ return;
284
+ }
285
+
286
+ // Check if there is a cause attached to the new error
287
+ const thrownErrorCause = getErrorCause(throwStatement);
288
+
289
+ if (thrownErrorCause === UNKNOWN_CAUSE) {
290
+ // Error options exist, but too complicated to be analyzed/fixed
291
+ return;
292
+ }
293
+
294
+ if (thrownErrorCause === null) {
295
+ // If there is no `cause` attached to the error being thrown.
296
+ context.report({
297
+ messageId: "missingCause",
298
+ node: throwStatement,
299
+ suggest: [
300
+ {
301
+ messageId: "includeCause",
302
+ fix(fixer) {
303
+ const throwExpression =
304
+ throwStatement.argument;
305
+ const args = throwExpression.arguments;
306
+ const errorType =
307
+ throwExpression.callee.name;
308
+
309
+ // AggregateError: errors, message, options
310
+ if (errorType === "AggregateError") {
311
+ const errorsArg = args[0];
312
+ const messageArg = args[1];
313
+ const optionsArg = args[2];
314
+
315
+ if (!errorsArg) {
316
+ // Case: `throw new AggregateError()` → insert all arguments
317
+ const lastToken =
318
+ sourceCode.getLastToken(
319
+ throwExpression,
320
+ );
321
+ const lastCalleeToken =
322
+ sourceCode.getLastToken(
323
+ throwExpression.callee,
324
+ );
325
+ const parenToken =
326
+ sourceCode.getFirstTokenBetween(
327
+ lastCalleeToken,
328
+ lastToken,
329
+ astUtils.isOpeningParenToken,
330
+ );
331
+
332
+ if (parenToken) {
333
+ return fixer.insertTextAfter(
334
+ parenToken,
335
+ `[], "", { cause: ${caughtError.name} }`,
336
+ );
337
+ }
338
+ return fixer.insertTextAfter(
339
+ throwExpression.callee,
340
+ `([], "", { cause: ${caughtError.name} })`,
341
+ );
342
+ }
343
+
344
+ if (!messageArg) {
345
+ // Case: `throw new AggregateError([])` → insert message and options
346
+ return fixer.insertTextAfter(
347
+ errorsArg,
348
+ `, "", { cause: ${caughtError.name} }`,
349
+ );
350
+ }
351
+
352
+ if (!optionsArg) {
353
+ // Case: `throw new AggregateError([], "")` → insert error options only
354
+ return fixer.insertTextAfter(
355
+ messageArg,
356
+ `, { cause: ${caughtError.name} }`,
357
+ );
358
+ }
359
+
360
+ if (
361
+ optionsArg.type ===
362
+ "ObjectExpression"
363
+ ) {
364
+ return insertCauseIntoOptions(
365
+ fixer,
366
+ optionsArg,
367
+ caughtError.name,
368
+ );
369
+ }
370
+
371
+ // Complex dynamic options — skip
372
+ return null;
373
+ }
374
+
375
+ // Normal Error types
376
+ const messageArg = args[0];
377
+ const optionsArg = args[1];
378
+
379
+ if (!messageArg) {
380
+ // Case: `throw new Error()` → insert both message and options
381
+ const lastToken =
382
+ sourceCode.getLastToken(
383
+ throwExpression,
384
+ );
385
+ const lastCalleeToken =
386
+ sourceCode.getLastToken(
387
+ throwExpression.callee,
388
+ );
389
+ const parenToken =
390
+ sourceCode.getFirstTokenBetween(
391
+ lastCalleeToken,
392
+ lastToken,
393
+ astUtils.isOpeningParenToken,
394
+ );
395
+
396
+ if (parenToken) {
397
+ return fixer.insertTextAfter(
398
+ parenToken,
399
+ `"", { cause: ${caughtError.name} }`,
400
+ );
401
+ }
402
+ return fixer.insertTextAfter(
403
+ throwExpression.callee,
404
+ `("", { cause: ${caughtError.name} })`,
405
+ );
406
+ }
407
+ if (!optionsArg) {
408
+ // Case: `throw new Error("Some message")` → insert only options
409
+ return fixer.insertTextAfter(
410
+ messageArg,
411
+ `, { cause: ${caughtError.name} }`,
412
+ );
413
+ }
414
+
415
+ if (
416
+ optionsArg.type ===
417
+ "ObjectExpression"
418
+ ) {
419
+ return insertCauseIntoOptions(
420
+ fixer,
421
+ optionsArg,
422
+ caughtError.name,
423
+ );
424
+ }
425
+
426
+ return null; // Identifier or spread — do not fix
427
+ },
428
+ },
429
+ ],
430
+ });
431
+
432
+ // We don't need to check further
433
+ return;
434
+ }
435
+
436
+ // If there is an attached cause, verify that is matches the caught error
437
+ if (
438
+ !(
439
+ thrownErrorCause.type === "Identifier" &&
440
+ thrownErrorCause.name === caughtError.name
441
+ )
442
+ ) {
443
+ context.report({
444
+ messageId: "incorrectCause",
445
+ node: thrownErrorCause,
446
+ suggest: [
447
+ {
448
+ messageId: "includeCause",
449
+ fix(fixer) {
450
+ /*
451
+ * In case `cause` is attached using object property shorthand or as a method.
452
+ * e.g. throw Error("fail", { cause });
453
+ * throw Error("fail", { cause() { // do something } });
454
+ */
455
+ if (
456
+ thrownErrorCause.parent.method ||
457
+ thrownErrorCause.parent.shorthand
458
+ ) {
459
+ return fixer.replaceText(
460
+ thrownErrorCause.parent,
461
+ `cause: ${caughtError.name}`,
462
+ );
463
+ }
464
+
465
+ return fixer.replaceText(
466
+ thrownErrorCause,
467
+ caughtError.name,
468
+ );
469
+ },
470
+ },
471
+ ],
472
+ });
473
+ return;
474
+ }
475
+
476
+ /*
477
+ * If the attached cause matches the identifier name of the caught error,
478
+ * make sure it is not being shadowed by a closer scoped redeclaration.
479
+ *
480
+ * e.g. try {
481
+ * doSomething();
482
+ * } catch (error) {
483
+ * if (whatever) {
484
+ * const error = anotherError;
485
+ * throw new Error("Something went wrong");
486
+ * }
487
+ * }
488
+ */
489
+ let scope = sourceCode.getScope(throwStatement);
490
+ do {
491
+ const variable = scope.set.get(caughtError.name);
492
+ if (variable) {
493
+ break;
494
+ }
495
+ scope = scope.upper;
496
+ } while (scope);
497
+
498
+ if (scope?.block !== parentCatch) {
499
+ // Caught error is being shadowed
500
+ context.report({
501
+ messageId: "caughtErrorShadowed",
502
+ node: throwStatement,
503
+ });
504
+ }
505
+ }
506
+ },
507
+ };
508
+ },
509
+ };
@@ -101,7 +101,8 @@ module.exports = {
101
101
  },
102
102
 
103
103
  create(context) {
104
- const ecmaFeatures = context.parserOptions.ecmaFeatures || {},
104
+ const ecmaFeatures =
105
+ context.languageOptions.parserOptions.ecmaFeatures || {},
105
106
  scopes = [],
106
107
  classScopes = [];
107
108
  let [mode] = context.options;
@@ -58,7 +58,7 @@ const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u;
58
58
 
59
59
  // Tests the presence of at least one LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence in a raw string
60
60
  const OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN =
61
- /^(?:[^\\]|\\.)*\\(?:[1-9]|0[0-9])/su;
61
+ /^(?:[^\\]|\\.)*\\(?:[1-9]|0\d)/su;
62
62
 
63
63
  const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]);
64
64
 
@@ -85,7 +85,7 @@ function readHexSequence(reader, length) {
85
85
  * @returns {string} A code unit.
86
86
  */
87
87
  function readUnicodeSequence(reader) {
88
- const regExp = /\{(?<hexDigits>[\dA-Fa-f]+)\}/uy;
88
+ const regExp = /\{(?<hexDigits>[\dA-F]+)\}/iuy;
89
89
 
90
90
  regExp.lastIndex = reader.pos;
91
91
  const match = regExp.exec(reader.source);
package/lib/rules/yoda.js CHANGED
@@ -20,7 +20,7 @@ const astUtils = require("./utils/ast-utils");
20
20
  * @returns {boolean} Whether or not it is a comparison operator.
21
21
  */
22
22
  function isComparisonOperator(operator) {
23
- return /^(==|===|!=|!==|<|>|<=|>=)$/u.test(operator);
23
+ return /^(?:==|===|!=|!==|<|>|<=|>=)$/u.test(operator);
24
24
  }
25
25
 
26
26
  /**
@@ -29,7 +29,7 @@ function isComparisonOperator(operator) {
29
29
  * @returns {boolean} Whether or not it is an equality operator.
30
30
  */
31
31
  function isEqualityOperator(operator) {
32
- return /^(==|===)$/u.test(operator);
32
+ return /^(?:==|===)$/u.test(operator);
33
33
  }
34
34
 
35
35
  /**
@@ -221,6 +221,9 @@ class SuppressionsService {
221
221
  }
222
222
  throw new Error(
223
223
  `Failed to parse suppressions file at ${this.filePath}`,
224
+ {
225
+ cause: err,
226
+ },
224
227
  );
225
228
  }
226
229
  }
@@ -80,6 +80,19 @@ class WarningService {
80
80
  emitInactiveFlagWarning(flag, message) {
81
81
  this.emitWarning(message, `ESLintInactiveFlag_${flag}`);
82
82
  }
83
+
84
+ /**
85
+ * Emits a warning when a suboptimal concurrency setting is detected.
86
+ * Currently, this is only used to warn when the net linting ratio is low.
87
+ * @param {string} notice A notice about how to improve performance.
88
+ * @returns {void}
89
+ */
90
+ emitPoorConcurrencyWarning(notice) {
91
+ this.emitWarning(
92
+ `You may ${notice} to improve performance.`,
93
+ "ESLintPoorConcurrencyWarning",
94
+ );
95
+ }
83
96
  }
84
97
 
85
98
  module.exports = { WarningService };
@@ -4,7 +4,7 @@
4
4
 
5
5
  "use strict";
6
6
 
7
- const NAMESPACE_REGEX = /^@.*\//iu;
7
+ const NAMESPACE_REGEX = /^@.*\//u;
8
8
 
9
9
  /**
10
10
  * Brings package name to correct format based on prefix