source: imaps-frontend/node_modules/@eslint/eslintrc/lib/shared/config-validator.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 11.6 KB
RevLine 
[d565449]1/**
2 * @fileoverview Validates configs.
3 * @author Brandon Mills
4 */
5
6/* eslint class-methods-use-this: "off" */
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12import util from "util";
13import * as ConfigOps from "./config-ops.js";
14import { emitDeprecationWarning } from "./deprecation-warnings.js";
15import ajvOrig from "./ajv.js";
16import configSchema from "../../conf/config-schema.js";
17import BuiltInEnvironments from "../../conf/environments.js";
18
19const ajv = ajvOrig();
20
21const ruleValidators = new WeakMap();
22const noop = Function.prototype;
23
24//------------------------------------------------------------------------------
25// Private
26//------------------------------------------------------------------------------
27let validateSchema;
28const severityMap = {
29 error: 2,
30 warn: 1,
31 off: 0
32};
33
34const validated = new WeakSet();
35
36//-----------------------------------------------------------------------------
37// Exports
38//-----------------------------------------------------------------------------
39
40export default class ConfigValidator {
41 constructor({ builtInRules = new Map() } = {}) {
42 this.builtInRules = builtInRules;
43 }
44
45 /**
46 * Gets a complete options schema for a rule.
47 * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
48 * @returns {Object} JSON Schema for the rule's options.
49 */
50 getRuleOptionsSchema(rule) {
51 if (!rule) {
52 return null;
53 }
54
55 const schema = rule.schema || rule.meta && rule.meta.schema;
56
57 // Given a tuple of schemas, insert warning level at the beginning
58 if (Array.isArray(schema)) {
59 if (schema.length) {
60 return {
61 type: "array",
62 items: schema,
63 minItems: 0,
64 maxItems: schema.length
65 };
66 }
67 return {
68 type: "array",
69 minItems: 0,
70 maxItems: 0
71 };
72
73 }
74
75 // Given a full schema, leave it alone
76 return schema || null;
77 }
78
79 /**
80 * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
81 * @param {options} options The given options for the rule.
82 * @returns {number|string} The rule's severity value
83 */
84 validateRuleSeverity(options) {
85 const severity = Array.isArray(options) ? options[0] : options;
86 const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
87
88 if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
89 return normSeverity;
90 }
91
92 throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
93
94 }
95
96 /**
97 * Validates the non-severity options passed to a rule, based on its schema.
98 * @param {{create: Function}} rule The rule to validate
99 * @param {Array} localOptions The options for the rule, excluding severity
100 * @returns {void}
101 */
102 validateRuleSchema(rule, localOptions) {
103 if (!ruleValidators.has(rule)) {
104 const schema = this.getRuleOptionsSchema(rule);
105
106 if (schema) {
107 ruleValidators.set(rule, ajv.compile(schema));
108 }
109 }
110
111 const validateRule = ruleValidators.get(rule);
112
113 if (validateRule) {
114 validateRule(localOptions);
115 if (validateRule.errors) {
116 throw new Error(validateRule.errors.map(
117 error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
118 ).join(""));
119 }
120 }
121 }
122
123 /**
124 * Validates a rule's options against its schema.
125 * @param {{create: Function}|null} rule The rule that the config is being validated for
126 * @param {string} ruleId The rule's unique name.
127 * @param {Array|number} options The given options for the rule.
128 * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
129 * no source is prepended to the message.
130 * @returns {void}
131 */
132 validateRuleOptions(rule, ruleId, options, source = null) {
133 try {
134 const severity = this.validateRuleSeverity(options);
135
136 if (severity !== 0) {
137 this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
138 }
139 } catch (err) {
140 const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
141
142 if (typeof source === "string") {
143 throw new Error(`${source}:\n\t${enhancedMessage}`);
144 } else {
145 throw new Error(enhancedMessage);
146 }
147 }
148 }
149
150 /**
151 * Validates an environment object
152 * @param {Object} environment The environment config object to validate.
153 * @param {string} source The name of the configuration source to report in any errors.
154 * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
155 * @returns {void}
156 */
157 validateEnvironment(
158 environment,
159 source,
160 getAdditionalEnv = noop
161 ) {
162
163 // not having an environment is ok
164 if (!environment) {
165 return;
166 }
167
168 Object.keys(environment).forEach(id => {
169 const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
170
171 if (!env) {
172 const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
173
174 throw new Error(message);
175 }
176 });
177 }
178
179 /**
180 * Validates a rules config object
181 * @param {Object} rulesConfig The rules config object to validate.
182 * @param {string} source The name of the configuration source to report in any errors.
183 * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
184 * @returns {void}
185 */
186 validateRules(
187 rulesConfig,
188 source,
189 getAdditionalRule = noop
190 ) {
191 if (!rulesConfig) {
192 return;
193 }
194
195 Object.keys(rulesConfig).forEach(id => {
196 const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
197
198 this.validateRuleOptions(rule, id, rulesConfig[id], source);
199 });
200 }
201
202 /**
203 * Validates a `globals` section of a config file
204 * @param {Object} globalsConfig The `globals` section
205 * @param {string|null} source The name of the configuration source to report in the event of an error.
206 * @returns {void}
207 */
208 validateGlobals(globalsConfig, source = null) {
209 if (!globalsConfig) {
210 return;
211 }
212
213 Object.entries(globalsConfig)
214 .forEach(([configuredGlobal, configuredValue]) => {
215 try {
216 ConfigOps.normalizeConfigGlobal(configuredValue);
217 } catch (err) {
218 throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
219 }
220 });
221 }
222
223 /**
224 * Validate `processor` configuration.
225 * @param {string|undefined} processorName The processor name.
226 * @param {string} source The name of config file.
227 * @param {function(id:string): Processor} getProcessor The getter of defined processors.
228 * @returns {void}
229 */
230 validateProcessor(processorName, source, getProcessor) {
231 if (processorName && !getProcessor(processorName)) {
232 throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
233 }
234 }
235
236 /**
237 * Formats an array of schema validation errors.
238 * @param {Array} errors An array of error messages to format.
239 * @returns {string} Formatted error message
240 */
241 formatErrors(errors) {
242 return errors.map(error => {
243 if (error.keyword === "additionalProperties") {
244 const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
245
246 return `Unexpected top-level property "${formattedPropertyPath}"`;
247 }
248 if (error.keyword === "type") {
249 const formattedField = error.dataPath.slice(1);
250 const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
251 const formattedValue = JSON.stringify(error.data);
252
253 return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
254 }
255
256 const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
257
258 return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
259 }).map(message => `\t- ${message}.\n`).join("");
260 }
261
262 /**
263 * Validates the top level properties of the config object.
264 * @param {Object} config The config object to validate.
265 * @param {string} source The name of the configuration source to report in any errors.
266 * @returns {void}
267 */
268 validateConfigSchema(config, source = null) {
269 validateSchema = validateSchema || ajv.compile(configSchema);
270
271 if (!validateSchema(config)) {
272 throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
273 }
274
275 if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
276 emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
277 }
278 }
279
280 /**
281 * Validates an entire config object.
282 * @param {Object} config The config object to validate.
283 * @param {string} source The name of the configuration source to report in any errors.
284 * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
285 * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
286 * @returns {void}
287 */
288 validate(config, source, getAdditionalRule, getAdditionalEnv) {
289 this.validateConfigSchema(config, source);
290 this.validateRules(config.rules, source, getAdditionalRule);
291 this.validateEnvironment(config.env, source, getAdditionalEnv);
292 this.validateGlobals(config.globals, source);
293
294 for (const override of config.overrides || []) {
295 this.validateRules(override.rules, source, getAdditionalRule);
296 this.validateEnvironment(override.env, source, getAdditionalEnv);
297 this.validateGlobals(config.globals, source);
298 }
299 }
300
301 /**
302 * Validate config array object.
303 * @param {ConfigArray} configArray The config array to validate.
304 * @returns {void}
305 */
306 validateConfigArray(configArray) {
307 const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
308 const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
309 const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
310
311 // Validate.
312 for (const element of configArray) {
313 if (validated.has(element)) {
314 continue;
315 }
316 validated.add(element);
317
318 this.validateEnvironment(element.env, element.name, getPluginEnv);
319 this.validateGlobals(element.globals, element.name);
320 this.validateProcessor(element.processor, element.name, getPluginProcessor);
321 this.validateRules(element.rules, element.name, getPluginRule);
322 }
323 }
324
325}
Note: See TracBrowser for help on using the repository browser.