rule-validator.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. /**
  2. * @fileoverview Rule Validator
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //-----------------------------------------------------------------------------
  7. // Requirements
  8. //-----------------------------------------------------------------------------
  9. const ajv = require("../shared/ajv")();
  10. const {
  11. parseRuleId,
  12. getRuleFromConfig,
  13. getRuleOptionsSchema
  14. } = require("./flat-config-helpers");
  15. const ruleReplacements = require("../../conf/replacements.json");
  16. //-----------------------------------------------------------------------------
  17. // Helpers
  18. //-----------------------------------------------------------------------------
  19. /**
  20. * Throws a helpful error when a rule cannot be found.
  21. * @param {Object} ruleId The rule identifier.
  22. * @param {string} ruleId.pluginName The ID of the rule to find.
  23. * @param {string} ruleId.ruleName The ID of the rule to find.
  24. * @param {Object} config The config to search in.
  25. * @throws {TypeError} For missing plugin or rule.
  26. * @returns {void}
  27. */
  28. function throwRuleNotFoundError({ pluginName, ruleName }, config) {
  29. const ruleId = pluginName === "@" ? ruleName : `${pluginName}/${ruleName}`;
  30. const errorMessageHeader = `Key "rules": Key "${ruleId}"`;
  31. let errorMessage = `${errorMessageHeader}: Could not find plugin "${pluginName}".`;
  32. // if the plugin exists then we need to check if the rule exists
  33. if (config.plugins && config.plugins[pluginName]) {
  34. const replacementRuleName = ruleReplacements.rules[ruleName];
  35. if (pluginName === "@" && replacementRuleName) {
  36. errorMessage = `${errorMessageHeader}: Rule "${ruleName}" was removed and replaced by "${replacementRuleName}".`;
  37. } else {
  38. errorMessage = `${errorMessageHeader}: Could not find "${ruleName}" in plugin "${pluginName}".`;
  39. // otherwise, let's see if we can find the rule name elsewhere
  40. for (const [otherPluginName, otherPlugin] of Object.entries(config.plugins)) {
  41. if (otherPlugin.rules && otherPlugin.rules[ruleName]) {
  42. errorMessage += ` Did you mean "${otherPluginName}/${ruleName}"?`;
  43. break;
  44. }
  45. }
  46. }
  47. // falls through to throw error
  48. }
  49. throw new TypeError(errorMessage);
  50. }
  51. //-----------------------------------------------------------------------------
  52. // Exports
  53. //-----------------------------------------------------------------------------
  54. /**
  55. * Implements validation functionality for the rules portion of a config.
  56. */
  57. class RuleValidator {
  58. /**
  59. * Creates a new instance.
  60. */
  61. constructor() {
  62. /**
  63. * A collection of compiled validators for rules that have already
  64. * been validated.
  65. * @type {WeakMap}
  66. */
  67. this.validators = new WeakMap();
  68. }
  69. /**
  70. * Validates all of the rule configurations in a config against each
  71. * rule's schema.
  72. * @param {Object} config The full config to validate. This object must
  73. * contain both the rules section and the plugins section.
  74. * @returns {void}
  75. * @throws {Error} If a rule's configuration does not match its schema.
  76. */
  77. validate(config) {
  78. if (!config.rules) {
  79. return;
  80. }
  81. for (const [ruleId, ruleOptions] of Object.entries(config.rules)) {
  82. // check for edge case
  83. if (ruleId === "__proto__") {
  84. continue;
  85. }
  86. /*
  87. * If a rule is disabled, we don't do any validation. This allows
  88. * users to safely set any value to 0 or "off" without worrying
  89. * that it will cause a validation error.
  90. *
  91. * Note: ruleOptions is always an array at this point because
  92. * this validation occurs after FlatConfigArray has merged and
  93. * normalized values.
  94. */
  95. if (ruleOptions[0] === 0) {
  96. continue;
  97. }
  98. const rule = getRuleFromConfig(ruleId, config);
  99. if (!rule) {
  100. throwRuleNotFoundError(parseRuleId(ruleId), config);
  101. }
  102. // Precompile and cache validator the first time
  103. if (!this.validators.has(rule)) {
  104. const schema = getRuleOptionsSchema(rule);
  105. if (schema) {
  106. this.validators.set(rule, ajv.compile(schema));
  107. }
  108. }
  109. const validateRule = this.validators.get(rule);
  110. if (validateRule) {
  111. validateRule(ruleOptions.slice(1));
  112. if (validateRule.errors) {
  113. throw new Error(`Key "rules": Key "${ruleId}": ${
  114. validateRule.errors.map(
  115. error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
  116. ).join("")
  117. }`);
  118. }
  119. }
  120. }
  121. }
  122. }
  123. exports.RuleValidator = RuleValidator;