eslint 7.27.0 → 7.31.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.
@@ -37,8 +37,10 @@ const
37
37
  const debug = require("debug")("eslint:linter");
38
38
  const MAX_AUTOFIX_PASSES = 10;
39
39
  const DEFAULT_PARSER_NAME = "espree";
40
+ const DEFAULT_ECMA_VERSION = 5;
40
41
  const commentParser = new ConfigCommentParser();
41
42
  const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } };
43
+ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
42
44
 
43
45
  //------------------------------------------------------------------------------
44
46
  // Typedefs
@@ -432,10 +434,16 @@ function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
432
434
 
433
435
  /**
434
436
  * Normalize ECMAScript version from the initial config
435
- * @param {number} ecmaVersion ECMAScript version from the initial config
437
+ * @param {Parser} parser The parser which uses this options.
438
+ * @param {number} ecmaVersion ECMAScript version from the initial config
436
439
  * @returns {number} normalized ECMAScript version
437
440
  */
438
- function normalizeEcmaVersion(ecmaVersion) {
441
+ function normalizeEcmaVersion(parser, ecmaVersion) {
442
+ if ((parser[parserSymbol] || parser) === espree) {
443
+ if (ecmaVersion === "latest") {
444
+ return espree.latestEcmaVersion;
445
+ }
446
+ }
439
447
 
440
448
  /*
441
449
  * Calculate ECMAScript edition number from official year version starting with
@@ -444,7 +452,7 @@ function normalizeEcmaVersion(ecmaVersion) {
444
452
  return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
445
453
  }
446
454
 
447
- const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu;
455
+ const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gsu;
448
456
 
449
457
  /**
450
458
  * Checks whether or not there is a comment which has "eslint-env *" in a given text.
@@ -521,12 +529,13 @@ function normalizeVerifyOptions(providedOptions, config) {
521
529
 
522
530
  /**
523
531
  * Combines the provided parserOptions with the options from environments
524
- * @param {string} parserName The parser name which uses this options.
532
+ * @param {Parser} parser The parser which uses this options.
525
533
  * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config
526
534
  * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
527
535
  * @returns {ParserOptions} Resulting parser options after merge
528
536
  */
529
- function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
537
+ function resolveParserOptions(parser, providedOptions, enabledEnvironments) {
538
+
530
539
  const parserOptionsFromEnv = enabledEnvironments
531
540
  .filter(env => env.parserOptions)
532
541
  .reduce((parserOptions, env) => merge(parserOptions, env.parserOptions), {});
@@ -542,12 +551,7 @@ function resolveParserOptions(parserName, providedOptions, enabledEnvironments)
542
551
  mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
543
552
  }
544
553
 
545
- /*
546
- * TODO: @aladdin-add
547
- * 1. for a 3rd-party parser, do not normalize parserOptions
548
- * 2. for espree, no need to do this (espree will do it)
549
- */
550
- mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion);
554
+ mergedParserOptions.ecmaVersion = normalizeEcmaVersion(parser, mergedParserOptions.ecmaVersion);
551
555
 
552
556
  return mergedParserOptions;
553
557
  }
@@ -606,7 +610,7 @@ function getRuleOptions(ruleConfig) {
606
610
  */
607
611
  function analyzeScope(ast, parserOptions, visitorKeys) {
608
612
  const ecmaFeatures = parserOptions.ecmaFeatures || {};
609
- const ecmaVersion = parserOptions.ecmaVersion || 5;
613
+ const ecmaVersion = parserOptions.ecmaVersion || DEFAULT_ECMA_VERSION;
610
614
 
611
615
  return eslintScope.analyze(ast, {
612
616
  ignoreEval: true,
@@ -828,9 +832,10 @@ const BASE_TRAVERSAL_CONTEXT = Object.freeze(
828
832
  * @param {string} filename The reported filename of the code
829
833
  * @param {boolean} disableFixes If true, it doesn't make `fix` properties.
830
834
  * @param {string | undefined} cwd cwd of the cli
835
+ * @param {string} physicalFilename The full path of the file on disk without any code block information
831
836
  * @returns {Problem[]} An array of reported problems
832
837
  */
833
- function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename, disableFixes, cwd) {
838
+ function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename, disableFixes, cwd, physicalFilename) {
834
839
  const emitter = createEmitter();
835
840
  const nodeQueue = [];
836
841
  let currentNode = sourceCode.ast;
@@ -859,6 +864,7 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parser
859
864
  getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager),
860
865
  getCwd: () => cwd,
861
866
  getFilename: () => filename,
867
+ getPhysicalFilename: () => physicalFilename || filename,
862
868
  getScope: () => getScope(sourceCode.scopeManager, currentNode),
863
869
  getSourceCode: () => sourceCode,
864
870
  markVariableAsUsed: name => markVariableAsUsed(sourceCode.scopeManager, currentNode, parserOptions, name),
@@ -1121,7 +1127,7 @@ class Linter {
1121
1127
  .map(envName => getEnv(slots, envName))
1122
1128
  .filter(env => env);
1123
1129
 
1124
- const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs);
1130
+ const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs);
1125
1131
  const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
1126
1132
  const settings = config.settings || {};
1127
1133
 
@@ -1181,7 +1187,8 @@ class Linter {
1181
1187
  settings,
1182
1188
  options.filename,
1183
1189
  options.disableFixes,
1184
- slots.cwd
1190
+ slots.cwd,
1191
+ providedOptions.physicalFilename
1185
1192
  );
1186
1193
  } catch (err) {
1187
1194
  err.message += `\nOccurred while linting ${options.filename}`;
@@ -1284,6 +1291,7 @@ class Linter {
1284
1291
  _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
1285
1292
  const filename = options.filename || "<input>";
1286
1293
  const filenameToExpose = normalizeFilename(filename);
1294
+ const physicalFilename = options.physicalFilename || filenameToExpose;
1287
1295
  const text = ensureText(textOrSourceCode);
1288
1296
  const preprocess = options.preprocess || (rawText => [rawText]);
1289
1297
 
@@ -1316,7 +1324,7 @@ class Linter {
1316
1324
  return this._verifyWithConfigArray(
1317
1325
  blockText,
1318
1326
  configForRecursive,
1319
- { ...options, filename: blockName }
1327
+ { ...options, filename: blockName, physicalFilename }
1320
1328
  );
1321
1329
  }
1322
1330
 
@@ -1324,7 +1332,7 @@ class Linter {
1324
1332
  return this._verifyWithoutProcessors(
1325
1333
  blockText,
1326
1334
  config,
1327
- { ...options, filename: blockName }
1335
+ { ...options, filename: blockName, physicalFilename }
1328
1336
  );
1329
1337
  });
1330
1338
 
@@ -53,6 +53,7 @@ const
53
53
  const ajv = require("../shared/ajv")({ strictDefaults: true });
54
54
 
55
55
  const espreePath = require.resolve("espree");
56
+ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
56
57
 
57
58
  //------------------------------------------------------------------------------
58
59
  // Typedefs
@@ -71,6 +72,7 @@ const espreePath = require.resolve("espree");
71
72
  * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
72
73
  * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
73
74
  * @property {{ [name: string]: boolean }} [env] Environments for the test case.
75
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
74
76
  */
75
77
 
76
78
  /**
@@ -86,6 +88,7 @@ const espreePath = require.resolve("espree");
86
88
  * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
87
89
  * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
88
90
  * @property {{ [name: string]: boolean }} [env] Environments for the test case.
91
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
89
92
  */
90
93
 
91
94
  /**
@@ -121,7 +124,8 @@ const RuleTesterParameters = [
121
124
  "filename",
122
125
  "options",
123
126
  "errors",
124
- "output"
127
+ "output",
128
+ "only"
125
129
  ];
126
130
 
127
131
  /*
@@ -236,6 +240,7 @@ function defineStartEndAsError(objName, node) {
236
240
  });
237
241
  }
238
242
 
243
+
239
244
  /**
240
245
  * Define `start`/`end` properties of all nodes of the given AST as throwing error.
241
246
  * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
@@ -255,8 +260,10 @@ function defineStartEndAsErrorInTree(ast, visitorKeys) {
255
260
  * @returns {Parser} Wrapped parser object.
256
261
  */
257
262
  function wrapParser(parser) {
263
+
258
264
  if (typeof parser.parseForESLint === "function") {
259
265
  return {
266
+ [parserSymbol]: parser,
260
267
  parseForESLint(...args) {
261
268
  const ret = parser.parseForESLint(...args);
262
269
 
@@ -265,7 +272,9 @@ function wrapParser(parser) {
265
272
  }
266
273
  };
267
274
  }
275
+
268
276
  return {
277
+ [parserSymbol]: parser,
269
278
  parse(...args) {
270
279
  const ast = parser.parse(...args);
271
280
 
@@ -282,6 +291,7 @@ function wrapParser(parser) {
282
291
  // default separators for testing
283
292
  const DESCRIBE = Symbol("describe");
284
293
  const IT = Symbol("it");
294
+ const IT_ONLY = Symbol("itOnly");
285
295
 
286
296
  /**
287
297
  * This is `it` default handler if `it` don't exist.
@@ -400,6 +410,46 @@ class RuleTester {
400
410
  this[IT] = value;
401
411
  }
402
412
 
413
+ /**
414
+ * Adds the `only` property to a test to run it in isolation.
415
+ * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
416
+ * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
417
+ */
418
+ static only(item) {
419
+ if (typeof item === "string") {
420
+ return { code: item, only: true };
421
+ }
422
+
423
+ return { ...item, only: true };
424
+ }
425
+
426
+ static get itOnly() {
427
+ if (typeof this[IT_ONLY] === "function") {
428
+ return this[IT_ONLY];
429
+ }
430
+ if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
431
+ return Function.bind.call(this[IT].only, this[IT]);
432
+ }
433
+ if (typeof it === "function" && typeof it.only === "function") {
434
+ return Function.bind.call(it.only, it);
435
+ }
436
+
437
+ if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
438
+ throw new Error(
439
+ "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
440
+ "See https://eslint.org/docs/developer-guide/nodejs-api#customizing-ruletester for more."
441
+ );
442
+ }
443
+ if (typeof it === "function") {
444
+ throw new Error("The current test framework does not support exclusive tests with `only`.");
445
+ }
446
+ throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
447
+ }
448
+
449
+ static set itOnly(value) {
450
+ this[IT_ONLY] = value;
451
+ }
452
+
403
453
  /**
404
454
  * Define a rule for one particular run of tests.
405
455
  * @param {string} name The name of the rule to define.
@@ -610,7 +660,8 @@ class RuleTester {
610
660
  const messages = result.messages;
611
661
 
612
662
  assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
613
- messages.length, util.inspect(messages)));
663
+ messages.length,
664
+ util.inspect(messages)));
614
665
 
615
666
  assertASTDidntChange(result.beforeAST, result.afterAST);
616
667
  }
@@ -665,13 +716,18 @@ class RuleTester {
665
716
  }
666
717
 
667
718
  assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
668
- item.errors, item.errors === 1 ? "" : "s", messages.length, util.inspect(messages)));
719
+ item.errors,
720
+ item.errors === 1 ? "" : "s",
721
+ messages.length,
722
+ util.inspect(messages)));
669
723
  } else {
670
724
  assert.strictEqual(
671
- messages.length, item.errors.length,
672
- util.format(
725
+ messages.length, item.errors.length, util.format(
673
726
  "Should have %d error%s but had %d: %s",
674
- item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages)
727
+ item.errors.length,
728
+ item.errors.length === 1 ? "" : "s",
729
+ messages.length,
730
+ util.inspect(messages)
675
731
  )
676
732
  );
677
733
 
@@ -885,23 +941,29 @@ class RuleTester {
885
941
  RuleTester.describe(ruleName, () => {
886
942
  RuleTester.describe("valid", () => {
887
943
  test.valid.forEach(valid => {
888
- RuleTester.it(sanitize(typeof valid === "object" ? valid.code : valid), () => {
889
- testValidTemplate(valid);
890
- });
944
+ RuleTester[valid.only ? "itOnly" : "it"](
945
+ sanitize(typeof valid === "object" ? valid.code : valid),
946
+ () => {
947
+ testValidTemplate(valid);
948
+ }
949
+ );
891
950
  });
892
951
  });
893
952
 
894
953
  RuleTester.describe("invalid", () => {
895
954
  test.invalid.forEach(invalid => {
896
- RuleTester.it(sanitize(invalid.code), () => {
897
- testInvalidTemplate(invalid);
898
- });
955
+ RuleTester[invalid.only ? "itOnly" : "it"](
956
+ sanitize(invalid.code),
957
+ () => {
958
+ testInvalidTemplate(invalid);
959
+ }
960
+ );
899
961
  });
900
962
  });
901
963
  });
902
964
  }
903
965
  }
904
966
 
905
- RuleTester[DESCRIBE] = RuleTester[IT] = null;
967
+ RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;
906
968
 
907
969
  module.exports = RuleTester;
@@ -87,17 +87,17 @@ module.exports = {
87
87
  }
88
88
 
89
89
  /**
90
- * Gets the closing parenthesis which is the pair of the given opening parenthesis.
91
- * @param {Token} token The opening parenthesis token to get.
90
+ * Gets the closing parenthesis by the given node.
91
+ * @param {ASTNode} node first node after an opening parenthesis.
92
92
  * @returns {Token} The found closing parenthesis token.
93
93
  */
94
- function findClosingParen(token) {
95
- let node = sourceCode.getNodeByRangeIndex(token.range[0]);
94
+ function findClosingParen(node) {
95
+ let nodeToCheck = node;
96
96
 
97
- while (!astUtils.isParenthesised(sourceCode, node)) {
98
- node = node.parent;
97
+ while (!astUtils.isParenthesised(sourceCode, nodeToCheck)) {
98
+ nodeToCheck = nodeToCheck.parent;
99
99
  }
100
- return sourceCode.getTokenAfter(node);
100
+ return sourceCode.getTokenAfter(nodeToCheck);
101
101
  }
102
102
 
103
103
  /**
@@ -226,12 +226,22 @@ module.exports = {
226
226
  const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken);
227
227
  const [firstTokenAfterArrow, secondTokenAfterArrow] = sourceCode.getTokensAfter(arrowToken, { count: 2 });
228
228
  const lastToken = sourceCode.getLastToken(node);
229
- const isParenthesisedObjectLiteral =
229
+
230
+ let parenthesisedObjectLiteral = null;
231
+
232
+ if (
230
233
  astUtils.isOpeningParenToken(firstTokenAfterArrow) &&
231
- astUtils.isOpeningBraceToken(secondTokenAfterArrow);
234
+ astUtils.isOpeningBraceToken(secondTokenAfterArrow)
235
+ ) {
236
+ const braceNode = sourceCode.getNodeByRangeIndex(secondTokenAfterArrow.range[0]);
237
+
238
+ if (braceNode.type === "ObjectExpression") {
239
+ parenthesisedObjectLiteral = braceNode;
240
+ }
241
+ }
232
242
 
233
243
  // If the value is object literal, remove parentheses which were forced by syntax.
234
- if (isParenthesisedObjectLiteral) {
244
+ if (parenthesisedObjectLiteral) {
235
245
  const openingParenToken = firstTokenAfterArrow;
236
246
  const openingBraceToken = secondTokenAfterArrow;
237
247
 
@@ -247,7 +257,7 @@ module.exports = {
247
257
  }
248
258
 
249
259
  // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo()
250
- fixes.push(fixer.remove(findClosingParen(openingBraceToken)));
260
+ fixes.push(fixer.remove(findClosingParen(parenthesisedObjectLiteral)));
251
261
  fixes.push(fixer.insertTextAfter(lastToken, "}"));
252
262
 
253
263
  } else {
@@ -207,8 +207,7 @@ module.exports = {
207
207
  * they are always valid regardless of an undefined item.
208
208
  */
209
209
  if (astUtils.isCommaToken(commaToken)) {
210
- validateCommaItemSpacing(previousItemToken, commaToken,
211
- currentItemToken, reportItem);
210
+ validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem);
212
211
  }
213
212
 
214
213
  if (item) {
@@ -104,18 +104,18 @@ module.exports = {
104
104
  } else if (node.type === "ArrowFunctionExpression") {
105
105
 
106
106
  // `=>` token
107
- loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start;
107
+ loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc;
108
108
  } else if (
109
109
  node.parent.type === "MethodDefinition" ||
110
110
  (node.parent.type === "Property" && node.parent.method)
111
111
  ) {
112
112
 
113
113
  // Method name.
114
- loc = node.parent.key.loc.start;
114
+ loc = node.parent.key.loc;
115
115
  } else {
116
116
 
117
117
  // Function name or `function` keyword.
118
- loc = (node.id || node).loc.start;
118
+ loc = (node.id || context.getSourceCode().getFirstToken(node)).loc;
119
119
  }
120
120
 
121
121
  if (!name) {
@@ -94,7 +94,7 @@ module.exports = {
94
94
 
95
95
  // Don't perform any fixes if there are comments inside the brackets.
96
96
  if (sourceCode.commentsExistBetween(leftBracket, rightBracket)) {
97
- return; // eslint-disable-line eslint-plugin/fixer-return -- false positive
97
+ return;
98
98
  }
99
99
 
100
100
  // Replace the brackets by an identifier.
@@ -154,12 +154,12 @@ module.exports = {
154
154
 
155
155
  // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression.
156
156
  if (node.object.type === "Identifier" && node.object.name === "let" && !node.optional) {
157
- return; // eslint-disable-line eslint-plugin/fixer-return -- false positive
157
+ return;
158
158
  }
159
159
 
160
160
  // Don't perform any fixes if there are comments between the dot and the property name.
161
161
  if (sourceCode.commentsExistBetween(dotToken, node.property)) {
162
- return; // eslint-disable-line eslint-plugin/fixer-return -- false positive
162
+ return;
163
163
  }
164
164
 
165
165
  // Replace the identifier to brackets.
@@ -1177,8 +1177,7 @@ module.exports = {
1177
1177
  offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
1178
1178
  offsets.setDesiredOffset(colonToken, firstToken, 1);
1179
1179
 
1180
- offsets.setDesiredOffset(firstConsequentToken, firstToken,
1181
- firstConsequentToken.type === "Punctuator" &&
1180
+ offsets.setDesiredOffset(firstConsequentToken, firstToken, firstConsequentToken.type === "Punctuator" &&
1182
1181
  options.offsetTernaryExpressions ? 2 : 1);
1183
1182
 
1184
1183
  /*
@@ -1204,8 +1203,7 @@ module.exports = {
1204
1203
  * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
1205
1204
  * having no expected indentation.
1206
1205
  */
1207
- offsets.setDesiredOffset(firstAlternateToken, firstToken,
1208
- firstAlternateToken.type === "Punctuator" &&
1206
+ offsets.setDesiredOffset(firstAlternateToken, firstToken, firstAlternateToken.type === "Punctuator" &&
1209
1207
  options.offsetTernaryExpressions ? 2 : 1);
1210
1208
  }
1211
1209
  }