2 * @fileoverview Defines a storage for rules.
3 * @author Nicholas C. Zakas
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
13 const builtInRules = require("../rules");
15 //------------------------------------------------------------------------------
17 //------------------------------------------------------------------------------
20 * Normalizes a rule module to the new-style API
21 * @param {(Function|{create: Function})} rule A rule object, which can either be a function
22 * ("old-style") or an object with a `create` method ("new-style")
23 * @returns {{create: Function}} A new-style rule.
25 function normalizeRule(rule) {
26 return typeof rule === "function" ? Object.assign({ create: rule }, rule) : rule;
29 //------------------------------------------------------------------------------
31 //------------------------------------------------------------------------------
35 this._rules = Object.create(null);
39 * Registers a rule module for rule id in storage.
40 * @param {string} ruleId Rule id (file name).
41 * @param {Function} ruleModule Rule handler.
44 define(ruleId, ruleModule) {
45 this._rules[ruleId] = normalizeRule(ruleModule);
49 * Access rule handler by id (file name).
50 * @param {string} ruleId Rule id (file name).
51 * @returns {{create: Function, schema: JsonSchema[]}}
52 * A rule. This is normalized to always have the new-style shape with a `create` method.
55 if (typeof this._rules[ruleId] === "string") {
56 this.define(ruleId, require(this._rules[ruleId]));
58 if (this._rules[ruleId]) {
59 return this._rules[ruleId];
61 if (builtInRules.has(ruleId)) {
62 return builtInRules.get(ruleId);
68 *[Symbol.iterator]() {
71 for (const ruleId of Object.keys(this._rules)) {
72 yield [ruleId, this.get(ruleId)];
77 module.exports = Rules;