validateOptions.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. 'use strict';
  2. const arrayEqual = require('./arrayEqual');
  3. const { isPlainObject } = require('./validateTypes');
  4. const IGNORED_OPTIONS = new Set(['severity', 'message', 'reportDisables', 'disableFix']);
  5. /** @typedef {import('stylelint').RuleOptions} RuleOptions */
  6. /** @typedef {import('stylelint').RuleOptionsPossible} Possible */
  7. /** @typedef {import('stylelint').RuleOptionsPossibleFunc} PossibleFunc */
  8. /**
  9. * Validate a rule's options.
  10. *
  11. * See existing rules for examples.
  12. *
  13. * @param {import('stylelint').PostcssResult} result - postcss result
  14. * @param {string} ruleName
  15. * @param {...RuleOptions} optionDescriptions - Each optionDescription can
  16. * have the following properties:
  17. * - `actual` (required): the actual passed option value or object.
  18. * - `possible` (required): a schema representation of what values are
  19. * valid for those options. `possible` should be an object if the
  20. * options are an object, with corresponding keys; if the options are not an
  21. * object, `possible` isn't, either. All `possible` value representations
  22. * should be **arrays of either values or functions**. Values are === checked
  23. * against `actual`. Functions are fed `actual` as an argument and their
  24. * return value is interpreted: truthy = valid, falsy = invalid.
  25. * - `optional` (optional): If this is `true`, `actual` can be undefined.
  26. * @return {boolean} Whether or not the options are valid (true = valid)
  27. */
  28. function validateOptions(result, ruleName, ...optionDescriptions) {
  29. let noErrors = true;
  30. for (const optionDescription of optionDescriptions) {
  31. validate(optionDescription, ruleName, complain);
  32. }
  33. /**
  34. * @param {string} message
  35. */
  36. function complain(message) {
  37. noErrors = false;
  38. result.warn(message, {
  39. stylelintType: 'invalidOption',
  40. });
  41. result.stylelint = result.stylelint || {
  42. disabledRanges: {},
  43. ruleSeverities: {},
  44. customMessages: {},
  45. ruleMetadata: {},
  46. };
  47. result.stylelint.stylelintError = true;
  48. }
  49. return noErrors;
  50. }
  51. /**
  52. * @param {RuleOptions} opts
  53. * @param {string} ruleName
  54. * @param {(message: string) => void} complain
  55. */
  56. function validate(opts, ruleName, complain) {
  57. const possible = opts.possible;
  58. const actual = opts.actual;
  59. const optional = opts.optional;
  60. if (actual === null || arrayEqual(actual, [null])) {
  61. return;
  62. }
  63. const nothingPossible =
  64. possible === undefined || (Array.isArray(possible) && possible.length === 0);
  65. if (nothingPossible && actual === true) {
  66. return;
  67. }
  68. if (actual === undefined) {
  69. if (nothingPossible || optional) {
  70. return;
  71. }
  72. complain(`Expected option value for rule "${ruleName}"`);
  73. return;
  74. }
  75. if (nothingPossible) {
  76. if (optional) {
  77. complain(
  78. `Incorrect configuration for rule "${ruleName}". Rule should have "possible" values for options validation`,
  79. );
  80. return;
  81. }
  82. complain(`Unexpected option value ${stringify(actual)} for rule "${ruleName}"`);
  83. return;
  84. }
  85. if (typeof possible === 'function') {
  86. if (!possible(actual)) {
  87. complain(`Invalid option ${stringify(actual)} for rule "${ruleName}"`);
  88. }
  89. return;
  90. }
  91. // If `possible` is an array instead of an object ...
  92. if (Array.isArray(possible)) {
  93. for (const a of [actual].flat()) {
  94. if (isValid(possible, a)) {
  95. continue;
  96. }
  97. complain(`Invalid option value ${stringify(a)} for rule "${ruleName}"`);
  98. }
  99. return;
  100. }
  101. // If actual is NOT an object ...
  102. if (!isPlainObject(actual) || typeof actual !== 'object' || actual == null) {
  103. complain(
  104. `Invalid option value ${stringify(actual)} for rule "${ruleName}": should be an object`,
  105. );
  106. return;
  107. }
  108. for (const [optionName, optionValue] of Object.entries(actual)) {
  109. if (IGNORED_OPTIONS.has(optionName)) {
  110. continue;
  111. }
  112. const possibleValue = possible && possible[optionName];
  113. if (!possibleValue) {
  114. complain(`Invalid option name "${optionName}" for rule "${ruleName}"`);
  115. continue;
  116. }
  117. for (const a of [optionValue].flat()) {
  118. if (isValid(possibleValue, a)) {
  119. continue;
  120. }
  121. complain(`Invalid value ${stringify(a)} for option "${optionName}" of rule "${ruleName}"`);
  122. }
  123. }
  124. }
  125. /**
  126. * @param {Possible | Possible[]} possible
  127. * @param {unknown} actual
  128. * @returns {boolean}
  129. */
  130. function isValid(possible, actual) {
  131. for (const possibility of [possible].flat()) {
  132. if (typeof possibility === 'function' && possibility(actual)) {
  133. return true;
  134. }
  135. if (actual === possibility) {
  136. return true;
  137. }
  138. }
  139. return false;
  140. }
  141. /**
  142. * @param {unknown} value
  143. * @returns {string}
  144. */
  145. function stringify(value) {
  146. if (typeof value === 'string') {
  147. return `"${value}"`;
  148. }
  149. return `"${JSON.stringify(value)}"`;
  150. }
  151. module.exports = /** @type {typeof import('stylelint').utils.validateOptions} */ (validateOptions);