RuleSetCompiler.js 11 KB

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