ObjectMatcherRulePlugin.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("../../declarations/WebpackOptions").RuleSetConditionOrConditions} RuleSetConditionOrConditions */
  7. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
  8. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  9. /** @typedef {import("./RuleSetCompiler").EffectData} EffectData */
  10. /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */
  11. /** @typedef {import("./RuleSetCompiler").RuleConditionFunction} RuleConditionFunction */
  12. /**
  13. * @template T
  14. * @template {T[keyof T]} V
  15. * @typedef {import("./RuleSetCompiler").KeysOfTypes<T, V>} KeysOfTypes
  16. */
  17. /** @typedef {KeysOfTypes<RuleSetRule, { [k: string]: RuleSetConditionOrConditions }>} ObjectMatcherRuleKeys */
  18. const PLUGIN_NAME = "ObjectMatcherRulePlugin";
  19. class ObjectMatcherRulePlugin {
  20. /**
  21. * @param {ObjectMatcherRuleKeys} ruleProperty the rule property
  22. * @param {keyof EffectData=} dataProperty the data property
  23. * @param {RuleConditionFunction=} additionalConditionFunction need to check
  24. */
  25. constructor(ruleProperty, dataProperty, additionalConditionFunction) {
  26. this.ruleProperty = ruleProperty;
  27. this.dataProperty = dataProperty || ruleProperty;
  28. this.additionalConditionFunction = additionalConditionFunction;
  29. }
  30. /**
  31. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  32. * @returns {void}
  33. */
  34. apply(ruleSetCompiler) {
  35. const { ruleProperty, dataProperty } = this;
  36. ruleSetCompiler.hooks.rule.tap(
  37. PLUGIN_NAME,
  38. (path, rule, unhandledProperties, result) => {
  39. if (unhandledProperties.has(ruleProperty)) {
  40. unhandledProperties.delete(ruleProperty);
  41. const value =
  42. /** @type {Record<string, RuleSetConditionOrConditions>} */
  43. (rule[ruleProperty]);
  44. for (const property of Object.keys(value)) {
  45. const nestedDataProperties = property.split(".");
  46. const condition = ruleSetCompiler.compileCondition(
  47. `${path}.${ruleProperty}.${property}`,
  48. value[property]
  49. );
  50. if (this.additionalConditionFunction) {
  51. result.conditions.push({
  52. property: [dataProperty],
  53. matchWhenEmpty: condition.matchWhenEmpty,
  54. fn: this.additionalConditionFunction
  55. });
  56. }
  57. result.conditions.push({
  58. property: [dataProperty, ...nestedDataProperties],
  59. matchWhenEmpty: condition.matchWhenEmpty,
  60. fn: condition.fn
  61. });
  62. }
  63. }
  64. }
  65. );
  66. }
  67. }
  68. module.exports = ObjectMatcherRulePlugin;