@afterpack/webpack 0.1.0-rc.20260925T1347

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 AfterPack
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ AfterPack CLI and framework integrations
2
+ Copyright 2026 AfterPack — https://www.afterpack.dev
3
+
4
+ This product includes software developed at AfterPack (https://www.afterpack.dev).
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # @afterpack/webpack
2
+
3
+ A webpack obfuscation plugin for webpack 5. It obfuscates your production JavaScript inside the
4
+ webpack build, using the [AfterPack](https://www.afterpack.dev) JavaScript obfuscator.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ npm install --save-dev @afterpack/webpack
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```js
15
+ // webpack.config.mjs
16
+ import { AfterpackWebpackPlugin } from "@afterpack/webpack";
17
+
18
+ export default {
19
+ // ...
20
+ plugins: [new AfterpackWebpackPlugin()],
21
+ };
22
+ ```
23
+
24
+ The plugin obfuscates each JavaScript asset your chunks produce at the last step before webpack
25
+ writes to disk, so the readable bundle is never written. Hot-update chunks and assets other plugins
26
+ copy in are left alone. If obfuscation fails, the build fails.
27
+
28
+ Subresource integrity plugins keep working: they hash the obfuscated files.
29
+
30
+ Each build writes a protection receipt, `.afterpack-protection.json`, into the output directory.
31
+ Run `npx afterpack verify dist` in your deploy step to check that what you ship is what was
32
+ obfuscated.
33
+
34
+ ## Options
35
+
36
+ ```js
37
+ new AfterpackWebpackPlugin({ preset: "hard", seed: "git" });
38
+ ```
39
+
40
+ | Option | What it does | Default |
41
+ | --- | --- | --- |
42
+ | [`preset`][preset] | `"minify"`, `"light"`, `"medium"`, `"hard"` or `"extreme"` | `"light"` |
43
+ | [`seed`][seed] | a number or string; `"git"` uses the current commit | a new random seed per build |
44
+ | [`identifiers.reserved`][identifiers.reserved] | names never to rename | none |
45
+ | [`paths.exclude`][paths.exclude] | globs for files to leave untouched | none |
46
+ | [`sourceMap.enabled`][sourceMap.enabled] | write source maps for the obfuscated output | on in development when webpack emits a map, off in production |
47
+ | [`protectionMap.enabled`][protectionMap.enabled] | write the Protection Map | on when `devtool` emits source maps |
48
+ | [`build.autorun`][build.autorun] | `false` turns AfterPack off | `true` |
49
+
50
+ Dotted names are nested objects: `sourceMap.enabled` is `{ sourceMap: { enabled: true } }`. Every
51
+ other option is in the [configuration reference](https://www.afterpack.dev/docs/config).
52
+
53
+ [preset]: https://www.afterpack.dev/docs/config#preset
54
+ [seed]: https://www.afterpack.dev/docs/config#seed
55
+ [identifiers.reserved]: https://www.afterpack.dev/docs/config#identifiers-reserved
56
+ [paths.exclude]: https://www.afterpack.dev/docs/config#paths-exclude
57
+ [sourceMap.enabled]: https://www.afterpack.dev/docs/config#sourceMap-enabled
58
+ [protectionMap.enabled]: https://www.afterpack.dev/docs/config#protectionMap-enabled
59
+ [build.autorun]: https://www.afterpack.dev/docs/config#build-autorun
60
+
61
+ `/* @afterpack */` [directives](https://www.afterpack.dev/docs/directives) in your source need a
62
+ `devtool` that emits source maps, such as `"source-map"`. Without one, the plugin skips them and
63
+ tells you.
64
+
65
+ The [Protection Map](https://www.afterpack.dev/docs/protection-map) is written to `.afterpack/`,
66
+ outside webpack's output, and the plugin adds its local artifacts to your `.gitignore`. It contains
67
+ your original source, so never deploy or commit it.
68
+
69
+ Options can also live in `afterpack.json` or in `AFTERPACK_*` environment variables. The options
70
+ object wins over the environment, which wins over the file. An unknown or misspelled key fails the
71
+ build and names the right spelling.
72
+
73
+ ## Pro
74
+
75
+ Without a key, AfterPack runs on your machine and applies basic protection. Set
76
+ [`AFTERPACK_KEY`](https://www.afterpack.dev/docs/config#key) in your environment and the same plugin
77
+ sends the build to AfterPack's cloud, which applies much stronger protection. Keep the key out of
78
+ your webpack config: the plugin rejects it there. See [AfterPack
79
+ Pro](https://www.afterpack.dev/docs/pro).
80
+
81
+ ## Not supported here
82
+
83
+ - [`build.backup`](https://www.afterpack.dev/docs/config#build-backup): the output goes back to
84
+ webpack in memory, so there is no file to back up.
85
+ - [`paths.include`](https://www.afterpack.dev/docs/config#paths-include): the plugin works on
86
+ webpack's assets and does not walk the output directory.
87
+
88
+ ## Links
89
+
90
+ - [webpack setup guide](https://www.afterpack.dev/docs/frameworks/webpack)
91
+ - [Presets and protection levels](https://www.afterpack.dev/docs/presets)
92
+ - [A javascript-obfuscator alternative: how AfterPack compares](https://www.afterpack.dev/docs/comparison)
93
+ - [Protecting pricing logic](https://www.afterpack.dev/docs/use-cases/pricing-logic)
94
+
95
+ ## License
96
+
97
+ Apache-2.0. The engine it runs, `@afterpack/core`, has its own
98
+ [license](https://www.afterpack.dev/license).
99
+
100
+ ## Feedback
101
+
102
+ Questions, suggestions and bug reports: [afterpack.dev/contact](https://www.afterpack.dev/contact).
103
+ You can also file a bug on [GitHub Issues](https://github.com/afterpack-dev/afterpack/issues).
package/dist/index.cjs ADDED
@@ -0,0 +1,254 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ const node_fs = __toESM(require("node:fs"));
25
+ const node_path = __toESM(require("node:path"));
26
+ const __afterpack_core = __toESM(require("@afterpack/core"));
27
+ const __afterpack_integration_utils = __toESM(require("@afterpack/integration-utils"));
28
+
29
+ //#region src/index.ts
30
+ const PLUGIN_NAME = "AfterpackWebpackPlugin";
31
+ const EMITTED_JS_RE = /\.(?:js|mjs|cjs)$/;
32
+ const SOURCE_MODULE_RE = /\.(?:m?[jt]sx?)$/;
33
+ const PATHS_INCLUDE_UNSUPPORTED = "this plugin obfuscates the assets webpack's own chunks claim, in the pipeline — there is no output-directory walk for a glob to re-admit anything into. Use `npx afterpack <dir> --paths.include=...` for a disk walk, or drop the key.";
34
+ function isEmittedJs(name) {
35
+ return !name.includes(".hot-update.") && EMITTED_JS_RE.test(name);
36
+ }
37
+ function assetText(compilation, name) {
38
+ const asset = compilation.getAsset(name);
39
+ if (!asset) return null;
40
+ const value = asset.source.source();
41
+ return typeof value === "string" ? value : value.toString("utf8");
42
+ }
43
+ function inputSourceMap(compilation, asset) {
44
+ if (asset.mapName) return assetText(compilation, asset.mapName);
45
+ if (asset.url == null) return null;
46
+ if (asset.url.startsWith("data:")) return (0, __afterpack_integration_utils.decodeDataUri)(asset.url);
47
+ if (/^https?:\/\//i.test(asset.url) || asset.url.startsWith("//")) return null;
48
+ const dir = asset.name.includes("/") ? `${asset.name.replace(/\/[^/]*$/, "")}/` : "";
49
+ return assetText(compilation, `${dir}${asset.url}`.replace(/^\.\//, ""));
50
+ }
51
+ function chunkClaimedJsAssets(compilation) {
52
+ const names = new Set();
53
+ for (const chunk of compilation.chunks) for (const name of chunk.files) if (isEmittedJs(name)) names.add(name);
54
+ const out = [];
55
+ for (const name of names) {
56
+ const asset = compilation.getAsset(name);
57
+ if (!asset) continue;
58
+ const related = asset.info.related;
59
+ const sourceMap = related?.sourceMap;
60
+ const mapName = typeof sourceMap === "string" ? sourceMap : sourceMap?.[0] ?? null;
61
+ const text = assetText(compilation, name);
62
+ out.push({
63
+ name,
64
+ mapName,
65
+ url: text ? (0, __afterpack_integration_utils.extractSourceMappingURL)(text) : null
66
+ });
67
+ }
68
+ return out;
69
+ }
70
+ function collectResourcesThroughConcatenatedModules(module$1, out) {
71
+ if (module$1 == null || typeof module$1 !== "object") return;
72
+ const inner = module$1.modules;
73
+ if (Array.isArray(inner)) {
74
+ for (const m of inner) collectResourcesThroughConcatenatedModules(m, out);
75
+ return;
76
+ }
77
+ const resource = module$1.resource;
78
+ if (typeof resource === "string") out.push(resource.replace(/[?#].*$/, ""));
79
+ }
80
+ var AfterpackWebpackPlugin = class {
81
+ settings;
82
+ engineConfig;
83
+ captured = new Map();
84
+ seenByBuildHooksThisCompilation = new Set();
85
+ captureDiagnostics = [];
86
+ deferredReceiptByCompilation = new WeakMap();
87
+ constructor(options = {}) {
88
+ const resolved = (0, __afterpack_integration_utils.resolvePluginConfig)({
89
+ label: PLUGIN_NAME,
90
+ options,
91
+ unsupported: { "paths.include": PATHS_INCLUDE_UNSUPPORTED }
92
+ });
93
+ this.settings = resolved.options;
94
+ this.engineConfig = resolved.engineConfig;
95
+ }
96
+ apply(compiler) {
97
+ const context = compiler.options.context ?? process.cwd();
98
+ const directivesEnabled = this.settings.directives.enabled;
99
+ if (directivesEnabled) compiler.hooks.thisCompilation.tap(PLUGIN_NAME, () => {
100
+ this.seenByBuildHooksThisCompilation.clear();
101
+ });
102
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
103
+ if (directivesEnabled) {
104
+ const hooks = compiler.webpack.NormalModule.getCompilationHooks(compilation);
105
+ hooks.beforeLoaders.tap(PLUGIN_NAME, (_loaders, module$1) => {
106
+ this.capture(module$1.resource, context);
107
+ });
108
+ }
109
+ compilation.hooks.processAssets.tapPromise({
110
+ name: PLUGIN_NAME,
111
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT
112
+ }, () => this.obfuscate(compiler, compilation, context));
113
+ });
114
+ compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (compilation) => {
115
+ const deferred = this.deferredReceiptByCompilation.get(compilation);
116
+ if (!deferred) return;
117
+ this.deferredReceiptByCompilation.delete(compilation);
118
+ try {
119
+ const receiptPath = (0, __afterpack_integration_utils.writeDeferredProtectionReceipt)(deferred);
120
+ if (receiptPath && this.settings.diagnostics?.level !== "none") console.log(`[afterpack-webpack] wrote protection receipt -> ${receiptPath} (afterpack verify)`);
121
+ } catch (error) {
122
+ console.warn(`[afterpack-webpack] failed to write protection receipt: ${error instanceof Error ? error.message : String(error)}`);
123
+ }
124
+ });
125
+ }
126
+ async obfuscate(compiler, compilation, context) {
127
+ if (this.settings.build?.autorun === false) return;
128
+ const startedAt = Date.now();
129
+ const outputPath = compiler.outputPath;
130
+ const owned = chunkClaimedJsAssets(compilation);
131
+ if (owned.length === 0) return;
132
+ const byPath = new Map();
133
+ const inputs = new Map();
134
+ for (const asset of owned) {
135
+ const source = assetText(compilation, asset.name);
136
+ if (source == null) continue;
137
+ const filePath = (0, node_path.join)(outputPath, asset.name);
138
+ byPath.set(filePath, asset);
139
+ inputs.set(filePath, {
140
+ source,
141
+ sourceMap: inputSourceMap(compilation, asset)
142
+ });
143
+ }
144
+ const files = [...byPath.keys()];
145
+ if (files.length === 0) return;
146
+ const directivesEnabled = this.settings.directives.enabled;
147
+ const capturedByFile = directivesEnabled ? this.joinCaptured(compilation, outputPath, new Set(files), context) : new Map();
148
+ for (const message of this.captureDiagnostics) console.warn(`[afterpack-webpack] directive ${message}`);
149
+ this.captureDiagnostics.length = 0;
150
+ const devtool = compiler.options.devtool;
151
+ const result = await (0, __afterpack_integration_utils.runObfuscationPass)({
152
+ files,
153
+ inputs,
154
+ emitToCaller: true,
155
+ engine: {
156
+ processBatch: __afterpack_core.processBatch,
157
+ version: __afterpack_core.version
158
+ },
159
+ client: (0, __afterpack_integration_utils.resolveClientIdentity)(require("url").pathToFileURL(__filename).href),
160
+ telemetry: (0, __afterpack_integration_utils.createTelemetryReporter)(),
161
+ label: "afterpack-webpack",
162
+ gitignoreDir: context,
163
+ startedAt,
164
+ capturedByFile: capturedByFile.size > 0 ? capturedByFile : void 0,
165
+ combinedProtectionMap: {
166
+ buildDir: outputPath,
167
+ afterpackDir: (0, node_path.join)(context, ".afterpack")
168
+ },
169
+ ...(0, __afterpack_integration_utils.passSettings)({
170
+ options: this.settings,
171
+ engineConfig: this.engineConfig
172
+ }),
173
+ hasBundlerSourcemap: typeof devtool === "string" && devtool.includes("source-map"),
174
+ messages: { autoEnableBundlerSourcemap: "protectionMap:true but no bundler sourcemap was found; set `devtool: 'source-map'` so future builds can render original source in the map." }
175
+ });
176
+ const { RawSource } = compiler.webpack.sources;
177
+ for (const out of result.outputs ?? []) {
178
+ const asset = byPath.get(out.path);
179
+ if (!asset) continue;
180
+ const emitMap = result.policy.sourceMap && out.sourceMap != null;
181
+ const mapName = asset.mapName ?? `${asset.name}.map`;
182
+ const keepWebpacksOwnReference = asset.mapName != null;
183
+ const url = emitMap && result.policy.emitSourceMappingURL ? keepWebpacksOwnReference ? asset.url : (0, node_path.basename)(mapName) : null;
184
+ compilation.updateAsset(asset.name, new RawSource((0, __afterpack_integration_utils.withSourceMappingURL)(out.code, url)));
185
+ if (emitMap && out.sourceMap != null) {
186
+ const map = new RawSource(out.sourceMap);
187
+ if (compilation.getAsset(mapName)) compilation.updateAsset(mapName, map);
188
+ else compilation.emitAsset(mapName, map);
189
+ } else if (asset.mapName && compilation.getAsset(asset.mapName)) compilation.deleteAsset(asset.mapName);
190
+ }
191
+ if (result.deferredReceipt) this.deferredReceiptByCompilation.set(compilation, result.deferredReceipt);
192
+ }
193
+ capture(resource, context) {
194
+ if (!resource) return;
195
+ const path = resource.replace(/[?#].*$/, "");
196
+ this.seenByBuildHooksThisCompilation.add(path);
197
+ if (path.replace(/\\/g, "/").includes("/node_modules/")) return;
198
+ if (!SOURCE_MODULE_RE.test(path)) return;
199
+ let source;
200
+ try {
201
+ source = (0, node_fs.readFileSync)(path, "utf8");
202
+ } catch {
203
+ return;
204
+ }
205
+ if (!source.includes("@afterpack")) {
206
+ this.captured.delete(path);
207
+ return;
208
+ }
209
+ const idAsWrittenInMapSources = `./${(0, node_path.relative)(context, path).replace(/\\/g, "/")}`;
210
+ const scan = (0, __afterpack_integration_utils.scanDirectives)(source);
211
+ if (scan.directives.length > 0 || scan.renameGlobals) this.captured.set(path, {
212
+ id: idAsWrittenInMapSources,
213
+ source,
214
+ directives: scan.directives,
215
+ renameGlobals: scan.renameGlobals
216
+ });
217
+ else this.captured.delete(path);
218
+ for (const d of scan.diagnostics) this.captureDiagnostics.push(`${idAsWrittenInMapSources} (${d.line}:${d.column}): ${d.message}`);
219
+ }
220
+ joinCaptured(compilation, outputPath, emitted, context) {
221
+ const out = new Map();
222
+ const chunkGraph = compilation.chunkGraph;
223
+ if (!chunkGraph) return out;
224
+ const byFile = new Map();
225
+ for (const chunk of compilation.chunks) {
226
+ const resources = [];
227
+ for (const module$1 of chunkGraph.getChunkModulesIterable(chunk)) collectResourcesThroughConcatenatedModules(module$1, resources);
228
+ const mods = [];
229
+ for (const resource of resources) {
230
+ const restoredFromCachePastEveryHook = !this.seenByBuildHooksThisCompilation.has(resource);
231
+ if (restoredFromCachePastEveryHook) this.capture(resource, context);
232
+ const cap = this.captured.get(resource);
233
+ if (cap) mods.push(cap);
234
+ }
235
+ if (mods.length === 0) continue;
236
+ for (const name of chunk.files) {
237
+ if (!isEmittedJs(name)) continue;
238
+ const full = (0, node_path.join)(outputPath, name);
239
+ if (!emitted.has(full)) continue;
240
+ let bucket = byFile.get(full);
241
+ if (!bucket) {
242
+ bucket = new Map();
243
+ byFile.set(full, bucket);
244
+ }
245
+ for (const mod of mods) bucket.set(mod.id, mod);
246
+ }
247
+ }
248
+ for (const [file, bucket] of byFile) out.set(file, [...bucket.values()]);
249
+ return out;
250
+ }
251
+ };
252
+
253
+ //#endregion
254
+ exports.AfterpackWebpackPlugin = AfterpackWebpackPlugin;
@@ -0,0 +1,20 @@
1
+ import { AfterpackPluginOptions } from "@afterpack/integration-utils";
2
+ import { Compiler } from "webpack";
3
+
4
+ //#region src/index.d.ts
5
+ type AfterpackWebpackOptions = AfterpackPluginOptions;
6
+ declare class AfterpackWebpackPlugin {
7
+ private readonly settings;
8
+ private readonly engineConfig;
9
+ private readonly captured;
10
+ private readonly seenByBuildHooksThisCompilation;
11
+ private readonly captureDiagnostics;
12
+ private readonly deferredReceiptByCompilation;
13
+ constructor(options?: AfterpackWebpackOptions);
14
+ apply(compiler: Compiler): void;
15
+ private obfuscate;
16
+ private capture;
17
+ private joinCaptured;
18
+ }
19
+ //#endregion
20
+ export { AfterpackWebpackOptions, AfterpackWebpackPlugin };
@@ -0,0 +1,20 @@
1
+ import { AfterpackPluginOptions } from "@afterpack/integration-utils";
2
+ import { Compiler } from "webpack";
3
+
4
+ //#region src/index.d.ts
5
+ type AfterpackWebpackOptions = AfterpackPluginOptions;
6
+ declare class AfterpackWebpackPlugin {
7
+ private readonly settings;
8
+ private readonly engineConfig;
9
+ private readonly captured;
10
+ private readonly seenByBuildHooksThisCompilation;
11
+ private readonly captureDiagnostics;
12
+ private readonly deferredReceiptByCompilation;
13
+ constructor(options?: AfterpackWebpackOptions);
14
+ apply(compiler: Compiler): void;
15
+ private obfuscate;
16
+ private capture;
17
+ private joinCaptured;
18
+ }
19
+ //#endregion
20
+ export { AfterpackWebpackOptions, AfterpackWebpackPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,231 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { basename, join, relative } from "node:path";
3
+ import { processBatch, version } from "@afterpack/core";
4
+ import { createTelemetryReporter, decodeDataUri, extractSourceMappingURL, passSettings, resolveClientIdentity, resolvePluginConfig, runObfuscationPass, scanDirectives, withSourceMappingURL, writeDeferredProtectionReceipt } from "@afterpack/integration-utils";
5
+
6
+ //#region src/index.ts
7
+ const PLUGIN_NAME = "AfterpackWebpackPlugin";
8
+ const EMITTED_JS_RE = /\.(?:js|mjs|cjs)$/;
9
+ const SOURCE_MODULE_RE = /\.(?:m?[jt]sx?)$/;
10
+ const PATHS_INCLUDE_UNSUPPORTED = "this plugin obfuscates the assets webpack's own chunks claim, in the pipeline — there is no output-directory walk for a glob to re-admit anything into. Use `npx afterpack <dir> --paths.include=...` for a disk walk, or drop the key.";
11
+ function isEmittedJs(name) {
12
+ return !name.includes(".hot-update.") && EMITTED_JS_RE.test(name);
13
+ }
14
+ function assetText(compilation, name) {
15
+ const asset = compilation.getAsset(name);
16
+ if (!asset) return null;
17
+ const value = asset.source.source();
18
+ return typeof value === "string" ? value : value.toString("utf8");
19
+ }
20
+ function inputSourceMap(compilation, asset) {
21
+ if (asset.mapName) return assetText(compilation, asset.mapName);
22
+ if (asset.url == null) return null;
23
+ if (asset.url.startsWith("data:")) return decodeDataUri(asset.url);
24
+ if (/^https?:\/\//i.test(asset.url) || asset.url.startsWith("//")) return null;
25
+ const dir = asset.name.includes("/") ? `${asset.name.replace(/\/[^/]*$/, "")}/` : "";
26
+ return assetText(compilation, `${dir}${asset.url}`.replace(/^\.\//, ""));
27
+ }
28
+ function chunkClaimedJsAssets(compilation) {
29
+ const names = new Set();
30
+ for (const chunk of compilation.chunks) for (const name of chunk.files) if (isEmittedJs(name)) names.add(name);
31
+ const out = [];
32
+ for (const name of names) {
33
+ const asset = compilation.getAsset(name);
34
+ if (!asset) continue;
35
+ const related = asset.info.related;
36
+ const sourceMap = related?.sourceMap;
37
+ const mapName = typeof sourceMap === "string" ? sourceMap : sourceMap?.[0] ?? null;
38
+ const text = assetText(compilation, name);
39
+ out.push({
40
+ name,
41
+ mapName,
42
+ url: text ? extractSourceMappingURL(text) : null
43
+ });
44
+ }
45
+ return out;
46
+ }
47
+ function collectResourcesThroughConcatenatedModules(module, out) {
48
+ if (module == null || typeof module !== "object") return;
49
+ const inner = module.modules;
50
+ if (Array.isArray(inner)) {
51
+ for (const m of inner) collectResourcesThroughConcatenatedModules(m, out);
52
+ return;
53
+ }
54
+ const resource = module.resource;
55
+ if (typeof resource === "string") out.push(resource.replace(/[?#].*$/, ""));
56
+ }
57
+ var AfterpackWebpackPlugin = class {
58
+ settings;
59
+ engineConfig;
60
+ captured = new Map();
61
+ seenByBuildHooksThisCompilation = new Set();
62
+ captureDiagnostics = [];
63
+ deferredReceiptByCompilation = new WeakMap();
64
+ constructor(options = {}) {
65
+ const resolved = resolvePluginConfig({
66
+ label: PLUGIN_NAME,
67
+ options,
68
+ unsupported: { "paths.include": PATHS_INCLUDE_UNSUPPORTED }
69
+ });
70
+ this.settings = resolved.options;
71
+ this.engineConfig = resolved.engineConfig;
72
+ }
73
+ apply(compiler) {
74
+ const context = compiler.options.context ?? process.cwd();
75
+ const directivesEnabled = this.settings.directives.enabled;
76
+ if (directivesEnabled) compiler.hooks.thisCompilation.tap(PLUGIN_NAME, () => {
77
+ this.seenByBuildHooksThisCompilation.clear();
78
+ });
79
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
80
+ if (directivesEnabled) {
81
+ const hooks = compiler.webpack.NormalModule.getCompilationHooks(compilation);
82
+ hooks.beforeLoaders.tap(PLUGIN_NAME, (_loaders, module) => {
83
+ this.capture(module.resource, context);
84
+ });
85
+ }
86
+ compilation.hooks.processAssets.tapPromise({
87
+ name: PLUGIN_NAME,
88
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT
89
+ }, () => this.obfuscate(compiler, compilation, context));
90
+ });
91
+ compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (compilation) => {
92
+ const deferred = this.deferredReceiptByCompilation.get(compilation);
93
+ if (!deferred) return;
94
+ this.deferredReceiptByCompilation.delete(compilation);
95
+ try {
96
+ const receiptPath = writeDeferredProtectionReceipt(deferred);
97
+ if (receiptPath && this.settings.diagnostics?.level !== "none") console.log(`[afterpack-webpack] wrote protection receipt -> ${receiptPath} (afterpack verify)`);
98
+ } catch (error) {
99
+ console.warn(`[afterpack-webpack] failed to write protection receipt: ${error instanceof Error ? error.message : String(error)}`);
100
+ }
101
+ });
102
+ }
103
+ async obfuscate(compiler, compilation, context) {
104
+ if (this.settings.build?.autorun === false) return;
105
+ const startedAt = Date.now();
106
+ const outputPath = compiler.outputPath;
107
+ const owned = chunkClaimedJsAssets(compilation);
108
+ if (owned.length === 0) return;
109
+ const byPath = new Map();
110
+ const inputs = new Map();
111
+ for (const asset of owned) {
112
+ const source = assetText(compilation, asset.name);
113
+ if (source == null) continue;
114
+ const filePath = join(outputPath, asset.name);
115
+ byPath.set(filePath, asset);
116
+ inputs.set(filePath, {
117
+ source,
118
+ sourceMap: inputSourceMap(compilation, asset)
119
+ });
120
+ }
121
+ const files = [...byPath.keys()];
122
+ if (files.length === 0) return;
123
+ const directivesEnabled = this.settings.directives.enabled;
124
+ const capturedByFile = directivesEnabled ? this.joinCaptured(compilation, outputPath, new Set(files), context) : new Map();
125
+ for (const message of this.captureDiagnostics) console.warn(`[afterpack-webpack] directive ${message}`);
126
+ this.captureDiagnostics.length = 0;
127
+ const devtool = compiler.options.devtool;
128
+ const result = await runObfuscationPass({
129
+ files,
130
+ inputs,
131
+ emitToCaller: true,
132
+ engine: {
133
+ processBatch,
134
+ version
135
+ },
136
+ client: resolveClientIdentity(import.meta.url),
137
+ telemetry: createTelemetryReporter(),
138
+ label: "afterpack-webpack",
139
+ gitignoreDir: context,
140
+ startedAt,
141
+ capturedByFile: capturedByFile.size > 0 ? capturedByFile : void 0,
142
+ combinedProtectionMap: {
143
+ buildDir: outputPath,
144
+ afterpackDir: join(context, ".afterpack")
145
+ },
146
+ ...passSettings({
147
+ options: this.settings,
148
+ engineConfig: this.engineConfig
149
+ }),
150
+ hasBundlerSourcemap: typeof devtool === "string" && devtool.includes("source-map"),
151
+ messages: { autoEnableBundlerSourcemap: "protectionMap:true but no bundler sourcemap was found; set `devtool: 'source-map'` so future builds can render original source in the map." }
152
+ });
153
+ const { RawSource } = compiler.webpack.sources;
154
+ for (const out of result.outputs ?? []) {
155
+ const asset = byPath.get(out.path);
156
+ if (!asset) continue;
157
+ const emitMap = result.policy.sourceMap && out.sourceMap != null;
158
+ const mapName = asset.mapName ?? `${asset.name}.map`;
159
+ const keepWebpacksOwnReference = asset.mapName != null;
160
+ const url = emitMap && result.policy.emitSourceMappingURL ? keepWebpacksOwnReference ? asset.url : basename(mapName) : null;
161
+ compilation.updateAsset(asset.name, new RawSource(withSourceMappingURL(out.code, url)));
162
+ if (emitMap && out.sourceMap != null) {
163
+ const map = new RawSource(out.sourceMap);
164
+ if (compilation.getAsset(mapName)) compilation.updateAsset(mapName, map);
165
+ else compilation.emitAsset(mapName, map);
166
+ } else if (asset.mapName && compilation.getAsset(asset.mapName)) compilation.deleteAsset(asset.mapName);
167
+ }
168
+ if (result.deferredReceipt) this.deferredReceiptByCompilation.set(compilation, result.deferredReceipt);
169
+ }
170
+ capture(resource, context) {
171
+ if (!resource) return;
172
+ const path = resource.replace(/[?#].*$/, "");
173
+ this.seenByBuildHooksThisCompilation.add(path);
174
+ if (path.replace(/\\/g, "/").includes("/node_modules/")) return;
175
+ if (!SOURCE_MODULE_RE.test(path)) return;
176
+ let source;
177
+ try {
178
+ source = readFileSync(path, "utf8");
179
+ } catch {
180
+ return;
181
+ }
182
+ if (!source.includes("@afterpack")) {
183
+ this.captured.delete(path);
184
+ return;
185
+ }
186
+ const idAsWrittenInMapSources = `./${relative(context, path).replace(/\\/g, "/")}`;
187
+ const scan = scanDirectives(source);
188
+ if (scan.directives.length > 0 || scan.renameGlobals) this.captured.set(path, {
189
+ id: idAsWrittenInMapSources,
190
+ source,
191
+ directives: scan.directives,
192
+ renameGlobals: scan.renameGlobals
193
+ });
194
+ else this.captured.delete(path);
195
+ for (const d of scan.diagnostics) this.captureDiagnostics.push(`${idAsWrittenInMapSources} (${d.line}:${d.column}): ${d.message}`);
196
+ }
197
+ joinCaptured(compilation, outputPath, emitted, context) {
198
+ const out = new Map();
199
+ const chunkGraph = compilation.chunkGraph;
200
+ if (!chunkGraph) return out;
201
+ const byFile = new Map();
202
+ for (const chunk of compilation.chunks) {
203
+ const resources = [];
204
+ for (const module of chunkGraph.getChunkModulesIterable(chunk)) collectResourcesThroughConcatenatedModules(module, resources);
205
+ const mods = [];
206
+ for (const resource of resources) {
207
+ const restoredFromCachePastEveryHook = !this.seenByBuildHooksThisCompilation.has(resource);
208
+ if (restoredFromCachePastEveryHook) this.capture(resource, context);
209
+ const cap = this.captured.get(resource);
210
+ if (cap) mods.push(cap);
211
+ }
212
+ if (mods.length === 0) continue;
213
+ for (const name of chunk.files) {
214
+ if (!isEmittedJs(name)) continue;
215
+ const full = join(outputPath, name);
216
+ if (!emitted.has(full)) continue;
217
+ let bucket = byFile.get(full);
218
+ if (!bucket) {
219
+ bucket = new Map();
220
+ byFile.set(full, bucket);
221
+ }
222
+ for (const mod of mods) bucket.set(mod.id, mod);
223
+ }
224
+ }
225
+ for (const [file, bucket] of byFile) out.set(file, [...bucket.values()]);
226
+ return out;
227
+ }
228
+ };
229
+
230
+ //#endregion
231
+ export { AfterpackWebpackPlugin };
package/package.json ADDED
@@ -0,0 +1,79 @@
1
+ {
2
+ "name": "@afterpack/webpack",
3
+ "version": "0.1.0-rc.20260925T1347",
4
+ "description": "webpack plugin for AfterPack: obfuscate your production JavaScript during the webpack build",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ },
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "LICENSE",
24
+ "NOTICE",
25
+ "dist"
26
+ ],
27
+ "peerDependencies": {
28
+ "webpack": "^5.0.0"
29
+ },
30
+ "dependencies": {
31
+ "@afterpack/core": "~0.1.0",
32
+ "@afterpack/integration-utils": "0.1.0-rc.20260925T1347"
33
+ },
34
+ "devDependencies": {
35
+ "@biomejs/biome": "2.4.4",
36
+ "@types/node": "^22.0.0",
37
+ "tsdown": "^0.11.0",
38
+ "typescript": "^5.0.0",
39
+ "vitest": "^2.0.0",
40
+ "webpack": "^5.0.0"
41
+ },
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "https://github.com/afterpack-dev/afterpack.git",
51
+ "directory": "packages/webpack"
52
+ },
53
+ "keywords": [
54
+ "obfuscator",
55
+ "javascript-obfuscator",
56
+ "obfuscation",
57
+ "code-protection",
58
+ "source-code-protection",
59
+ "javascript-security",
60
+ "anti-reverse-engineering",
61
+ "webpack",
62
+ "webpack-plugin",
63
+ "afterpack"
64
+ ],
65
+ "author": "AfterPack (https://www.afterpack.dev)",
66
+ "license": "Apache-2.0",
67
+ "homepage": "https://www.afterpack.dev/docs/frameworks/webpack",
68
+ "bugs": {
69
+ "url": "https://github.com/afterpack-dev/afterpack/issues"
70
+ },
71
+ "scripts": {
72
+ "build": "tsdown src/index.ts --format esm --format cjs --dts --shims",
73
+ "dev": "tsdown src/index.ts --format esm --format cjs --shims --watch",
74
+ "lint": "biome check .",
75
+ "lint:fix": "biome check --write .",
76
+ "typecheck": "tsc --noEmit",
77
+ "test": "vitest run"
78
+ }
79
+ }