webpack/lib/rules/ObjectMatcherRulePlugin.js

76 lines
2.4 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
2025-03-27 08:07:25 +08:00
/** @typedef {import("../../declarations/WebpackOptions").RuleSetConditionOrConditions} RuleSetConditionOrConditions */
2024-08-06 11:08:48 +08:00
/** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
2025-05-01 22:36:51 +08:00
/** @typedef {import("./RuleSetCompiler").EffectData} EffectData */
2024-06-11 01:40:50 +08:00
/** @typedef {import("./RuleSetCompiler").RuleConditionFunction} RuleConditionFunction */
2025-03-27 08:07:25 +08:00
/**
* @template T
* @template {T[keyof T]} V
* @typedef {import("./RuleSetCompiler").KeysOfTypes<T, V>} KeysOfTypes
*/
/** @typedef {KeysOfTypes<RuleSetRule, { [k: string]: RuleSetConditionOrConditions }>} ObjectMatcherRuleKeys */
2025-06-04 02:20:37 +08:00
const PLUGIN_NAME = "ObjectMatcherRulePlugin";
class ObjectMatcherRulePlugin {
2024-03-11 22:56:35 +08:00
/**
2025-03-27 08:07:25 +08:00
* @param {ObjectMatcherRuleKeys} ruleProperty the rule property
2025-05-01 22:36:51 +08:00
* @param {keyof EffectData=} dataProperty the data property
2024-06-11 01:40:50 +08:00
* @param {RuleConditionFunction=} additionalConditionFunction need to check
2024-03-11 22:56:35 +08:00
*/
2024-06-11 01:40:50 +08:00
constructor(ruleProperty, dataProperty, additionalConditionFunction) {
this.ruleProperty = ruleProperty;
this.dataProperty = dataProperty || ruleProperty;
2024-06-11 01:40:50 +08:00
this.additionalConditionFunction = additionalConditionFunction;
}
/**
* @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
* @returns {void}
*/
apply(ruleSetCompiler) {
const { ruleProperty, dataProperty } = this;
ruleSetCompiler.hooks.rule.tap(
2025-06-04 02:20:37 +08:00
PLUGIN_NAME,
(path, rule, unhandledProperties, result) => {
if (unhandledProperties.has(ruleProperty)) {
unhandledProperties.delete(ruleProperty);
2024-08-06 11:08:48 +08:00
const value =
2025-03-27 08:07:25 +08:00
/** @type {Record<string, RuleSetConditionOrConditions>} */
(rule[ruleProperty]);
for (const property of Object.keys(value)) {
const nestedDataProperties = property.split(".");
const condition = ruleSetCompiler.compileCondition(
`${path}.${ruleProperty}.${property}`,
value[property]
);
2024-06-11 01:40:50 +08:00
if (this.additionalConditionFunction) {
result.conditions.push({
property: [dataProperty],
matchWhenEmpty: condition.matchWhenEmpty,
fn: this.additionalConditionFunction
});
}
result.conditions.push({
property: [dataProperty, ...nestedDataProperties],
matchWhenEmpty: condition.matchWhenEmpty,
fn: condition.fn
});
}
}
}
);
}
}
module.exports = ObjectMatcherRulePlugin;