config-array-factory.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. /**
  2. * @fileoverview The factory of `ConfigArray` objects.
  3. *
  4. * This class provides methods to create `ConfigArray` instance.
  5. *
  6. * - `create(configData, options)`
  7. * Create a `ConfigArray` instance from a config data. This is to handle CLI
  8. * options except `--config`.
  9. * - `loadFile(filePath, options)`
  10. * Create a `ConfigArray` instance from a config file. This is to handle
  11. * `--config` option. If the file was not found, throws the following error:
  12. * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
  13. * - If the filename was `package.json`, an IO error or an
  14. * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
  15. * - Otherwise, an IO error such as `ENOENT`.
  16. * - `loadInDirectory(directoryPath, options)`
  17. * Create a `ConfigArray` instance from a config file which is on a given
  18. * directory. This tries to load `.eslintrc.*` or `package.json`. If not
  19. * found, returns an empty `ConfigArray`.
  20. * - `loadESLintIgnore(filePath)`
  21. * Create a `ConfigArray` instance from a config file that is `.eslintignore`
  22. * format. This is to handle `--ignore-path` option.
  23. * - `loadDefaultESLintIgnore()`
  24. * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
  25. * the current working directory.
  26. *
  27. * `ConfigArrayFactory` class has the responsibility that loads configuration
  28. * files, including loading `extends`, `parser`, and `plugins`. The created
  29. * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
  30. *
  31. * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
  32. * handles cascading and hierarchy.
  33. *
  34. * @author Toru Nagashima <https://github.com/mysticatea>
  35. */
  36. //------------------------------------------------------------------------------
  37. // Requirements
  38. //------------------------------------------------------------------------------
  39. import debugOrig from "debug";
  40. import fs from "node:fs";
  41. import importFresh from "import-fresh";
  42. import { createRequire } from "node:module";
  43. import path from "node:path";
  44. import stripComments from "strip-json-comments";
  45. import {
  46. ConfigArray,
  47. ConfigDependency,
  48. IgnorePattern,
  49. OverrideTester
  50. } from "./config-array/index.js";
  51. import ConfigValidator from "./shared/config-validator.js";
  52. import * as naming from "./shared/naming.js";
  53. import * as ModuleResolver from "./shared/relative-module-resolver.js";
  54. const require = createRequire(import.meta.url);
  55. const debug = debugOrig("eslintrc:config-array-factory");
  56. //------------------------------------------------------------------------------
  57. // Helpers
  58. //------------------------------------------------------------------------------
  59. const configFilenames = [
  60. ".eslintrc.js",
  61. ".eslintrc.cjs",
  62. ".eslintrc.yaml",
  63. ".eslintrc.yml",
  64. ".eslintrc.json",
  65. ".eslintrc",
  66. "package.json"
  67. ];
  68. // Define types for VSCode IntelliSense.
  69. /** @typedef {import("./shared/types").ConfigData} ConfigData */
  70. /** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
  71. /** @typedef {import("./shared/types").Parser} Parser */
  72. /** @typedef {import("./shared/types").Plugin} Plugin */
  73. /** @typedef {import("./shared/types").Rule} Rule */
  74. /** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
  75. /** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
  76. /** @typedef {ConfigArray[0]} ConfigArrayElement */
  77. /**
  78. * @typedef {Object} ConfigArrayFactoryOptions
  79. * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
  80. * @property {string} [cwd] The path to the current working directory.
  81. * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
  82. * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
  83. * @property {Object} [resolver=ModuleResolver] The module resolver object.
  84. * @property {string} eslintAllPath The path to the definitions for eslint:all.
  85. * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
  86. * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
  87. * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
  88. */
  89. /**
  90. * @typedef {Object} ConfigArrayFactoryInternalSlots
  91. * @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
  92. * @property {string} cwd The path to the current working directory.
  93. * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
  94. * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
  95. * @property {Object} [resolver=ModuleResolver] The module resolver object.
  96. * @property {string} eslintAllPath The path to the definitions for eslint:all.
  97. * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
  98. * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
  99. * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
  100. */
  101. /**
  102. * @typedef {Object} ConfigArrayFactoryLoadingContext
  103. * @property {string} filePath The path to the current configuration.
  104. * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  105. * @property {string} name The name of the current configuration.
  106. * @property {string} pluginBasePath The base path to resolve plugins.
  107. * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
  108. */
  109. /**
  110. * @typedef {Object} ConfigArrayFactoryLoadingContext
  111. * @property {string} filePath The path to the current configuration.
  112. * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  113. * @property {string} name The name of the current configuration.
  114. * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
  115. */
  116. /** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
  117. const internalSlotsMap = new WeakMap();
  118. /** @type {WeakMap<object, Plugin>} */
  119. const normalizedPlugins = new WeakMap();
  120. /**
  121. * Check if a given string is a file path.
  122. * @param {string} nameOrPath A module name or file path.
  123. * @returns {boolean} `true` if the `nameOrPath` is a file path.
  124. */
  125. function isFilePath(nameOrPath) {
  126. return (
  127. /^\.{1,2}[/\\]/u.test(nameOrPath) ||
  128. path.isAbsolute(nameOrPath)
  129. );
  130. }
  131. /**
  132. * Convenience wrapper for synchronously reading file contents.
  133. * @param {string} filePath The filename to read.
  134. * @returns {string} The file contents, with the BOM removed.
  135. * @private
  136. */
  137. function readFile(filePath) {
  138. return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
  139. }
  140. /**
  141. * Loads a YAML configuration from a file.
  142. * @param {string} filePath The filename to load.
  143. * @returns {ConfigData} The configuration object from the file.
  144. * @throws {Error} If the file cannot be read.
  145. * @private
  146. */
  147. function loadYAMLConfigFile(filePath) {
  148. debug(`Loading YAML config file: ${filePath}`);
  149. // lazy load YAML to improve performance when not used
  150. const yaml = require("js-yaml");
  151. try {
  152. // empty YAML file can be null, so always use
  153. return yaml.load(readFile(filePath)) || {};
  154. } catch (e) {
  155. debug(`Error reading YAML file: ${filePath}`);
  156. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  157. throw e;
  158. }
  159. }
  160. /**
  161. * Loads a JSON configuration from a file.
  162. * @param {string} filePath The filename to load.
  163. * @returns {ConfigData} The configuration object from the file.
  164. * @throws {Error} If the file cannot be read.
  165. * @private
  166. */
  167. function loadJSONConfigFile(filePath) {
  168. debug(`Loading JSON config file: ${filePath}`);
  169. try {
  170. return JSON.parse(stripComments(readFile(filePath)));
  171. } catch (e) {
  172. debug(`Error reading JSON file: ${filePath}`);
  173. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  174. e.messageTemplate = "failed-to-read-json";
  175. e.messageData = {
  176. path: filePath,
  177. message: e.message
  178. };
  179. throw e;
  180. }
  181. }
  182. /**
  183. * Loads a legacy (.eslintrc) configuration from a file.
  184. * @param {string} filePath The filename to load.
  185. * @returns {ConfigData} The configuration object from the file.
  186. * @throws {Error} If the file cannot be read.
  187. * @private
  188. */
  189. function loadLegacyConfigFile(filePath) {
  190. debug(`Loading legacy config file: ${filePath}`);
  191. // lazy load YAML to improve performance when not used
  192. const yaml = require("js-yaml");
  193. try {
  194. return yaml.load(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};
  195. } catch (e) {
  196. debug("Error reading YAML file: %s\n%o", filePath, e);
  197. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  198. throw e;
  199. }
  200. }
  201. /**
  202. * Loads a JavaScript configuration from a file.
  203. * @param {string} filePath The filename to load.
  204. * @returns {ConfigData} The configuration object from the file.
  205. * @throws {Error} If the file cannot be read.
  206. * @private
  207. */
  208. function loadJSConfigFile(filePath) {
  209. debug(`Loading JS config file: ${filePath}`);
  210. try {
  211. return importFresh(filePath);
  212. } catch (e) {
  213. debug(`Error reading JavaScript file: ${filePath}`);
  214. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  215. throw e;
  216. }
  217. }
  218. /**
  219. * Loads a configuration from a package.json file.
  220. * @param {string} filePath The filename to load.
  221. * @returns {ConfigData} The configuration object from the file.
  222. * @throws {Error} If the file cannot be read.
  223. * @private
  224. */
  225. function loadPackageJSONConfigFile(filePath) {
  226. debug(`Loading package.json config file: ${filePath}`);
  227. try {
  228. const packageData = loadJSONConfigFile(filePath);
  229. if (!Object.hasOwn(packageData, "eslintConfig")) {
  230. throw Object.assign(
  231. new Error("package.json file doesn't have 'eslintConfig' field."),
  232. { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
  233. );
  234. }
  235. return packageData.eslintConfig;
  236. } catch (e) {
  237. debug(`Error reading package.json file: ${filePath}`);
  238. e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
  239. throw e;
  240. }
  241. }
  242. /**
  243. * Loads a `.eslintignore` from a file.
  244. * @param {string} filePath The filename to load.
  245. * @returns {string[]} The ignore patterns from the file.
  246. * @throws {Error} If the file cannot be read.
  247. * @private
  248. */
  249. function loadESLintIgnoreFile(filePath) {
  250. debug(`Loading .eslintignore file: ${filePath}`);
  251. try {
  252. return readFile(filePath)
  253. .split(/\r?\n/gu)
  254. .filter(line => line.trim() !== "" && !line.startsWith("#"));
  255. } catch (e) {
  256. debug(`Error reading .eslintignore file: ${filePath}`);
  257. e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
  258. throw e;
  259. }
  260. }
  261. /**
  262. * Creates an error to notify about a missing config to extend from.
  263. * @param {string} configName The name of the missing config.
  264. * @param {string} importerName The name of the config that imported the missing config
  265. * @param {string} messageTemplate The text template to source error strings from.
  266. * @returns {Error} The error object to throw
  267. * @private
  268. */
  269. function configInvalidError(configName, importerName, messageTemplate) {
  270. return Object.assign(
  271. new Error(`Failed to load config "${configName}" to extend from.`),
  272. {
  273. messageTemplate,
  274. messageData: { configName, importerName }
  275. }
  276. );
  277. }
  278. /**
  279. * Loads a configuration file regardless of the source. Inspects the file path
  280. * to determine the correctly way to load the config file.
  281. * @param {string} filePath The path to the configuration.
  282. * @returns {ConfigData|null} The configuration information.
  283. * @private
  284. */
  285. function loadConfigFile(filePath) {
  286. switch (path.extname(filePath)) {
  287. case ".js":
  288. case ".cjs":
  289. return loadJSConfigFile(filePath);
  290. case ".json":
  291. if (path.basename(filePath) === "package.json") {
  292. return loadPackageJSONConfigFile(filePath);
  293. }
  294. return loadJSONConfigFile(filePath);
  295. case ".yaml":
  296. case ".yml":
  297. return loadYAMLConfigFile(filePath);
  298. default:
  299. return loadLegacyConfigFile(filePath);
  300. }
  301. }
  302. /**
  303. * Write debug log.
  304. * @param {string} request The requested module name.
  305. * @param {string} relativeTo The file path to resolve the request relative to.
  306. * @param {string} filePath The resolved file path.
  307. * @returns {void}
  308. */
  309. function writeDebugLogForLoading(request, relativeTo, filePath) {
  310. /* istanbul ignore next */
  311. if (debug.enabled) {
  312. let nameAndVersion = null; // eslint-disable-line no-useless-assignment -- known bug in the rule
  313. try {
  314. const packageJsonPath = ModuleResolver.resolve(
  315. `${request}/package.json`,
  316. relativeTo
  317. );
  318. const { version = "unknown" } = require(packageJsonPath);
  319. nameAndVersion = `${request}@${version}`;
  320. } catch (error) {
  321. debug("package.json was not found:", error.message);
  322. nameAndVersion = request;
  323. }
  324. debug("Loaded: %s (%s)", nameAndVersion, filePath);
  325. }
  326. }
  327. /**
  328. * Create a new context with default values.
  329. * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
  330. * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
  331. * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
  332. * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
  333. * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
  334. * @returns {ConfigArrayFactoryLoadingContext} The created context.
  335. */
  336. function createContext(
  337. { cwd, resolvePluginsRelativeTo },
  338. providedType,
  339. providedName,
  340. providedFilePath,
  341. providedMatchBasePath
  342. ) {
  343. const filePath = providedFilePath
  344. ? path.resolve(cwd, providedFilePath)
  345. : "";
  346. const matchBasePath =
  347. (providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) ||
  348. (filePath && path.dirname(filePath)) ||
  349. cwd;
  350. const name =
  351. providedName ||
  352. (filePath && path.relative(cwd, filePath)) ||
  353. "";
  354. const pluginBasePath =
  355. resolvePluginsRelativeTo ||
  356. (filePath && path.dirname(filePath)) ||
  357. cwd;
  358. const type = providedType || "config";
  359. return { filePath, matchBasePath, name, pluginBasePath, type };
  360. }
  361. /**
  362. * Normalize a given plugin.
  363. * - Ensure the object to have four properties: configs, environments, processors, and rules.
  364. * - Ensure the object to not have other properties.
  365. * @param {Plugin} plugin The plugin to normalize.
  366. * @returns {Plugin} The normalized plugin.
  367. */
  368. function normalizePlugin(plugin) {
  369. // first check the cache
  370. let normalizedPlugin = normalizedPlugins.get(plugin);
  371. if (normalizedPlugin) {
  372. return normalizedPlugin;
  373. }
  374. normalizedPlugin = {
  375. configs: plugin.configs || {},
  376. environments: plugin.environments || {},
  377. processors: plugin.processors || {},
  378. rules: plugin.rules || {}
  379. };
  380. // save the reference for later
  381. normalizedPlugins.set(plugin, normalizedPlugin);
  382. return normalizedPlugin;
  383. }
  384. //------------------------------------------------------------------------------
  385. // Public Interface
  386. //------------------------------------------------------------------------------
  387. /**
  388. * The factory of `ConfigArray` objects.
  389. */
  390. class ConfigArrayFactory {
  391. /**
  392. * Initialize this instance.
  393. * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
  394. */
  395. constructor({
  396. additionalPluginPool = new Map(),
  397. cwd = process.cwd(),
  398. resolvePluginsRelativeTo,
  399. builtInRules,
  400. resolver = ModuleResolver,
  401. eslintAllPath,
  402. getEslintAllConfig,
  403. eslintRecommendedPath,
  404. getEslintRecommendedConfig
  405. } = {}) {
  406. internalSlotsMap.set(this, {
  407. additionalPluginPool,
  408. cwd,
  409. resolvePluginsRelativeTo:
  410. resolvePluginsRelativeTo &&
  411. path.resolve(cwd, resolvePluginsRelativeTo),
  412. builtInRules,
  413. resolver,
  414. eslintAllPath,
  415. getEslintAllConfig,
  416. eslintRecommendedPath,
  417. getEslintRecommendedConfig
  418. });
  419. }
  420. /**
  421. * Create `ConfigArray` instance from a config data.
  422. * @param {ConfigData|null} configData The config data to create.
  423. * @param {Object} [options] The options.
  424. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  425. * @param {string} [options.filePath] The path to this config data.
  426. * @param {string} [options.name] The config name.
  427. * @returns {ConfigArray} Loaded config.
  428. */
  429. create(configData, { basePath, filePath, name } = {}) {
  430. if (!configData) {
  431. return new ConfigArray();
  432. }
  433. const slots = internalSlotsMap.get(this);
  434. const ctx = createContext(slots, "config", name, filePath, basePath);
  435. const elements = this._normalizeConfigData(configData, ctx);
  436. return new ConfigArray(...elements);
  437. }
  438. /**
  439. * Load a config file.
  440. * @param {string} filePath The path to a config file.
  441. * @param {Object} [options] The options.
  442. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  443. * @param {string} [options.name] The config name.
  444. * @returns {ConfigArray} Loaded config.
  445. */
  446. loadFile(filePath, { basePath, name } = {}) {
  447. const slots = internalSlotsMap.get(this);
  448. const ctx = createContext(slots, "config", name, filePath, basePath);
  449. return new ConfigArray(...this._loadConfigData(ctx));
  450. }
  451. /**
  452. * Load the config file on a given directory if exists.
  453. * @param {string} directoryPath The path to a directory.
  454. * @param {Object} [options] The options.
  455. * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
  456. * @param {string} [options.name] The config name.
  457. * @throws {Error} If the config file is invalid.
  458. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  459. */
  460. loadInDirectory(directoryPath, { basePath, name } = {}) {
  461. const slots = internalSlotsMap.get(this);
  462. for (const filename of configFilenames) {
  463. const ctx = createContext(
  464. slots,
  465. "config",
  466. name,
  467. path.join(directoryPath, filename),
  468. basePath
  469. );
  470. if (fs.existsSync(ctx.filePath) && fs.statSync(ctx.filePath).isFile()) {
  471. let configData;
  472. try {
  473. configData = loadConfigFile(ctx.filePath);
  474. } catch (error) {
  475. if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
  476. throw error;
  477. }
  478. }
  479. if (configData) {
  480. debug(`Config file found: ${ctx.filePath}`);
  481. return new ConfigArray(
  482. ...this._normalizeConfigData(configData, ctx)
  483. );
  484. }
  485. }
  486. }
  487. debug(`Config file not found on ${directoryPath}`);
  488. return new ConfigArray();
  489. }
  490. /**
  491. * Check if a config file on a given directory exists or not.
  492. * @param {string} directoryPath The path to a directory.
  493. * @returns {string | null} The path to the found config file. If not found then null.
  494. */
  495. static getPathToConfigFileInDirectory(directoryPath) {
  496. for (const filename of configFilenames) {
  497. const filePath = path.join(directoryPath, filename);
  498. if (fs.existsSync(filePath)) {
  499. if (filename === "package.json") {
  500. try {
  501. loadPackageJSONConfigFile(filePath);
  502. return filePath;
  503. } catch { /* ignore */ }
  504. } else {
  505. return filePath;
  506. }
  507. }
  508. }
  509. return null;
  510. }
  511. /**
  512. * Load `.eslintignore` file.
  513. * @param {string} filePath The path to a `.eslintignore` file to load.
  514. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  515. */
  516. loadESLintIgnore(filePath) {
  517. const slots = internalSlotsMap.get(this);
  518. const ctx = createContext(
  519. slots,
  520. "ignore",
  521. void 0,
  522. filePath,
  523. slots.cwd
  524. );
  525. const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
  526. return new ConfigArray(
  527. ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
  528. );
  529. }
  530. /**
  531. * Load `.eslintignore` file in the current working directory.
  532. * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
  533. * @throws {Error} If the ignore file is invalid.
  534. */
  535. loadDefaultESLintIgnore() {
  536. const slots = internalSlotsMap.get(this);
  537. const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore");
  538. const packageJsonPath = path.resolve(slots.cwd, "package.json");
  539. if (fs.existsSync(eslintIgnorePath)) {
  540. return this.loadESLintIgnore(eslintIgnorePath);
  541. }
  542. if (fs.existsSync(packageJsonPath)) {
  543. const data = loadJSONConfigFile(packageJsonPath);
  544. if (Object.hasOwn(data, "eslintIgnore")) {
  545. if (!Array.isArray(data.eslintIgnore)) {
  546. throw new Error("Package.json eslintIgnore property requires an array of paths");
  547. }
  548. const ctx = createContext(
  549. slots,
  550. "ignore",
  551. "eslintIgnore in package.json",
  552. packageJsonPath,
  553. slots.cwd
  554. );
  555. return new ConfigArray(
  556. ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
  557. );
  558. }
  559. }
  560. return new ConfigArray();
  561. }
  562. /**
  563. * Load a given config file.
  564. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  565. * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
  566. * @private
  567. */
  568. _loadConfigData(ctx) {
  569. return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
  570. }
  571. /**
  572. * Normalize a given `.eslintignore` data to config array elements.
  573. * @param {string[]} ignorePatterns The patterns to ignore files.
  574. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  575. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  576. * @private
  577. */
  578. *_normalizeESLintIgnoreData(ignorePatterns, ctx) {
  579. const elements = this._normalizeObjectConfigData(
  580. { ignorePatterns },
  581. ctx
  582. );
  583. // Set `ignorePattern.loose` flag for backward compatibility.
  584. for (const element of elements) {
  585. if (element.ignorePattern) {
  586. element.ignorePattern.loose = true;
  587. }
  588. yield element;
  589. }
  590. }
  591. /**
  592. * Normalize a given config to an array.
  593. * @param {ConfigData} configData The config data to normalize.
  594. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  595. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  596. * @private
  597. */
  598. _normalizeConfigData(configData, ctx) {
  599. const validator = new ConfigValidator();
  600. validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
  601. return this._normalizeObjectConfigData(configData, ctx);
  602. }
  603. /**
  604. * Normalize a given config to an array.
  605. * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
  606. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  607. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  608. * @private
  609. */
  610. *_normalizeObjectConfigData(configData, ctx) {
  611. const { files, excludedFiles, ...configBody } = configData;
  612. const criteria = OverrideTester.create(
  613. files,
  614. excludedFiles,
  615. ctx.matchBasePath
  616. );
  617. const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
  618. // Apply the criteria to every element.
  619. for (const element of elements) {
  620. /*
  621. * Merge the criteria.
  622. * This is for the `overrides` entries that came from the
  623. * configurations of `overrides[].extends`.
  624. */
  625. element.criteria = OverrideTester.and(criteria, element.criteria);
  626. /*
  627. * Remove `root` property to ignore `root` settings which came from
  628. * `extends` in `overrides`.
  629. */
  630. if (element.criteria) {
  631. element.root = void 0;
  632. }
  633. yield element;
  634. }
  635. }
  636. /**
  637. * Normalize a given config to an array.
  638. * @param {ConfigData} configData The config data to normalize.
  639. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  640. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  641. * @private
  642. */
  643. *_normalizeObjectConfigDataBody(
  644. {
  645. env,
  646. extends: extend,
  647. globals,
  648. ignorePatterns,
  649. noInlineConfig,
  650. parser: parserName,
  651. parserOptions,
  652. plugins: pluginList,
  653. processor,
  654. reportUnusedDisableDirectives,
  655. root,
  656. rules,
  657. settings,
  658. overrides: overrideList = []
  659. },
  660. ctx
  661. ) {
  662. const extendList = Array.isArray(extend) ? extend : [extend];
  663. const ignorePattern = ignorePatterns && new IgnorePattern(
  664. Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
  665. ctx.matchBasePath
  666. );
  667. // Flatten `extends`.
  668. for (const extendName of extendList.filter(Boolean)) {
  669. yield* this._loadExtends(extendName, ctx);
  670. }
  671. // Load parser & plugins.
  672. const parser = parserName && this._loadParser(parserName, ctx);
  673. const plugins = pluginList && this._loadPlugins(pluginList, ctx);
  674. // Yield pseudo config data for file extension processors.
  675. if (plugins) {
  676. yield* this._takeFileExtensionProcessors(plugins, ctx);
  677. }
  678. // Yield the config data except `extends` and `overrides`.
  679. yield {
  680. // Debug information.
  681. type: ctx.type,
  682. name: ctx.name,
  683. filePath: ctx.filePath,
  684. // Config data.
  685. criteria: null,
  686. env,
  687. globals,
  688. ignorePattern,
  689. noInlineConfig,
  690. parser,
  691. parserOptions,
  692. plugins,
  693. processor,
  694. reportUnusedDisableDirectives,
  695. root,
  696. rules,
  697. settings
  698. };
  699. // Flatten `overries`.
  700. for (let i = 0; i < overrideList.length; ++i) {
  701. yield* this._normalizeObjectConfigData(
  702. overrideList[i],
  703. { ...ctx, name: `${ctx.name}#overrides[${i}]` }
  704. );
  705. }
  706. }
  707. /**
  708. * Load configs of an element in `extends`.
  709. * @param {string} extendName The name of a base config.
  710. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  711. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  712. * @throws {Error} If the extended config file can't be loaded.
  713. * @private
  714. */
  715. _loadExtends(extendName, ctx) {
  716. debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
  717. try {
  718. if (extendName.startsWith("eslint:")) {
  719. return this._loadExtendedBuiltInConfig(extendName, ctx);
  720. }
  721. if (extendName.startsWith("plugin:")) {
  722. return this._loadExtendedPluginConfig(extendName, ctx);
  723. }
  724. return this._loadExtendedShareableConfig(extendName, ctx);
  725. } catch (error) {
  726. error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
  727. throw error;
  728. }
  729. }
  730. /**
  731. * Load configs of an element in `extends`.
  732. * @param {string} extendName The name of a base config.
  733. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  734. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  735. * @throws {Error} If the extended config file can't be loaded.
  736. * @private
  737. */
  738. _loadExtendedBuiltInConfig(extendName, ctx) {
  739. const {
  740. eslintAllPath,
  741. getEslintAllConfig,
  742. eslintRecommendedPath,
  743. getEslintRecommendedConfig
  744. } = internalSlotsMap.get(this);
  745. if (extendName === "eslint:recommended") {
  746. const name = `${ctx.name} » ${extendName}`;
  747. if (getEslintRecommendedConfig) {
  748. if (typeof getEslintRecommendedConfig !== "function") {
  749. throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);
  750. }
  751. return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" });
  752. }
  753. return this._loadConfigData({
  754. ...ctx,
  755. name,
  756. filePath: eslintRecommendedPath
  757. });
  758. }
  759. if (extendName === "eslint:all") {
  760. const name = `${ctx.name} » ${extendName}`;
  761. if (getEslintAllConfig) {
  762. if (typeof getEslintAllConfig !== "function") {
  763. throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);
  764. }
  765. return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" });
  766. }
  767. return this._loadConfigData({
  768. ...ctx,
  769. name,
  770. filePath: eslintAllPath
  771. });
  772. }
  773. throw configInvalidError(extendName, ctx.name, "extend-config-missing");
  774. }
  775. /**
  776. * Load configs of an element in `extends`.
  777. * @param {string} extendName The name of a base config.
  778. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  779. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  780. * @throws {Error} If the extended config file can't be loaded.
  781. * @private
  782. */
  783. _loadExtendedPluginConfig(extendName, ctx) {
  784. const slashIndex = extendName.lastIndexOf("/");
  785. if (slashIndex === -1) {
  786. throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
  787. }
  788. const pluginName = extendName.slice("plugin:".length, slashIndex);
  789. const configName = extendName.slice(slashIndex + 1);
  790. if (isFilePath(pluginName)) {
  791. throw new Error("'extends' cannot use a file path for plugins.");
  792. }
  793. const plugin = this._loadPlugin(pluginName, ctx);
  794. const configData =
  795. plugin.definition &&
  796. plugin.definition.configs[configName];
  797. if (configData) {
  798. return this._normalizeConfigData(configData, {
  799. ...ctx,
  800. filePath: plugin.filePath || ctx.filePath,
  801. name: `${ctx.name} » plugin:${plugin.id}/${configName}`
  802. });
  803. }
  804. throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
  805. }
  806. /**
  807. * Load configs of an element in `extends`.
  808. * @param {string} extendName The name of a base config.
  809. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  810. * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
  811. * @throws {Error} If the extended config file can't be loaded.
  812. * @private
  813. */
  814. _loadExtendedShareableConfig(extendName, ctx) {
  815. const { cwd, resolver } = internalSlotsMap.get(this);
  816. const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
  817. let request;
  818. if (isFilePath(extendName)) {
  819. request = extendName;
  820. } else if (extendName.startsWith(".")) {
  821. request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
  822. } else {
  823. request = naming.normalizePackageName(
  824. extendName,
  825. "eslint-config"
  826. );
  827. }
  828. let filePath;
  829. try {
  830. filePath = resolver.resolve(request, relativeTo);
  831. } catch (error) {
  832. /* istanbul ignore else */
  833. if (error && error.code === "MODULE_NOT_FOUND") {
  834. throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
  835. }
  836. throw error;
  837. }
  838. writeDebugLogForLoading(request, relativeTo, filePath);
  839. return this._loadConfigData({
  840. ...ctx,
  841. filePath,
  842. name: `${ctx.name} » ${request}`
  843. });
  844. }
  845. /**
  846. * Load given plugins.
  847. * @param {string[]} names The plugin names to load.
  848. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  849. * @returns {Record<string,DependentPlugin>} The loaded parser.
  850. * @private
  851. */
  852. _loadPlugins(names, ctx) {
  853. return names.reduce((map, name) => {
  854. if (isFilePath(name)) {
  855. throw new Error("Plugins array cannot includes file paths.");
  856. }
  857. const plugin = this._loadPlugin(name, ctx);
  858. map[plugin.id] = plugin;
  859. return map;
  860. }, {});
  861. }
  862. /**
  863. * Load a given parser.
  864. * @param {string} nameOrPath The package name or the path to a parser file.
  865. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  866. * @returns {DependentParser} The loaded parser.
  867. */
  868. _loadParser(nameOrPath, ctx) {
  869. debug("Loading parser %j from %s", nameOrPath, ctx.filePath);
  870. const { cwd, resolver } = internalSlotsMap.get(this);
  871. const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
  872. try {
  873. const filePath = resolver.resolve(nameOrPath, relativeTo);
  874. writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
  875. return new ConfigDependency({
  876. definition: require(filePath),
  877. filePath,
  878. id: nameOrPath,
  879. importerName: ctx.name,
  880. importerPath: ctx.filePath
  881. });
  882. } catch (error) {
  883. // If the parser name is "espree", load the espree of ESLint.
  884. if (nameOrPath === "espree") {
  885. debug("Fallback espree.");
  886. return new ConfigDependency({
  887. definition: require("espree"),
  888. filePath: require.resolve("espree"),
  889. id: nameOrPath,
  890. importerName: ctx.name,
  891. importerPath: ctx.filePath
  892. });
  893. }
  894. debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
  895. error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
  896. return new ConfigDependency({
  897. error,
  898. id: nameOrPath,
  899. importerName: ctx.name,
  900. importerPath: ctx.filePath
  901. });
  902. }
  903. }
  904. /**
  905. * Load a given plugin.
  906. * @param {string} name The plugin name to load.
  907. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  908. * @returns {DependentPlugin} The loaded plugin.
  909. * @private
  910. */
  911. _loadPlugin(name, ctx) {
  912. debug("Loading plugin %j from %s", name, ctx.filePath);
  913. const { additionalPluginPool, resolver } = internalSlotsMap.get(this);
  914. const request = naming.normalizePackageName(name, "eslint-plugin");
  915. const id = naming.getShorthandName(request, "eslint-plugin");
  916. const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js");
  917. if (name.match(/\s+/u)) {
  918. const error = Object.assign(
  919. new Error(`Whitespace found in plugin name '${name}'`),
  920. {
  921. messageTemplate: "whitespace-found",
  922. messageData: { pluginName: request }
  923. }
  924. );
  925. return new ConfigDependency({
  926. error,
  927. id,
  928. importerName: ctx.name,
  929. importerPath: ctx.filePath
  930. });
  931. }
  932. // Check for additional pool.
  933. const plugin =
  934. additionalPluginPool.get(request) ||
  935. additionalPluginPool.get(id);
  936. if (plugin) {
  937. return new ConfigDependency({
  938. definition: normalizePlugin(plugin),
  939. original: plugin,
  940. filePath: "", // It's unknown where the plugin came from.
  941. id,
  942. importerName: ctx.name,
  943. importerPath: ctx.filePath
  944. });
  945. }
  946. let filePath;
  947. let error;
  948. try {
  949. filePath = resolver.resolve(request, relativeTo);
  950. } catch (resolveError) {
  951. error = resolveError;
  952. /* istanbul ignore else */
  953. if (error && error.code === "MODULE_NOT_FOUND") {
  954. error.messageTemplate = "plugin-missing";
  955. error.messageData = {
  956. pluginName: request,
  957. resolvePluginsRelativeTo: ctx.pluginBasePath,
  958. importerName: ctx.name
  959. };
  960. }
  961. }
  962. if (filePath) {
  963. try {
  964. writeDebugLogForLoading(request, relativeTo, filePath);
  965. const startTime = Date.now();
  966. const pluginDefinition = require(filePath);
  967. debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
  968. return new ConfigDependency({
  969. definition: normalizePlugin(pluginDefinition),
  970. original: pluginDefinition,
  971. filePath,
  972. id,
  973. importerName: ctx.name,
  974. importerPath: ctx.filePath
  975. });
  976. } catch (loadError) {
  977. error = loadError;
  978. }
  979. }
  980. debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
  981. error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
  982. return new ConfigDependency({
  983. error,
  984. id,
  985. importerName: ctx.name,
  986. importerPath: ctx.filePath
  987. });
  988. }
  989. /**
  990. * Take file expression processors as config array elements.
  991. * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
  992. * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
  993. * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
  994. * @private
  995. */
  996. *_takeFileExtensionProcessors(plugins, ctx) {
  997. for (const pluginId of Object.keys(plugins)) {
  998. const processors =
  999. plugins[pluginId] &&
  1000. plugins[pluginId].definition &&
  1001. plugins[pluginId].definition.processors;
  1002. if (!processors) {
  1003. continue;
  1004. }
  1005. for (const processorId of Object.keys(processors)) {
  1006. if (processorId.startsWith(".")) {
  1007. yield* this._normalizeObjectConfigData(
  1008. {
  1009. files: [`*${processorId}`],
  1010. processor: `${pluginId}/${processorId}`
  1011. },
  1012. {
  1013. ...ctx,
  1014. type: "implicit-processor",
  1015. name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
  1016. }
  1017. );
  1018. }
  1019. }
  1020. }
  1021. }
  1022. }
  1023. export {
  1024. ConfigArrayFactory,
  1025. createContext,
  1026. loadConfigFile
  1027. };