validateDisableSettings.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { isRegExp, isString } from './utils/validateTypes.mjs';
  2. import { DEFAULT_SEVERITY } from './constants.mjs';
  3. import validateOptions from './utils/validateOptions.mjs';
  4. /** @import {DisablePropertyName, DisableOptions, PostcssResult} from 'stylelint' */
  5. /**
  6. * Validates that the stylelint config for `result` has a valid disable field
  7. * named `field`, and returns the result in normalized form.
  8. *
  9. * Returns `[]` if no disables should be reported, and automatically reports
  10. * an invalid configuration.
  11. *
  12. * @param {PostcssResult} result
  13. * @param {DisablePropertyName} field
  14. * @returns {[boolean, Required<DisableOptions>] | []}
  15. */
  16. export default function validateDisableSettings(result, field) {
  17. const stylelintResult = result.stylelint;
  18. // Files with linting errors may not have configs associated with them.
  19. if (!stylelintResult.config) return [];
  20. const rawSettings = stylelintResult.config[field];
  21. /** @type {boolean} */
  22. let enabled;
  23. /** @type {DisableOptions} */
  24. let options;
  25. if (Array.isArray(rawSettings)) {
  26. enabled = rawSettings[0];
  27. options = rawSettings[1] || {};
  28. } else {
  29. enabled = rawSettings || false;
  30. options = {};
  31. }
  32. const validOptions = validateOptions(
  33. result,
  34. field,
  35. {
  36. actual: enabled,
  37. possible: [true, false],
  38. },
  39. {
  40. actual: options,
  41. possible: {
  42. except: [isString, isRegExp],
  43. },
  44. },
  45. );
  46. if (!validOptions) return [];
  47. // If the check is disabled with no exceptions, there's no reason to run
  48. // it at all.
  49. if (!enabled && !options.except) return [];
  50. return [
  51. enabled,
  52. {
  53. except: options.except || [],
  54. severity: options.severity || stylelintResult.config.defaultSeverity || DEFAULT_SEVERITY,
  55. },
  56. ];
  57. }