checkAgainstRule.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const normalizeRuleSettings = require('../normalizeRuleSettings');
  3. const Result = require('postcss/lib/result');
  4. const rules = require('../rules');
  5. /**
  6. * Useful for third-party code (e.g. plugins) to run a PostCSS Root
  7. * against a specific rule and do something with the warnings
  8. * @template T
  9. * @template {Object} O
  10. * @param {{
  11. ruleName: string,
  12. ruleSettings: import('stylelint').ConfigRuleSettings<T, O>,
  13. root: import('postcss').Root,
  14. }} options
  15. * @param {(warning: import('postcss').Warning) => void} callback
  16. * @returns {void}
  17. */
  18. function checkAgainstRule(options, callback) {
  19. if (!options)
  20. throw new Error(
  21. "checkAgainstRule requires an options object with 'ruleName', 'ruleSettings', and 'root' properties",
  22. );
  23. if (!callback) throw new Error('checkAgainstRule requires a callback');
  24. if (!options.ruleName) throw new Error("checkAgainstRule requires a 'ruleName' option");
  25. if (!Object.keys(rules).includes(options.ruleName))
  26. throw new Error(`Rule '${options.ruleName}' does not exist`);
  27. if (!options.ruleSettings) throw new Error("checkAgainstRule requires a 'ruleSettings' option");
  28. if (!options.root) throw new Error("checkAgainstRule requires a 'root' option");
  29. const settings = normalizeRuleSettings(options.ruleSettings, options.ruleName);
  30. if (!settings) {
  31. return;
  32. }
  33. // @ts-expect-error - this error should not occur with PostCSS 8
  34. const tmpPostcssResult = new Result();
  35. rules[options.ruleName](
  36. settings[0],
  37. /** @type {O} */ (settings[1]),
  38. {},
  39. )(options.root, tmpPostcssResult);
  40. for (const warning of tmpPostcssResult.warnings()) callback(warning);
  41. }
  42. module.exports = /** @type {typeof import('stylelint').utils.checkAgainstRule} */ (
  43. checkAgainstRule
  44. );