config-validator.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /**
  2. * @fileoverview Validates configs.
  3. * @author Brandon Mills
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const ajv = require("../util/ajv"),
  10. lodash = require("lodash"),
  11. configSchema = require("../../conf/config-schema.js"),
  12. util = require("util");
  13. const ruleValidators = new WeakMap();
  14. //------------------------------------------------------------------------------
  15. // Private
  16. //------------------------------------------------------------------------------
  17. let validateSchema;
  18. /**
  19. * Gets a complete options schema for a rule.
  20. * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
  21. * @returns {Object} JSON Schema for the rule's options.
  22. */
  23. function getRuleOptionsSchema(rule) {
  24. const schema = rule.schema || rule.meta && rule.meta.schema;
  25. // Given a tuple of schemas, insert warning level at the beginning
  26. if (Array.isArray(schema)) {
  27. if (schema.length) {
  28. return {
  29. type: "array",
  30. items: schema,
  31. minItems: 0,
  32. maxItems: schema.length
  33. };
  34. }
  35. return {
  36. type: "array",
  37. minItems: 0,
  38. maxItems: 0
  39. };
  40. }
  41. // Given a full schema, leave it alone
  42. return schema || null;
  43. }
  44. /**
  45. * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
  46. * @param {options} options The given options for the rule.
  47. * @returns {number|string} The rule's severity value
  48. */
  49. function validateRuleSeverity(options) {
  50. const severity = Array.isArray(options) ? options[0] : options;
  51. if (severity !== 0 && severity !== 1 && severity !== 2 && !(typeof severity === "string" && /^(?:off|warn|error)$/i.test(severity))) {
  52. throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, "")}').\n`);
  53. }
  54. return severity;
  55. }
  56. /**
  57. * Validates the non-severity options passed to a rule, based on its schema.
  58. * @param {{create: Function}} rule The rule to validate
  59. * @param {array} localOptions The options for the rule, excluding severity
  60. * @returns {void}
  61. */
  62. function validateRuleSchema(rule, localOptions) {
  63. if (!ruleValidators.has(rule)) {
  64. const schema = getRuleOptionsSchema(rule);
  65. if (schema) {
  66. ruleValidators.set(rule, ajv.compile(schema));
  67. }
  68. }
  69. const validateRule = ruleValidators.get(rule);
  70. if (validateRule) {
  71. validateRule(localOptions);
  72. if (validateRule.errors) {
  73. throw new Error(validateRule.errors.map(
  74. error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
  75. ).join(""));
  76. }
  77. }
  78. }
  79. /**
  80. * Validates a rule's options against its schema.
  81. * @param {{create: Function}|null} rule The rule that the config is being validated for
  82. * @param {string} ruleId The rule's unique name.
  83. * @param {array|number} options The given options for the rule.
  84. * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
  85. * no source is prepended to the message.
  86. * @returns {void}
  87. */
  88. function validateRuleOptions(rule, ruleId, options, source) {
  89. if (!rule) {
  90. return;
  91. }
  92. try {
  93. const severity = validateRuleSeverity(options);
  94. if (severity !== 0 && !(typeof severity === "string" && severity.toLowerCase() === "off")) {
  95. validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
  96. }
  97. } catch (err) {
  98. const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
  99. if (typeof source === "string") {
  100. throw new Error(`${source}:\n\t${enhancedMessage}`);
  101. } else {
  102. throw new Error(enhancedMessage);
  103. }
  104. }
  105. }
  106. /**
  107. * Validates an environment object
  108. * @param {Object} environment The environment config object to validate.
  109. * @param {string} source The name of the configuration source to report in any errors.
  110. * @param {Environments} envContext Env context
  111. * @returns {void}
  112. */
  113. function validateEnvironment(environment, source, envContext) {
  114. // not having an environment is ok
  115. if (!environment) {
  116. return;
  117. }
  118. Object.keys(environment).forEach(env => {
  119. if (!envContext.get(env)) {
  120. const message = `${source}:\n\tEnvironment key "${env}" is unknown\n`;
  121. throw new Error(message);
  122. }
  123. });
  124. }
  125. /**
  126. * Validates a rules config object
  127. * @param {Object} rulesConfig The rules config object to validate.
  128. * @param {string} source The name of the configuration source to report in any errors.
  129. * @param {function(string): {create: Function}} ruleMapper A mapper function from strings to loaded rules
  130. * @returns {void}
  131. */
  132. function validateRules(rulesConfig, source, ruleMapper) {
  133. if (!rulesConfig) {
  134. return;
  135. }
  136. Object.keys(rulesConfig).forEach(id => {
  137. validateRuleOptions(ruleMapper(id), id, rulesConfig[id], source);
  138. });
  139. }
  140. /**
  141. * Formats an array of schema validation errors.
  142. * @param {Array} errors An array of error messages to format.
  143. * @returns {string} Formatted error message
  144. */
  145. function formatErrors(errors) {
  146. return errors.map(error => {
  147. if (error.keyword === "additionalProperties") {
  148. const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
  149. return `Unexpected top-level property "${formattedPropertyPath}"`;
  150. }
  151. if (error.keyword === "type") {
  152. const formattedField = error.dataPath.slice(1);
  153. const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
  154. const formattedValue = JSON.stringify(error.data);
  155. return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
  156. }
  157. const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
  158. return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
  159. }).map(message => `\t- ${message}.\n`).join("");
  160. }
  161. /**
  162. * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
  163. * for each unique file path, but repeated invocations with the same file path have no effect.
  164. * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
  165. * @param {string} source The name of the configuration source to report the warning for.
  166. * @returns {void}
  167. */
  168. const emitEcmaFeaturesWarning = lodash.memoize(source => {
  169. /*
  170. * util.deprecate seems to be the only way to emit a warning in Node 4.x while respecting the --no-warnings flag.
  171. * (In Node 6+, process.emitWarning could be used instead.)
  172. */
  173. util.deprecate(
  174. () => {},
  175. `[eslint] The 'ecmaFeatures' config file property is deprecated, and has no effect. (found in ${source})`
  176. )();
  177. });
  178. /**
  179. * Validates the top level properties of the config object.
  180. * @param {Object} config The config object to validate.
  181. * @param {string} source The name of the configuration source to report in any errors.
  182. * @returns {void}
  183. */
  184. function validateConfigSchema(config, source) {
  185. validateSchema = validateSchema || ajv.compile(configSchema);
  186. if (!validateSchema(config)) {
  187. throw new Error(`ESLint configuration in ${source} is invalid:\n${formatErrors(validateSchema.errors)}`);
  188. }
  189. if (Object.prototype.hasOwnProperty.call(config, "ecmaFeatures")) {
  190. emitEcmaFeaturesWarning(source);
  191. }
  192. }
  193. /**
  194. * Validates an entire config object.
  195. * @param {Object} config The config object to validate.
  196. * @param {string} source The name of the configuration source to report in any errors.
  197. * @param {function(string): {create: Function}} ruleMapper A mapper function from rule IDs to defined rules
  198. * @param {Environments} envContext The env context
  199. * @returns {void}
  200. */
  201. function validate(config, source, ruleMapper, envContext) {
  202. validateConfigSchema(config, source);
  203. validateRules(config.rules, source, ruleMapper);
  204. validateEnvironment(config.env, source, envContext);
  205. }
  206. //------------------------------------------------------------------------------
  207. // Public Interface
  208. //------------------------------------------------------------------------------
  209. module.exports = {
  210. getRuleOptionsSchema,
  211. validate,
  212. validateRuleOptions
  213. };