2 * @fileoverview The factory of `ConfigArray` objects.
4 * This class provides methods to create `ConfigArray` instance.
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.
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`.
31 * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
32 * handles cascading and hierarchy.
34 * @author Toru Nagashima <https://github.com/mysticatea>
38 //------------------------------------------------------------------------------
40 //------------------------------------------------------------------------------
42 const fs = require("fs");
43 const path = require("path");
44 const importFresh = require("import-fresh");
45 const stripComments = require("strip-json-comments");
46 const { validateConfigSchema } = require("../shared/config-validator");
47 const naming = require("../shared/naming");
48 const ModuleResolver = require("../shared/relative-module-resolver");
54 } = require("./config-array");
55 const debug = require("debug")("eslint:config-array-factory");
57 //------------------------------------------------------------------------------
59 //------------------------------------------------------------------------------
61 const eslintRecommendedPath = path.resolve(__dirname, "../../conf/eslint-recommended.js");
62 const eslintAllPath = path.resolve(__dirname, "../../conf/eslint-all.js");
63 const configFilenames = [
73 // Define types for VSCode IntelliSense.
74 /** @typedef {import("../shared/types").ConfigData} ConfigData */
75 /** @typedef {import("../shared/types").OverrideConfigData} OverrideConfigData */
76 /** @typedef {import("../shared/types").Parser} Parser */
77 /** @typedef {import("../shared/types").Plugin} Plugin */
78 /** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
79 /** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
80 /** @typedef {ConfigArray[0]} ConfigArrayElement */
83 * @typedef {Object} ConfigArrayFactoryOptions
84 * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
85 * @property {string} [cwd] The path to the current working directory.
86 * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
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} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
96 /** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
97 const internalSlotsMap = new WeakMap();
100 * Check if a given string is a file path.
101 * @param {string} nameOrPath A module name or file path.
102 * @returns {boolean} `true` if the `nameOrPath` is a file path.
104 function isFilePath(nameOrPath) {
106 /^\.{1,2}[/\\]/u.test(nameOrPath) ||
107 path.isAbsolute(nameOrPath)
112 * Convenience wrapper for synchronously reading file contents.
113 * @param {string} filePath The filename to read.
114 * @returns {string} The file contents, with the BOM removed.
117 function readFile(filePath) {
118 return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
122 * Loads a YAML configuration from a file.
123 * @param {string} filePath The filename to load.
124 * @returns {ConfigData} The configuration object from the file.
125 * @throws {Error} If the file cannot be read.
128 function loadYAMLConfigFile(filePath) {
129 debug(`Loading YAML config file: ${filePath}`);
131 // lazy load YAML to improve performance when not used
132 const yaml = require("js-yaml");
136 // empty YAML file can be null, so always use
137 return yaml.safeLoad(readFile(filePath)) || {};
139 debug(`Error reading YAML file: ${filePath}`);
140 e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
146 * Loads a JSON configuration from a file.
147 * @param {string} filePath The filename to load.
148 * @returns {ConfigData} The configuration object from the file.
149 * @throws {Error} If the file cannot be read.
152 function loadJSONConfigFile(filePath) {
153 debug(`Loading JSON config file: ${filePath}`);
156 return JSON.parse(stripComments(readFile(filePath)));
158 debug(`Error reading JSON file: ${filePath}`);
159 e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
160 e.messageTemplate = "failed-to-read-json";
170 * Loads a legacy (.eslintrc) configuration from a file.
171 * @param {string} filePath The filename to load.
172 * @returns {ConfigData} The configuration object from the file.
173 * @throws {Error} If the file cannot be read.
176 function loadLegacyConfigFile(filePath) {
177 debug(`Loading legacy config file: ${filePath}`);
179 // lazy load YAML to improve performance when not used
180 const yaml = require("js-yaml");
183 return yaml.safeLoad(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};
185 debug("Error reading YAML file: %s\n%o", filePath, e);
186 e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
192 * Loads a JavaScript configuration from a file.
193 * @param {string} filePath The filename to load.
194 * @returns {ConfigData} The configuration object from the file.
195 * @throws {Error} If the file cannot be read.
198 function loadJSConfigFile(filePath) {
199 debug(`Loading JS config file: ${filePath}`);
201 return importFresh(filePath);
203 debug(`Error reading JavaScript file: ${filePath}`);
204 e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
210 * Loads a configuration from a package.json file.
211 * @param {string} filePath The filename to load.
212 * @returns {ConfigData} The configuration object from the file.
213 * @throws {Error} If the file cannot be read.
216 function loadPackageJSONConfigFile(filePath) {
217 debug(`Loading package.json config file: ${filePath}`);
219 const packageData = loadJSONConfigFile(filePath);
221 if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
223 new Error("package.json file doesn't have 'eslintConfig' field."),
224 { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
228 return packageData.eslintConfig;
230 debug(`Error reading package.json file: ${filePath}`);
231 e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
237 * Loads a `.eslintignore` from a file.
238 * @param {string} filePath The filename to load.
239 * @returns {string[]} The ignore patterns from the file.
242 function loadESLintIgnoreFile(filePath) {
243 debug(`Loading .eslintignore file: ${filePath}`);
246 return readFile(filePath)
248 .filter(line => line.trim() !== "" && !line.startsWith("#"));
250 debug(`Error reading .eslintignore file: ${filePath}`);
251 e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
257 * Creates an error to notify about a missing config to extend from.
258 * @param {string} configName The name of the missing config.
259 * @param {string} importerName The name of the config that imported the missing config
260 * @returns {Error} The error object to throw
263 function configMissingError(configName, importerName) {
264 return Object.assign(
265 new Error(`Failed to load config "${configName}" to extend from.`),
267 messageTemplate: "extend-config-missing",
268 messageData: { configName, importerName }
274 * Loads a configuration file regardless of the source. Inspects the file path
275 * to determine the correctly way to load the config file.
276 * @param {string} filePath The path to the configuration.
277 * @returns {ConfigData|null} The configuration information.
280 function loadConfigFile(filePath) {
281 switch (path.extname(filePath)) {
284 return loadJSConfigFile(filePath);
287 if (path.basename(filePath) === "package.json") {
288 return loadPackageJSONConfigFile(filePath);
290 return loadJSONConfigFile(filePath);
294 return loadYAMLConfigFile(filePath);
297 return loadLegacyConfigFile(filePath);
303 * @param {string} request The requested module name.
304 * @param {string} relativeTo The file path to resolve the request relative to.
305 * @param {string} filePath The resolved file path.
308 function writeDebugLogForLoading(request, relativeTo, filePath) {
309 /* istanbul ignore next */
311 let nameAndVersion = null;
314 const packageJsonPath = ModuleResolver.resolve(
315 `${request}/package.json`,
318 const { version = "unknown" } = require(packageJsonPath);
320 nameAndVersion = `${request}@${version}`;
322 debug("package.json was not found:", error.message);
323 nameAndVersion = request;
326 debug("Loaded: %s (%s)", nameAndVersion, filePath);
331 * Concatenate two config data.
332 * @param {IterableIterator<ConfigArrayElement>|null} elements The config elements.
333 * @param {ConfigArray|null} parentConfigArray The parent config array.
334 * @returns {ConfigArray} The concatenated config array.
336 function createConfigArray(elements, parentConfigArray) {
338 return parentConfigArray || new ConfigArray();
340 const configArray = new ConfigArray(...elements);
342 if (parentConfigArray && !configArray.isRoot()) {
343 configArray.unshift(...parentConfigArray);
349 * Normalize a given plugin.
350 * - Ensure the object to have four properties: configs, environments, processors, and rules.
351 * - Ensure the object to not have other properties.
352 * @param {Plugin} plugin The plugin to normalize.
353 * @returns {Plugin} The normalized plugin.
355 function normalizePlugin(plugin) {
357 configs: plugin.configs || {},
358 environments: plugin.environments || {},
359 processors: plugin.processors || {},
360 rules: plugin.rules || {}
364 //------------------------------------------------------------------------------
366 //------------------------------------------------------------------------------
369 * The factory of `ConfigArray` objects.
371 class ConfigArrayFactory {
374 * Initialize this instance.
375 * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
378 additionalPluginPool = new Map(),
380 resolvePluginsRelativeTo = cwd
382 internalSlotsMap.set(this, { additionalPluginPool, cwd, resolvePluginsRelativeTo: path.resolve(cwd, resolvePluginsRelativeTo) });
386 * Create `ConfigArray` instance from a config data.
387 * @param {ConfigData|null} configData The config data to create.
388 * @param {Object} [options] The options.
389 * @param {string} [options.filePath] The path to this config data.
390 * @param {string} [options.name] The config name.
391 * @param {ConfigArray} [options.parent] The parent config array.
392 * @returns {ConfigArray} Loaded config.
394 create(configData, { filePath, name, parent } = {}) {
395 return createConfigArray(
397 ? this._normalizeConfigData(configData, filePath, name)
404 * Load a config file.
405 * @param {string} filePath The path to a config file.
406 * @param {Object} [options] The options.
407 * @param {string} [options.name] The config name.
408 * @param {ConfigArray} [options.parent] The parent config array.
409 * @returns {ConfigArray} Loaded config.
411 loadFile(filePath, { name, parent } = {}) {
412 const { cwd } = internalSlotsMap.get(this);
413 const absolutePath = path.resolve(cwd, filePath);
415 return createConfigArray(
416 this._loadConfigData(absolutePath, name),
422 * Load the config file on a given directory if exists.
423 * @param {string} directoryPath The path to a directory.
424 * @param {Object} [options] The options.
425 * @param {string} [options.name] The config name.
426 * @param {ConfigArray} [options.parent] The parent config array.
427 * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
429 loadInDirectory(directoryPath, { name, parent } = {}) {
430 const { cwd } = internalSlotsMap.get(this);
431 const absolutePath = path.resolve(cwd, directoryPath);
433 return createConfigArray(
434 this._loadConfigDataInDirectory(absolutePath, name),
440 * Load `.eslintignore` file.
441 * @param {string} filePath The path to a `.eslintignore` file to load.
442 * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
444 loadESLintIgnore(filePath) {
445 const { cwd } = internalSlotsMap.get(this);
446 const absolutePath = path.resolve(cwd, filePath);
447 const name = path.relative(cwd, absolutePath);
448 const ignorePatterns = loadESLintIgnoreFile(absolutePath);
450 return createConfigArray(
451 this._normalizeESLintIgnoreData(ignorePatterns, absolutePath, name)
456 * Load `.eslintignore` file in the current working directory.
457 * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
459 loadDefaultESLintIgnore() {
460 const { cwd } = internalSlotsMap.get(this);
461 const eslintIgnorePath = path.resolve(cwd, ".eslintignore");
462 const packageJsonPath = path.resolve(cwd, "package.json");
464 if (fs.existsSync(eslintIgnorePath)) {
465 return this.loadESLintIgnore(eslintIgnorePath);
467 if (fs.existsSync(packageJsonPath)) {
468 const data = loadJSONConfigFile(packageJsonPath);
470 if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
471 if (!Array.isArray(data.eslintIgnore)) {
472 throw new Error("Package.json eslintIgnore property requires an array of paths");
474 return createConfigArray(
475 this._normalizeESLintIgnoreData(
478 "eslintIgnore in package.json"
484 return new ConfigArray();
488 * Load a given config file.
489 * @param {string} filePath The path to a config file.
490 * @param {string} name The config name.
491 * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
494 _loadConfigData(filePath, name) {
495 return this._normalizeConfigData(
496 loadConfigFile(filePath),
503 * Load the config file in a given directory if exists.
504 * @param {string} directoryPath The path to a directory.
505 * @param {string} name The config name.
506 * @returns {IterableIterator<ConfigArrayElement> | null} Loaded config. `null` if any config doesn't exist.
509 _loadConfigDataInDirectory(directoryPath, name) {
510 for (const filename of configFilenames) {
511 const filePath = path.join(directoryPath, filename);
513 if (fs.existsSync(filePath)) {
517 configData = loadConfigFile(filePath);
519 if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
525 debug(`Config file found: ${filePath}`);
526 return this._normalizeConfigData(configData, filePath, name);
531 debug(`Config file not found on ${directoryPath}`);
536 * Normalize a given `.eslintignore` data to config array elements.
537 * @param {string[]} ignorePatterns The patterns to ignore files.
538 * @param {string|undefined} filePath The file path of this config.
539 * @param {string|undefined} name The name of this config.
540 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
543 *_normalizeESLintIgnoreData(ignorePatterns, filePath, name) {
544 const elements = this._normalizeObjectConfigData(
550 // Set `ignorePattern.loose` flag for backward compatibility.
551 for (const element of elements) {
552 if (element.ignorePattern) {
553 element.ignorePattern.loose = true;
560 * Normalize a given config to an array.
561 * @param {ConfigData} configData The config data to normalize.
562 * @param {string|undefined} providedFilePath The file path of this config.
563 * @param {string|undefined} providedName The name of this config.
564 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
567 _normalizeConfigData(configData, providedFilePath, providedName) {
568 const { cwd } = internalSlotsMap.get(this);
569 const filePath = providedFilePath
570 ? path.resolve(cwd, providedFilePath)
572 const name = providedName || (filePath && path.relative(cwd, filePath));
574 validateConfigSchema(configData, name || filePath);
576 return this._normalizeObjectConfigData(configData, filePath, name);
580 * Normalize a given config to an array.
581 * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
582 * @param {string} filePath The file path of this config.
583 * @param {string} name The name of this config.
584 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
587 *_normalizeObjectConfigData(configData, filePath, name) {
588 const { cwd } = internalSlotsMap.get(this);
589 const { files, excludedFiles, ...configBody } = configData;
590 const basePath = filePath ? path.dirname(filePath) : cwd;
591 const criteria = OverrideTester.create(files, excludedFiles, basePath);
593 this._normalizeObjectConfigDataBody(configBody, filePath, name);
595 // Apply the criteria to every element.
596 for (const element of elements) {
598 // Adopt the base path of the entry file (the outermost base path).
599 if (element.criteria) {
600 element.criteria.basePath = basePath;
602 if (element.ignorePattern) {
603 element.ignorePattern.basePath = basePath;
607 * Merge the criteria; this is for only file extension processors in
608 * `overrides` section for now.
610 element.criteria = OverrideTester.and(criteria, element.criteria);
613 * Remove `root` property to ignore `root` settings which came from
614 * `extends` in `overrides`.
616 if (element.criteria) {
617 element.root = void 0;
625 * Normalize a given config to an array.
626 * @param {ConfigData} configData The config data to normalize.
627 * @param {string} filePath The file path of this config.
628 * @param {string} name The name of this config.
629 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
632 *_normalizeObjectConfigDataBody(
643 reportUnusedDisableDirectives,
647 overrides: overrideList = []
652 const extendList = Array.isArray(extend) ? extend : [extend];
653 const ignorePattern = ignorePatterns && new IgnorePattern(
654 Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
655 filePath ? path.dirname(filePath) : internalSlotsMap.get(this).cwd
658 // Flatten `extends`.
659 for (const extendName of extendList.filter(Boolean)) {
660 yield* this._loadExtends(extendName, filePath, name);
663 // Load parser & plugins.
665 parserName && this._loadParser(parserName, filePath, name);
667 pluginList && this._loadPlugins(pluginList, filePath, name);
669 // Yield pseudo config data for file extension processors.
671 yield* this._takeFileExtensionProcessors(plugins, filePath, name);
674 // Yield the config data except `extends` and `overrides`.
677 // Debug information.
691 reportUnusedDisableDirectives,
697 // Flatten `overries`.
698 for (let i = 0; i < overrideList.length; ++i) {
699 yield* this._normalizeObjectConfigData(
702 `${name}#overrides[${i}]`
708 * Load configs of an element in `extends`.
709 * @param {string} extendName The name of a base config.
710 * @param {string} importerPath The file path which has the `extends` property.
711 * @param {string} importerName The name of the config which has the `extends` property.
712 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
715 _loadExtends(extendName, importerPath, importerName) {
716 debug("Loading {extends:%j} relative to %s", extendName, importerPath);
718 if (extendName.startsWith("eslint:")) {
719 return this._loadExtendedBuiltInConfig(
724 if (extendName.startsWith("plugin:")) {
725 return this._loadExtendedPluginConfig(
731 return this._loadExtendedShareableConfig(
737 error.message += `\nReferenced from: ${importerPath || importerName}`;
743 * Load configs of an element in `extends`.
744 * @param {string} extendName The name of a base config.
745 * @param {string} importerName The name of the config which has the `extends` property.
746 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
749 _loadExtendedBuiltInConfig(extendName, importerName) {
750 const name = `${importerName} » ${extendName}`;
752 if (extendName === "eslint:recommended") {
753 return this._loadConfigData(eslintRecommendedPath, name);
755 if (extendName === "eslint:all") {
756 return this._loadConfigData(eslintAllPath, name);
759 throw configMissingError(extendName, importerName);
763 * Load configs of an element in `extends`.
764 * @param {string} extendName The name of a base config.
765 * @param {string} importerPath The file path which has the `extends` property.
766 * @param {string} importerName The name of the config which has the `extends` property.
767 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
770 _loadExtendedPluginConfig(extendName, importerPath, importerName) {
771 const slashIndex = extendName.lastIndexOf("/");
772 const pluginName = extendName.slice("plugin:".length, slashIndex);
773 const configName = extendName.slice(slashIndex + 1);
775 if (isFilePath(pluginName)) {
776 throw new Error("'extends' cannot use a file path for plugins.");
779 const plugin = this._loadPlugin(pluginName, importerPath, importerName);
782 plugin.definition.configs[configName];
785 return this._normalizeConfigData(
788 `${importerName} » plugin:${plugin.id}/${configName}`
792 throw plugin.error || configMissingError(extendName, importerPath);
796 * Load configs of an element in `extends`.
797 * @param {string} extendName The name of a base config.
798 * @param {string} importerPath The file path which has the `extends` property.
799 * @param {string} importerName The name of the config which has the `extends` property.
800 * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
803 _loadExtendedShareableConfig(extendName, importerPath, importerName) {
804 const { cwd } = internalSlotsMap.get(this);
805 const relativeTo = importerPath || path.join(cwd, "__placeholder__.js");
808 if (isFilePath(extendName)) {
809 request = extendName;
810 } else if (extendName.startsWith(".")) {
811 request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
813 request = naming.normalizePackageName(
822 filePath = ModuleResolver.resolve(request, relativeTo);
824 /* istanbul ignore else */
825 if (error && error.code === "MODULE_NOT_FOUND") {
826 throw configMissingError(extendName, importerPath);
831 writeDebugLogForLoading(request, relativeTo, filePath);
832 return this._loadConfigData(filePath, `${importerName} » ${request}`);
836 * Load given plugins.
837 * @param {string[]} names The plugin names to load.
838 * @param {string} importerPath The path to a config file that imports it. This is just a debug info.
839 * @param {string} importerName The name of a config file that imports it. This is just a debug info.
840 * @returns {Record<string,DependentPlugin>} The loaded parser.
843 _loadPlugins(names, importerPath, importerName) {
844 return names.reduce((map, name) => {
845 if (isFilePath(name)) {
846 throw new Error("Plugins array cannot includes file paths.");
848 const plugin = this._loadPlugin(name, importerPath, importerName);
850 map[plugin.id] = plugin;
857 * Load a given parser.
858 * @param {string} nameOrPath The package name or the path to a parser file.
859 * @param {string} importerPath The path to a config file that imports it.
860 * @param {string} importerName The name of a config file that imports it. This is just a debug info.
861 * @returns {DependentParser} The loaded parser.
863 _loadParser(nameOrPath, importerPath, importerName) {
864 debug("Loading parser %j from %s", nameOrPath, importerPath);
866 const { cwd } = internalSlotsMap.get(this);
867 const relativeTo = importerPath || path.join(cwd, "__placeholder__.js");
870 const filePath = ModuleResolver.resolve(nameOrPath, relativeTo);
872 writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
874 return new ConfigDependency({
875 definition: require(filePath),
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"),
895 debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, importerName);
896 error.message = `Failed to load parser '${nameOrPath}' declared in '${importerName}': ${error.message}`;
898 return new ConfigDependency({
908 * Load a given plugin.
909 * @param {string} name The plugin name to load.
910 * @param {string} importerPath The path to a config file that imports it. This is just a debug info.
911 * @param {string} importerName The name of a config file that imports it. This is just a debug info.
912 * @returns {DependentPlugin} The loaded plugin.
915 _loadPlugin(name, importerPath, importerName) {
916 debug("Loading plugin %j from %s", name, importerPath);
918 const { additionalPluginPool, resolvePluginsRelativeTo } = internalSlotsMap.get(this);
919 const request = naming.normalizePackageName(name, "eslint-plugin");
920 const id = naming.getShorthandName(request, "eslint-plugin");
921 const relativeTo = path.join(resolvePluginsRelativeTo, "__placeholder__.js");
923 if (name.match(/\s+/u)) {
924 const error = Object.assign(
925 new Error(`Whitespace found in plugin name '${name}'`),
927 messageTemplate: "whitespace-found",
928 messageData: { pluginName: request }
932 return new ConfigDependency({
940 // Check for additional pool.
942 additionalPluginPool.get(request) ||
943 additionalPluginPool.get(id);
946 return new ConfigDependency({
947 definition: normalizePlugin(plugin),
948 filePath: importerPath,
959 filePath = ModuleResolver.resolve(request, relativeTo);
960 } catch (resolveError) {
961 error = resolveError;
962 /* istanbul ignore else */
963 if (error && error.code === "MODULE_NOT_FOUND") {
964 error.messageTemplate = "plugin-missing";
965 error.messageData = {
967 resolvePluginsRelativeTo,
975 writeDebugLogForLoading(request, relativeTo, filePath);
977 const startTime = Date.now();
978 const pluginDefinition = require(filePath);
980 debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
982 return new ConfigDependency({
983 definition: normalizePlugin(pluginDefinition),
989 } catch (loadError) {
994 debug("Failed to load plugin '%s' declared in '%s'.", name, importerName);
995 error.message = `Failed to load plugin '${name}' declared in '${importerName}': ${error.message}`;
996 return new ConfigDependency({
1005 * Take file expression processors as config array elements.
1006 * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
1007 * @param {string} filePath The file path of this config.
1008 * @param {string} name The name of this config.
1009 * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
1012 *_takeFileExtensionProcessors(plugins, filePath, name) {
1013 for (const pluginId of Object.keys(plugins)) {
1015 plugins[pluginId] &&
1016 plugins[pluginId].definition &&
1017 plugins[pluginId].definition.processors;
1023 for (const processorId of Object.keys(processors)) {
1024 if (processorId.startsWith(".")) {
1025 yield* this._normalizeObjectConfigData(
1027 files: [`*${processorId}`],
1028 processor: `${pluginId}/${processorId}`
1031 `${name}#processors["${pluginId}/${processorId}"]`
1039 module.exports = { ConfigArrayFactory };