aboutsummaryrefslogtreecommitdiffstats
path: root/config/webpack/plugins/create-rules-webpack-plugin.js
blob: ce2fbef443bb591ed8ddfd4af03b478ec2801afe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import fs from "fs";
import path from "path";

import webpack from "webpack";

/**
 * Webpack plugin that reads all JSON rule files from `src/rules/`,
 * assigns sequential IDs to each rule, and emits a single `rules.json`
 * asset used by `declarativeNetRequest`.
 */
class CreateRulesPlugin {
	/**
	 * @param {import("webpack").Compiler} compiler
	 * @returns {void}
	 */
	apply(compiler) {
		compiler.hooks.compilation.tap("CreateRulesPlugin", (compilation) => {
			compilation.hooks.processAssets.tap(
				{
					name: "CreateRulesPlugin",
					stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
				},
				(_assets) => {
					const ruleFileNames = fs.readdirSync(path.resolve(SOURCE_DIR, "rules"));
					const rules = [];
					let ruleId = 1;

					for (const ruleFileName of ruleFileNames) {
						const rule = JSON.parse(fs.readFileSync(path.resolve("src/rules", ruleFileName)));

						if (rule instanceof Array) {
							for (const currentRule of rule) {
								currentRule.id = ruleId++;
								rules.push(currentRule);
							}
						} else {
							rule.id = ruleId++;
							rules.push(rule);
						}
					}

					compilation.emitAsset(
						"rules.json",
						new webpack.sources.RawSource(
							JSON.stringify(
								rules,
								undefined,
								process.env.NODE_ENV === "production"
									? undefined
									: "\t"
							)
						)
					);
				}
			);
		});
	}
}

export default CreateRulesPlugin;