aboutsummaryrefslogtreecommitdiffstats
path: root/config/webpack/plugins/create-rules-webpack-plugin.js
blob: e2a25684cbf6909d7d6d3d4554430ed364aa79b8 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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`.
 *
 * If `src/rules/` is missing or contains no JSON rule files, no asset is
 * emitted and a build warning is raised.  `CreateManifestPlugin` relies on
 * that: it drops the `declarative_net_request` manifest key when
 * `rules.json` is absent, so the extension never ships a dangling ruleset
 * reference.
 */
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 rulesDirectoryPath = path.resolve(SOURCE_DIR, "rules");
					const ruleFileNames = fs.existsSync(rulesDirectoryPath)
						? fs.readdirSync(rulesDirectoryPath).filter((ruleFileName) => ruleFileName.endsWith(".json"))
						: [];
					const rules = [];
					let ruleId = 1;

					if (ruleFileNames.length === 0) {
						compilation.warnings.push(
							new Error(
								`No *.json rule files found in ${rulesDirectoryPath}; skipping the rules.json asset and the declarative_net_request manifest key.`
							)
						);

						return;
					}

					for (const ruleFileName of ruleFileNames) {
						const rule = JSON.parse(fs.readFileSync(path.resolve(rulesDirectoryPath, 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;