reportUnknownRuleNames.cjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // NOTICE: This file is generated by Rollup. To modify it,
  2. // please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
  3. 'use strict';
  4. const fastestLevenshtein = require('fastest-levenshtein');
  5. const constants = require('./constants.cjs');
  6. const index = require('./rules/index.cjs');
  7. const MAX_LEVENSHTEIN_DISTANCE = 6;
  8. const MAX_SUGGESTIONS_COUNT = 3;
  9. /**
  10. * @param {string} ruleName
  11. * @returns {string[]}
  12. */
  13. function extractSuggestions(ruleName) {
  14. const suggestions = Array.from({ length: MAX_LEVENSHTEIN_DISTANCE });
  15. for (let i = 0; i < suggestions.length; i++) {
  16. suggestions[i] = [];
  17. }
  18. for (const existRuleName of Object.keys(index)) {
  19. const dist = fastestLevenshtein.distance(existRuleName, ruleName);
  20. if (dist <= MAX_LEVENSHTEIN_DISTANCE) {
  21. suggestions[dist - 1].push(existRuleName);
  22. }
  23. }
  24. /** @type {string[]} */
  25. let result = [];
  26. for (const [i, suggestion] of suggestions.entries()) {
  27. if (suggestion.length > 0) {
  28. if (i < 3) {
  29. return suggestion.slice(0, MAX_SUGGESTIONS_COUNT);
  30. }
  31. result = result.concat(suggestion);
  32. }
  33. }
  34. return result.slice(0, MAX_SUGGESTIONS_COUNT);
  35. }
  36. /**
  37. * @param {string} ruleName
  38. * @param {string[]} [suggestions]
  39. * @returns {string}
  40. */
  41. function rejectMessage(ruleName, suggestions = []) {
  42. return `Unknown rule ${ruleName}.${
  43. suggestions.length > 0 ? ` Did you mean ${suggestions.join(', ')}?` : ''
  44. }`;
  45. }
  46. /** @type {Map<string, string[]>} */
  47. const cache = new Map();
  48. /**
  49. * @param {string} unknownRuleName
  50. * @param {import('postcss').Root} postcssRoot
  51. * @param {import('stylelint').PostcssResult} postcssResult
  52. * @returns {void}
  53. */
  54. function reportUnknownRuleNames(unknownRuleName, postcssRoot, postcssResult) {
  55. const suggestions = cache.has(unknownRuleName)
  56. ? /** @type {string[]} */ (cache.get(unknownRuleName))
  57. : extractSuggestions(unknownRuleName);
  58. cache.set(unknownRuleName, suggestions);
  59. postcssResult.warn(rejectMessage(unknownRuleName, suggestions), {
  60. severity: constants.SEVERITY_ERROR,
  61. rule: unknownRuleName,
  62. node: postcssRoot,
  63. index: 0,
  64. });
  65. }
  66. module.exports = reportUnknownRuleNames;