config-array.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /**
  2. * @fileoverview `ConfigArray` class.
  3. *
  4. * `ConfigArray` class expresses the full of a configuration. It has the entry
  5. * config file, base config files that were extended, loaded parsers, and loaded
  6. * plugins.
  7. *
  8. * `ConfigArray` class provides three properties and two methods.
  9. *
  10. * - `pluginEnvironments`
  11. * - `pluginProcessors`
  12. * - `pluginRules`
  13. * The `Map` objects that contain the members of all plugins that this
  14. * config array contains. Those map objects don't have mutation methods.
  15. * Those keys are the member ID such as `pluginId/memberName`.
  16. * - `isRoot()`
  17. * If `true` then this configuration has `root:true` property.
  18. * - `extractConfig(filePath)`
  19. * Extract the final configuration for a given file. This means merging
  20. * every config array element which that `criteria` property matched. The
  21. * `filePath` argument must be an absolute path.
  22. *
  23. * `ConfigArrayFactory` provides the loading logic of config files.
  24. *
  25. * @author Toru Nagashima <https://github.com/mysticatea>
  26. */
  27. //------------------------------------------------------------------------------
  28. // Requirements
  29. //------------------------------------------------------------------------------
  30. import { ExtractedConfig } from "./extracted-config.js";
  31. import { IgnorePattern } from "./ignore-pattern.js";
  32. //------------------------------------------------------------------------------
  33. // Helpers
  34. //------------------------------------------------------------------------------
  35. // Define types for VSCode IntelliSense.
  36. /** @typedef {import("../../shared/types").Environment} Environment */
  37. /** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
  38. /** @typedef {import("../../shared/types").RuleConf} RuleConf */
  39. /** @typedef {import("../../shared/types").Rule} Rule */
  40. /** @typedef {import("../../shared/types").Plugin} Plugin */
  41. /** @typedef {import("../../shared/types").Processor} Processor */
  42. /** @typedef {import("./config-dependency").DependentParser} DependentParser */
  43. /** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
  44. /** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
  45. /**
  46. * @typedef {Object} ConfigArrayElement
  47. * @property {string} name The name of this config element.
  48. * @property {string} filePath The path to the source file of this config element.
  49. * @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
  50. * @property {Record<string, boolean>|undefined} env The environment settings.
  51. * @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
  52. * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
  53. * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
  54. * @property {DependentParser|undefined} parser The parser loader.
  55. * @property {Object|undefined} parserOptions The parser options.
  56. * @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
  57. * @property {string|undefined} processor The processor name to refer plugin's processor.
  58. * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
  59. * @property {boolean|undefined} root The flag to express root.
  60. * @property {Record<string, RuleConf>|undefined} rules The rule settings
  61. * @property {Object|undefined} settings The shared settings.
  62. * @property {"config" | "ignore" | "implicit-processor"} type The element type.
  63. */
  64. /**
  65. * @typedef {Object} ConfigArrayInternalSlots
  66. * @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
  67. * @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
  68. * @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
  69. * @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
  70. */
  71. /** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
  72. const internalSlotsMap = new class extends WeakMap {
  73. get(key) {
  74. let value = super.get(key);
  75. if (!value) {
  76. value = {
  77. cache: new Map(),
  78. envMap: null,
  79. processorMap: null,
  80. ruleMap: null
  81. };
  82. super.set(key, value);
  83. }
  84. return value;
  85. }
  86. }();
  87. /**
  88. * Get the indices which are matched to a given file.
  89. * @param {ConfigArrayElement[]} elements The elements.
  90. * @param {string} filePath The path to a target file.
  91. * @returns {number[]} The indices.
  92. */
  93. function getMatchedIndices(elements, filePath) {
  94. const indices = [];
  95. for (let i = elements.length - 1; i >= 0; --i) {
  96. const element = elements[i];
  97. if (!element.criteria || (filePath && element.criteria.test(filePath))) {
  98. indices.push(i);
  99. }
  100. }
  101. return indices;
  102. }
  103. /**
  104. * Check if a value is a non-null object.
  105. * @param {any} x The value to check.
  106. * @returns {boolean} `true` if the value is a non-null object.
  107. */
  108. function isNonNullObject(x) {
  109. return typeof x === "object" && x !== null;
  110. }
  111. /**
  112. * Merge two objects.
  113. *
  114. * Assign every property values of `y` to `x` if `x` doesn't have the property.
  115. * If `x`'s property value is an object, it does recursive.
  116. * @param {Object} target The destination to merge
  117. * @param {Object|undefined} source The source to merge.
  118. * @returns {void}
  119. */
  120. function mergeWithoutOverwrite(target, source) {
  121. if (!isNonNullObject(source)) {
  122. return;
  123. }
  124. for (const key of Object.keys(source)) {
  125. if (key === "__proto__") {
  126. continue;
  127. }
  128. if (isNonNullObject(target[key])) {
  129. mergeWithoutOverwrite(target[key], source[key]);
  130. } else if (target[key] === void 0) {
  131. if (isNonNullObject(source[key])) {
  132. target[key] = Array.isArray(source[key]) ? [] : {};
  133. mergeWithoutOverwrite(target[key], source[key]);
  134. } else if (source[key] !== void 0) {
  135. target[key] = source[key];
  136. }
  137. }
  138. }
  139. }
  140. /**
  141. * The error for plugin conflicts.
  142. */
  143. class PluginConflictError extends Error {
  144. /**
  145. * Initialize this error object.
  146. * @param {string} pluginId The plugin ID.
  147. * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
  148. */
  149. constructor(pluginId, plugins) {
  150. super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
  151. this.messageTemplate = "plugin-conflict";
  152. this.messageData = { pluginId, plugins };
  153. }
  154. }
  155. /**
  156. * Merge plugins.
  157. * `target`'s definition is prior to `source`'s.
  158. * @param {Record<string, DependentPlugin>} target The destination to merge
  159. * @param {Record<string, DependentPlugin>|undefined} source The source to merge.
  160. * @returns {void}
  161. * @throws {PluginConflictError} When a plugin was conflicted.
  162. */
  163. function mergePlugins(target, source) {
  164. if (!isNonNullObject(source)) {
  165. return;
  166. }
  167. for (const key of Object.keys(source)) {
  168. if (key === "__proto__") {
  169. continue;
  170. }
  171. const targetValue = target[key];
  172. const sourceValue = source[key];
  173. // Adopt the plugin which was found at first.
  174. if (targetValue === void 0) {
  175. if (sourceValue.error) {
  176. throw sourceValue.error;
  177. }
  178. target[key] = sourceValue;
  179. } else if (sourceValue.filePath !== targetValue.filePath) {
  180. throw new PluginConflictError(key, [
  181. {
  182. filePath: targetValue.filePath,
  183. importerName: targetValue.importerName
  184. },
  185. {
  186. filePath: sourceValue.filePath,
  187. importerName: sourceValue.importerName
  188. }
  189. ]);
  190. }
  191. }
  192. }
  193. /**
  194. * Merge rule configs.
  195. * `target`'s definition is prior to `source`'s.
  196. * @param {Record<string, Array>} target The destination to merge
  197. * @param {Record<string, RuleConf>|undefined} source The source to merge.
  198. * @returns {void}
  199. */
  200. function mergeRuleConfigs(target, source) {
  201. if (!isNonNullObject(source)) {
  202. return;
  203. }
  204. for (const key of Object.keys(source)) {
  205. if (key === "__proto__") {
  206. continue;
  207. }
  208. const targetDef = target[key];
  209. const sourceDef = source[key];
  210. // Adopt the rule config which was found at first.
  211. if (targetDef === void 0) {
  212. if (Array.isArray(sourceDef)) {
  213. target[key] = [...sourceDef];
  214. } else {
  215. target[key] = [sourceDef];
  216. }
  217. /*
  218. * If the first found rule config is severity only and the current rule
  219. * config has options, merge the severity and the options.
  220. */
  221. } else if (
  222. targetDef.length === 1 &&
  223. Array.isArray(sourceDef) &&
  224. sourceDef.length >= 2
  225. ) {
  226. targetDef.push(...sourceDef.slice(1));
  227. }
  228. }
  229. }
  230. /**
  231. * Create the extracted config.
  232. * @param {ConfigArray} instance The config elements.
  233. * @param {number[]} indices The indices to use.
  234. * @returns {ExtractedConfig} The extracted config.
  235. * @throws {Error} When a plugin is conflicted.
  236. */
  237. function createConfig(instance, indices) {
  238. const config = new ExtractedConfig();
  239. const ignorePatterns = [];
  240. // Merge elements.
  241. for (const index of indices) {
  242. const element = instance[index];
  243. // Adopt the parser which was found at first.
  244. if (!config.parser && element.parser) {
  245. if (element.parser.error) {
  246. throw element.parser.error;
  247. }
  248. config.parser = element.parser;
  249. }
  250. // Adopt the processor which was found at first.
  251. if (!config.processor && element.processor) {
  252. config.processor = element.processor;
  253. }
  254. // Adopt the noInlineConfig which was found at first.
  255. if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
  256. config.noInlineConfig = element.noInlineConfig;
  257. config.configNameOfNoInlineConfig = element.name;
  258. }
  259. // Adopt the reportUnusedDisableDirectives which was found at first.
  260. if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
  261. config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
  262. }
  263. // Collect ignorePatterns
  264. if (element.ignorePattern) {
  265. ignorePatterns.push(element.ignorePattern);
  266. }
  267. // Merge others.
  268. mergeWithoutOverwrite(config.env, element.env);
  269. mergeWithoutOverwrite(config.globals, element.globals);
  270. mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
  271. mergeWithoutOverwrite(config.settings, element.settings);
  272. mergePlugins(config.plugins, element.plugins);
  273. mergeRuleConfigs(config.rules, element.rules);
  274. }
  275. // Create the predicate function for ignore patterns.
  276. if (ignorePatterns.length > 0) {
  277. config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
  278. }
  279. return config;
  280. }
  281. /**
  282. * Collect definitions.
  283. * @template T, U
  284. * @param {string} pluginId The plugin ID for prefix.
  285. * @param {Record<string,T>} defs The definitions to collect.
  286. * @param {Map<string, U>} map The map to output.
  287. * @returns {void}
  288. */
  289. function collect(pluginId, defs, map) {
  290. if (defs) {
  291. const prefix = pluginId && `${pluginId}/`;
  292. for (const [key, value] of Object.entries(defs)) {
  293. map.set(`${prefix}${key}`, value);
  294. }
  295. }
  296. }
  297. /**
  298. * Delete the mutation methods from a given map.
  299. * @param {Map<any, any>} map The map object to delete.
  300. * @returns {void}
  301. */
  302. function deleteMutationMethods(map) {
  303. Object.defineProperties(map, {
  304. clear: { configurable: true, value: void 0 },
  305. delete: { configurable: true, value: void 0 },
  306. set: { configurable: true, value: void 0 }
  307. });
  308. }
  309. /**
  310. * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
  311. * @param {ConfigArrayElement[]} elements The config elements.
  312. * @param {ConfigArrayInternalSlots} slots The internal slots.
  313. * @returns {void}
  314. */
  315. function initPluginMemberMaps(elements, slots) {
  316. const processed = new Set();
  317. slots.envMap = new Map();
  318. slots.processorMap = new Map();
  319. slots.ruleMap = new Map();
  320. for (const element of elements) {
  321. if (!element.plugins) {
  322. continue;
  323. }
  324. for (const [pluginId, value] of Object.entries(element.plugins)) {
  325. const plugin = value.definition;
  326. if (!plugin || processed.has(pluginId)) {
  327. continue;
  328. }
  329. processed.add(pluginId);
  330. collect(pluginId, plugin.environments, slots.envMap);
  331. collect(pluginId, plugin.processors, slots.processorMap);
  332. collect(pluginId, plugin.rules, slots.ruleMap);
  333. }
  334. }
  335. deleteMutationMethods(slots.envMap);
  336. deleteMutationMethods(slots.processorMap);
  337. deleteMutationMethods(slots.ruleMap);
  338. }
  339. /**
  340. * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
  341. * @param {ConfigArray} instance The config elements.
  342. * @returns {ConfigArrayInternalSlots} The extracted config.
  343. */
  344. function ensurePluginMemberMaps(instance) {
  345. const slots = internalSlotsMap.get(instance);
  346. if (!slots.ruleMap) {
  347. initPluginMemberMaps(instance, slots);
  348. }
  349. return slots;
  350. }
  351. //------------------------------------------------------------------------------
  352. // Public Interface
  353. //------------------------------------------------------------------------------
  354. /**
  355. * The Config Array.
  356. *
  357. * `ConfigArray` instance contains all settings, parsers, and plugins.
  358. * You need to call `ConfigArray#extractConfig(filePath)` method in order to
  359. * extract, merge and get only the config data which is related to an arbitrary
  360. * file.
  361. * @extends {Array<ConfigArrayElement>}
  362. */
  363. class ConfigArray extends Array {
  364. /**
  365. * Get the plugin environments.
  366. * The returned map cannot be mutated.
  367. * @type {ReadonlyMap<string, Environment>} The plugin environments.
  368. */
  369. get pluginEnvironments() {
  370. return ensurePluginMemberMaps(this).envMap;
  371. }
  372. /**
  373. * Get the plugin processors.
  374. * The returned map cannot be mutated.
  375. * @type {ReadonlyMap<string, Processor>} The plugin processors.
  376. */
  377. get pluginProcessors() {
  378. return ensurePluginMemberMaps(this).processorMap;
  379. }
  380. /**
  381. * Get the plugin rules.
  382. * The returned map cannot be mutated.
  383. * @returns {ReadonlyMap<string, Rule>} The plugin rules.
  384. */
  385. get pluginRules() {
  386. return ensurePluginMemberMaps(this).ruleMap;
  387. }
  388. /**
  389. * Check if this config has `root` flag.
  390. * @returns {boolean} `true` if this config array is root.
  391. */
  392. isRoot() {
  393. for (let i = this.length - 1; i >= 0; --i) {
  394. const root = this[i].root;
  395. if (typeof root === "boolean") {
  396. return root;
  397. }
  398. }
  399. return false;
  400. }
  401. /**
  402. * Extract the config data which is related to a given file.
  403. * @param {string} filePath The absolute path to the target file.
  404. * @returns {ExtractedConfig} The extracted config data.
  405. */
  406. extractConfig(filePath) {
  407. const { cache } = internalSlotsMap.get(this);
  408. const indices = getMatchedIndices(this, filePath);
  409. const cacheKey = indices.join(",");
  410. if (!cache.has(cacheKey)) {
  411. cache.set(cacheKey, createConfig(this, indices));
  412. }
  413. return cache.get(cacheKey);
  414. }
  415. /**
  416. * Check if a given path is an additional lint target.
  417. * @param {string} filePath The absolute path to the target file.
  418. * @returns {boolean} `true` if the file is an additional lint target.
  419. */
  420. isAdditionalTargetPath(filePath) {
  421. for (const { criteria, type } of this) {
  422. if (
  423. type === "config" &&
  424. criteria &&
  425. !criteria.endsWithWildcard &&
  426. criteria.test(filePath)
  427. ) {
  428. return true;
  429. }
  430. }
  431. return false;
  432. }
  433. }
  434. /**
  435. * Get the used extracted configs.
  436. * CLIEngine will use this method to collect used deprecated rules.
  437. * @param {ConfigArray} instance The config array object to get.
  438. * @returns {ExtractedConfig[]} The used extracted configs.
  439. * @private
  440. */
  441. function getUsedExtractedConfigs(instance) {
  442. const { cache } = internalSlotsMap.get(instance);
  443. return Array.from(cache.values());
  444. }
  445. export {
  446. ConfigArray,
  447. getUsedExtractedConfigs
  448. };