Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config-validator.js 11KB

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