BasicMatcherRulePlugin.js 2.2 KB

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