BasicMatcherRulePlugin.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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").RuleSetConditionOrConditionsAbsolute} RuleSetConditionOrConditionsAbsolute */
  8. /** @typedef {import("../../declarations/WebpackOptions").RuleSetLoaderOptions} RuleSetLoaderOptions */
  9. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
  10. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  11. /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */
  12. /**
  13. * @template T
  14. * @template {T[keyof T]} V
  15. * @typedef {import("./RuleSetCompiler").KeysOfTypes<T, V>} KeysOfTypes
  16. */
  17. /** @typedef {KeysOfTypes<RuleSetRule, RuleSetConditionOrConditions | RuleSetConditionOrConditionsAbsolute>} BasicMatcherRuleKeys */
  18. const PLUGIN_NAME = "BasicMatcherRulePlugin";
  19. class BasicMatcherRulePlugin {
  20. /**
  21. * @param {BasicMatcherRuleKeys} ruleProperty the rule property
  22. * @param {string=} dataProperty the data property
  23. * @param {boolean=} invert if true, inverts the condition
  24. */
  25. constructor(ruleProperty, dataProperty, invert) {
  26. this.ruleProperty = ruleProperty;
  27. this.dataProperty = dataProperty || ruleProperty;
  28. this.invert = invert || false;
  29. }
  30. /**
  31. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  32. * @returns {void}
  33. */
  34. apply(ruleSetCompiler) {
  35. ruleSetCompiler.hooks.rule.tap(
  36. PLUGIN_NAME,
  37. (path, rule, unhandledProperties, result) => {
  38. if (unhandledProperties.has(this.ruleProperty)) {
  39. unhandledProperties.delete(this.ruleProperty);
  40. const value = rule[this.ruleProperty];
  41. const condition = ruleSetCompiler.compileCondition(
  42. `${path}.${this.ruleProperty}`,
  43. /** @type {RuleSetConditionOrConditions | RuleSetConditionOrConditionsAbsolute} */
  44. (value)
  45. );
  46. const fn = condition.fn;
  47. result.conditions.push({
  48. property: this.dataProperty,
  49. matchWhenEmpty: this.invert
  50. ? !condition.matchWhenEmpty
  51. : condition.matchWhenEmpty,
  52. fn: this.invert ? v => !fn(v) : fn
  53. });
  54. }
  55. }
  56. );
  57. }
  58. }
  59. module.exports = BasicMatcherRulePlugin;