RuleSetCompiler.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { SyncHook } = require("tapable");
  7. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
  8. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */
  9. /** @typedef {function(string | EffectData): boolean} RuleConditionFunction */
  10. /**
  11. * @typedef {object} RuleCondition
  12. * @property {string | string[]} property
  13. * @property {boolean} matchWhenEmpty
  14. * @property {RuleConditionFunction} fn
  15. */
  16. /**
  17. * @typedef {object} Condition
  18. * @property {boolean} matchWhenEmpty
  19. * @property {RuleConditionFunction} fn
  20. */
  21. /**
  22. * @typedef {Record<string, TODO>} EffectData
  23. */
  24. /**
  25. * @typedef {object} CompiledRule
  26. * @property {RuleCondition[]} conditions
  27. * @property {(Effect|function(EffectData): Effect[])[]} effects
  28. * @property {CompiledRule[]=} rules
  29. * @property {CompiledRule[]=} oneOf
  30. */
  31. /**
  32. * @typedef {object} Effect
  33. * @property {string} type
  34. * @property {any} value
  35. */
  36. /**
  37. * @typedef {object} RuleSet
  38. * @property {Map<string, any>} references map of references in the rule set (may grow over time)
  39. * @property {function(EffectData): Effect[]} exec execute the rule set
  40. */
  41. /** @typedef {{ apply: (function(RuleSetCompiler): void) }} RuleSetPlugin */
  42. class RuleSetCompiler {
  43. /**
  44. * @param {RuleSetPlugin[]} plugins plugins
  45. */
  46. constructor(plugins) {
  47. this.hooks = Object.freeze({
  48. /** @type {SyncHook<[string, RuleSetRule, Set<string>, CompiledRule, Map<string | undefined, any>]>} */
  49. rule: new SyncHook([
  50. "path",
  51. "rule",
  52. "unhandledProperties",
  53. "compiledRule",
  54. "references"
  55. ])
  56. });
  57. if (plugins) {
  58. for (const plugin of plugins) {
  59. plugin.apply(this);
  60. }
  61. }
  62. }
  63. /**
  64. * @param {TODO[]} ruleSet raw user provided rules
  65. * @returns {RuleSet} compiled RuleSet
  66. */
  67. compile(ruleSet) {
  68. const refs = new Map();
  69. const rules = this.compileRules("ruleSet", ruleSet, refs);
  70. /**
  71. * @param {EffectData} data data passed in
  72. * @param {CompiledRule} rule the compiled rule
  73. * @param {Effect[]} effects an array where effects are pushed to
  74. * @returns {boolean} true, if the rule has matched
  75. */
  76. const execRule = (data, rule, effects) => {
  77. for (const condition of rule.conditions) {
  78. const p = condition.property;
  79. if (Array.isArray(p)) {
  80. /** @type {EffectData | string | undefined} */
  81. let current = data;
  82. for (const subProperty of p) {
  83. if (
  84. current &&
  85. typeof current === "object" &&
  86. Object.prototype.hasOwnProperty.call(current, subProperty)
  87. ) {
  88. current = current[subProperty];
  89. } else {
  90. current = undefined;
  91. break;
  92. }
  93. }
  94. if (current !== undefined) {
  95. if (!condition.fn(current)) return false;
  96. continue;
  97. }
  98. } else if (p in data) {
  99. const value = data[p];
  100. if (value !== undefined) {
  101. if (!condition.fn(value)) return false;
  102. continue;
  103. }
  104. }
  105. if (!condition.matchWhenEmpty) {
  106. return false;
  107. }
  108. }
  109. for (const effect of rule.effects) {
  110. if (typeof effect === "function") {
  111. const returnedEffects = effect(data);
  112. for (const effect of returnedEffects) {
  113. effects.push(effect);
  114. }
  115. } else {
  116. effects.push(effect);
  117. }
  118. }
  119. if (rule.rules) {
  120. for (const childRule of rule.rules) {
  121. execRule(data, childRule, effects);
  122. }
  123. }
  124. if (rule.oneOf) {
  125. for (const childRule of rule.oneOf) {
  126. if (execRule(data, childRule, effects)) {
  127. break;
  128. }
  129. }
  130. }
  131. return true;
  132. };
  133. return {
  134. references: refs,
  135. exec: data => {
  136. /** @type {Effect[]} */
  137. const effects = [];
  138. for (const rule of rules) {
  139. execRule(data, rule, effects);
  140. }
  141. return effects;
  142. }
  143. };
  144. }
  145. /**
  146. * @param {string} path current path
  147. * @param {RuleSetRules} rules the raw rules provided by user
  148. * @param {Map<string, any>} refs references
  149. * @returns {CompiledRule[]} rules
  150. */
  151. compileRules(path, rules, refs) {
  152. return rules
  153. .filter(Boolean)
  154. .map((rule, i) =>
  155. this.compileRule(
  156. `${path}[${i}]`,
  157. /** @type {RuleSetRule} */ (rule),
  158. refs
  159. )
  160. );
  161. }
  162. /**
  163. * @param {string} path current path
  164. * @param {RuleSetRule} rule the raw rule provided by user
  165. * @param {Map<string, any>} refs references
  166. * @returns {CompiledRule} normalized and compiled rule for processing
  167. */
  168. compileRule(path, rule, refs) {
  169. const unhandledProperties = new Set(
  170. Object.keys(rule).filter(
  171. key => rule[/** @type {keyof RuleSetRule} */ (key)] !== undefined
  172. )
  173. );
  174. /** @type {CompiledRule} */
  175. const compiledRule = {
  176. conditions: [],
  177. effects: [],
  178. rules: undefined,
  179. oneOf: undefined
  180. };
  181. this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs);
  182. if (unhandledProperties.has("rules")) {
  183. unhandledProperties.delete("rules");
  184. const rules = rule.rules;
  185. if (!Array.isArray(rules))
  186. throw this.error(path, rules, "Rule.rules must be an array of rules");
  187. compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs);
  188. }
  189. if (unhandledProperties.has("oneOf")) {
  190. unhandledProperties.delete("oneOf");
  191. const oneOf = rule.oneOf;
  192. if (!Array.isArray(oneOf))
  193. throw this.error(path, oneOf, "Rule.oneOf must be an array of rules");
  194. compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs);
  195. }
  196. if (unhandledProperties.size > 0) {
  197. throw this.error(
  198. path,
  199. rule,
  200. `Properties ${Array.from(unhandledProperties).join(", ")} are unknown`
  201. );
  202. }
  203. return compiledRule;
  204. }
  205. /**
  206. * @param {string} path current path
  207. * @param {any} condition user provided condition value
  208. * @returns {Condition} compiled condition
  209. */
  210. compileCondition(path, condition) {
  211. if (condition === "") {
  212. return {
  213. matchWhenEmpty: true,
  214. fn: str => str === ""
  215. };
  216. }
  217. if (!condition) {
  218. throw this.error(
  219. path,
  220. condition,
  221. "Expected condition but got falsy value"
  222. );
  223. }
  224. if (typeof condition === "string") {
  225. return {
  226. matchWhenEmpty: condition.length === 0,
  227. fn: str => typeof str === "string" && str.startsWith(condition)
  228. };
  229. }
  230. if (typeof condition === "function") {
  231. try {
  232. return {
  233. matchWhenEmpty: condition(""),
  234. fn: condition
  235. };
  236. } catch (_err) {
  237. throw this.error(
  238. path,
  239. condition,
  240. "Evaluation of condition function threw error"
  241. );
  242. }
  243. }
  244. if (condition instanceof RegExp) {
  245. return {
  246. matchWhenEmpty: condition.test(""),
  247. fn: v => typeof v === "string" && condition.test(v)
  248. };
  249. }
  250. if (Array.isArray(condition)) {
  251. const items = condition.map((c, i) =>
  252. this.compileCondition(`${path}[${i}]`, c)
  253. );
  254. return this.combineConditionsOr(items);
  255. }
  256. if (typeof condition !== "object") {
  257. throw this.error(
  258. path,
  259. condition,
  260. `Unexpected ${typeof condition} when condition was expected`
  261. );
  262. }
  263. const conditions = [];
  264. for (const key of Object.keys(condition)) {
  265. const value = condition[key];
  266. switch (key) {
  267. case "or":
  268. if (value) {
  269. if (!Array.isArray(value)) {
  270. throw this.error(
  271. `${path}.or`,
  272. condition.or,
  273. "Expected array of conditions"
  274. );
  275. }
  276. conditions.push(this.compileCondition(`${path}.or`, value));
  277. }
  278. break;
  279. case "and":
  280. if (value) {
  281. if (!Array.isArray(value)) {
  282. throw this.error(
  283. `${path}.and`,
  284. condition.and,
  285. "Expected array of conditions"
  286. );
  287. }
  288. let i = 0;
  289. for (const item of value) {
  290. conditions.push(this.compileCondition(`${path}.and[${i}]`, item));
  291. i++;
  292. }
  293. }
  294. break;
  295. case "not":
  296. if (value) {
  297. const matcher = this.compileCondition(`${path}.not`, value);
  298. const fn = matcher.fn;
  299. conditions.push({
  300. matchWhenEmpty: !matcher.matchWhenEmpty,
  301. fn: /** @type {RuleConditionFunction} */ (v => !fn(v))
  302. });
  303. }
  304. break;
  305. default:
  306. throw this.error(
  307. `${path}.${key}`,
  308. condition[key],
  309. `Unexpected property ${key} in condition`
  310. );
  311. }
  312. }
  313. if (conditions.length === 0) {
  314. throw this.error(
  315. path,
  316. condition,
  317. "Expected condition, but got empty thing"
  318. );
  319. }
  320. return this.combineConditionsAnd(conditions);
  321. }
  322. /**
  323. * @param {Condition[]} conditions some conditions
  324. * @returns {Condition} merged condition
  325. */
  326. combineConditionsOr(conditions) {
  327. if (conditions.length === 0) {
  328. return {
  329. matchWhenEmpty: false,
  330. fn: () => false
  331. };
  332. } else if (conditions.length === 1) {
  333. return conditions[0];
  334. }
  335. return {
  336. matchWhenEmpty: conditions.some(c => c.matchWhenEmpty),
  337. fn: v => conditions.some(c => c.fn(v))
  338. };
  339. }
  340. /**
  341. * @param {Condition[]} conditions some conditions
  342. * @returns {Condition} merged condition
  343. */
  344. combineConditionsAnd(conditions) {
  345. if (conditions.length === 0) {
  346. return {
  347. matchWhenEmpty: false,
  348. fn: () => false
  349. };
  350. } else if (conditions.length === 1) {
  351. return conditions[0];
  352. }
  353. return {
  354. matchWhenEmpty: conditions.every(c => c.matchWhenEmpty),
  355. fn: v => conditions.every(c => c.fn(v))
  356. };
  357. }
  358. /**
  359. * @param {string} path current path
  360. * @param {any} value value at the error location
  361. * @param {string} message message explaining the problem
  362. * @returns {Error} an error object
  363. */
  364. error(path, value, message) {
  365. return new Error(
  366. `Compiling RuleSet failed: ${message} (at ${path}: ${value})`
  367. );
  368. }
  369. }
  370. module.exports = RuleSetCompiler;