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