checkAgainstRule.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const normalizeRuleSettings = require('../normalizeRuleSettings');
  3. const Result = require('postcss/lib/result');
  4. const { isPlainObject } = require('./validateTypes');
  5. const getStylelintRule = require('./getStylelintRule');
  6. /**
  7. * Useful for third-party code (e.g. plugins) to run a PostCSS Root
  8. * against a specific rule and do something with the warnings
  9. *
  10. * @type {typeof import('stylelint').utils.checkAgainstRule}
  11. */
  12. function checkAgainstRule(options, callback) {
  13. if (!isPlainObject(options)) throw new Error('Expected an options object');
  14. if (!callback) throw new Error('Expected a callback function');
  15. const { ruleName, ruleSettings, root, result, context = {} } = options;
  16. if (!ruleName) throw new Error('Expected a "ruleName" option');
  17. const rule = getStylelintRule(ruleName, result && result.stylelint.config);
  18. if (!rule) throw new Error(`Rule "${ruleName}" does not exist`);
  19. if (!ruleSettings) throw new Error('Expected a "ruleSettings" option');
  20. if (!root) throw new Error('Expected a "root" option');
  21. const settings = normalizeRuleSettings(ruleSettings, rule);
  22. if (!settings) {
  23. return;
  24. }
  25. // @ts-expect-error - this error should not occur with PostCSS 8
  26. const tmpPostcssResult = new Result();
  27. rule(settings[0], /** @type {Object} */ (settings[1]), context)(root, tmpPostcssResult);
  28. for (const warning of tmpPostcssResult.warnings()) callback(warning);
  29. }
  30. module.exports = checkAgainstRule;