@afterpack/integration-utils 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/dist/index.js ADDED
@@ -0,0 +1,4246 @@
1
+ import { createRequire } from "node:module";
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
4
+ import { renderProtectionMapHtml } from "@afterpack/protection-map";
5
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
6
+ import { fileURLToPath } from "node:url";
7
+ import { readFile } from "node:fs/promises";
8
+ import { execFileSync } from "node:child_process";
9
+ import { decode } from "@jridgewell/sourcemap-codec";
10
+ import { homedir } from "node:os";
11
+
12
+ //#region src/paths.ts
13
+ const COMBINED_PROTECTION_MAP_NAME = "protectionMap.html";
14
+ function shortHash(content) {
15
+ return createHash("sha256").update(content, "utf8").digest("hex").slice(0, 8);
16
+ }
17
+ function resolveArtifactPaths(outPath, mode, contentHash) {
18
+ const { dir, name, ext } = parse(outPath);
19
+ const stem = join(dir, name);
20
+ return {
21
+ mapPath: `${outPath}.map`,
22
+ protectionMapPath: mode === "single" ? `${stem}.protectionMap.html` : null,
23
+ backupPath: contentHash != null ? `${stem}.backup.${contentHash}${ext}` : null
24
+ };
25
+ }
26
+ function combinedProtectionMapPath(buildDir) {
27
+ return join(buildDir, COMBINED_PROTECTION_MAP_NAME);
28
+ }
29
+ function findUpward(startDir, fileName, options = {}) {
30
+ let current = resolve(startDir);
31
+ for (;;) {
32
+ const candidate = join(current, fileName);
33
+ if (existsSync(candidate)) return candidate;
34
+ if (options.stopAtDir?.(current)) return null;
35
+ const parent = dirname(current);
36
+ if (parent === current) return null;
37
+ current = parent;
38
+ }
39
+ }
40
+
41
+ //#endregion
42
+ //#region src/artifacts.ts
43
+ const AFTERPACK_DIR = ".afterpack";
44
+ const GITIGNORE_ENTRIES = [
45
+ ".afterpack/",
46
+ "*.protectionMap.html",
47
+ "protectionMap.html",
48
+ "*.backup.*",
49
+ "*.map"
50
+ ];
51
+ const GITIGNORE_FILE = ".gitignore";
52
+ const GITIGNORE_BLOCK_HEADER = "# AfterPack artifacts (auto-added)";
53
+ const PUBLIC_SEGMENTS = new Set([
54
+ "public",
55
+ "static",
56
+ "assets",
57
+ "dist",
58
+ "build",
59
+ "out",
60
+ "www",
61
+ "htdocs",
62
+ "_next"
63
+ ]);
64
+ const DEFAULT_LOGGER = {
65
+ warn: (m) => console.warn(m),
66
+ log: (m) => console.log(m)
67
+ };
68
+ function appendSourceMappingURL(code, mapPath) {
69
+ const comment = `//# sourceMappingURL=${basename(mapPath)}`;
70
+ if (code.includes(comment)) return code;
71
+ const needsNewline = code.length > 0 && !code.endsWith("\n");
72
+ return `${code}${needsNewline ? "\n" : ""}${comment}\n`;
73
+ }
74
+ function writeArtifacts(input) {
75
+ const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
76
+ const mode = input.mode ?? "single";
77
+ const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
78
+ const logger = input.logger ?? DEFAULT_LOGGER;
79
+ const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
80
+ const paths = resolveArtifactPaths(outPath, mode, hash);
81
+ const result = {
82
+ codePath: outPath,
83
+ mapPath: null,
84
+ backupPath: null,
85
+ protectionMapPath: null,
86
+ wroteSourceMappingURL: false
87
+ };
88
+ if (policy.backup && originalSource != null && paths.backupPath != null) {
89
+ writeFileSync(paths.backupPath, originalSource);
90
+ result.backupPath = paths.backupPath;
91
+ }
92
+ const willWriteMap = policy.sourceMap && sourceMapJson != null;
93
+ let finalCode = code;
94
+ if (willWriteMap && policy.emitSourceMappingURL) {
95
+ finalCode = appendSourceMappingURL(code, paths.mapPath);
96
+ result.wroteSourceMappingURL = true;
97
+ }
98
+ writeFileSync(outPath, finalCode);
99
+ if (willWriteMap && sourceMapJson != null) {
100
+ writeFileSync(paths.mapPath, sourceMapJson);
101
+ result.mapPath = paths.mapPath;
102
+ }
103
+ if (mode === "single" && policy.protectionMap && protectionMapJson != null) {
104
+ mkdirSync(afterpackDir, { recursive: true });
105
+ const pmPath = join(afterpackDir, basename(paths.protectionMapPath));
106
+ if (policy.protectionMapInProd) warnProtectionMapInProd(pmPath, logger);
107
+ else logger.log(`[afterpack] wrote Protection Map -> ${pmPath} (gitignored; set protectionMap.enabled:false to skip)`);
108
+ const { html } = renderProtectionMapHtml(protectionMapJson);
109
+ writeFileSync(pmPath, html);
110
+ result.protectionMapPath = pmPath;
111
+ }
112
+ return result;
113
+ }
114
+ const REVERSAL_CLASS_ORDER = [
115
+ "preserved",
116
+ "renamed-encoded",
117
+ "flattened-fused",
118
+ "destroyed-fused"
119
+ ];
120
+ function round4(v) {
121
+ return Math.round(v * 1e4) / 1e4;
122
+ }
123
+ function isRuntimeSource(rawPath) {
124
+ const p = rawPath ?? "";
125
+ if (p.includes("[turbopack]") || p.includes("[next]")) return true;
126
+ if (/(^|\/)webpack\/(runtime|bootstrap)/.test(p)) return true;
127
+ if (p.includes("webpack://_N_E/webpack/")) return true;
128
+ if (/node_modules\/\.pnpm\/next[@/]/.test(p)) return true;
129
+ if (/(^|\/)node_modules\/next\//.test(p)) return true;
130
+ return false;
131
+ }
132
+ function cleanSourcePath(rawPath) {
133
+ let p = rawPath ?? "";
134
+ p = p.replace(/^turbopack:\/\/\/\[project\]\//, "");
135
+ p = p.replace(/^turbopack:\/\/\//, "");
136
+ p = p.replace(/^webpack:\/\/_N_E\/\.\//, "");
137
+ p = p.replace(/^webpack:\/\/_N_E\//, "");
138
+ p = p.replace(/^webpack:\/\//, "");
139
+ p = p.replace(/^\.\//, "");
140
+ p = p.replace(/node_modules\/\.pnpm\/[^/]+\/node_modules\//, "node_modules/");
141
+ return p;
142
+ }
143
+ function computeAggregate(regions, spotlights, renamedCount = 0, directives = [], extractedCount = 0) {
144
+ const regionCount = regions.length;
145
+ let sumEntropy = 0;
146
+ let maxEntropy = 0;
147
+ let minEntropy = regionCount === 0 ? 0 : 1;
148
+ let totalTransforms = 0;
149
+ let decodeOps = 0;
150
+ let callFrames = 0;
151
+ let sizeDeltaEstTotal = 0;
152
+ const classCounts = {
153
+ preserved: 0,
154
+ "renamed-encoded": 0,
155
+ "flattened-fused": 0,
156
+ "destroyed-fused": 0
157
+ };
158
+ let maxClassRank = 0;
159
+ for (const r of regions) {
160
+ const e = typeof r.entropy === "number" ? r.entropy : 0;
161
+ sumEntropy += e;
162
+ if (e > maxEntropy) maxEntropy = e;
163
+ if (e < minEntropy) minEntropy = e;
164
+ totalTransforms += r.transformCount ?? (Array.isArray(r.lineage) ? r.lineage.length : 0);
165
+ if (r.perf) {
166
+ decodeOps += r.perf.decodeOps ?? 0;
167
+ callFrames += r.perf.callFrames ?? 0;
168
+ }
169
+ sizeDeltaEstTotal += r.sizeDeltaEst ?? 0;
170
+ const cls = r.reversalClass;
171
+ if (cls != null && cls in classCounts) classCounts[cls] += 1;
172
+ const rank = REVERSAL_CLASS_ORDER.indexOf(cls);
173
+ if (rank > maxClassRank) maxClassRank = rank;
174
+ }
175
+ let leakCount = 0;
176
+ for (const s of spotlights) if (s.severity === "leak") leakCount += 1;
177
+ return {
178
+ avgEntropy: round4(regionCount === 0 ? 0 : sumEntropy / regionCount),
179
+ maxEntropy: round4(maxEntropy),
180
+ minEntropy: round4(regionCount === 0 ? 0 : minEntropy),
181
+ totalTransforms,
182
+ renamedCount,
183
+ extractedCount,
184
+ weakRegions: spotlights.length,
185
+ leakCount,
186
+ perfCostTotal: {
187
+ decodeOps,
188
+ callFrames
189
+ },
190
+ sizeDeltaEstTotal,
191
+ classSummary: {
192
+ ...classCounts,
193
+ maxClassReached: REVERSAL_CLASS_ORDER[maxClassRank]
194
+ },
195
+ directives
196
+ };
197
+ }
198
+ const SPAN_PACK_LIMIT = 1 << 25;
199
+ function packable(v, limit) {
200
+ return v >= 0 && v < limit && (v | 0) === v;
201
+ }
202
+ function spanKey(start, end, kind) {
203
+ if (packable(start, SPAN_PACK_LIMIT) && packable(end, SPAN_PACK_LIMIT) && packable(kind, 4)) return (start * SPAN_PACK_LIMIT + end) * 4 + kind;
204
+ return `${start},${end},${kind}`;
205
+ }
206
+ function mergeEntries(entries, path) {
207
+ const regions = [];
208
+ const seenRegion = new Set();
209
+ const spotlights = [];
210
+ const seenSpot = new Set();
211
+ const renamedSpans = [];
212
+ const seenRenamed = new Set();
213
+ const extractedFlat = [];
214
+ const seenExtracted = new Set();
215
+ const directives = [];
216
+ const seenDirective = new Set();
217
+ for (const e of entries) {
218
+ for (const r of e.regions ?? []) {
219
+ const key = Array.isArray(r.span) ? `${r.span[0]},${r.span[1]}` : `~${regions.length}`;
220
+ if (seenRegion.has(key)) continue;
221
+ seenRegion.add(key);
222
+ regions.push(r);
223
+ }
224
+ for (const s of e.spotlights ?? []) {
225
+ const sp = Array.isArray(s.span) ? `${s.span[0]},${s.span[1]}` : "";
226
+ const key = `${sp}|${s.severity ?? ""}|${s.sample ?? ""}`;
227
+ if (seenSpot.has(key)) continue;
228
+ seenSpot.add(key);
229
+ spotlights.push(s);
230
+ }
231
+ for (const rn of e.renamedSpans ?? []) {
232
+ const key = spanKey(rn[0], rn[1], 0);
233
+ if (seenRenamed.has(key)) continue;
234
+ seenRenamed.add(key);
235
+ renamedSpans.push(rn);
236
+ }
237
+ const flat = e.extractedSpans ?? [];
238
+ for (let i = 0; i + 2 < flat.length; i += 3) {
239
+ const key = spanKey(flat[i], flat[i + 1], flat[i + 2]);
240
+ if (seenExtracted.has(key)) continue;
241
+ seenExtracted.add(key);
242
+ extractedFlat.push(flat[i], flat[i + 1], flat[i + 2]);
243
+ }
244
+ const agg = e.aggregate;
245
+ for (const d of agg?.directives ?? []) {
246
+ const key = typeof d === "string" ? d : JSON.stringify(d);
247
+ if (seenDirective.has(key)) continue;
248
+ seenDirective.add(key);
249
+ directives.push(d);
250
+ }
251
+ }
252
+ renamedSpans.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
253
+ const extractedCount = extractedFlat.length / 3 | 0;
254
+ const order = new Uint32Array(extractedCount);
255
+ for (let i = 0; i < extractedCount; i++) order[i] = i;
256
+ order.sort((x, y) => {
257
+ const a = x * 3;
258
+ const b = y * 3;
259
+ return extractedFlat[a] - extractedFlat[b] || extractedFlat[a + 1] - extractedFlat[b + 1] || extractedFlat[a + 2] - extractedFlat[b + 2];
260
+ });
261
+ const extractedSpans = new Array(extractedCount * 3);
262
+ for (let i = 0; i < extractedCount; i++) {
263
+ const from = order[i] * 3;
264
+ const to = i * 3;
265
+ extractedSpans[to] = extractedFlat[from];
266
+ extractedSpans[to + 1] = extractedFlat[from + 1];
267
+ extractedSpans[to + 2] = extractedFlat[from + 2];
268
+ }
269
+ regions.sort((a, b) => {
270
+ const er = (b.entropyRaw ?? 0) - (a.entropyRaw ?? 0);
271
+ if (er !== 0) return er;
272
+ const as = Array.isArray(a.span) ? a.span[0] : 0;
273
+ const bs = Array.isArray(b.span) ? b.span[0] : 0;
274
+ if (as !== bs) return as - bs;
275
+ const ae = Array.isArray(a.span) ? a.span[1] : 0;
276
+ const be = Array.isArray(b.span) ? b.span[1] : 0;
277
+ return ae - be;
278
+ });
279
+ const rep = entries.find((e) => e.file?.sourceOrigin === "original") ?? entries[0];
280
+ const file = {
281
+ ...rep.file ?? {},
282
+ path,
283
+ sourceOrigin: "original"
284
+ };
285
+ let outputSum = 0;
286
+ let bundledSum = 0;
287
+ let sawOutput = false;
288
+ let sawBundled = false;
289
+ let anyEstimated = false;
290
+ for (const e of entries) {
291
+ const m = e.file;
292
+ if (!m) continue;
293
+ if (typeof m.outputSize === "number" && Number.isFinite(m.outputSize)) {
294
+ outputSum += m.outputSize;
295
+ sawOutput = true;
296
+ }
297
+ if (typeof m.bundledInputSize === "number" && Number.isFinite(m.bundledInputSize)) {
298
+ bundledSum += m.bundledInputSize;
299
+ sawBundled = true;
300
+ }
301
+ if (m.outputSizeEstimated) anyEstimated = true;
302
+ }
303
+ if (sawBundled) file.bundledInputSize = bundledSum;
304
+ if (sawOutput) {
305
+ file.outputSize = outputSum;
306
+ file.outputSizeEstimated = anyEstimated;
307
+ }
308
+ const denom = sawBundled && bundledSum > 0 ? bundledSum : file.inputSize;
309
+ if (sawOutput && typeof denom === "number" && denom > 0) file.inflationRatio = round4(outputSum / denom);
310
+ else if (sawOutput) file.inflationRatio = 0;
311
+ return {
312
+ file,
313
+ regions,
314
+ spotlights,
315
+ renamedSpans,
316
+ extractedSpans,
317
+ aggregate: computeAggregate(regions, spotlights, renamedSpans.length, directives, extractedCount)
318
+ };
319
+ }
320
+ function buildProjectFileTree(files) {
321
+ const byPath = new Map();
322
+ const pathOrder = [];
323
+ for (const raw of files) {
324
+ const entry = raw;
325
+ const file = entry?.file;
326
+ if (!file) continue;
327
+ if (file.sourceOrigin !== "original") continue;
328
+ if (isRuntimeSource(file.path)) continue;
329
+ const clean = cleanSourcePath(file.path);
330
+ const srcKey = file.originalSource ?? "";
331
+ let bySrc = byPath.get(clean);
332
+ if (!bySrc) {
333
+ bySrc = new Map();
334
+ byPath.set(clean, bySrc);
335
+ pathOrder.push(clean);
336
+ }
337
+ const group$1 = bySrc.get(srcKey);
338
+ if (group$1) group$1.push(entry);
339
+ else bySrc.set(srcKey, [entry]);
340
+ }
341
+ const out = [];
342
+ for (const clean of pathOrder) {
343
+ const bySrc = byPath.get(clean);
344
+ const variants = [...bySrc.values()];
345
+ variants.forEach((entries, i) => {
346
+ const path = i === 0 ? clean : `${clean}#${i + 1}`;
347
+ const merged = mergeEntries(entries, path);
348
+ if (i > 0 && merged.file) merged.file.pathCollision = true;
349
+ out.push(merged);
350
+ });
351
+ }
352
+ return out;
353
+ }
354
+ function writeCombinedProtectionMap(input) {
355
+ const { buildDir, docs, policy } = input;
356
+ const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
357
+ const logger = input.logger ?? DEFAULT_LOGGER;
358
+ if (!policy.protectionMap || docs.length === 0) return null;
359
+ mkdirSync(afterpackDir, { recursive: true });
360
+ const outPath = join(afterpackDir, input.fileName ?? basename(combinedProtectionMapPath(buildDir)));
361
+ if (policy.protectionMapInProd) warnProtectionMapInProd(outPath, logger);
362
+ else logger.log(`[afterpack] wrote Protection Map -> ${outPath} (gitignored; set protectionMap.enabled:false to skip)`);
363
+ const flat = docs.flatMap((doc) => {
364
+ if (!doc) return [];
365
+ const f = doc.files;
366
+ return Array.isArray(f) ? f : [doc];
367
+ });
368
+ const files = buildProjectFileTree(flat);
369
+ const envelope = docs.find((d) => !!d && (d.schemaVersion !== void 0 || d.engine !== void 0));
370
+ const { html } = renderProtectionMapHtml({
371
+ schemaVersion: envelope?.schemaVersion,
372
+ spanUnits: envelope?.spanUnits,
373
+ engine: envelope?.engine,
374
+ files
375
+ }, { includeLineage: true });
376
+ writeFileSync(outPath, html);
377
+ return outPath;
378
+ }
379
+ function warnProtectionMapInProd(pmPath, logger) {
380
+ logger.warn(`[afterpack] WARNING: the Protection Map is ENABLED in a PRODUCTION build. This LOCAL file embeds your ORIGINAL SOURCE and surviving-literal samples -- NEVER serve or commit it. Writing it to the gitignored "${pmPath}" instead of alongside the build output.`);
381
+ }
382
+ function nearestGitignore(startDir) {
383
+ return findUpward(startDir, GITIGNORE_FILE, { stopAtDir: (dir) => existsSync(join(dir, ".git")) });
384
+ }
385
+ function ensureGitignore(targetDir) {
386
+ const gitignorePath = nearestGitignore(targetDir);
387
+ if (gitignorePath === null) return [];
388
+ let existing = "";
389
+ try {
390
+ existing = readFileSync(gitignorePath, "utf8");
391
+ } catch {
392
+ existing = "";
393
+ }
394
+ const present = new Set(existing.split(/\r?\n/).map((l) => l.trim()));
395
+ const missing = GITIGNORE_ENTRIES.filter((e) => !present.has(e));
396
+ if (missing.length === 0) return [];
397
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
398
+ const block = `${prefix}\n${GITIGNORE_BLOCK_HEADER}\n${missing.join("\n")}\n`;
399
+ writeFileSync(gitignorePath, existing + block);
400
+ return missing;
401
+ }
402
+ function warnIfPublicPath(artifactPath, logger = DEFAULT_LOGGER) {
403
+ const segments$1 = artifactPath.split(/[\\/]/).filter(Boolean);
404
+ const hit = segments$1.find((s) => PUBLIC_SEGMENTS.has(s.toLowerCase()));
405
+ if (hit == null) return false;
406
+ logger.warn(`[afterpack] WARNING: writing "${artifactPath}" under a public/served path segment ("${hit}"). Source maps and Protection Maps must NOT be served publicly -- a served obfuscator map is full deobfuscation. Move it out of the served tree or disable the artifact for this build.`);
407
+ return true;
408
+ }
409
+
410
+ //#endregion
411
+ //#region src/source-map.ts
412
+ const SOURCE_MAPPING_URL_RE = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
413
+ const SOURCE_MAPPING_URL_LINE_RE = /^[ \t]*\/\/[#@]\s*sourceMappingURL=\S+[ \t]*\r?\n?/gm;
414
+ function withSourceMappingURL(code, url) {
415
+ const stripped = code.replace(SOURCE_MAPPING_URL_LINE_RE, "");
416
+ if (url == null) return stripped;
417
+ const separator = stripped.length > 0 && !stripped.endsWith("\n") ? "\n" : "";
418
+ return `${stripped}${separator}//# sourceMappingURL=${url}\n`;
419
+ }
420
+ function extractSourceMappingURL(code) {
421
+ let last = null;
422
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) last = match[1];
423
+ return last;
424
+ }
425
+ function isRemoteSourceMappingURL(url) {
426
+ return /^https?:\/\//i.test(url) || url.startsWith("//");
427
+ }
428
+ function decodeDataUri(url) {
429
+ if (!url.startsWith("data:")) return null;
430
+ const comma = url.indexOf(",");
431
+ if (comma === -1) return null;
432
+ const meta = url.slice(5, comma);
433
+ const payload = url.slice(comma + 1);
434
+ try {
435
+ if (/;base64/i.test(meta)) return Buffer.from(payload, "base64").toString("utf8");
436
+ return decodeURIComponent(payload);
437
+ } catch {
438
+ return null;
439
+ }
440
+ }
441
+ function discoverInputSourceMap(jsPath, code) {
442
+ const adjacent = `${jsPath}.map`;
443
+ if (existsSync(adjacent)) try {
444
+ return readFileSync(adjacent, "utf8");
445
+ } catch {}
446
+ let source = code;
447
+ if (source == null) try {
448
+ source = readFileSync(jsPath, "utf8");
449
+ } catch {
450
+ return null;
451
+ }
452
+ const url = extractSourceMappingURL(source);
453
+ if (url == null) return null;
454
+ if (url.startsWith("data:")) return decodeDataUri(url);
455
+ if (isRemoteSourceMappingURL(url)) return null;
456
+ let mapPath;
457
+ try {
458
+ mapPath = isAbsolute(url) ? url : resolve(dirname(jsPath), decodeURIComponent(url));
459
+ } catch {
460
+ return null;
461
+ }
462
+ if (!existsSync(mapPath)) return null;
463
+ try {
464
+ return readFileSync(mapPath, "utf8");
465
+ } catch {
466
+ return null;
467
+ }
468
+ }
469
+
470
+ //#endregion
471
+ //#region src/bundle.ts
472
+ const BUNDLE_JS_RE = /\.[cm]?js$/;
473
+ function collectBundleJs(bundle, outDir) {
474
+ const files = [];
475
+ const inputs = new Map();
476
+ const entries = new Map();
477
+ for (const [fileName, entry] of Object.entries(bundle)) {
478
+ if (!BUNDLE_JS_RE.test(fileName)) continue;
479
+ const source = entry.type === "chunk" ? entry.code : typeof entry.source === "string" ? entry.source : void 0;
480
+ if (source === void 0) continue;
481
+ const filePath = resolve(outDir, fileName);
482
+ files.push(filePath);
483
+ entries.set(filePath, entry);
484
+ inputs.set(filePath, {
485
+ source,
486
+ sourceMap: entry.map ? entry.map.toString() : null
487
+ });
488
+ }
489
+ return {
490
+ files,
491
+ inputs,
492
+ entries
493
+ };
494
+ }
495
+ function dataUri(json) {
496
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
497
+ }
498
+ function applyBundleOutput(bundle, entry, out, policy) {
499
+ if (entry.type !== "chunk") {
500
+ entry.source = out.code;
501
+ return;
502
+ }
503
+ const mapName = entry.sourcemapFileName ?? null;
504
+ const inlineMap = mapName == null && entry.map != null;
505
+ const emitMap = policy.sourceMap && out.sourceMap != null;
506
+ let url = null;
507
+ if (emitMap && out.sourceMap != null) {
508
+ if (mapName != null && bundle[mapName]) {
509
+ bundle[mapName].source = out.sourceMap;
510
+ url = basename(mapName);
511
+ } else if (inlineMap) url = dataUri(out.sourceMap);
512
+ } else {
513
+ if (mapName != null) delete bundle[mapName];
514
+ entry.map = null;
515
+ }
516
+ entry.code = withSourceMappingURL(out.code, policy.emitSourceMappingURL ? url : null);
517
+ }
518
+
519
+ //#endregion
520
+ //#region src/glob.ts
521
+ function normalize(value) {
522
+ return value.includes("\\") ? value.replaceAll("\\", "/") : value;
523
+ }
524
+ function segments(value) {
525
+ return value.split("/").filter((part) => part !== "");
526
+ }
527
+ function isAnchored(pattern) {
528
+ if (pattern.startsWith("/")) return true;
529
+ return pattern.length >= 2 && pattern[1] === ":" && /^[A-Za-z]$/.test(pattern[0]);
530
+ }
531
+ function segmentMatches(pattern, seg) {
532
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === seg;
533
+ const p = [...pattern];
534
+ const s = [...seg];
535
+ let pi = 0;
536
+ let si = 0;
537
+ let star = -1;
538
+ let starSi = 0;
539
+ while (si < s.length) if (pi < p.length && p[pi] === "*") {
540
+ star = pi;
541
+ starSi = si;
542
+ pi += 1;
543
+ } else if (pi < p.length && (p[pi] === "?" || p[pi] === s[si])) {
544
+ pi += 1;
545
+ si += 1;
546
+ } else if (star >= 0) {
547
+ pi = star + 1;
548
+ starSi += 1;
549
+ si = starSi;
550
+ } else return false;
551
+ return p.slice(pi).every((c) => c === "*");
552
+ }
553
+ function segmentsMatch(pattern, path) {
554
+ let pi = 0;
555
+ let si = 0;
556
+ let star = -1;
557
+ let starSi = 0;
558
+ while (si < path.length) if (pi < pattern.length && pattern[pi] === "**") {
559
+ star = pi;
560
+ starSi = si;
561
+ pi += 1;
562
+ } else if (pi < pattern.length && segmentMatches(pattern[pi], path[si])) {
563
+ pi += 1;
564
+ si += 1;
565
+ } else if (star >= 0) {
566
+ pi = star + 1;
567
+ starSi += 1;
568
+ si = starSi;
569
+ } else return false;
570
+ return pattern.slice(pi).every((s) => s === "**");
571
+ }
572
+ function matchesPath(pattern, path) {
573
+ const pat = normalize(pattern);
574
+ const parts = segments(pat);
575
+ if (parts.length === 0) return false;
576
+ const segs = segments(normalize(path));
577
+ if (isAnchored(pat)) return segmentsMatch(parts, segs);
578
+ for (let i = 0; i <= segs.length; i++) if (segmentsMatch(parts, segs.slice(i))) return true;
579
+ return false;
580
+ }
581
+ function reachesInto(pattern, dir) {
582
+ const pat = normalize(pattern);
583
+ const parts = segments(pat);
584
+ if (parts.length === 0) return false;
585
+ if (!isAnchored(pat)) return true;
586
+ for (let k = 1; k <= parts.length; k++) if (matchesPath(`/${parts.slice(0, k).join("/")}`, dir)) return true;
587
+ return false;
588
+ }
589
+
590
+ //#endregion
591
+ //#region src/collect.ts
592
+ const BACKUP_RE = /\.backup\.[0-9a-f]{8}\.[cm]?js$/;
593
+ const NODE_MODULES = "node_modules";
594
+ function isCollectableJs(name) {
595
+ if (BACKUP_RE.test(name)) return false;
596
+ return name.endsWith(".js") || name.endsWith(".mjs") || name.endsWith(".cjs");
597
+ }
598
+ function statOrNull(path) {
599
+ try {
600
+ return statSync(path);
601
+ } catch {
602
+ return null;
603
+ }
604
+ }
605
+ function collectJsFiles(target, options = {}) {
606
+ const stat = statOrNull(target);
607
+ if (!stat) return [];
608
+ if (!stat.isDirectory()) return isCollectableJs(basename(target)) ? [target] : [];
609
+ return walkJs(target, options.include ?? [], false, options.onNestedProject);
610
+ }
611
+ function entriesOf(dir) {
612
+ try {
613
+ return readdirSync(dir, { withFileTypes: true });
614
+ } catch {
615
+ return [];
616
+ }
617
+ }
618
+ function kindOf(entry, full) {
619
+ if (entry.isDirectory()) return "dir";
620
+ if (entry.isFile()) return "file";
621
+ const stat = statOrNull(full);
622
+ if (!stat) return null;
623
+ return stat.isDirectory() ? "dir" : "file";
624
+ }
625
+ function isNestedProject(dir) {
626
+ return existsSync(join(dir, "package.json"));
627
+ }
628
+ function walkJs(dir, include, readmitted, onNestedProject) {
629
+ const out = [];
630
+ for (const entry of entriesOf(dir)) {
631
+ const name = entry.name;
632
+ const full = join(dir, name);
633
+ const kind = kindOf(entry, full);
634
+ if (kind === null) continue;
635
+ if (kind === "dir") {
636
+ const skipped = name === NODE_MODULES;
637
+ if (!skipped && !readmitted && isNestedProject(full)) {
638
+ onNestedProject?.(full);
639
+ continue;
640
+ }
641
+ if (skipped && !include.some((pattern) => reachesInto(pattern, full))) continue;
642
+ out.push(...walkJs(full, include, readmitted || skipped, onNestedProject));
643
+ } else if (isCollectableJs(name)) {
644
+ if (readmitted && !include.some((pattern) => matchesPath(pattern, full))) continue;
645
+ out.push(full);
646
+ }
647
+ }
648
+ return out;
649
+ }
650
+ function isSourceMap(name) {
651
+ return name.endsWith(".js.map") || name.endsWith(".mjs.map") || name.endsWith(".cjs.map");
652
+ }
653
+ function collectSourceMaps(dir) {
654
+ if (!existsSync(dir)) return [];
655
+ const out = [];
656
+ for (const entry of entriesOf(dir)) {
657
+ const name = entry.name;
658
+ const full = join(dir, name);
659
+ const kind = kindOf(entry, full);
660
+ if (kind === null) continue;
661
+ if (kind === "dir") out.push(...collectSourceMaps(full));
662
+ else if (isSourceMap(name)) out.push(full);
663
+ }
664
+ return out;
665
+ }
666
+
667
+ //#endregion
668
+ //#region src/notices.ts
669
+ const NOTICE_MESSAGE_LIMIT = 500;
670
+ const NOTICE_LIMIT = 5;
671
+ const NOTICE_CODE_LIMIT = 64;
672
+ const NOTICE_HOSTS = new Set(["afterpack.dev", "www.afterpack.dev"]);
673
+ const ESC = 27;
674
+ const BEL = 7;
675
+ const C1_CSI = 155;
676
+ const C1_OSC = 157;
677
+ function isControl(code) {
678
+ return code < 32 || code >= 127 && code <= 159;
679
+ }
680
+ function isInvisibleFormat(code) {
681
+ return code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
682
+ }
683
+ function skipCsi(text, from) {
684
+ let i = from;
685
+ while (i < text.length) {
686
+ const c = text.charCodeAt(i);
687
+ i += 1;
688
+ if (c >= 64 && c <= 126) return i;
689
+ }
690
+ return i;
691
+ }
692
+ function skipOsc(text, from) {
693
+ let i = from;
694
+ while (i < text.length) {
695
+ const c = text.charCodeAt(i);
696
+ if (c === BEL) return i + 1;
697
+ if (c === ESC) return text.charCodeAt(i + 1) === 92 ? i + 2 : i + 1;
698
+ if (c === 156) return i + 1;
699
+ i += 1;
700
+ }
701
+ return i;
702
+ }
703
+ function stripTerminalControls(text) {
704
+ let out = "";
705
+ let i = 0;
706
+ while (i < text.length) {
707
+ const c = text.charCodeAt(i);
708
+ if (c === ESC) {
709
+ const next = text.charCodeAt(i + 1);
710
+ if (next === 91) i = skipCsi(text, i + 2);
711
+ else if (next === 93) i = skipOsc(text, i + 2);
712
+ else i += Number.isNaN(next) ? 1 : 2;
713
+ continue;
714
+ }
715
+ if (c === C1_CSI) {
716
+ i = skipCsi(text, i + 1);
717
+ continue;
718
+ }
719
+ if (c === C1_OSC) {
720
+ i = skipOsc(text, i + 1);
721
+ continue;
722
+ }
723
+ if (isControl(c)) {
724
+ out += c === 9 || c === 10 || c === 13 ? " " : "";
725
+ i += 1;
726
+ continue;
727
+ }
728
+ if (c === 8232 || c === 8233) {
729
+ out += " ";
730
+ i += 1;
731
+ continue;
732
+ }
733
+ if (isInvisibleFormat(c)) {
734
+ i += 1;
735
+ continue;
736
+ }
737
+ out += text[i];
738
+ i += 1;
739
+ }
740
+ return out;
741
+ }
742
+ function sanitizeServerText(value, limit = NOTICE_MESSAGE_LIMIT) {
743
+ if (typeof value !== "string") return "";
744
+ const clean = stripTerminalControls(value).replace(/\s+/g, " ").trim();
745
+ if (clean.length <= limit) return clean;
746
+ const chars = Array.from(clean);
747
+ return chars.length > limit ? chars.slice(0, limit).join("") : clean;
748
+ }
749
+ function sanitizeNoticeUrl(value) {
750
+ if (typeof value !== "string") return null;
751
+ let url;
752
+ try {
753
+ url = new URL(value.trim());
754
+ } catch {
755
+ return null;
756
+ }
757
+ if (url.protocol !== "https:") return null;
758
+ if (!NOTICE_HOSTS.has(url.hostname) || url.port !== "") return null;
759
+ if (url.username !== "" || url.password !== "") return null;
760
+ const href = url.href;
761
+ return href.length <= NOTICE_MESSAGE_LIMIT ? href : null;
762
+ }
763
+ function noticeSeverity(value) {
764
+ if (value === "info") return "info";
765
+ if (value === "error" || value === "critical") return "error";
766
+ return "warning";
767
+ }
768
+ function sanitizeNotices(raw) {
769
+ if (!Array.isArray(raw)) return [];
770
+ const out = [];
771
+ for (const entry of raw) {
772
+ if (out.length >= NOTICE_LIMIT) break;
773
+ if (typeof entry !== "object" || entry === null) continue;
774
+ const n = entry;
775
+ const message = sanitizeServerText(n.message);
776
+ if (message === "") continue;
777
+ out.push({
778
+ severity: noticeSeverity(n.severity),
779
+ code: sanitizeServerText(n.code, NOTICE_CODE_LIMIT),
780
+ message,
781
+ url: sanitizeNoticeUrl(n.url)
782
+ });
783
+ }
784
+ return out;
785
+ }
786
+ function formatNotice(notice) {
787
+ const head = notice.severity === "info" ? "AfterPack notice" : `AfterPack ${notice.severity}`;
788
+ const tail = notice.url ? ` ${notice.url}` : "";
789
+ return `${head}: ${notice.message}${tail}`;
790
+ }
791
+ function reportNotices(raw, logger, prefix = (m) => m) {
792
+ const notices = sanitizeNotices(raw);
793
+ for (const notice of notices) {
794
+ const line = prefix(formatNotice(notice));
795
+ if (notice.severity === "info" || !logger.warn) logger.log(line);
796
+ else logger.warn(line);
797
+ }
798
+ return notices;
799
+ }
800
+
801
+ //#endregion
802
+ //#region src/registry.ts
803
+ const PRESET_VALUES = [
804
+ "minify",
805
+ "light",
806
+ "medium",
807
+ "hard",
808
+ "extreme"
809
+ ];
810
+ const TRANSFORM_KIND_VALUES = [
811
+ "stringEncoding",
812
+ "controlFlowFlatten",
813
+ "opaquePredicate",
814
+ "mixedBooleanArithmetic",
815
+ "integerBytecode",
816
+ "crossDependency",
817
+ "scopeDeepen",
818
+ "comparisonHardening",
819
+ "selfIntegrity",
820
+ "objectConstruction"
821
+ ];
822
+ const REFLECTION_ALLOW_VALUES = [
823
+ "functionToString",
824
+ "nameIntrospection",
825
+ "argumentsCallee",
826
+ "prototypeChain",
827
+ "decoratorMetadata",
828
+ "constructorIntrospection",
829
+ "angular",
830
+ "nestjs"
831
+ ];
832
+ const BUILD_MODE_VALUES = ["production", "development"];
833
+ const UNLIMITED = "unlimited";
834
+ const DIRECTIVES_ENABLED_DEFAULT = true;
835
+ const RESERVED_FILE_FORM = "{ \"identifiers\": { \"reserved\": [{ \"glob\": \"…\", \"names\": [\"…\"] }] } }";
836
+ const REGIONS_FILE_FORM = "{ \"regions\": [{ \"start\": 0, \"end\": 100, \"complexity\": 40 }] }";
837
+ const CONFIG_KEYS = [
838
+ {
839
+ path: "seed",
840
+ shape: "scalar",
841
+ scope: "program",
842
+ tier: "free",
843
+ surface: "engine",
844
+ item: { kind: "seed" },
845
+ default: "a new random seed per build"
846
+ },
847
+ {
848
+ path: "preset",
849
+ shape: "scalar",
850
+ scope: "region",
851
+ tier: "free",
852
+ surface: "engine",
853
+ item: {
854
+ kind: "enum",
855
+ values: PRESET_VALUES
856
+ },
857
+ default: "light"
858
+ },
859
+ {
860
+ path: "complexity",
861
+ shape: "scalar",
862
+ scope: "region",
863
+ tier: "free",
864
+ surface: "engine",
865
+ item: {
866
+ kind: "number",
867
+ min: 0
868
+ },
869
+ default: "the preset's value; light is 2",
870
+ namedValuesOf: "preset"
871
+ },
872
+ {
873
+ path: "inflation.max",
874
+ shape: "scalar",
875
+ scope: "region",
876
+ tier: "free",
877
+ surface: "engine",
878
+ item: {
879
+ kind: "unbounded",
880
+ min: 0,
881
+ unlimited: UNLIMITED
882
+ },
883
+ default: "the preset's output-size ladder: 1.2 / 2 / 2.5 / 4 / 7"
884
+ },
885
+ {
886
+ path: "strings.encode",
887
+ shape: "scalar",
888
+ scope: "region",
889
+ tier: "free",
890
+ surface: "engine",
891
+ item: { kind: "boolean" },
892
+ default: "true at any positive complexity; false at 0"
893
+ },
894
+ {
895
+ path: "strings.minLength",
896
+ shape: "scalar",
897
+ scope: "program",
898
+ tier: "free",
899
+ surface: "engine",
900
+ item: {
901
+ kind: "number",
902
+ min: 0,
903
+ integer: true
904
+ },
905
+ default: "0"
906
+ },
907
+ {
908
+ path: "strings.leaks.max",
909
+ shape: "scalar",
910
+ scope: "program",
911
+ tier: "free",
912
+ surface: "engine",
913
+ item: {
914
+ kind: "number",
915
+ min: 0,
916
+ integer: true
917
+ },
918
+ default: "unset; the count is reported but never fails a build"
919
+ },
920
+ {
921
+ path: "strings.preserveLiterals",
922
+ shape: "list",
923
+ scope: "program",
924
+ tier: "free",
925
+ surface: "engine",
926
+ item: { kind: "string" },
927
+ default: "[]"
928
+ },
929
+ {
930
+ path: "paths.include",
931
+ shape: "list",
932
+ scope: "program",
933
+ tier: "free",
934
+ surface: "build",
935
+ item: { kind: "string" },
936
+ default: "[]"
937
+ },
938
+ {
939
+ path: "paths.exclude",
940
+ shape: "list",
941
+ scope: "program",
942
+ tier: "free",
943
+ surface: "engine",
944
+ item: { kind: "string" },
945
+ default: "[]"
946
+ },
947
+ {
948
+ path: "identifiers.rename",
949
+ shape: "scalar",
950
+ scope: "program",
951
+ tier: "free",
952
+ surface: "engine",
953
+ item: { kind: "boolean" },
954
+ default: "true"
955
+ },
956
+ {
957
+ path: "identifiers.globals.rename",
958
+ shape: "scalar",
959
+ scope: "program",
960
+ tier: "free",
961
+ surface: "engine",
962
+ item: { kind: "boolean" },
963
+ default: "false"
964
+ },
965
+ {
966
+ path: "identifiers.reserved",
967
+ shape: "mixedList",
968
+ scope: "program",
969
+ tier: "free",
970
+ surface: "engine",
971
+ item: { kind: "reserved" },
972
+ default: "[]",
973
+ configFileForm: RESERVED_FILE_FORM
974
+ },
975
+ {
976
+ path: "identifiers.methods.rename",
977
+ shape: "scalar",
978
+ scope: "program",
979
+ tier: "free",
980
+ surface: "engine",
981
+ item: { kind: "boolean" },
982
+ default: "true"
983
+ },
984
+ {
985
+ path: "reflection.allow",
986
+ shape: "list",
987
+ scope: "program",
988
+ tier: "free",
989
+ surface: "engine",
990
+ item: {
991
+ kind: "enum",
992
+ values: REFLECTION_ALLOW_VALUES
993
+ },
994
+ default: "[]"
995
+ },
996
+ {
997
+ path: "sourceMap.enabled",
998
+ shape: "scalar",
999
+ scope: "program",
1000
+ tier: "free",
1001
+ surface: "engine",
1002
+ item: { kind: "boolean" },
1003
+ default: "true in development when an input map exists; false in production"
1004
+ },
1005
+ {
1006
+ path: "sourceMap.sourcesContent",
1007
+ shape: "scalar",
1008
+ scope: "program",
1009
+ tier: "free",
1010
+ surface: "engine",
1011
+ item: { kind: "boolean" },
1012
+ default: "true in development; false in production"
1013
+ },
1014
+ {
1015
+ path: "sourceMap.emitUrl",
1016
+ shape: "scalar",
1017
+ scope: "program",
1018
+ tier: "free",
1019
+ surface: "build",
1020
+ item: { kind: "boolean" },
1021
+ default: "true in development; false in production"
1022
+ },
1023
+ {
1024
+ path: "protectionMap.enabled",
1025
+ shape: "scalar",
1026
+ scope: "program",
1027
+ tier: "free",
1028
+ surface: "engine",
1029
+ item: { kind: "boolean" },
1030
+ default: "true when the bundler emitted a source map"
1031
+ },
1032
+ {
1033
+ path: "protectionMap.detailed",
1034
+ shape: "scalar",
1035
+ scope: "program",
1036
+ tier: "free",
1037
+ surface: "engine",
1038
+ item: { kind: "boolean" },
1039
+ default: "true"
1040
+ },
1041
+ {
1042
+ path: "regions",
1043
+ shape: "structured",
1044
+ scope: "program",
1045
+ tier: "pro",
1046
+ surface: "engine",
1047
+ item: { kind: "region" },
1048
+ default: "[]",
1049
+ configFileForm: REGIONS_FILE_FORM
1050
+ },
1051
+ {
1052
+ path: "transforms.controlFlowFlatten.enabled",
1053
+ shape: "scalar",
1054
+ scope: "program",
1055
+ tier: "free",
1056
+ surface: "engine",
1057
+ item: { kind: "boolean" },
1058
+ default: "true"
1059
+ },
1060
+ {
1061
+ path: "transforms.opaquePredicate.enabled",
1062
+ shape: "scalar",
1063
+ scope: "program",
1064
+ tier: "free",
1065
+ surface: "engine",
1066
+ item: { kind: "boolean" },
1067
+ default: "true"
1068
+ },
1069
+ {
1070
+ path: "transforms.mixedBooleanArithmetic.enabled",
1071
+ shape: "scalar",
1072
+ scope: "program",
1073
+ tier: "free",
1074
+ surface: "engine",
1075
+ item: { kind: "boolean" },
1076
+ default: "true"
1077
+ },
1078
+ {
1079
+ path: "transforms.integerBytecode.enabled",
1080
+ shape: "scalar",
1081
+ scope: "program",
1082
+ tier: "free",
1083
+ surface: "engine",
1084
+ item: { kind: "boolean" },
1085
+ default: "true"
1086
+ },
1087
+ {
1088
+ path: "transforms.crossDependency.enabled",
1089
+ shape: "scalar",
1090
+ scope: "program",
1091
+ tier: "free",
1092
+ surface: "engine",
1093
+ item: { kind: "boolean" },
1094
+ default: "true"
1095
+ },
1096
+ {
1097
+ path: "transforms.scopeDeepen.enabled",
1098
+ shape: "scalar",
1099
+ scope: "program",
1100
+ tier: "free",
1101
+ surface: "engine",
1102
+ item: { kind: "boolean" },
1103
+ default: "true"
1104
+ },
1105
+ {
1106
+ path: "transforms.objectConstruction.enabled",
1107
+ shape: "scalar",
1108
+ scope: "program",
1109
+ tier: "free",
1110
+ surface: "engine",
1111
+ item: { kind: "boolean" },
1112
+ default: "true"
1113
+ },
1114
+ {
1115
+ path: "transforms.comparisonHardening.enabled",
1116
+ shape: "scalar",
1117
+ scope: "program",
1118
+ tier: "pro",
1119
+ surface: "engine",
1120
+ item: { kind: "boolean" },
1121
+ default: "false"
1122
+ },
1123
+ {
1124
+ path: "transforms.selfIntegrity.enabled",
1125
+ shape: "scalar",
1126
+ scope: "program",
1127
+ tier: "pro",
1128
+ surface: "engine",
1129
+ item: { kind: "boolean" },
1130
+ default: "false"
1131
+ },
1132
+ {
1133
+ path: "build.backup",
1134
+ shape: "scalar",
1135
+ scope: "program",
1136
+ tier: "free",
1137
+ surface: "build",
1138
+ item: { kind: "boolean" },
1139
+ default: "false for an in-place pass; true standalone"
1140
+ },
1141
+ {
1142
+ path: "build.autorun",
1143
+ shape: "scalar",
1144
+ scope: "program",
1145
+ tier: "free",
1146
+ surface: "build",
1147
+ item: { kind: "boolean" },
1148
+ default: "true"
1149
+ },
1150
+ {
1151
+ path: "build.mode",
1152
+ shape: "scalar",
1153
+ scope: "program",
1154
+ tier: "free",
1155
+ surface: "build",
1156
+ item: {
1157
+ kind: "enum",
1158
+ values: BUILD_MODE_VALUES
1159
+ },
1160
+ default: "detected from the environment"
1161
+ },
1162
+ {
1163
+ path: "directives.enabled",
1164
+ shape: "scalar",
1165
+ scope: "program",
1166
+ tier: "free",
1167
+ surface: "build",
1168
+ item: { kind: "boolean" },
1169
+ default: "true"
1170
+ },
1171
+ {
1172
+ path: "diagnostics.level",
1173
+ shape: "scalar",
1174
+ scope: "program",
1175
+ tier: "free",
1176
+ surface: "build",
1177
+ item: {
1178
+ kind: "enum",
1179
+ values: [
1180
+ "summary",
1181
+ "all",
1182
+ "none"
1183
+ ]
1184
+ },
1185
+ default: "summary"
1186
+ },
1187
+ {
1188
+ path: "diagnostics.format",
1189
+ shape: "scalar",
1190
+ scope: "program",
1191
+ tier: "free",
1192
+ surface: "cli",
1193
+ item: {
1194
+ kind: "enum",
1195
+ values: ["text", "json"]
1196
+ },
1197
+ default: "text"
1198
+ },
1199
+ {
1200
+ path: "telemetry.enabled",
1201
+ shape: "scalar",
1202
+ scope: "program",
1203
+ tier: "free",
1204
+ surface: "build",
1205
+ item: { kind: "boolean" },
1206
+ default: "true"
1207
+ },
1208
+ {
1209
+ path: "allowUnobfuscated",
1210
+ shape: "scalar",
1211
+ scope: "program",
1212
+ tier: "free",
1213
+ surface: "build",
1214
+ item: { kind: "boolean" },
1215
+ default: "false"
1216
+ },
1217
+ {
1218
+ path: "key",
1219
+ shape: "scalar",
1220
+ scope: "program",
1221
+ tier: "pro",
1222
+ surface: "build",
1223
+ item: { kind: "string" },
1224
+ default: "unset; builds run locally with basic protection"
1225
+ }
1226
+ ];
1227
+ const EMPTY_CONFIG = {};
1228
+ const CONFIG_BY_PATH = new Map(CONFIG_KEYS.map((k) => [k.path, k]));
1229
+ const CONFIG_PREFIXES = new Set(CONFIG_KEYS.flatMap((k) => {
1230
+ const parts = k.path.split(".");
1231
+ return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join("."));
1232
+ }));
1233
+ const CONFIG_CHILDREN = new Map([...CONFIG_PREFIXES].map((prefix) => [prefix, CONFIG_KEYS.filter((k) => k.path.startsWith(`${prefix}.`)).map((k) => k.path)]));
1234
+ const BY_NORMALIZED = new Map(CONFIG_KEYS.map((k) => [normalizeKey(k.path), k]));
1235
+ const CHILDREN_BY_NORMALIZED = new Map([...CONFIG_CHILDREN].map(([prefix, children]) => [normalizeKey(prefix), children]));
1236
+ const PREFIX_BY_NORMALIZED = new Map([...CONFIG_PREFIXES].map((prefix) => [normalizeKey(prefix), prefix]));
1237
+ function normalizeKey(key) {
1238
+ return key.replace(/[-_.]/g, "").toLowerCase();
1239
+ }
1240
+ function groupBooleanKey(path) {
1241
+ if (!CONFIG_PREFIXES.has(path)) return void 0;
1242
+ return CONFIG_BY_PATH.get(`${path}.enabled`);
1243
+ }
1244
+ function nearestName(name, candidates) {
1245
+ const target = normalizeKey(name);
1246
+ let best;
1247
+ for (const candidate of candidates) {
1248
+ const distance = editDistance(target, normalizeKey(candidate));
1249
+ if (distance > Math.max(2, Math.floor(target.length / 4))) continue;
1250
+ if (!best || distance < best.distance) best = {
1251
+ name: candidate,
1252
+ distance
1253
+ };
1254
+ }
1255
+ return best?.name;
1256
+ }
1257
+ function suggestKey(key) {
1258
+ const exact = BY_NORMALIZED.get(normalizeKey(key));
1259
+ if (exact) return exact.path;
1260
+ const near = nearestName(key, CONFIG_KEYS.map((k) => k.path));
1261
+ if (near) return near;
1262
+ const tail = normalizeKey(key);
1263
+ const owners = CONFIG_KEYS.filter((k) => normalizeKey(k.path.slice(k.path.lastIndexOf(".") + 1)) === tail);
1264
+ return owners.length === 1 ? owners[0].path : void 0;
1265
+ }
1266
+ function canonicalSpelling(name) {
1267
+ const norm$1 = normalizeKey(name);
1268
+ const key = BY_NORMALIZED.get(norm$1);
1269
+ if (key) return { key: key.path };
1270
+ const group$1 = CHILDREN_BY_NORMALIZED.get(norm$1);
1271
+ return group$1 && group$1.length > 0 ? { group: group$1 } : void 0;
1272
+ }
1273
+ function editDistance(a, b) {
1274
+ const prev = new Array(b.length + 1);
1275
+ const next = new Array(b.length + 1);
1276
+ for (let j = 0; j <= b.length; j++) prev[j] = j;
1277
+ for (let i = 1; i <= a.length; i++) {
1278
+ next[0] = i;
1279
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(prev[j] + 1, next[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
1280
+ for (let j = 0; j <= b.length; j++) prev[j] = next[j];
1281
+ }
1282
+ return prev[b.length];
1283
+ }
1284
+ const DOCS_URL = "https://www.afterpack.dev/docs/config";
1285
+ function unknownKeyMessage(path, surface) {
1286
+ const group$1 = CHILDREN_BY_NORMALIZED.get(normalizeKey(path));
1287
+ if (group$1 && group$1.length > 0) {
1288
+ const list = group$1.map((child) => `\`${child}\``).join(", ");
1289
+ const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1290
+ const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1291
+ const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1292
+ const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1293
+ return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1294
+ }
1295
+ const suggestion = suggestKey(path);
1296
+ const tail = suggestion ? ` — did you mean \`${suggestion}\`?` : ` — see ${DOCS_URL}`;
1297
+ return `unknown configuration key \`${path}\` (${surface})${tail}`;
1298
+ }
1299
+ function isPlainObject(value) {
1300
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1301
+ }
1302
+ function describe(item) {
1303
+ switch (item.kind) {
1304
+ case "boolean": return "true or false";
1305
+ case "number": return item.integer ? `an integer >= ${item.min}` : `a number >= ${item.min}`;
1306
+ case "unbounded": return `a number >= ${item.min}, or the string "${item.unlimited}"`;
1307
+ case "string": return "a string";
1308
+ case "enum": return `one of: ${item.values.join(", ")}`;
1309
+ case "seed": return "a number, any string, or \"git\"";
1310
+ case "reserved": return "a name, or { \"glob\": \"…\", \"names\": [\"…\"] }";
1311
+ case "region": return "an object with numeric `start` and `end`";
1312
+ }
1313
+ }
1314
+ function misdirectedHint(key, value, spell) {
1315
+ const other = misdirectedTo(key, value);
1316
+ if (!other) return "";
1317
+ const written = spell(other.path, String(value));
1318
+ return ` — \`${String(value)}\` is a \`${other.path}\` value; write \`${written}\` instead`;
1319
+ }
1320
+ const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
1321
+ const isTransformKinds = (v) => Array.isArray(v) && v.every((k) => TRANSFORM_KIND_VALUES.includes(k));
1322
+ const KINDS = `a list of: ${TRANSFORM_KIND_VALUES.join(", ")}`;
1323
+ const isNonNegative = (v) => isFiniteNumber(v) && v >= 0;
1324
+ function group(fields) {
1325
+ return {
1326
+ is: isPlainObject,
1327
+ want: "an object",
1328
+ fields
1329
+ };
1330
+ }
1331
+ const REGION_FIELDS = {
1332
+ start: {
1333
+ required: true,
1334
+ is: isFiniteNumber,
1335
+ want: "a number"
1336
+ },
1337
+ end: {
1338
+ required: true,
1339
+ is: isFiniteNumber,
1340
+ want: "a number"
1341
+ },
1342
+ complexity: {
1343
+ is: isNonNegative,
1344
+ want: "a number >= 0"
1345
+ },
1346
+ inflation: group({ max: {
1347
+ is: isNonNegative,
1348
+ want: "a number >= 0"
1349
+ } }),
1350
+ strings: group({ encode: {
1351
+ is: (v) => typeof v === "boolean",
1352
+ want: "true or false"
1353
+ } }),
1354
+ transforms: group({
1355
+ only: {
1356
+ is: isTransformKinds,
1357
+ want: KINDS
1358
+ },
1359
+ deny: {
1360
+ is: isTransformKinds,
1361
+ want: KINDS
1362
+ }
1363
+ }),
1364
+ label: {
1365
+ is: (v) => typeof v === "string",
1366
+ want: "a string"
1367
+ }
1368
+ };
1369
+ const RESERVED_FIELDS = {
1370
+ glob: {
1371
+ required: true,
1372
+ is: (v) => typeof v === "string",
1373
+ want: "a string"
1374
+ },
1375
+ names: {
1376
+ required: true,
1377
+ is: (v) => Array.isArray(v) && v.every((n) => typeof n === "string"),
1378
+ want: "a list of names"
1379
+ }
1380
+ };
1381
+ function leafNames(spec, prefix) {
1382
+ return Object.entries(spec).flatMap(([name, field]) => field.fields ? leafNames(field.fields, `${prefix}${name}.`) : [prefix + name]);
1383
+ }
1384
+ function checkFields(spec, value, prefix = "") {
1385
+ for (const name of Object.keys(value)) {
1386
+ if (name in spec) continue;
1387
+ const near = nearestName(prefix + name, Object.keys(spec).map((n) => prefix + n));
1388
+ return `item has an unknown field \`${prefix}${name}\`` + (near ? ` — did you mean \`${near}\`?` : "") + ` (allowed: ${leafNames(spec, prefix).join(", ")})`;
1389
+ }
1390
+ for (const [name, field] of Object.entries(spec)) {
1391
+ const present = value[name];
1392
+ if (present === void 0) {
1393
+ if (field.required) return `item is missing \`${prefix}${name}\` (${field.want})`;
1394
+ continue;
1395
+ }
1396
+ if (!field.is(present)) return `item's \`${prefix}${name}\` must be ${field.want}, got ${JSON.stringify(present)}`;
1397
+ if (field.fields) {
1398
+ const nested = checkFields(field.fields, present, `${prefix}${name}.`);
1399
+ if (nested) return nested;
1400
+ }
1401
+ }
1402
+ return void 0;
1403
+ }
1404
+ function expected(item, value) {
1405
+ return `expected ${describe(item)}, got ${JSON.stringify(value)}`;
1406
+ }
1407
+ function checkItem(item, value) {
1408
+ switch (item.kind) {
1409
+ case "boolean": return typeof value === "boolean" ? void 0 : expected(item, value);
1410
+ case "number": {
1411
+ if (typeof value !== "number" || !Number.isFinite(value)) return expected(item, value);
1412
+ if (value < item.min) return expected(item, value);
1413
+ if (item.integer && !Number.isInteger(value)) return expected(item, value);
1414
+ return void 0;
1415
+ }
1416
+ case "unbounded": {
1417
+ if (value === item.unlimited) return void 0;
1418
+ if (typeof value === "number" && Number.isFinite(value) && value >= item.min) return void 0;
1419
+ return `${expected(item, value)} — there is no \`Infinity\` in JSON; write "${item.unlimited}"`;
1420
+ }
1421
+ case "string": return typeof value === "string" ? void 0 : expected(item, value);
1422
+ case "enum": return typeof value === "string" && item.values.includes(value) ? void 0 : expected(item, value);
1423
+ case "seed": return typeof value === "number" || typeof value === "string" ? void 0 : expected(item, value);
1424
+ case "reserved": {
1425
+ if (typeof value === "string") return void 0;
1426
+ if (!isPlainObject(value)) return expected(item, value);
1427
+ return checkFields(RESERVED_FIELDS, value);
1428
+ }
1429
+ case "region": {
1430
+ if (!isPlainObject(value)) return expected(item, value);
1431
+ return checkFields(REGION_FIELDS, value);
1432
+ }
1433
+ }
1434
+ }
1435
+ function checkValue(key, value) {
1436
+ if (key.shape === "scalar") {
1437
+ const failure = checkItem(key.item, value);
1438
+ return failure ? `\`${key.path}\`: ${failure}` : void 0;
1439
+ }
1440
+ if (!Array.isArray(value)) return `\`${key.path}\`: expected a list of values, got ${JSON.stringify(value)}`;
1441
+ for (const entry of value) {
1442
+ const failure = checkItem(key.item, entry);
1443
+ if (failure) return `\`${key.path}\`: ${failure}`;
1444
+ }
1445
+ return void 0;
1446
+ }
1447
+ function misdirectedTo(key, value) {
1448
+ if (key.namedValuesOf === void 0 || typeof value !== "string") return void 0;
1449
+ const other = CONFIG_BY_PATH.get(key.namedValuesOf);
1450
+ if (!other || other.shape !== "scalar") return void 0;
1451
+ return checkItem(other.item, value) === void 0 ? other : void 0;
1452
+ }
1453
+ function validateConfig(input, surface) {
1454
+ const issues = [];
1455
+ const config = {};
1456
+ if (input === void 0 || input === null) return {
1457
+ config,
1458
+ issues
1459
+ };
1460
+ if (!isPlainObject(input)) {
1461
+ issues.push({
1462
+ path: "",
1463
+ message: `configuration (${surface}) must be an object`
1464
+ });
1465
+ return {
1466
+ config,
1467
+ issues
1468
+ };
1469
+ }
1470
+ walk(input, "", config, issues, surface);
1471
+ return {
1472
+ config,
1473
+ issues
1474
+ };
1475
+ }
1476
+ function walk(source, prefix, target, issues, surface) {
1477
+ for (const [name, value] of Object.entries(source)) {
1478
+ if (value === void 0) continue;
1479
+ const path = prefix ? `${prefix}.${name}` : name;
1480
+ const key = CONFIG_BY_PATH.get(path);
1481
+ if (key) {
1482
+ const failure = checkValue(key, value);
1483
+ if (failure) {
1484
+ const hint = misdirectedHint(key, value, (p, v) => `"${p}": ${JSON.stringify(v)}`);
1485
+ issues.push({
1486
+ path,
1487
+ message: `${failure} (${surface})${hint}`
1488
+ });
1489
+ } else target[name] = value;
1490
+ continue;
1491
+ }
1492
+ if (CONFIG_PREFIXES.has(path)) {
1493
+ if (isPlainObject(value)) {
1494
+ const nested = {};
1495
+ walk(value, path, nested, issues, surface);
1496
+ if (Object.keys(nested).length > 0) target[name] = nested;
1497
+ continue;
1498
+ }
1499
+ const enabled = groupBooleanKey(path);
1500
+ if (enabled && typeof value === "boolean") {
1501
+ target[name] = { enabled: value };
1502
+ continue;
1503
+ }
1504
+ }
1505
+ issues.push({
1506
+ path,
1507
+ message: unknownKeyMessage(path, surface)
1508
+ });
1509
+ }
1510
+ }
1511
+ function deepMerge(base, override) {
1512
+ const out = { ...base };
1513
+ for (const [name, value] of Object.entries(override)) {
1514
+ if (value === void 0) continue;
1515
+ const existing = out[name];
1516
+ out[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
1517
+ }
1518
+ return out;
1519
+ }
1520
+ function mergeInto(base, override) {
1521
+ return deepMerge(base, override);
1522
+ }
1523
+ function mergeConfig(base, override) {
1524
+ return deepMerge(base, override);
1525
+ }
1526
+ function getPath(config, path) {
1527
+ let current = config;
1528
+ for (const part of path.split(".")) {
1529
+ if (!isPlainObject(current)) return void 0;
1530
+ current = current[part];
1531
+ }
1532
+ return current;
1533
+ }
1534
+ function nest(path, value) {
1535
+ return path.split(".").reduceRight((inner, segment) => ({ [segment]: inner }), value);
1536
+ }
1537
+ function setPath(target, path, value) {
1538
+ const parts = path.split(".");
1539
+ let node = target;
1540
+ for (const part of parts.slice(0, -1)) {
1541
+ if (!isPlainObject(node[part])) node[part] = {};
1542
+ node = node[part];
1543
+ }
1544
+ node[parts[parts.length - 1]] = value;
1545
+ }
1546
+ function toEngineConfig(config) {
1547
+ const out = {};
1548
+ for (const key of CONFIG_KEYS) {
1549
+ if (key.surface !== "engine") continue;
1550
+ const value = getPath(config, key.path);
1551
+ if (value === void 0) continue;
1552
+ setPath(out, key.path, value);
1553
+ }
1554
+ return out;
1555
+ }
1556
+ function toPluginOptions(config) {
1557
+ const read = (path) => getPath(config, path);
1558
+ const set = (container) => Object.values(container).some((v) => v !== void 0) ? container : void 0;
1559
+ return {
1560
+ artifactOptions: {
1561
+ protectionMap: set({ enabled: read("protectionMap.enabled") }),
1562
+ sourceMap: set({
1563
+ enabled: read("sourceMap.enabled"),
1564
+ emitUrl: read("sourceMap.emitUrl")
1565
+ }),
1566
+ build: set({
1567
+ backup: read("build.backup"),
1568
+ mode: read("build.mode")
1569
+ }),
1570
+ allowUnobfuscated: read("allowUnobfuscated"),
1571
+ telemetry: set({ enabled: read("telemetry.enabled") })
1572
+ },
1573
+ seed: read("seed"),
1574
+ preset: read("preset"),
1575
+ complexity: read("complexity"),
1576
+ regions: read("regions"),
1577
+ directives: {
1578
+ enabled: read("directives.enabled") ?? DIRECTIVES_ENABLED_DEFAULT,
1579
+ explicit: read("directives.enabled") !== void 0
1580
+ },
1581
+ build: set({ autorun: read("build.autorun") }),
1582
+ diagnostics: set({
1583
+ level: read("diagnostics.level"),
1584
+ format: read("diagnostics.format")
1585
+ }),
1586
+ paths: set({ include: read("paths.include") }),
1587
+ key: read("key")
1588
+ };
1589
+ }
1590
+
1591
+ //#endregion
1592
+ //#region src/compat.ts
1593
+ const MIN_CORE_VERSION = "0.1.0";
1594
+ const CORE_PACKAGE = "@afterpack/core";
1595
+ const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1596
+ const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
1597
+ function safeVersionString(value) {
1598
+ return typeof value === "string" && VERSION_PATTERN$1.test(value) ? value : null;
1599
+ }
1600
+ function readPackageJson(path) {
1601
+ try {
1602
+ return JSON.parse(readFileSync(path, "utf8"));
1603
+ } catch {
1604
+ return null;
1605
+ }
1606
+ }
1607
+ function ownPackage(moduleUrl) {
1608
+ try {
1609
+ const path = findUpward(dirname(fileURLToPath(moduleUrl)), "package.json");
1610
+ const pkg = path ? readPackageJson(path) : null;
1611
+ if (!pkg || typeof pkg.name !== "string" || !PACKAGE_NAME_PATTERN.test(pkg.name)) return null;
1612
+ const version = safeVersionString(pkg.version);
1613
+ return version ? {
1614
+ name: pkg.name,
1615
+ version
1616
+ } : null;
1617
+ } catch {
1618
+ return null;
1619
+ }
1620
+ }
1621
+ function installedCoreVersion(moduleUrl) {
1622
+ try {
1623
+ const path = createRequire(moduleUrl).resolve(`${CORE_PACKAGE}/package.json`);
1624
+ const pkg = readPackageJson(path);
1625
+ return pkg?.name === CORE_PACKAGE ? safeVersionString(pkg.version) : null;
1626
+ } catch {
1627
+ return null;
1628
+ }
1629
+ }
1630
+ const identities = new Map();
1631
+ function resolveClientIdentity(moduleUrl) {
1632
+ const key = String(moduleUrl);
1633
+ const cached = identities.get(key);
1634
+ if (cached) return cached;
1635
+ const own = ownPackage(moduleUrl);
1636
+ const identity = {
1637
+ packageName: own?.name ?? null,
1638
+ packageVersion: own?.version ?? null,
1639
+ coreVersion: installedCoreVersion(moduleUrl)
1640
+ };
1641
+ identities.set(key, identity);
1642
+ return identity;
1643
+ }
1644
+ function clientString(identity) {
1645
+ if (!identity?.packageName || !identity.packageVersion) return null;
1646
+ return `${identity.packageName}/${identity.packageVersion}`;
1647
+ }
1648
+ function releaseTriple(version) {
1649
+ if (typeof version !== "string") return null;
1650
+ const match = /^(\d{1,9})\.(\d{1,9})\.(\d{1,9})(?:[-+].*)?$/.exec(version.trim());
1651
+ if (!match) return null;
1652
+ return [
1653
+ Number(match[1]),
1654
+ Number(match[2]),
1655
+ Number(match[3])
1656
+ ];
1657
+ }
1658
+ function isBelowVersion(version, minimum) {
1659
+ const have = releaseTriple(version);
1660
+ const need = releaseTriple(minimum);
1661
+ if (!have || !need) return false;
1662
+ for (let i = 0; i < 3; i++) if (have[i] !== need[i]) return have[i] < need[i];
1663
+ return false;
1664
+ }
1665
+ const CLI_PACKAGE = "afterpack";
1666
+ function updateCommand(identity, minVersion) {
1667
+ const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
1668
+ const name = identity?.packageName;
1669
+ return name && name !== CORE_PACKAGE ? `npm install ${name}@latest ${core}` : `npm install ${core}`;
1670
+ }
1671
+ function npxAlternative(identity) {
1672
+ return identity?.packageName === CLI_PACKAGE ? `npx ${CLI_PACKAGE}@latest` : null;
1673
+ }
1674
+ const CLOUD_REFUSAL_SUMMARY = "This version of AfterPack is no longer supported by the AfterPack cloud.";
1675
+ const CORE_FLOOR_SUMMARY = "@afterpack/core is too old to protect this build — update @afterpack/core.";
1676
+ function requiredText(minVersion) {
1677
+ return minVersion ? `${minVersion} or newer` : "a newer release";
1678
+ }
1679
+ function installedRequiredLine(installed, minVersion) {
1680
+ const required = requiredText(minVersion);
1681
+ return installed ? `Installed ${CORE_PACKAGE} ${installed} · required ${required}` : `Required ${CORE_PACKAGE} ${required}`;
1682
+ }
1683
+ const TOKEN_STOPWORDS = new Set([
1684
+ "this",
1685
+ "is",
1686
+ "are",
1687
+ "a",
1688
+ "an",
1689
+ "the",
1690
+ "by",
1691
+ "to",
1692
+ "of",
1693
+ "or",
1694
+ "no",
1695
+ "longer",
1696
+ "required",
1697
+ "version",
1698
+ "newer",
1699
+ "for",
1700
+ "that"
1701
+ ]);
1702
+ function meaningfulTokens(text) {
1703
+ const tokens = text.toLowerCase().split(/[^a-z0-9.]+/);
1704
+ return new Set(tokens.filter((token) => token.length > 0 && !TOKEN_STOPWORDS.has(token)));
1705
+ }
1706
+ function serverAddsInfo(serverMessage, shownText) {
1707
+ const serverTokens = meaningfulTokens(serverMessage);
1708
+ if (serverTokens.size === 0) return false;
1709
+ const shownTokens = meaningfulTokens(shownText);
1710
+ let novel = 0;
1711
+ for (const token of serverTokens) if (!shownTokens.has(token)) novel++;
1712
+ return novel / serverTokens.size > .25;
1713
+ }
1714
+ function refusalLines(input) {
1715
+ const installedLine = installedRequiredLine(input.installed, input.minVersion);
1716
+ const lines = [
1717
+ input.summary,
1718
+ installedLine,
1719
+ input.fix
1720
+ ];
1721
+ if (input.npxAlt) lines.push(`or, without a local install: ${input.npxAlt}`);
1722
+ if (serverAddsInfo(input.serverMessage, `${input.summary} ${installedLine}`)) lines.push(`Server: ${input.serverMessage}`);
1723
+ return lines;
1724
+ }
1725
+ var CoreVersionError = class extends Error {
1726
+ code = "CORE_VERSION_UNSUPPORTED";
1727
+ installed;
1728
+ minimum;
1729
+ fix;
1730
+ constructor(message, installed, minimum, fix) {
1731
+ super(message);
1732
+ this.name = "CoreVersionError";
1733
+ this.installed = installed;
1734
+ this.minimum = minimum;
1735
+ this.fix = fix;
1736
+ }
1737
+ };
1738
+ function assertSupportedCore(identity, prefix = (m) => m) {
1739
+ const installed = identity?.coreVersion ?? null;
1740
+ if (installed === null || !isBelowVersion(installed, MIN_CORE_VERSION)) return;
1741
+ const fix = updateCommand(identity);
1742
+ const lines = refusalLines({
1743
+ summary: CORE_FLOOR_SUMMARY,
1744
+ installed,
1745
+ minVersion: MIN_CORE_VERSION,
1746
+ fix,
1747
+ npxAlt: npxAlternative(identity),
1748
+ serverMessage: ""
1749
+ });
1750
+ throw new CoreVersionError(prefix(lines.join("\n")), installed, MIN_CORE_VERSION, fix);
1751
+ }
1752
+ const CLOUD_UPGRADE_REQUIRED = "AFTERPACK_CLOUD_UPGRADE_REQUIRED";
1753
+ const CLOUD_SUNSET = "AFTERPACK_CLOUD_SUNSET";
1754
+ const CLOUD_API = "AFTERPACK_CLOUD_API";
1755
+ const KIND_BY_CODE = {
1756
+ [CLOUD_UPGRADE_REQUIRED]: "upgradeRequired",
1757
+ [CLOUD_SUNSET]: "sunset",
1758
+ [CLOUD_API]: "api"
1759
+ };
1760
+ const API_CODE_LIMIT = 64;
1761
+ var CloudApiError = class extends Error {
1762
+ code;
1763
+ kind;
1764
+ apiCode;
1765
+ apiMessage;
1766
+ details;
1767
+ notices;
1768
+ minVersion;
1769
+ installed;
1770
+ fix;
1771
+ constructor(input) {
1772
+ super(input.message, { cause: input.cause });
1773
+ this.name = "CloudApiError";
1774
+ this.code = input.code;
1775
+ this.kind = input.kind;
1776
+ this.apiCode = input.apiCode;
1777
+ this.apiMessage = input.apiMessage;
1778
+ this.details = input.details;
1779
+ this.notices = input.notices;
1780
+ this.minVersion = input.minVersion;
1781
+ this.installed = input.installed;
1782
+ this.fix = input.fix;
1783
+ }
1784
+ };
1785
+ function refusalApiCode(diagnostics) {
1786
+ if (!Array.isArray(diagnostics)) return null;
1787
+ for (const d of diagnostics) {
1788
+ if (!isPlainObject(d)) continue;
1789
+ const code = sanitizeServerText(d.code, API_CODE_LIMIT);
1790
+ if (code !== "") return code;
1791
+ }
1792
+ return null;
1793
+ }
1794
+ function readCloudErrorBody(error) {
1795
+ return {
1796
+ code: refusalApiCode(error.diagnostics),
1797
+ message: sanitizeServerText(error.message),
1798
+ details: isPlainObject(error.details) ? error.details : null,
1799
+ notices: Array.isArray(error.notices) ? error.notices : null
1800
+ };
1801
+ }
1802
+ function describeCloudFailure(kind, body, minVersion, identity, fix) {
1803
+ if (kind === "api") {
1804
+ if (!body.code && body.message.startsWith("cloud obfuscation failed")) return body.message;
1805
+ const code = body.code ? `${body.code}: ` : "";
1806
+ return `cloud obfuscation failed: ${code}${body.message || "the API refused the request"}`;
1807
+ }
1808
+ return refusalLines({
1809
+ summary: CLOUD_REFUSAL_SUMMARY,
1810
+ installed: identity?.coreVersion ?? null,
1811
+ minVersion,
1812
+ fix,
1813
+ npxAlt: npxAlternative(identity),
1814
+ serverMessage: body.message
1815
+ }).join("\n");
1816
+ }
1817
+ function toCloudApiError(error, options = {}) {
1818
+ if (!isPlainObject(error) && !(error instanceof Error)) return null;
1819
+ const code = error.code;
1820
+ if (typeof code !== "string") return null;
1821
+ const kind = KIND_BY_CODE[code];
1822
+ if (!kind) return null;
1823
+ const body = readCloudErrorBody(error);
1824
+ const minVersion = safeVersionString(body.details?.minVersion);
1825
+ const prefix = options.prefix ?? ((m) => m);
1826
+ const fix = updateCommand(options.identity, minVersion);
1827
+ return new CloudApiError({
1828
+ message: prefix(describeCloudFailure(kind, body, minVersion, options.identity, fix)),
1829
+ code,
1830
+ kind,
1831
+ apiCode: body.code,
1832
+ apiMessage: body.message,
1833
+ details: body.details,
1834
+ notices: sanitizeNotices(body.notices),
1835
+ minVersion,
1836
+ installed: options.identity?.coreVersion ?? null,
1837
+ fix,
1838
+ cause: error
1839
+ });
1840
+ }
1841
+
1842
+ //#endregion
1843
+ //#region src/config-file.ts
1844
+ const CONFIG_FILE_NAME = "afterpack.json";
1845
+ function findConfigFile(startDir) {
1846
+ return findUpward(startDir, CONFIG_FILE_NAME);
1847
+ }
1848
+ function loadConfigFile(startDir) {
1849
+ const path = findConfigFile(startDir);
1850
+ if (!path) return {
1851
+ path: null,
1852
+ config: EMPTY_CONFIG,
1853
+ issues: []
1854
+ };
1855
+ let raw;
1856
+ try {
1857
+ raw = JSON.parse(readFileSync(path, "utf8"));
1858
+ } catch (error) {
1859
+ const detail = error instanceof Error ? error.message : String(error);
1860
+ return {
1861
+ path,
1862
+ config: EMPTY_CONFIG,
1863
+ issues: [{
1864
+ path: CONFIG_FILE_NAME,
1865
+ message: `${path} is not valid JSON: ${detail}`
1866
+ }]
1867
+ };
1868
+ }
1869
+ const { config, issues } = validateConfig(raw, path);
1870
+ return {
1871
+ path,
1872
+ config,
1873
+ issues
1874
+ };
1875
+ }
1876
+
1877
+ //#endregion
1878
+ //#region src/config-parse.ts
1879
+ const ENV_PREFIX = "AFTERPACK_";
1880
+ function splitAssignment(token) {
1881
+ const eq = token.indexOf("=");
1882
+ if (eq < 0) return {
1883
+ key: token,
1884
+ value: true
1885
+ };
1886
+ return {
1887
+ key: token.slice(0, eq),
1888
+ value: token.slice(eq + 1)
1889
+ };
1890
+ }
1891
+ function parseScalarLiteral(raw) {
1892
+ try {
1893
+ return JSON.parse(raw);
1894
+ } catch {
1895
+ return raw;
1896
+ }
1897
+ }
1898
+ function parseListLiteral(raw) {
1899
+ const whole = parseScalarLiteral(raw);
1900
+ if (Array.isArray(whole)) return { json: whole };
1901
+ if (raw.trim() === "") return { items: [] };
1902
+ const parts = raw.split(",").map((part) => part.trim());
1903
+ if (parts.some((part) => part === "")) return { empty: true };
1904
+ return { items: parts.map(parseScalarLiteral) };
1905
+ }
1906
+ function spellKey(path, surface) {
1907
+ if (surface === "cli") return `--${path}`;
1908
+ if (surface === "env") return `${ENV_PREFIX}${path.replace(/\./g, "_")}`;
1909
+ return path;
1910
+ }
1911
+ function surfaceLabel(surface) {
1912
+ if (surface === "cli") return "command line";
1913
+ if (surface === "env") return "environment";
1914
+ return "directive";
1915
+ }
1916
+ function fileFormCta(key) {
1917
+ return key.configFileForm ?? `{ "${key.path.split(".").join("\": { \"")}": … }`;
1918
+ }
1919
+ function structuredIssue(key, surface) {
1920
+ return {
1921
+ path: key.path,
1922
+ message: `\`${key.path}\` is an object and cannot be written on the ${surfaceLabel(surface)}. Move it to afterpack.json: ${fileFormCta(key)}`
1923
+ };
1924
+ }
1925
+ function objectItemIssue(key, surface) {
1926
+ return {
1927
+ path: key.path,
1928
+ message: `\`${key.path}\` takes plain comma-separated values on the ${surfaceLabel(surface)}; an object item must move to afterpack.json: ${fileFormCta(key)}`
1929
+ };
1930
+ }
1931
+ function jsonArrayIssue(key, items, surface) {
1932
+ const flat = items.every((v) => v !== null && typeof v !== "object");
1933
+ const spelled = spellKey(key.path, surface);
1934
+ const how = flat ? `write \`${spelled}=${items.map(String).join(",")}\`${items.length === 0 ? " for an empty list" : ""}` : key.shape === "mixedList" ? `an object item must move to afterpack.json: ${fileFormCta(key)}` : `write \`${spelled}=<value>,<value>\``;
1935
+ return {
1936
+ path: key.path,
1937
+ message: `\`${key.path}\` takes comma-separated values on the ${surfaceLabel(surface)}, not a JSON array — ${how}`
1938
+ };
1939
+ }
1940
+ function spaceFormIssue(path, raw, surface) {
1941
+ const spelled = spellKey(path, surface);
1942
+ return {
1943
+ path,
1944
+ message: `\`${spelled} ${raw}\` is not a flag — the space-separated form was removed; write \`${spelled}=${raw}\``
1945
+ };
1946
+ }
1947
+ function kebabIssue(key, surface) {
1948
+ const suggestion = suggestKey(key);
1949
+ const canonical = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
1950
+ return {
1951
+ path: key,
1952
+ message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical}`
1953
+ };
1954
+ }
1955
+ function parseAssignment(key, raw, surface) {
1956
+ const spaced = raw === true ? /^(\S+)[ \t]+(.+)$/.exec(key) : null;
1957
+ const head = spaced ? CONFIG_BY_PATH.get(spaced[1]) : void 0;
1958
+ if (spaced && head) return { issue: head.shape === "structured" ? structuredIssue(head, surface) : spaceFormIssue(head.path, spaced[2], surface) };
1959
+ if (key.includes("-")) return { issue: kebabIssue(key, surface) };
1960
+ const grouped = CONFIG_BY_PATH.has(key) ? void 0 : groupBooleanKey(key);
1961
+ const boolish = raw === true || typeof parseScalarLiteral(raw) === "boolean";
1962
+ const path = grouped && boolish ? grouped.path : key;
1963
+ const def = CONFIG_BY_PATH.get(path);
1964
+ if (!def) return { issue: {
1965
+ path: key,
1966
+ message: unknownKeyMessage(key, surfaceLabel(surface))
1967
+ } };
1968
+ if (def.shape === "structured") return { issue: structuredIssue(def, surface) };
1969
+ if (raw === true) {
1970
+ const failure$1 = checkValue(def, true);
1971
+ return failure$1 ? { issue: {
1972
+ path: key,
1973
+ message: `${failure$1} (${surfaceLabel(surface)})`
1974
+ } } : { assignment: {
1975
+ path,
1976
+ value: true
1977
+ } };
1978
+ }
1979
+ if (def.shape === "mixedList" && raw.includes("{")) return { issue: objectItemIssue(def, surface) };
1980
+ let value;
1981
+ if (def.shape === "scalar") value = parseScalarLiteral(raw);
1982
+ else {
1983
+ const parsed = parseListLiteral(raw);
1984
+ if ("json" in parsed) return { issue: jsonArrayIssue(def, parsed.json, surface) };
1985
+ if ("empty" in parsed) return { issue: {
1986
+ path: key,
1987
+ message: `\`${key}\` has an empty item in its comma-separated value (${surfaceLabel(surface)}) — write the items with no stray comma, or omit the key entirely`
1988
+ } };
1989
+ value = parsed.items;
1990
+ }
1991
+ const failure = checkValue(def, value);
1992
+ if (failure) {
1993
+ const hint = misdirectedHint(def, value, (p, v) => `${spellKey(p, surface)}=${v}`);
1994
+ return { issue: {
1995
+ path: key,
1996
+ message: `${failure} (${surfaceLabel(surface)})${hint}`
1997
+ } };
1998
+ }
1999
+ return { assignment: {
2000
+ path,
2001
+ value
2002
+ } };
2003
+ }
2004
+ function collect(assignments) {
2005
+ let config = EMPTY_CONFIG;
2006
+ for (const a of assignments) config = mergeConfig(config, nest(a.path, a.value));
2007
+ return config;
2008
+ }
2009
+ function parseCliOptions(argv) {
2010
+ const assignments = [];
2011
+ const issues = [];
2012
+ const positionals = [];
2013
+ let help = false;
2014
+ let version = false;
2015
+ for (let i = 0; i < argv.length; i++) {
2016
+ const token = argv[i];
2017
+ if (!token.startsWith("-")) {
2018
+ positionals.push(token);
2019
+ continue;
2020
+ }
2021
+ if (token === "--help") {
2022
+ help = true;
2023
+ continue;
2024
+ }
2025
+ if (token === "--version") {
2026
+ version = true;
2027
+ continue;
2028
+ }
2029
+ if (!token.startsWith("--") || token === "--") {
2030
+ issues.push({
2031
+ path: token,
2032
+ message: `\`${token}\` is not a flag — every option is written \`--key=value\` (no short flags)`
2033
+ });
2034
+ continue;
2035
+ }
2036
+ const { key, value } = splitAssignment(token.slice(2));
2037
+ const def = value === true ? CONFIG_BY_PATH.get(key) : void 0;
2038
+ const next = argv[i + 1];
2039
+ if (def !== void 0 && def.shape !== "structured" && next !== void 0 && !next.startsWith("-") && checkValue(def, true) !== void 0) {
2040
+ issues.push(spaceFormIssue(key, next, "cli"));
2041
+ const retry = parseAssignment(key, next, "cli");
2042
+ if ("issue" in retry) issues.push(retry.issue);
2043
+ i++;
2044
+ continue;
2045
+ }
2046
+ const parsed = parseAssignment(key, value, "cli");
2047
+ if ("issue" in parsed) issues.push(parsed.issue);
2048
+ else assignments.push(parsed.assignment);
2049
+ }
2050
+ return {
2051
+ config: collect(assignments),
2052
+ positionals,
2053
+ help,
2054
+ version,
2055
+ issues
2056
+ };
2057
+ }
2058
+ const LIVE_SCREAMING_ENV = new Set(["SEED", "KEY"]);
2059
+ function screamingIssue(name, suffix) {
2060
+ const dotted = suffix.replace(/_/g, ".");
2061
+ const envForm = (path) => `${ENV_PREFIX}${path.replace(/\./g, "_")}`;
2062
+ const spelling = canonicalSpelling(dotted);
2063
+ let tail = `see ${DOCS_URL}`;
2064
+ if (spelling && "key" in spelling) tail = `write \`${envForm(spelling.key)}\``;
2065
+ else if (spelling && spelling.group.length === 1) tail = `write \`${envForm(spelling.group[0])}\``;
2066
+ else if (spelling) tail = `its keys are ${spelling.group.map((k) => `\`${envForm(k)}\``).join(", ")}`;
2067
+ return {
2068
+ path: suffix,
2069
+ message: `\`${name}\` is not a configuration variable — an AfterPack variable spells its key exactly, dots as underscores and case preserved: ${tail}`
2070
+ };
2071
+ }
2072
+ function isReservedEnvSuffix(suffix) {
2073
+ if (/[a-z]/.test(suffix)) return false;
2074
+ const dotted = suffix.replace(/_/g, ".");
2075
+ return LIVE_SCREAMING_ENV.has(suffix) || canonicalSpelling(dotted) === void 0;
2076
+ }
2077
+ function parseEnvOptions(env) {
2078
+ const assignments = [];
2079
+ const issues = [];
2080
+ for (const name of Object.keys(env).sort()) {
2081
+ if (!name.startsWith(ENV_PREFIX)) continue;
2082
+ const suffix = name.slice(ENV_PREFIX.length);
2083
+ if (suffix === "" || isReservedEnvSuffix(suffix)) continue;
2084
+ const raw = env[name];
2085
+ if (raw === void 0) continue;
2086
+ if (!/[a-z]/.test(suffix)) {
2087
+ issues.push(screamingIssue(name, suffix));
2088
+ continue;
2089
+ }
2090
+ const parsed = parseAssignment(suffix.replace(/_/g, "."), raw, "env");
2091
+ if ("issue" in parsed) issues.push(parsed.issue);
2092
+ else assignments.push(parsed.assignment);
2093
+ }
2094
+ return {
2095
+ config: collect(assignments),
2096
+ issues
2097
+ };
2098
+ }
2099
+
2100
+ //#endregion
2101
+ //#region src/diagnostics.ts
2102
+ const ISSUES_URL = "https://github.com/afterpack-dev/afterpack/issues";
2103
+ const MAX_INSTANCES_PER_CODE = 5;
2104
+ const DIAGNOSTIC_MESSAGE_LIMIT = 4e3;
2105
+ const MAX_CODES_IN_SUMMARY = 6;
2106
+ const SEVERITY_RANK = {
2107
+ critical: 0,
2108
+ error: 1,
2109
+ info: 2
2110
+ };
2111
+ function isEngineDiagnostic(value) {
2112
+ if (typeof value !== "object" || value === null) return false;
2113
+ const d = value;
2114
+ return typeof d.severity === "string" && typeof d.message === "string" && typeof d.code === "string";
2115
+ }
2116
+ const DIAGNOSTIC_CODE_LIMIT = 64;
2117
+ const DIAGNOSTIC_SEVERITY_LIMIT = 16;
2118
+ const DIAGNOSTIC_FIELD_LIMIT = 500;
2119
+ function sanitizeSpan(span) {
2120
+ if (typeof span !== "object" || span === null) return null;
2121
+ const { startByte, endByte } = span;
2122
+ if (typeof startByte !== "number" || typeof endByte !== "number") return null;
2123
+ if (!Number.isFinite(startByte) || !Number.isFinite(endByte)) return null;
2124
+ return {
2125
+ startByte,
2126
+ endByte
2127
+ };
2128
+ }
2129
+ function sanitizeData(data) {
2130
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
2131
+ const out = {};
2132
+ for (const [key, value] of Object.entries(data)) {
2133
+ const safeKey = sanitizeServerText(key, DIAGNOSTIC_CODE_LIMIT);
2134
+ if (safeKey === "") continue;
2135
+ out[safeKey] = typeof value === "string" ? sanitizeServerText(value, DIAGNOSTIC_FIELD_LIMIT) : value;
2136
+ }
2137
+ return typeof out.kind === "string" ? out : null;
2138
+ }
2139
+ function sanitizeDiagnostic(d) {
2140
+ const out = {
2141
+ ...d,
2142
+ severity: sanitizeServerText(d.severity, DIAGNOSTIC_SEVERITY_LIMIT),
2143
+ code: sanitizeServerText(d.code, DIAGNOSTIC_CODE_LIMIT)
2144
+ };
2145
+ if (d.file != null) out.file = sanitizeServerText(d.file, DIAGNOSTIC_FIELD_LIMIT) || null;
2146
+ if (d.span != null) out.span = sanitizeSpan(d.span);
2147
+ if (d.data != null) out.data = sanitizeData(d.data);
2148
+ return out;
2149
+ }
2150
+ function sanitizeEngineDiagnostics(value) {
2151
+ if (value == null) return null;
2152
+ if (!Array.isArray(value)) return null;
2153
+ const diagnostics = value.filter(isEngineDiagnostic).map(sanitizeDiagnostic);
2154
+ return {
2155
+ diagnostics,
2156
+ malformed: value.length - diagnostics.length
2157
+ };
2158
+ }
2159
+ function collectDiagnostics(files) {
2160
+ const diagnostics = [];
2161
+ let unknownFiles = 0;
2162
+ let malformedEntries = 0;
2163
+ for (const file of files) {
2164
+ const parsed = sanitizeEngineDiagnostics(file.diagnostics);
2165
+ if (parsed === null) {
2166
+ unknownFiles += 1;
2167
+ continue;
2168
+ }
2169
+ malformedEntries += parsed.malformed;
2170
+ for (const d of parsed.diagnostics) diagnostics.push(d.file || !file.path ? d : {
2171
+ ...d,
2172
+ file: file.path
2173
+ });
2174
+ }
2175
+ return {
2176
+ diagnostics,
2177
+ unknownFiles,
2178
+ malformedEntries
2179
+ };
2180
+ }
2181
+ function resolveDiagnosticsVerbosity(option) {
2182
+ return option ?? "summary";
2183
+ }
2184
+ function formatLocator(d) {
2185
+ const span = d.span ? `bytes ${d.span.startByte}..${d.span.endByte}` : null;
2186
+ if (d.file && span) return `${d.file} ${span}`;
2187
+ return d.file || span;
2188
+ }
2189
+ function formatData(data) {
2190
+ if (!data) return null;
2191
+ const pairs = [];
2192
+ for (const [key, value] of Object.entries(data)) {
2193
+ if (key === "kind" || value === null || value === void 0) continue;
2194
+ const text = sanitizeServerText(String(value), DIAGNOSTIC_FIELD_LIMIT);
2195
+ if (typeof value === "string") pairs.push(`${key}="${text}"`);
2196
+ else if (text !== "") pairs.push(`${key}=${text}`);
2197
+ }
2198
+ return pairs.length > 0 ? pairs.join(" ") : null;
2199
+ }
2200
+ function formatDiagnostic(d) {
2201
+ const parts = [`${d.severity} ${d.code}`];
2202
+ const locator = formatLocator(d);
2203
+ if (locator) parts.push(locator);
2204
+ const message = sanitizeServerText(d.message, DIAGNOSTIC_MESSAGE_LIMIT);
2205
+ if (message) parts.push(message);
2206
+ const data = formatData(d.data);
2207
+ if (data) parts.push(data);
2208
+ return parts.join(" · ");
2209
+ }
2210
+ const DIAG_ALREADY_OBFUSCATED = "DIAG_ALREADY_OBFUSCATED";
2211
+ var AlreadyObfuscatedError = class extends Error {
2212
+ code = DIAG_ALREADY_OBFUSCATED;
2213
+ files;
2214
+ receiptPath;
2215
+ dir;
2216
+ constructor(message, files, receiptPath, dir) {
2217
+ super(message);
2218
+ this.name = "AlreadyObfuscatedError";
2219
+ this.files = files;
2220
+ this.receiptPath = receiptPath;
2221
+ this.dir = dir;
2222
+ }
2223
+ };
2224
+ const ALREADY_OBFUSCATED_FILE_CAP = 10;
2225
+ function formatAlreadyObfuscatedMessage(input) {
2226
+ const { files, receiptPath, dir } = input;
2227
+ const shown = files.slice(0, ALREADY_OBFUSCATED_FILE_CAP);
2228
+ const hidden = files.length - shown.length;
2229
+ const list = hidden > 0 ? `${shown.join(", ")}, and ${hidden} more` : shown.join(", ");
2230
+ return `error ${DIAG_ALREADY_OBFUSCATED} · ${files.length} file(s) already carry AfterPack's obfuscated output from a previous run (matched by content hash against ${receiptPath}): ${list} — rebuild from source before running AfterPack again (delete \`${dir}\` or run your bundler's clean); AfterPack output is not idempotent`;
2231
+ }
2232
+ function summarizeDiagnostics(diagnostics) {
2233
+ const summary = {
2234
+ total: 0,
2235
+ info: 0,
2236
+ error: 0,
2237
+ critical: 0,
2238
+ byCode: {}
2239
+ };
2240
+ for (const d of diagnostics) {
2241
+ summary.total += 1;
2242
+ if (d.severity === "critical" || d.severity === "error" || d.severity === "info") summary[d.severity] += 1;
2243
+ summary.byCode[d.code] = (summary.byCode[d.code] ?? 0) + 1;
2244
+ }
2245
+ return summary;
2246
+ }
2247
+ function groupByCode(diagnostics) {
2248
+ const groups = new Map();
2249
+ for (const d of diagnostics) {
2250
+ const existing = groups.get(d.code);
2251
+ if (existing) existing.push(d);
2252
+ else groups.set(d.code, [d]);
2253
+ }
2254
+ return groups;
2255
+ }
2256
+ function formatInfoSummary(infos) {
2257
+ const byCode = [...groupByCode(infos).entries()].sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
2258
+ const shown = byCode.slice(0, MAX_CODES_IN_SUMMARY);
2259
+ const parts = shown.map(([code, list]) => `${code} x${list.length}`);
2260
+ const hidden = byCode.length - shown.length;
2261
+ if (hidden > 0) parts.push(`+${hidden} more code(s)`);
2262
+ return `${infos.length} info diagnostic(s): ${parts.join(" · ")}`;
2263
+ }
2264
+ function reportDiagnostics(input) {
2265
+ const { diagnostics, logger, prefix } = input;
2266
+ const verbosity = resolveDiagnosticsVerbosity(input.verbosity);
2267
+ const malformedEntries = input.malformedEntries ?? 0;
2268
+ const summary = summarizeDiagnostics(diagnostics);
2269
+ if (malformedEntries > 0) logger.warn(prefix(`${malformedEntries} diagnostic entry/entries did not match the engine's diagnostic contract and were dropped — treat this build's diagnostics as incomplete.`));
2270
+ if (diagnostics.length === 0) return summary;
2271
+ const infos = verbosity === "all" ? diagnostics.filter((d) => d.severity === "info") : [];
2272
+ if (infos.length > 0) {
2273
+ logger.log(prefix(formatInfoSummary(infos)));
2274
+ for (const d of infos) logger.log(prefix(formatDiagnostic(d)));
2275
+ }
2276
+ const loud = diagnostics.filter((d) => d.severity !== "info").sort((a, b) => (SEVERITY_RANK[a.severity] ?? 1) - (SEVERITY_RANK[b.severity] ?? 1));
2277
+ for (const [code, list] of groupByCode(loud)) {
2278
+ const cap = verbosity === "all" ? list.length : MAX_INSTANCES_PER_CODE;
2279
+ for (const d of list.slice(0, cap)) logger.warn(prefix(formatDiagnostic(d)));
2280
+ const hidden = list.length - cap;
2281
+ if (hidden > 0) logger.warn(prefix(`${list[0].severity} ${code} · +${hidden} more occurrence(s) (AFTERPACK_diagnostics_level=all to list them)`));
2282
+ }
2283
+ if (summary.critical > 0) logger.warn(prefix(`${summary.critical} critical diagnostic(s) above are engine bugs — please report them at ${ISSUES_URL}, quoting the code(s).`));
2284
+ return summary;
2285
+ }
2286
+
2287
+ //#endregion
2288
+ //#region src/policy.ts
2289
+ function detectProduction(env = {}, opts = {}) {
2290
+ if (opts.build?.mode !== void 0) return opts.build.mode === "production";
2291
+ return env.NODE_ENV === "production" || env.CI === "true";
2292
+ }
2293
+ function resolveReportPolicy(env = {}, userOpts = {}, signals = {}) {
2294
+ const isProduction = detectProduction(env, userOpts);
2295
+ const hasBundlerSourcemap = signals.hasBundlerSourcemap ?? false;
2296
+ const protectionMap = userOpts.protectionMap?.enabled ?? hasBundlerSourcemap;
2297
+ const autoEnableBundlerSourcemap = userOpts.protectionMap?.enabled === true && !hasBundlerSourcemap;
2298
+ const emitSourceMappingURL = userOpts.sourceMap?.emitUrl ?? !isProduction;
2299
+ const backup = userOpts.build?.backup ?? !signals.inPlaceOutput;
2300
+ const sourceMap = userOpts.sourceMap?.enabled ?? !isProduction;
2301
+ return {
2302
+ isProduction,
2303
+ protectionMap,
2304
+ autoEnableBundlerSourcemap,
2305
+ sourceMap,
2306
+ emitSourceMappingURL,
2307
+ backup,
2308
+ protectionMapInProd: isProduction && protectionMap,
2309
+ engineSourceMapOverride: userOpts.sourceMap?.enabled ?? (isProduction ? false : void 0)
2310
+ };
2311
+ }
2312
+ function resolveSourceMapEnabled(sourceMapOverride, hasInputMap) {
2313
+ if (sourceMapOverride === false) return false;
2314
+ if (sourceMapOverride === true) return true;
2315
+ return hasInputMap;
2316
+ }
2317
+ const PRESETS = PRESET_VALUES;
2318
+ const DEFAULT_PRESET = "light";
2319
+ function presetTarget(preset) {
2320
+ switch (preset) {
2321
+ case "minify": return 0;
2322
+ case "light": return 2;
2323
+ case "medium": return 8;
2324
+ case "hard": return 25;
2325
+ case "extreme": return 80;
2326
+ }
2327
+ }
2328
+ function effectiveComplexityTarget(preset, complexity) {
2329
+ return complexity ?? presetTarget(preset ?? DEFAULT_PRESET);
2330
+ }
2331
+ function buildEngineConfig(options) {
2332
+ const { filePath, policy, seed = 0, engine } = options;
2333
+ const perFileMap = "inputSourceMap" in options;
2334
+ const inputSourceMap = options.inputSourceMap ?? null;
2335
+ const sourcesContent = options.sourcesContent ?? !policy.isProduction;
2336
+ const smEnabled = perFileMap ? resolveSourceMapEnabled(policy.engineSourceMapOverride, inputSourceMap != null) : policy.engineSourceMapOverride;
2337
+ const sourceMap = { sourcesContent };
2338
+ if (smEnabled !== void 0) sourceMap.enabled = smEnabled;
2339
+ const defaults = {};
2340
+ const target = effectiveComplexityTarget(options.preset, options.complexity);
2341
+ if (options.preset !== void 0) defaults.preset = options.preset;
2342
+ if (options.preset === void 0 || options.complexity !== void 0) defaults.complexity = target;
2343
+ const config = mergeInto({
2344
+ ...defaults,
2345
+ sourceMap,
2346
+ protectionMap: { enabled: policy.protectionMap }
2347
+ }, engine ?? {});
2348
+ config.seed = seed;
2349
+ if (options.renameGlobals === true) config.identifiers = {
2350
+ ...config.identifiers,
2351
+ globals: { rename: true }
2352
+ };
2353
+ if (filePath !== void 0) config.filePath = filePath;
2354
+ if (perFileMap && smEnabled && inputSourceMap != null) config.inputSourceMap = inputSourceMap;
2355
+ if (options.regions !== void 0) config.regions = options.regions;
2356
+ return config;
2357
+ }
2358
+ function buildContext(git, client = {}) {
2359
+ const context = {};
2360
+ if (git?.commitSha) context.commitSha = git.commitSha;
2361
+ if (git?.ref) context.ref = git.ref;
2362
+ if (client.clientVersion) context.clientVersion = client.clientVersion;
2363
+ if (client.client) context.client = client.client;
2364
+ return Object.keys(context).length > 0 ? context : void 0;
2365
+ }
2366
+
2367
+ //#endregion
2368
+ //#region src/directives.ts
2369
+ const KIND_BY_LOWER = new Map(TRANSFORM_KIND_VALUES.map((k) => [k.toLowerCase(), k]));
2370
+ function parseKindList(value) {
2371
+ const parts = value.split(",").map((s) => s.trim()).filter(Boolean);
2372
+ if (parts.length === 0) return { error: "empty transform-kind list" };
2373
+ const kinds = [];
2374
+ for (const p of parts) {
2375
+ const k = KIND_BY_LOWER.get(p.toLowerCase());
2376
+ if (!k) return { error: `unknown transform kind \`${p}\`` };
2377
+ kinds.push(k);
2378
+ }
2379
+ return { kinds };
2380
+ }
2381
+ const DIRECTIVE_MARKER = "@afterpack";
2382
+ const UTF8$1 = new TextEncoder();
2383
+ function byteOffset(source, charIndex) {
2384
+ return UTF8$1.encode(source.slice(0, charIndex)).length;
2385
+ }
2386
+ function lineCol(source, charIndex) {
2387
+ let line = 1;
2388
+ let lineStart = 0;
2389
+ for (let i = 0; i < charIndex && i < source.length; i++) if (source[i] === "\n") {
2390
+ line++;
2391
+ lineStart = i + 1;
2392
+ }
2393
+ return {
2394
+ line,
2395
+ column: charIndex - lineStart + 1
2396
+ };
2397
+ }
2398
+ function scanComments(source) {
2399
+ const out = [];
2400
+ const n = source.length;
2401
+ let i = 0;
2402
+ while (i < n) {
2403
+ const c = source[i];
2404
+ if (c === "\"" || c === "'") {
2405
+ i++;
2406
+ while (i < n && source[i] !== c && source[i] !== "\n") i += source[i] === "\\" ? 2 : 1;
2407
+ i++;
2408
+ } else if (c === "`") {
2409
+ i++;
2410
+ while (i < n && source[i] !== "`") i += source[i] === "\\" ? 2 : 1;
2411
+ i++;
2412
+ } else if (c === "/" && source[i + 1] === "/") {
2413
+ const start = i;
2414
+ i += 2;
2415
+ while (i < n && source[i] !== "\n") i++;
2416
+ const body = source.slice(start + 2, i);
2417
+ if (body.includes(DIRECTIVE_MARKER)) out.push({
2418
+ kind: "line",
2419
+ start,
2420
+ end: i,
2421
+ body
2422
+ });
2423
+ } else if (c === "/" && source[i + 1] === "*") {
2424
+ const start = i;
2425
+ i += 2;
2426
+ while (i < n && !(source[i] === "*" && source[i + 1] === "/")) i++;
2427
+ out.push({
2428
+ kind: "block",
2429
+ start,
2430
+ end: Math.min(i + 2, n),
2431
+ body: source.slice(start + 2, i)
2432
+ });
2433
+ i += 2;
2434
+ } else i++;
2435
+ }
2436
+ return out;
2437
+ }
2438
+ function afterpackPayload(body) {
2439
+ const m = /^\s*@afterpack\b([\s\S]*)$/.exec(body);
2440
+ return m ? m[1].trim() : null;
2441
+ }
2442
+ const BLOCK_FORM_CTA = "open a block with `/* @afterpack <directive> */` alone on its own line and close it with `/* @afterpack end */`, or put the marker inline to scope it to the rest of that line";
2443
+ function unsupportedForm(kind, payload) {
2444
+ if (payload.startsWith(":")) return `the \`@afterpack:begin … @afterpack:end\` span form is not implemented — ${BLOCK_FORM_CTA}`;
2445
+ if (kind === "line") return `\`// @afterpack …\` line comments are not scanned — ${BLOCK_FORM_CTA}`;
2446
+ return void 0;
2447
+ }
2448
+ function classifyTier(delta) {
2449
+ const decreaseComplexity = delta.complexity === void 0 || delta.complexity === 0;
2450
+ const encode = delta.strings?.encode;
2451
+ const decreaseEncode = encode === void 0 || encode === false;
2452
+ const noMask = delta.transforms?.only === void 0 && delta.transforms?.deny === void 0;
2453
+ return decreaseComplexity && decreaseEncode && delta.inflation?.max === void 0 && noMask ? "free" : "amplifying";
2454
+ }
2455
+ function boolValue(value) {
2456
+ if (value === "on" || value === "true") return true;
2457
+ if (value === "off" || value === "false") return false;
2458
+ return void 0;
2459
+ }
2460
+ function pushDeny(delta, kinds) {
2461
+ const merged = new Set(delta.transforms?.deny ?? []);
2462
+ for (const k of kinds) merged.add(k);
2463
+ delta.transforms = {
2464
+ ...delta.transforms,
2465
+ deny: [...merged]
2466
+ };
2467
+ }
2468
+ const NOT_IMPLEMENTED_REASON = "recognised but not implemented as a per-region directive — the engine's region wire carries only complexity, inflation.max, strings.encode, transforms.only and transforms.deny; set it in afterpack.json / a CLI flag / an env var instead";
2469
+ const DIRECTIVE_KEYS = [
2470
+ {
2471
+ key: "skip",
2472
+ kind: "escapeHatch",
2473
+ bool: true,
2474
+ apply: (delta, value, notes) => {
2475
+ const on = boolValue(value);
2476
+ if (on === void 0) return "`skip` must be `on` or `off`";
2477
+ if (!on) notes.push("`skip=off` has no effect — omit the directive instead");
2478
+ else {
2479
+ delta.complexity = 0;
2480
+ delta.strings = { encode: false };
2481
+ }
2482
+ return void 0;
2483
+ }
2484
+ },
2485
+ {
2486
+ key: "controlFlow.enabled",
2487
+ kind: "escapeHatch",
2488
+ bool: true,
2489
+ apply: (delta, value, notes) => {
2490
+ const on = boolValue(value);
2491
+ if (on === void 0) return "`controlFlow.enabled` must be `on` or `off`";
2492
+ if (on) notes.push("`controlFlow.enabled=on` cannot be expressed per region — a region mask can only forbid a transform, never re-enable one the global config disabled");
2493
+ else pushDeny(delta, ["controlFlowFlatten"]);
2494
+ return void 0;
2495
+ }
2496
+ },
2497
+ {
2498
+ key: "preset",
2499
+ kind: "amplifier",
2500
+ apply: (delta, value) => {
2501
+ const preset = PRESETS.find((p) => p === value);
2502
+ if (!preset) return `unknown preset \`${value}\` (one of ${PRESETS.join(", ")})`;
2503
+ delta.complexity = presetTarget(preset);
2504
+ delta.strings = { encode: delta.complexity > 0 };
2505
+ return void 0;
2506
+ }
2507
+ },
2508
+ {
2509
+ key: "complexity",
2510
+ kind: "amplifier",
2511
+ apply: (delta, value) => {
2512
+ const n = Number(value);
2513
+ if (!Number.isFinite(n) || n < 0) return "`complexity` needs a non-negative number";
2514
+ delta.complexity = n;
2515
+ return void 0;
2516
+ }
2517
+ },
2518
+ {
2519
+ key: "inflation.max",
2520
+ kind: "amplifier",
2521
+ apply: (delta, value) => {
2522
+ const n = Number(value);
2523
+ if (!Number.isFinite(n) || n < 0) return "`inflation.max` needs a non-negative number";
2524
+ delta.inflation = { max: n };
2525
+ return void 0;
2526
+ }
2527
+ },
2528
+ {
2529
+ key: "strings.encode",
2530
+ kind: "amplifier",
2531
+ bool: true,
2532
+ apply: (delta, value) => {
2533
+ const on = boolValue(value);
2534
+ if (on === void 0) return "`strings.encode` must be `on` or `off`";
2535
+ delta.strings = { encode: on };
2536
+ return void 0;
2537
+ }
2538
+ },
2539
+ {
2540
+ key: "transforms.only",
2541
+ kind: "amplifier",
2542
+ apply: (delta, value) => {
2543
+ const { kinds, error } = parseKindList(value);
2544
+ if (error) return error;
2545
+ delta.transforms = {
2546
+ ...delta.transforms,
2547
+ only: kinds
2548
+ };
2549
+ return void 0;
2550
+ }
2551
+ },
2552
+ {
2553
+ key: "transforms.deny",
2554
+ kind: "amplifier",
2555
+ apply: (delta, value) => {
2556
+ const { kinds, error } = parseKindList(value);
2557
+ if (error || !kinds) return error;
2558
+ pushDeny(delta, kinds);
2559
+ return void 0;
2560
+ }
2561
+ },
2562
+ {
2563
+ key: "async.preserve",
2564
+ kind: "escapeHatch",
2565
+ bool: true
2566
+ },
2567
+ {
2568
+ key: "generators.preserve",
2569
+ kind: "escapeHatch",
2570
+ bool: true
2571
+ },
2572
+ {
2573
+ key: "identifiers.rename",
2574
+ kind: "escapeHatch",
2575
+ bool: true
2576
+ },
2577
+ {
2578
+ key: "identifiers.globals.rename",
2579
+ kind: "escapeHatch",
2580
+ bool: true,
2581
+ fileScope: "renameGlobals"
2582
+ },
2583
+ {
2584
+ key: "reflection.allow",
2585
+ kind: "escapeHatch"
2586
+ },
2587
+ {
2588
+ key: "strings.destructionRate",
2589
+ kind: "amplifier"
2590
+ },
2591
+ {
2592
+ key: "strings.materializationVariants",
2593
+ kind: "amplifier"
2594
+ },
2595
+ {
2596
+ key: "strings.hoistScopeBias",
2597
+ kind: "amplifier"
2598
+ },
2599
+ {
2600
+ key: "decoder.stateVarCount",
2601
+ kind: "amplifier"
2602
+ },
2603
+ {
2604
+ key: "controlFlow.deadEntries",
2605
+ kind: "amplifier"
2606
+ },
2607
+ {
2608
+ key: "codegen.useEval",
2609
+ kind: "amplifier",
2610
+ bool: true
2611
+ }
2612
+ ];
2613
+ const SPEC_BY_LOWER = new Map(DIRECTIVE_KEYS.map((s) => [s.key.toLowerCase(), s]));
2614
+ function unknownKeyError(rawKey) {
2615
+ if (rawKey.includes("-")) return `kebab-case is not a directive key (\`${rawKey}\`) — keys are dot-delimited camelCase`;
2616
+ return `unknown directive key \`${rawKey}\``;
2617
+ }
2618
+ function parseDirectivePayload(payload) {
2619
+ const notes = [];
2620
+ const fail = (keyword$1, error) => ({
2621
+ keyword: keyword$1,
2622
+ delta: {},
2623
+ tier: "free",
2624
+ notes,
2625
+ noop: true,
2626
+ error
2627
+ });
2628
+ const text = payload.trim();
2629
+ if (text === "") return fail("", "empty `@afterpack` directive");
2630
+ const tokens = text.split(/\s+/);
2631
+ const leadKey = splitAssignment(tokens[0]).key;
2632
+ if (leadKey.toLowerCase() === "end") {
2633
+ if (tokens.length > 1) return fail("end", "`@afterpack end` closes a block and takes no keys");
2634
+ return {
2635
+ keyword: "end",
2636
+ delta: {},
2637
+ tier: "free",
2638
+ notes,
2639
+ noop: false
2640
+ };
2641
+ }
2642
+ const delta = {};
2643
+ let allEscapeHatch = true;
2644
+ let keyword = leadKey;
2645
+ let renameGlobals = false;
2646
+ for (let i = 0; i < tokens.length; i++) {
2647
+ const { key: rawKey, value: rawValue } = splitAssignment(tokens[i]);
2648
+ const bare = rawValue === true;
2649
+ const spec = SPEC_BY_LOWER.get(rawKey.toLowerCase());
2650
+ if (!spec) return fail(keyword, unknownKeyError(rawKey));
2651
+ if (i === 0) keyword = spec.key;
2652
+ if (spec.kind !== "escapeHatch") allEscapeHatch = false;
2653
+ if (bare && !spec.bool) return fail(keyword, `\`${spec.key}\` needs a \`=<value>\``);
2654
+ if (spec.fileScope === "renameGlobals") {
2655
+ const on = bare ? true : boolValue(rawValue.toLowerCase());
2656
+ if (on === void 0) return fail(keyword, "`identifiers.globals.rename` must be `on` or `off`");
2657
+ if (on) renameGlobals = true;
2658
+ else notes.push("`identifiers.globals.rename=off` is the default — omit the directive instead. To keep SPECIFIC names while renaming other globals, set `identifiers.globals.rename` on and list the names to keep in `identifiers.reserved`");
2659
+ continue;
2660
+ }
2661
+ if (!spec.apply) {
2662
+ notes.push(`\`${spec.key}\` is ${NOT_IMPLEMENTED_REASON}`);
2663
+ continue;
2664
+ }
2665
+ const error = spec.apply(delta, bare ? "on" : rawValue.toLowerCase(), notes);
2666
+ if (error) return fail(keyword, error);
2667
+ }
2668
+ const noop = Object.keys(delta).length === 0;
2669
+ return {
2670
+ keyword,
2671
+ delta,
2672
+ tier: allEscapeHatch ? "free" : classifyTier(delta),
2673
+ notes,
2674
+ noop,
2675
+ renameGlobals
2676
+ };
2677
+ }
2678
+ function eolOf(source, from) {
2679
+ const nl = source.indexOf("\n", from);
2680
+ return nl < 0 ? source.length : nl;
2681
+ }
2682
+ function isInline(source, marker) {
2683
+ return source.slice(marker.end, eolOf(source, marker.end)).trim() !== "";
2684
+ }
2685
+ function lineSpan(source, marker) {
2686
+ const eol = eolOf(source, marker.end);
2687
+ if (isInline(source, marker)) return {
2688
+ start: marker.end,
2689
+ end: eol
2690
+ };
2691
+ const nextStart = eol + 1;
2692
+ return {
2693
+ start: nextStart,
2694
+ end: eolOf(source, nextStart)
2695
+ };
2696
+ }
2697
+ function record(source, parsed, marker, form, span) {
2698
+ const { line, column } = lineCol(source, marker.start);
2699
+ const region = {
2700
+ start: byteOffset(source, span.start),
2701
+ end: byteOffset(source, span.end),
2702
+ ...parsed.delta,
2703
+ label: parsed.keyword
2704
+ };
2705
+ return {
2706
+ keyword: parsed.keyword,
2707
+ form,
2708
+ tier: parsed.tier,
2709
+ line,
2710
+ column,
2711
+ region,
2712
+ charStart: span.start,
2713
+ charEnd: span.end
2714
+ };
2715
+ }
2716
+ function scanDirectives(source) {
2717
+ const directives = [];
2718
+ const diagnostics = [];
2719
+ const open = [];
2720
+ let renameGlobals = false;
2721
+ if (!source.includes(DIRECTIVE_MARKER)) return {
2722
+ regions: [],
2723
+ directives,
2724
+ diagnostics,
2725
+ renameGlobals
2726
+ };
2727
+ for (const marker of scanComments(source)) {
2728
+ const payload = afterpackPayload(marker.body);
2729
+ if (payload === null) continue;
2730
+ const at = lineCol(source, marker.start);
2731
+ const unsupported = unsupportedForm(marker.kind, payload);
2732
+ if (unsupported) {
2733
+ diagnostics.push({
2734
+ code: "DIAG_DIRECTIVE_UNSUPPORTED_FORM",
2735
+ message: unsupported,
2736
+ ...at
2737
+ });
2738
+ continue;
2739
+ }
2740
+ const parsed = parseDirectivePayload(payload);
2741
+ for (const note of parsed.notes) diagnostics.push({
2742
+ code: "DIAG_DIRECTIVE_NOT_IMPLEMENTED",
2743
+ message: note,
2744
+ ...at
2745
+ });
2746
+ if (parsed.error) {
2747
+ diagnostics.push({
2748
+ code: "DIAG_DIRECTIVE_UNKNOWN",
2749
+ message: parsed.error,
2750
+ ...at
2751
+ });
2752
+ continue;
2753
+ }
2754
+ if (parsed.renameGlobals) {
2755
+ renameGlobals = true;
2756
+ diagnostics.push({
2757
+ code: "DIAG_DIRECTIVE_REGION_TO_FILE",
2758
+ message: "`identifiers.globals.rename` cannot be scoped to a region — a global binding's references span the whole file, so a rename is wholesale; applied to the ENTIRE file instead. To keep SPECIFIC names while renaming the rest, use `identifiers.reserved`",
2759
+ ...at
2760
+ });
2761
+ }
2762
+ if (parsed.keyword === "end") {
2763
+ const opened = open.pop();
2764
+ if (!opened) {
2765
+ diagnostics.push({
2766
+ code: "DIAG_DIRECTIVE_DANGLING_END",
2767
+ message: "`@afterpack end` has no open directive",
2768
+ ...at
2769
+ });
2770
+ continue;
2771
+ }
2772
+ if (opened.parsed.noop) continue;
2773
+ directives.push(record(source, opened.parsed, opened.marker, "block", {
2774
+ start: opened.marker.end,
2775
+ end: marker.start
2776
+ }));
2777
+ continue;
2778
+ }
2779
+ if (isInline(source, marker)) {
2780
+ if (parsed.noop) continue;
2781
+ directives.push(record(source, parsed, marker, "line", {
2782
+ start: marker.end,
2783
+ end: eolOf(source, marker.end)
2784
+ }));
2785
+ } else open.push({
2786
+ parsed,
2787
+ marker
2788
+ });
2789
+ }
2790
+ for (const opened of open) {
2791
+ if (opened.parsed.noop) continue;
2792
+ directives.push(record(source, opened.parsed, opened.marker, "line", lineSpan(source, opened.marker)));
2793
+ }
2794
+ directives.sort((a, b) => a.region.start - b.region.start || a.region.end - b.region.end);
2795
+ return {
2796
+ regions: directives.map((d) => d.region),
2797
+ directives,
2798
+ diagnostics,
2799
+ renameGlobals
2800
+ };
2801
+ }
2802
+ const REFUSAL_LIST_LIMIT = 3;
2803
+ function renameGlobalsRefusalMessage(refused, fileCount) {
2804
+ const shown = refused.slice(0, REFUSAL_LIST_LIMIT).join(", ");
2805
+ const rest = refused.length > REFUSAL_LIST_LIMIT ? ` and ${refused.length - REFUSAL_LIST_LIMIT} more` : "";
2806
+ return `REFUSED \`identifiers.globals.rename\` from ${shown}${rest} — the engine takes that flag BUILD-WIDE (one shared config), so honouring it here would rename top-level bindings in all ${fileCount} file(s) of this build, not only the file that asked. Nothing was renamed. Obfuscate that file on its own to apply it.`;
2807
+ }
2808
+ function inputLabel(input, index) {
2809
+ return input.path ?? `file #${index + 1}`;
2810
+ }
2811
+ function captureDirectiveRegions(inputs, handAuthored, enabled = true) {
2812
+ if (!enabled) return {
2813
+ regions: handAuthored,
2814
+ applied: 0,
2815
+ deferredFiles: 0,
2816
+ diagnostics: [],
2817
+ renameGlobals: false,
2818
+ renameGlobalsRefused: []
2819
+ };
2820
+ if (inputs.length === 1) {
2821
+ const scan = scanDirectives(inputs[0].source);
2822
+ if (scan.regions.length === 0) return {
2823
+ regions: handAuthored,
2824
+ applied: 0,
2825
+ deferredFiles: 0,
2826
+ diagnostics: scan.diagnostics,
2827
+ renameGlobals: scan.renameGlobals,
2828
+ renameGlobalsRefused: []
2829
+ };
2830
+ return {
2831
+ regions: [...handAuthored ?? [], ...scan.regions],
2832
+ applied: scan.regions.length,
2833
+ deferredFiles: 0,
2834
+ diagnostics: scan.diagnostics,
2835
+ renameGlobals: scan.renameGlobals,
2836
+ renameGlobalsRefused: []
2837
+ };
2838
+ }
2839
+ let deferredFiles = 0;
2840
+ const renameGlobalsRefused = [];
2841
+ const diagnostics = [];
2842
+ inputs.forEach((input, index) => {
2843
+ const scan = scanDirectives(input.source);
2844
+ if (scan.regions.length > 0) deferredFiles++;
2845
+ if (scan.renameGlobals) renameGlobalsRefused.push(inputLabel(input, index));
2846
+ diagnostics.push(...scan.diagnostics);
2847
+ });
2848
+ return {
2849
+ regions: handAuthored,
2850
+ applied: 0,
2851
+ deferredFiles,
2852
+ diagnostics,
2853
+ renameGlobals: false,
2854
+ renameGlobalsRefused
2855
+ };
2856
+ }
2857
+
2858
+ //#endregion
2859
+ //#region src/git.ts
2860
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
2861
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
2862
+ function sanitizeCommitSha(value) {
2863
+ if (typeof value !== "string") return null;
2864
+ const sha = value.trim().toLowerCase();
2865
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
2866
+ }
2867
+ function sanitizeGitRef(value) {
2868
+ if (typeof value !== "string") return null;
2869
+ const ref = value.trim();
2870
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
2871
+ }
2872
+ function contextFrom(rawSha, rawRef) {
2873
+ const commitSha = sanitizeCommitSha(rawSha);
2874
+ const ref = sanitizeGitRef(rawRef);
2875
+ if (commitSha === null && ref === null) return null;
2876
+ const context = {};
2877
+ if (commitSha !== null) context.commitSha = commitSha;
2878
+ if (ref !== null) context.ref = ref;
2879
+ return context;
2880
+ }
2881
+ const CI_SOURCES = [
2882
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
2883
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
2884
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
2885
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
2886
+ ["GIT_COMMIT", "BRANCH_NAME"]
2887
+ ];
2888
+ function ciGitContext(env) {
2889
+ for (const [shaVar, refVar] of CI_SOURCES) {
2890
+ const context = contextFrom(env[shaVar], env[refVar]);
2891
+ if (context !== null) return context;
2892
+ }
2893
+ return null;
2894
+ }
2895
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
2896
+ function localGitContext(cwd) {
2897
+ let lines;
2898
+ try {
2899
+ const out = execFileSync("git", [
2900
+ "rev-parse",
2901
+ "HEAD",
2902
+ "--abbrev-ref",
2903
+ "HEAD"
2904
+ ], {
2905
+ cwd,
2906
+ stdio: [
2907
+ "ignore",
2908
+ "pipe",
2909
+ "ignore"
2910
+ ],
2911
+ timeout: GIT_PROBE_TIMEOUT_MS,
2912
+ maxBuffer: 64 * 1024
2913
+ }).toString();
2914
+ lines = out.split("\n").map((line) => line.trim());
2915
+ } catch {
2916
+ return null;
2917
+ }
2918
+ const ref = lines[1] === "HEAD" ? null : lines[1];
2919
+ return contextFrom(lines[0], ref);
2920
+ }
2921
+ function detectGitContext(explicit, deps = {}) {
2922
+ if (explicit) {
2923
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
2924
+ if (declared !== null) return declared;
2925
+ }
2926
+ const ci = ciGitContext(deps.env ?? process.env);
2927
+ if (ci !== null) return ci;
2928
+ return (deps.localGit ?? localGitContext)(deps.cwd);
2929
+ }
2930
+
2931
+ //#endregion
2932
+ //#region src/map-color.ts
2933
+ const UTF8 = new TextEncoder();
2934
+ const utf8Len = (s) => UTF8.encode(s).length;
2935
+ const NON_ASCII = /[\u0080-\uFFFF]/;
2936
+ const HIGH_SURROGATE_START = 55296;
2937
+ const HIGH_SURROGATE_END = 56319;
2938
+ const LOW_SURROGATE_START = 56320;
2939
+ const LOW_SURROGATE_END = 57343;
2940
+ function charToByteTable(line) {
2941
+ const table = new Array(line.length + 1);
2942
+ let bytes = 0;
2943
+ let i = 0;
2944
+ while (i < line.length) {
2945
+ table[i] = bytes;
2946
+ const code = line.charCodeAt(i);
2947
+ if (code < 128) {
2948
+ bytes += 1;
2949
+ i += 1;
2950
+ continue;
2951
+ }
2952
+ if (code < 2048) {
2953
+ bytes += 2;
2954
+ i += 1;
2955
+ continue;
2956
+ }
2957
+ if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
2958
+ const low = line.charCodeAt(i + 1);
2959
+ if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
2960
+ table[i + 1] = bytes + 3;
2961
+ bytes += 4;
2962
+ i += 2;
2963
+ continue;
2964
+ }
2965
+ }
2966
+ bytes += 3;
2967
+ i += 1;
2968
+ }
2969
+ table[line.length] = bytes;
2970
+ return table;
2971
+ }
2972
+ var ChunkByteIndex = class {
2973
+ starts;
2974
+ ascii;
2975
+ tables;
2976
+ totalBytes;
2977
+ constructor(lines) {
2978
+ this.lines = lines;
2979
+ this.starts = new Array(lines.length);
2980
+ this.ascii = new Array(lines.length);
2981
+ this.tables = new Array(lines.length).fill(null);
2982
+ let acc = 0;
2983
+ for (let i = 0; i < lines.length; i++) {
2984
+ const line = lines[i];
2985
+ this.starts[i] = acc;
2986
+ const isAscii = !NON_ASCII.test(line);
2987
+ this.ascii[i] = isAscii;
2988
+ acc += (isAscii ? line.length : utf8Len(line)) + 1;
2989
+ }
2990
+ this.totalBytes = lines.length === 0 ? 0 : acc - 1;
2991
+ }
2992
+ byteOf(line, col) {
2993
+ if (line < 0 || line >= this.lines.length) return this.totalBytes;
2994
+ const text = this.lines[line];
2995
+ const clamped = col < 0 ? 0 : col < text.length ? col : text.length;
2996
+ if (this.ascii[line]) return this.starts[line] + clamped;
2997
+ let table = this.tables[line];
2998
+ if (table === null) {
2999
+ table = charToByteTable(text);
3000
+ this.tables[line] = table;
3001
+ }
3002
+ return this.starts[line] + table[clamped];
3003
+ }
3004
+ };
3005
+ function charToLineCol(source, charIndex) {
3006
+ let line = 0;
3007
+ let lineStart = 0;
3008
+ const stop = Math.min(charIndex, source.length);
3009
+ for (let i = 0; i < stop; i++) if (source.charCodeAt(i) === 10) {
3010
+ line++;
3011
+ lineStart = i + 1;
3012
+ }
3013
+ return {
3014
+ line,
3015
+ col: charIndex - lineStart
3016
+ };
3017
+ }
3018
+ function norm(p) {
3019
+ return p.replace(/\\/g, "/").replace(/[?#].*$/, "").replace(/^(?:\.\.?\/)+/, "");
3020
+ }
3021
+ function normEq(a, b) {
3022
+ return a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`);
3023
+ }
3024
+ const DEFAULT_WARN = (message) => {
3025
+ console.warn(`[afterpack] ${message}`);
3026
+ };
3027
+ const countDirectives = (modules) => modules.reduce((n, m) => n + m.directives.length, 0);
3028
+ function colorRegions(chunkCode, map, modules, warn = DEFAULT_WARN) {
3029
+ const withDirectives = modules.filter((m) => m.directives.length > 0);
3030
+ if (withDirectives.length === 0) return [];
3031
+ let segsByLine = null;
3032
+ if (map && typeof map.mappings === "string") try {
3033
+ segsByLine = decode(map.mappings);
3034
+ } catch {
3035
+ segsByLine = null;
3036
+ }
3037
+ if (!segsByLine || !map) {
3038
+ warn(`DIAG_DIRECTIVE_COVERAGE_UNVERIFIED: skipped ${countDirectives(withDirectives)} @afterpack directive(s) from ${withDirectives.length} module(s) — this chunk has no decodable source map, so they cannot be placed in its bytes.`);
3039
+ return [];
3040
+ }
3041
+ const sources = map.sources ?? [];
3042
+ const normSources = sources.map((s) => s == null ? null : norm(s));
3043
+ const lines = chunkCode.split("\n");
3044
+ const index = new ChunkByteIndex(lines);
3045
+ const bySource = bucketBySource(segsByLine, lines);
3046
+ const out = [];
3047
+ const located = [];
3048
+ for (const mod of withDirectives) {
3049
+ let srcIdx = mod.srcIndex != null && mod.srcIndex >= 0 && mod.srcIndex < sources.length ? mod.srcIndex : -1;
3050
+ if (srcIdx < 0) {
3051
+ const normId = norm(mod.id);
3052
+ srcIdx = normSources.findIndex((ns) => ns != null && normEq(normId, ns));
3053
+ }
3054
+ if (srcIdx < 0) {
3055
+ warn(`DIAG_DIRECTIVE_COVERAGE_UNVERIFIED: skipped ${mod.directives.length} @afterpack directive(s) — the bundler placed \`${mod.id}\` in this chunk but its source map does not list it, so they cannot be placed in the chunk's bytes.`);
3056
+ continue;
3057
+ }
3058
+ located.push({
3059
+ mod,
3060
+ srcIdx
3061
+ });
3062
+ const segments$1 = bySource.get(srcIdx) ?? [];
3063
+ for (const d of mod.directives) {
3064
+ const start = charToLineCol(mod.source, d.charStart);
3065
+ const end = charToLineCol(mod.source, d.charEnd);
3066
+ const ranges = coverGenerated(segments$1, start, end, index);
3067
+ for (const [s, e] of ranges) out.push({
3068
+ ...d.region,
3069
+ start: s,
3070
+ end: e
3071
+ });
3072
+ }
3073
+ }
3074
+ if (out.length === 0 && located.length > 0) for (const { mod, srcIdx } of located) if ((bySource.get(srcIdx)?.length ?? 0) === 0) warn(`DIAG_DIRECTIVE_SOURCE_UNRESOLVED: \`${mod.id}\` carries ${mod.directives.length} @afterpack directive(s) but this chunk's source map has NO mapping segment anywhere for that source, so its interior cannot be resolved at all — the directive(s) were NOT applied. This is a source-map coverage gap, not tree-shaking.`);
3075
+ else warn(`DIAG_DIRECTIVE_TARGET_ELIMINATED: located \`${mod.id}\` carrying ${mod.directives.length} @afterpack directive(s) in this chunk's source map but colored 0 ranges for it — the marked code was tree-shaken, or the map's original coordinates do not line up with the captured source.`);
3076
+ return out;
3077
+ }
3078
+ function bucketBySource(segsByLine, lines) {
3079
+ const bySource = new Map();
3080
+ for (let gl = 0; gl < segsByLine.length; gl++) {
3081
+ const segs = segsByLine[gl];
3082
+ for (let i = 0; i < segs.length; i++) {
3083
+ const seg = segs[i];
3084
+ if (seg.length < 4) continue;
3085
+ const genCol = seg[0];
3086
+ const srcIdx = seg[1];
3087
+ let bucket = bySource.get(srcIdx);
3088
+ if (bucket === void 0) {
3089
+ bucket = [];
3090
+ bySource.set(srcIdx, bucket);
3091
+ }
3092
+ bucket.push({
3093
+ genLine: gl,
3094
+ genCol,
3095
+ endCol: i + 1 < segs.length ? segs[i + 1][0] : lines[gl]?.length ?? genCol,
3096
+ srcLine: seg[2],
3097
+ srcCol: seg[3]
3098
+ });
3099
+ }
3100
+ }
3101
+ return bySource;
3102
+ }
3103
+ function coverGenerated(segments$1, start, end, index) {
3104
+ const inSpan = (line, col) => {
3105
+ const afterStart = line > start.line || line === start.line && col >= start.col;
3106
+ const beforeEnd = line < end.line || line === end.line && col < end.col;
3107
+ return afterStart && beforeEnd;
3108
+ };
3109
+ const ranges = [];
3110
+ for (const seg of segments$1) {
3111
+ if (!inSpan(seg.srcLine, seg.srcCol)) continue;
3112
+ const s = index.byteOf(seg.genLine, seg.genCol);
3113
+ const e = index.byteOf(seg.genLine, seg.endCol);
3114
+ if (e > s) ranges.push([s, e]);
3115
+ }
3116
+ ranges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
3117
+ const merged = [];
3118
+ for (const [a, b] of ranges) {
3119
+ const last = merged[merged.length - 1];
3120
+ if (last && a <= last[1]) last[1] = Math.max(last[1], b);
3121
+ else merged.push([a, b]);
3122
+ }
3123
+ return merged;
3124
+ }
3125
+
3126
+ //#endregion
3127
+ //#region src/receipt.ts
3128
+ const PROTECTION_RECEIPT_FILE = ".afterpack-protection.json";
3129
+ const PROTECTION_RECEIPT_SCHEMA = 1;
3130
+ function sha256OfBytes(bytes) {
3131
+ return createHash("sha256").update(bytes).digest("hex");
3132
+ }
3133
+ function sha256Of(path) {
3134
+ return sha256OfBytes(readFileSync(path));
3135
+ }
3136
+ function receiptPathOf(dir, file) {
3137
+ return relative(dir, file).split(sep).join("/");
3138
+ }
3139
+ function writeDeferredProtectionReceipt(deferred) {
3140
+ const survivingFiles = deferred.files.filter((file) => existsSync(file));
3141
+ if (survivingFiles.length === 0) return null;
3142
+ return writeProtectionReceipt({
3143
+ ...deferred,
3144
+ files: survivingFiles
3145
+ });
3146
+ }
3147
+ function writeProtectionReceipt(input) {
3148
+ const transformed = new Set(input.transformed);
3149
+ const receipt = {
3150
+ schema: PROTECTION_RECEIPT_SCHEMA,
3151
+ tool: input.tool,
3152
+ engine: input.engine,
3153
+ engineVersion: input.engineVersion,
3154
+ seed: String(input.seed),
3155
+ seedOrigin: input.seedOrigin,
3156
+ bundler: input.bundler,
3157
+ buildId: input.buildId,
3158
+ files: input.files.map((file) => ({
3159
+ path: receiptPathOf(input.dir, file),
3160
+ sha256: sha256Of(file),
3161
+ transformed: transformed.has(file)
3162
+ })).sort((a, b) => a.path.localeCompare(b.path))
3163
+ };
3164
+ const path = join(input.dir, PROTECTION_RECEIPT_FILE);
3165
+ writeFileSync(path, `${JSON.stringify(receipt, null, 2)}\n`);
3166
+ return path;
3167
+ }
3168
+ function parseReceipt(path) {
3169
+ let raw;
3170
+ try {
3171
+ raw = JSON.parse(readFileSync(path, "utf8"));
3172
+ } catch (error) {
3173
+ const reason = error instanceof Error ? error.message : String(error);
3174
+ return {
3175
+ error: `${path} is not valid JSON: ${reason}`,
3176
+ newerSchema: null
3177
+ };
3178
+ }
3179
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return {
3180
+ error: `${path} is not a protection receipt object`,
3181
+ newerSchema: null
3182
+ };
3183
+ const receipt = raw;
3184
+ const schema = receipt.schema;
3185
+ const newerSchema = typeof schema === "number" && Number.isInteger(schema) && schema > PROTECTION_RECEIPT_SCHEMA ? schema : null;
3186
+ const fail = (error) => ({
3187
+ error,
3188
+ newerSchema
3189
+ });
3190
+ if (typeof schema !== "number" || !Number.isInteger(schema) || schema < PROTECTION_RECEIPT_SCHEMA) return fail(`${path} has schema ${String(schema)}, which this afterpack cannot read`);
3191
+ if (!Array.isArray(receipt.files)) return fail(`${path} lists no files`);
3192
+ if (!receipt.files.every(isReceiptFile)) return fail(`${path} lists a file entry it cannot read`);
3193
+ return { receipt };
3194
+ }
3195
+ function isReceiptFile(value) {
3196
+ if (typeof value !== "object" || value === null) return false;
3197
+ const entry = value;
3198
+ return typeof entry.path === "string" && typeof entry.sha256 === "string";
3199
+ }
3200
+ const DIAG_RECEIPT_UNREADABLE = "DIAG_RECEIPT_UNREADABLE";
3201
+ var UnreadableReceiptError = class extends Error {
3202
+ code = DIAG_RECEIPT_UNREADABLE;
3203
+ receiptPath;
3204
+ schema;
3205
+ constructor(message, receiptPath, schema) {
3206
+ super(message);
3207
+ this.name = "UnreadableReceiptError";
3208
+ this.receiptPath = receiptPath;
3209
+ this.schema = schema;
3210
+ }
3211
+ };
3212
+ function verifyProtectionReceipt(dir, expectedBuildId) {
3213
+ const receiptPath = join(dir, PROTECTION_RECEIPT_FILE);
3214
+ if (!existsSync(receiptPath)) return {
3215
+ receiptPath,
3216
+ receipt: null,
3217
+ problems: [`no protection receipt at ${receiptPath}`]
3218
+ };
3219
+ const result = parseReceipt(receiptPath);
3220
+ if (result.error !== void 0) return {
3221
+ receiptPath,
3222
+ receipt: null,
3223
+ problems: [result.error]
3224
+ };
3225
+ const parsed = result.receipt;
3226
+ const problems = [];
3227
+ if (expectedBuildId != null && parsed.buildId !== expectedBuildId) problems.push(`receipt is for build ${String(parsed.buildId)}, but this output is build ${expectedBuildId} — the tree was rebuilt without the AfterPack wrapper`);
3228
+ if (parsed.files.length === 0) problems.push("receipt records zero obfuscated files");
3229
+ const transformed = parsed.files.filter((f) => f.transformed !== false).length;
3230
+ if (parsed.files.length > 0 && transformed === 0) problems.push(`receipt lists ${parsed.files.length} file(s) but the engine changed NONE of them — this build shipped its source (check \`paths.exclude\` and AFTERPACK_paths_exclude)`);
3231
+ for (const entry of parsed.files) {
3232
+ const file = join(dir, entry.path);
3233
+ if (!existsSync(file)) {
3234
+ problems.push(`${entry.path}: obfuscated at build time, missing now`);
3235
+ continue;
3236
+ }
3237
+ if (sha256Of(file) !== entry.sha256) problems.push(`${entry.path}: content changed since it was obfuscated`);
3238
+ }
3239
+ return {
3240
+ receiptPath,
3241
+ receipt: parsed,
3242
+ problems
3243
+ };
3244
+ }
3245
+ function findReceiptDir(startDir) {
3246
+ const receiptPath = findUpward(startDir, PROTECTION_RECEIPT_FILE);
3247
+ return receiptPath ? dirname(receiptPath) : null;
3248
+ }
3249
+ function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
3250
+ const dir = findReceiptDir(startDir);
3251
+ if (!dir) return null;
3252
+ const receiptPath = join(dir, PROTECTION_RECEIPT_FILE);
3253
+ const result = parseReceipt(receiptPath);
3254
+ if (result.error !== void 0) {
3255
+ const schema = result.newerSchema;
3256
+ if (schema === null) return null;
3257
+ throw new UnreadableReceiptError(prefix(`${receiptPath} was written by a newer AfterPack (receipt schema ${schema}), so this version cannot tell whether these files are already obfuscated — update afterpack, or rebuild from source and delete the receipt before running it again.`), receiptPath, schema);
3258
+ }
3259
+ const outputHashes = new Set(result.receipt.files.map((f) => f.sha256));
3260
+ if (outputHashes.size === 0) return null;
3261
+ const matches = files.filter((file) => {
3262
+ const bytes = bytesByPath?.get(file);
3263
+ if (bytes !== void 0) return outputHashes.has(sha256OfBytes(bytes));
3264
+ return existsSync(file) && outputHashes.has(sha256Of(file));
3265
+ });
3266
+ return matches.length > 0 ? {
3267
+ receiptPath,
3268
+ files: matches
3269
+ } : null;
3270
+ }
3271
+
3272
+ //#endregion
3273
+ //#region src/seed.ts
3274
+ function randomSeed() {
3275
+ const b = randomBytes(8);
3276
+ const hi = b.readUInt32BE(0) & 2097151;
3277
+ const lo = b.readUInt32BE(4);
3278
+ return hi * 4294967296 + lo;
3279
+ }
3280
+ function gitHead() {
3281
+ try {
3282
+ const out = execFileSync("git", ["rev-parse", "HEAD"], { stdio: [
3283
+ "ignore",
3284
+ "pipe",
3285
+ "ignore"
3286
+ ] }).toString().trim();
3287
+ return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3288
+ } catch {
3289
+ return null;
3290
+ }
3291
+ }
3292
+ const SEED_ENV_VAR = "AFTERPACK_SEED";
3293
+ function parseSeedValue(raw) {
3294
+ return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3295
+ }
3296
+ const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3297
+ function sharedSeedState() {
3298
+ const holder = globalThis;
3299
+ holder[SEED_STATE] ??= {
3300
+ sessions: new Map(),
3301
+ ownEnvExports: []
3302
+ };
3303
+ return holder[SEED_STATE];
3304
+ }
3305
+ const { sessions, ownEnvExports } = sharedSeedState();
3306
+ function isOwnEnvExport(env, value) {
3307
+ return ownEnvExports.some((e) => e.env === env && e.value === value);
3308
+ }
3309
+ function openGeneration(root, leg) {
3310
+ let session = sessions.get(root);
3311
+ if (!session) {
3312
+ session = {
3313
+ seed: void 0,
3314
+ generation: 1,
3315
+ legs: [],
3316
+ resolvedByLeg: new Map(),
3317
+ gitFallbackWarned: false
3318
+ };
3319
+ sessions.set(root, session);
3320
+ } else if (session.legs.includes(leg)) {
3321
+ session.seed = void 0;
3322
+ session.generation += 1;
3323
+ session.legs = [];
3324
+ session.resolvedByLeg.clear();
3325
+ session.gitFallbackWarned = false;
3326
+ }
3327
+ session.legs.push(leg);
3328
+ return session;
3329
+ }
3330
+ function resolveWithinSession(input, session, env, deps) {
3331
+ if (typeof input === "number") return {
3332
+ seed: input,
3333
+ origin: "option"
3334
+ };
3335
+ if (typeof input === "string" && input !== "git") return {
3336
+ seed: input,
3337
+ origin: "option"
3338
+ };
3339
+ if (input === "git") {
3340
+ const head = (deps.gitHead ?? gitHead)();
3341
+ if (head) return {
3342
+ seed: head,
3343
+ origin: "git"
3344
+ };
3345
+ if (!session.gitFallbackWarned) {
3346
+ session.gitFallbackWarned = true;
3347
+ (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
3348
+ }
3349
+ }
3350
+ const fromEnv = env[SEED_ENV_VAR];
3351
+ if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3352
+ seed: parseSeedValue(fromEnv),
3353
+ origin: "env"
3354
+ };
3355
+ if (session.seed !== void 0) return {
3356
+ seed: session.seed,
3357
+ origin: "session"
3358
+ };
3359
+ return {
3360
+ seed: (deps.randomSeed ?? randomSeed)(),
3361
+ origin: "fresh"
3362
+ };
3363
+ }
3364
+ function resolveBuildSeed(input, scope, deps = {}) {
3365
+ const env = deps.env ?? process.env;
3366
+ const session = openGeneration(scope.root, scope.leg);
3367
+ const { seed, origin } = resolveWithinSession(input, session, env, deps);
3368
+ if (origin === "env" || origin === "fresh") session.seed = seed;
3369
+ if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3370
+ const value = String(seed);
3371
+ env[SEED_ENV_VAR] = value;
3372
+ const stale = ownEnvExports.findIndex((e) => e.env === env);
3373
+ if (stale >= 0) ownEnvExports.splice(stale, 1);
3374
+ ownEnvExports.push({
3375
+ env,
3376
+ value
3377
+ });
3378
+ }
3379
+ const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3380
+ session.resolvedByLeg.set(scope.leg, seed);
3381
+ return {
3382
+ seed,
3383
+ origin,
3384
+ legs: [...session.legs],
3385
+ generation: session.generation,
3386
+ mismatch: prior && session.generation === 1 ? {
3387
+ leg: prior[0],
3388
+ seed: prior[1]
3389
+ } : null
3390
+ };
3391
+ }
3392
+
3393
+ //#endregion
3394
+ //#region src/summary.ts
3395
+ function fmtBytes(n) {
3396
+ if (n < 1024) return `${n} B`;
3397
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
3398
+ return `${(n / (1024 * 1024)).toFixed(2)} MB`;
3399
+ }
3400
+ function fmtElapsed(ms) {
3401
+ return ms < 1e3 ? `${Math.round(ms)}ms` : `${(ms / 1e3).toFixed(1)}s`;
3402
+ }
3403
+ function formatPassSummary(input, style, colorGlyph = (glyph) => glyph) {
3404
+ const head = style === "cli" ? colorGlyph("✓") : `[${input.label}]`;
3405
+ const files = input.fileCount === 1 ? "file" : "files";
3406
+ const tail = (input.unobfuscatedCount > 0 ? ` · ${input.unobfuscatedCount} shipped UNOBFUSCATED (fallback, cleartext)` : "") + (input.noOpCount > 0 ? ` · ${input.noOpCount} no-op (unchanged)` : "");
3407
+ return `${head} Protected ${input.fileCount} ${files} · ${fmtBytes(input.inputBytes)} → ${fmtBytes(input.outputBytes)}${tail} · ${fmtElapsed(input.elapsedMs)}`;
3408
+ }
3409
+
3410
+ //#endregion
3411
+ //#region src/telemetry.ts
3412
+ const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3413
+ const DEFAULT_API_URL = "https://api.afterpack.dev";
3414
+ const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3415
+ const TELEMETRY_PAYLOAD_VERSION = 1;
3416
+ const TELEMETRY_TIMEOUT_MS = 1500;
3417
+ const INSTALL_ID_ROTATION_DAYS = 30;
3418
+ const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3419
+ const TELEMETRY_STATE_FILE = join(homedir(), ".afterpack", "telemetry.json");
3420
+ const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3421
+ const DATA_FIELD_WHITELIST = {
3422
+ outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3423
+ parseError: ["parserErrorKind"],
3424
+ engineBug: [
3425
+ "phase",
3426
+ "transform",
3427
+ "nodeKind"
3428
+ ],
3429
+ inflationBudget: [
3430
+ "target",
3431
+ "achieved",
3432
+ "budgetRatio",
3433
+ "inflationRatio"
3434
+ ],
3435
+ configParse: [
3436
+ "category",
3437
+ "line",
3438
+ "column"
3439
+ ]
3440
+ };
3441
+ function resolveTelemetryEnabled(option, env = {}) {
3442
+ if (option !== void 0) return option;
3443
+ return !(env.NODE_ENV === "test" || env.VITEST);
3444
+ }
3445
+ const FRAMEWORK_ENTRIES = [
3446
+ {
3447
+ label: "afterpack",
3448
+ name: "cli"
3449
+ },
3450
+ {
3451
+ label: "afterpack-angular",
3452
+ name: "angular",
3453
+ pkg: "@angular/core"
3454
+ },
3455
+ {
3456
+ label: "afterpack-esbuild",
3457
+ name: "esbuild",
3458
+ pkg: "esbuild"
3459
+ },
3460
+ {
3461
+ label: "afterpack-next",
3462
+ name: "next",
3463
+ pkg: "next"
3464
+ },
3465
+ {
3466
+ label: "afterpack-rollup",
3467
+ name: "rollup",
3468
+ pkg: "rollup"
3469
+ },
3470
+ {
3471
+ label: "afterpack-vite",
3472
+ name: "vite",
3473
+ pkg: "vite"
3474
+ },
3475
+ {
3476
+ label: "afterpack-webpack",
3477
+ name: "webpack",
3478
+ pkg: "webpack"
3479
+ }
3480
+ ];
3481
+ const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3482
+ const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3483
+ function frameworkFromLabel(label) {
3484
+ return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
3485
+ }
3486
+ const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3487
+ function detectFrameworkVersion(projectRoot, framework) {
3488
+ const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3489
+ if (!pkgName) return null;
3490
+ let deps;
3491
+ try {
3492
+ const pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
3493
+ deps = {
3494
+ ...pkg.dependencies,
3495
+ ...pkg.devDependencies
3496
+ };
3497
+ } catch {
3498
+ return null;
3499
+ }
3500
+ const raw = deps[pkgName];
3501
+ if (typeof raw !== "string") return null;
3502
+ const range = raw.trim();
3503
+ return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3504
+ }
3505
+ function complexityLabel(preset, complexity) {
3506
+ if (preset !== void 0) return preset;
3507
+ return complexity === void 0 ? "default" : "custom";
3508
+ }
3509
+ const FILE_COUNT_BUCKETS = [
3510
+ 1,
3511
+ 5,
3512
+ 20,
3513
+ 100,
3514
+ 500,
3515
+ 2e3
3516
+ ];
3517
+ function fileCountBucket(count) {
3518
+ if (!Number.isFinite(count) || count <= 0) return "0";
3519
+ let lower = 1;
3520
+ for (const upper of FILE_COUNT_BUCKETS) {
3521
+ if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3522
+ lower = upper + 1;
3523
+ }
3524
+ return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3525
+ }
3526
+ const DURATION_BUCKETS_MS = [
3527
+ [1e3, "<1s"],
3528
+ [5e3, "1-5s"],
3529
+ [15e3, "5-15s"],
3530
+ [6e4, "15-60s"],
3531
+ [3e5, "60-300s"]
3532
+ ];
3533
+ function durationBucket(ms) {
3534
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
3535
+ for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3536
+ return "300s+";
3537
+ }
3538
+ function safeScalar(value) {
3539
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3540
+ if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3541
+ return null;
3542
+ }
3543
+ function telemetrySafeData(data) {
3544
+ if (!data || typeof data.kind !== "string") return null;
3545
+ const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3546
+ if (kind === null) return null;
3547
+ const out = { kind };
3548
+ for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3549
+ const value = safeScalar(data[field]);
3550
+ if (value !== null) out[field] = value;
3551
+ }
3552
+ return out;
3553
+ }
3554
+ function telemetrySafeSpan(d) {
3555
+ const span = d.span;
3556
+ if (!span) return null;
3557
+ const start = safeScalar(span.startByte);
3558
+ const end = safeScalar(span.endByte);
3559
+ if (typeof start !== "number" || typeof end !== "number") return null;
3560
+ if (start < 0 || end < 0) return null;
3561
+ return {
3562
+ startByte: start,
3563
+ endByte: end
3564
+ };
3565
+ }
3566
+ function telemetrySafeDiagnostic(d, severity) {
3567
+ return {
3568
+ code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3569
+ severity,
3570
+ span: telemetrySafeSpan(d),
3571
+ data: telemetrySafeData(d.data)
3572
+ };
3573
+ }
3574
+ function buildTelemetryPayload(facts, ctx) {
3575
+ let errorCount = 0;
3576
+ let criticalCount = 0;
3577
+ const alerting = [];
3578
+ for (const d of facts.diagnostics) {
3579
+ if (d.severity !== "error" && d.severity !== "critical") continue;
3580
+ if (d.severity === "critical") criticalCount += 1;
3581
+ else errorCount += 1;
3582
+ alerting.push(telemetrySafeDiagnostic(d, d.severity));
3583
+ }
3584
+ if (alerting.length === 0) return null;
3585
+ const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3586
+ const env = ctx.env ?? {};
3587
+ const runtime = ctx.runtime ?? {
3588
+ node: process.versions.node,
3589
+ platform: process.platform,
3590
+ arch: process.arch
3591
+ };
3592
+ const framework = frameworkFromLabel(facts.label);
3593
+ return {
3594
+ version: TELEMETRY_PAYLOAD_VERSION,
3595
+ installId: ctx.installId,
3596
+ framework,
3597
+ frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3598
+ engineVersion: safeVersion(facts.engineVersion),
3599
+ clientVersion: safeVersion(facts.clientVersion),
3600
+ nodeVersion: safeVersion(runtime.node) ?? "unknown",
3601
+ os: safeToken(runtime.platform),
3602
+ arch: safeToken(runtime.arch),
3603
+ ci: env.CI === "true",
3604
+ complexity: complexityLabel(facts.preset, facts.complexity),
3605
+ fileCountBucket: fileCountBucket(facts.fileCount),
3606
+ durationBucket: durationBucket(facts.durationMs),
3607
+ diagnostics: kept,
3608
+ errorCount,
3609
+ criticalCount,
3610
+ droppedCount: alerting.length - kept.length
3611
+ };
3612
+ }
3613
+ const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3614
+ function safeVersion(value) {
3615
+ return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3616
+ }
3617
+ function safeToken(value) {
3618
+ return TOKEN_PATTERN.test(value) ? value : "unknown";
3619
+ }
3620
+ const TELEMETRY_NOTICE = [
3621
+ "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3622
+ "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3623
+ "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3624
+ "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3625
+ "AfterPack: file counts and durations, and a random install id that rotates every 30",
3626
+ "AfterPack: days.",
3627
+ "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3628
+ "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3629
+ "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3630
+ "AfterPack: `telemetry: { enabled: false }` in your config.",
3631
+ "AfterPack: https://www.afterpack.dev/privacy"
3632
+ ];
3633
+ const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3634
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3635
+ function readState(file, now) {
3636
+ try {
3637
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
3638
+ if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3639
+ installId: parsed.installId,
3640
+ rotatedAt: parsed.rotatedAt,
3641
+ noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
3642
+ };
3643
+ } catch {}
3644
+ return {
3645
+ installId: randomUUID(),
3646
+ rotatedAt: now,
3647
+ noticeShownAt: 0
3648
+ };
3649
+ }
3650
+ function writeState(file, state) {
3651
+ try {
3652
+ mkdirSync(dirname(file), { recursive: true });
3653
+ writeFileSync(file, `${JSON.stringify(state)}\n`, "utf8");
3654
+ } catch {}
3655
+ }
3656
+ function telemetryUrl(env) {
3657
+ const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3658
+ return `${base}${TELEMETRY_ENDPOINT_PATH}`;
3659
+ }
3660
+ const TELEMETRY_BODY_LIMIT = 64 * 1024;
3661
+ async function reportTelemetryNotices(response, logger) {
3662
+ if (!response || response.status !== 202 || typeof response.text !== "function") return;
3663
+ const declared = Number(response.headers?.get?.("content-length"));
3664
+ if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3665
+ await response.body?.cancel().catch(() => {});
3666
+ return;
3667
+ }
3668
+ const text = await response.text();
3669
+ if (text.length > TELEMETRY_BODY_LIMIT) return;
3670
+ let body;
3671
+ try {
3672
+ body = JSON.parse(text);
3673
+ } catch {
3674
+ return;
3675
+ }
3676
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3677
+ reportNotices(body.notices, logger);
3678
+ }
3679
+ function createTelemetryReporter(deps = {}) {
3680
+ const env = deps.env ?? process.env;
3681
+ const logger = deps.logger ?? console;
3682
+ const now = deps.now ?? Date.now;
3683
+ const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3684
+ const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3685
+ return async (facts) => {
3686
+ try {
3687
+ const at = now();
3688
+ const state = readState(stateFile, at);
3689
+ let dirty = false;
3690
+ if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3691
+ state.installId = randomUUID();
3692
+ state.rotatedAt = at;
3693
+ dirty = true;
3694
+ }
3695
+ if (state.noticeShownAt === 0) {
3696
+ for (const line of TELEMETRY_NOTICE) logger.log(line);
3697
+ state.noticeShownAt = at;
3698
+ dirty = true;
3699
+ }
3700
+ if (dirty) writeState(stateFile, state);
3701
+ if (facts === null) return;
3702
+ const payload = buildTelemetryPayload(facts, {
3703
+ installId: state.installId,
3704
+ env
3705
+ });
3706
+ if (payload === null) return;
3707
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3708
+ if (typeof fetchImpl !== "function") return;
3709
+ const response = await fetchImpl(telemetryUrl(env), {
3710
+ method: "POST",
3711
+ headers: { "content-type": "application/json" },
3712
+ body: JSON.stringify(payload),
3713
+ signal: AbortSignal.timeout(timeoutMs)
3714
+ });
3715
+ await reportTelemetryNotices(response, logger);
3716
+ } catch {}
3717
+ };
3718
+ }
3719
+
3720
+ //#endregion
3721
+ //#region src/pass.ts
3722
+ function silenceSummaryLines(logger, level) {
3723
+ if (level !== "none") return logger;
3724
+ return {
3725
+ warn: (m) => logger.warn(m),
3726
+ log: () => {}
3727
+ };
3728
+ }
3729
+ function parseSourceMap(json) {
3730
+ if (!json) return null;
3731
+ try {
3732
+ const m = JSON.parse(json);
3733
+ if (typeof m.mappings !== "string") return null;
3734
+ return {
3735
+ sources: m.sources ?? [],
3736
+ mappings: m.mappings,
3737
+ sourcesContent: Array.isArray(m.sourcesContent) ? m.sourcesContent : void 0
3738
+ };
3739
+ } catch {
3740
+ return null;
3741
+ }
3742
+ }
3743
+ function fileFailure(f, source) {
3744
+ if (f.status !== "success") {
3745
+ const reason = sanitizeServerText(f.error);
3746
+ if (reason) return reason;
3747
+ return f.status === "failure" ? "empty output" : `the engine reported status "${sanitizeServerText(f.status, 32)}"`;
3748
+ }
3749
+ if (typeof f.unobfuscated !== "boolean") return "the engine result does not say whether the file was obfuscated";
3750
+ if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
3751
+ return null;
3752
+ }
3753
+ async function readEngineVersion(engine) {
3754
+ try {
3755
+ return await engine.version?.() ?? null;
3756
+ } catch {
3757
+ return null;
3758
+ }
3759
+ }
3760
+ function describeLevel(preset, complexity) {
3761
+ if (complexity === void 0) return `preset "${preset ?? DEFAULT_PRESET}"`;
3762
+ if (preset === void 0) return `complexity target ${complexity}`;
3763
+ return `preset "${preset}" with complexity target ${complexity}`;
3764
+ }
3765
+ async function runObfuscationPass(options) {
3766
+ const passStartedAt = options.startedAt ?? Date.now();
3767
+ const callerAnchored = options.startedAt !== void 0;
3768
+ const { files, engine, label, gitignoreDir, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
3769
+ const logger = silenceSummaryLines(options.logger ?? DEFAULT_LOGGER, options.diagnostics);
3770
+ const prefix = (message) => `[${label}] ${message}`;
3771
+ const style = options.summaryStyle ?? "plugin";
3772
+ assertSupportedCore(options.client, prefix);
3773
+ const onDiskFiles = options.inputs ? files.filter((f) => !options.inputs?.has(f)) : files;
3774
+ const onDiskBytes = new Map(await Promise.all(onDiskFiles.map(async (filePath) => [filePath, await readFile(filePath)])));
3775
+ if (!options.emitToCaller) {
3776
+ const already = detectAlreadyObfuscatedInputs(onDiskFiles, combinedProtectionMap.buildDir, onDiskBytes, prefix);
3777
+ if (already) throw new AlreadyObfuscatedError(prefix(formatAlreadyObfuscatedMessage({
3778
+ files: already.files,
3779
+ receiptPath: already.receiptPath,
3780
+ dir: combinedProtectionMap.buildDir
3781
+ })), already.files, already.receiptPath, combinedProtectionMap.buildDir);
3782
+ }
3783
+ const resolvedSeed = resolveBuildSeed(options.seed, {
3784
+ root: gitignoreDir,
3785
+ leg: options.buildLeg ?? combinedProtectionMap.buildDir
3786
+ }, {
3787
+ env,
3788
+ warn: (m) => logger.warn(m)
3789
+ });
3790
+ const seed = resolvedSeed.seed;
3791
+ if (resolvedSeed.mismatch) logger.warn(prefix(`build seed ${seed} does not match leg "${resolvedSeed.mismatch.leg}" of this same build, which used ${resolvedSeed.mismatch.seed} — pin the same \`seed\` on every leg (or none) so the bundles share one polymorphic layout.`));
3792
+ const directivesEnabled = options.directivesEnabled ?? false;
3793
+ const bundledCapture = options.capturedByFile != null;
3794
+ const postMinifyMode = directivesEnabled && options.postMinify === true && !bundledCapture;
3795
+ const sourceByPath = new Map();
3796
+ let coloredRegionCount = 0;
3797
+ let directivesNeededMap = false;
3798
+ let postMinifyMapsSeen = 0;
3799
+ const postMinifyDiagnostics = [];
3800
+ const postMinifyRenameGlobals = [];
3801
+ const inputs = files.map((filePath) => {
3802
+ const provided = options.inputs?.get(filePath);
3803
+ const source = provided ? provided.source : (onDiskBytes.get(filePath) ?? readFileSync(filePath)).toString("utf8");
3804
+ sourceByPath.set(filePath, source);
3805
+ const inputSourceMap = provided ? provided.sourceMap ?? null : discoverInputSourceMap(filePath, source);
3806
+ let regions;
3807
+ const modules = options.capturedByFile?.get(filePath);
3808
+ if (modules?.some((m) => m.directives.length > 0)) {
3809
+ const map = parseSourceMap(inputSourceMap);
3810
+ if (!map) directivesNeededMap = true;
3811
+ else {
3812
+ const colored = colorRegions(source, map, modules, (m) => logger.warn(prefix(m)));
3813
+ if (colored.length > 0) {
3814
+ regions = colored;
3815
+ coloredRegionCount += colored.length;
3816
+ }
3817
+ }
3818
+ } else if (postMinifyMode) {
3819
+ const map = parseSourceMap(inputSourceMap);
3820
+ if (map?.sourcesContent && map.sourcesContent.length > 0) {
3821
+ postMinifyMapsSeen += 1;
3822
+ const mods = [];
3823
+ for (let i = 0; i < map.sourcesContent.length; i++) {
3824
+ const content = map.sourcesContent[i];
3825
+ const id = map.sources[i];
3826
+ if (!content || id == null || !content.includes(DIRECTIVE_MARKER)) continue;
3827
+ const scan = scanDirectives(content);
3828
+ for (const d of scan.diagnostics) postMinifyDiagnostics.push(`${id} (${d.line}:${d.column}): ${d.message}`);
3829
+ if (scan.renameGlobals) postMinifyRenameGlobals.push(`${id} (bundled into ${filePath})`);
3830
+ if (scan.directives.length > 0) mods.push({
3831
+ id,
3832
+ source: content,
3833
+ directives: scan.directives,
3834
+ srcIndex: i
3835
+ });
3836
+ }
3837
+ if (mods.length > 0) {
3838
+ const colored = colorRegions(source, map, mods, (m) => logger.warn(prefix(m)));
3839
+ if (colored.length > 0) {
3840
+ regions = colored;
3841
+ coloredRegionCount += colored.length;
3842
+ }
3843
+ }
3844
+ }
3845
+ }
3846
+ return {
3847
+ path: filePath,
3848
+ source,
3849
+ sourceMap: inputSourceMap ?? void 0,
3850
+ regions
3851
+ };
3852
+ });
3853
+ onDiskBytes.clear();
3854
+ const hasBundlerSourcemap = (options.hasBundlerSourcemap ?? false) || inputs.some((i) => i.sourceMap != null);
3855
+ const policy = resolveReportPolicy(env, artifactOptions, {
3856
+ hasBundlerSourcemap,
3857
+ inPlaceOutput: true
3858
+ });
3859
+ ensureGitignore(combinedProtectionMap.buildDir);
3860
+ if (policy.autoEnableBundlerSourcemap && options.messages?.autoEnableBundlerSourcemap) logger.warn(prefix(options.messages.autoEnableBundlerSourcemap));
3861
+ if (options.emitToCaller && artifactOptions.build?.backup === true) logger.warn(prefix("build.backup:true is not available on this build — the obfuscated output is handed back in memory, so there is no emitted file for a `.backup.<hash>` copy to sit beside."));
3862
+ const capture = captureDirectiveRegions(inputs, options.regions, directivesEnabled && !bundledCapture && !(postMinifyMode && inputs.length > 1));
3863
+ for (const d of capture.diagnostics) logger.warn(prefix(`directive at ${d.line}:${d.column}: ${d.message}`));
3864
+ for (const d of postMinifyDiagnostics) logger.warn(prefix(`directive in ${d}`));
3865
+ const bundledRenameGlobals = [];
3866
+ if (bundledCapture && directivesEnabled) {
3867
+ for (const [file, modules] of options.capturedByFile ?? []) for (const mod of modules) if (mod.renameGlobals) bundledRenameGlobals.push(`${mod.id} (bundled into ${file})`);
3868
+ }
3869
+ const renameGlobalsRefused = [
3870
+ ...capture.renameGlobalsRefused,
3871
+ ...postMinifyRenameGlobals,
3872
+ ...bundledRenameGlobals
3873
+ ];
3874
+ if (renameGlobalsRefused.length > 0) logger.warn(prefix(renameGlobalsRefusalMessage(renameGlobalsRefused, files.length)));
3875
+ if (capture.deferredFiles > 0) logger.warn(prefix(`found @afterpack directives in ${capture.deferredFiles} file(s) but this is a multi-file build; enable the bundler's directive capture (backward-coloring) to apply them.`));
3876
+ if (coloredRegionCount > 0) logger.log(prefix(`applied ${coloredRegionCount} directive region(s) across the bundle`));
3877
+ if (directivesNeededMap) logger.warn(prefix("found @afterpack directives in a bundled file with no source map — skipped them (enable the bundler's sourcemap so they can be colored into the emitted output)."));
3878
+ if (postMinifyMode && options.directivesEnabledExplicit === true && files.length > 0 && postMinifyMapsSeen === 0 && options.messages?.directivesNeedClientMaps) logger.warn(prefix(options.messages.directivesNeedClientMaps));
3879
+ const mappedInputs = inputs.filter((i) => i.sourceMap != null).length;
3880
+ if (policy.protectionMap && files.length > 0 && mappedInputs > 0 && mappedInputs < files.length) logger.warn(prefix(`source-map coverage: ${mappedInputs}/${files.length} chunk(s) had a discoverable input source map — the other ${files.length - mappedInputs} are attributed only as opaque dist chunks, so the Protection Map under-reports their original sources.`));
3881
+ const git = artifactOptions.git === false ? null : detectGitContext(artifactOptions.git ?? null, {
3882
+ env,
3883
+ cwd: gitignoreDir
3884
+ });
3885
+ const engineConfig = buildEngineConfig({
3886
+ policy,
3887
+ seed,
3888
+ preset: options.preset,
3889
+ complexity: options.complexity,
3890
+ regions: capture.regions,
3891
+ engine: options.engineConfig,
3892
+ renameGlobals: capture.renameGlobals
3893
+ });
3894
+ if (style !== "cli") logger.log(prefix(`obfuscating ${inputs.length} file(s) at ${describeLevel(options.preset, options.complexity)} ...`));
3895
+ const engineStartedAt = Date.now();
3896
+ const prepMs = engineStartedAt - passStartedAt;
3897
+ const context = buildContext(git, {
3898
+ clientVersion: options.client?.coreVersion,
3899
+ client: clientString(options.client)
3900
+ });
3901
+ let batch;
3902
+ try {
3903
+ batch = await engine.processBatch(inputs, engineConfig, context);
3904
+ } catch (error) {
3905
+ const cloud = toCloudApiError(error, {
3906
+ identity: options.client,
3907
+ prefix
3908
+ });
3909
+ if (!cloud) throw error;
3910
+ reportNotices(cloud.notices, logger, prefix);
3911
+ throw cloud;
3912
+ }
3913
+ const engineEndedAt = Date.now();
3914
+ reportNotices(batch.notices, logger, prefix);
3915
+ const engineMs = engineEndedAt - engineStartedAt;
3916
+ const collected = collectDiagnostics(batch.files);
3917
+ const diagnosticsSummary = reportDiagnostics({
3918
+ diagnostics: collected.diagnostics,
3919
+ malformedEntries: collected.malformedEntries,
3920
+ logger,
3921
+ prefix,
3922
+ verbosity: resolveDiagnosticsVerbosity(options.diagnostics)
3923
+ });
3924
+ if (collected.unknownFiles > 0 && batch.source === "cloud") logger.warn(prefix("engine diagnostics are not returned on the Pro Cloud path — this build's diagnostics were recorded server-side."));
3925
+ const telemetry = options.telemetry;
3926
+ const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
3927
+ const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? await readEngineVersion(engine);
3928
+ if (telemetry && telemetryEnabled) {
3929
+ const facts = {
3930
+ label,
3931
+ projectRoot: gitignoreDir,
3932
+ diagnostics: collected.diagnostics,
3933
+ fileCount: files.length,
3934
+ durationMs: engineEndedAt - passStartedAt,
3935
+ preset: options.preset,
3936
+ complexity: options.complexity,
3937
+ engineVersion,
3938
+ clientVersion: options.clientVersion ?? options.client?.packageVersion ?? null
3939
+ };
3940
+ await telemetry(facts);
3941
+ }
3942
+ const protectionMapDocs = [];
3943
+ const sensitiveArtifactPaths = [];
3944
+ const outputs = [];
3945
+ let inputBytes = 0;
3946
+ let outputBytes = 0;
3947
+ const unobfuscatedFiles = [];
3948
+ let noOp = 0;
3949
+ const transformedFiles = [];
3950
+ const verified = [];
3951
+ for (const f of batch.files) {
3952
+ const source = sourceByPath.get(f.path);
3953
+ if (source === void 0) throw new Error(prefix(`no captured source for engine-returned path ${f.path}`));
3954
+ const failure = fileFailure(f, source);
3955
+ if (failure !== null) throw new Error(prefix(`failed to obfuscate ${f.path}: ${failure}`));
3956
+ inputBytes += Buffer.byteLength(source);
3957
+ outputBytes += Buffer.byteLength(f.code);
3958
+ if (f.unobfuscated === true) unobfuscatedFiles.push(basename(f.path));
3959
+ else if (f.code === source) noOp += 1;
3960
+ else transformedFiles.push(f.path);
3961
+ if (policy.protectionMap && f.protectionMap != null) protectionMapDocs.push(f.protectionMap);
3962
+ verified.push({
3963
+ result: f,
3964
+ source
3965
+ });
3966
+ }
3967
+ if (unobfuscatedFiles.length > 0) if (artifactOptions.allowUnobfuscated === true) for (const name of unobfuscatedFiles) logger.warn(prefix(`${name} could not be obfuscated and SHIPPED AS CLEARTEXT (allowUnobfuscated:true). This is an engine bug — please report it.`));
3968
+ else throw new Error(prefix(`${unobfuscatedFiles.length} file(s) could not be obfuscated and would ship as cleartext: ${unobfuscatedFiles.join(", ")} — fix the engine or set allowUnobfuscated:true`));
3969
+ const writtenFiles = [];
3970
+ const emittedFiles = [];
3971
+ for (const { result: f, source } of verified) {
3972
+ if (options.emitToCaller) {
3973
+ outputs.push({
3974
+ path: f.path,
3975
+ code: f.code,
3976
+ sourceMap: f.sourceMap ?? null
3977
+ });
3978
+ emittedFiles.push(f.path);
3979
+ continue;
3980
+ }
3981
+ const written = writeArtifacts({
3982
+ outPath: f.path,
3983
+ code: f.code,
3984
+ sourceMapJson: f.sourceMap ?? null,
3985
+ protectionMapJson: null,
3986
+ originalSource: source,
3987
+ policy,
3988
+ mode: "framework",
3989
+ logger
3990
+ });
3991
+ writtenFiles.push(written.codePath);
3992
+ if (written.mapPath) sensitiveArtifactPaths.push(written.mapPath);
3993
+ if (written.backupPath) sensitiveArtifactPaths.push(written.backupPath);
3994
+ }
3995
+ if (!options.emitToCaller) options.afterWrite?.();
3996
+ const protectionMapPath = writeCombinedProtectionMap({
3997
+ buildDir: combinedProtectionMap.buildDir,
3998
+ docs: protectionMapDocs,
3999
+ policy,
4000
+ afterpackDir: combinedProtectionMap.afterpackDir,
4001
+ fileName: combinedProtectionMap.fileName,
4002
+ logger
4003
+ });
4004
+ if (protectionMapPath) sensitiveArtifactPaths.push(protectionMapPath);
4005
+ for (const artifactPath of sensitiveArtifactPaths) if (warnIfPublicPath(artifactPath, logger)) break;
4006
+ let receiptPath = null;
4007
+ let deferredReceipt = null;
4008
+ const engineSource = batch.source === "local" || batch.source === "cloud" ? batch.source : null;
4009
+ const receiptFields = {
4010
+ tool: label,
4011
+ engine: engineSource,
4012
+ engineVersion,
4013
+ seed,
4014
+ seedOrigin: resolvedSeed.origin,
4015
+ bundler: options.receipt?.bundler ?? "unknown",
4016
+ buildId: options.receipt?.buildId ?? null,
4017
+ transformed: transformedFiles
4018
+ };
4019
+ if (options.emitToCaller) deferredReceipt = {
4020
+ ...receiptFields,
4021
+ dir: combinedProtectionMap.buildDir,
4022
+ files: emittedFiles
4023
+ };
4024
+ else {
4025
+ receiptPath = writeProtectionReceipt({
4026
+ ...receiptFields,
4027
+ dir: combinedProtectionMap.buildDir,
4028
+ files: writtenFiles
4029
+ });
4030
+ if (style !== "cli") logger.log(prefix(`wrote protection receipt -> ${receiptPath} (afterpack verify)`));
4031
+ }
4032
+ const writeEndedAt = Date.now();
4033
+ const writeMs = writeEndedAt - engineEndedAt;
4034
+ const totalMs = writeEndedAt - passStartedAt;
4035
+ const cloudMs = engineSource === "cloud" ? engineMs : null;
4036
+ const timing = {
4037
+ totalMs,
4038
+ prepMs,
4039
+ engineMs,
4040
+ writeMs,
4041
+ cloudMs,
4042
+ engineSource,
4043
+ callerAnchored
4044
+ };
4045
+ const summaryVerbosity = resolveDiagnosticsVerbosity(options.diagnostics);
4046
+ const seedSuffix = summaryVerbosity === "all" ? ` · seed ${seed} (${resolvedSeed.mismatch ? "MISMATCH" : resolvedSeed.origin})` : "";
4047
+ logger.log(formatPassSummary({
4048
+ label,
4049
+ fileCount: files.length,
4050
+ inputBytes,
4051
+ outputBytes,
4052
+ unobfuscatedCount: unobfuscatedFiles.length,
4053
+ noOpCount: noOp,
4054
+ elapsedMs: totalMs
4055
+ }, style, options.colorGlyph) + seedSuffix);
4056
+ return {
4057
+ fileCount: files.length,
4058
+ protectionMapPath,
4059
+ receiptPath,
4060
+ deferredReceipt,
4061
+ policy,
4062
+ seed,
4063
+ seedOrigin: resolvedSeed.origin,
4064
+ timing,
4065
+ diagnostics: diagnosticsSummary,
4066
+ transformedFiles,
4067
+ ...options.emitToCaller ? { outputs } : {}
4068
+ };
4069
+ }
4070
+
4071
+ //#endregion
4072
+ //#region src/plugin-config.ts
4073
+ const PLUGIN_LOCAL_KEYS = ["git"];
4074
+ function proKeyMessage(surface) {
4075
+ return `\`key\` is not a plugin option (${surface}) — no plugin forwards it, and a bundler config is committed source. Set \`AFTERPACK_KEY\` in the environment, or \`key\` in afterpack.json, instead — without it the build runs locally, without Pro protection.`;
4076
+ }
4077
+ function normalizePluginOptions(input, localKeys, surface) {
4078
+ const config = {};
4079
+ const issues = [];
4080
+ if (input === void 0 || input === null) return {
4081
+ config,
4082
+ issues
4083
+ };
4084
+ if (!isPlainObject(input)) {
4085
+ issues.push({
4086
+ path: "",
4087
+ message: `configuration (${surface}) must be an object`
4088
+ });
4089
+ return {
4090
+ config,
4091
+ issues
4092
+ };
4093
+ }
4094
+ const local = new Set([...PLUGIN_LOCAL_KEYS, ...localKeys]);
4095
+ for (const [name, value] of Object.entries(input)) {
4096
+ if (value === void 0 || local.has(name)) continue;
4097
+ if (name === "key") {
4098
+ issues.push({
4099
+ path: name,
4100
+ message: proKeyMessage(surface)
4101
+ });
4102
+ continue;
4103
+ }
4104
+ if (CONFIG_BY_PATH.has(name)) {
4105
+ config[name] = value;
4106
+ continue;
4107
+ }
4108
+ if (CONFIG_PREFIXES.has(name)) {
4109
+ const existing = config[name];
4110
+ config[name] = isPlainObject(value) && isPlainObject(existing) ? deepMerge(existing, value) : value;
4111
+ continue;
4112
+ }
4113
+ issues.push({
4114
+ path: name,
4115
+ message: unknownKeyMessage(name, surface)
4116
+ });
4117
+ }
4118
+ return {
4119
+ config,
4120
+ issues
4121
+ };
4122
+ }
4123
+ function passSettings(resolved) {
4124
+ const settings = resolved.options;
4125
+ return {
4126
+ artifactOptions: settings.artifactOptions,
4127
+ seed: settings.seed,
4128
+ preset: settings.preset,
4129
+ complexity: settings.complexity,
4130
+ regions: settings.regions,
4131
+ engineConfig: resolved.engineConfig,
4132
+ diagnostics: settings.diagnostics?.level,
4133
+ directivesEnabled: settings.directives.enabled,
4134
+ directivesEnabledExplicit: settings.directives.explicit
4135
+ };
4136
+ }
4137
+ function unsupportedIssues(unsupported, merged, layers) {
4138
+ if (!unsupported) return [];
4139
+ const out = [];
4140
+ for (const [path, reason] of Object.entries(unsupported)) {
4141
+ const resolved = getPath(merged, path);
4142
+ if (resolved === void 0 || resolved === false) continue;
4143
+ if (Array.isArray(resolved) && resolved.length === 0) continue;
4144
+ const from = [...layers].reverse().find((l) => getPath(l.config, path) !== void 0);
4145
+ out.push(` ${from?.name ?? "configuration"}: \`${path}\` is not supported here — ${reason}`);
4146
+ }
4147
+ return out;
4148
+ }
4149
+ function applyResolvedKey(config, env = process.env) {
4150
+ const key = getPath(config, "key");
4151
+ if (typeof key === "string" && key !== "") env.AFTERPACK_KEY = key;
4152
+ }
4153
+ function sameRankConflicts(options, cli) {
4154
+ const issues = [];
4155
+ for (const key of CONFIG_KEYS) {
4156
+ const fromOptions = getPath(options, key.path);
4157
+ const fromCli = getPath(cli, key.path);
4158
+ if (fromOptions === void 0 || fromCli === void 0) continue;
4159
+ if (JSON.stringify(fromOptions) === JSON.stringify(fromCli)) continue;
4160
+ issues.push({
4161
+ path: key.path,
4162
+ message: `\`${key.path}\` is set twice at the same precedence — the options object says ${JSON.stringify(fromOptions)}, the command line says ${JSON.stringify(fromCli)}. A flag and an option rank equally, so neither wins: set it in one of them, or move it to afterpack.json.`
4163
+ });
4164
+ }
4165
+ return issues;
4166
+ }
4167
+ const NO_ARGV = {
4168
+ config: EMPTY_CONFIG,
4169
+ positionals: [],
4170
+ help: false,
4171
+ version: false,
4172
+ issues: []
4173
+ };
4174
+ function argvOnlyAnswer(cli) {
4175
+ const config = EMPTY_CONFIG;
4176
+ return {
4177
+ config,
4178
+ options: toPluginOptions(config),
4179
+ engineConfig: toEngineConfig(config),
4180
+ configFile: null,
4181
+ positionals: cli.positionals,
4182
+ help: cli.help,
4183
+ version: cli.version
4184
+ };
4185
+ }
4186
+ function resolvePluginConfig(input) {
4187
+ const cli = input.argv ? parseCliOptions(input.argv) : NO_ARGV;
4188
+ if (cli.help || cli.version) return argvOnlyAnswer(cli);
4189
+ const file = loadConfigFile(input.cwd ?? process.cwd());
4190
+ const env = parseEnvOptions(input.env ?? process.env);
4191
+ const localKeys = input.localKeys ?? [];
4192
+ const optionsSurface = `the ${input.label} options object`;
4193
+ const normalized = normalizePluginOptions(input.options, localKeys, optionsSurface);
4194
+ const options = validateConfig(normalized.config, optionsSurface);
4195
+ const explicit = mergeConfig(options.config, cli.config);
4196
+ const config = mergeConfig(mergeConfig(file.config, env.config), explicit);
4197
+ const issues = [
4198
+ ...file.issues.map((i) => ` ${file.path ?? CONFIG_FILE_NAME}: ${i.message}`),
4199
+ ...env.issues.map((i) => ` environment: ${i.message}`),
4200
+ ...[...normalized.issues, ...options.issues].map((i) => ` ${optionsSurface}: ${i.message}`),
4201
+ ...cli.issues.map((i) => ` command line: ${i.message}`),
4202
+ ...sameRankConflicts(options.config, cli.config).map((i) => ` ${i.message}`),
4203
+ ...unsupportedIssues(input.unsupported, config, [
4204
+ {
4205
+ name: file.path ?? CONFIG_FILE_NAME,
4206
+ config: file.config
4207
+ },
4208
+ {
4209
+ name: "environment",
4210
+ config: env.config
4211
+ },
4212
+ {
4213
+ name: optionsSurface,
4214
+ config: options.config
4215
+ },
4216
+ {
4217
+ name: "command line",
4218
+ config: cli.config
4219
+ }
4220
+ ])
4221
+ ];
4222
+ if (issues.length > 0) throw new Error([`[${input.label}] refusing to build with an invalid configuration:`, ...issues].join("\n"));
4223
+ applyResolvedKey(config, input.env ?? process.env);
4224
+ const pluginOptions = toPluginOptions(config);
4225
+ const supplied = isPlainObject(input.options) ? input.options : {};
4226
+ const localArtifactOptions = {};
4227
+ for (const name of PLUGIN_LOCAL_KEYS) if (supplied[name] !== void 0) localArtifactOptions[name] = supplied[name];
4228
+ return {
4229
+ config,
4230
+ options: {
4231
+ ...pluginOptions,
4232
+ artifactOptions: {
4233
+ ...pluginOptions.artifactOptions,
4234
+ ...localArtifactOptions
4235
+ }
4236
+ },
4237
+ engineConfig: toEngineConfig(config),
4238
+ configFile: file.path,
4239
+ positionals: cli.positionals,
4240
+ help: false,
4241
+ version: false
4242
+ };
4243
+ }
4244
+
4245
+ //#endregion
4246
+ export { AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, PROTECTION_RECEIPT_FILE, SEED_ENV_VAR, UnreadableReceiptError, applyBundleOutput, applyResolvedKey, collectBundleJs, collectJsFiles, collectSourceMaps, createTelemetryReporter, decodeDataUri, discoverInputSourceMap, extractSourceMappingURL, findUpward, getPath, installedRequiredLine, loadConfigFile, mergeConfig, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Of, toEngineConfig, toPluginOptions, validateConfig, verifyProtectionReceipt, withSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeProtectionReceipt };