eslint 8.55.0 → 9.0.0-alpha.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 (54) hide show
  1. package/README.md +15 -15
  2. package/conf/rule-type-list.json +3 -1
  3. package/lib/api.js +1 -1
  4. package/lib/cli-engine/cli-engine.js +15 -4
  5. package/lib/cli-engine/formatters/formatters-meta.json +1 -29
  6. package/lib/cli.js +52 -10
  7. package/lib/config/default-config.js +3 -0
  8. package/lib/config/flat-config-array.js +0 -20
  9. package/lib/config/flat-config-helpers.js +41 -20
  10. package/lib/config/flat-config-schema.js +57 -26
  11. package/lib/config/rule-validator.js +27 -4
  12. package/lib/eslint/eslint-helpers.js +35 -22
  13. package/lib/eslint/eslint.js +856 -373
  14. package/lib/eslint/index.js +2 -2
  15. package/lib/eslint/legacy-eslint.js +722 -0
  16. package/lib/linter/apply-disable-directives.js +33 -5
  17. package/lib/linter/config-comment-parser.js +36 -2
  18. package/lib/linter/linter.js +100 -120
  19. package/lib/linter/rules.js +6 -15
  20. package/lib/options.js +17 -1
  21. package/lib/rule-tester/rule-tester.js +240 -272
  22. package/lib/rules/index.js +0 -2
  23. package/lib/rules/no-constant-binary-expression.js +1 -1
  24. package/lib/rules/no-constructor-return.js +1 -1
  25. package/lib/rules/no-empty-static-block.js +1 -1
  26. package/lib/rules/no-extra-semi.js +1 -1
  27. package/lib/rules/no-implicit-coercion.js +17 -1
  28. package/lib/rules/no-inner-declarations.js +1 -1
  29. package/lib/rules/no-invalid-regexp.js +1 -1
  30. package/lib/rules/no-invalid-this.js +1 -1
  31. package/lib/rules/no-mixed-spaces-and-tabs.js +1 -1
  32. package/lib/rules/no-new-native-nonconstructor.js +1 -1
  33. package/lib/rules/no-new-symbol.js +8 -1
  34. package/lib/rules/no-promise-executor-return.js +9 -6
  35. package/lib/rules/no-restricted-properties.js +15 -28
  36. package/lib/rules/no-sequences.js +1 -0
  37. package/lib/rules/no-unused-private-class-members.js +1 -1
  38. package/lib/shared/config-validator.js +44 -11
  39. package/lib/shared/severity.js +49 -0
  40. package/lib/shared/types.js +1 -1
  41. package/lib/source-code/source-code.js +3 -102
  42. package/lib/unsupported-api.js +3 -5
  43. package/package.json +12 -14
  44. package/lib/cli-engine/formatters/checkstyle.js +0 -60
  45. package/lib/cli-engine/formatters/compact.js +0 -60
  46. package/lib/cli-engine/formatters/jslint-xml.js +0 -41
  47. package/lib/cli-engine/formatters/junit.js +0 -82
  48. package/lib/cli-engine/formatters/tap.js +0 -95
  49. package/lib/cli-engine/formatters/unix.js +0 -58
  50. package/lib/cli-engine/formatters/visualstudio.js +0 -63
  51. package/lib/eslint/flat-eslint.js +0 -1149
  52. package/lib/rule-tester/flat-rule-tester.js +0 -1122
  53. package/lib/rules/require-jsdoc.js +0 -122
  54. package/lib/rules/valid-jsdoc.js +0 -516
@@ -1,7 +1,6 @@
1
1
  /**
2
- * @fileoverview Main API Class
3
- * @author Kai Cataldo
4
- * @author Toru Nagashima
2
+ * @fileoverview Main class using flat config
3
+ * @author Nicholas C. Zakas
5
4
  */
6
5
 
7
6
  "use strict";
@@ -10,39 +9,60 @@
10
9
  // Requirements
11
10
  //------------------------------------------------------------------------------
12
11
 
12
+ // Note: Node.js 12 does not support fs/promises.
13
+ const fs = require("fs").promises;
14
+ const { existsSync } = require("fs");
13
15
  const path = require("path");
14
- const fs = require("fs");
15
- const { promisify } = require("util");
16
- const { CLIEngine, getCLIEngineInternalSlots } = require("../cli-engine/cli-engine");
17
- const BuiltinRules = require("../rules");
16
+ const findUp = require("find-up");
17
+ const { version } = require("../../package.json");
18
+ const { Linter } = require("../linter");
19
+ const { getRuleFromConfig } = require("../config/flat-config-helpers");
18
20
  const {
19
21
  Legacy: {
20
22
  ConfigOps: {
21
23
  getRuleSeverity
22
- }
24
+ },
25
+ ModuleResolver,
26
+ naming
23
27
  }
24
28
  } = require("@eslint/eslintrc");
25
- const { version } = require("../../package.json");
29
+
30
+ const {
31
+ findFiles,
32
+ getCacheFile,
33
+
34
+ isNonEmptyString,
35
+ isArrayOfNonEmptyString,
36
+
37
+ createIgnoreResult,
38
+ isErrorMessage,
39
+
40
+ processOptions
41
+ } = require("./eslint-helpers");
42
+ const { pathToFileURL } = require("url");
43
+ const { FlatConfigArray } = require("../config/flat-config-array");
44
+ const LintResultCache = require("../cli-engine/lint-result-cache");
45
+
46
+ /*
47
+ * This is necessary to allow overwriting writeFile for testing purposes.
48
+ * We can just use fs/promises once we drop Node.js 12 support.
49
+ */
26
50
 
27
51
  //------------------------------------------------------------------------------
28
52
  // Typedefs
29
53
  //------------------------------------------------------------------------------
30
54
 
31
- /** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */
32
- /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
55
+ // For VSCode IntelliSense
33
56
  /** @typedef {import("../shared/types").ConfigData} ConfigData */
57
+ /** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
34
58
  /** @typedef {import("../shared/types").LintMessage} LintMessage */
35
- /** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */
36
- /** @typedef {import("../shared/types").Plugin} Plugin */
37
- /** @typedef {import("../shared/types").Rule} Rule */
38
59
  /** @typedef {import("../shared/types").LintResult} LintResult */
60
+ /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
61
+ /** @typedef {import("../shared/types").Plugin} Plugin */
39
62
  /** @typedef {import("../shared/types").ResultsMeta} ResultsMeta */
40
-
41
- /**
42
- * The main formatter object.
43
- * @typedef LoadedFormatter
44
- * @property {(results: LintResult[], resultsMeta: ResultsMeta) => string | Promise<string>} format format function.
45
- */
63
+ /** @typedef {import("../shared/types").RuleConf} RuleConf */
64
+ /** @typedef {import("../shared/types").Rule} Rule */
65
+ /** @typedef {ReturnType<ConfigArray.extractConfig>} ExtractedConfig */
46
66
 
47
67
  /**
48
68
  * The options with which to configure the ESLint instance.
@@ -54,270 +74,79 @@ const { version } = require("../../package.json");
54
74
  * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
55
75
  * @property {string} [cwd] The value to use for the current working directory.
56
76
  * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
57
- * @property {string[]} [extensions] An array of file extensions to check.
58
77
  * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
59
78
  * @property {string[]} [fixTypes] Array of rule types to apply fixes for.
60
79
  * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
61
- * @property {boolean} [ignore] False disables use of .eslintignore.
62
- * @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
80
+ * @property {boolean} [ignore] False disables all ignore patterns except for the default ones.
81
+ * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to config ignores. These patterns are relative to `cwd`.
63
82
  * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
64
- * @property {string} [overrideConfigFile] The configuration file to use.
65
- * @property {Record<string,Plugin>|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation.
66
- * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
67
- * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD.
68
- * @property {string[]} [rulePaths] An array of directories to load custom rules from.
69
- * @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files.
70
- */
71
-
72
- /**
73
- * A rules metadata object.
74
- * @typedef {Object} RulesMeta
75
- * @property {string} id The plugin ID.
76
- * @property {Object} definition The plugin definition.
77
- */
78
-
79
- /**
80
- * Private members for the `ESLint` instance.
81
- * @typedef {Object} ESLintPrivateMembers
82
- * @property {CLIEngine} cliEngine The wrapped CLIEngine instance.
83
- * @property {ESLintOptions} options The options used to instantiate the ESLint instance.
83
+ * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy;
84
+ * doesn't do any config file lookup when `true`; considered to be a config filename
85
+ * when a string.
86
+ * @property {Record<string,Plugin>} [plugins] An array of plugin implementations.
87
+ * @property {boolean} warnIgnored Show warnings when the file list includes ignored files
88
+ * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause
89
+ * the linting operation to short circuit and not report any failures.
84
90
  */
85
91
 
86
92
  //------------------------------------------------------------------------------
87
93
  // Helpers
88
94
  //------------------------------------------------------------------------------
89
95
 
90
- const writeFile = promisify(fs.writeFile);
91
-
92
- /**
93
- * The map with which to store private class members.
94
- * @type {WeakMap<ESLint, ESLintPrivateMembers>}
95
- */
96
- const privateMembersMap = new WeakMap();
97
-
98
- /**
99
- * Check if a given value is a non-empty string or not.
100
- * @param {any} x The value to check.
101
- * @returns {boolean} `true` if `x` is a non-empty string.
102
- */
103
- function isNonEmptyString(x) {
104
- return typeof x === "string" && x.trim() !== "";
105
- }
106
-
107
- /**
108
- * Check if a given value is an array of non-empty strings or not.
109
- * @param {any} x The value to check.
110
- * @returns {boolean} `true` if `x` is an array of non-empty strings.
111
- */
112
- function isArrayOfNonEmptyString(x) {
113
- return Array.isArray(x) && x.every(isNonEmptyString);
114
- }
115
-
116
- /**
117
- * Check if a given value is a valid fix type or not.
118
- * @param {any} x The value to check.
119
- * @returns {boolean} `true` if `x` is valid fix type.
120
- */
121
- function isFixType(x) {
122
- return x === "directive" || x === "problem" || x === "suggestion" || x === "layout";
123
- }
96
+ const FLAT_CONFIG_FILENAMES = [
97
+ "eslint.config.js",
98
+ "eslint.config.mjs",
99
+ "eslint.config.cjs"
100
+ ];
101
+ const debug = require("debug")("eslint:eslint");
102
+ const privateMembers = new WeakMap();
103
+ const importedConfigFileModificationTime = new Map();
104
+ const removedFormatters = new Set([
105
+ "checkstyle",
106
+ "codeframe",
107
+ "compact",
108
+ "jslint-xml",
109
+ "junit",
110
+ "table",
111
+ "tap",
112
+ "unix",
113
+ "visualstudio"
114
+ ]);
124
115
 
125
116
  /**
126
- * Check if a given value is an array of fix types or not.
127
- * @param {any} x The value to check.
128
- * @returns {boolean} `true` if `x` is an array of fix types.
117
+ * It will calculate the error and warning count for collection of messages per file
118
+ * @param {LintMessage[]} messages Collection of messages
119
+ * @returns {Object} Contains the stats
120
+ * @private
129
121
  */
130
- function isFixTypeArray(x) {
131
- return Array.isArray(x) && x.every(isFixType);
132
- }
133
-
134
- /**
135
- * The error for invalid options.
136
- */
137
- class ESLintInvalidOptionsError extends Error {
138
- constructor(messages) {
139
- super(`Invalid Options:\n- ${messages.join("\n- ")}`);
140
- this.code = "ESLINT_INVALID_OPTIONS";
141
- Error.captureStackTrace(this, ESLintInvalidOptionsError);
142
- }
143
- }
144
-
145
- /**
146
- * Validates and normalizes options for the wrapped CLIEngine instance.
147
- * @param {ESLintOptions} options The options to process.
148
- * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
149
- * @returns {ESLintOptions} The normalized options.
150
- */
151
- function processOptions({
152
- allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
153
- baseConfig = null,
154
- cache = false,
155
- cacheLocation = ".eslintcache",
156
- cacheStrategy = "metadata",
157
- cwd = process.cwd(),
158
- errorOnUnmatchedPattern = true,
159
- extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature.
160
- fix = false,
161
- fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property.
162
- globInputPaths = true,
163
- ignore = true,
164
- ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT.
165
- overrideConfig = null,
166
- overrideConfigFile = null,
167
- plugins = {},
168
- reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that.
169
- resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature.
170
- rulePaths = [],
171
- useEslintrc = true,
172
- ...unknownOptions
173
- }) {
174
- const errors = [];
175
- const unknownOptionKeys = Object.keys(unknownOptions);
176
-
177
- if (unknownOptionKeys.length >= 1) {
178
- errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
179
- if (unknownOptionKeys.includes("cacheFile")) {
180
- errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead.");
181
- }
182
- if (unknownOptionKeys.includes("configFile")) {
183
- errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead.");
184
- }
185
- if (unknownOptionKeys.includes("envs")) {
186
- errors.push("'envs' has been removed. Please use the 'overrideConfig.env' option instead.");
187
- }
188
- if (unknownOptionKeys.includes("globals")) {
189
- errors.push("'globals' has been removed. Please use the 'overrideConfig.globals' option instead.");
190
- }
191
- if (unknownOptionKeys.includes("ignorePattern")) {
192
- errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.");
193
- }
194
- if (unknownOptionKeys.includes("parser")) {
195
- errors.push("'parser' has been removed. Please use the 'overrideConfig.parser' option instead.");
196
- }
197
- if (unknownOptionKeys.includes("parserOptions")) {
198
- errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead.");
199
- }
200
- if (unknownOptionKeys.includes("rules")) {
201
- errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead.");
202
- }
203
- }
204
- if (typeof allowInlineConfig !== "boolean") {
205
- errors.push("'allowInlineConfig' must be a boolean.");
206
- }
207
- if (typeof baseConfig !== "object") {
208
- errors.push("'baseConfig' must be an object or null.");
209
- }
210
- if (typeof cache !== "boolean") {
211
- errors.push("'cache' must be a boolean.");
212
- }
213
- if (!isNonEmptyString(cacheLocation)) {
214
- errors.push("'cacheLocation' must be a non-empty string.");
215
- }
216
- if (
217
- cacheStrategy !== "metadata" &&
218
- cacheStrategy !== "content"
219
- ) {
220
- errors.push("'cacheStrategy' must be any of \"metadata\", \"content\".");
221
- }
222
- if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
223
- errors.push("'cwd' must be an absolute path.");
224
- }
225
- if (typeof errorOnUnmatchedPattern !== "boolean") {
226
- errors.push("'errorOnUnmatchedPattern' must be a boolean.");
227
- }
228
- if (!isArrayOfNonEmptyString(extensions) && extensions !== null) {
229
- errors.push("'extensions' must be an array of non-empty strings or null.");
230
- }
231
- if (typeof fix !== "boolean" && typeof fix !== "function") {
232
- errors.push("'fix' must be a boolean or a function.");
233
- }
234
- if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
235
- errors.push("'fixTypes' must be an array of any of \"directive\", \"problem\", \"suggestion\", and \"layout\".");
236
- }
237
- if (typeof globInputPaths !== "boolean") {
238
- errors.push("'globInputPaths' must be a boolean.");
239
- }
240
- if (typeof ignore !== "boolean") {
241
- errors.push("'ignore' must be a boolean.");
242
- }
243
- if (!isNonEmptyString(ignorePath) && ignorePath !== null) {
244
- errors.push("'ignorePath' must be a non-empty string or null.");
245
- }
246
- if (typeof overrideConfig !== "object") {
247
- errors.push("'overrideConfig' must be an object or null.");
248
- }
249
- if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) {
250
- errors.push("'overrideConfigFile' must be a non-empty string or null.");
251
- }
252
- if (typeof plugins !== "object") {
253
- errors.push("'plugins' must be an object or null.");
254
- } else if (plugins !== null && Object.keys(plugins).includes("")) {
255
- errors.push("'plugins' must not include an empty string.");
256
- }
257
- if (Array.isArray(plugins)) {
258
- errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.");
259
- }
260
- if (
261
- reportUnusedDisableDirectives !== "error" &&
262
- reportUnusedDisableDirectives !== "warn" &&
263
- reportUnusedDisableDirectives !== "off" &&
264
- reportUnusedDisableDirectives !== null
265
- ) {
266
- errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null.");
267
- }
268
- if (
269
- !isNonEmptyString(resolvePluginsRelativeTo) &&
270
- resolvePluginsRelativeTo !== null
271
- ) {
272
- errors.push("'resolvePluginsRelativeTo' must be a non-empty string or null.");
273
- }
274
- if (!isArrayOfNonEmptyString(rulePaths)) {
275
- errors.push("'rulePaths' must be an array of non-empty strings.");
276
- }
277
- if (typeof useEslintrc !== "boolean") {
278
- errors.push("'useEslintrc' must be a boolean.");
279
- }
280
-
281
- if (errors.length > 0) {
282
- throw new ESLintInvalidOptionsError(errors);
283
- }
284
-
285
- return {
286
- allowInlineConfig,
287
- baseConfig,
288
- cache,
289
- cacheLocation,
290
- cacheStrategy,
291
- configFile: overrideConfigFile,
292
- cwd: path.normalize(cwd),
293
- errorOnUnmatchedPattern,
294
- extensions,
295
- fix,
296
- fixTypes,
297
- globInputPaths,
298
- ignore,
299
- ignorePath,
300
- reportUnusedDisableDirectives,
301
- resolvePluginsRelativeTo,
302
- rulePaths,
303
- useEslintrc
122
+ function calculateStatsPerFile(messages) {
123
+ const stat = {
124
+ errorCount: 0,
125
+ fatalErrorCount: 0,
126
+ warningCount: 0,
127
+ fixableErrorCount: 0,
128
+ fixableWarningCount: 0
304
129
  };
305
- }
306
130
 
307
- /**
308
- * Check if a value has one or more properties and that value is not undefined.
309
- * @param {any} obj The value to check.
310
- * @returns {boolean} `true` if `obj` has one or more properties that that value is not undefined.
311
- */
312
- function hasDefinedProperty(obj) {
313
- if (typeof obj === "object" && obj !== null) {
314
- for (const key in obj) {
315
- if (typeof obj[key] !== "undefined") {
316
- return true;
131
+ for (let i = 0; i < messages.length; i++) {
132
+ const message = messages[i];
133
+
134
+ if (message.fatal || message.severity === 2) {
135
+ stat.errorCount++;
136
+ if (message.fatal) {
137
+ stat.fatalErrorCount++;
138
+ }
139
+ if (message.fix) {
140
+ stat.fixableErrorCount++;
141
+ }
142
+ } else {
143
+ stat.warningCount++;
144
+ if (message.fix) {
145
+ stat.fixableWarningCount++;
317
146
  }
318
147
  }
319
148
  }
320
- return false;
149
+ return stat;
321
150
  }
322
151
 
323
152
  /**
@@ -332,62 +161,73 @@ function createRulesMeta(rules) {
332
161
  }, {});
333
162
  }
334
163
 
164
+ /**
165
+ * Return the absolute path of a file named `"__placeholder__.js"` in a given directory.
166
+ * This is used as a replacement for a missing file path.
167
+ * @param {string} cwd An absolute directory path.
168
+ * @returns {string} The absolute path of a file named `"__placeholder__.js"` in the given directory.
169
+ */
170
+ function getPlaceholderPath(cwd) {
171
+ return path.join(cwd, "__placeholder__.js");
172
+ }
173
+
335
174
  /** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
336
175
  const usedDeprecatedRulesCache = new WeakMap();
337
176
 
338
177
  /**
339
178
  * Create used deprecated rule list.
340
- * @param {CLIEngine} cliEngine The CLIEngine instance.
179
+ * @param {CLIEngine} eslint The CLIEngine instance.
341
180
  * @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
342
181
  * @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
343
182
  */
344
- function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) {
183
+ function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) {
345
184
  const {
346
- configArrayFactory,
185
+ configs,
347
186
  options: { cwd }
348
- } = getCLIEngineInternalSlots(cliEngine);
187
+ } = privateMembers.get(eslint);
349
188
  const filePath = path.isAbsolute(maybeFilePath)
350
189
  ? maybeFilePath
351
- : path.join(cwd, "__placeholder__.js");
352
- const configArray = configArrayFactory.getConfigArrayForFile(filePath);
353
- const config = configArray.extractConfig(filePath);
190
+ : getPlaceholderPath(cwd);
191
+ const config = configs.getConfig(filePath);
354
192
 
355
193
  // Most files use the same config, so cache it.
356
- if (!usedDeprecatedRulesCache.has(config)) {
357
- const pluginRules = configArray.pluginRules;
194
+ if (config && !usedDeprecatedRulesCache.has(config)) {
358
195
  const retv = [];
359
196
 
360
- for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
361
- if (getRuleSeverity(ruleConf) === 0) {
362
- continue;
363
- }
364
- const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId);
365
- const meta = rule && rule.meta;
366
-
367
- if (meta && meta.deprecated) {
368
- retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
197
+ if (config.rules) {
198
+ for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
199
+ if (getRuleSeverity(ruleConf) === 0) {
200
+ continue;
201
+ }
202
+ const rule = getRuleFromConfig(ruleId, config);
203
+ const meta = rule && rule.meta;
204
+
205
+ if (meta && meta.deprecated) {
206
+ retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
207
+ }
369
208
  }
370
209
  }
371
210
 
211
+
372
212
  usedDeprecatedRulesCache.set(config, Object.freeze(retv));
373
213
  }
374
214
 
375
- return usedDeprecatedRulesCache.get(config);
215
+ return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]);
376
216
  }
377
217
 
378
218
  /**
379
219
  * Processes the linting results generated by a CLIEngine linting report to
380
220
  * match the ESLint class's API.
381
- * @param {CLIEngine} cliEngine The CLIEngine instance.
221
+ * @param {CLIEngine} eslint The CLIEngine instance.
382
222
  * @param {CLIEngineLintReport} report The CLIEngine linting report to process.
383
223
  * @returns {LintResult[]} The processed linting results.
384
224
  */
385
- function processCLIEngineLintReport(cliEngine, { results }) {
225
+ function processLintReport(eslint, { results }) {
386
226
  const descriptor = {
387
227
  configurable: true,
388
228
  enumerable: true,
389
229
  get() {
390
- return getOrFindUsedDeprecatedRules(cliEngine, this.filePath);
230
+ return getOrFindUsedDeprecatedRules(eslint, this.filePath);
391
231
  }
392
232
  };
393
233
 
@@ -417,7 +257,311 @@ function compareResultsByFilePath(a, b) {
417
257
  }
418
258
 
419
259
  /**
420
- * Main API.
260
+ * Searches from the current working directory up until finding the
261
+ * given flat config filename.
262
+ * @param {string} cwd The current working directory to search from.
263
+ * @returns {Promise<string|undefined>} The filename if found or `undefined` if not.
264
+ */
265
+ function findFlatConfigFile(cwd) {
266
+ return findUp(
267
+ FLAT_CONFIG_FILENAMES,
268
+ { cwd }
269
+ );
270
+ }
271
+
272
+ /**
273
+ * Load the config array from the given filename.
274
+ * @param {string} filePath The filename to load from.
275
+ * @returns {Promise<any>} The config loaded from the config file.
276
+ */
277
+ async function loadFlatConfigFile(filePath) {
278
+ debug(`Loading config from ${filePath}`);
279
+
280
+ const fileURL = pathToFileURL(filePath);
281
+
282
+ debug(`Config file URL is ${fileURL}`);
283
+
284
+ const mtime = (await fs.stat(filePath)).mtime.getTime();
285
+
286
+ /*
287
+ * Append a query with the config file's modification time (`mtime`) in order
288
+ * to import the current version of the config file. Without the query, `import()` would
289
+ * cache the config file module by the pathname only, and then always return
290
+ * the same version (the one that was actual when the module was imported for the first time).
291
+ *
292
+ * This ensures that the config file module is loaded and executed again
293
+ * if it has been changed since the last time it was imported.
294
+ * If it hasn't been changed, `import()` will just return the cached version.
295
+ *
296
+ * Note that we should not overuse queries (e.g., by appending the current time
297
+ * to always reload the config file module) as that could cause memory leaks
298
+ * because entries are never removed from the import cache.
299
+ */
300
+ fileURL.searchParams.append("mtime", mtime);
301
+
302
+ /*
303
+ * With queries, we can bypass the import cache. However, when import-ing a CJS module,
304
+ * Node.js uses the require infrastructure under the hood. That includes the require cache,
305
+ * which caches the config file module by its file path (queries have no effect).
306
+ * Therefore, we also need to clear the require cache before importing the config file module.
307
+ * In order to get the same behavior with ESM and CJS config files, in particular - to reload
308
+ * the config file only if it has been changed, we track file modification times and clear
309
+ * the require cache only if the file has been changed.
310
+ */
311
+ if (importedConfigFileModificationTime.get(filePath) !== mtime) {
312
+ delete require.cache[filePath];
313
+ }
314
+
315
+ const config = (await import(fileURL)).default;
316
+
317
+ importedConfigFileModificationTime.set(filePath, mtime);
318
+
319
+ return config;
320
+ }
321
+
322
+ /**
323
+ * Determines which config file to use. This is determined by seeing if an
324
+ * override config file was passed, and if so, using it; otherwise, as long
325
+ * as override config file is not explicitly set to `false`, it will search
326
+ * upwards from the cwd for a file named `eslint.config.js`.
327
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
328
+ * @returns {{configFilePath:string|undefined,basePath:string,error:Error|null}} Location information for
329
+ * the config file.
330
+ */
331
+ async function locateConfigFileToUse({ configFile, cwd }) {
332
+
333
+ // determine where to load config file from
334
+ let configFilePath;
335
+ let basePath = cwd;
336
+ let error = null;
337
+
338
+ if (typeof configFile === "string") {
339
+ debug(`Override config file path is ${configFile}`);
340
+ configFilePath = path.resolve(cwd, configFile);
341
+ } else if (configFile !== false) {
342
+ debug("Searching for eslint.config.js");
343
+ configFilePath = await findFlatConfigFile(cwd);
344
+
345
+ if (configFilePath) {
346
+ basePath = path.resolve(path.dirname(configFilePath));
347
+ } else {
348
+ error = new Error("Could not find config file.");
349
+ }
350
+
351
+ }
352
+
353
+ return {
354
+ configFilePath,
355
+ basePath,
356
+ error
357
+ };
358
+
359
+ }
360
+
361
+ /**
362
+ * Calculates the config array for this run based on inputs.
363
+ * @param {ESLint} eslint The instance to create the config array for.
364
+ * @param {import("./eslint").ESLintOptions} options The ESLint instance options.
365
+ * @returns {FlatConfigArray} The config array for `eslint``.
366
+ */
367
+ async function calculateConfigArray(eslint, {
368
+ cwd,
369
+ baseConfig,
370
+ overrideConfig,
371
+ configFile,
372
+ ignore: shouldIgnore,
373
+ ignorePatterns
374
+ }) {
375
+
376
+ // check for cached instance
377
+ const slots = privateMembers.get(eslint);
378
+
379
+ if (slots.configs) {
380
+ return slots.configs;
381
+ }
382
+
383
+ const { configFilePath, basePath, error } = await locateConfigFileToUse({ configFile, cwd });
384
+
385
+ // config file is required to calculate config
386
+ if (error) {
387
+ throw error;
388
+ }
389
+
390
+ const configs = new FlatConfigArray(baseConfig || [], { basePath, shouldIgnore });
391
+
392
+ // load config file
393
+ if (configFilePath) {
394
+ const fileConfig = await loadFlatConfigFile(configFilePath);
395
+
396
+ if (Array.isArray(fileConfig)) {
397
+ configs.push(...fileConfig);
398
+ } else {
399
+ configs.push(fileConfig);
400
+ }
401
+ }
402
+
403
+ // add in any configured defaults
404
+ configs.push(...slots.defaultConfigs);
405
+
406
+ // append command line ignore patterns
407
+ if (ignorePatterns && ignorePatterns.length > 0) {
408
+
409
+ let relativeIgnorePatterns;
410
+
411
+ /*
412
+ * If the config file basePath is different than the cwd, then
413
+ * the ignore patterns won't work correctly. Here, we adjust the
414
+ * ignore pattern to include the correct relative path. Patterns
415
+ * passed as `ignorePatterns` are relative to the cwd, whereas
416
+ * the config file basePath can be an ancestor of the cwd.
417
+ */
418
+ if (basePath === cwd) {
419
+ relativeIgnorePatterns = ignorePatterns;
420
+ } else {
421
+
422
+ const relativeIgnorePath = path.relative(basePath, cwd);
423
+
424
+ relativeIgnorePatterns = ignorePatterns.map(pattern => {
425
+ const negated = pattern.startsWith("!");
426
+ const basePattern = negated ? pattern.slice(1) : pattern;
427
+
428
+ return (negated ? "!" : "") +
429
+ path.posix.join(relativeIgnorePath, basePattern);
430
+ });
431
+ }
432
+
433
+ /*
434
+ * Ignore patterns are added to the end of the config array
435
+ * so they can override default ignores.
436
+ */
437
+ configs.push({
438
+ ignores: relativeIgnorePatterns
439
+ });
440
+ }
441
+
442
+ if (overrideConfig) {
443
+ if (Array.isArray(overrideConfig)) {
444
+ configs.push(...overrideConfig);
445
+ } else {
446
+ configs.push(overrideConfig);
447
+ }
448
+ }
449
+
450
+ await configs.normalize();
451
+
452
+ // cache the config array for this instance
453
+ slots.configs = configs;
454
+
455
+ return configs;
456
+ }
457
+
458
+ /**
459
+ * Processes an source code using ESLint.
460
+ * @param {Object} config The config object.
461
+ * @param {string} config.text The source code to verify.
462
+ * @param {string} config.cwd The path to the current working directory.
463
+ * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses `<text>`.
464
+ * @param {FlatConfigArray} config.configs The config.
465
+ * @param {boolean} config.fix If `true` then it does fix.
466
+ * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments.
467
+ * @param {Function} config.ruleFilter A predicate function to filter which rules should be run.
468
+ * @param {Linter} config.linter The linter instance to verify.
469
+ * @returns {LintResult} The result of linting.
470
+ * @private
471
+ */
472
+ function verifyText({
473
+ text,
474
+ cwd,
475
+ filePath: providedFilePath,
476
+ configs,
477
+ fix,
478
+ allowInlineConfig,
479
+ ruleFilter,
480
+ linter
481
+ }) {
482
+ const filePath = providedFilePath || "<text>";
483
+
484
+ debug(`Lint ${filePath}`);
485
+
486
+ /*
487
+ * Verify.
488
+ * `config.extractConfig(filePath)` requires an absolute path, but `linter`
489
+ * doesn't know CWD, so it gives `linter` an absolute path always.
490
+ */
491
+ const filePathToVerify = filePath === "<text>" ? getPlaceholderPath(cwd) : filePath;
492
+ const { fixed, messages, output } = linter.verifyAndFix(
493
+ text,
494
+ configs,
495
+ {
496
+ allowInlineConfig,
497
+ filename: filePathToVerify,
498
+ fix,
499
+ ruleFilter,
500
+
501
+ /**
502
+ * Check if the linter should adopt a given code block or not.
503
+ * @param {string} blockFilename The virtual filename of a code block.
504
+ * @returns {boolean} `true` if the linter should adopt the code block.
505
+ */
506
+ filterCodeBlock(blockFilename) {
507
+ return configs.isExplicitMatch(blockFilename);
508
+ }
509
+ }
510
+ );
511
+
512
+ // Tweak and return.
513
+ const result = {
514
+ filePath: filePath === "<text>" ? filePath : path.resolve(filePath),
515
+ messages,
516
+ suppressedMessages: linter.getSuppressedMessages(),
517
+ ...calculateStatsPerFile(messages)
518
+ };
519
+
520
+ if (fixed) {
521
+ result.output = output;
522
+ }
523
+
524
+ if (
525
+ result.errorCount + result.warningCount > 0 &&
526
+ typeof result.output === "undefined"
527
+ ) {
528
+ result.source = text;
529
+ }
530
+
531
+ return result;
532
+ }
533
+
534
+ /**
535
+ * Checks whether a message's rule type should be fixed.
536
+ * @param {LintMessage} message The message to check.
537
+ * @param {FlatConfig} config The config for the file that generated the message.
538
+ * @param {string[]} fixTypes An array of fix types to check.
539
+ * @returns {boolean} Whether the message should be fixed.
540
+ */
541
+ function shouldMessageBeFixed(message, config, fixTypes) {
542
+ if (!message.ruleId) {
543
+ return fixTypes.has("directive");
544
+ }
545
+
546
+ const rule = message.ruleId && getRuleFromConfig(message.ruleId, config);
547
+
548
+ return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type));
549
+ }
550
+
551
+ /**
552
+ * Creates an error to be thrown when an array of results passed to `getRulesMetaForResults` was not created by the current engine.
553
+ * @returns {TypeError} An error object.
554
+ */
555
+ function createExtraneousResultsError() {
556
+ return new TypeError("Results object was not created from this ESLint instance.");
557
+ }
558
+
559
+ //-----------------------------------------------------------------------------
560
+ // Main API
561
+ //-----------------------------------------------------------------------------
562
+
563
+ /**
564
+ * Primary Node.js API for ESLint.
421
565
  */
422
566
  class ESLint {
423
567
 
@@ -426,35 +570,49 @@ class ESLint {
426
570
  * @param {ESLintOptions} options The options for this instance.
427
571
  */
428
572
  constructor(options = {}) {
573
+
574
+ const defaultConfigs = [];
429
575
  const processedOptions = processOptions(options);
430
- const cliEngine = new CLIEngine(processedOptions, { preloadedPlugins: options.plugins });
431
- const {
432
- configArrayFactory,
433
- lastConfigArrays
434
- } = getCLIEngineInternalSlots(cliEngine);
435
- let updated = false;
576
+ const linter = new Linter({
577
+ cwd: processedOptions.cwd,
578
+ configType: "flat"
579
+ });
436
580
 
437
- /*
438
- * Address `overrideConfig` to set override config.
439
- * Operate the `configArrayFactory` internal slot directly because this
440
- * functionality doesn't exist as the public API of CLIEngine.
581
+ const cacheFilePath = getCacheFile(
582
+ processedOptions.cacheLocation,
583
+ processedOptions.cwd
584
+ );
585
+
586
+ const lintResultCache = processedOptions.cache
587
+ ? new LintResultCache(cacheFilePath, processedOptions.cacheStrategy)
588
+ : null;
589
+
590
+ privateMembers.set(this, {
591
+ options: processedOptions,
592
+ linter,
593
+ cacheFilePath,
594
+ lintResultCache,
595
+ defaultConfigs,
596
+ configs: null
597
+ });
598
+
599
+ /**
600
+ * If additional plugins are passed in, add that to the default
601
+ * configs for this instance.
441
602
  */
442
- if (hasDefinedProperty(options.overrideConfig)) {
443
- configArrayFactory.setOverrideConfig(options.overrideConfig);
444
- updated = true;
445
- }
603
+ if (options.plugins) {
604
+
605
+ const plugins = {};
606
+
607
+ for (const [pluginName, plugin] of Object.entries(options.plugins)) {
608
+ plugins[naming.getShorthandName(pluginName, "eslint-plugin")] = plugin;
609
+ }
446
610
 
447
- // Update caches.
448
- if (updated) {
449
- configArrayFactory.clearCache();
450
- lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
611
+ defaultConfigs.push({
612
+ plugins
613
+ });
451
614
  }
452
615
 
453
- // Initialize private properties.
454
- privateMembersMap.set(this, {
455
- cliEngine,
456
- options: processedOptions
457
- });
458
616
  }
459
617
 
460
618
  /**
@@ -486,7 +644,7 @@ class ESLint {
486
644
  path.isAbsolute(result.filePath)
487
645
  );
488
646
  })
489
- .map(r => writeFile(r.filePath, r.output))
647
+ .map(r => fs.writeFile(r.filePath, r.output))
490
648
  );
491
649
  }
492
650
 
@@ -496,60 +654,286 @@ class ESLint {
496
654
  * @returns {LintResult[]} The filtered results.
497
655
  */
498
656
  static getErrorResults(results) {
499
- return CLIEngine.getErrorResults(results);
657
+ const filtered = [];
658
+
659
+ results.forEach(result => {
660
+ const filteredMessages = result.messages.filter(isErrorMessage);
661
+ const filteredSuppressedMessages = result.suppressedMessages.filter(isErrorMessage);
662
+
663
+ if (filteredMessages.length > 0) {
664
+ filtered.push({
665
+ ...result,
666
+ messages: filteredMessages,
667
+ suppressedMessages: filteredSuppressedMessages,
668
+ errorCount: filteredMessages.length,
669
+ warningCount: 0,
670
+ fixableErrorCount: result.fixableErrorCount,
671
+ fixableWarningCount: 0
672
+ });
673
+ }
674
+ });
675
+
676
+ return filtered;
500
677
  }
501
678
 
502
679
  /**
503
680
  * Returns meta objects for each rule represented in the lint results.
504
681
  * @param {LintResult[]} results The results to fetch rules meta for.
505
682
  * @returns {Object} A mapping of ruleIds to rule meta objects.
683
+ * @throws {TypeError} When the results object wasn't created from this ESLint instance.
684
+ * @throws {TypeError} When a plugin or rule is missing.
506
685
  */
507
686
  getRulesMetaForResults(results) {
508
687
 
509
- const resultRuleIds = new Set();
688
+ // short-circuit simple case
689
+ if (results.length === 0) {
690
+ return {};
691
+ }
510
692
 
511
- // first gather all ruleIds from all results
693
+ const resultRules = new Map();
694
+ const {
695
+ configs,
696
+ options: { cwd }
697
+ } = privateMembers.get(this);
512
698
 
513
- for (const result of results) {
514
- for (const { ruleId } of result.messages) {
515
- resultRuleIds.add(ruleId);
516
- }
517
- for (const { ruleId } of result.suppressedMessages) {
518
- resultRuleIds.add(ruleId);
519
- }
699
+ /*
700
+ * We can only accurately return rules meta information for linting results if the
701
+ * results were created by this instance. Otherwise, the necessary rules data is
702
+ * not available. So if the config array doesn't already exist, just throw an error
703
+ * to let the user know we can't do anything here.
704
+ */
705
+ if (!configs) {
706
+ throw createExtraneousResultsError();
520
707
  }
521
708
 
522
- // create a map of all rules in the results
523
-
524
- const { cliEngine } = privateMembersMap.get(this);
525
- const rules = cliEngine.getRules();
526
- const resultRules = new Map();
709
+ for (const result of results) {
527
710
 
528
- for (const [ruleId, rule] of rules) {
529
- if (resultRuleIds.has(ruleId)) {
530
- resultRules.set(ruleId, rule);
711
+ /*
712
+ * Normalize filename for <text>.
713
+ */
714
+ const filePath = result.filePath === "<text>"
715
+ ? getPlaceholderPath(cwd) : result.filePath;
716
+ const allMessages = result.messages.concat(result.suppressedMessages);
717
+
718
+ for (const { ruleId } of allMessages) {
719
+ if (!ruleId) {
720
+ continue;
721
+ }
722
+
723
+ /*
724
+ * All of the plugin and rule information is contained within the
725
+ * calculated config for the given file.
726
+ */
727
+ const config = configs.getConfig(filePath);
728
+
729
+ if (!config) {
730
+ throw createExtraneousResultsError();
731
+ }
732
+ const rule = getRuleFromConfig(ruleId, config);
733
+
734
+ // ignore unknown rules
735
+ if (rule) {
736
+ resultRules.set(ruleId, rule);
737
+ }
531
738
  }
532
739
  }
533
740
 
534
741
  return createRulesMeta(resultRules);
535
-
536
742
  }
537
743
 
538
744
  /**
539
745
  * Executes the current configuration on an array of file and directory names.
540
- * @param {string[]} patterns An array of file and directory names.
746
+ * @param {string|string[]} patterns An array of file and directory names.
541
747
  * @returns {Promise<LintResult[]>} The results of linting the file patterns given.
542
748
  */
543
749
  async lintFiles(patterns) {
544
- if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
545
- throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
750
+
751
+ let normalizedPatterns = patterns;
752
+ const {
753
+ cacheFilePath,
754
+ lintResultCache,
755
+ linter,
756
+ options: eslintOptions
757
+ } = privateMembers.get(this);
758
+
759
+ /*
760
+ * Special cases:
761
+ * 1. `patterns` is an empty string
762
+ * 2. `patterns` is an empty array
763
+ *
764
+ * In both cases, we use the cwd as the directory to lint.
765
+ */
766
+ if (patterns === "" || Array.isArray(patterns) && patterns.length === 0) {
767
+
768
+ /*
769
+ * Special case: If `passOnNoPatterns` is true, then we just exit
770
+ * without doing any work.
771
+ */
772
+ if (eslintOptions.passOnNoPatterns) {
773
+ return [];
774
+ }
775
+
776
+ normalizedPatterns = ["."];
777
+ } else {
778
+
779
+ if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
780
+ throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
781
+ }
782
+
783
+ if (typeof patterns === "string") {
784
+ normalizedPatterns = [patterns];
785
+ }
786
+ }
787
+
788
+ debug(`Using file patterns: ${normalizedPatterns}`);
789
+
790
+ const configs = await calculateConfigArray(this, eslintOptions);
791
+ const {
792
+ allowInlineConfig,
793
+ cache,
794
+ cwd,
795
+ fix,
796
+ fixTypes,
797
+ ruleFilter,
798
+ globInputPaths,
799
+ errorOnUnmatchedPattern,
800
+ warnIgnored
801
+ } = eslintOptions;
802
+ const startTime = Date.now();
803
+ const fixTypesSet = fixTypes ? new Set(fixTypes) : null;
804
+
805
+ // Delete cache file; should this be done here?
806
+ if (!cache && cacheFilePath) {
807
+ debug(`Deleting cache file at ${cacheFilePath}`);
808
+
809
+ try {
810
+ await fs.unlink(cacheFilePath);
811
+ } catch (error) {
812
+ const errorCode = error && error.code;
813
+
814
+ // Ignore errors when no such file exists or file system is read only (and cache file does not exist)
815
+ if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !existsSync(cacheFilePath))) {
816
+ throw error;
817
+ }
818
+ }
546
819
  }
547
- const { cliEngine } = privateMembersMap.get(this);
548
820
 
549
- return processCLIEngineLintReport(
550
- cliEngine,
551
- cliEngine.executeOnFiles(patterns)
821
+ const filePaths = await findFiles({
822
+ patterns: normalizedPatterns,
823
+ cwd,
824
+ globInputPaths,
825
+ configs,
826
+ errorOnUnmatchedPattern
827
+ });
828
+
829
+ debug(`${filePaths.length} files found in: ${Date.now() - startTime}ms`);
830
+
831
+ /*
832
+ * Because we need to process multiple files, including reading from disk,
833
+ * it is most efficient to start by reading each file via promises so that
834
+ * they can be done in parallel. Then, we can lint the returned text. This
835
+ * ensures we are waiting the minimum amount of time in between lints.
836
+ */
837
+ const results = await Promise.all(
838
+
839
+ filePaths.map(({ filePath, ignored }) => {
840
+
841
+ /*
842
+ * If a filename was entered that matches an ignore
843
+ * pattern, then notify the user.
844
+ */
845
+ if (ignored) {
846
+ if (warnIgnored) {
847
+ return createIgnoreResult(filePath, cwd);
848
+ }
849
+
850
+ return void 0;
851
+ }
852
+
853
+ const config = configs.getConfig(filePath);
854
+
855
+ /*
856
+ * Sometimes a file found through a glob pattern will
857
+ * be ignored. In this case, `config` will be undefined
858
+ * and we just silently ignore the file.
859
+ */
860
+ if (!config) {
861
+ return void 0;
862
+ }
863
+
864
+ // Skip if there is cached result.
865
+ if (lintResultCache) {
866
+ const cachedResult =
867
+ lintResultCache.getCachedLintResults(filePath, config);
868
+
869
+ if (cachedResult) {
870
+ const hadMessages =
871
+ cachedResult.messages &&
872
+ cachedResult.messages.length > 0;
873
+
874
+ if (hadMessages && fix) {
875
+ debug(`Reprocessing cached file to allow autofix: ${filePath}`);
876
+ } else {
877
+ debug(`Skipping file since it hasn't changed: ${filePath}`);
878
+ return cachedResult;
879
+ }
880
+ }
881
+ }
882
+
883
+
884
+ // set up fixer for fixTypes if necessary
885
+ let fixer = fix;
886
+
887
+ if (fix && fixTypesSet) {
888
+
889
+ // save original value of options.fix in case it's a function
890
+ const originalFix = (typeof fix === "function")
891
+ ? fix : () => true;
892
+
893
+ fixer = message => shouldMessageBeFixed(message, config, fixTypesSet) && originalFix(message);
894
+ }
895
+
896
+ return fs.readFile(filePath, "utf8")
897
+ .then(text => {
898
+
899
+ // do the linting
900
+ const result = verifyText({
901
+ text,
902
+ filePath,
903
+ configs,
904
+ cwd,
905
+ fix: fixer,
906
+ allowInlineConfig,
907
+ ruleFilter,
908
+ linter
909
+ });
910
+
911
+ /*
912
+ * Store the lint result in the LintResultCache.
913
+ * NOTE: The LintResultCache will remove the file source and any
914
+ * other properties that are difficult to serialize, and will
915
+ * hydrate those properties back in on future lint runs.
916
+ */
917
+ if (lintResultCache) {
918
+ lintResultCache.setCachedLintResults(filePath, config, result);
919
+ }
920
+
921
+ return result;
922
+ });
923
+
924
+ })
552
925
  );
926
+
927
+ // Persist the cache to disk.
928
+ if (lintResultCache) {
929
+ lintResultCache.reconcile();
930
+ }
931
+
932
+ const finalResults = results.filter(result => !!result);
933
+
934
+ return processLintReport(this, {
935
+ results: finalResults
936
+ });
553
937
  }
554
938
 
555
939
  /**
@@ -561,15 +945,22 @@ class ESLint {
561
945
  * @returns {Promise<LintResult[]>} The results of linting the string of code given.
562
946
  */
563
947
  async lintText(code, options = {}) {
948
+
949
+ // Parameter validation
950
+
564
951
  if (typeof code !== "string") {
565
952
  throw new Error("'code' must be a string");
566
953
  }
954
+
567
955
  if (typeof options !== "object") {
568
956
  throw new Error("'options' must be an object, null, or undefined");
569
957
  }
958
+
959
+ // Options validation
960
+
570
961
  const {
571
962
  filePath,
572
- warnIgnored = false,
963
+ warnIgnored,
573
964
  ...unknownOptions
574
965
  } = options || {};
575
966
 
@@ -582,16 +973,57 @@ class ESLint {
582
973
  if (filePath !== void 0 && !isNonEmptyString(filePath)) {
583
974
  throw new Error("'options.filePath' must be a non-empty string or undefined");
584
975
  }
585
- if (typeof warnIgnored !== "boolean") {
976
+
977
+ if (typeof warnIgnored !== "boolean" && typeof warnIgnored !== "undefined") {
586
978
  throw new Error("'options.warnIgnored' must be a boolean or undefined");
587
979
  }
588
980
 
589
- const { cliEngine } = privateMembersMap.get(this);
981
+ // Now we can get down to linting
982
+
983
+ const {
984
+ linter,
985
+ options: eslintOptions
986
+ } = privateMembers.get(this);
987
+ const configs = await calculateConfigArray(this, eslintOptions);
988
+ const {
989
+ allowInlineConfig,
990
+ cwd,
991
+ fix,
992
+ warnIgnored: constructorWarnIgnored,
993
+ ruleFilter
994
+ } = eslintOptions;
995
+ const results = [];
996
+ const startTime = Date.now();
997
+ const resolvedFilename = path.resolve(cwd, filePath || "__placeholder__.js");
998
+
999
+ // Clear the last used config arrays.
1000
+ if (resolvedFilename && await this.isPathIgnored(resolvedFilename)) {
1001
+ const shouldWarnIgnored = typeof warnIgnored === "boolean" ? warnIgnored : constructorWarnIgnored;
1002
+
1003
+ if (shouldWarnIgnored) {
1004
+ results.push(createIgnoreResult(resolvedFilename, cwd));
1005
+ }
1006
+ } else {
1007
+
1008
+ // Do lint.
1009
+ results.push(verifyText({
1010
+ text: code,
1011
+ filePath: resolvedFilename.endsWith("__placeholder__.js") ? "<text>" : resolvedFilename,
1012
+ configs,
1013
+ cwd,
1014
+ fix,
1015
+ allowInlineConfig,
1016
+ ruleFilter,
1017
+ linter
1018
+ }));
1019
+ }
1020
+
1021
+ debug(`Linting complete in: ${Date.now() - startTime}ms`);
1022
+
1023
+ return processLintReport(this, {
1024
+ results
1025
+ });
590
1026
 
591
- return processCLIEngineLintReport(
592
- cliEngine,
593
- cliEngine.executeOnText(code, filePath, warnIgnored)
594
- );
595
1027
  }
596
1028
 
597
1029
  /**
@@ -605,7 +1037,7 @@ class ESLint {
605
1037
  * - `@foo` → `@foo/eslint-formatter`
606
1038
  * - `@foo/bar` → `@foo/eslint-formatter-bar`
607
1039
  * - A file path ... Load the file.
608
- * @returns {Promise<LoadedFormatter>} A promise resolving to the formatter object.
1040
+ * @returns {Promise<Formatter>} A promise resolving to the formatter object.
609
1041
  * This promise will be rejected if the given formatter was not found or not
610
1042
  * a function.
611
1043
  */
@@ -614,20 +1046,60 @@ class ESLint {
614
1046
  throw new Error("'name' must be a string");
615
1047
  }
616
1048
 
617
- const { cliEngine, options } = privateMembersMap.get(this);
618
- const formatter = cliEngine.getFormatter(name);
1049
+ // replace \ with / for Windows compatibility
1050
+ const normalizedFormatName = name.replace(/\\/gu, "/");
1051
+ const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
1052
+
1053
+ // grab our options
1054
+ const { cwd } = privateMembers.get(this).options;
1055
+
1056
+
1057
+ let formatterPath;
1058
+
1059
+ // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages)
1060
+ if (!namespace && normalizedFormatName.includes("/")) {
1061
+ formatterPath = path.resolve(cwd, normalizedFormatName);
1062
+ } else {
1063
+ try {
1064
+ const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter");
1065
+
1066
+ // TODO: This is pretty dirty...would be nice to clean up at some point.
1067
+ formatterPath = ModuleResolver.resolve(npmFormat, getPlaceholderPath(cwd));
1068
+ } catch {
1069
+ formatterPath = path.resolve(__dirname, "../", "cli-engine", "formatters", `${normalizedFormatName}.js`);
1070
+ }
1071
+ }
1072
+
1073
+ let formatter;
1074
+
1075
+ try {
1076
+ formatter = (await import(pathToFileURL(formatterPath))).default;
1077
+ } catch (ex) {
1078
+
1079
+ // check for formatters that have been removed
1080
+ if (removedFormatters.has(name)) {
1081
+ ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``;
1082
+ } else {
1083
+ ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
1084
+ }
1085
+
1086
+ throw ex;
1087
+ }
1088
+
619
1089
 
620
1090
  if (typeof formatter !== "function") {
621
- throw new Error(`Formatter must be a function, but got a ${typeof formatter}.`);
1091
+ throw new TypeError(`Formatter must be a function, but got a ${typeof formatter}.`);
622
1092
  }
623
1093
 
1094
+ const eslint = this;
1095
+
624
1096
  return {
625
1097
 
626
1098
  /**
627
1099
  * The main formatter method.
628
- * @param {LintResult[]} results The lint results to format.
1100
+ * @param {LintResults[]} results The lint results to format.
629
1101
  * @param {ResultsMeta} resultsMeta Warning count and max threshold.
630
- * @returns {string | Promise<string>} The formatted lint results.
1102
+ * @returns {string} The formatted lint results.
631
1103
  */
632
1104
  format(results, resultsMeta) {
633
1105
  let rulesMeta = null;
@@ -636,12 +1108,10 @@ class ESLint {
636
1108
 
637
1109
  return formatter(results, {
638
1110
  ...resultsMeta,
639
- get cwd() {
640
- return options.cwd;
641
- },
1111
+ cwd,
642
1112
  get rulesMeta() {
643
1113
  if (!rulesMeta) {
644
- rulesMeta = createRulesMeta(cliEngine.getRules());
1114
+ rulesMeta = eslint.getRulesMetaForResults(results);
645
1115
  }
646
1116
 
647
1117
  return rulesMeta;
@@ -656,15 +1126,31 @@ class ESLint {
656
1126
  * This is the same logic used by the ESLint CLI executable to determine
657
1127
  * configuration for each file it processes.
658
1128
  * @param {string} filePath The path of the file to retrieve a config object for.
659
- * @returns {Promise<ConfigData>} A configuration object for the file.
1129
+ * @returns {Promise<ConfigData|undefined>} A configuration object for the file
1130
+ * or `undefined` if there is no configuration data for the object.
660
1131
  */
661
1132
  async calculateConfigForFile(filePath) {
662
1133
  if (!isNonEmptyString(filePath)) {
663
1134
  throw new Error("'filePath' must be a non-empty string");
664
1135
  }
665
- const { cliEngine } = privateMembersMap.get(this);
1136
+ const options = privateMembers.get(this).options;
1137
+ const absolutePath = path.resolve(options.cwd, filePath);
1138
+ const configs = await calculateConfigArray(this, options);
1139
+
1140
+ return configs.getConfig(absolutePath);
1141
+ }
666
1142
 
667
- return cliEngine.getConfigForFile(filePath);
1143
+ /**
1144
+ * Finds the config file being used by this instance based on the options
1145
+ * passed to the constructor.
1146
+ * @returns {string|undefined} The path to the config file being used or
1147
+ * `undefined` if no config file is being used.
1148
+ */
1149
+ async findConfigFile() {
1150
+ const options = privateMembers.get(this).options;
1151
+ const { configFilePath } = await locateConfigFileToUse(options);
1152
+
1153
+ return configFilePath;
668
1154
  }
669
1155
 
670
1156
  /**
@@ -673,28 +1159,25 @@ class ESLint {
673
1159
  * @returns {Promise<boolean>} Whether or not the given path is ignored.
674
1160
  */
675
1161
  async isPathIgnored(filePath) {
676
- if (!isNonEmptyString(filePath)) {
677
- throw new Error("'filePath' must be a non-empty string");
678
- }
679
- const { cliEngine } = privateMembersMap.get(this);
1162
+ const config = await this.calculateConfigForFile(filePath);
680
1163
 
681
- return cliEngine.isPathIgnored(filePath);
1164
+ return config === void 0;
682
1165
  }
683
1166
  }
684
1167
 
1168
+ /**
1169
+ * Returns whether flat config should be used.
1170
+ * @returns {Promise<boolean>} Whether flat config should be used.
1171
+ */
1172
+ async function shouldUseFlatConfig() {
1173
+ return (process.env.ESLINT_USE_FLAT_CONFIG !== "false");
1174
+ }
1175
+
685
1176
  //------------------------------------------------------------------------------
686
1177
  // Public Interface
687
1178
  //------------------------------------------------------------------------------
688
1179
 
689
1180
  module.exports = {
690
1181
  ESLint,
691
-
692
- /**
693
- * Get the private class members of a given ESLint instance for tests.
694
- * @param {ESLint} instance The ESLint instance to get.
695
- * @returns {ESLintPrivateMembers} The instance's private class members.
696
- */
697
- getESLintPrivateMembers(instance) {
698
- return privateMembersMap.get(instance);
699
- }
1182
+ shouldUseFlatConfig
700
1183
  };