flat-config-helpers.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * @fileoverview Shared functions to work with configs.
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //-----------------------------------------------------------------------------
  7. // Functions
  8. //-----------------------------------------------------------------------------
  9. /**
  10. * Parses a ruleId into its plugin and rule parts.
  11. * @param {string} ruleId The rule ID to parse.
  12. * @returns {{pluginName:string,ruleName:string}} The plugin and rule
  13. * parts of the ruleId;
  14. */
  15. function parseRuleId(ruleId) {
  16. let pluginName, ruleName;
  17. // distinguish between core rules and plugin rules
  18. if (ruleId.includes("/")) {
  19. pluginName = ruleId.slice(0, ruleId.lastIndexOf("/"));
  20. ruleName = ruleId.slice(pluginName.length + 1);
  21. } else {
  22. pluginName = "@";
  23. ruleName = ruleId;
  24. }
  25. return {
  26. pluginName,
  27. ruleName
  28. };
  29. }
  30. /**
  31. * Retrieves a rule instance from a given config based on the ruleId.
  32. * @param {string} ruleId The rule ID to look for.
  33. * @param {FlatConfig} config The config to search.
  34. * @returns {import("../shared/types").Rule|undefined} The rule if found
  35. * or undefined if not.
  36. */
  37. function getRuleFromConfig(ruleId, config) {
  38. const { pluginName, ruleName } = parseRuleId(ruleId);
  39. const plugin = config.plugins && config.plugins[pluginName];
  40. let rule = plugin && plugin.rules && plugin.rules[ruleName];
  41. // normalize function rules into objects
  42. if (rule && typeof rule === "function") {
  43. rule = {
  44. create: rule
  45. };
  46. }
  47. return rule;
  48. }
  49. /**
  50. * Gets a complete options schema for a rule.
  51. * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
  52. * @returns {Object} JSON Schema for the rule's options.
  53. */
  54. function getRuleOptionsSchema(rule) {
  55. if (!rule) {
  56. return null;
  57. }
  58. const schema = rule.schema || rule.meta && rule.meta.schema;
  59. if (Array.isArray(schema)) {
  60. if (schema.length) {
  61. return {
  62. type: "array",
  63. items: schema,
  64. minItems: 0,
  65. maxItems: schema.length
  66. };
  67. }
  68. return {
  69. type: "array",
  70. minItems: 0,
  71. maxItems: 0
  72. };
  73. }
  74. // Given a full schema, leave it alone
  75. return schema || null;
  76. }
  77. //-----------------------------------------------------------------------------
  78. // Exports
  79. //-----------------------------------------------------------------------------
  80. module.exports = {
  81. parseRuleId,
  82. getRuleFromConfig,
  83. getRuleOptionsSchema
  84. };