@dineroregnskab/eslint-plugin-custom-rules 2.0.6 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/README.md +49 -9
  2. package/eslint-plugin-custom-rules.js +10 -4
  3. package/package.json +2 -4
  4. package/rules/replace-first-with-take.js +31 -0
  5. package/rules/use-danish-currency-pipe.js +53 -0
  6. package/willy.yaml +5 -0
  7. package/node_modules/@aashutoshrathi/word-wrap/LICENSE +0 -21
  8. package/node_modules/@aashutoshrathi/word-wrap/README.md +0 -182
  9. package/node_modules/@aashutoshrathi/word-wrap/index.d.ts +0 -50
  10. package/node_modules/@aashutoshrathi/word-wrap/index.js +0 -52
  11. package/node_modules/@aashutoshrathi/word-wrap/package.json +0 -81
  12. package/node_modules/@angular-eslint/bundled-angular-compiler/README.md +0 -1
  13. package/node_modules/@angular-eslint/bundled-angular-compiler/dist/index.d.ts +0 -5
  14. package/node_modules/@angular-eslint/bundled-angular-compiler/dist/index.js +0 -32004
  15. package/node_modules/@angular-eslint/bundled-angular-compiler/package.json +0 -19
  16. package/node_modules/@angular-eslint/template-parser/LICENSE +0 -21
  17. package/node_modules/@angular-eslint/template-parser/README.md +0 -1
  18. package/node_modules/@angular-eslint/template-parser/dist/convert-source-span-to-loc.d.ts +0 -6
  19. package/node_modules/@angular-eslint/template-parser/dist/convert-source-span-to-loc.js +0 -69
  20. package/node_modules/@angular-eslint/template-parser/dist/index.d.ts +0 -44
  21. package/node_modules/@angular-eslint/template-parser/dist/index.js +0 -219
  22. package/node_modules/@angular-eslint/template-parser/package.json +0 -28
  23. package/node_modules/@eslint/eslintrc/LICENSE +0 -19
  24. package/node_modules/@eslint/eslintrc/README.md +0 -115
  25. package/node_modules/@eslint/eslintrc/conf/config-schema.js +0 -79
  26. package/node_modules/@eslint/eslintrc/conf/environments.js +0 -215
  27. package/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs +0 -1104
  28. package/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map +0 -1
  29. package/node_modules/@eslint/eslintrc/dist/eslintrc.cjs +0 -4333
  30. package/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map +0 -1
  31. package/node_modules/@eslint/eslintrc/lib/cascading-config-array-factory.js +0 -532
  32. package/node_modules/@eslint/eslintrc/lib/config-array/config-array.js +0 -523
  33. package/node_modules/@eslint/eslintrc/lib/config-array/config-dependency.js +0 -115
  34. package/node_modules/@eslint/eslintrc/lib/config-array/extracted-config.js +0 -145
  35. package/node_modules/@eslint/eslintrc/lib/config-array/ignore-pattern.js +0 -238
  36. package/node_modules/@eslint/eslintrc/lib/config-array/index.js +0 -19
  37. package/node_modules/@eslint/eslintrc/lib/config-array/override-tester.js +0 -225
  38. package/node_modules/@eslint/eslintrc/lib/config-array-factory.js +0 -1149
  39. package/node_modules/@eslint/eslintrc/lib/flat-compat.js +0 -318
  40. package/node_modules/@eslint/eslintrc/lib/index-universal.js +0 -29
  41. package/node_modules/@eslint/eslintrc/lib/index.js +0 -56
  42. package/node_modules/@eslint/eslintrc/lib/shared/ajv.js +0 -191
  43. package/node_modules/@eslint/eslintrc/lib/shared/config-ops.js +0 -135
  44. package/node_modules/@eslint/eslintrc/lib/shared/config-validator.js +0 -325
  45. package/node_modules/@eslint/eslintrc/lib/shared/deprecation-warnings.js +0 -63
  46. package/node_modules/@eslint/eslintrc/lib/shared/naming.js +0 -96
  47. package/node_modules/@eslint/eslintrc/lib/shared/relative-module-resolver.js +0 -42
  48. package/node_modules/@eslint/eslintrc/lib/shared/types.js +0 -149
  49. package/node_modules/@eslint/eslintrc/package.json +0 -82
  50. package/node_modules/@eslint/eslintrc/universal.js +0 -9
  51. package/node_modules/@eslint/js/LICENSE +0 -19
  52. package/node_modules/@eslint/js/README.md +0 -57
  53. package/node_modules/@eslint/js/package.json +0 -31
  54. package/node_modules/@eslint/js/src/configs/eslint-all.js +0 -211
  55. package/node_modules/@eslint/js/src/configs/eslint-recommended.js +0 -76
  56. package/node_modules/@eslint/js/src/index.js +0 -17
  57. package/node_modules/@eslint-community/eslint-utils/LICENSE +0 -21
  58. package/node_modules/@eslint-community/eslint-utils/README.md +0 -37
  59. package/node_modules/@eslint-community/eslint-utils/index.js +0 -2068
  60. package/node_modules/@eslint-community/eslint-utils/index.js.map +0 -1
  61. package/node_modules/@eslint-community/eslint-utils/index.mjs +0 -2027
  62. package/node_modules/@eslint-community/eslint-utils/index.mjs.map +0 -1
  63. package/node_modules/@eslint-community/eslint-utils/package.json +0 -73
  64. package/node_modules/@eslint-community/regexpp/LICENSE +0 -21
  65. package/node_modules/@eslint-community/regexpp/README.md +0 -177
  66. package/node_modules/@eslint-community/regexpp/index.d.ts +0 -1065
  67. package/node_modules/@eslint-community/regexpp/index.js +0 -2747
  68. package/node_modules/@eslint-community/regexpp/index.js.map +0 -1
  69. package/node_modules/@eslint-community/regexpp/index.mjs +0 -2737
  70. package/node_modules/@eslint-community/regexpp/index.mjs.map +0 -1
  71. package/node_modules/@eslint-community/regexpp/package.json +0 -93
  72. package/node_modules/@humanwhocodes/config-array/LICENSE +0 -201
  73. package/node_modules/@humanwhocodes/config-array/README.md +0 -342
  74. package/node_modules/@humanwhocodes/config-array/api.js +0 -1061
  75. package/node_modules/@humanwhocodes/config-array/package.json +0 -61
  76. package/node_modules/@humanwhocodes/module-importer/CHANGELOG.md +0 -15
  77. package/node_modules/@humanwhocodes/module-importer/LICENSE +0 -201
  78. package/node_modules/@humanwhocodes/module-importer/README.md +0 -80
  79. package/node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs +0 -22
  80. package/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts +0 -27
  81. package/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts +0 -2
  82. package/node_modules/@humanwhocodes/module-importer/dist/module-importer.js +0 -18
  83. package/node_modules/@humanwhocodes/module-importer/package.json +0 -65
  84. package/node_modules/@humanwhocodes/module-importer/src/module-importer.cjs +0 -81
  85. package/node_modules/@humanwhocodes/module-importer/src/module-importer.js +0 -22
  86. package/node_modules/@humanwhocodes/object-schema/.eslintrc.js +0 -29
  87. package/node_modules/@humanwhocodes/object-schema/.github/workflows/nodejs-test.yml +0 -27
  88. package/node_modules/@humanwhocodes/object-schema/.github/workflows/release-please.yml +0 -39
  89. package/node_modules/@humanwhocodes/object-schema/CHANGELOG.md +0 -26
  90. package/node_modules/@humanwhocodes/object-schema/LICENSE +0 -29
  91. package/node_modules/@humanwhocodes/object-schema/README.md +0 -234
  92. package/node_modules/@humanwhocodes/object-schema/package.json +0 -33
  93. package/node_modules/@humanwhocodes/object-schema/src/index.js +0 -7
  94. package/node_modules/@humanwhocodes/object-schema/src/merge-strategy.js +0 -53
  95. package/node_modules/@humanwhocodes/object-schema/src/object-schema.js +0 -301
  96. package/node_modules/@humanwhocodes/object-schema/src/validation-strategy.js +0 -102
  97. package/node_modules/@humanwhocodes/object-schema/tests/merge-strategy.js +0 -66
  98. package/node_modules/@humanwhocodes/object-schema/tests/object-schema.js +0 -659
  99. package/node_modules/@humanwhocodes/object-schema/tests/validation-strategy.js +0 -186
  100. package/node_modules/@nodelib/fs.scandir/LICENSE +0 -21
  101. package/node_modules/@nodelib/fs.scandir/README.md +0 -171
  102. package/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts +0 -20
  103. package/node_modules/@nodelib/fs.scandir/out/adapters/fs.js +0 -19
  104. package/node_modules/@nodelib/fs.scandir/out/constants.d.ts +0 -4
  105. package/node_modules/@nodelib/fs.scandir/out/constants.js +0 -17
  106. package/node_modules/@nodelib/fs.scandir/out/index.d.ts +0 -12
  107. package/node_modules/@nodelib/fs.scandir/out/index.js +0 -26
  108. package/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts +0 -7
  109. package/node_modules/@nodelib/fs.scandir/out/providers/async.js +0 -104
  110. package/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts +0 -1
  111. package/node_modules/@nodelib/fs.scandir/out/providers/common.js +0 -13
  112. package/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts +0 -5
  113. package/node_modules/@nodelib/fs.scandir/out/providers/sync.js +0 -54
  114. package/node_modules/@nodelib/fs.scandir/out/settings.d.ts +0 -20
  115. package/node_modules/@nodelib/fs.scandir/out/settings.js +0 -24
  116. package/node_modules/@nodelib/fs.scandir/out/types/index.d.ts +0 -20
  117. package/node_modules/@nodelib/fs.scandir/out/types/index.js +0 -2
  118. package/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts +0 -2
  119. package/node_modules/@nodelib/fs.scandir/out/utils/fs.js +0 -19
  120. package/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts +0 -2
  121. package/node_modules/@nodelib/fs.scandir/out/utils/index.js +0 -5
  122. package/node_modules/@nodelib/fs.scandir/package.json +0 -44
  123. package/node_modules/@nodelib/fs.stat/LICENSE +0 -21
  124. package/node_modules/@nodelib/fs.stat/README.md +0 -126
  125. package/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts +0 -13
  126. package/node_modules/@nodelib/fs.stat/out/adapters/fs.js +0 -17
  127. package/node_modules/@nodelib/fs.stat/out/index.d.ts +0 -12
  128. package/node_modules/@nodelib/fs.stat/out/index.js +0 -26
  129. package/node_modules/@nodelib/fs.stat/out/providers/async.d.ts +0 -4
  130. package/node_modules/@nodelib/fs.stat/out/providers/async.js +0 -36
  131. package/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts +0 -3
  132. package/node_modules/@nodelib/fs.stat/out/providers/sync.js +0 -23
  133. package/node_modules/@nodelib/fs.stat/out/settings.d.ts +0 -16
  134. package/node_modules/@nodelib/fs.stat/out/settings.js +0 -16
  135. package/node_modules/@nodelib/fs.stat/out/types/index.d.ts +0 -4
  136. package/node_modules/@nodelib/fs.stat/out/types/index.js +0 -2
  137. package/node_modules/@nodelib/fs.stat/package.json +0 -37
  138. package/node_modules/@nodelib/fs.walk/LICENSE +0 -21
  139. package/node_modules/@nodelib/fs.walk/README.md +0 -215
  140. package/node_modules/@nodelib/fs.walk/out/index.d.ts +0 -14
  141. package/node_modules/@nodelib/fs.walk/out/index.js +0 -34
  142. package/node_modules/@nodelib/fs.walk/out/providers/async.d.ts +0 -12
  143. package/node_modules/@nodelib/fs.walk/out/providers/async.js +0 -30
  144. package/node_modules/@nodelib/fs.walk/out/providers/index.d.ts +0 -4
  145. package/node_modules/@nodelib/fs.walk/out/providers/index.js +0 -9
  146. package/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts +0 -12
  147. package/node_modules/@nodelib/fs.walk/out/providers/stream.js +0 -34
  148. package/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts +0 -10
  149. package/node_modules/@nodelib/fs.walk/out/providers/sync.js +0 -14
  150. package/node_modules/@nodelib/fs.walk/out/readers/async.d.ts +0 -30
  151. package/node_modules/@nodelib/fs.walk/out/readers/async.js +0 -97
  152. package/node_modules/@nodelib/fs.walk/out/readers/common.d.ts +0 -7
  153. package/node_modules/@nodelib/fs.walk/out/readers/common.js +0 -31
  154. package/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts +0 -6
  155. package/node_modules/@nodelib/fs.walk/out/readers/reader.js +0 -11
  156. package/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts +0 -15
  157. package/node_modules/@nodelib/fs.walk/out/readers/sync.js +0 -59
  158. package/node_modules/@nodelib/fs.walk/out/settings.d.ts +0 -30
  159. package/node_modules/@nodelib/fs.walk/out/settings.js +0 -26
  160. package/node_modules/@nodelib/fs.walk/out/types/index.d.ts +0 -8
  161. package/node_modules/@nodelib/fs.walk/out/types/index.js +0 -2
  162. package/node_modules/@nodelib/fs.walk/package.json +0 -44
  163. package/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml +0 -31
  164. package/node_modules/@ungap/structured-clone/LICENSE +0 -15
  165. package/node_modules/@ungap/structured-clone/README.md +0 -95
  166. package/node_modules/@ungap/structured-clone/cjs/deserialize.js +0 -78
  167. package/node_modules/@ungap/structured-clone/cjs/index.js +0 -27
  168. package/node_modules/@ungap/structured-clone/cjs/json.js +0 -24
  169. package/node_modules/@ungap/structured-clone/cjs/package.json +0 -1
  170. package/node_modules/@ungap/structured-clone/cjs/serialize.js +0 -160
  171. package/node_modules/@ungap/structured-clone/cjs/types.js +0 -22
  172. package/node_modules/@ungap/structured-clone/esm/deserialize.js +0 -79
  173. package/node_modules/@ungap/structured-clone/esm/index.js +0 -25
  174. package/node_modules/@ungap/structured-clone/esm/json.js +0 -21
  175. package/node_modules/@ungap/structured-clone/esm/serialize.js +0 -161
  176. package/node_modules/@ungap/structured-clone/esm/types.js +0 -11
  177. package/node_modules/@ungap/structured-clone/package.json +0 -53
  178. package/node_modules/@ungap/structured-clone/structured-json.js +0 -1
@@ -1,4333 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var debugOrig = require('debug');
6
- var fs = require('fs');
7
- var importFresh = require('import-fresh');
8
- var Module = require('module');
9
- var path = require('path');
10
- var stripComments = require('strip-json-comments');
11
- var assert = require('assert');
12
- var ignore = require('ignore');
13
- var util = require('util');
14
- var minimatch = require('minimatch');
15
- var Ajv = require('ajv');
16
- var globals = require('globals');
17
- var os = require('os');
18
-
19
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
20
-
21
- var debugOrig__default = /*#__PURE__*/_interopDefaultLegacy(debugOrig);
22
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
23
- var importFresh__default = /*#__PURE__*/_interopDefaultLegacy(importFresh);
24
- var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);
25
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
26
- var stripComments__default = /*#__PURE__*/_interopDefaultLegacy(stripComments);
27
- var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
28
- var ignore__default = /*#__PURE__*/_interopDefaultLegacy(ignore);
29
- var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
30
- var minimatch__default = /*#__PURE__*/_interopDefaultLegacy(minimatch);
31
- var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
32
- var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals);
33
- var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
34
-
35
- /**
36
- * @fileoverview `IgnorePattern` class.
37
- *
38
- * `IgnorePattern` class has the set of glob patterns and the base path.
39
- *
40
- * It provides two static methods.
41
- *
42
- * - `IgnorePattern.createDefaultIgnore(cwd)`
43
- * Create the default predicate function.
44
- * - `IgnorePattern.createIgnore(ignorePatterns)`
45
- * Create the predicate function from multiple `IgnorePattern` objects.
46
- *
47
- * It provides two properties and a method.
48
- *
49
- * - `patterns`
50
- * The glob patterns that ignore to lint.
51
- * - `basePath`
52
- * The base path of the glob patterns. If absolute paths existed in the
53
- * glob patterns, those are handled as relative paths to the base path.
54
- * - `getPatternsRelativeTo(basePath)`
55
- * Get `patterns` as modified for a given base path. It modifies the
56
- * absolute paths in the patterns as prepending the difference of two base
57
- * paths.
58
- *
59
- * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
60
- * `ignorePatterns` properties.
61
- *
62
- * @author Toru Nagashima <https://github.com/mysticatea>
63
- */
64
-
65
- const debug$3 = debugOrig__default["default"]("eslintrc:ignore-pattern");
66
-
67
- /** @typedef {ReturnType<import("ignore").default>} Ignore */
68
-
69
- //------------------------------------------------------------------------------
70
- // Helpers
71
- //------------------------------------------------------------------------------
72
-
73
- /**
74
- * Get the path to the common ancestor directory of given paths.
75
- * @param {string[]} sourcePaths The paths to calculate the common ancestor.
76
- * @returns {string} The path to the common ancestor directory.
77
- */
78
- function getCommonAncestorPath(sourcePaths) {
79
- let result = sourcePaths[0];
80
-
81
- for (let i = 1; i < sourcePaths.length; ++i) {
82
- const a = result;
83
- const b = sourcePaths[i];
84
-
85
- // Set the shorter one (it's the common ancestor if one includes the other).
86
- result = a.length < b.length ? a : b;
87
-
88
- // Set the common ancestor.
89
- for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
90
- if (a[j] !== b[j]) {
91
- result = a.slice(0, lastSepPos);
92
- break;
93
- }
94
- if (a[j] === path__default["default"].sep) {
95
- lastSepPos = j;
96
- }
97
- }
98
- }
99
-
100
- let resolvedResult = result || path__default["default"].sep;
101
-
102
- // if Windows common ancestor is root of drive must have trailing slash to be absolute.
103
- if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
104
- resolvedResult += path__default["default"].sep;
105
- }
106
- return resolvedResult;
107
- }
108
-
109
- /**
110
- * Make relative path.
111
- * @param {string} from The source path to get relative path.
112
- * @param {string} to The destination path to get relative path.
113
- * @returns {string} The relative path.
114
- */
115
- function relative(from, to) {
116
- const relPath = path__default["default"].relative(from, to);
117
-
118
- if (path__default["default"].sep === "/") {
119
- return relPath;
120
- }
121
- return relPath.split(path__default["default"].sep).join("/");
122
- }
123
-
124
- /**
125
- * Get the trailing slash if existed.
126
- * @param {string} filePath The path to check.
127
- * @returns {string} The trailing slash if existed.
128
- */
129
- function dirSuffix(filePath) {
130
- const isDir = (
131
- filePath.endsWith(path__default["default"].sep) ||
132
- (process.platform === "win32" && filePath.endsWith("/"))
133
- );
134
-
135
- return isDir ? "/" : "";
136
- }
137
-
138
- const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
139
- const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]);
140
-
141
- //------------------------------------------------------------------------------
142
- // Public
143
- //------------------------------------------------------------------------------
144
-
145
- class IgnorePattern {
146
-
147
- /**
148
- * The default patterns.
149
- * @type {string[]}
150
- */
151
- static get DefaultPatterns() {
152
- return DefaultPatterns;
153
- }
154
-
155
- /**
156
- * Create the default predicate function.
157
- * @param {string} cwd The current working directory.
158
- * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
159
- * The preficate function.
160
- * The first argument is an absolute path that is checked.
161
- * The second argument is the flag to not ignore dotfiles.
162
- * If the predicate function returned `true`, it means the path should be ignored.
163
- */
164
- static createDefaultIgnore(cwd) {
165
- return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
166
- }
167
-
168
- /**
169
- * Create the predicate function from multiple `IgnorePattern` objects.
170
- * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
171
- * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
172
- * The preficate function.
173
- * The first argument is an absolute path that is checked.
174
- * The second argument is the flag to not ignore dotfiles.
175
- * If the predicate function returned `true`, it means the path should be ignored.
176
- */
177
- static createIgnore(ignorePatterns) {
178
- debug$3("Create with: %o", ignorePatterns);
179
-
180
- const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
181
- const patterns = [].concat(
182
- ...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))
183
- );
184
- const ig = ignore__default["default"]({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);
185
- const dotIg = ignore__default["default"]({ allowRelativePaths: true }).add(patterns);
186
-
187
- debug$3(" processed: %o", { basePath, patterns });
188
-
189
- return Object.assign(
190
- (filePath, dot = false) => {
191
- assert__default["default"](path__default["default"].isAbsolute(filePath), "'filePath' should be an absolute path.");
192
- const relPathRaw = relative(basePath, filePath);
193
- const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
194
- const adoptedIg = dot ? dotIg : ig;
195
- const result = relPath !== "" && adoptedIg.ignores(relPath);
196
-
197
- debug$3("Check", { filePath, dot, relativePath: relPath, result });
198
- return result;
199
- },
200
- { basePath, patterns }
201
- );
202
- }
203
-
204
- /**
205
- * Initialize a new `IgnorePattern` instance.
206
- * @param {string[]} patterns The glob patterns that ignore to lint.
207
- * @param {string} basePath The base path of `patterns`.
208
- */
209
- constructor(patterns, basePath) {
210
- assert__default["default"](path__default["default"].isAbsolute(basePath), "'basePath' should be an absolute path.");
211
-
212
- /**
213
- * The glob patterns that ignore to lint.
214
- * @type {string[]}
215
- */
216
- this.patterns = patterns;
217
-
218
- /**
219
- * The base path of `patterns`.
220
- * @type {string}
221
- */
222
- this.basePath = basePath;
223
-
224
- /**
225
- * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
226
- *
227
- * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
228
- * It's `false` as-is for `ignorePatterns` property in config files.
229
- * @type {boolean}
230
- */
231
- this.loose = false;
232
- }
233
-
234
- /**
235
- * Get `patterns` as modified for a given base path. It modifies the
236
- * absolute paths in the patterns as prepending the difference of two base
237
- * paths.
238
- * @param {string} newBasePath The base path.
239
- * @returns {string[]} Modifired patterns.
240
- */
241
- getPatternsRelativeTo(newBasePath) {
242
- assert__default["default"](path__default["default"].isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
243
- const { basePath, loose, patterns } = this;
244
-
245
- if (newBasePath === basePath) {
246
- return patterns;
247
- }
248
- const prefix = `/${relative(newBasePath, basePath)}`;
249
-
250
- return patterns.map(pattern => {
251
- const negative = pattern.startsWith("!");
252
- const head = negative ? "!" : "";
253
- const body = negative ? pattern.slice(1) : pattern;
254
-
255
- if (body.startsWith("/") || body.startsWith("../")) {
256
- return `${head}${prefix}${body}`;
257
- }
258
- return loose ? pattern : `${head}${prefix}/**/${body}`;
259
- });
260
- }
261
- }
262
-
263
- /**
264
- * @fileoverview `ExtractedConfig` class.
265
- *
266
- * `ExtractedConfig` class expresses a final configuration for a specific file.
267
- *
268
- * It provides one method.
269
- *
270
- * - `toCompatibleObjectAsConfigFileContent()`
271
- * Convert this configuration to the compatible object as the content of
272
- * config files. It converts the loaded parser and plugins to strings.
273
- * `CLIEngine#getConfigForFile(filePath)` method uses this method.
274
- *
275
- * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
276
- *
277
- * @author Toru Nagashima <https://github.com/mysticatea>
278
- */
279
-
280
- // For VSCode intellisense
281
- /** @typedef {import("../../shared/types").ConfigData} ConfigData */
282
- /** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
283
- /** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
284
- /** @typedef {import("./config-dependency").DependentParser} DependentParser */
285
- /** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
286
-
287
- /**
288
- * Check if `xs` starts with `ys`.
289
- * @template T
290
- * @param {T[]} xs The array to check.
291
- * @param {T[]} ys The array that may be the first part of `xs`.
292
- * @returns {boolean} `true` if `xs` starts with `ys`.
293
- */
294
- function startsWith(xs, ys) {
295
- return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
296
- }
297
-
298
- /**
299
- * The class for extracted config data.
300
- */
301
- class ExtractedConfig {
302
- constructor() {
303
-
304
- /**
305
- * The config name what `noInlineConfig` setting came from.
306
- * @type {string}
307
- */
308
- this.configNameOfNoInlineConfig = "";
309
-
310
- /**
311
- * Environments.
312
- * @type {Record<string, boolean>}
313
- */
314
- this.env = {};
315
-
316
- /**
317
- * Global variables.
318
- * @type {Record<string, GlobalConf>}
319
- */
320
- this.globals = {};
321
-
322
- /**
323
- * The glob patterns that ignore to lint.
324
- * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
325
- */
326
- this.ignores = void 0;
327
-
328
- /**
329
- * The flag that disables directive comments.
330
- * @type {boolean|undefined}
331
- */
332
- this.noInlineConfig = void 0;
333
-
334
- /**
335
- * Parser definition.
336
- * @type {DependentParser|null}
337
- */
338
- this.parser = null;
339
-
340
- /**
341
- * Options for the parser.
342
- * @type {Object}
343
- */
344
- this.parserOptions = {};
345
-
346
- /**
347
- * Plugin definitions.
348
- * @type {Record<string, DependentPlugin>}
349
- */
350
- this.plugins = {};
351
-
352
- /**
353
- * Processor ID.
354
- * @type {string|null}
355
- */
356
- this.processor = null;
357
-
358
- /**
359
- * The flag that reports unused `eslint-disable` directive comments.
360
- * @type {boolean|undefined}
361
- */
362
- this.reportUnusedDisableDirectives = void 0;
363
-
364
- /**
365
- * Rule settings.
366
- * @type {Record<string, [SeverityConf, ...any[]]>}
367
- */
368
- this.rules = {};
369
-
370
- /**
371
- * Shared settings.
372
- * @type {Object}
373
- */
374
- this.settings = {};
375
- }
376
-
377
- /**
378
- * Convert this config to the compatible object as a config file content.
379
- * @returns {ConfigData} The converted object.
380
- */
381
- toCompatibleObjectAsConfigFileContent() {
382
- const {
383
- /* eslint-disable no-unused-vars */
384
- configNameOfNoInlineConfig: _ignore1,
385
- processor: _ignore2,
386
- /* eslint-enable no-unused-vars */
387
- ignores,
388
- ...config
389
- } = this;
390
-
391
- config.parser = config.parser && config.parser.filePath;
392
- config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
393
- config.ignorePatterns = ignores ? ignores.patterns : [];
394
-
395
- // Strip the default patterns from `ignorePatterns`.
396
- if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
397
- config.ignorePatterns =
398
- config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
399
- }
400
-
401
- return config;
402
- }
403
- }
404
-
405
- /**
406
- * @fileoverview `ConfigArray` class.
407
- *
408
- * `ConfigArray` class expresses the full of a configuration. It has the entry
409
- * config file, base config files that were extended, loaded parsers, and loaded
410
- * plugins.
411
- *
412
- * `ConfigArray` class provides three properties and two methods.
413
- *
414
- * - `pluginEnvironments`
415
- * - `pluginProcessors`
416
- * - `pluginRules`
417
- * The `Map` objects that contain the members of all plugins that this
418
- * config array contains. Those map objects don't have mutation methods.
419
- * Those keys are the member ID such as `pluginId/memberName`.
420
- * - `isRoot()`
421
- * If `true` then this configuration has `root:true` property.
422
- * - `extractConfig(filePath)`
423
- * Extract the final configuration for a given file. This means merging
424
- * every config array element which that `criteria` property matched. The
425
- * `filePath` argument must be an absolute path.
426
- *
427
- * `ConfigArrayFactory` provides the loading logic of config files.
428
- *
429
- * @author Toru Nagashima <https://github.com/mysticatea>
430
- */
431
-
432
- //------------------------------------------------------------------------------
433
- // Helpers
434
- //------------------------------------------------------------------------------
435
-
436
- // Define types for VSCode IntelliSense.
437
- /** @typedef {import("../../shared/types").Environment} Environment */
438
- /** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
439
- /** @typedef {import("../../shared/types").RuleConf} RuleConf */
440
- /** @typedef {import("../../shared/types").Rule} Rule */
441
- /** @typedef {import("../../shared/types").Plugin} Plugin */
442
- /** @typedef {import("../../shared/types").Processor} Processor */
443
- /** @typedef {import("./config-dependency").DependentParser} DependentParser */
444
- /** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
445
- /** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
446
-
447
- /**
448
- * @typedef {Object} ConfigArrayElement
449
- * @property {string} name The name of this config element.
450
- * @property {string} filePath The path to the source file of this config element.
451
- * @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
452
- * @property {Record<string, boolean>|undefined} env The environment settings.
453
- * @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
454
- * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
455
- * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
456
- * @property {DependentParser|undefined} parser The parser loader.
457
- * @property {Object|undefined} parserOptions The parser options.
458
- * @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
459
- * @property {string|undefined} processor The processor name to refer plugin's processor.
460
- * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
461
- * @property {boolean|undefined} root The flag to express root.
462
- * @property {Record<string, RuleConf>|undefined} rules The rule settings
463
- * @property {Object|undefined} settings The shared settings.
464
- * @property {"config" | "ignore" | "implicit-processor"} type The element type.
465
- */
466
-
467
- /**
468
- * @typedef {Object} ConfigArrayInternalSlots
469
- * @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
470
- * @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
471
- * @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
472
- * @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
473
- */
474
-
475
- /** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
476
- const internalSlotsMap$2 = new class extends WeakMap {
477
- get(key) {
478
- let value = super.get(key);
479
-
480
- if (!value) {
481
- value = {
482
- cache: new Map(),
483
- envMap: null,
484
- processorMap: null,
485
- ruleMap: null
486
- };
487
- super.set(key, value);
488
- }
489
-
490
- return value;
491
- }
492
- }();
493
-
494
- /**
495
- * Get the indices which are matched to a given file.
496
- * @param {ConfigArrayElement[]} elements The elements.
497
- * @param {string} filePath The path to a target file.
498
- * @returns {number[]} The indices.
499
- */
500
- function getMatchedIndices(elements, filePath) {
501
- const indices = [];
502
-
503
- for (let i = elements.length - 1; i >= 0; --i) {
504
- const element = elements[i];
505
-
506
- if (!element.criteria || (filePath && element.criteria.test(filePath))) {
507
- indices.push(i);
508
- }
509
- }
510
-
511
- return indices;
512
- }
513
-
514
- /**
515
- * Check if a value is a non-null object.
516
- * @param {any} x The value to check.
517
- * @returns {boolean} `true` if the value is a non-null object.
518
- */
519
- function isNonNullObject(x) {
520
- return typeof x === "object" && x !== null;
521
- }
522
-
523
- /**
524
- * Merge two objects.
525
- *
526
- * Assign every property values of `y` to `x` if `x` doesn't have the property.
527
- * If `x`'s property value is an object, it does recursive.
528
- * @param {Object} target The destination to merge
529
- * @param {Object|undefined} source The source to merge.
530
- * @returns {void}
531
- */
532
- function mergeWithoutOverwrite(target, source) {
533
- if (!isNonNullObject(source)) {
534
- return;
535
- }
536
-
537
- for (const key of Object.keys(source)) {
538
- if (key === "__proto__") {
539
- continue;
540
- }
541
-
542
- if (isNonNullObject(target[key])) {
543
- mergeWithoutOverwrite(target[key], source[key]);
544
- } else if (target[key] === void 0) {
545
- if (isNonNullObject(source[key])) {
546
- target[key] = Array.isArray(source[key]) ? [] : {};
547
- mergeWithoutOverwrite(target[key], source[key]);
548
- } else if (source[key] !== void 0) {
549
- target[key] = source[key];
550
- }
551
- }
552
- }
553
- }
554
-
555
- /**
556
- * The error for plugin conflicts.
557
- */
558
- class PluginConflictError extends Error {
559
-
560
- /**
561
- * Initialize this error object.
562
- * @param {string} pluginId The plugin ID.
563
- * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
564
- */
565
- constructor(pluginId, plugins) {
566
- super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
567
- this.messageTemplate = "plugin-conflict";
568
- this.messageData = { pluginId, plugins };
569
- }
570
- }
571
-
572
- /**
573
- * Merge plugins.
574
- * `target`'s definition is prior to `source`'s.
575
- * @param {Record<string, DependentPlugin>} target The destination to merge
576
- * @param {Record<string, DependentPlugin>|undefined} source The source to merge.
577
- * @returns {void}
578
- */
579
- function mergePlugins(target, source) {
580
- if (!isNonNullObject(source)) {
581
- return;
582
- }
583
-
584
- for (const key of Object.keys(source)) {
585
- if (key === "__proto__") {
586
- continue;
587
- }
588
- const targetValue = target[key];
589
- const sourceValue = source[key];
590
-
591
- // Adopt the plugin which was found at first.
592
- if (targetValue === void 0) {
593
- if (sourceValue.error) {
594
- throw sourceValue.error;
595
- }
596
- target[key] = sourceValue;
597
- } else if (sourceValue.filePath !== targetValue.filePath) {
598
- throw new PluginConflictError(key, [
599
- {
600
- filePath: targetValue.filePath,
601
- importerName: targetValue.importerName
602
- },
603
- {
604
- filePath: sourceValue.filePath,
605
- importerName: sourceValue.importerName
606
- }
607
- ]);
608
- }
609
- }
610
- }
611
-
612
- /**
613
- * Merge rule configs.
614
- * `target`'s definition is prior to `source`'s.
615
- * @param {Record<string, Array>} target The destination to merge
616
- * @param {Record<string, RuleConf>|undefined} source The source to merge.
617
- * @returns {void}
618
- */
619
- function mergeRuleConfigs(target, source) {
620
- if (!isNonNullObject(source)) {
621
- return;
622
- }
623
-
624
- for (const key of Object.keys(source)) {
625
- if (key === "__proto__") {
626
- continue;
627
- }
628
- const targetDef = target[key];
629
- const sourceDef = source[key];
630
-
631
- // Adopt the rule config which was found at first.
632
- if (targetDef === void 0) {
633
- if (Array.isArray(sourceDef)) {
634
- target[key] = [...sourceDef];
635
- } else {
636
- target[key] = [sourceDef];
637
- }
638
-
639
- /*
640
- * If the first found rule config is severity only and the current rule
641
- * config has options, merge the severity and the options.
642
- */
643
- } else if (
644
- targetDef.length === 1 &&
645
- Array.isArray(sourceDef) &&
646
- sourceDef.length >= 2
647
- ) {
648
- targetDef.push(...sourceDef.slice(1));
649
- }
650
- }
651
- }
652
-
653
- /**
654
- * Create the extracted config.
655
- * @param {ConfigArray} instance The config elements.
656
- * @param {number[]} indices The indices to use.
657
- * @returns {ExtractedConfig} The extracted config.
658
- */
659
- function createConfig(instance, indices) {
660
- const config = new ExtractedConfig();
661
- const ignorePatterns = [];
662
-
663
- // Merge elements.
664
- for (const index of indices) {
665
- const element = instance[index];
666
-
667
- // Adopt the parser which was found at first.
668
- if (!config.parser && element.parser) {
669
- if (element.parser.error) {
670
- throw element.parser.error;
671
- }
672
- config.parser = element.parser;
673
- }
674
-
675
- // Adopt the processor which was found at first.
676
- if (!config.processor && element.processor) {
677
- config.processor = element.processor;
678
- }
679
-
680
- // Adopt the noInlineConfig which was found at first.
681
- if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
682
- config.noInlineConfig = element.noInlineConfig;
683
- config.configNameOfNoInlineConfig = element.name;
684
- }
685
-
686
- // Adopt the reportUnusedDisableDirectives which was found at first.
687
- if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
688
- config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
689
- }
690
-
691
- // Collect ignorePatterns
692
- if (element.ignorePattern) {
693
- ignorePatterns.push(element.ignorePattern);
694
- }
695
-
696
- // Merge others.
697
- mergeWithoutOverwrite(config.env, element.env);
698
- mergeWithoutOverwrite(config.globals, element.globals);
699
- mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
700
- mergeWithoutOverwrite(config.settings, element.settings);
701
- mergePlugins(config.plugins, element.plugins);
702
- mergeRuleConfigs(config.rules, element.rules);
703
- }
704
-
705
- // Create the predicate function for ignore patterns.
706
- if (ignorePatterns.length > 0) {
707
- config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
708
- }
709
-
710
- return config;
711
- }
712
-
713
- /**
714
- * Collect definitions.
715
- * @template T, U
716
- * @param {string} pluginId The plugin ID for prefix.
717
- * @param {Record<string,T>} defs The definitions to collect.
718
- * @param {Map<string, U>} map The map to output.
719
- * @param {function(T): U} [normalize] The normalize function for each value.
720
- * @returns {void}
721
- */
722
- function collect(pluginId, defs, map, normalize) {
723
- if (defs) {
724
- const prefix = pluginId && `${pluginId}/`;
725
-
726
- for (const [key, value] of Object.entries(defs)) {
727
- map.set(
728
- `${prefix}${key}`,
729
- normalize ? normalize(value) : value
730
- );
731
- }
732
- }
733
- }
734
-
735
- /**
736
- * Normalize a rule definition.
737
- * @param {Function|Rule} rule The rule definition to normalize.
738
- * @returns {Rule} The normalized rule definition.
739
- */
740
- function normalizePluginRule(rule) {
741
- return typeof rule === "function" ? { create: rule } : rule;
742
- }
743
-
744
- /**
745
- * Delete the mutation methods from a given map.
746
- * @param {Map<any, any>} map The map object to delete.
747
- * @returns {void}
748
- */
749
- function deleteMutationMethods(map) {
750
- Object.defineProperties(map, {
751
- clear: { configurable: true, value: void 0 },
752
- delete: { configurable: true, value: void 0 },
753
- set: { configurable: true, value: void 0 }
754
- });
755
- }
756
-
757
- /**
758
- * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
759
- * @param {ConfigArrayElement[]} elements The config elements.
760
- * @param {ConfigArrayInternalSlots} slots The internal slots.
761
- * @returns {void}
762
- */
763
- function initPluginMemberMaps(elements, slots) {
764
- const processed = new Set();
765
-
766
- slots.envMap = new Map();
767
- slots.processorMap = new Map();
768
- slots.ruleMap = new Map();
769
-
770
- for (const element of elements) {
771
- if (!element.plugins) {
772
- continue;
773
- }
774
-
775
- for (const [pluginId, value] of Object.entries(element.plugins)) {
776
- const plugin = value.definition;
777
-
778
- if (!plugin || processed.has(pluginId)) {
779
- continue;
780
- }
781
- processed.add(pluginId);
782
-
783
- collect(pluginId, plugin.environments, slots.envMap);
784
- collect(pluginId, plugin.processors, slots.processorMap);
785
- collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
786
- }
787
- }
788
-
789
- deleteMutationMethods(slots.envMap);
790
- deleteMutationMethods(slots.processorMap);
791
- deleteMutationMethods(slots.ruleMap);
792
- }
793
-
794
- /**
795
- * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
796
- * @param {ConfigArray} instance The config elements.
797
- * @returns {ConfigArrayInternalSlots} The extracted config.
798
- */
799
- function ensurePluginMemberMaps(instance) {
800
- const slots = internalSlotsMap$2.get(instance);
801
-
802
- if (!slots.ruleMap) {
803
- initPluginMemberMaps(instance, slots);
804
- }
805
-
806
- return slots;
807
- }
808
-
809
- //------------------------------------------------------------------------------
810
- // Public Interface
811
- //------------------------------------------------------------------------------
812
-
813
- /**
814
- * The Config Array.
815
- *
816
- * `ConfigArray` instance contains all settings, parsers, and plugins.
817
- * You need to call `ConfigArray#extractConfig(filePath)` method in order to
818
- * extract, merge and get only the config data which is related to an arbitrary
819
- * file.
820
- * @extends {Array<ConfigArrayElement>}
821
- */
822
- class ConfigArray extends Array {
823
-
824
- /**
825
- * Get the plugin environments.
826
- * The returned map cannot be mutated.
827
- * @type {ReadonlyMap<string, Environment>} The plugin environments.
828
- */
829
- get pluginEnvironments() {
830
- return ensurePluginMemberMaps(this).envMap;
831
- }
832
-
833
- /**
834
- * Get the plugin processors.
835
- * The returned map cannot be mutated.
836
- * @type {ReadonlyMap<string, Processor>} The plugin processors.
837
- */
838
- get pluginProcessors() {
839
- return ensurePluginMemberMaps(this).processorMap;
840
- }
841
-
842
- /**
843
- * Get the plugin rules.
844
- * The returned map cannot be mutated.
845
- * @returns {ReadonlyMap<string, Rule>} The plugin rules.
846
- */
847
- get pluginRules() {
848
- return ensurePluginMemberMaps(this).ruleMap;
849
- }
850
-
851
- /**
852
- * Check if this config has `root` flag.
853
- * @returns {boolean} `true` if this config array is root.
854
- */
855
- isRoot() {
856
- for (let i = this.length - 1; i >= 0; --i) {
857
- const root = this[i].root;
858
-
859
- if (typeof root === "boolean") {
860
- return root;
861
- }
862
- }
863
- return false;
864
- }
865
-
866
- /**
867
- * Extract the config data which is related to a given file.
868
- * @param {string} filePath The absolute path to the target file.
869
- * @returns {ExtractedConfig} The extracted config data.
870
- */
871
- extractConfig(filePath) {
872
- const { cache } = internalSlotsMap$2.get(this);
873
- const indices = getMatchedIndices(this, filePath);
874
- const cacheKey = indices.join(",");
875
-
876
- if (!cache.has(cacheKey)) {
877
- cache.set(cacheKey, createConfig(this, indices));
878
- }
879
-
880
- return cache.get(cacheKey);
881
- }
882
-
883
- /**
884
- * Check if a given path is an additional lint target.
885
- * @param {string} filePath The absolute path to the target file.
886
- * @returns {boolean} `true` if the file is an additional lint target.
887
- */
888
- isAdditionalTargetPath(filePath) {
889
- for (const { criteria, type } of this) {
890
- if (
891
- type === "config" &&
892
- criteria &&
893
- !criteria.endsWithWildcard &&
894
- criteria.test(filePath)
895
- ) {
896
- return true;
897
- }
898
- }
899
- return false;
900
- }
901
- }
902
-
903
- /**
904
- * Get the used extracted configs.
905
- * CLIEngine will use this method to collect used deprecated rules.
906
- * @param {ConfigArray} instance The config array object to get.
907
- * @returns {ExtractedConfig[]} The used extracted configs.
908
- * @private
909
- */
910
- function getUsedExtractedConfigs(instance) {
911
- const { cache } = internalSlotsMap$2.get(instance);
912
-
913
- return Array.from(cache.values());
914
- }
915
-
916
- /**
917
- * @fileoverview `ConfigDependency` class.
918
- *
919
- * `ConfigDependency` class expresses a loaded parser or plugin.
920
- *
921
- * If the parser or plugin was loaded successfully, it has `definition` property
922
- * and `filePath` property. Otherwise, it has `error` property.
923
- *
924
- * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
925
- * omits `definition` property.
926
- *
927
- * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
928
- * or plugins.
929
- *
930
- * @author Toru Nagashima <https://github.com/mysticatea>
931
- */
932
-
933
- /**
934
- * The class is to store parsers or plugins.
935
- * This class hides the loaded object from `JSON.stringify()` and `console.log`.
936
- * @template T
937
- */
938
- class ConfigDependency {
939
-
940
- /**
941
- * Initialize this instance.
942
- * @param {Object} data The dependency data.
943
- * @param {T} [data.definition] The dependency if the loading succeeded.
944
- * @param {Error} [data.error] The error object if the loading failed.
945
- * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
946
- * @param {string} data.id The ID of this dependency.
947
- * @param {string} data.importerName The name of the config file which loads this dependency.
948
- * @param {string} data.importerPath The path to the config file which loads this dependency.
949
- */
950
- constructor({
951
- definition = null,
952
- error = null,
953
- filePath = null,
954
- id,
955
- importerName,
956
- importerPath
957
- }) {
958
-
959
- /**
960
- * The loaded dependency if the loading succeeded.
961
- * @type {T|null}
962
- */
963
- this.definition = definition;
964
-
965
- /**
966
- * The error object if the loading failed.
967
- * @type {Error|null}
968
- */
969
- this.error = error;
970
-
971
- /**
972
- * The loaded dependency if the loading succeeded.
973
- * @type {string|null}
974
- */
975
- this.filePath = filePath;
976
-
977
- /**
978
- * The ID of this dependency.
979
- * @type {string}
980
- */
981
- this.id = id;
982
-
983
- /**
984
- * The name of the config file which loads this dependency.
985
- * @type {string}
986
- */
987
- this.importerName = importerName;
988
-
989
- /**
990
- * The path to the config file which loads this dependency.
991
- * @type {string}
992
- */
993
- this.importerPath = importerPath;
994
- }
995
-
996
- // eslint-disable-next-line jsdoc/require-description
997
- /**
998
- * @returns {Object} a JSON compatible object.
999
- */
1000
- toJSON() {
1001
- const obj = this[util__default["default"].inspect.custom]();
1002
-
1003
- // Display `error.message` (`Error#message` is unenumerable).
1004
- if (obj.error instanceof Error) {
1005
- obj.error = { ...obj.error, message: obj.error.message };
1006
- }
1007
-
1008
- return obj;
1009
- }
1010
-
1011
- // eslint-disable-next-line jsdoc/require-description
1012
- /**
1013
- * @returns {Object} an object to display by `console.log()`.
1014
- */
1015
- [util__default["default"].inspect.custom]() {
1016
- const {
1017
- definition: _ignore, // eslint-disable-line no-unused-vars
1018
- ...obj
1019
- } = this;
1020
-
1021
- return obj;
1022
- }
1023
- }
1024
-
1025
- /**
1026
- * @fileoverview `OverrideTester` class.
1027
- *
1028
- * `OverrideTester` class handles `files` property and `excludedFiles` property
1029
- * of `overrides` config.
1030
- *
1031
- * It provides one method.
1032
- *
1033
- * - `test(filePath)`
1034
- * Test if a file path matches the pair of `files` property and
1035
- * `excludedFiles` property. The `filePath` argument must be an absolute
1036
- * path.
1037
- *
1038
- * `ConfigArrayFactory` creates `OverrideTester` objects when it processes
1039
- * `overrides` properties.
1040
- *
1041
- * @author Toru Nagashima <https://github.com/mysticatea>
1042
- */
1043
-
1044
- const { Minimatch } = minimatch__default["default"];
1045
-
1046
- const minimatchOpts = { dot: true, matchBase: true };
1047
-
1048
- /**
1049
- * @typedef {Object} Pattern
1050
- * @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
1051
- * @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
1052
- */
1053
-
1054
- /**
1055
- * Normalize a given pattern to an array.
1056
- * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
1057
- * @returns {string[]|null} Normalized patterns.
1058
- * @private
1059
- */
1060
- function normalizePatterns(patterns) {
1061
- if (Array.isArray(patterns)) {
1062
- return patterns.filter(Boolean);
1063
- }
1064
- if (typeof patterns === "string" && patterns) {
1065
- return [patterns];
1066
- }
1067
- return [];
1068
- }
1069
-
1070
- /**
1071
- * Create the matchers of given patterns.
1072
- * @param {string[]} patterns The patterns.
1073
- * @returns {InstanceType<Minimatch>[] | null} The matchers.
1074
- */
1075
- function toMatcher(patterns) {
1076
- if (patterns.length === 0) {
1077
- return null;
1078
- }
1079
- return patterns.map(pattern => {
1080
- if (/^\.[/\\]/u.test(pattern)) {
1081
- return new Minimatch(
1082
- pattern.slice(2),
1083
-
1084
- // `./*.js` should not match with `subdir/foo.js`
1085
- { ...minimatchOpts, matchBase: false }
1086
- );
1087
- }
1088
- return new Minimatch(pattern, minimatchOpts);
1089
- });
1090
- }
1091
-
1092
- /**
1093
- * Convert a given matcher to string.
1094
- * @param {Pattern} matchers The matchers.
1095
- * @returns {string} The string expression of the matcher.
1096
- */
1097
- function patternToJson({ includes, excludes }) {
1098
- return {
1099
- includes: includes && includes.map(m => m.pattern),
1100
- excludes: excludes && excludes.map(m => m.pattern)
1101
- };
1102
- }
1103
-
1104
- /**
1105
- * The class to test given paths are matched by the patterns.
1106
- */
1107
- class OverrideTester {
1108
-
1109
- /**
1110
- * Create a tester with given criteria.
1111
- * If there are no criteria, returns `null`.
1112
- * @param {string|string[]} files The glob patterns for included files.
1113
- * @param {string|string[]} excludedFiles The glob patterns for excluded files.
1114
- * @param {string} basePath The path to the base directory to test paths.
1115
- * @returns {OverrideTester|null} The created instance or `null`.
1116
- */
1117
- static create(files, excludedFiles, basePath) {
1118
- const includePatterns = normalizePatterns(files);
1119
- const excludePatterns = normalizePatterns(excludedFiles);
1120
- let endsWithWildcard = false;
1121
-
1122
- if (includePatterns.length === 0) {
1123
- return null;
1124
- }
1125
-
1126
- // Rejects absolute paths or relative paths to parents.
1127
- for (const pattern of includePatterns) {
1128
- if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) {
1129
- throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
1130
- }
1131
- if (pattern.endsWith("*")) {
1132
- endsWithWildcard = true;
1133
- }
1134
- }
1135
- for (const pattern of excludePatterns) {
1136
- if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) {
1137
- throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
1138
- }
1139
- }
1140
-
1141
- const includes = toMatcher(includePatterns);
1142
- const excludes = toMatcher(excludePatterns);
1143
-
1144
- return new OverrideTester(
1145
- [{ includes, excludes }],
1146
- basePath,
1147
- endsWithWildcard
1148
- );
1149
- }
1150
-
1151
- /**
1152
- * Combine two testers by logical and.
1153
- * If either of the testers was `null`, returns the other tester.
1154
- * The `basePath` property of the two must be the same value.
1155
- * @param {OverrideTester|null} a A tester.
1156
- * @param {OverrideTester|null} b Another tester.
1157
- * @returns {OverrideTester|null} Combined tester.
1158
- */
1159
- static and(a, b) {
1160
- if (!b) {
1161
- return a && new OverrideTester(
1162
- a.patterns,
1163
- a.basePath,
1164
- a.endsWithWildcard
1165
- );
1166
- }
1167
- if (!a) {
1168
- return new OverrideTester(
1169
- b.patterns,
1170
- b.basePath,
1171
- b.endsWithWildcard
1172
- );
1173
- }
1174
-
1175
- assert__default["default"].strictEqual(a.basePath, b.basePath);
1176
- return new OverrideTester(
1177
- a.patterns.concat(b.patterns),
1178
- a.basePath,
1179
- a.endsWithWildcard || b.endsWithWildcard
1180
- );
1181
- }
1182
-
1183
- /**
1184
- * Initialize this instance.
1185
- * @param {Pattern[]} patterns The matchers.
1186
- * @param {string} basePath The base path.
1187
- * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
1188
- */
1189
- constructor(patterns, basePath, endsWithWildcard = false) {
1190
-
1191
- /** @type {Pattern[]} */
1192
- this.patterns = patterns;
1193
-
1194
- /** @type {string} */
1195
- this.basePath = basePath;
1196
-
1197
- /** @type {boolean} */
1198
- this.endsWithWildcard = endsWithWildcard;
1199
- }
1200
-
1201
- /**
1202
- * Test if a given path is matched or not.
1203
- * @param {string} filePath The absolute path to the target file.
1204
- * @returns {boolean} `true` if the path was matched.
1205
- */
1206
- test(filePath) {
1207
- if (typeof filePath !== "string" || !path__default["default"].isAbsolute(filePath)) {
1208
- throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
1209
- }
1210
- const relativePath = path__default["default"].relative(this.basePath, filePath);
1211
-
1212
- return this.patterns.every(({ includes, excludes }) => (
1213
- (!includes || includes.some(m => m.match(relativePath))) &&
1214
- (!excludes || !excludes.some(m => m.match(relativePath)))
1215
- ));
1216
- }
1217
-
1218
- // eslint-disable-next-line jsdoc/require-description
1219
- /**
1220
- * @returns {Object} a JSON compatible object.
1221
- */
1222
- toJSON() {
1223
- if (this.patterns.length === 1) {
1224
- return {
1225
- ...patternToJson(this.patterns[0]),
1226
- basePath: this.basePath
1227
- };
1228
- }
1229
- return {
1230
- AND: this.patterns.map(patternToJson),
1231
- basePath: this.basePath
1232
- };
1233
- }
1234
-
1235
- // eslint-disable-next-line jsdoc/require-description
1236
- /**
1237
- * @returns {Object} an object to display by `console.log()`.
1238
- */
1239
- [util__default["default"].inspect.custom]() {
1240
- return this.toJSON();
1241
- }
1242
- }
1243
-
1244
- /**
1245
- * @fileoverview `ConfigArray` class.
1246
- * @author Toru Nagashima <https://github.com/mysticatea>
1247
- */
1248
-
1249
- /**
1250
- * @fileoverview Config file operations. This file must be usable in the browser,
1251
- * so no Node-specific code can be here.
1252
- * @author Nicholas C. Zakas
1253
- */
1254
-
1255
- //------------------------------------------------------------------------------
1256
- // Private
1257
- //------------------------------------------------------------------------------
1258
-
1259
- const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
1260
- RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
1261
- map[value] = index;
1262
- return map;
1263
- }, {}),
1264
- VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
1265
-
1266
- //------------------------------------------------------------------------------
1267
- // Public Interface
1268
- //------------------------------------------------------------------------------
1269
-
1270
- /**
1271
- * Normalizes the severity value of a rule's configuration to a number
1272
- * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
1273
- * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
1274
- * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
1275
- * whose first element is one of the above values. Strings are matched case-insensitively.
1276
- * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
1277
- */
1278
- function getRuleSeverity(ruleConfig) {
1279
- const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
1280
-
1281
- if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
1282
- return severityValue;
1283
- }
1284
-
1285
- if (typeof severityValue === "string") {
1286
- return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
1287
- }
1288
-
1289
- return 0;
1290
- }
1291
-
1292
- /**
1293
- * Converts old-style severity settings (0, 1, 2) into new-style
1294
- * severity settings (off, warn, error) for all rules. Assumption is that severity
1295
- * values have already been validated as correct.
1296
- * @param {Object} config The config object to normalize.
1297
- * @returns {void}
1298
- */
1299
- function normalizeToStrings(config) {
1300
-
1301
- if (config.rules) {
1302
- Object.keys(config.rules).forEach(ruleId => {
1303
- const ruleConfig = config.rules[ruleId];
1304
-
1305
- if (typeof ruleConfig === "number") {
1306
- config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
1307
- } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
1308
- ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
1309
- }
1310
- });
1311
- }
1312
- }
1313
-
1314
- /**
1315
- * Determines if the severity for the given rule configuration represents an error.
1316
- * @param {int|string|Array} ruleConfig The configuration for an individual rule.
1317
- * @returns {boolean} True if the rule represents an error, false if not.
1318
- */
1319
- function isErrorSeverity(ruleConfig) {
1320
- return getRuleSeverity(ruleConfig) === 2;
1321
- }
1322
-
1323
- /**
1324
- * Checks whether a given config has valid severity or not.
1325
- * @param {number|string|Array} ruleConfig The configuration for an individual rule.
1326
- * @returns {boolean} `true` if the configuration has valid severity.
1327
- */
1328
- function isValidSeverity(ruleConfig) {
1329
- let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
1330
-
1331
- if (typeof severity === "string") {
1332
- severity = severity.toLowerCase();
1333
- }
1334
- return VALID_SEVERITIES.indexOf(severity) !== -1;
1335
- }
1336
-
1337
- /**
1338
- * Checks whether every rule of a given config has valid severity or not.
1339
- * @param {Object} config The configuration for rules.
1340
- * @returns {boolean} `true` if the configuration has valid severity.
1341
- */
1342
- function isEverySeverityValid(config) {
1343
- return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
1344
- }
1345
-
1346
- /**
1347
- * Normalizes a value for a global in a config
1348
- * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
1349
- * a global directive comment
1350
- * @returns {("readable"|"writeable"|"off")} The value normalized as a string
1351
- * @throws Error if global value is invalid
1352
- */
1353
- function normalizeConfigGlobal(configuredValue) {
1354
- switch (configuredValue) {
1355
- case "off":
1356
- return "off";
1357
-
1358
- case true:
1359
- case "true":
1360
- case "writeable":
1361
- case "writable":
1362
- return "writable";
1363
-
1364
- case null:
1365
- case false:
1366
- case "false":
1367
- case "readable":
1368
- case "readonly":
1369
- return "readonly";
1370
-
1371
- default:
1372
- throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
1373
- }
1374
- }
1375
-
1376
- var ConfigOps = {
1377
- __proto__: null,
1378
- getRuleSeverity: getRuleSeverity,
1379
- normalizeToStrings: normalizeToStrings,
1380
- isErrorSeverity: isErrorSeverity,
1381
- isValidSeverity: isValidSeverity,
1382
- isEverySeverityValid: isEverySeverityValid,
1383
- normalizeConfigGlobal: normalizeConfigGlobal
1384
- };
1385
-
1386
- /**
1387
- * @fileoverview Provide the function that emits deprecation warnings.
1388
- * @author Toru Nagashima <http://github.com/mysticatea>
1389
- */
1390
-
1391
- //------------------------------------------------------------------------------
1392
- // Private
1393
- //------------------------------------------------------------------------------
1394
-
1395
- // Defitions for deprecation warnings.
1396
- const deprecationWarningMessages = {
1397
- ESLINT_LEGACY_ECMAFEATURES:
1398
- "The 'ecmaFeatures' config file property is deprecated and has no effect.",
1399
- ESLINT_PERSONAL_CONFIG_LOAD:
1400
- "'~/.eslintrc.*' config files have been deprecated. " +
1401
- "Please use a config file per project or the '--config' option.",
1402
- ESLINT_PERSONAL_CONFIG_SUPPRESS:
1403
- "'~/.eslintrc.*' config files have been deprecated. " +
1404
- "Please remove it or add 'root:true' to the config files in your " +
1405
- "projects in order to avoid loading '~/.eslintrc.*' accidentally."
1406
- };
1407
-
1408
- const sourceFileErrorCache = new Set();
1409
-
1410
- /**
1411
- * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
1412
- * for each unique file path, but repeated invocations with the same file path have no effect.
1413
- * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
1414
- * @param {string} source The name of the configuration source to report the warning for.
1415
- * @param {string} errorCode The warning message to show.
1416
- * @returns {void}
1417
- */
1418
- function emitDeprecationWarning(source, errorCode) {
1419
- const cacheKey = JSON.stringify({ source, errorCode });
1420
-
1421
- if (sourceFileErrorCache.has(cacheKey)) {
1422
- return;
1423
- }
1424
- sourceFileErrorCache.add(cacheKey);
1425
-
1426
- const rel = path__default["default"].relative(process.cwd(), source);
1427
- const message = deprecationWarningMessages[errorCode];
1428
-
1429
- process.emitWarning(
1430
- `${message} (found in "${rel}")`,
1431
- "DeprecationWarning",
1432
- errorCode
1433
- );
1434
- }
1435
-
1436
- /**
1437
- * @fileoverview The instance of Ajv validator.
1438
- * @author Evgeny Poberezkin
1439
- */
1440
-
1441
- //-----------------------------------------------------------------------------
1442
- // Helpers
1443
- //-----------------------------------------------------------------------------
1444
-
1445
- /*
1446
- * Copied from ajv/lib/refs/json-schema-draft-04.json
1447
- * The MIT License (MIT)
1448
- * Copyright (c) 2015-2017 Evgeny Poberezkin
1449
- */
1450
- const metaSchema = {
1451
- id: "http://json-schema.org/draft-04/schema#",
1452
- $schema: "http://json-schema.org/draft-04/schema#",
1453
- description: "Core schema meta-schema",
1454
- definitions: {
1455
- schemaArray: {
1456
- type: "array",
1457
- minItems: 1,
1458
- items: { $ref: "#" }
1459
- },
1460
- positiveInteger: {
1461
- type: "integer",
1462
- minimum: 0
1463
- },
1464
- positiveIntegerDefault0: {
1465
- allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
1466
- },
1467
- simpleTypes: {
1468
- enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
1469
- },
1470
- stringArray: {
1471
- type: "array",
1472
- items: { type: "string" },
1473
- minItems: 1,
1474
- uniqueItems: true
1475
- }
1476
- },
1477
- type: "object",
1478
- properties: {
1479
- id: {
1480
- type: "string"
1481
- },
1482
- $schema: {
1483
- type: "string"
1484
- },
1485
- title: {
1486
- type: "string"
1487
- },
1488
- description: {
1489
- type: "string"
1490
- },
1491
- default: { },
1492
- multipleOf: {
1493
- type: "number",
1494
- minimum: 0,
1495
- exclusiveMinimum: true
1496
- },
1497
- maximum: {
1498
- type: "number"
1499
- },
1500
- exclusiveMaximum: {
1501
- type: "boolean",
1502
- default: false
1503
- },
1504
- minimum: {
1505
- type: "number"
1506
- },
1507
- exclusiveMinimum: {
1508
- type: "boolean",
1509
- default: false
1510
- },
1511
- maxLength: { $ref: "#/definitions/positiveInteger" },
1512
- minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
1513
- pattern: {
1514
- type: "string",
1515
- format: "regex"
1516
- },
1517
- additionalItems: {
1518
- anyOf: [
1519
- { type: "boolean" },
1520
- { $ref: "#" }
1521
- ],
1522
- default: { }
1523
- },
1524
- items: {
1525
- anyOf: [
1526
- { $ref: "#" },
1527
- { $ref: "#/definitions/schemaArray" }
1528
- ],
1529
- default: { }
1530
- },
1531
- maxItems: { $ref: "#/definitions/positiveInteger" },
1532
- minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
1533
- uniqueItems: {
1534
- type: "boolean",
1535
- default: false
1536
- },
1537
- maxProperties: { $ref: "#/definitions/positiveInteger" },
1538
- minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
1539
- required: { $ref: "#/definitions/stringArray" },
1540
- additionalProperties: {
1541
- anyOf: [
1542
- { type: "boolean" },
1543
- { $ref: "#" }
1544
- ],
1545
- default: { }
1546
- },
1547
- definitions: {
1548
- type: "object",
1549
- additionalProperties: { $ref: "#" },
1550
- default: { }
1551
- },
1552
- properties: {
1553
- type: "object",
1554
- additionalProperties: { $ref: "#" },
1555
- default: { }
1556
- },
1557
- patternProperties: {
1558
- type: "object",
1559
- additionalProperties: { $ref: "#" },
1560
- default: { }
1561
- },
1562
- dependencies: {
1563
- type: "object",
1564
- additionalProperties: {
1565
- anyOf: [
1566
- { $ref: "#" },
1567
- { $ref: "#/definitions/stringArray" }
1568
- ]
1569
- }
1570
- },
1571
- enum: {
1572
- type: "array",
1573
- minItems: 1,
1574
- uniqueItems: true
1575
- },
1576
- type: {
1577
- anyOf: [
1578
- { $ref: "#/definitions/simpleTypes" },
1579
- {
1580
- type: "array",
1581
- items: { $ref: "#/definitions/simpleTypes" },
1582
- minItems: 1,
1583
- uniqueItems: true
1584
- }
1585
- ]
1586
- },
1587
- format: { type: "string" },
1588
- allOf: { $ref: "#/definitions/schemaArray" },
1589
- anyOf: { $ref: "#/definitions/schemaArray" },
1590
- oneOf: { $ref: "#/definitions/schemaArray" },
1591
- not: { $ref: "#" }
1592
- },
1593
- dependencies: {
1594
- exclusiveMaximum: ["maximum"],
1595
- exclusiveMinimum: ["minimum"]
1596
- },
1597
- default: { }
1598
- };
1599
-
1600
- //------------------------------------------------------------------------------
1601
- // Public Interface
1602
- //------------------------------------------------------------------------------
1603
-
1604
- var ajvOrig = (additionalOptions = {}) => {
1605
- const ajv = new Ajv__default["default"]({
1606
- meta: false,
1607
- useDefaults: true,
1608
- validateSchema: false,
1609
- missingRefs: "ignore",
1610
- verbose: true,
1611
- schemaId: "auto",
1612
- ...additionalOptions
1613
- });
1614
-
1615
- ajv.addMetaSchema(metaSchema);
1616
- // eslint-disable-next-line no-underscore-dangle
1617
- ajv._opts.defaultMeta = metaSchema.id;
1618
-
1619
- return ajv;
1620
- };
1621
-
1622
- /**
1623
- * @fileoverview Defines a schema for configs.
1624
- * @author Sylvan Mably
1625
- */
1626
-
1627
- const baseConfigProperties = {
1628
- $schema: { type: "string" },
1629
- env: { type: "object" },
1630
- extends: { $ref: "#/definitions/stringOrStrings" },
1631
- globals: { type: "object" },
1632
- overrides: {
1633
- type: "array",
1634
- items: { $ref: "#/definitions/overrideConfig" },
1635
- additionalItems: false
1636
- },
1637
- parser: { type: ["string", "null"] },
1638
- parserOptions: { type: "object" },
1639
- plugins: { type: "array" },
1640
- processor: { type: "string" },
1641
- rules: { type: "object" },
1642
- settings: { type: "object" },
1643
- noInlineConfig: { type: "boolean" },
1644
- reportUnusedDisableDirectives: { type: "boolean" },
1645
-
1646
- ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
1647
- };
1648
-
1649
- const configSchema = {
1650
- definitions: {
1651
- stringOrStrings: {
1652
- oneOf: [
1653
- { type: "string" },
1654
- {
1655
- type: "array",
1656
- items: { type: "string" },
1657
- additionalItems: false
1658
- }
1659
- ]
1660
- },
1661
- stringOrStringsRequired: {
1662
- oneOf: [
1663
- { type: "string" },
1664
- {
1665
- type: "array",
1666
- items: { type: "string" },
1667
- additionalItems: false,
1668
- minItems: 1
1669
- }
1670
- ]
1671
- },
1672
-
1673
- // Config at top-level.
1674
- objectConfig: {
1675
- type: "object",
1676
- properties: {
1677
- root: { type: "boolean" },
1678
- ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
1679
- ...baseConfigProperties
1680
- },
1681
- additionalProperties: false
1682
- },
1683
-
1684
- // Config in `overrides`.
1685
- overrideConfig: {
1686
- type: "object",
1687
- properties: {
1688
- excludedFiles: { $ref: "#/definitions/stringOrStrings" },
1689
- files: { $ref: "#/definitions/stringOrStringsRequired" },
1690
- ...baseConfigProperties
1691
- },
1692
- required: ["files"],
1693
- additionalProperties: false
1694
- }
1695
- },
1696
-
1697
- $ref: "#/definitions/objectConfig"
1698
- };
1699
-
1700
- /**
1701
- * @fileoverview Defines environment settings and globals.
1702
- * @author Elan Shanker
1703
- */
1704
-
1705
- //------------------------------------------------------------------------------
1706
- // Helpers
1707
- //------------------------------------------------------------------------------
1708
-
1709
- /**
1710
- * Get the object that has difference.
1711
- * @param {Record<string,boolean>} current The newer object.
1712
- * @param {Record<string,boolean>} prev The older object.
1713
- * @returns {Record<string,boolean>} The difference object.
1714
- */
1715
- function getDiff(current, prev) {
1716
- const retv = {};
1717
-
1718
- for (const [key, value] of Object.entries(current)) {
1719
- if (!Object.hasOwnProperty.call(prev, key)) {
1720
- retv[key] = value;
1721
- }
1722
- }
1723
-
1724
- return retv;
1725
- }
1726
-
1727
- const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ...
1728
- const newGlobals2017 = {
1729
- Atomics: false,
1730
- SharedArrayBuffer: false
1731
- };
1732
- const newGlobals2020 = {
1733
- BigInt: false,
1734
- BigInt64Array: false,
1735
- BigUint64Array: false,
1736
- globalThis: false
1737
- };
1738
-
1739
- const newGlobals2021 = {
1740
- AggregateError: false,
1741
- FinalizationRegistry: false,
1742
- WeakRef: false
1743
- };
1744
-
1745
- //------------------------------------------------------------------------------
1746
- // Public Interface
1747
- //------------------------------------------------------------------------------
1748
-
1749
- /** @type {Map<string, import("../lib/shared/types").Environment>} */
1750
- var environments = new Map(Object.entries({
1751
-
1752
- // Language
1753
- builtin: {
1754
- globals: globals__default["default"].es5
1755
- },
1756
- es6: {
1757
- globals: newGlobals2015,
1758
- parserOptions: {
1759
- ecmaVersion: 6
1760
- }
1761
- },
1762
- es2015: {
1763
- globals: newGlobals2015,
1764
- parserOptions: {
1765
- ecmaVersion: 6
1766
- }
1767
- },
1768
- es2016: {
1769
- globals: newGlobals2015,
1770
- parserOptions: {
1771
- ecmaVersion: 7
1772
- }
1773
- },
1774
- es2017: {
1775
- globals: { ...newGlobals2015, ...newGlobals2017 },
1776
- parserOptions: {
1777
- ecmaVersion: 8
1778
- }
1779
- },
1780
- es2018: {
1781
- globals: { ...newGlobals2015, ...newGlobals2017 },
1782
- parserOptions: {
1783
- ecmaVersion: 9
1784
- }
1785
- },
1786
- es2019: {
1787
- globals: { ...newGlobals2015, ...newGlobals2017 },
1788
- parserOptions: {
1789
- ecmaVersion: 10
1790
- }
1791
- },
1792
- es2020: {
1793
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
1794
- parserOptions: {
1795
- ecmaVersion: 11
1796
- }
1797
- },
1798
- es2021: {
1799
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1800
- parserOptions: {
1801
- ecmaVersion: 12
1802
- }
1803
- },
1804
- es2022: {
1805
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1806
- parserOptions: {
1807
- ecmaVersion: 13
1808
- }
1809
- },
1810
- es2023: {
1811
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1812
- parserOptions: {
1813
- ecmaVersion: 14
1814
- }
1815
- },
1816
- es2024: {
1817
- globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
1818
- parserOptions: {
1819
- ecmaVersion: 15
1820
- }
1821
- },
1822
-
1823
- // Platforms
1824
- browser: {
1825
- globals: globals__default["default"].browser
1826
- },
1827
- node: {
1828
- globals: globals__default["default"].node,
1829
- parserOptions: {
1830
- ecmaFeatures: {
1831
- globalReturn: true
1832
- }
1833
- }
1834
- },
1835
- "shared-node-browser": {
1836
- globals: globals__default["default"]["shared-node-browser"]
1837
- },
1838
- worker: {
1839
- globals: globals__default["default"].worker
1840
- },
1841
- serviceworker: {
1842
- globals: globals__default["default"].serviceworker
1843
- },
1844
-
1845
- // Frameworks
1846
- commonjs: {
1847
- globals: globals__default["default"].commonjs,
1848
- parserOptions: {
1849
- ecmaFeatures: {
1850
- globalReturn: true
1851
- }
1852
- }
1853
- },
1854
- amd: {
1855
- globals: globals__default["default"].amd
1856
- },
1857
- mocha: {
1858
- globals: globals__default["default"].mocha
1859
- },
1860
- jasmine: {
1861
- globals: globals__default["default"].jasmine
1862
- },
1863
- jest: {
1864
- globals: globals__default["default"].jest
1865
- },
1866
- phantomjs: {
1867
- globals: globals__default["default"].phantomjs
1868
- },
1869
- jquery: {
1870
- globals: globals__default["default"].jquery
1871
- },
1872
- qunit: {
1873
- globals: globals__default["default"].qunit
1874
- },
1875
- prototypejs: {
1876
- globals: globals__default["default"].prototypejs
1877
- },
1878
- shelljs: {
1879
- globals: globals__default["default"].shelljs
1880
- },
1881
- meteor: {
1882
- globals: globals__default["default"].meteor
1883
- },
1884
- mongo: {
1885
- globals: globals__default["default"].mongo
1886
- },
1887
- protractor: {
1888
- globals: globals__default["default"].protractor
1889
- },
1890
- applescript: {
1891
- globals: globals__default["default"].applescript
1892
- },
1893
- nashorn: {
1894
- globals: globals__default["default"].nashorn
1895
- },
1896
- atomtest: {
1897
- globals: globals__default["default"].atomtest
1898
- },
1899
- embertest: {
1900
- globals: globals__default["default"].embertest
1901
- },
1902
- webextensions: {
1903
- globals: globals__default["default"].webextensions
1904
- },
1905
- greasemonkey: {
1906
- globals: globals__default["default"].greasemonkey
1907
- }
1908
- }));
1909
-
1910
- /**
1911
- * @fileoverview Validates configs.
1912
- * @author Brandon Mills
1913
- */
1914
-
1915
- const ajv = ajvOrig();
1916
-
1917
- const ruleValidators = new WeakMap();
1918
- const noop = Function.prototype;
1919
-
1920
- //------------------------------------------------------------------------------
1921
- // Private
1922
- //------------------------------------------------------------------------------
1923
- let validateSchema;
1924
- const severityMap = {
1925
- error: 2,
1926
- warn: 1,
1927
- off: 0
1928
- };
1929
-
1930
- const validated = new WeakSet();
1931
-
1932
- //-----------------------------------------------------------------------------
1933
- // Exports
1934
- //-----------------------------------------------------------------------------
1935
-
1936
- class ConfigValidator {
1937
- constructor({ builtInRules = new Map() } = {}) {
1938
- this.builtInRules = builtInRules;
1939
- }
1940
-
1941
- /**
1942
- * Gets a complete options schema for a rule.
1943
- * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
1944
- * @returns {Object} JSON Schema for the rule's options.
1945
- */
1946
- getRuleOptionsSchema(rule) {
1947
- if (!rule) {
1948
- return null;
1949
- }
1950
-
1951
- const schema = rule.schema || rule.meta && rule.meta.schema;
1952
-
1953
- // Given a tuple of schemas, insert warning level at the beginning
1954
- if (Array.isArray(schema)) {
1955
- if (schema.length) {
1956
- return {
1957
- type: "array",
1958
- items: schema,
1959
- minItems: 0,
1960
- maxItems: schema.length
1961
- };
1962
- }
1963
- return {
1964
- type: "array",
1965
- minItems: 0,
1966
- maxItems: 0
1967
- };
1968
-
1969
- }
1970
-
1971
- // Given a full schema, leave it alone
1972
- return schema || null;
1973
- }
1974
-
1975
- /**
1976
- * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
1977
- * @param {options} options The given options for the rule.
1978
- * @returns {number|string} The rule's severity value
1979
- */
1980
- validateRuleSeverity(options) {
1981
- const severity = Array.isArray(options) ? options[0] : options;
1982
- const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
1983
-
1984
- if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
1985
- return normSeverity;
1986
- }
1987
-
1988
- throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
1989
-
1990
- }
1991
-
1992
- /**
1993
- * Validates the non-severity options passed to a rule, based on its schema.
1994
- * @param {{create: Function}} rule The rule to validate
1995
- * @param {Array} localOptions The options for the rule, excluding severity
1996
- * @returns {void}
1997
- */
1998
- validateRuleSchema(rule, localOptions) {
1999
- if (!ruleValidators.has(rule)) {
2000
- const schema = this.getRuleOptionsSchema(rule);
2001
-
2002
- if (schema) {
2003
- ruleValidators.set(rule, ajv.compile(schema));
2004
- }
2005
- }
2006
-
2007
- const validateRule = ruleValidators.get(rule);
2008
-
2009
- if (validateRule) {
2010
- validateRule(localOptions);
2011
- if (validateRule.errors) {
2012
- throw new Error(validateRule.errors.map(
2013
- error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
2014
- ).join(""));
2015
- }
2016
- }
2017
- }
2018
-
2019
- /**
2020
- * Validates a rule's options against its schema.
2021
- * @param {{create: Function}|null} rule The rule that the config is being validated for
2022
- * @param {string} ruleId The rule's unique name.
2023
- * @param {Array|number} options The given options for the rule.
2024
- * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
2025
- * no source is prepended to the message.
2026
- * @returns {void}
2027
- */
2028
- validateRuleOptions(rule, ruleId, options, source = null) {
2029
- try {
2030
- const severity = this.validateRuleSeverity(options);
2031
-
2032
- if (severity !== 0) {
2033
- this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
2034
- }
2035
- } catch (err) {
2036
- const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
2037
-
2038
- if (typeof source === "string") {
2039
- throw new Error(`${source}:\n\t${enhancedMessage}`);
2040
- } else {
2041
- throw new Error(enhancedMessage);
2042
- }
2043
- }
2044
- }
2045
-
2046
- /**
2047
- * Validates an environment object
2048
- * @param {Object} environment The environment config object to validate.
2049
- * @param {string} source The name of the configuration source to report in any errors.
2050
- * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
2051
- * @returns {void}
2052
- */
2053
- validateEnvironment(
2054
- environment,
2055
- source,
2056
- getAdditionalEnv = noop
2057
- ) {
2058
-
2059
- // not having an environment is ok
2060
- if (!environment) {
2061
- return;
2062
- }
2063
-
2064
- Object.keys(environment).forEach(id => {
2065
- const env = getAdditionalEnv(id) || environments.get(id) || null;
2066
-
2067
- if (!env) {
2068
- const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
2069
-
2070
- throw new Error(message);
2071
- }
2072
- });
2073
- }
2074
-
2075
- /**
2076
- * Validates a rules config object
2077
- * @param {Object} rulesConfig The rules config object to validate.
2078
- * @param {string} source The name of the configuration source to report in any errors.
2079
- * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
2080
- * @returns {void}
2081
- */
2082
- validateRules(
2083
- rulesConfig,
2084
- source,
2085
- getAdditionalRule = noop
2086
- ) {
2087
- if (!rulesConfig) {
2088
- return;
2089
- }
2090
-
2091
- Object.keys(rulesConfig).forEach(id => {
2092
- const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
2093
-
2094
- this.validateRuleOptions(rule, id, rulesConfig[id], source);
2095
- });
2096
- }
2097
-
2098
- /**
2099
- * Validates a `globals` section of a config file
2100
- * @param {Object} globalsConfig The `globals` section
2101
- * @param {string|null} source The name of the configuration source to report in the event of an error.
2102
- * @returns {void}
2103
- */
2104
- validateGlobals(globalsConfig, source = null) {
2105
- if (!globalsConfig) {
2106
- return;
2107
- }
2108
-
2109
- Object.entries(globalsConfig)
2110
- .forEach(([configuredGlobal, configuredValue]) => {
2111
- try {
2112
- normalizeConfigGlobal(configuredValue);
2113
- } catch (err) {
2114
- throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
2115
- }
2116
- });
2117
- }
2118
-
2119
- /**
2120
- * Validate `processor` configuration.
2121
- * @param {string|undefined} processorName The processor name.
2122
- * @param {string} source The name of config file.
2123
- * @param {function(id:string): Processor} getProcessor The getter of defined processors.
2124
- * @returns {void}
2125
- */
2126
- validateProcessor(processorName, source, getProcessor) {
2127
- if (processorName && !getProcessor(processorName)) {
2128
- throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
2129
- }
2130
- }
2131
-
2132
- /**
2133
- * Formats an array of schema validation errors.
2134
- * @param {Array} errors An array of error messages to format.
2135
- * @returns {string} Formatted error message
2136
- */
2137
- formatErrors(errors) {
2138
- return errors.map(error => {
2139
- if (error.keyword === "additionalProperties") {
2140
- const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
2141
-
2142
- return `Unexpected top-level property "${formattedPropertyPath}"`;
2143
- }
2144
- if (error.keyword === "type") {
2145
- const formattedField = error.dataPath.slice(1);
2146
- const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
2147
- const formattedValue = JSON.stringify(error.data);
2148
-
2149
- return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
2150
- }
2151
-
2152
- const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
2153
-
2154
- return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
2155
- }).map(message => `\t- ${message}.\n`).join("");
2156
- }
2157
-
2158
- /**
2159
- * Validates the top level properties of the config object.
2160
- * @param {Object} config The config object to validate.
2161
- * @param {string} source The name of the configuration source to report in any errors.
2162
- * @returns {void}
2163
- */
2164
- validateConfigSchema(config, source = null) {
2165
- validateSchema = validateSchema || ajv.compile(configSchema);
2166
-
2167
- if (!validateSchema(config)) {
2168
- throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
2169
- }
2170
-
2171
- if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
2172
- emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
2173
- }
2174
- }
2175
-
2176
- /**
2177
- * Validates an entire config object.
2178
- * @param {Object} config The config object to validate.
2179
- * @param {string} source The name of the configuration source to report in any errors.
2180
- * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
2181
- * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
2182
- * @returns {void}
2183
- */
2184
- validate(config, source, getAdditionalRule, getAdditionalEnv) {
2185
- this.validateConfigSchema(config, source);
2186
- this.validateRules(config.rules, source, getAdditionalRule);
2187
- this.validateEnvironment(config.env, source, getAdditionalEnv);
2188
- this.validateGlobals(config.globals, source);
2189
-
2190
- for (const override of config.overrides || []) {
2191
- this.validateRules(override.rules, source, getAdditionalRule);
2192
- this.validateEnvironment(override.env, source, getAdditionalEnv);
2193
- this.validateGlobals(config.globals, source);
2194
- }
2195
- }
2196
-
2197
- /**
2198
- * Validate config array object.
2199
- * @param {ConfigArray} configArray The config array to validate.
2200
- * @returns {void}
2201
- */
2202
- validateConfigArray(configArray) {
2203
- const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
2204
- const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
2205
- const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
2206
-
2207
- // Validate.
2208
- for (const element of configArray) {
2209
- if (validated.has(element)) {
2210
- continue;
2211
- }
2212
- validated.add(element);
2213
-
2214
- this.validateEnvironment(element.env, element.name, getPluginEnv);
2215
- this.validateGlobals(element.globals, element.name);
2216
- this.validateProcessor(element.processor, element.name, getPluginProcessor);
2217
- this.validateRules(element.rules, element.name, getPluginRule);
2218
- }
2219
- }
2220
-
2221
- }
2222
-
2223
- /**
2224
- * @fileoverview Common helpers for naming of plugins, formatters and configs
2225
- */
2226
-
2227
- const NAMESPACE_REGEX = /^@.*\//iu;
2228
-
2229
- /**
2230
- * Brings package name to correct format based on prefix
2231
- * @param {string} name The name of the package.
2232
- * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
2233
- * @returns {string} Normalized name of the package
2234
- * @private
2235
- */
2236
- function normalizePackageName(name, prefix) {
2237
- let normalizedName = name;
2238
-
2239
- /**
2240
- * On Windows, name can come in with Windows slashes instead of Unix slashes.
2241
- * Normalize to Unix first to avoid errors later on.
2242
- * https://github.com/eslint/eslint/issues/5644
2243
- */
2244
- if (normalizedName.includes("\\")) {
2245
- normalizedName = normalizedName.replace(/\\/gu, "/");
2246
- }
2247
-
2248
- if (normalizedName.charAt(0) === "@") {
2249
-
2250
- /**
2251
- * it's a scoped package
2252
- * package name is the prefix, or just a username
2253
- */
2254
- const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
2255
- scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
2256
-
2257
- if (scopedPackageShortcutRegex.test(normalizedName)) {
2258
- normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
2259
- } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
2260
-
2261
- /**
2262
- * for scoped packages, insert the prefix after the first / unless
2263
- * the path is already @scope/eslint or @scope/eslint-xxx-yyy
2264
- */
2265
- normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
2266
- }
2267
- } else if (!normalizedName.startsWith(`${prefix}-`)) {
2268
- normalizedName = `${prefix}-${normalizedName}`;
2269
- }
2270
-
2271
- return normalizedName;
2272
- }
2273
-
2274
- /**
2275
- * Removes the prefix from a fullname.
2276
- * @param {string} fullname The term which may have the prefix.
2277
- * @param {string} prefix The prefix to remove.
2278
- * @returns {string} The term without prefix.
2279
- */
2280
- function getShorthandName(fullname, prefix) {
2281
- if (fullname[0] === "@") {
2282
- let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
2283
-
2284
- if (matchResult) {
2285
- return matchResult[1];
2286
- }
2287
-
2288
- matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
2289
- if (matchResult) {
2290
- return `${matchResult[1]}/${matchResult[2]}`;
2291
- }
2292
- } else if (fullname.startsWith(`${prefix}-`)) {
2293
- return fullname.slice(prefix.length + 1);
2294
- }
2295
-
2296
- return fullname;
2297
- }
2298
-
2299
- /**
2300
- * Gets the scope (namespace) of a term.
2301
- * @param {string} term The term which may have the namespace.
2302
- * @returns {string} The namespace of the term if it has one.
2303
- */
2304
- function getNamespaceFromTerm(term) {
2305
- const match = term.match(NAMESPACE_REGEX);
2306
-
2307
- return match ? match[0] : "";
2308
- }
2309
-
2310
- var naming = {
2311
- __proto__: null,
2312
- normalizePackageName: normalizePackageName,
2313
- getShorthandName: getShorthandName,
2314
- getNamespaceFromTerm: getNamespaceFromTerm
2315
- };
2316
-
2317
- /**
2318
- * Utility for resolving a module relative to another module
2319
- * @author Teddy Katz
2320
- */
2321
-
2322
- /*
2323
- * `Module.createRequire` is added in v12.2.0. It supports URL as well.
2324
- * We only support the case where the argument is a filepath, not a URL.
2325
- */
2326
- const createRequire = Module__default["default"].createRequire;
2327
-
2328
- /**
2329
- * Resolves a Node module relative to another module
2330
- * @param {string} moduleName The name of a Node module, or a path to a Node module.
2331
- * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
2332
- * a file rather than a directory, but the file need not actually exist.
2333
- * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
2334
- */
2335
- function resolve(moduleName, relativeToPath) {
2336
- try {
2337
- return createRequire(relativeToPath).resolve(moduleName);
2338
- } catch (error) {
2339
-
2340
- // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
2341
- if (
2342
- typeof error === "object" &&
2343
- error !== null &&
2344
- error.code === "MODULE_NOT_FOUND" &&
2345
- !error.requireStack &&
2346
- error.message.includes(moduleName)
2347
- ) {
2348
- error.message += `\nRequire stack:\n- ${relativeToPath}`;
2349
- }
2350
- throw error;
2351
- }
2352
- }
2353
-
2354
- var ModuleResolver = {
2355
- __proto__: null,
2356
- resolve: resolve
2357
- };
2358
-
2359
- /**
2360
- * @fileoverview The factory of `ConfigArray` objects.
2361
- *
2362
- * This class provides methods to create `ConfigArray` instance.
2363
- *
2364
- * - `create(configData, options)`
2365
- * Create a `ConfigArray` instance from a config data. This is to handle CLI
2366
- * options except `--config`.
2367
- * - `loadFile(filePath, options)`
2368
- * Create a `ConfigArray` instance from a config file. This is to handle
2369
- * `--config` option. If the file was not found, throws the following error:
2370
- * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
2371
- * - If the filename was `package.json`, an IO error or an
2372
- * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
2373
- * - Otherwise, an IO error such as `ENOENT`.
2374
- * - `loadInDirectory(directoryPath, options)`
2375
- * Create a `ConfigArray` instance from a config file which is on a given
2376
- * directory. This tries to load `.eslintrc.*` or `package.json`. If not
2377
- * found, returns an empty `ConfigArray`.
2378
- * - `loadESLintIgnore(filePath)`
2379
- * Create a `ConfigArray` instance from a config file that is `.eslintignore`
2380
- * format. This is to handle `--ignore-path` option.
2381
- * - `loadDefaultESLintIgnore()`
2382
- * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
2383
- * the current working directory.
2384
- *
2385
- * `ConfigArrayFactory` class has the responsibility that loads configuration
2386
- * files, including loading `extends`, `parser`, and `plugins`. The created
2387
- * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
2388
- *
2389
- * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
2390
- * handles cascading and hierarchy.
2391
- *
2392
- * @author Toru Nagashima <https://github.com/mysticatea>
2393
- */
2394
-
2395
- const require$1 = Module.createRequire(require('url').pathToFileURL(__filename).toString());
2396
-
2397
- const debug$2 = debugOrig__default["default"]("eslintrc:config-array-factory");
2398
-
2399
- //------------------------------------------------------------------------------
2400
- // Helpers
2401
- //------------------------------------------------------------------------------
2402
-
2403
- const configFilenames = [
2404
- ".eslintrc.js",
2405
- ".eslintrc.cjs",
2406
- ".eslintrc.yaml",
2407
- ".eslintrc.yml",
2408
- ".eslintrc.json",
2409
- ".eslintrc",
2410
- "package.json"
2411
- ];
2412
-
2413
- // Define types for VSCode IntelliSense.
2414
- /** @typedef {import("./shared/types").ConfigData} ConfigData */
2415
- /** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
2416
- /** @typedef {import("./shared/types").Parser} Parser */
2417
- /** @typedef {import("./shared/types").Plugin} Plugin */
2418
- /** @typedef {import("./shared/types").Rule} Rule */
2419
- /** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
2420
- /** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
2421
- /** @typedef {ConfigArray[0]} ConfigArrayElement */
2422
-
2423
- /**
2424
- * @typedef {Object} ConfigArrayFactoryOptions
2425
- * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
2426
- * @property {string} [cwd] The path to the current working directory.
2427
- * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
2428
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
2429
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
2430
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
2431
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
2432
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
2433
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
2434
- */
2435
-
2436
- /**
2437
- * @typedef {Object} ConfigArrayFactoryInternalSlots
2438
- * @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
2439
- * @property {string} cwd The path to the current working directory.
2440
- * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
2441
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
2442
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
2443
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
2444
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
2445
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
2446
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
2447
- */
2448
-
2449
- /**
2450
- * @typedef {Object} ConfigArrayFactoryLoadingContext
2451
- * @property {string} filePath The path to the current configuration.
2452
- * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2453
- * @property {string} name The name of the current configuration.
2454
- * @property {string} pluginBasePath The base path to resolve plugins.
2455
- * @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.
2456
- */
2457
-
2458
- /**
2459
- * @typedef {Object} ConfigArrayFactoryLoadingContext
2460
- * @property {string} filePath The path to the current configuration.
2461
- * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2462
- * @property {string} name The name of the current configuration.
2463
- * @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.
2464
- */
2465
-
2466
- /** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
2467
- const internalSlotsMap$1 = new WeakMap();
2468
-
2469
- /** @type {WeakMap<object, Plugin>} */
2470
- const normalizedPlugins = new WeakMap();
2471
-
2472
- /**
2473
- * Check if a given string is a file path.
2474
- * @param {string} nameOrPath A module name or file path.
2475
- * @returns {boolean} `true` if the `nameOrPath` is a file path.
2476
- */
2477
- function isFilePath(nameOrPath) {
2478
- return (
2479
- /^\.{1,2}[/\\]/u.test(nameOrPath) ||
2480
- path__default["default"].isAbsolute(nameOrPath)
2481
- );
2482
- }
2483
-
2484
- /**
2485
- * Convenience wrapper for synchronously reading file contents.
2486
- * @param {string} filePath The filename to read.
2487
- * @returns {string} The file contents, with the BOM removed.
2488
- * @private
2489
- */
2490
- function readFile(filePath) {
2491
- return fs__default["default"].readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
2492
- }
2493
-
2494
- /**
2495
- * Loads a YAML configuration from a file.
2496
- * @param {string} filePath The filename to load.
2497
- * @returns {ConfigData} The configuration object from the file.
2498
- * @throws {Error} If the file cannot be read.
2499
- * @private
2500
- */
2501
- function loadYAMLConfigFile(filePath) {
2502
- debug$2(`Loading YAML config file: ${filePath}`);
2503
-
2504
- // lazy load YAML to improve performance when not used
2505
- const yaml = require$1("js-yaml");
2506
-
2507
- try {
2508
-
2509
- // empty YAML file can be null, so always use
2510
- return yaml.load(readFile(filePath)) || {};
2511
- } catch (e) {
2512
- debug$2(`Error reading YAML file: ${filePath}`);
2513
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2514
- throw e;
2515
- }
2516
- }
2517
-
2518
- /**
2519
- * Loads a JSON configuration from a file.
2520
- * @param {string} filePath The filename to load.
2521
- * @returns {ConfigData} The configuration object from the file.
2522
- * @throws {Error} If the file cannot be read.
2523
- * @private
2524
- */
2525
- function loadJSONConfigFile(filePath) {
2526
- debug$2(`Loading JSON config file: ${filePath}`);
2527
-
2528
- try {
2529
- return JSON.parse(stripComments__default["default"](readFile(filePath)));
2530
- } catch (e) {
2531
- debug$2(`Error reading JSON file: ${filePath}`);
2532
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2533
- e.messageTemplate = "failed-to-read-json";
2534
- e.messageData = {
2535
- path: filePath,
2536
- message: e.message
2537
- };
2538
- throw e;
2539
- }
2540
- }
2541
-
2542
- /**
2543
- * Loads a legacy (.eslintrc) configuration from a file.
2544
- * @param {string} filePath The filename to load.
2545
- * @returns {ConfigData} The configuration object from the file.
2546
- * @throws {Error} If the file cannot be read.
2547
- * @private
2548
- */
2549
- function loadLegacyConfigFile(filePath) {
2550
- debug$2(`Loading legacy config file: ${filePath}`);
2551
-
2552
- // lazy load YAML to improve performance when not used
2553
- const yaml = require$1("js-yaml");
2554
-
2555
- try {
2556
- return yaml.load(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {};
2557
- } catch (e) {
2558
- debug$2("Error reading YAML file: %s\n%o", filePath, e);
2559
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2560
- throw e;
2561
- }
2562
- }
2563
-
2564
- /**
2565
- * Loads a JavaScript configuration from a file.
2566
- * @param {string} filePath The filename to load.
2567
- * @returns {ConfigData} The configuration object from the file.
2568
- * @throws {Error} If the file cannot be read.
2569
- * @private
2570
- */
2571
- function loadJSConfigFile(filePath) {
2572
- debug$2(`Loading JS config file: ${filePath}`);
2573
- try {
2574
- return importFresh__default["default"](filePath);
2575
- } catch (e) {
2576
- debug$2(`Error reading JavaScript file: ${filePath}`);
2577
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2578
- throw e;
2579
- }
2580
- }
2581
-
2582
- /**
2583
- * Loads a configuration from a package.json file.
2584
- * @param {string} filePath The filename to load.
2585
- * @returns {ConfigData} The configuration object from the file.
2586
- * @throws {Error} If the file cannot be read.
2587
- * @private
2588
- */
2589
- function loadPackageJSONConfigFile(filePath) {
2590
- debug$2(`Loading package.json config file: ${filePath}`);
2591
- try {
2592
- const packageData = loadJSONConfigFile(filePath);
2593
-
2594
- if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
2595
- throw Object.assign(
2596
- new Error("package.json file doesn't have 'eslintConfig' field."),
2597
- { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
2598
- );
2599
- }
2600
-
2601
- return packageData.eslintConfig;
2602
- } catch (e) {
2603
- debug$2(`Error reading package.json file: ${filePath}`);
2604
- e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
2605
- throw e;
2606
- }
2607
- }
2608
-
2609
- /**
2610
- * Loads a `.eslintignore` from a file.
2611
- * @param {string} filePath The filename to load.
2612
- * @returns {string[]} The ignore patterns from the file.
2613
- * @private
2614
- */
2615
- function loadESLintIgnoreFile(filePath) {
2616
- debug$2(`Loading .eslintignore file: ${filePath}`);
2617
-
2618
- try {
2619
- return readFile(filePath)
2620
- .split(/\r?\n/gu)
2621
- .filter(line => line.trim() !== "" && !line.startsWith("#"));
2622
- } catch (e) {
2623
- debug$2(`Error reading .eslintignore file: ${filePath}`);
2624
- e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
2625
- throw e;
2626
- }
2627
- }
2628
-
2629
- /**
2630
- * Creates an error to notify about a missing config to extend from.
2631
- * @param {string} configName The name of the missing config.
2632
- * @param {string} importerName The name of the config that imported the missing config
2633
- * @param {string} messageTemplate The text template to source error strings from.
2634
- * @returns {Error} The error object to throw
2635
- * @private
2636
- */
2637
- function configInvalidError(configName, importerName, messageTemplate) {
2638
- return Object.assign(
2639
- new Error(`Failed to load config "${configName}" to extend from.`),
2640
- {
2641
- messageTemplate,
2642
- messageData: { configName, importerName }
2643
- }
2644
- );
2645
- }
2646
-
2647
- /**
2648
- * Loads a configuration file regardless of the source. Inspects the file path
2649
- * to determine the correctly way to load the config file.
2650
- * @param {string} filePath The path to the configuration.
2651
- * @returns {ConfigData|null} The configuration information.
2652
- * @private
2653
- */
2654
- function loadConfigFile(filePath) {
2655
- switch (path__default["default"].extname(filePath)) {
2656
- case ".js":
2657
- case ".cjs":
2658
- return loadJSConfigFile(filePath);
2659
-
2660
- case ".json":
2661
- if (path__default["default"].basename(filePath) === "package.json") {
2662
- return loadPackageJSONConfigFile(filePath);
2663
- }
2664
- return loadJSONConfigFile(filePath);
2665
-
2666
- case ".yaml":
2667
- case ".yml":
2668
- return loadYAMLConfigFile(filePath);
2669
-
2670
- default:
2671
- return loadLegacyConfigFile(filePath);
2672
- }
2673
- }
2674
-
2675
- /**
2676
- * Write debug log.
2677
- * @param {string} request The requested module name.
2678
- * @param {string} relativeTo The file path to resolve the request relative to.
2679
- * @param {string} filePath The resolved file path.
2680
- * @returns {void}
2681
- */
2682
- function writeDebugLogForLoading(request, relativeTo, filePath) {
2683
- /* istanbul ignore next */
2684
- if (debug$2.enabled) {
2685
- let nameAndVersion = null;
2686
-
2687
- try {
2688
- const packageJsonPath = resolve(
2689
- `${request}/package.json`,
2690
- relativeTo
2691
- );
2692
- const { version = "unknown" } = require$1(packageJsonPath);
2693
-
2694
- nameAndVersion = `${request}@${version}`;
2695
- } catch (error) {
2696
- debug$2("package.json was not found:", error.message);
2697
- nameAndVersion = request;
2698
- }
2699
-
2700
- debug$2("Loaded: %s (%s)", nameAndVersion, filePath);
2701
- }
2702
- }
2703
-
2704
- /**
2705
- * Create a new context with default values.
2706
- * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
2707
- * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
2708
- * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
2709
- * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
2710
- * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
2711
- * @returns {ConfigArrayFactoryLoadingContext} The created context.
2712
- */
2713
- function createContext(
2714
- { cwd, resolvePluginsRelativeTo },
2715
- providedType,
2716
- providedName,
2717
- providedFilePath,
2718
- providedMatchBasePath
2719
- ) {
2720
- const filePath = providedFilePath
2721
- ? path__default["default"].resolve(cwd, providedFilePath)
2722
- : "";
2723
- const matchBasePath =
2724
- (providedMatchBasePath && path__default["default"].resolve(cwd, providedMatchBasePath)) ||
2725
- (filePath && path__default["default"].dirname(filePath)) ||
2726
- cwd;
2727
- const name =
2728
- providedName ||
2729
- (filePath && path__default["default"].relative(cwd, filePath)) ||
2730
- "";
2731
- const pluginBasePath =
2732
- resolvePluginsRelativeTo ||
2733
- (filePath && path__default["default"].dirname(filePath)) ||
2734
- cwd;
2735
- const type = providedType || "config";
2736
-
2737
- return { filePath, matchBasePath, name, pluginBasePath, type };
2738
- }
2739
-
2740
- /**
2741
- * Normalize a given plugin.
2742
- * - Ensure the object to have four properties: configs, environments, processors, and rules.
2743
- * - Ensure the object to not have other properties.
2744
- * @param {Plugin} plugin The plugin to normalize.
2745
- * @returns {Plugin} The normalized plugin.
2746
- */
2747
- function normalizePlugin(plugin) {
2748
-
2749
- // first check the cache
2750
- let normalizedPlugin = normalizedPlugins.get(plugin);
2751
-
2752
- if (normalizedPlugin) {
2753
- return normalizedPlugin;
2754
- }
2755
-
2756
- normalizedPlugin = {
2757
- configs: plugin.configs || {},
2758
- environments: plugin.environments || {},
2759
- processors: plugin.processors || {},
2760
- rules: plugin.rules || {}
2761
- };
2762
-
2763
- // save the reference for later
2764
- normalizedPlugins.set(plugin, normalizedPlugin);
2765
-
2766
- return normalizedPlugin;
2767
- }
2768
-
2769
- //------------------------------------------------------------------------------
2770
- // Public Interface
2771
- //------------------------------------------------------------------------------
2772
-
2773
- /**
2774
- * The factory of `ConfigArray` objects.
2775
- */
2776
- class ConfigArrayFactory {
2777
-
2778
- /**
2779
- * Initialize this instance.
2780
- * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
2781
- */
2782
- constructor({
2783
- additionalPluginPool = new Map(),
2784
- cwd = process.cwd(),
2785
- resolvePluginsRelativeTo,
2786
- builtInRules,
2787
- resolver = ModuleResolver,
2788
- eslintAllPath,
2789
- getEslintAllConfig,
2790
- eslintRecommendedPath,
2791
- getEslintRecommendedConfig
2792
- } = {}) {
2793
- internalSlotsMap$1.set(this, {
2794
- additionalPluginPool,
2795
- cwd,
2796
- resolvePluginsRelativeTo:
2797
- resolvePluginsRelativeTo &&
2798
- path__default["default"].resolve(cwd, resolvePluginsRelativeTo),
2799
- builtInRules,
2800
- resolver,
2801
- eslintAllPath,
2802
- getEslintAllConfig,
2803
- eslintRecommendedPath,
2804
- getEslintRecommendedConfig
2805
- });
2806
- }
2807
-
2808
- /**
2809
- * Create `ConfigArray` instance from a config data.
2810
- * @param {ConfigData|null} configData The config data to create.
2811
- * @param {Object} [options] The options.
2812
- * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2813
- * @param {string} [options.filePath] The path to this config data.
2814
- * @param {string} [options.name] The config name.
2815
- * @returns {ConfigArray} Loaded config.
2816
- */
2817
- create(configData, { basePath, filePath, name } = {}) {
2818
- if (!configData) {
2819
- return new ConfigArray();
2820
- }
2821
-
2822
- const slots = internalSlotsMap$1.get(this);
2823
- const ctx = createContext(slots, "config", name, filePath, basePath);
2824
- const elements = this._normalizeConfigData(configData, ctx);
2825
-
2826
- return new ConfigArray(...elements);
2827
- }
2828
-
2829
- /**
2830
- * Load a config file.
2831
- * @param {string} filePath The path to a config file.
2832
- * @param {Object} [options] The options.
2833
- * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2834
- * @param {string} [options.name] The config name.
2835
- * @returns {ConfigArray} Loaded config.
2836
- */
2837
- loadFile(filePath, { basePath, name } = {}) {
2838
- const slots = internalSlotsMap$1.get(this);
2839
- const ctx = createContext(slots, "config", name, filePath, basePath);
2840
-
2841
- return new ConfigArray(...this._loadConfigData(ctx));
2842
- }
2843
-
2844
- /**
2845
- * Load the config file on a given directory if exists.
2846
- * @param {string} directoryPath The path to a directory.
2847
- * @param {Object} [options] The options.
2848
- * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
2849
- * @param {string} [options.name] The config name.
2850
- * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
2851
- */
2852
- loadInDirectory(directoryPath, { basePath, name } = {}) {
2853
- const slots = internalSlotsMap$1.get(this);
2854
-
2855
- for (const filename of configFilenames) {
2856
- const ctx = createContext(
2857
- slots,
2858
- "config",
2859
- name,
2860
- path__default["default"].join(directoryPath, filename),
2861
- basePath
2862
- );
2863
-
2864
- if (fs__default["default"].existsSync(ctx.filePath) && fs__default["default"].statSync(ctx.filePath).isFile()) {
2865
- let configData;
2866
-
2867
- try {
2868
- configData = loadConfigFile(ctx.filePath);
2869
- } catch (error) {
2870
- if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
2871
- throw error;
2872
- }
2873
- }
2874
-
2875
- if (configData) {
2876
- debug$2(`Config file found: ${ctx.filePath}`);
2877
- return new ConfigArray(
2878
- ...this._normalizeConfigData(configData, ctx)
2879
- );
2880
- }
2881
- }
2882
- }
2883
-
2884
- debug$2(`Config file not found on ${directoryPath}`);
2885
- return new ConfigArray();
2886
- }
2887
-
2888
- /**
2889
- * Check if a config file on a given directory exists or not.
2890
- * @param {string} directoryPath The path to a directory.
2891
- * @returns {string | null} The path to the found config file. If not found then null.
2892
- */
2893
- static getPathToConfigFileInDirectory(directoryPath) {
2894
- for (const filename of configFilenames) {
2895
- const filePath = path__default["default"].join(directoryPath, filename);
2896
-
2897
- if (fs__default["default"].existsSync(filePath)) {
2898
- if (filename === "package.json") {
2899
- try {
2900
- loadPackageJSONConfigFile(filePath);
2901
- return filePath;
2902
- } catch { /* ignore */ }
2903
- } else {
2904
- return filePath;
2905
- }
2906
- }
2907
- }
2908
- return null;
2909
- }
2910
-
2911
- /**
2912
- * Load `.eslintignore` file.
2913
- * @param {string} filePath The path to a `.eslintignore` file to load.
2914
- * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
2915
- */
2916
- loadESLintIgnore(filePath) {
2917
- const slots = internalSlotsMap$1.get(this);
2918
- const ctx = createContext(
2919
- slots,
2920
- "ignore",
2921
- void 0,
2922
- filePath,
2923
- slots.cwd
2924
- );
2925
- const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
2926
-
2927
- return new ConfigArray(
2928
- ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
2929
- );
2930
- }
2931
-
2932
- /**
2933
- * Load `.eslintignore` file in the current working directory.
2934
- * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
2935
- */
2936
- loadDefaultESLintIgnore() {
2937
- const slots = internalSlotsMap$1.get(this);
2938
- const eslintIgnorePath = path__default["default"].resolve(slots.cwd, ".eslintignore");
2939
- const packageJsonPath = path__default["default"].resolve(slots.cwd, "package.json");
2940
-
2941
- if (fs__default["default"].existsSync(eslintIgnorePath)) {
2942
- return this.loadESLintIgnore(eslintIgnorePath);
2943
- }
2944
- if (fs__default["default"].existsSync(packageJsonPath)) {
2945
- const data = loadJSONConfigFile(packageJsonPath);
2946
-
2947
- if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
2948
- if (!Array.isArray(data.eslintIgnore)) {
2949
- throw new Error("Package.json eslintIgnore property requires an array of paths");
2950
- }
2951
- const ctx = createContext(
2952
- slots,
2953
- "ignore",
2954
- "eslintIgnore in package.json",
2955
- packageJsonPath,
2956
- slots.cwd
2957
- );
2958
-
2959
- return new ConfigArray(
2960
- ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
2961
- );
2962
- }
2963
- }
2964
-
2965
- return new ConfigArray();
2966
- }
2967
-
2968
- /**
2969
- * Load a given config file.
2970
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
2971
- * @returns {IterableIterator<ConfigArrayElement>} Loaded config.
2972
- * @private
2973
- */
2974
- _loadConfigData(ctx) {
2975
- return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
2976
- }
2977
-
2978
- /**
2979
- * Normalize a given `.eslintignore` data to config array elements.
2980
- * @param {string[]} ignorePatterns The patterns to ignore files.
2981
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
2982
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
2983
- * @private
2984
- */
2985
- *_normalizeESLintIgnoreData(ignorePatterns, ctx) {
2986
- const elements = this._normalizeObjectConfigData(
2987
- { ignorePatterns },
2988
- ctx
2989
- );
2990
-
2991
- // Set `ignorePattern.loose` flag for backward compatibility.
2992
- for (const element of elements) {
2993
- if (element.ignorePattern) {
2994
- element.ignorePattern.loose = true;
2995
- }
2996
- yield element;
2997
- }
2998
- }
2999
-
3000
- /**
3001
- * Normalize a given config to an array.
3002
- * @param {ConfigData} configData The config data to normalize.
3003
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3004
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3005
- * @private
3006
- */
3007
- _normalizeConfigData(configData, ctx) {
3008
- const validator = new ConfigValidator();
3009
-
3010
- validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
3011
- return this._normalizeObjectConfigData(configData, ctx);
3012
- }
3013
-
3014
- /**
3015
- * Normalize a given config to an array.
3016
- * @param {ConfigData|OverrideConfigData} configData The config data to normalize.
3017
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3018
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3019
- * @private
3020
- */
3021
- *_normalizeObjectConfigData(configData, ctx) {
3022
- const { files, excludedFiles, ...configBody } = configData;
3023
- const criteria = OverrideTester.create(
3024
- files,
3025
- excludedFiles,
3026
- ctx.matchBasePath
3027
- );
3028
- const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
3029
-
3030
- // Apply the criteria to every element.
3031
- for (const element of elements) {
3032
-
3033
- /*
3034
- * Merge the criteria.
3035
- * This is for the `overrides` entries that came from the
3036
- * configurations of `overrides[].extends`.
3037
- */
3038
- element.criteria = OverrideTester.and(criteria, element.criteria);
3039
-
3040
- /*
3041
- * Remove `root` property to ignore `root` settings which came from
3042
- * `extends` in `overrides`.
3043
- */
3044
- if (element.criteria) {
3045
- element.root = void 0;
3046
- }
3047
-
3048
- yield element;
3049
- }
3050
- }
3051
-
3052
- /**
3053
- * Normalize a given config to an array.
3054
- * @param {ConfigData} configData The config data to normalize.
3055
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3056
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3057
- * @private
3058
- */
3059
- *_normalizeObjectConfigDataBody(
3060
- {
3061
- env,
3062
- extends: extend,
3063
- globals,
3064
- ignorePatterns,
3065
- noInlineConfig,
3066
- parser: parserName,
3067
- parserOptions,
3068
- plugins: pluginList,
3069
- processor,
3070
- reportUnusedDisableDirectives,
3071
- root,
3072
- rules,
3073
- settings,
3074
- overrides: overrideList = []
3075
- },
3076
- ctx
3077
- ) {
3078
- const extendList = Array.isArray(extend) ? extend : [extend];
3079
- const ignorePattern = ignorePatterns && new IgnorePattern(
3080
- Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
3081
- ctx.matchBasePath
3082
- );
3083
-
3084
- // Flatten `extends`.
3085
- for (const extendName of extendList.filter(Boolean)) {
3086
- yield* this._loadExtends(extendName, ctx);
3087
- }
3088
-
3089
- // Load parser & plugins.
3090
- const parser = parserName && this._loadParser(parserName, ctx);
3091
- const plugins = pluginList && this._loadPlugins(pluginList, ctx);
3092
-
3093
- // Yield pseudo config data for file extension processors.
3094
- if (plugins) {
3095
- yield* this._takeFileExtensionProcessors(plugins, ctx);
3096
- }
3097
-
3098
- // Yield the config data except `extends` and `overrides`.
3099
- yield {
3100
-
3101
- // Debug information.
3102
- type: ctx.type,
3103
- name: ctx.name,
3104
- filePath: ctx.filePath,
3105
-
3106
- // Config data.
3107
- criteria: null,
3108
- env,
3109
- globals,
3110
- ignorePattern,
3111
- noInlineConfig,
3112
- parser,
3113
- parserOptions,
3114
- plugins,
3115
- processor,
3116
- reportUnusedDisableDirectives,
3117
- root,
3118
- rules,
3119
- settings
3120
- };
3121
-
3122
- // Flatten `overries`.
3123
- for (let i = 0; i < overrideList.length; ++i) {
3124
- yield* this._normalizeObjectConfigData(
3125
- overrideList[i],
3126
- { ...ctx, name: `${ctx.name}#overrides[${i}]` }
3127
- );
3128
- }
3129
- }
3130
-
3131
- /**
3132
- * Load configs of an element in `extends`.
3133
- * @param {string} extendName The name of a base config.
3134
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3135
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3136
- * @private
3137
- */
3138
- _loadExtends(extendName, ctx) {
3139
- debug$2("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
3140
- try {
3141
- if (extendName.startsWith("eslint:")) {
3142
- return this._loadExtendedBuiltInConfig(extendName, ctx);
3143
- }
3144
- if (extendName.startsWith("plugin:")) {
3145
- return this._loadExtendedPluginConfig(extendName, ctx);
3146
- }
3147
- return this._loadExtendedShareableConfig(extendName, ctx);
3148
- } catch (error) {
3149
- error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
3150
- throw error;
3151
- }
3152
- }
3153
-
3154
- /**
3155
- * Load configs of an element in `extends`.
3156
- * @param {string} extendName The name of a base config.
3157
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3158
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3159
- * @private
3160
- */
3161
- _loadExtendedBuiltInConfig(extendName, ctx) {
3162
- const {
3163
- eslintAllPath,
3164
- getEslintAllConfig,
3165
- eslintRecommendedPath,
3166
- getEslintRecommendedConfig
3167
- } = internalSlotsMap$1.get(this);
3168
-
3169
- if (extendName === "eslint:recommended") {
3170
- const name = `${ctx.name} » ${extendName}`;
3171
-
3172
- if (getEslintRecommendedConfig) {
3173
- if (typeof getEslintRecommendedConfig !== "function") {
3174
- throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);
3175
- }
3176
- return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" });
3177
- }
3178
- return this._loadConfigData({
3179
- ...ctx,
3180
- name,
3181
- filePath: eslintRecommendedPath
3182
- });
3183
- }
3184
- if (extendName === "eslint:all") {
3185
- const name = `${ctx.name} » ${extendName}`;
3186
-
3187
- if (getEslintAllConfig) {
3188
- if (typeof getEslintAllConfig !== "function") {
3189
- throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);
3190
- }
3191
- return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" });
3192
- }
3193
- return this._loadConfigData({
3194
- ...ctx,
3195
- name,
3196
- filePath: eslintAllPath
3197
- });
3198
- }
3199
-
3200
- throw configInvalidError(extendName, ctx.name, "extend-config-missing");
3201
- }
3202
-
3203
- /**
3204
- * Load configs of an element in `extends`.
3205
- * @param {string} extendName The name of a base config.
3206
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3207
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3208
- * @private
3209
- */
3210
- _loadExtendedPluginConfig(extendName, ctx) {
3211
- const slashIndex = extendName.lastIndexOf("/");
3212
-
3213
- if (slashIndex === -1) {
3214
- throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
3215
- }
3216
-
3217
- const pluginName = extendName.slice("plugin:".length, slashIndex);
3218
- const configName = extendName.slice(slashIndex + 1);
3219
-
3220
- if (isFilePath(pluginName)) {
3221
- throw new Error("'extends' cannot use a file path for plugins.");
3222
- }
3223
-
3224
- const plugin = this._loadPlugin(pluginName, ctx);
3225
- const configData =
3226
- plugin.definition &&
3227
- plugin.definition.configs[configName];
3228
-
3229
- if (configData) {
3230
- return this._normalizeConfigData(configData, {
3231
- ...ctx,
3232
- filePath: plugin.filePath || ctx.filePath,
3233
- name: `${ctx.name} » plugin:${plugin.id}/${configName}`
3234
- });
3235
- }
3236
-
3237
- throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
3238
- }
3239
-
3240
- /**
3241
- * Load configs of an element in `extends`.
3242
- * @param {string} extendName The name of a base config.
3243
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3244
- * @returns {IterableIterator<ConfigArrayElement>} The normalized config.
3245
- * @private
3246
- */
3247
- _loadExtendedShareableConfig(extendName, ctx) {
3248
- const { cwd, resolver } = internalSlotsMap$1.get(this);
3249
- const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
3250
- let request;
3251
-
3252
- if (isFilePath(extendName)) {
3253
- request = extendName;
3254
- } else if (extendName.startsWith(".")) {
3255
- request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
3256
- } else {
3257
- request = normalizePackageName(
3258
- extendName,
3259
- "eslint-config"
3260
- );
3261
- }
3262
-
3263
- let filePath;
3264
-
3265
- try {
3266
- filePath = resolver.resolve(request, relativeTo);
3267
- } catch (error) {
3268
- /* istanbul ignore else */
3269
- if (error && error.code === "MODULE_NOT_FOUND") {
3270
- throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
3271
- }
3272
- throw error;
3273
- }
3274
-
3275
- writeDebugLogForLoading(request, relativeTo, filePath);
3276
- return this._loadConfigData({
3277
- ...ctx,
3278
- filePath,
3279
- name: `${ctx.name} » ${request}`
3280
- });
3281
- }
3282
-
3283
- /**
3284
- * Load given plugins.
3285
- * @param {string[]} names The plugin names to load.
3286
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3287
- * @returns {Record<string,DependentPlugin>} The loaded parser.
3288
- * @private
3289
- */
3290
- _loadPlugins(names, ctx) {
3291
- return names.reduce((map, name) => {
3292
- if (isFilePath(name)) {
3293
- throw new Error("Plugins array cannot includes file paths.");
3294
- }
3295
- const plugin = this._loadPlugin(name, ctx);
3296
-
3297
- map[plugin.id] = plugin;
3298
-
3299
- return map;
3300
- }, {});
3301
- }
3302
-
3303
- /**
3304
- * Load a given parser.
3305
- * @param {string} nameOrPath The package name or the path to a parser file.
3306
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3307
- * @returns {DependentParser} The loaded parser.
3308
- */
3309
- _loadParser(nameOrPath, ctx) {
3310
- debug$2("Loading parser %j from %s", nameOrPath, ctx.filePath);
3311
-
3312
- const { cwd, resolver } = internalSlotsMap$1.get(this);
3313
- const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
3314
-
3315
- try {
3316
- const filePath = resolver.resolve(nameOrPath, relativeTo);
3317
-
3318
- writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
3319
-
3320
- return new ConfigDependency({
3321
- definition: require$1(filePath),
3322
- filePath,
3323
- id: nameOrPath,
3324
- importerName: ctx.name,
3325
- importerPath: ctx.filePath
3326
- });
3327
- } catch (error) {
3328
-
3329
- // If the parser name is "espree", load the espree of ESLint.
3330
- if (nameOrPath === "espree") {
3331
- debug$2("Fallback espree.");
3332
- return new ConfigDependency({
3333
- definition: require$1("espree"),
3334
- filePath: require$1.resolve("espree"),
3335
- id: nameOrPath,
3336
- importerName: ctx.name,
3337
- importerPath: ctx.filePath
3338
- });
3339
- }
3340
-
3341
- debug$2("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
3342
- error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
3343
-
3344
- return new ConfigDependency({
3345
- error,
3346
- id: nameOrPath,
3347
- importerName: ctx.name,
3348
- importerPath: ctx.filePath
3349
- });
3350
- }
3351
- }
3352
-
3353
- /**
3354
- * Load a given plugin.
3355
- * @param {string} name The plugin name to load.
3356
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3357
- * @returns {DependentPlugin} The loaded plugin.
3358
- * @private
3359
- */
3360
- _loadPlugin(name, ctx) {
3361
- debug$2("Loading plugin %j from %s", name, ctx.filePath);
3362
-
3363
- const { additionalPluginPool, resolver } = internalSlotsMap$1.get(this);
3364
- const request = normalizePackageName(name, "eslint-plugin");
3365
- const id = getShorthandName(request, "eslint-plugin");
3366
- const relativeTo = path__default["default"].join(ctx.pluginBasePath, "__placeholder__.js");
3367
-
3368
- if (name.match(/\s+/u)) {
3369
- const error = Object.assign(
3370
- new Error(`Whitespace found in plugin name '${name}'`),
3371
- {
3372
- messageTemplate: "whitespace-found",
3373
- messageData: { pluginName: request }
3374
- }
3375
- );
3376
-
3377
- return new ConfigDependency({
3378
- error,
3379
- id,
3380
- importerName: ctx.name,
3381
- importerPath: ctx.filePath
3382
- });
3383
- }
3384
-
3385
- // Check for additional pool.
3386
- const plugin =
3387
- additionalPluginPool.get(request) ||
3388
- additionalPluginPool.get(id);
3389
-
3390
- if (plugin) {
3391
- return new ConfigDependency({
3392
- definition: normalizePlugin(plugin),
3393
- filePath: "", // It's unknown where the plugin came from.
3394
- id,
3395
- importerName: ctx.name,
3396
- importerPath: ctx.filePath
3397
- });
3398
- }
3399
-
3400
- let filePath;
3401
- let error;
3402
-
3403
- try {
3404
- filePath = resolver.resolve(request, relativeTo);
3405
- } catch (resolveError) {
3406
- error = resolveError;
3407
- /* istanbul ignore else */
3408
- if (error && error.code === "MODULE_NOT_FOUND") {
3409
- error.messageTemplate = "plugin-missing";
3410
- error.messageData = {
3411
- pluginName: request,
3412
- resolvePluginsRelativeTo: ctx.pluginBasePath,
3413
- importerName: ctx.name
3414
- };
3415
- }
3416
- }
3417
-
3418
- if (filePath) {
3419
- try {
3420
- writeDebugLogForLoading(request, relativeTo, filePath);
3421
-
3422
- const startTime = Date.now();
3423
- const pluginDefinition = require$1(filePath);
3424
-
3425
- debug$2(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
3426
-
3427
- return new ConfigDependency({
3428
- definition: normalizePlugin(pluginDefinition),
3429
- filePath,
3430
- id,
3431
- importerName: ctx.name,
3432
- importerPath: ctx.filePath
3433
- });
3434
- } catch (loadError) {
3435
- error = loadError;
3436
- }
3437
- }
3438
-
3439
- debug$2("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
3440
- error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
3441
- return new ConfigDependency({
3442
- error,
3443
- id,
3444
- importerName: ctx.name,
3445
- importerPath: ctx.filePath
3446
- });
3447
- }
3448
-
3449
- /**
3450
- * Take file expression processors as config array elements.
3451
- * @param {Record<string,DependentPlugin>} plugins The plugin definitions.
3452
- * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
3453
- * @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
3454
- * @private
3455
- */
3456
- *_takeFileExtensionProcessors(plugins, ctx) {
3457
- for (const pluginId of Object.keys(plugins)) {
3458
- const processors =
3459
- plugins[pluginId] &&
3460
- plugins[pluginId].definition &&
3461
- plugins[pluginId].definition.processors;
3462
-
3463
- if (!processors) {
3464
- continue;
3465
- }
3466
-
3467
- for (const processorId of Object.keys(processors)) {
3468
- if (processorId.startsWith(".")) {
3469
- yield* this._normalizeObjectConfigData(
3470
- {
3471
- files: [`*${processorId}`],
3472
- processor: `${pluginId}/${processorId}`
3473
- },
3474
- {
3475
- ...ctx,
3476
- type: "implicit-processor",
3477
- name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
3478
- }
3479
- );
3480
- }
3481
- }
3482
- }
3483
- }
3484
- }
3485
-
3486
- /**
3487
- * @fileoverview `CascadingConfigArrayFactory` class.
3488
- *
3489
- * `CascadingConfigArrayFactory` class has a responsibility:
3490
- *
3491
- * 1. Handles cascading of config files.
3492
- *
3493
- * It provides two methods:
3494
- *
3495
- * - `getConfigArrayForFile(filePath)`
3496
- * Get the corresponded configuration of a given file. This method doesn't
3497
- * throw even if the given file didn't exist.
3498
- * - `clearCache()`
3499
- * Clear the internal cache. You have to call this method when
3500
- * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
3501
- * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
3502
- *
3503
- * @author Toru Nagashima <https://github.com/mysticatea>
3504
- */
3505
-
3506
- const debug$1 = debugOrig__default["default"]("eslintrc:cascading-config-array-factory");
3507
-
3508
- //------------------------------------------------------------------------------
3509
- // Helpers
3510
- //------------------------------------------------------------------------------
3511
-
3512
- // Define types for VSCode IntelliSense.
3513
- /** @typedef {import("./shared/types").ConfigData} ConfigData */
3514
- /** @typedef {import("./shared/types").Parser} Parser */
3515
- /** @typedef {import("./shared/types").Plugin} Plugin */
3516
- /** @typedef {import("./shared/types").Rule} Rule */
3517
- /** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
3518
-
3519
- /**
3520
- * @typedef {Object} CascadingConfigArrayFactoryOptions
3521
- * @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
3522
- * @property {ConfigData} [baseConfig] The config by `baseConfig` option.
3523
- * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
3524
- * @property {string} [cwd] The base directory to start lookup.
3525
- * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
3526
- * @property {string[]} [rulePaths] The value of `--rulesdir` option.
3527
- * @property {string} [specificConfigPath] The value of `--config` option.
3528
- * @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
3529
- * @property {Function} loadRules The function to use to load rules.
3530
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
3531
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
3532
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
3533
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
3534
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
3535
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
3536
- */
3537
-
3538
- /**
3539
- * @typedef {Object} CascadingConfigArrayFactoryInternalSlots
3540
- * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
3541
- * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
3542
- * @property {ConfigArray} cliConfigArray The config array of CLI options.
3543
- * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
3544
- * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
3545
- * @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
3546
- * @property {string} cwd The base directory to start lookup.
3547
- * @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
3548
- * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
3549
- * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
3550
- * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
3551
- * @property {boolean} useEslintrc if `false` then it doesn't load config files.
3552
- * @property {Function} loadRules The function to use to load rules.
3553
- * @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
3554
- * @property {Object} [resolver=ModuleResolver] The module resolver object.
3555
- * @property {string} eslintAllPath The path to the definitions for eslint:all.
3556
- * @property {Function} getEslintAllConfig Returns the config data for eslint:all.
3557
- * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
3558
- * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
3559
- */
3560
-
3561
- /** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
3562
- const internalSlotsMap = new WeakMap();
3563
-
3564
- /**
3565
- * Create the config array from `baseConfig` and `rulePaths`.
3566
- * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
3567
- * @returns {ConfigArray} The config array of the base configs.
3568
- */
3569
- function createBaseConfigArray({
3570
- configArrayFactory,
3571
- baseConfigData,
3572
- rulePaths,
3573
- cwd,
3574
- loadRules
3575
- }) {
3576
- const baseConfigArray = configArrayFactory.create(
3577
- baseConfigData,
3578
- { name: "BaseConfig" }
3579
- );
3580
-
3581
- /*
3582
- * Create the config array element for the default ignore patterns.
3583
- * This element has `ignorePattern` property that ignores the default
3584
- * patterns in the current working directory.
3585
- */
3586
- baseConfigArray.unshift(configArrayFactory.create(
3587
- { ignorePatterns: IgnorePattern.DefaultPatterns },
3588
- { name: "DefaultIgnorePattern" }
3589
- )[0]);
3590
-
3591
- /*
3592
- * Load rules `--rulesdir` option as a pseudo plugin.
3593
- * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
3594
- * the rule's options with only information in the config array.
3595
- */
3596
- if (rulePaths && rulePaths.length > 0) {
3597
- baseConfigArray.push({
3598
- type: "config",
3599
- name: "--rulesdir",
3600
- filePath: "",
3601
- plugins: {
3602
- "": new ConfigDependency({
3603
- definition: {
3604
- rules: rulePaths.reduce(
3605
- (map, rulesPath) => Object.assign(
3606
- map,
3607
- loadRules(rulesPath, cwd)
3608
- ),
3609
- {}
3610
- )
3611
- },
3612
- filePath: "",
3613
- id: "",
3614
- importerName: "--rulesdir",
3615
- importerPath: ""
3616
- })
3617
- }
3618
- });
3619
- }
3620
-
3621
- return baseConfigArray;
3622
- }
3623
-
3624
- /**
3625
- * Create the config array from CLI options.
3626
- * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
3627
- * @returns {ConfigArray} The config array of the base configs.
3628
- */
3629
- function createCLIConfigArray({
3630
- cliConfigData,
3631
- configArrayFactory,
3632
- cwd,
3633
- ignorePath,
3634
- specificConfigPath
3635
- }) {
3636
- const cliConfigArray = configArrayFactory.create(
3637
- cliConfigData,
3638
- { name: "CLIOptions" }
3639
- );
3640
-
3641
- cliConfigArray.unshift(
3642
- ...(ignorePath
3643
- ? configArrayFactory.loadESLintIgnore(ignorePath)
3644
- : configArrayFactory.loadDefaultESLintIgnore())
3645
- );
3646
-
3647
- if (specificConfigPath) {
3648
- cliConfigArray.unshift(
3649
- ...configArrayFactory.loadFile(
3650
- specificConfigPath,
3651
- { name: "--config", basePath: cwd }
3652
- )
3653
- );
3654
- }
3655
-
3656
- return cliConfigArray;
3657
- }
3658
-
3659
- /**
3660
- * The error type when there are files matched by a glob, but all of them have been ignored.
3661
- */
3662
- class ConfigurationNotFoundError extends Error {
3663
-
3664
- // eslint-disable-next-line jsdoc/require-description
3665
- /**
3666
- * @param {string} directoryPath The directory path.
3667
- */
3668
- constructor(directoryPath) {
3669
- super(`No ESLint configuration found in ${directoryPath}.`);
3670
- this.messageTemplate = "no-config-found";
3671
- this.messageData = { directoryPath };
3672
- }
3673
- }
3674
-
3675
- /**
3676
- * This class provides the functionality that enumerates every file which is
3677
- * matched by given glob patterns and that configuration.
3678
- */
3679
- class CascadingConfigArrayFactory {
3680
-
3681
- /**
3682
- * Initialize this enumerator.
3683
- * @param {CascadingConfigArrayFactoryOptions} options The options.
3684
- */
3685
- constructor({
3686
- additionalPluginPool = new Map(),
3687
- baseConfig: baseConfigData = null,
3688
- cliConfig: cliConfigData = null,
3689
- cwd = process.cwd(),
3690
- ignorePath,
3691
- resolvePluginsRelativeTo,
3692
- rulePaths = [],
3693
- specificConfigPath = null,
3694
- useEslintrc = true,
3695
- builtInRules = new Map(),
3696
- loadRules,
3697
- resolver,
3698
- eslintRecommendedPath,
3699
- getEslintRecommendedConfig,
3700
- eslintAllPath,
3701
- getEslintAllConfig
3702
- } = {}) {
3703
- const configArrayFactory = new ConfigArrayFactory({
3704
- additionalPluginPool,
3705
- cwd,
3706
- resolvePluginsRelativeTo,
3707
- builtInRules,
3708
- resolver,
3709
- eslintRecommendedPath,
3710
- getEslintRecommendedConfig,
3711
- eslintAllPath,
3712
- getEslintAllConfig
3713
- });
3714
-
3715
- internalSlotsMap.set(this, {
3716
- baseConfigArray: createBaseConfigArray({
3717
- baseConfigData,
3718
- configArrayFactory,
3719
- cwd,
3720
- rulePaths,
3721
- loadRules
3722
- }),
3723
- baseConfigData,
3724
- cliConfigArray: createCLIConfigArray({
3725
- cliConfigData,
3726
- configArrayFactory,
3727
- cwd,
3728
- ignorePath,
3729
- specificConfigPath
3730
- }),
3731
- cliConfigData,
3732
- configArrayFactory,
3733
- configCache: new Map(),
3734
- cwd,
3735
- finalizeCache: new WeakMap(),
3736
- ignorePath,
3737
- rulePaths,
3738
- specificConfigPath,
3739
- useEslintrc,
3740
- builtInRules,
3741
- loadRules
3742
- });
3743
- }
3744
-
3745
- /**
3746
- * The path to the current working directory.
3747
- * This is used by tests.
3748
- * @type {string}
3749
- */
3750
- get cwd() {
3751
- const { cwd } = internalSlotsMap.get(this);
3752
-
3753
- return cwd;
3754
- }
3755
-
3756
- /**
3757
- * Get the config array of a given file.
3758
- * If `filePath` was not given, it returns the config which contains only
3759
- * `baseConfigData` and `cliConfigData`.
3760
- * @param {string} [filePath] The file path to a file.
3761
- * @param {Object} [options] The options.
3762
- * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
3763
- * @returns {ConfigArray} The config array of the file.
3764
- */
3765
- getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
3766
- const {
3767
- baseConfigArray,
3768
- cliConfigArray,
3769
- cwd
3770
- } = internalSlotsMap.get(this);
3771
-
3772
- if (!filePath) {
3773
- return new ConfigArray(...baseConfigArray, ...cliConfigArray);
3774
- }
3775
-
3776
- const directoryPath = path__default["default"].dirname(path__default["default"].resolve(cwd, filePath));
3777
-
3778
- debug$1(`Load config files for ${directoryPath}.`);
3779
-
3780
- return this._finalizeConfigArray(
3781
- this._loadConfigInAncestors(directoryPath),
3782
- directoryPath,
3783
- ignoreNotFoundError
3784
- );
3785
- }
3786
-
3787
- /**
3788
- * Set the config data to override all configs.
3789
- * Require to call `clearCache()` method after this method is called.
3790
- * @param {ConfigData} configData The config data to override all configs.
3791
- * @returns {void}
3792
- */
3793
- setOverrideConfig(configData) {
3794
- const slots = internalSlotsMap.get(this);
3795
-
3796
- slots.cliConfigData = configData;
3797
- }
3798
-
3799
- /**
3800
- * Clear config cache.
3801
- * @returns {void}
3802
- */
3803
- clearCache() {
3804
- const slots = internalSlotsMap.get(this);
3805
-
3806
- slots.baseConfigArray = createBaseConfigArray(slots);
3807
- slots.cliConfigArray = createCLIConfigArray(slots);
3808
- slots.configCache.clear();
3809
- }
3810
-
3811
- /**
3812
- * Load and normalize config files from the ancestor directories.
3813
- * @param {string} directoryPath The path to a leaf directory.
3814
- * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
3815
- * @returns {ConfigArray} The loaded config.
3816
- * @private
3817
- */
3818
- _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
3819
- const {
3820
- baseConfigArray,
3821
- configArrayFactory,
3822
- configCache,
3823
- cwd,
3824
- useEslintrc
3825
- } = internalSlotsMap.get(this);
3826
-
3827
- if (!useEslintrc) {
3828
- return baseConfigArray;
3829
- }
3830
-
3831
- let configArray = configCache.get(directoryPath);
3832
-
3833
- // Hit cache.
3834
- if (configArray) {
3835
- debug$1(`Cache hit: ${directoryPath}.`);
3836
- return configArray;
3837
- }
3838
- debug$1(`No cache found: ${directoryPath}.`);
3839
-
3840
- const homePath = os__default["default"].homedir();
3841
-
3842
- // Consider this is root.
3843
- if (directoryPath === homePath && cwd !== homePath) {
3844
- debug$1("Stop traversing because of considered root.");
3845
- if (configsExistInSubdirs) {
3846
- const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
3847
-
3848
- if (filePath) {
3849
- emitDeprecationWarning(
3850
- filePath,
3851
- "ESLINT_PERSONAL_CONFIG_SUPPRESS"
3852
- );
3853
- }
3854
- }
3855
- return this._cacheConfig(directoryPath, baseConfigArray);
3856
- }
3857
-
3858
- // Load the config on this directory.
3859
- try {
3860
- configArray = configArrayFactory.loadInDirectory(directoryPath);
3861
- } catch (error) {
3862
- /* istanbul ignore next */
3863
- if (error.code === "EACCES") {
3864
- debug$1("Stop traversing because of 'EACCES' error.");
3865
- return this._cacheConfig(directoryPath, baseConfigArray);
3866
- }
3867
- throw error;
3868
- }
3869
-
3870
- if (configArray.length > 0 && configArray.isRoot()) {
3871
- debug$1("Stop traversing because of 'root:true'.");
3872
- configArray.unshift(...baseConfigArray);
3873
- return this._cacheConfig(directoryPath, configArray);
3874
- }
3875
-
3876
- // Load from the ancestors and merge it.
3877
- const parentPath = path__default["default"].dirname(directoryPath);
3878
- const parentConfigArray = parentPath && parentPath !== directoryPath
3879
- ? this._loadConfigInAncestors(
3880
- parentPath,
3881
- configsExistInSubdirs || configArray.length > 0
3882
- )
3883
- : baseConfigArray;
3884
-
3885
- if (configArray.length > 0) {
3886
- configArray.unshift(...parentConfigArray);
3887
- } else {
3888
- configArray = parentConfigArray;
3889
- }
3890
-
3891
- // Cache and return.
3892
- return this._cacheConfig(directoryPath, configArray);
3893
- }
3894
-
3895
- /**
3896
- * Freeze and cache a given config.
3897
- * @param {string} directoryPath The path to a directory as a cache key.
3898
- * @param {ConfigArray} configArray The config array as a cache value.
3899
- * @returns {ConfigArray} The `configArray` (frozen).
3900
- */
3901
- _cacheConfig(directoryPath, configArray) {
3902
- const { configCache } = internalSlotsMap.get(this);
3903
-
3904
- Object.freeze(configArray);
3905
- configCache.set(directoryPath, configArray);
3906
-
3907
- return configArray;
3908
- }
3909
-
3910
- /**
3911
- * Finalize a given config array.
3912
- * Concatenate `--config` and other CLI options.
3913
- * @param {ConfigArray} configArray The parent config array.
3914
- * @param {string} directoryPath The path to the leaf directory to find config files.
3915
- * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
3916
- * @returns {ConfigArray} The loaded config.
3917
- * @private
3918
- */
3919
- _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
3920
- const {
3921
- cliConfigArray,
3922
- configArrayFactory,
3923
- finalizeCache,
3924
- useEslintrc,
3925
- builtInRules
3926
- } = internalSlotsMap.get(this);
3927
-
3928
- let finalConfigArray = finalizeCache.get(configArray);
3929
-
3930
- if (!finalConfigArray) {
3931
- finalConfigArray = configArray;
3932
-
3933
- // Load the personal config if there are no regular config files.
3934
- if (
3935
- useEslintrc &&
3936
- configArray.every(c => !c.filePath) &&
3937
- cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
3938
- ) {
3939
- const homePath = os__default["default"].homedir();
3940
-
3941
- debug$1("Loading the config file of the home directory:", homePath);
3942
-
3943
- const personalConfigArray = configArrayFactory.loadInDirectory(
3944
- homePath,
3945
- { name: "PersonalConfig" }
3946
- );
3947
-
3948
- if (
3949
- personalConfigArray.length > 0 &&
3950
- !directoryPath.startsWith(homePath)
3951
- ) {
3952
- const lastElement =
3953
- personalConfigArray[personalConfigArray.length - 1];
3954
-
3955
- emitDeprecationWarning(
3956
- lastElement.filePath,
3957
- "ESLINT_PERSONAL_CONFIG_LOAD"
3958
- );
3959
- }
3960
-
3961
- finalConfigArray = finalConfigArray.concat(personalConfigArray);
3962
- }
3963
-
3964
- // Apply CLI options.
3965
- if (cliConfigArray.length > 0) {
3966
- finalConfigArray = finalConfigArray.concat(cliConfigArray);
3967
- }
3968
-
3969
- // Validate rule settings and environments.
3970
- const validator = new ConfigValidator({
3971
- builtInRules
3972
- });
3973
-
3974
- validator.validateConfigArray(finalConfigArray);
3975
-
3976
- // Cache it.
3977
- Object.freeze(finalConfigArray);
3978
- finalizeCache.set(configArray, finalConfigArray);
3979
-
3980
- debug$1(
3981
- "Configuration was determined: %o on %s",
3982
- finalConfigArray,
3983
- directoryPath
3984
- );
3985
- }
3986
-
3987
- // At least one element (the default ignore patterns) exists.
3988
- if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
3989
- throw new ConfigurationNotFoundError(directoryPath);
3990
- }
3991
-
3992
- return finalConfigArray;
3993
- }
3994
- }
3995
-
3996
- /**
3997
- * @fileoverview Compatibility class for flat config.
3998
- * @author Nicholas C. Zakas
3999
- */
4000
-
4001
- //-----------------------------------------------------------------------------
4002
- // Helpers
4003
- //-----------------------------------------------------------------------------
4004
-
4005
- /** @typedef {import("../../shared/types").Environment} Environment */
4006
- /** @typedef {import("../../shared/types").Processor} Processor */
4007
-
4008
- const debug = debugOrig__default["default"]("eslintrc:flat-compat");
4009
- const cafactory = Symbol("cafactory");
4010
-
4011
- /**
4012
- * Translates an ESLintRC-style config object into a flag-config-style config
4013
- * object.
4014
- * @param {Object} eslintrcConfig An ESLintRC-style config object.
4015
- * @param {Object} options Options to help translate the config.
4016
- * @param {string} options.resolveConfigRelativeTo To the directory to resolve
4017
- * configs from.
4018
- * @param {string} options.resolvePluginsRelativeTo The directory to resolve
4019
- * plugins from.
4020
- * @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
4021
- * names to objects.
4022
- * @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
4023
- * names to objects.
4024
- * @returns {Object} A flag-config-style config object.
4025
- */
4026
- function translateESLintRC(eslintrcConfig, {
4027
- resolveConfigRelativeTo,
4028
- resolvePluginsRelativeTo,
4029
- pluginEnvironments,
4030
- pluginProcessors
4031
- }) {
4032
-
4033
- const flatConfig = {};
4034
- const configs = [];
4035
- const languageOptions = {};
4036
- const linterOptions = {};
4037
- const keysToCopy = ["settings", "rules", "processor"];
4038
- const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
4039
- const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
4040
-
4041
- // copy over simple translations
4042
- for (const key of keysToCopy) {
4043
- if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
4044
- flatConfig[key] = eslintrcConfig[key];
4045
- }
4046
- }
4047
-
4048
- // copy over languageOptions
4049
- for (const key of languageOptionsKeysToCopy) {
4050
- if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
4051
-
4052
- // create the languageOptions key in the flat config
4053
- flatConfig.languageOptions = languageOptions;
4054
-
4055
- if (key === "parser") {
4056
- debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
4057
-
4058
- if (eslintrcConfig[key].error) {
4059
- throw eslintrcConfig[key].error;
4060
- }
4061
-
4062
- languageOptions[key] = eslintrcConfig[key].definition;
4063
- continue;
4064
- }
4065
-
4066
- // clone any object values that are in the eslintrc config
4067
- if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
4068
- languageOptions[key] = {
4069
- ...eslintrcConfig[key]
4070
- };
4071
- } else {
4072
- languageOptions[key] = eslintrcConfig[key];
4073
- }
4074
- }
4075
- }
4076
-
4077
- // copy over linterOptions
4078
- for (const key of linterOptionsKeysToCopy) {
4079
- if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
4080
- flatConfig.linterOptions = linterOptions;
4081
- linterOptions[key] = eslintrcConfig[key];
4082
- }
4083
- }
4084
-
4085
- // move ecmaVersion a level up
4086
- if (languageOptions.parserOptions) {
4087
-
4088
- if ("ecmaVersion" in languageOptions.parserOptions) {
4089
- languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
4090
- delete languageOptions.parserOptions.ecmaVersion;
4091
- }
4092
-
4093
- if ("sourceType" in languageOptions.parserOptions) {
4094
- languageOptions.sourceType = languageOptions.parserOptions.sourceType;
4095
- delete languageOptions.parserOptions.sourceType;
4096
- }
4097
-
4098
- // check to see if we even need parserOptions anymore and remove it if not
4099
- if (Object.keys(languageOptions.parserOptions).length === 0) {
4100
- delete languageOptions.parserOptions;
4101
- }
4102
- }
4103
-
4104
- // overrides
4105
- if (eslintrcConfig.criteria) {
4106
- flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
4107
- }
4108
-
4109
- // translate plugins
4110
- if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
4111
- debug(`Translating plugins: ${eslintrcConfig.plugins}`);
4112
-
4113
- flatConfig.plugins = {};
4114
-
4115
- for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
4116
-
4117
- debug(`Translating plugin: ${pluginName}`);
4118
- debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
4119
-
4120
- const { definition: plugin, error } = eslintrcConfig.plugins[pluginName];
4121
-
4122
- if (error) {
4123
- throw error;
4124
- }
4125
-
4126
- flatConfig.plugins[pluginName] = plugin;
4127
-
4128
- // create a config for any processors
4129
- if (plugin.processors) {
4130
- for (const processorName of Object.keys(plugin.processors)) {
4131
- if (processorName.startsWith(".")) {
4132
- debug(`Assigning processor: ${pluginName}/${processorName}`);
4133
-
4134
- configs.unshift({
4135
- files: [`**/*${processorName}`],
4136
- processor: pluginProcessors.get(`${pluginName}/${processorName}`)
4137
- });
4138
- }
4139
-
4140
- }
4141
- }
4142
- }
4143
- }
4144
-
4145
- // translate env - must come after plugins
4146
- if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
4147
- for (const envName of Object.keys(eslintrcConfig.env)) {
4148
-
4149
- // only add environments that are true
4150
- if (eslintrcConfig.env[envName]) {
4151
- debug(`Translating environment: ${envName}`);
4152
-
4153
- if (environments.has(envName)) {
4154
-
4155
- // built-in environments should be defined first
4156
- configs.unshift(...translateESLintRC({
4157
- criteria: eslintrcConfig.criteria,
4158
- ...environments.get(envName)
4159
- }, {
4160
- resolveConfigRelativeTo,
4161
- resolvePluginsRelativeTo
4162
- }));
4163
- } else if (pluginEnvironments.has(envName)) {
4164
-
4165
- // if the environment comes from a plugin, it should come after the plugin config
4166
- configs.push(...translateESLintRC({
4167
- criteria: eslintrcConfig.criteria,
4168
- ...pluginEnvironments.get(envName)
4169
- }, {
4170
- resolveConfigRelativeTo,
4171
- resolvePluginsRelativeTo
4172
- }));
4173
- }
4174
- }
4175
- }
4176
- }
4177
-
4178
- // only add if there are actually keys in the config
4179
- if (Object.keys(flatConfig).length > 0) {
4180
- configs.push(flatConfig);
4181
- }
4182
-
4183
- return configs;
4184
- }
4185
-
4186
-
4187
- //-----------------------------------------------------------------------------
4188
- // Exports
4189
- //-----------------------------------------------------------------------------
4190
-
4191
- /**
4192
- * A compatibility class for working with configs.
4193
- */
4194
- class FlatCompat {
4195
-
4196
- constructor({
4197
- baseDirectory = process.cwd(),
4198
- resolvePluginsRelativeTo = baseDirectory,
4199
- recommendedConfig,
4200
- allConfig
4201
- } = {}) {
4202
- this.baseDirectory = baseDirectory;
4203
- this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
4204
- this[cafactory] = new ConfigArrayFactory({
4205
- cwd: baseDirectory,
4206
- resolvePluginsRelativeTo,
4207
- getEslintAllConfig: () => {
4208
-
4209
- if (!allConfig) {
4210
- throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor.");
4211
- }
4212
-
4213
- return allConfig;
4214
- },
4215
- getEslintRecommendedConfig: () => {
4216
-
4217
- if (!recommendedConfig) {
4218
- throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor.");
4219
- }
4220
-
4221
- return recommendedConfig;
4222
- }
4223
- });
4224
- }
4225
-
4226
- /**
4227
- * Translates an ESLintRC-style config into a flag-config-style config.
4228
- * @param {Object} eslintrcConfig The ESLintRC-style config object.
4229
- * @returns {Object} A flag-config-style config object.
4230
- */
4231
- config(eslintrcConfig) {
4232
- const eslintrcArray = this[cafactory].create(eslintrcConfig, {
4233
- basePath: this.baseDirectory
4234
- });
4235
-
4236
- const flatArray = [];
4237
- let hasIgnorePatterns = false;
4238
-
4239
- eslintrcArray.forEach(configData => {
4240
- if (configData.type === "config") {
4241
- hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
4242
- flatArray.push(...translateESLintRC(configData, {
4243
- resolveConfigRelativeTo: path__default["default"].join(this.baseDirectory, "__placeholder.js"),
4244
- resolvePluginsRelativeTo: path__default["default"].join(this.resolvePluginsRelativeTo, "__placeholder.js"),
4245
- pluginEnvironments: eslintrcArray.pluginEnvironments,
4246
- pluginProcessors: eslintrcArray.pluginProcessors
4247
- }));
4248
- }
4249
- });
4250
-
4251
- // combine ignorePatterns to emulate ESLintRC behavior better
4252
- if (hasIgnorePatterns) {
4253
- flatArray.unshift({
4254
- ignores: [filePath => {
4255
-
4256
- // Compute the final config for this file.
4257
- // This filters config array elements by `files`/`excludedFiles` then merges the elements.
4258
- const finalConfig = eslintrcArray.extractConfig(filePath);
4259
-
4260
- // Test the `ignorePattern` properties of the final config.
4261
- return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
4262
- }]
4263
- });
4264
- }
4265
-
4266
- return flatArray;
4267
- }
4268
-
4269
- /**
4270
- * Translates the `env` section of an ESLintRC-style config.
4271
- * @param {Object} envConfig The `env` section of an ESLintRC config.
4272
- * @returns {Object[]} An array of flag-config objects representing the environments.
4273
- */
4274
- env(envConfig) {
4275
- return this.config({
4276
- env: envConfig
4277
- });
4278
- }
4279
-
4280
- /**
4281
- * Translates the `extends` section of an ESLintRC-style config.
4282
- * @param {...string} configsToExtend The names of the configs to load.
4283
- * @returns {Object[]} An array of flag-config objects representing the config.
4284
- */
4285
- extends(...configsToExtend) {
4286
- return this.config({
4287
- extends: configsToExtend
4288
- });
4289
- }
4290
-
4291
- /**
4292
- * Translates the `plugins` section of an ESLintRC-style config.
4293
- * @param {...string} plugins The names of the plugins to load.
4294
- * @returns {Object[]} An array of flag-config objects representing the plugins.
4295
- */
4296
- plugins(...plugins) {
4297
- return this.config({
4298
- plugins
4299
- });
4300
- }
4301
- }
4302
-
4303
- /**
4304
- * @fileoverview Package exports for @eslint/eslintrc
4305
- * @author Nicholas C. Zakas
4306
- */
4307
-
4308
- //-----------------------------------------------------------------------------
4309
- // Exports
4310
- //-----------------------------------------------------------------------------
4311
-
4312
- const Legacy = {
4313
- ConfigArray,
4314
- createConfigArrayFactoryContext: createContext,
4315
- CascadingConfigArrayFactory,
4316
- ConfigArrayFactory,
4317
- ConfigDependency,
4318
- ExtractedConfig,
4319
- IgnorePattern,
4320
- OverrideTester,
4321
- getUsedExtractedConfigs,
4322
- environments,
4323
-
4324
- // shared
4325
- ConfigOps,
4326
- ConfigValidator,
4327
- ModuleResolver,
4328
- naming
4329
- };
4330
-
4331
- exports.FlatCompat = FlatCompat;
4332
- exports.Legacy = Legacy;
4333
- //# sourceMappingURL=eslintrc.cjs.map