@afterpack/integration-utils 0.2.3 → 0.2.5

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.cjs CHANGED
@@ -21,17 +21,117 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  }) : target, mod));
22
22
 
23
23
  //#endregion
24
+ const node_crypto = __toESM(require("node:crypto"));
24
25
  const node_fs = __toESM(require("node:fs"));
25
26
  const node_path = __toESM(require("node:path"));
26
27
  const node_module = __toESM(require("node:module"));
27
28
  const node_zlib = __toESM(require("node:zlib"));
28
- const node_crypto = __toESM(require("node:crypto"));
29
29
  const node_url = __toESM(require("node:url"));
30
- const node_fs_promises = __toESM(require("node:fs/promises"));
31
30
  const node_child_process = __toESM(require("node:child_process"));
32
- const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
33
31
  const node_os = __toESM(require("node:os"));
32
+ const node_fs_promises = __toESM(require("node:fs/promises"));
33
+ const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
34
+
35
+ //#region src/atomic-write.ts
36
+ const STAGED_SUFFIX = ".afterpack-tmp";
37
+ function stagedPath(path) {
38
+ return `${path}${STAGED_SUFFIX}`;
39
+ }
40
+ function sha256Hex(content) {
41
+ return (0, node_crypto.createHash)("sha256").update(content).digest("hex");
42
+ }
43
+ function writeFileAtomic(path, content) {
44
+ const staged = stagedPath(path);
45
+ let mode = null;
46
+ try {
47
+ mode = (0, node_fs.statSync)(path).mode & 4095;
48
+ } catch {
49
+ mode = null;
50
+ }
51
+ try {
52
+ (0, node_fs.writeFileSync)(staged, content);
53
+ if (mode !== null) (0, node_fs.chmodSync)(staged, mode);
54
+ (0, node_fs.renameSync)(staged, path);
55
+ } catch (error) {
56
+ try {
57
+ (0, node_fs.rmSync)(staged, { force: true });
58
+ } catch {}
59
+ throw error;
60
+ }
61
+ }
62
+
63
+ //#endregion
64
+ //#region src/angular-integrity.ts
65
+ const SRI_ATTR = /\b(src|href)\s*=\s*"([^"]+)"[^>]*\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"/g;
66
+ const SRI_ATTR_REVERSED = /\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"[^>]*\b(src|href)\s*=\s*"([^"]+)"/g;
67
+ function digest(bytes, algo, enc) {
68
+ return (0, node_crypto.createHash)(algo).update(bytes).digest(enc);
69
+ }
70
+ function fileFor(baseDir, ref) {
71
+ if (/^[a-z][a-z0-9+.-]*:/i.test(ref) || ref.startsWith("//")) return null;
72
+ const path = ref.split(/[?#]/)[0];
73
+ if (path === "") return null;
74
+ return (0, node_path.join)(baseDir, path);
75
+ }
76
+ function planHtmlIntegrity(browserDir, planned) {
77
+ for (const html of htmlFilesUnder(browserDir)) {
78
+ const text = (0, node_fs.readFileSync)(html, "utf8");
79
+ const rewrite = (algo, ref, match) => {
80
+ const file = fileFor(browserDir, ref);
81
+ if (file === null || !(0, node_fs.existsSync)(file)) return match;
82
+ const hash = digest((0, node_fs.readFileSync)(file), algo, "base64");
83
+ return match.replace(/integrity\s*=\s*"sha(?:256|384|512)-[^"]*"/, `integrity="${algo}-${hash}"`);
84
+ };
85
+ let next = text.replace(SRI_ATTR, (match, _attr, ref, algo) => rewrite(algo, ref, match));
86
+ next = next.replace(SRI_ATTR_REVERSED, (match, algo, _attr, ref) => rewrite(algo, ref, match));
87
+ if (next !== text) planned.set(html, next);
88
+ }
89
+ }
90
+ function htmlFilesUnder(dir) {
91
+ const out = [];
92
+ for (const entry of (0, node_fs.readdirSync)(dir, {
93
+ recursive: true,
94
+ encoding: "utf8"
95
+ })) if (entry.endsWith(".html")) out.push((0, node_path.join)(dir, entry));
96
+ return out;
97
+ }
98
+ const PLUGIN_LABEL = "@afterpack/angular";
99
+ function planNgswHashTable(browserDir, label, planned) {
100
+ const ngsw = (0, node_path.join)(browserDir, "ngsw.json");
101
+ if (!(0, node_fs.existsSync)(ngsw)) return;
102
+ const config = JSON.parse((0, node_fs.readFileSync)(ngsw, "utf8"));
103
+ const table = config.hashTable;
104
+ if (!table) return;
105
+ for (const url of Object.keys(table)) {
106
+ const file = (0, node_path.join)(browserDir, url.replace(/^\//, ""));
107
+ if (!(0, node_fs.existsSync)(file) || !(0, node_fs.statSync)(file).isFile()) throw new Error(`${label}: ngsw.json names ${url}, which is not in the browser output after obfuscation. AfterPack cannot recompute the service worker hash table. Rebuild, or disable the service worker for this build.`);
108
+ table[url] = digest(planned.get(file) ?? (0, node_fs.readFileSync)(file), "sha1", "hex");
109
+ }
110
+ planned.set(ngsw, `${JSON.stringify(config, null, 2)}\n`);
111
+ }
112
+ function planAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
113
+ const refusal = angularServerManifestRefusal(outputRoot);
114
+ if (refusal !== null) throw new Error(`${label}: ${refusal} — obfuscate only the browser output, or remove @afterpack/angular from the SSR build.`);
115
+ const planned = new Map();
116
+ planHtmlIntegrity(browserDir, planned);
117
+ planNgswHashTable(browserDir, label, planned);
118
+ return planned;
119
+ }
120
+ function recomputeAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
121
+ for (const [path, text] of planAngularIntegrity(outputRoot, browserDir, label)) writeFileAtomic(path, text);
122
+ }
123
+ function angularServerManifestRefusal(outputRoot) {
124
+ const serverDir = (0, node_path.join)(outputRoot, "server");
125
+ if (!(0, node_fs.existsSync)(serverDir)) return null;
126
+ for (const entry of (0, node_fs.readdirSync)(serverDir)) {
127
+ if (!/angular-app-(?:engine-)?manifest\.mjs$/.test(entry)) continue;
128
+ const text = (0, node_fs.readFileSync)((0, node_path.join)(serverDir, entry), "utf8");
129
+ if (/\bhash\s*:\s*['"`]/.test(text) || /\bintegrity\s*:/.test(text)) return `${entry} embeds asset hashes that AfterPack cannot recompute after renaming and obfuscating the browser output, so the SSR ETags would be stale. This Angular server build is not supported`;
130
+ }
131
+ return null;
132
+ }
34
133
 
134
+ //#endregion
35
135
  //#region ../protection-map/codec.mjs
36
136
  const COMPACT_SCHEMA_VERSION = 5;
37
137
  const DICT_FIELDS = [
@@ -297,6 +397,91 @@ function renderProtectionMapHtml(raw, { template, includeLineage = true } = {})
297
397
  };
298
398
  }
299
399
 
400
+ //#endregion
401
+ //#region src/home.ts
402
+ const AFTERPACK_DIR = ".afterpack";
403
+ const STRONG_MARKERS = [
404
+ "afterpack.json",
405
+ ".git",
406
+ "package-lock.json",
407
+ "npm-shrinkwrap.json",
408
+ "pnpm-lock.yaml",
409
+ "yarn.lock",
410
+ "bun.lock",
411
+ "bun.lockb"
412
+ ];
413
+ const WEAK_MARKERS = ["package.json"];
414
+ const DIAG_AFTERPACK_DIR_IN_OUTPUT = "DIAG_AFTERPACK_DIR_IN_OUTPUT";
415
+ const DIAG_RECEIPT_UNWRITABLE = "DIAG_RECEIPT_UNWRITABLE";
416
+ var AfterpackFilesError = class extends Error {
417
+ code;
418
+ summary;
419
+ fix;
420
+ constructor(code, summary, fix) {
421
+ super(`${summary} ${fix}`);
422
+ this.name = "AfterpackFilesError";
423
+ this.code = code;
424
+ this.summary = summary;
425
+ this.fix = fix;
426
+ }
427
+ };
428
+ function realPath(path) {
429
+ const resolved = (0, node_path.resolve)(path);
430
+ try {
431
+ return node_fs.realpathSync.native(resolved);
432
+ } catch {
433
+ const parent = (0, node_path.dirname)(resolved);
434
+ return parent === resolved ? resolved : (0, node_path.join)(realPath(parent), (0, node_path.basename)(resolved));
435
+ }
436
+ }
437
+ function isWithinDir(dir, path) {
438
+ const rel = (0, node_path.relative)(dir, path);
439
+ return rel === "" || !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
440
+ }
441
+ function markerIn(dir, markers) {
442
+ return markers.find((name) => (0, node_fs.existsSync)((0, node_path.join)(dir, name))) ?? null;
443
+ }
444
+ function nearestMarker(start, markers) {
445
+ for (let current = start;;) {
446
+ const marker = markerIn(current, markers);
447
+ if (marker) return {
448
+ root: current,
449
+ marker
450
+ };
451
+ const parent = (0, node_path.dirname)(current);
452
+ if (parent === current) return null;
453
+ current = parent;
454
+ }
455
+ }
456
+ function afterpackHome(buildDir, options = {}) {
457
+ const realBuildDir = realPath(buildDir);
458
+ const ownMarker = options.fileTarget ? markerIn(realBuildDir, STRONG_MARKERS) : null;
459
+ if (ownMarker !== null) return {
460
+ dir: (0, node_path.join)(realBuildDir, AFTERPACK_DIR),
461
+ projectRoot: realBuildDir,
462
+ marker: ownMarker,
463
+ strong: true,
464
+ buildDir: realBuildDir
465
+ };
466
+ const start = (0, node_path.dirname)(realBuildDir);
467
+ const strong = nearestMarker(start, STRONG_MARKERS);
468
+ const found = strong ?? nearestMarker(start, WEAK_MARKERS);
469
+ const projectRoot = found?.root ?? start;
470
+ const dir = (0, node_path.join)(projectRoot, AFTERPACK_DIR);
471
+ if (isWithinDir(realBuildDir, dir)) throw new AfterpackFilesError(DIAG_AFTERPACK_DIR_IN_OUTPUT, `AfterPack would keep its files in ${dir}, inside the build output ${realBuildDir}, where they would ship.`, "Point AfterPack at a build directory below your project root.");
472
+ return {
473
+ dir,
474
+ projectRoot,
475
+ marker: found?.marker ?? null,
476
+ strong: strong !== null,
477
+ buildDir: realBuildDir
478
+ };
479
+ }
480
+ function describeUnanchoredHome(home) {
481
+ if (home.marker !== null) return null;
482
+ return `no lockfile, afterpack.json, .git or package.json above ${home.buildDir}, so AfterPack keeps its files beside it, in ${home.dir}`;
483
+ }
484
+
300
485
  //#endregion
301
486
  //#region src/paths.ts
302
487
  const COMBINED_PROTECTION_MAP_NAME = "protectionMap.html";
@@ -329,7 +514,6 @@ function findUpward(startDir, fileName, options = {}) {
329
514
 
330
515
  //#endregion
331
516
  //#region src/artifacts.ts
332
- const AFTERPACK_DIR = ".afterpack";
333
517
  const AFTERPACK_GITIGNORE_CONTENT = "*\n";
334
518
  const PUBLIC_SEGMENTS = new Set([
335
519
  "public",
@@ -352,35 +536,55 @@ function appendSourceMappingURL(code, mapPath) {
352
536
  const needsNewline = code.length > 0 && !code.endsWith("\n");
353
537
  return `${code}${needsNewline ? "\n" : ""}${comment}\n`;
354
538
  }
355
- function writeArtifacts(input) {
356
- const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
357
- const mode = input.mode ?? "single";
358
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
359
- const logger = input.logger ?? DEFAULT_LOGGER;
539
+ function planArtifactWrites(input) {
540
+ const { outPath, code, sourceMapJson, originalSource, policy } = input;
360
541
  const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
361
- const paths = resolveArtifactPaths(outPath, mode, hash);
362
- const result = {
542
+ const paths = resolveArtifactPaths(outPath, input.mode ?? "single", hash);
543
+ const plan = {
363
544
  codePath: outPath,
364
545
  mapPath: null,
365
546
  backupPath: null,
366
- protectionMapPath: null,
367
- wroteSourceMappingURL: false
547
+ wroteSourceMappingURL: false,
548
+ writes: []
368
549
  };
369
550
  if (policy.backup && originalSource != null && paths.backupPath != null) {
370
- (0, node_fs.writeFileSync)(paths.backupPath, originalSource);
371
- result.backupPath = paths.backupPath;
551
+ plan.writes.push({
552
+ path: paths.backupPath,
553
+ content: originalSource
554
+ });
555
+ plan.backupPath = paths.backupPath;
372
556
  }
373
557
  const willWriteMap = policy.sourceMap && sourceMapJson != null;
374
558
  let finalCode = code;
375
559
  if (willWriteMap && policy.emitSourceMappingURL) {
376
560
  finalCode = appendSourceMappingURL(code, paths.mapPath);
377
- result.wroteSourceMappingURL = true;
561
+ plan.wroteSourceMappingURL = true;
378
562
  }
379
- (0, node_fs.writeFileSync)(outPath, finalCode);
563
+ plan.writes.push({
564
+ path: outPath,
565
+ content: finalCode
566
+ });
380
567
  if (willWriteMap && sourceMapJson != null) {
381
- (0, node_fs.writeFileSync)(paths.mapPath, sourceMapJson);
382
- result.mapPath = paths.mapPath;
568
+ plan.writes.push({
569
+ path: paths.mapPath,
570
+ content: sourceMapJson
571
+ });
572
+ plan.mapPath = paths.mapPath;
383
573
  }
574
+ return plan;
575
+ }
576
+ function writeArtifacts(input) {
577
+ const { protectionMapJson, policy } = input;
578
+ const mode = input.mode ?? "single";
579
+ const afterpackDir = input.afterpackDir;
580
+ const logger = input.logger ?? DEFAULT_LOGGER;
581
+ const paths = resolveArtifactPaths(input.outPath, mode);
582
+ const { writes,...planned } = planArtifactWrites(input);
583
+ for (const write of writes) writeFileAtomic(write.path, write.content);
584
+ const result = {
585
+ ...planned,
586
+ protectionMapPath: null
587
+ };
384
588
  if (mode === "single" && policy.protectionMap && protectionMapJson != null) {
385
589
  (0, node_fs.mkdirSync)(afterpackDir, { recursive: true });
386
590
  ensureAfterpackGitignore(afterpackDir);
@@ -713,7 +917,7 @@ function buildProjectFileTree(files) {
713
917
  }
714
918
  function writeCombinedProtectionMap(input) {
715
919
  const { buildDir, docs, policy } = input;
716
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
920
+ const afterpackDir = input.afterpackDir;
717
921
  const logger = input.logger ?? DEFAULT_LOGGER;
718
922
  if (!policy.protectionMap || docs.length === 0) return null;
719
923
  (0, node_fs.mkdirSync)(afterpackDir, { recursive: true });
@@ -991,7 +1195,7 @@ const CONFIG_KEYS = [
991
1195
  tier: "free",
992
1196
  surface: "engine",
993
1197
  item: { kind: "boolean" },
994
- default: "true in development when an input map exists; false in production"
1198
+ default: "false; true in development mode when an input map exists"
995
1199
  },
996
1200
  {
997
1201
  path: "sourceMap.sourcesContent",
@@ -1000,7 +1204,7 @@ const CONFIG_KEYS = [
1000
1204
  tier: "free",
1001
1205
  surface: "engine",
1002
1206
  item: { kind: "boolean" },
1003
- default: "true in development; false in production"
1207
+ default: "false; true in development mode"
1004
1208
  },
1005
1209
  {
1006
1210
  path: "sourceMap.emitUrl",
@@ -1009,7 +1213,7 @@ const CONFIG_KEYS = [
1009
1213
  tier: "free",
1010
1214
  surface: "build",
1011
1215
  item: { kind: "boolean" },
1012
- default: "true in development; false in production"
1216
+ default: "false; true in development mode"
1013
1217
  },
1014
1218
  {
1015
1219
  path: "protectionMap.enabled",
@@ -1148,7 +1352,7 @@ const CONFIG_KEYS = [
1148
1352
  kind: "enum",
1149
1353
  values: BUILD_MODE_VALUES
1150
1354
  },
1151
- default: "detected from the environment"
1355
+ default: "production, unless NODE_ENV is development"
1152
1356
  },
1153
1357
  {
1154
1358
  path: "directives.enabled",
@@ -1269,8 +1473,8 @@ function unknownKeyMessage(path, surface) {
1269
1473
  if (group$1 && group$1.length > 0) {
1270
1474
  const list = group$1.map((child) => `\`${child}\``).join(", ");
1271
1475
  const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1272
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1273
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1476
+ const canonical$1 = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1477
+ const enabled = canonical$1 ? groupBooleanKey(canonical$1) : void 0;
1274
1478
  const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1275
1479
  return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1276
1480
  }
@@ -1604,6 +1808,15 @@ function decodeDataUri(url) {
1604
1808
  return null;
1605
1809
  }
1606
1810
  }
1811
+ function localSourceMapPath(jsPath, url) {
1812
+ if (url.startsWith("data:") || isRemoteSourceMappingURL(url)) return null;
1813
+ const path = url.replace(/[?#].*$/, "");
1814
+ try {
1815
+ return (0, node_path.isAbsolute)(path) ? path : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(path));
1816
+ } catch {
1817
+ return null;
1818
+ }
1819
+ }
1607
1820
  function discoverInputSourceMap(jsPath, code) {
1608
1821
  const adjacent = `${jsPath}.map`;
1609
1822
  if ((0, node_fs.existsSync)(adjacent)) try {
@@ -1618,20 +1831,81 @@ function discoverInputSourceMap(jsPath, code) {
1618
1831
  const url = extractSourceMappingURL(source);
1619
1832
  if (url == null) return null;
1620
1833
  if (url.startsWith("data:")) return decodeDataUri(url);
1621
- if (isRemoteSourceMappingURL(url)) return null;
1622
- let mapPath;
1834
+ const mapPath = localSourceMapPath(jsPath, url);
1835
+ if (mapPath == null || !(0, node_fs.existsSync)(mapPath)) return null;
1623
1836
  try {
1624
- mapPath = (0, node_path.isAbsolute)(url) ? url : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(url));
1837
+ return (0, node_fs.readFileSync)(mapPath, "utf8");
1625
1838
  } catch {
1626
1839
  return null;
1627
1840
  }
1628
- if (!(0, node_fs.existsSync)(mapPath)) return null;
1841
+ }
1842
+ function bundlerSourceMapPaths(jsPath, code, root) {
1843
+ const candidates = [`${jsPath}.map`];
1844
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) {
1845
+ const url = match[1];
1846
+ const local = localSourceMapPath(jsPath, url);
1847
+ if (local != null) candidates.push(local);
1848
+ if (url.startsWith("/") && !url.startsWith("//")) try {
1849
+ candidates.push((0, node_path.resolve)(root, `.${decodeURIComponent(url.replace(/[?#].*$/, ""))}`));
1850
+ } catch {}
1851
+ }
1852
+ return containedSourceMaps(candidates, root);
1853
+ }
1854
+ function realpathOrNull(path) {
1629
1855
  try {
1630
- return (0, node_fs.readFileSync)(mapPath, "utf8");
1856
+ return (0, node_fs.realpathSync)(path);
1631
1857
  } catch {
1632
1858
  return null;
1633
1859
  }
1634
1860
  }
1861
+ function withinRealDir(dir, root) {
1862
+ const rootReal = realpathOrNull(root);
1863
+ const real = realpathOrNull(dir);
1864
+ if (rootReal == null || real == null) return false;
1865
+ if (real === rootReal) return true;
1866
+ return real.startsWith(rootReal.endsWith(node_path.sep) ? rootReal : `${rootReal}${node_path.sep}`);
1867
+ }
1868
+ function containedSourceMaps(paths, root) {
1869
+ const found = new Set();
1870
+ for (const path of paths) {
1871
+ if (!path.endsWith(".map")) continue;
1872
+ const lexical = (0, node_path.resolve)(path);
1873
+ if (!withinRealDir((0, node_path.dirname)(lexical), root)) continue;
1874
+ try {
1875
+ const stat = (0, node_fs.lstatSync)(lexical);
1876
+ if (stat.isFile() || stat.isSymbolicLink()) found.add(lexical);
1877
+ } catch {}
1878
+ }
1879
+ return [...found];
1880
+ }
1881
+ function removeSourceMaps(paths, label) {
1882
+ let removed = 0;
1883
+ for (const path of paths) try {
1884
+ (0, node_fs.unlinkSync)(path);
1885
+ removed++;
1886
+ } catch (error) {
1887
+ if (error.code === "ENOENT") continue;
1888
+ throw new Error(`[${label}] could not remove the source map ${path}, refusing to ship it: ${error}`);
1889
+ }
1890
+ return removed;
1891
+ }
1892
+ function stripCssSourceMappingURLs(paths) {
1893
+ let stripped = 0;
1894
+ for (const path of paths) {
1895
+ let css;
1896
+ try {
1897
+ css = (0, node_fs.readFileSync)(path, "utf8");
1898
+ } catch (error) {
1899
+ if (error.code === "ENOENT") continue;
1900
+ throw error;
1901
+ }
1902
+ const without = withoutCssSourceMappingURL(css);
1903
+ if (without === css) continue;
1904
+ writeFileAtomic(path, without);
1905
+ stripped++;
1906
+ }
1907
+ return stripped;
1908
+ }
1635
1909
 
1636
1910
  //#endregion
1637
1911
  //#region src/bundle.ts
@@ -1663,6 +1937,39 @@ function sourceTypeForBundle(format, entries) {
1663
1937
  for (const entry of entries) if (entry.type !== "chunk") return void 0;
1664
1938
  return sourceTypeForOutputFormat(format);
1665
1939
  }
1940
+ const COMPRESSED_SIBLING = /\.(gz|br|zst|zz|deflate)$/;
1941
+ function entryBytes(entry) {
1942
+ if (entry.type === "chunk") return entry.code === void 0 ? null : Buffer.from(entry.code);
1943
+ if (typeof entry.source === "string") return Buffer.from(entry.source);
1944
+ if (entry.source !== void 0) return Buffer.from(entry.source);
1945
+ return null;
1946
+ }
1947
+ function regenerateCompressedSiblings(bundle, obfuscated, label) {
1948
+ for (const [name, entry] of Object.entries(bundle)) {
1949
+ const match = COMPRESSED_SIBLING.exec(name);
1950
+ if (match === null) continue;
1951
+ const base = name.slice(0, -match[0].length);
1952
+ if (!obfuscated.has(base)) continue;
1953
+ const bytes = entryBytes(bundle[base]);
1954
+ if (bytes === null) continue;
1955
+ if (match[1] === "gz") entry.source = (0, node_zlib.gzipSync)(bytes);
1956
+ else if (match[1] === "br") entry.source = (0, node_zlib.brotliCompressSync)(bytes);
1957
+ else throw new Error(`[${label}] ${name} is a ${match[1]} copy of the obfuscated ${base}, but AfterPack can only regenerate .gz and .br. The precompressed file would hold the plain bytes. Drop the ${match[1]} compressor, or move it after AfterPack.`);
1958
+ }
1959
+ }
1960
+ const SRI_PLUGIN_NAME = /subresource|integrity|(?:^|[^a-z])sri(?:[^a-z]|$)/i;
1961
+ function sriPluginRefusal(plugins, label) {
1962
+ const found = (plugins ?? []).find((plugin) => SRI_PLUGIN_NAME.test(plugin?.name ?? ""));
1963
+ if (!found) return null;
1964
+ return `[${label}] the "${found.name}" plugin computes subresource integrity hashes, which AfterPack cannot support: unless it runs strictly after obfuscation, the integrity attributes pin the plain bytes and the browser blocks every script. AfterPack cannot see plugin ordering, so it refuses. Remove the SRI plugin, or compute integrity from the deployed files after the build.`;
1965
+ }
1966
+ function unsaltedAssetsWarning(entries, salted) {
1967
+ const fileNames = [];
1968
+ for (const entry of entries.values()) if (entry.type !== "chunk" && !salted.has(entry.fileName)) fileNames.push(entry.fileName);
1969
+ fileNames.sort();
1970
+ if (fileNames.length === 0) return null;
1971
+ return `${fileNames.length} JS file(s) reached the bundle as plain assets rather than chunks (${fileNames.join(", ")}); the bundler fixed their content-hashed names before obfuscation, so each keeps its name while its bytes change. Serve them without long-lived caching, or import them as modules so the bundler builds them as chunks.`;
1972
+ }
1666
1973
  function dataUri(json) {
1667
1974
  return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
1668
1975
  }
@@ -1791,7 +2098,7 @@ function collectJsFiles(target, options = {}) {
1791
2098
  if (!stat.isDirectory()) return isCollectableJs((0, node_path.basename)(target)) ? [target] : [];
1792
2099
  return walkJs(target, options.include ?? [], false, options.onNestedProject);
1793
2100
  }
1794
- function entriesOf(dir) {
2101
+ function entriesOf$1(dir) {
1795
2102
  try {
1796
2103
  return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
1797
2104
  } catch {
@@ -1810,12 +2117,13 @@ function isNestedProject(dir) {
1810
2117
  }
1811
2118
  function walkJs(dir, include, readmitted, onNestedProject) {
1812
2119
  const out = [];
1813
- for (const entry of entriesOf(dir)) {
2120
+ for (const entry of entriesOf$1(dir)) {
1814
2121
  const name = entry.name;
1815
2122
  const full = (0, node_path.join)(dir, name);
1816
2123
  const kind = kindOf(entry, full);
1817
2124
  if (kind === null) continue;
1818
2125
  if (kind === "dir") {
2126
+ if (name === AFTERPACK_DIR) continue;
1819
2127
  const skipped = name === NODE_MODULES;
1820
2128
  if (!skipped && !readmitted && isNestedProject(full)) {
1821
2129
  onNestedProject?.(full);
@@ -1834,13 +2142,15 @@ const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
1834
2142
  function collectFiles(dir, accept) {
1835
2143
  if (!(0, node_fs.existsSync)(dir)) return [];
1836
2144
  const out = [];
1837
- for (const entry of entriesOf(dir)) {
2145
+ for (const entry of entriesOf$1(dir)) {
1838
2146
  const name = entry.name;
1839
2147
  const full = (0, node_path.join)(dir, name);
1840
2148
  const kind = kindOf(entry, full);
1841
2149
  if (kind === null) continue;
1842
- if (kind === "dir") out.push(...collectFiles(full, accept));
1843
- else if (accept(name)) out.push(full);
2150
+ if (kind === "dir") {
2151
+ if (name === NODE_MODULES || name === AFTERPACK_DIR || isNestedProject(full)) continue;
2152
+ out.push(...collectFiles(full, accept));
2153
+ } else if (accept(name)) out.push(full);
1844
2154
  }
1845
2155
  return out;
1846
2156
  }
@@ -1989,6 +2299,7 @@ function reportNotices(raw, logger, prefix = (m) => m) {
1989
2299
  //#region src/compat.ts
1990
2300
  const MIN_CORE_VERSION = "0.2.0";
1991
2301
  const SOURCE_TYPE_MIN_CORE_VERSION = "0.2.3";
2302
+ const FILE_SOURCE_TYPE_MIN_CORE_VERSION = "0.2.5";
1992
2303
  const CORE_PACKAGE = "@afterpack/core";
1993
2304
  const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1994
2305
  const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -2063,6 +2374,9 @@ function isBelowVersion(version, minimum) {
2063
2374
  function coreSupportsSourceType(coreVersion) {
2064
2375
  return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, SOURCE_TYPE_MIN_CORE_VERSION);
2065
2376
  }
2377
+ function coreSupportsFileSourceType(coreVersion) {
2378
+ return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, FILE_SOURCE_TYPE_MIN_CORE_VERSION);
2379
+ }
2066
2380
  const CLI_PACKAGE = "afterpack";
2067
2381
  function updateCommand(identity, minVersion) {
2068
2382
  const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
@@ -2347,10 +2661,10 @@ function spaceFormIssue(path, raw, surface) {
2347
2661
  }
2348
2662
  function kebabIssue(key, surface) {
2349
2663
  const suggestion = suggestKey(key);
2350
- const canonical = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2664
+ const canonical$1 = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2351
2665
  return {
2352
2666
  path: key,
2353
- message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical}`
2667
+ message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical$1}`
2354
2668
  };
2355
2669
  }
2356
2670
  function parseAssignment(key, raw, surface) {
@@ -2689,7 +3003,7 @@ function reportDiagnostics(input) {
2689
3003
  //#region src/policy.ts
2690
3004
  function detectProduction(env = {}, opts = {}) {
2691
3005
  if (opts.build?.mode !== void 0) return opts.build.mode === "production";
2692
- return env.NODE_ENV === "production" || env.CI === "true";
3006
+ return env.NODE_ENV !== "development";
2693
3007
  }
2694
3008
  function resolveReportPolicy(env = {}, userOpts = {}, signals = {}) {
2695
3009
  const isProduction = detectProduction(env, userOpts);
@@ -3256,121 +3570,986 @@ function captureDirectiveRegions(inputs, handAuthored, enabled = true) {
3256
3570
  }
3257
3571
 
3258
3572
  //#endregion
3259
- //#region src/git.ts
3260
- const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
3261
- const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
3262
- function sanitizeCommitSha(value) {
3263
- if (typeof value !== "string") return null;
3264
- const sha = value.trim().toLowerCase();
3265
- return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
3266
- }
3267
- function sanitizeGitRef(value) {
3268
- if (typeof value !== "string") return null;
3269
- const ref = value.trim();
3270
- return GIT_REF_PATTERN.test(ref) ? ref : null;
3271
- }
3272
- function contextFrom(rawSha, rawRef) {
3273
- const commitSha = sanitizeCommitSha(rawSha);
3274
- const ref = sanitizeGitRef(rawRef);
3275
- if (commitSha === null && ref === null) return null;
3276
- const context = {};
3277
- if (commitSha !== null) context.commitSha = commitSha;
3278
- if (ref !== null) context.ref = ref;
3279
- return context;
3280
- }
3281
- const CI_SOURCES = [
3282
- ["GITHUB_SHA", "GITHUB_REF_NAME"],
3283
- ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
3284
- ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
3285
- ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
3286
- ["GIT_COMMIT", "BRANCH_NAME"]
3287
- ];
3288
- function ciGitContext(env) {
3289
- for (const [shaVar, refVar] of CI_SOURCES) {
3290
- const context = contextFrom(env[shaVar], env[refVar]);
3291
- if (context !== null) return context;
3292
- }
3293
- return null;
3573
+ //#region src/seed.ts
3574
+ function randomSeed() {
3575
+ const b = (0, node_crypto.randomBytes)(8);
3576
+ const hi = b.readUInt32BE(0) & 2097151;
3577
+ const lo = b.readUInt32BE(4);
3578
+ return hi * 4294967296 + lo;
3294
3579
  }
3295
- const GIT_PROBE_TIMEOUT_MS = 2e3;
3296
- function localGitContext(cwd) {
3297
- let lines;
3580
+ function gitHead() {
3298
3581
  try {
3299
- const out = (0, node_child_process.execFileSync)("git", [
3300
- "rev-parse",
3301
- "HEAD",
3302
- "--abbrev-ref",
3303
- "HEAD"
3304
- ], {
3305
- cwd,
3306
- stdio: [
3307
- "ignore",
3308
- "pipe",
3309
- "ignore"
3310
- ],
3311
- timeout: GIT_PROBE_TIMEOUT_MS,
3312
- maxBuffer: 64 * 1024
3313
- }).toString();
3314
- lines = out.split("\n").map((line) => line.trim());
3582
+ const out = (0, node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], { stdio: [
3583
+ "ignore",
3584
+ "pipe",
3585
+ "ignore"
3586
+ ] }).toString().trim();
3587
+ return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3315
3588
  } catch {
3316
3589
  return null;
3317
3590
  }
3318
- const ref = lines[1] === "HEAD" ? null : lines[1];
3319
- return contextFrom(lines[0], ref);
3320
3591
  }
3321
- function detectGitContext(explicit, deps = {}) {
3322
- if (explicit) {
3323
- const declared = contextFrom(explicit.commitSha, explicit.ref);
3324
- if (declared !== null) return declared;
3325
- }
3326
- const ci = ciGitContext(deps.env ?? process.env);
3327
- if (ci !== null) return ci;
3328
- return (deps.localGit ?? localGitContext)(deps.cwd);
3592
+ const SEED_ENV_VAR = "AFTERPACK_SEED";
3593
+ function parseSeedValue(raw) {
3594
+ return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3329
3595
  }
3330
-
3331
- //#endregion
3332
- //#region src/map-color.ts
3333
- const UTF8 = new TextEncoder();
3334
- const utf8Len = (s) => UTF8.encode(s).length;
3335
- const NON_ASCII = /[\u0080-\uFFFF]/;
3336
- const HIGH_SURROGATE_START = 55296;
3337
- const HIGH_SURROGATE_END = 56319;
3338
- const LOW_SURROGATE_START = 56320;
3339
- const LOW_SURROGATE_END = 57343;
3340
- function charToByteTable(line) {
3341
- const table = new Array(line.length + 1);
3342
- let bytes = 0;
3343
- let i = 0;
3344
- while (i < line.length) {
3345
- table[i] = bytes;
3346
- const code = line.charCodeAt(i);
3347
- if (code < 128) {
3348
- bytes += 1;
3349
- i += 1;
3350
- continue;
3351
- }
3352
- if (code < 2048) {
3353
- bytes += 2;
3354
- i += 1;
3355
- continue;
3356
- }
3357
- if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
3358
- const low = line.charCodeAt(i + 1);
3359
- if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
3360
- table[i + 1] = bytes + 3;
3361
- bytes += 4;
3362
- i += 2;
3363
- continue;
3364
- }
3365
- }
3366
- bytes += 3;
3367
- i += 1;
3596
+ const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3597
+ function sharedSeedState() {
3598
+ const holder = globalThis;
3599
+ holder[SEED_STATE] ??= {
3600
+ sessions: new Map(),
3601
+ ownEnvExports: []
3602
+ };
3603
+ return holder[SEED_STATE];
3604
+ }
3605
+ const { sessions, ownEnvExports } = sharedSeedState();
3606
+ function isOwnEnvExport(env, value) {
3607
+ return ownEnvExports.some((e) => e.env === env && e.value === value);
3608
+ }
3609
+ function openGeneration(root, leg) {
3610
+ let session = sessions.get(root);
3611
+ if (!session) {
3612
+ session = {
3613
+ seed: void 0,
3614
+ generation: 1,
3615
+ legs: [],
3616
+ resolvedByLeg: new Map(),
3617
+ gitFallbackWarned: false
3618
+ };
3619
+ sessions.set(root, session);
3620
+ } else if (session.legs.includes(leg)) {
3621
+ session.seed = void 0;
3622
+ session.generation += 1;
3623
+ session.legs = [];
3624
+ session.resolvedByLeg.clear();
3625
+ session.gitFallbackWarned = false;
3368
3626
  }
3369
- table[line.length] = bytes;
3370
- return table;
3627
+ session.legs.push(leg);
3628
+ return session;
3371
3629
  }
3372
- var ChunkByteIndex = class {
3373
- starts;
3630
+ function resolveWithinSession(input, session, env, deps) {
3631
+ if (typeof input === "number") return {
3632
+ seed: input,
3633
+ origin: "option"
3634
+ };
3635
+ if (typeof input === "string" && input !== "git") return {
3636
+ seed: input,
3637
+ origin: "option"
3638
+ };
3639
+ if (input === "git") {
3640
+ const head = (deps.gitHead ?? gitHead)();
3641
+ if (head) return {
3642
+ seed: head,
3643
+ origin: "git"
3644
+ };
3645
+ if (!session.gitFallbackWarned) {
3646
+ session.gitFallbackWarned = true;
3647
+ (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
3648
+ }
3649
+ }
3650
+ const fromEnv = env[SEED_ENV_VAR];
3651
+ if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3652
+ seed: parseSeedValue(fromEnv),
3653
+ origin: "env"
3654
+ };
3655
+ if (session.seed !== void 0) return {
3656
+ seed: session.seed,
3657
+ origin: "session"
3658
+ };
3659
+ return {
3660
+ seed: (deps.randomSeed ?? randomSeed)(),
3661
+ origin: "fresh"
3662
+ };
3663
+ }
3664
+ function resolveBuildSeed(input, scope, deps = {}) {
3665
+ const env = deps.env ?? process.env;
3666
+ const session = openGeneration(scope.root, scope.leg);
3667
+ const { seed, origin } = resolveWithinSession(input, session, env, deps);
3668
+ if (origin === "env" || origin === "fresh") session.seed = seed;
3669
+ if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3670
+ const value = String(seed);
3671
+ env[SEED_ENV_VAR] = value;
3672
+ const stale = ownEnvExports.findIndex((e) => e.env === env);
3673
+ if (stale >= 0) ownEnvExports.splice(stale, 1);
3674
+ ownEnvExports.push({
3675
+ env,
3676
+ value
3677
+ });
3678
+ }
3679
+ const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3680
+ session.resolvedByLeg.set(scope.leg, seed);
3681
+ return {
3682
+ seed,
3683
+ origin,
3684
+ legs: [...session.legs],
3685
+ generation: session.generation,
3686
+ mismatch: prior && session.generation === 1 ? {
3687
+ leg: prior[0],
3688
+ seed: prior[1]
3689
+ } : null
3690
+ };
3691
+ }
3692
+
3693
+ //#endregion
3694
+ //#region src/telemetry.ts
3695
+ const API_URL_ENV_VAR$1 = "AFTERPACK_API_URL";
3696
+ const DEFAULT_API_URL = "https://api.afterpack.dev";
3697
+ const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3698
+ const TELEMETRY_PAYLOAD_VERSION = 1;
3699
+ const TELEMETRY_TIMEOUT_MS = 1500;
3700
+ const INSTALL_ID_ROTATION_DAYS = 30;
3701
+ const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3702
+ const TELEMETRY_STATE_FILE = (0, node_path.join)((0, node_os.homedir)(), ".afterpack", "telemetry.json");
3703
+ const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3704
+ const DATA_FIELD_WHITELIST = {
3705
+ outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3706
+ parseError: ["parserErrorKind"],
3707
+ engineBug: [
3708
+ "phase",
3709
+ "transform",
3710
+ "nodeKind"
3711
+ ],
3712
+ inflationBudget: [
3713
+ "target",
3714
+ "achieved",
3715
+ "budgetRatio",
3716
+ "inflationRatio"
3717
+ ],
3718
+ configParse: [
3719
+ "category",
3720
+ "line",
3721
+ "column"
3722
+ ]
3723
+ };
3724
+ function resolveTelemetryEnabled(option, env = {}) {
3725
+ if (option !== void 0) return option;
3726
+ return !(env.NODE_ENV === "test" || env.VITEST);
3727
+ }
3728
+ const FRAMEWORK_ENTRIES = [
3729
+ {
3730
+ label: "afterpack",
3731
+ name: "cli"
3732
+ },
3733
+ {
3734
+ label: "afterpack-angular",
3735
+ name: "angular",
3736
+ pkg: "@angular/core"
3737
+ },
3738
+ {
3739
+ label: "afterpack-esbuild",
3740
+ name: "esbuild",
3741
+ pkg: "esbuild"
3742
+ },
3743
+ {
3744
+ label: "afterpack-next",
3745
+ name: "next",
3746
+ pkg: "next"
3747
+ },
3748
+ {
3749
+ label: "afterpack-rollup",
3750
+ name: "rollup",
3751
+ pkg: "rollup"
3752
+ },
3753
+ {
3754
+ label: "afterpack-vite",
3755
+ name: "vite",
3756
+ pkg: "vite"
3757
+ },
3758
+ {
3759
+ label: "afterpack-webpack",
3760
+ name: "webpack",
3761
+ pkg: "webpack"
3762
+ }
3763
+ ];
3764
+ const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3765
+ const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3766
+ function frameworkFromLabel(label) {
3767
+ return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
3768
+ }
3769
+ const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3770
+ function detectFrameworkVersion(projectRoot, framework) {
3771
+ const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3772
+ if (!pkgName) return null;
3773
+ let deps;
3774
+ try {
3775
+ const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(projectRoot, "package.json"), "utf8"));
3776
+ deps = {
3777
+ ...pkg.dependencies,
3778
+ ...pkg.devDependencies
3779
+ };
3780
+ } catch {
3781
+ return null;
3782
+ }
3783
+ const raw = deps[pkgName];
3784
+ if (typeof raw !== "string") return null;
3785
+ const range = raw.trim();
3786
+ return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3787
+ }
3788
+ function complexityLabel(preset, complexity) {
3789
+ if (preset !== void 0) return preset;
3790
+ return complexity === void 0 ? "default" : "custom";
3791
+ }
3792
+ const FILE_COUNT_BUCKETS = [
3793
+ 1,
3794
+ 5,
3795
+ 20,
3796
+ 100,
3797
+ 500,
3798
+ 2e3
3799
+ ];
3800
+ function fileCountBucket(count) {
3801
+ if (!Number.isFinite(count) || count <= 0) return "0";
3802
+ let lower = 1;
3803
+ for (const upper of FILE_COUNT_BUCKETS) {
3804
+ if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3805
+ lower = upper + 1;
3806
+ }
3807
+ return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3808
+ }
3809
+ const DURATION_BUCKETS_MS = [
3810
+ [1e3, "<1s"],
3811
+ [5e3, "1-5s"],
3812
+ [15e3, "5-15s"],
3813
+ [6e4, "15-60s"],
3814
+ [3e5, "60-300s"]
3815
+ ];
3816
+ function durationBucket(ms) {
3817
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
3818
+ for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3819
+ return "300s+";
3820
+ }
3821
+ function safeScalar(value) {
3822
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3823
+ if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3824
+ return null;
3825
+ }
3826
+ function telemetrySafeData(data) {
3827
+ if (!data || typeof data.kind !== "string") return null;
3828
+ const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3829
+ if (kind === null) return null;
3830
+ const out = { kind };
3831
+ for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3832
+ const value = safeScalar(data[field]);
3833
+ if (value !== null) out[field] = value;
3834
+ }
3835
+ return out;
3836
+ }
3837
+ function telemetrySafeSpan(d) {
3838
+ const span = d.span;
3839
+ if (!span) return null;
3840
+ const start = safeScalar(span.startByte);
3841
+ const end = safeScalar(span.endByte);
3842
+ if (typeof start !== "number" || typeof end !== "number") return null;
3843
+ if (start < 0 || end < 0) return null;
3844
+ return {
3845
+ startByte: start,
3846
+ endByte: end
3847
+ };
3848
+ }
3849
+ function telemetrySafeDiagnostic(d, severity) {
3850
+ return {
3851
+ code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3852
+ severity,
3853
+ span: telemetrySafeSpan(d),
3854
+ data: telemetrySafeData(d.data)
3855
+ };
3856
+ }
3857
+ function buildTelemetryPayload(facts, ctx) {
3858
+ let errorCount = 0;
3859
+ let criticalCount = 0;
3860
+ const alerting = [];
3861
+ for (const d of facts.diagnostics) {
3862
+ if (d.severity !== "error" && d.severity !== "critical") continue;
3863
+ if (d.severity === "critical") criticalCount += 1;
3864
+ else errorCount += 1;
3865
+ alerting.push(telemetrySafeDiagnostic(d, d.severity));
3866
+ }
3867
+ if (alerting.length === 0) return null;
3868
+ const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3869
+ const env = ctx.env ?? {};
3870
+ const runtime = ctx.runtime ?? {
3871
+ node: process.versions.node,
3872
+ platform: process.platform,
3873
+ arch: process.arch
3874
+ };
3875
+ const framework = frameworkFromLabel(facts.label);
3876
+ return {
3877
+ version: TELEMETRY_PAYLOAD_VERSION,
3878
+ installId: ctx.installId,
3879
+ framework,
3880
+ frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3881
+ engineVersion: safeVersion(facts.engineVersion),
3882
+ clientVersion: safeVersion(facts.clientVersion),
3883
+ nodeVersion: safeVersion(runtime.node) ?? "unknown",
3884
+ os: safeToken(runtime.platform),
3885
+ arch: safeToken(runtime.arch),
3886
+ ci: env.CI === "true",
3887
+ complexity: complexityLabel(facts.preset, facts.complexity),
3888
+ fileCountBucket: fileCountBucket(facts.fileCount),
3889
+ durationBucket: durationBucket(facts.durationMs),
3890
+ diagnostics: kept,
3891
+ errorCount,
3892
+ criticalCount,
3893
+ droppedCount: alerting.length - kept.length
3894
+ };
3895
+ }
3896
+ const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3897
+ function safeVersion(value) {
3898
+ return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3899
+ }
3900
+ function safeToken(value) {
3901
+ return TOKEN_PATTERN.test(value) ? value : "unknown";
3902
+ }
3903
+ const TELEMETRY_NOTICE = [
3904
+ "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3905
+ "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3906
+ "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3907
+ "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3908
+ "AfterPack: file counts and durations, and a random install id that rotates every 30",
3909
+ "AfterPack: days.",
3910
+ "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3911
+ "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3912
+ "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3913
+ "AfterPack: `telemetry: { enabled: false }` in your config.",
3914
+ "AfterPack: https://www.afterpack.dev/privacy"
3915
+ ];
3916
+ const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3917
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3918
+ function readState(file, now) {
3919
+ try {
3920
+ const parsed = JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
3921
+ if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3922
+ installId: parsed.installId,
3923
+ rotatedAt: parsed.rotatedAt,
3924
+ noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
3925
+ };
3926
+ } catch {}
3927
+ return {
3928
+ installId: (0, node_crypto.randomUUID)(),
3929
+ rotatedAt: now,
3930
+ noticeShownAt: 0
3931
+ };
3932
+ }
3933
+ function writeState(file, state) {
3934
+ try {
3935
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
3936
+ (0, node_fs.writeFileSync)(file, `${JSON.stringify(state)}\n`, "utf8");
3937
+ } catch {}
3938
+ }
3939
+ function telemetryUrl(env) {
3940
+ const base = (env[API_URL_ENV_VAR$1] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3941
+ return `${base}${TELEMETRY_ENDPOINT_PATH}`;
3942
+ }
3943
+ const TELEMETRY_BODY_LIMIT = 64 * 1024;
3944
+ async function reportTelemetryNotices(response, logger) {
3945
+ if (!response || response.status !== 202 || typeof response.text !== "function") return;
3946
+ const declared = Number(response.headers?.get?.("content-length"));
3947
+ if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3948
+ await response.body?.cancel().catch(() => {});
3949
+ return;
3950
+ }
3951
+ const text = await response.text();
3952
+ if (text.length > TELEMETRY_BODY_LIMIT) return;
3953
+ let body;
3954
+ try {
3955
+ body = JSON.parse(text);
3956
+ } catch {
3957
+ return;
3958
+ }
3959
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3960
+ reportNotices(body.notices, logger);
3961
+ }
3962
+ function createTelemetryReporter(deps = {}) {
3963
+ const env = deps.env ?? process.env;
3964
+ const logger = deps.logger ?? console;
3965
+ const now = deps.now ?? Date.now;
3966
+ const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3967
+ const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3968
+ return async (facts) => {
3969
+ try {
3970
+ const at = now();
3971
+ const state = readState(stateFile, at);
3972
+ let dirty = false;
3973
+ if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3974
+ state.installId = (0, node_crypto.randomUUID)();
3975
+ state.rotatedAt = at;
3976
+ dirty = true;
3977
+ }
3978
+ if (state.noticeShownAt === 0) {
3979
+ for (const line of TELEMETRY_NOTICE) logger.log(line);
3980
+ state.noticeShownAt = at;
3981
+ dirty = true;
3982
+ }
3983
+ if (dirty) writeState(stateFile, state);
3984
+ if (facts === null) return;
3985
+ const payload = buildTelemetryPayload(facts, {
3986
+ installId: state.installId,
3987
+ env
3988
+ });
3989
+ if (payload === null) return;
3990
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3991
+ if (typeof fetchImpl !== "function") return;
3992
+ const response = await fetchImpl(telemetryUrl(env), {
3993
+ method: "POST",
3994
+ headers: { "content-type": "application/json" },
3995
+ body: JSON.stringify(payload),
3996
+ signal: AbortSignal.timeout(timeoutMs)
3997
+ });
3998
+ await reportTelemetryNotices(response, logger);
3999
+ } catch {}
4000
+ };
4001
+ }
4002
+
4003
+ //#endregion
4004
+ //#region src/hash-salt.ts
4005
+ const API_URL_ENV_VAR = "AFTERPACK_API_URL";
4006
+ const VERSION_ENDPOINT_PATH = "/v1/version";
4007
+ const VERSION_PROBE_TIMEOUT_MS = 2e3;
4008
+ function canonical(value) {
4009
+ if (Array.isArray(value)) return value.map(canonical);
4010
+ if (value === null || typeof value !== "object") return value;
4011
+ const out = {};
4012
+ for (const key of Object.keys(value).sort()) {
4013
+ const item = value[key];
4014
+ if (item !== void 0) out[key] = canonical(item);
4015
+ }
4016
+ return out;
4017
+ }
4018
+ function afterpackHashSalt(input) {
4019
+ const payload = JSON.stringify(canonical({
4020
+ salt: "afterpack-output-name/1",
4021
+ seed: String(input.seed),
4022
+ engineVersion: input.engine.engineVersion,
4023
+ nonce: input.engine.nonce,
4024
+ cloud: input.engine.cloud,
4025
+ settings: input.settings
4026
+ }));
4027
+ return (0, node_crypto.createHash)("sha256").update(payload).digest("hex").slice(0, 32);
4028
+ }
4029
+ function isCloudBuild(env) {
4030
+ const key = env.AFTERPACK_KEY;
4031
+ return typeof key === "string" && key.trim() !== "";
4032
+ }
4033
+ function versionEndpoint(env) {
4034
+ const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
4035
+ return `${base}${VERSION_ENDPOINT_PATH}`;
4036
+ }
4037
+ async function resolveSaltEngine(env, localEngineVersion, deps = {}) {
4038
+ if (!isCloudBuild(env)) return {
4039
+ engineVersion: localEngineVersion,
4040
+ nonce: null,
4041
+ cloud: false,
4042
+ probedCloudVersion: null,
4043
+ probeFailed: false
4044
+ };
4045
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
4046
+ let probed = null;
4047
+ if (typeof fetchImpl === "function") try {
4048
+ const response = await fetchImpl(versionEndpoint(env), { signal: AbortSignal.timeout(deps.timeoutMs ?? VERSION_PROBE_TIMEOUT_MS) });
4049
+ if (response.ok) {
4050
+ const body = await response.json();
4051
+ if (typeof body.engineVersion === "string" && body.engineVersion !== "") probed = body.engineVersion;
4052
+ }
4053
+ } catch {
4054
+ probed = null;
4055
+ }
4056
+ if (probed === null) return {
4057
+ engineVersion: null,
4058
+ nonce: (0, node_crypto.randomUUID)(),
4059
+ cloud: true,
4060
+ probedCloudVersion: null,
4061
+ probeFailed: true
4062
+ };
4063
+ return {
4064
+ engineVersion: probed,
4065
+ nonce: null,
4066
+ cloud: true,
4067
+ probedCloudVersion: probed,
4068
+ probeFailed: false
4069
+ };
4070
+ }
4071
+ const PROBE_FAILED_WARNING = "could not read the cloud engine version from the API, so output file names carry a random nonce this build only. They are safe, but a pinned seed will not reproduce them. Re-run when the API is reachable to get stable names.";
4072
+ function saltSettings(settings, extra = {}) {
4073
+ const { seed: _seed, diagnostics: _diagnostics, artifactOptions, engineConfig,...rest } = settings;
4074
+ const { git: _git, telemetry: _telemetry,...output } = artifactOptions ?? {};
4075
+ const { seed: _engineSeed,...engine } = engineConfig ?? {};
4076
+ return {
4077
+ ...rest,
4078
+ engineConfig: engine,
4079
+ artifactOptions: output,
4080
+ ...extra
4081
+ };
4082
+ }
4083
+ function reportPolicySaltBits(env, artifactOptions, hasBundlerSourcemap) {
4084
+ const policy = resolveReportPolicy(env, artifactOptions ?? {}, { hasBundlerSourcemap });
4085
+ return {
4086
+ sourceMap: policy.sourceMap,
4087
+ emitSourceMappingURL: policy.emitSourceMappingURL
4088
+ };
4089
+ }
4090
+ async function prepareHashSalt(input) {
4091
+ const env = input.env ?? process.env;
4092
+ const resolvedSeed = resolveBuildSeed(input.seed, {
4093
+ root: input.root,
4094
+ leg: input.leg
4095
+ }, {
4096
+ env,
4097
+ warn: input.warn
4098
+ });
4099
+ const engine = await resolveSaltEngine(env, input.localEngineVersion, { fetchImpl: input.fetchImpl });
4100
+ if (engine.probeFailed) input.warn?.(PROBE_FAILED_WARNING);
4101
+ return {
4102
+ resolvedSeed,
4103
+ engine,
4104
+ salt: afterpackHashSalt({
4105
+ seed: resolvedSeed.seed,
4106
+ engine,
4107
+ settings: input.settings
4108
+ })
4109
+ };
4110
+ }
4111
+ async function readEngineVersion(engine) {
4112
+ try {
4113
+ return await engine.version?.() ?? null;
4114
+ } catch {
4115
+ return null;
4116
+ }
4117
+ }
4118
+ function cloudEngineMismatch(engine, batchEngineVersion) {
4119
+ if (!engine.cloud || engine.probedCloudVersion === null) return null;
4120
+ if (batchEngineVersion === null) return null;
4121
+ if (batchEngineVersion === engine.probedCloudVersion) return null;
4122
+ return `the cloud engine was version ${engine.probedCloudVersion} when output names were derived, but the build ran on ${batchEngineVersion}. Names would not match the bytes. This is a rare race during a service upgrade — re-run the build.`;
4123
+ }
4124
+
4125
+ //#endregion
4126
+ //#region src/hash-tokens.ts
4127
+ const NEXT_CHUNKS_PREFIX = "static/chunks/";
4128
+ const TURBOPACK_CHUNK_RE = /^(?:turbopack-)?([0-9a-z~._-]{13})\.(?:js|css)$/;
4129
+ const WEBPACK_CHUNK_RE = /[-.]([0-9a-f]{16})\.js$/;
4130
+ const ANGULAR_HASHED_NAME_RE = /-([A-Z0-9]{8})\.(?:js|mjs|css)$/;
4131
+ function detectNextBundler(distDir) {
4132
+ if ((0, node_fs.existsSync)((0, node_path.join)(distDir, "turbopack"))) return "turbopack";
4133
+ if ((0, node_fs.existsSync)((0, node_path.join)(distDir, "server", "webpack-runtime.js"))) return "webpack";
4134
+ return "unknown";
4135
+ }
4136
+ function nextChunkToken(bundler, chunksPrefix = NEXT_CHUNKS_PREFIX) {
4137
+ const pattern = bundler === "turbopack" ? TURBOPACK_CHUNK_RE : bundler === "webpack" ? WEBPACK_CHUNK_RE : null;
4138
+ return (relativePath) => {
4139
+ if (pattern === null || !relativePath.startsWith(chunksPrefix)) return null;
4140
+ return pattern.exec((0, node_path.basename)(relativePath))?.[1] ?? null;
4141
+ };
4142
+ }
4143
+ function skipNextInternals(relativePath) {
4144
+ return relativePath === "cache" || relativePath.startsWith("trace");
4145
+ }
4146
+ const angularHashToken = (relativePath) => ANGULAR_HASHED_NAME_RE.exec((0, node_path.basename)(relativePath))?.[1] ?? null;
4147
+
4148
+ //#endregion
4149
+ //#region src/hashed-names.ts
4150
+ const LOWER_HEX = "0123456789abcdef";
4151
+ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
4152
+ const UPPER_ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
4153
+ const LOWER_ALNUM = "0123456789abcdefghijklmnopqrstuvwxyz";
4154
+ const ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4155
+ const MIN_TOKEN_LENGTH = 6;
4156
+ const BINARY_EXTENSIONS = new Set([
4157
+ ".png",
4158
+ ".jpg",
4159
+ ".jpeg",
4160
+ ".gif",
4161
+ ".webp",
4162
+ ".avif",
4163
+ ".ico",
4164
+ ".bmp",
4165
+ ".woff",
4166
+ ".woff2",
4167
+ ".ttf",
4168
+ ".otf",
4169
+ ".eot",
4170
+ ".wasm",
4171
+ ".gz",
4172
+ ".br",
4173
+ ".zst",
4174
+ ".zip",
4175
+ ".pdf",
4176
+ ".mp3",
4177
+ ".mp4",
4178
+ ".webm",
4179
+ ".ogg",
4180
+ ".wav",
4181
+ ".pack"
4182
+ ]);
4183
+ function alphabetOf(token) {
4184
+ if (/^[0-9a-f]+$/.test(token)) return LOWER_HEX;
4185
+ if (/^[A-Z2-7]+$/.test(token)) return BASE32;
4186
+ if (/^[0-9A-Z]+$/.test(token)) return UPPER_ALNUM;
4187
+ if (/^[0-9a-z~._-]+$/.test(token)) return LOWER_ALNUM;
4188
+ return ALNUM;
4189
+ }
4190
+ function inputKey(input = {}) {
4191
+ const regions = input.regions && input.regions.length > 0 ? JSON.stringify(input.regions) : "";
4192
+ return input.sourceType === void 0 ? regions : `${regions}\0${input.sourceType}`;
4193
+ }
4194
+ function deriveHashToken(token, salt, regions = "") {
4195
+ const alphabet = alphabetOf(token);
4196
+ let out = "";
4197
+ for (let round = 0; out.length < token.length; round++) {
4198
+ const bytes = (0, node_crypto.createHash)("sha256").update(`${salt}\0${token}\0${regions}\0${round}`).digest();
4199
+ for (const byte of bytes) {
4200
+ if (out.length === token.length) break;
4201
+ out += alphabet[byte % alphabet.length];
4202
+ }
4203
+ }
4204
+ return out;
4205
+ }
4206
+ function escapeRegExp$1(text) {
4207
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4208
+ }
4209
+ function tokenPattern(tokens) {
4210
+ const list = [...tokens].sort((a, b) => b.length - a.length || (a < b ? -1 : 1));
4211
+ if (list.length === 0) return null;
4212
+ return new RegExp(`(?<![A-Za-z0-9])(?:${list.map(escapeRegExp$1).join("|")})(?![A-Za-z0-9])`, "g");
4213
+ }
4214
+ function toPosix$1(path) {
4215
+ return node_path.sep === "/" ? path : path.split(node_path.sep).join("/");
4216
+ }
4217
+ function readText(path) {
4218
+ let bytes;
4219
+ try {
4220
+ bytes = (0, node_fs.readFileSync)(path);
4221
+ } catch {
4222
+ return null;
4223
+ }
4224
+ if (bytes.subarray(0, 8192).includes(0)) return null;
4225
+ try {
4226
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
4227
+ } catch {
4228
+ return null;
4229
+ }
4230
+ }
4231
+ function listFiles(root, skip) {
4232
+ const out = [];
4233
+ const walk$1 = (dir) => {
4234
+ let entries;
4235
+ try {
4236
+ entries = (0, node_fs.readdirSync)(dir, { withFileTypes: true });
4237
+ } catch {
4238
+ return;
4239
+ }
4240
+ for (const entry of entries) {
4241
+ const full = (0, node_path.join)(dir, entry.name);
4242
+ const rel = toPosix$1((0, node_path.relative)(root, full));
4243
+ if (entry.name === AFTERPACK_DIR || entry.name === "node_modules" || skip(rel)) continue;
4244
+ if (entry.isDirectory()) walk$1(full);
4245
+ else if (entry.isFile()) out.push(full);
4246
+ }
4247
+ };
4248
+ walk$1(root);
4249
+ return out;
4250
+ }
4251
+ function isCandidate(path) {
4252
+ const name = (0, node_path.basename)(path).toLowerCase();
4253
+ if (name.endsWith(".map")) return false;
4254
+ const dot = name.lastIndexOf(".");
4255
+ return dot < 0 || !BINARY_EXTENSIONS.has(name.slice(dot));
4256
+ }
4257
+ function tokenAt(root, tokenOf, path) {
4258
+ const rel = toPosix$1((0, node_path.relative)(root, path));
4259
+ if (rel.startsWith("..")) return null;
4260
+ const token = tokenOf(rel);
4261
+ if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
4262
+ return (0, node_path.basename)(path).includes(token) ? token : null;
4263
+ }
4264
+ function unreferencedHashedFiles(options, files) {
4265
+ const owners = new Map();
4266
+ for (const file of files) {
4267
+ const token = tokenAt(options.root, options.tokenOf, file);
4268
+ if (token !== null) owners.set(token, (owners.get(token) ?? new Set()).add(file));
4269
+ }
4270
+ const pattern = tokenPattern(owners.keys());
4271
+ if (pattern === null) return [];
4272
+ const referenced = new Set();
4273
+ for (const path of listFiles(options.root, options.skip ?? (() => false))) {
4274
+ if (!isCandidate(path)) continue;
4275
+ const text = readText(path);
4276
+ if (text === null) continue;
4277
+ for (const [token] of text.matchAll(pattern)) for (const owner of owners.get(token) ?? []) if (owner !== path) referenced.add(owner);
4278
+ }
4279
+ return [...owners.values()].flatMap((set) => [...set]).filter((file) => !referenced.has(file)).sort();
4280
+ }
4281
+ const SCAN_SKIPPED_DIRS = new Set([
4282
+ "node_modules",
4283
+ ".git",
4284
+ AFTERPACK_DIR,
4285
+ ".cache",
4286
+ "cache"
4287
+ ]);
4288
+ function findHashTokenReference(paths, options, files, limits) {
4289
+ const tokens = files.map((file) => tokenAt(options.root, options.tokenOf, file)).filter((token) => token !== null);
4290
+ const pattern = tokenPattern(new Set(tokens));
4291
+ const result = {
4292
+ found: null,
4293
+ truncated: false
4294
+ };
4295
+ if (pattern === null) return result;
4296
+ let seenFiles = 0;
4297
+ let seenBytes = 0;
4298
+ const visit = (path, depth) => {
4299
+ if (result.found !== null || result.truncated || isWithinDir(options.root, path)) return;
4300
+ let stats;
4301
+ try {
4302
+ stats = (0, node_fs.statSync)(path);
4303
+ } catch {
4304
+ return;
4305
+ }
4306
+ if (stats.isDirectory()) {
4307
+ if (SCAN_SKIPPED_DIRS.has((0, node_path.basename)(path))) return;
4308
+ if (depth > limits.maxDepth) {
4309
+ result.truncated = true;
4310
+ return;
4311
+ }
4312
+ for (const entry of (0, node_fs.readdirSync)(path).sort()) visit((0, node_path.join)(path, entry), depth + 1);
4313
+ return;
4314
+ }
4315
+ if (!stats.isFile() || !isCandidate(path)) return;
4316
+ seenFiles += 1;
4317
+ seenBytes += stats.size;
4318
+ if (seenFiles > limits.maxFiles || seenBytes > limits.maxBytes) {
4319
+ result.truncated = true;
4320
+ return;
4321
+ }
4322
+ const text = readText(path);
4323
+ pattern.lastIndex = 0;
4324
+ if (text !== null && pattern.test(text)) result.found = path;
4325
+ };
4326
+ for (const path of paths) visit(path, 0);
4327
+ return result;
4328
+ }
4329
+ function writableDir(dir) {
4330
+ try {
4331
+ (0, node_fs.accessSync)(dir, node_fs.constants.W_OK);
4332
+ return true;
4333
+ } catch {
4334
+ return false;
4335
+ }
4336
+ }
4337
+ function planHashedNames(input) {
4338
+ const { root, tokenOf } = input.options;
4339
+ const skip = input.options.skip ?? (() => false);
4340
+ const tokens = new Map();
4341
+ const tokenOfPath = (path) => tokenAt(root, tokenOf, path);
4342
+ const addToken = (token, file) => {
4343
+ if (tokens.has(token)) return false;
4344
+ tokens.set(token, deriveHashToken(token, input.salt, inputKey(file)));
4345
+ return true;
4346
+ };
4347
+ for (const [path, file] of input.inputs) {
4348
+ const token = tokenOfPath(path);
4349
+ if (token !== null) addToken(token, file);
4350
+ }
4351
+ const others = new Map();
4352
+ if (tokens.size > 0) for (const path of listFiles(root, skip)) {
4353
+ if (input.inputs.has(path) || !isCandidate(path)) continue;
4354
+ const text = readText(path);
4355
+ if (text !== null) others.set(path, text);
4356
+ }
4357
+ const changed = new Set();
4358
+ let grew = tokens.size > 0;
4359
+ while (grew) {
4360
+ grew = false;
4361
+ const pattern$1 = tokenPattern(tokens.keys());
4362
+ if (pattern$1 === null) break;
4363
+ for (const [path, text] of others) {
4364
+ if (changed.has(path)) continue;
4365
+ pattern$1.lastIndex = 0;
4366
+ if (!pattern$1.test(text)) continue;
4367
+ changed.add(path);
4368
+ const token = tokenOfPath(path);
4369
+ if (token !== null && addToken(token)) grew = true;
4370
+ }
4371
+ }
4372
+ const pattern = tokenPattern(tokens.keys());
4373
+ const rewrite = (text) => pattern === null ? text : text.replace(pattern, (token) => tokens.get(token) ?? token);
4374
+ const renamedPath = (path) => {
4375
+ const token = tokenOfPath(path);
4376
+ if (token === null || !tokens.has(token)) return path;
4377
+ const name = (0, node_path.basename)(path);
4378
+ const at = name.lastIndexOf(token);
4379
+ return (0, node_path.join)((0, node_path.dirname)(path), `${name.slice(0, at)}${tokens.get(token)}${name.slice(at + token.length)}`);
4380
+ };
4381
+ const renamed = new Map();
4382
+ for (const path of input.inputs.keys()) {
4383
+ const next = renamedPath(path);
4384
+ if (next !== path) renamed.set(path, next);
4385
+ }
4386
+ const writes = [];
4387
+ const rewrites = new Map();
4388
+ for (const path of changed) {
4389
+ const to = renamedPath(path);
4390
+ if (to !== path) renamed.set(path, to);
4391
+ const text = rewrite(others.get(path));
4392
+ rewrites.set(path, {
4393
+ to,
4394
+ text
4395
+ });
4396
+ writes.push({
4397
+ from: path,
4398
+ to,
4399
+ text
4400
+ });
4401
+ }
4402
+ const preflight = () => {
4403
+ const unwritable = new Set();
4404
+ for (const [from, to] of renamed) {
4405
+ if (!writableDir((0, node_path.dirname)(from))) unwritable.add((0, node_path.dirname)(from));
4406
+ if (!writableDir((0, node_path.dirname)(to))) unwritable.add((0, node_path.dirname)(to));
4407
+ }
4408
+ for (const write of writes) if (!writableDir((0, node_path.dirname)(write.to))) unwritable.add((0, node_path.dirname)(write.to));
4409
+ if (unwritable.size > 0) throw new Error(`cannot rename content-hashed files: these directories are not writable: ${[...unwritable].sort().join(", ")}`);
4410
+ };
4411
+ return {
4412
+ tokens,
4413
+ renamed,
4414
+ rewrites,
4415
+ rewrite,
4416
+ preflight,
4417
+ apply() {
4418
+ preflight();
4419
+ const staged = [];
4420
+ try {
4421
+ for (const write of writes) {
4422
+ (0, node_fs.writeFileSync)(stagedPath(write.to), write.text);
4423
+ staged.push(stagedPath(write.to));
4424
+ }
4425
+ } catch (error) {
4426
+ for (const path of staged) (0, node_fs.rmSync)(path, { force: true });
4427
+ throw error;
4428
+ }
4429
+ for (const write of writes) {
4430
+ (0, node_fs.renameSync)(stagedPath(write.to), write.to);
4431
+ if (write.to !== write.from) (0, node_fs.rmSync)(write.from, { force: true });
4432
+ }
4433
+ }
4434
+ };
4435
+ }
4436
+
4437
+ //#endregion
4438
+ //#region src/git.ts
4439
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
4440
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
4441
+ function sanitizeCommitSha(value) {
4442
+ if (typeof value !== "string") return null;
4443
+ const sha = value.trim().toLowerCase();
4444
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
4445
+ }
4446
+ function sanitizeGitRef(value) {
4447
+ if (typeof value !== "string") return null;
4448
+ const ref = value.trim();
4449
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
4450
+ }
4451
+ function contextFrom(rawSha, rawRef) {
4452
+ const commitSha = sanitizeCommitSha(rawSha);
4453
+ const ref = sanitizeGitRef(rawRef);
4454
+ if (commitSha === null && ref === null) return null;
4455
+ const context = {};
4456
+ if (commitSha !== null) context.commitSha = commitSha;
4457
+ if (ref !== null) context.ref = ref;
4458
+ return context;
4459
+ }
4460
+ const CI_SOURCES = [
4461
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
4462
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
4463
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
4464
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
4465
+ ["GIT_COMMIT", "BRANCH_NAME"]
4466
+ ];
4467
+ function ciGitContext(env) {
4468
+ for (const [shaVar, refVar] of CI_SOURCES) {
4469
+ const context = contextFrom(env[shaVar], env[refVar]);
4470
+ if (context !== null) return context;
4471
+ }
4472
+ return null;
4473
+ }
4474
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
4475
+ function localGitContext(cwd) {
4476
+ let lines;
4477
+ try {
4478
+ const out = (0, node_child_process.execFileSync)("git", [
4479
+ "rev-parse",
4480
+ "HEAD",
4481
+ "--abbrev-ref",
4482
+ "HEAD"
4483
+ ], {
4484
+ cwd,
4485
+ stdio: [
4486
+ "ignore",
4487
+ "pipe",
4488
+ "ignore"
4489
+ ],
4490
+ timeout: GIT_PROBE_TIMEOUT_MS,
4491
+ maxBuffer: 64 * 1024
4492
+ }).toString();
4493
+ lines = out.split("\n").map((line) => line.trim());
4494
+ } catch {
4495
+ return null;
4496
+ }
4497
+ const ref = lines[1] === "HEAD" ? null : lines[1];
4498
+ return contextFrom(lines[0], ref);
4499
+ }
4500
+ function detectGitContext(explicit, deps = {}) {
4501
+ if (explicit) {
4502
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
4503
+ if (declared !== null) return declared;
4504
+ }
4505
+ const ci = ciGitContext(deps.env ?? process.env);
4506
+ if (ci !== null) return ci;
4507
+ return (deps.localGit ?? localGitContext)(deps.cwd);
4508
+ }
4509
+
4510
+ //#endregion
4511
+ //#region src/map-color.ts
4512
+ const UTF8 = new TextEncoder();
4513
+ const utf8Len = (s) => UTF8.encode(s).length;
4514
+ const NON_ASCII = /[\u0080-\uFFFF]/;
4515
+ const HIGH_SURROGATE_START = 55296;
4516
+ const HIGH_SURROGATE_END = 56319;
4517
+ const LOW_SURROGATE_START = 56320;
4518
+ const LOW_SURROGATE_END = 57343;
4519
+ function charToByteTable(line) {
4520
+ const table = new Array(line.length + 1);
4521
+ let bytes = 0;
4522
+ let i = 0;
4523
+ while (i < line.length) {
4524
+ table[i] = bytes;
4525
+ const code = line.charCodeAt(i);
4526
+ if (code < 128) {
4527
+ bytes += 1;
4528
+ i += 1;
4529
+ continue;
4530
+ }
4531
+ if (code < 2048) {
4532
+ bytes += 2;
4533
+ i += 1;
4534
+ continue;
4535
+ }
4536
+ if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
4537
+ const low = line.charCodeAt(i + 1);
4538
+ if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
4539
+ table[i + 1] = bytes + 3;
4540
+ bytes += 4;
4541
+ i += 2;
4542
+ continue;
4543
+ }
4544
+ }
4545
+ bytes += 3;
4546
+ i += 1;
4547
+ }
4548
+ table[line.length] = bytes;
4549
+ return table;
4550
+ }
4551
+ var ChunkByteIndex = class {
4552
+ starts;
3374
4553
  ascii;
3375
4554
  tables;
3376
4555
  totalBytes;
@@ -3522,19 +4701,110 @@ function coverGenerated(segments$1, start, end, index) {
3522
4701
  }
3523
4702
  return merged;
3524
4703
  }
3525
-
3526
- //#endregion
3527
- //#region src/receipt.ts
3528
- const PROTECTION_RECEIPT_FILE = ".afterpack-protection.json";
3529
- const PROTECTION_RECEIPT_SCHEMA = 1;
3530
- function sha256OfBytes(bytes) {
3531
- return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex");
4704
+
4705
+ //#endregion
4706
+ //#region src/receipt.ts
4707
+ const PROTECTION_RECEIPTS_DIR = "receipts";
4708
+ const STALE_OUTPUT_RECEIPT_FILE = ".afterpack-protection.json";
4709
+ const PROTECTION_RECEIPT_SCHEMA = 1;
4710
+ function sha256OfBytes(bytes) {
4711
+ return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex");
4712
+ }
4713
+ function sha256Of(path) {
4714
+ return sha256OfBytes((0, node_fs.readFileSync)(path));
4715
+ }
4716
+ function receiptPathOf(dir, file) {
4717
+ return (0, node_path.relative)(dir, file).split(node_path.sep).join("/");
4718
+ }
4719
+ const MAX_KEY_BYTES = 180;
4720
+ const HASHED_KEY_PREFIX_BYTES = 120;
4721
+ function buildDirOf(home) {
4722
+ const rel = (0, node_path.relative)(home.projectRoot, home.buildDir).split(node_path.sep).join("/");
4723
+ return rel === "" ? "." : rel;
4724
+ }
4725
+ function receiptKey(buildDir) {
4726
+ const encoded = encodeURIComponent(buildDir).replace(/\*/g, "%2A").replace(/~/g, "%7E");
4727
+ if (Buffer.byteLength(encoded) <= MAX_KEY_BYTES) return encoded;
4728
+ const prefix = encoded.slice(0, HASHED_KEY_PREFIX_BYTES).replace(/%[0-9A-F]?$/, "");
4729
+ const digest$1 = (0, node_crypto.createHash)("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4730
+ return `${prefix}~${digest$1}`;
4731
+ }
4732
+ function receiptsDirOf(home) {
4733
+ return (0, node_path.join)(home.dir, PROTECTION_RECEIPTS_DIR);
4734
+ }
4735
+ function receiptPathIn(home) {
4736
+ return (0, node_path.join)(receiptsDirOf(home), `${receiptKey(buildDirOf(home))}.json`);
4737
+ }
4738
+ function homeOf(target) {
4739
+ return typeof target === "string" ? afterpackHome(target) : target;
4740
+ }
4741
+ function buildDirKey(target) {
4742
+ return receiptKey(buildDirOf(homeOf(target)));
4743
+ }
4744
+ function protectionReceiptPath(target) {
4745
+ return receiptPathIn(homeOf(target));
4746
+ }
4747
+ function prepareProtectionReceipt(target, label) {
4748
+ const home = homeOf(target);
4749
+ const path = receiptPathIn(home);
4750
+ try {
4751
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
4752
+ ensureAfterpackGitignore(home.dir);
4753
+ const existed = (0, node_fs.existsSync)(path);
4754
+ (0, node_fs.closeSync)((0, node_fs.openSync)(path, "a"));
4755
+ if (!existed) (0, node_fs.unlinkSync)(path);
4756
+ } catch (error) {
4757
+ throw new AfterpackFilesError(DIAG_RECEIPT_UNWRITABLE, `[${label}] cannot write the protection receipt ${path}, so no file was rewritten: ${error}`, `Make ${(0, node_path.dirname)(path)} a writable directory, then build again.`);
4758
+ }
4759
+ return path;
4760
+ }
4761
+ function entriesOf(dir) {
4762
+ try {
4763
+ return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
4764
+ } catch {
4765
+ return [];
4766
+ }
4767
+ }
4768
+ function removeStaleReceipt(path, label) {
4769
+ try {
4770
+ (0, node_fs.unlinkSync)(path);
4771
+ } catch (error) {
4772
+ if (error.code === "ENOENT") return;
4773
+ throw new Error(`[${label}] could not remove the stale protection receipt ${path}, refusing to ship it: ${error}`);
4774
+ }
4775
+ }
4776
+ function refuseShippedAfterpackDir(path, buildDir, label) {
4777
+ throw new AfterpackFilesError(DIAG_AFTERPACK_DIR_IN_OUTPUT, `[${label}] found ${path} inside the build output ${buildDir}. It holds AfterPack backups, receipts or Protection Maps, which must never ship.`, `Delete ${path}, then build again.`);
3532
4778
  }
3533
- function sha256Of(path) {
3534
- return sha256OfBytes((0, node_fs.readFileSync)(path));
4779
+ function sweepDir(dir, context, recursive) {
4780
+ for (const entry of entriesOf(dir)) {
4781
+ const full = (0, node_path.join)(dir, entry.name);
4782
+ if (entry.name === STALE_OUTPUT_RECEIPT_FILE) removeStaleReceipt(full, context.label);
4783
+ else if (entry.isDirectory()) {
4784
+ if (entry.name === AFTERPACK_DIR) {
4785
+ if (context.ownHome !== null && realPath(full) === context.ownHome) continue;
4786
+ refuseShippedAfterpackDir(full, context.buildDir, context.label);
4787
+ }
4788
+ if (!recursive || entry.name === "node_modules") continue;
4789
+ sweepDir(full, context, true);
4790
+ }
4791
+ }
3535
4792
  }
3536
- function receiptPathOf(dir, file) {
3537
- return (0, node_path.relative)(dir, file).split(node_path.sep).join("/");
4793
+ function sweepOutputTree(buildDir, walkedDir, label, ownHome = null) {
4794
+ const context = {
4795
+ buildDir,
4796
+ label,
4797
+ ownHome: ownHome?.strong ? realPath(ownHome.dir) : null
4798
+ };
4799
+ const walksBuildDir = walkedDir !== null && realPath(walkedDir) === realPath(buildDir);
4800
+ sweepDir(buildDir, context, walksBuildDir);
4801
+ if (walkedDir !== null && !walksBuildDir) sweepDir(walkedDir, context, true);
4802
+ }
4803
+ function keptEntries(path, replaced) {
4804
+ if (!(0, node_fs.existsSync)(path)) return [];
4805
+ const previous = parseReceipt(path);
4806
+ if (previous.error !== void 0 || previous.receipt.schema !== PROTECTION_RECEIPT_SCHEMA) return [];
4807
+ return previous.receipt.files.filter((entry) => !replaced.has(entry.path));
3538
4808
  }
3539
4809
  function writeDeferredProtectionReceipt(deferred) {
3540
4810
  const survivingFiles = deferred.files.filter((file) => (0, node_fs.existsSync)(file));
@@ -3555,13 +4825,22 @@ function writeProtectionReceipt(input) {
3555
4825
  seedOrigin: input.seedOrigin,
3556
4826
  bundler: input.bundler,
3557
4827
  buildId: input.buildId,
4828
+ buildDir: ".",
3558
4829
  files: input.files.map((file) => ({
3559
4830
  path: receiptPathOf(input.dir, file),
3560
4831
  sha256: sha256Of(file),
3561
4832
  transformed: transformed.has(file)
3562
4833
  })).sort((a, b) => a.path.localeCompare(b.path))
3563
4834
  };
3564
- const path = (0, node_path.join)(input.dir, PROTECTION_RECEIPT_FILE);
4835
+ const home = input.home ?? afterpackHome(input.dir);
4836
+ receipt.buildDir = buildDirOf(home);
4837
+ const path = receiptPathIn(home);
4838
+ if (input.merge) {
4839
+ const replaced = new Set(receipt.files.map((entry) => entry.path));
4840
+ receipt.files = [...keptEntries(path, replaced), ...receipt.files].sort((a, b) => a.path.localeCompare(b.path));
4841
+ }
4842
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
4843
+ ensureAfterpackGitignore(home.dir);
3565
4844
  (0, node_fs.writeFileSync)(path, `${JSON.stringify(receipt, null, 2)}\n`);
3566
4845
  return path;
3567
4846
  }
@@ -3609,8 +4888,7 @@ var UnreadableReceiptError = class extends Error {
3609
4888
  this.schema = schema;
3610
4889
  }
3611
4890
  };
3612
- function verifyProtectionReceipt(dir, expectedBuildId) {
3613
- const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
4891
+ function verifyProtectionReceipt(receiptPath, dir, expectedBuildId) {
3614
4892
  if (!(0, node_fs.existsSync)(receiptPath)) return {
3615
4893
  receiptPath,
3616
4894
  receipt: null,
@@ -3642,152 +4920,93 @@ function verifyProtectionReceipt(dir, expectedBuildId) {
3642
4920
  problems
3643
4921
  };
3644
4922
  }
3645
- function findReceiptDir(startDir) {
3646
- const receiptPath = findUpward(startDir, PROTECTION_RECEIPT_FILE);
3647
- return receiptPath ? (0, node_path.dirname)(receiptPath) : null;
3648
- }
3649
- function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
3650
- const dir = findReceiptDir(startDir);
3651
- if (!dir) return null;
3652
- const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
3653
- const result = parseReceipt(receiptPath);
3654
- if (result.error !== void 0) {
3655
- const schema = result.newerSchema;
3656
- if (schema === null) return null;
3657
- 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);
3658
- }
3659
- const outputHashes = new Set(result.receipt.files.map((f) => f.sha256));
3660
- if (outputHashes.size === 0) return null;
3661
- const matches = files.filter((file) => {
3662
- const bytes = bytesByPath?.get(file);
3663
- if (bytes !== void 0) return outputHashes.has(sha256OfBytes(bytes));
3664
- return (0, node_fs.existsSync)(file) && outputHashes.has(sha256Of(file));
3665
- });
3666
- return matches.length > 0 ? {
3667
- receiptPath,
3668
- files: matches
3669
- } : null;
3670
- }
3671
-
3672
- //#endregion
3673
- //#region src/seed.ts
3674
- function randomSeed() {
3675
- const b = (0, node_crypto.randomBytes)(8);
3676
- const hi = b.readUInt32BE(0) & 2097151;
3677
- const lo = b.readUInt32BE(4);
3678
- return hi * 4294967296 + lo;
3679
- }
3680
- function gitHead() {
3681
- try {
3682
- const out = (0, node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], { stdio: [
3683
- "ignore",
3684
- "pipe",
3685
- "ignore"
3686
- ] }).toString().trim();
3687
- return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3688
- } catch {
3689
- return null;
3690
- }
3691
- }
3692
- const SEED_ENV_VAR = "AFTERPACK_SEED";
3693
- function parseSeedValue(raw) {
3694
- return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3695
- }
3696
- const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3697
- function sharedSeedState() {
3698
- const holder = globalThis;
3699
- holder[SEED_STATE] ??= {
3700
- sessions: new Map(),
3701
- ownEnvExports: []
4923
+ function receiptsIn(home) {
4924
+ const dir = receiptsDirOf(home);
4925
+ return entriesOf(dir).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => (0, node_path.join)(dir, entry.name)).sort();
4926
+ }
4927
+ function filesByName(dir) {
4928
+ const byName = new Map();
4929
+ const walk$1 = (current, rel) => {
4930
+ for (const entry of entriesOf(current)) {
4931
+ if (entry.name === "node_modules" || entry.name === AFTERPACK_DIR) continue;
4932
+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
4933
+ if (entry.isDirectory()) walk$1((0, node_path.join)(current, entry.name), childRel);
4934
+ else if (entry.isFile()) byName.set(entry.name, [...byName.get(entry.name) ?? [], childRel]);
4935
+ }
3702
4936
  };
3703
- return holder[SEED_STATE];
3704
- }
3705
- const { sessions, ownEnvExports } = sharedSeedState();
3706
- function isOwnEnvExport(env, value) {
3707
- return ownEnvExports.some((e) => e.env === env && e.value === value);
3708
- }
3709
- function openGeneration(root, leg) {
3710
- let session = sessions.get(root);
3711
- if (!session) {
3712
- session = {
3713
- seed: void 0,
3714
- generation: 1,
3715
- legs: [],
3716
- resolvedByLeg: new Map(),
3717
- gitFallbackWarned: false
3718
- };
3719
- sessions.set(root, session);
3720
- } else if (session.legs.includes(leg)) {
3721
- session.seed = void 0;
3722
- session.generation += 1;
3723
- session.legs = [];
3724
- session.resolvedByLeg.clear();
3725
- session.gitFallbackWarned = false;
4937
+ walk$1(dir, "");
4938
+ return byName;
4939
+ }
4940
+ function copyMatches(dir, home, skip) {
4941
+ const receipts = receiptsIn(home).filter((path) => !skip.has(path));
4942
+ if (receipts.length === 0) return [];
4943
+ const byName = filesByName(dir);
4944
+ const matches = [];
4945
+ for (const receiptPath of receipts) {
4946
+ const parsed = parseReceipt(receiptPath);
4947
+ if (parsed.error !== void 0 || parsed.receipt.files.length === 0) continue;
4948
+ const { files, buildDir } = parsed.receipt;
4949
+ const first = files[0].path;
4950
+ for (const rel of byName.get(first.split("/").pop() ?? first) ?? []) {
4951
+ if (rel !== first && !rel.endsWith(`/${first}`)) continue;
4952
+ const prefix = rel.slice(0, rel.length - first.length);
4953
+ const copyDir = (0, node_path.join)(dir, ...prefix.split("/").filter(Boolean));
4954
+ if (!files.every((entry) => (0, node_fs.existsSync)((0, node_path.join)(copyDir, entry.path)))) continue;
4955
+ matches.push({
4956
+ receiptPath,
4957
+ dir: copyDir,
4958
+ copiedFrom: typeof buildDir === "string" ? (0, node_path.join)(home.projectRoot, buildDir) : null,
4959
+ hashesMatch: files.every((entry) => sha256Of((0, node_path.join)(copyDir, entry.path)) === entry.sha256),
4960
+ prefix
4961
+ });
4962
+ }
3726
4963
  }
3727
- session.legs.push(leg);
3728
- return session;
4964
+ return matches.sort((a, b) => Number(b.hashesMatch) - Number(a.hashesMatch) || a.prefix.length - b.prefix.length || a.receiptPath.localeCompare(b.receiptPath));
3729
4965
  }
3730
- function resolveWithinSession(input, session, env, deps) {
3731
- if (typeof input === "number") return {
3732
- seed: input,
3733
- origin: "option"
4966
+ function locateProtectionReceipt(dir, options = {}) {
4967
+ const homes = [afterpackHome(dir), afterpackHome(dir, { fileTarget: true })];
4968
+ const exact = [...new Set(homes.map(receiptPathIn))];
4969
+ const found = exact.find((path) => (0, node_fs.existsSync)(path));
4970
+ if (found) return {
4971
+ receiptPath: found,
4972
+ dir,
4973
+ copiedFrom: null
3734
4974
  };
3735
- if (typeof input === "string" && input !== "git") return {
3736
- seed: input,
3737
- origin: "option"
4975
+ if (options.copies === false) return null;
4976
+ const best = copyMatches(dir, homes[0], new Set(exact))[0];
4977
+ return best ? {
4978
+ receiptPath: best.receiptPath,
4979
+ dir: best.dir,
4980
+ copiedFrom: best.copiedFrom
4981
+ } : null;
4982
+ }
4983
+ function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
4984
+ const hashOf = (file) => {
4985
+ const bytes = bytesByPath?.get(file);
4986
+ if (bytes !== void 0) return sha256OfBytes(bytes);
4987
+ return (0, node_fs.existsSync)(file) ? sha256Of(file) : null;
3738
4988
  };
3739
- if (input === "git") {
3740
- const head = (deps.gitHead ?? gitHead)();
3741
- if (head) return {
3742
- seed: head,
3743
- origin: "git"
3744
- };
3745
- if (!session.gitFallbackWarned) {
3746
- session.gitFallbackWarned = true;
3747
- (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
4989
+ let hashes = null;
4990
+ for (const receiptPath of receiptsIn(homeOf(startDir))) {
4991
+ const result = parseReceipt(receiptPath);
4992
+ if (result.error !== void 0) {
4993
+ const schema = result.newerSchema;
4994
+ if (schema === null) continue;
4995
+ 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);
3748
4996
  }
3749
- }
3750
- const fromEnv = env[SEED_ENV_VAR];
3751
- if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3752
- seed: parseSeedValue(fromEnv),
3753
- origin: "env"
3754
- };
3755
- if (session.seed !== void 0) return {
3756
- seed: session.seed,
3757
- origin: "session"
3758
- };
3759
- return {
3760
- seed: (deps.randomSeed ?? randomSeed)(),
3761
- origin: "fresh"
3762
- };
3763
- }
3764
- function resolveBuildSeed(input, scope, deps = {}) {
3765
- const env = deps.env ?? process.env;
3766
- const session = openGeneration(scope.root, scope.leg);
3767
- const { seed, origin } = resolveWithinSession(input, session, env, deps);
3768
- if (origin === "env" || origin === "fresh") session.seed = seed;
3769
- if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3770
- const value = String(seed);
3771
- env[SEED_ENV_VAR] = value;
3772
- const stale = ownEnvExports.findIndex((e) => e.env === env);
3773
- if (stale >= 0) ownEnvExports.splice(stale, 1);
3774
- ownEnvExports.push({
3775
- env,
3776
- value
4997
+ const outputHashes = new Set(result.receipt.files.filter((f) => f.transformed !== false).map((f) => f.sha256));
4998
+ if (outputHashes.size === 0) continue;
4999
+ hashes ??= new Map(files.map((file) => [file, hashOf(file)]));
5000
+ const matches = files.filter((file) => {
5001
+ const hash = hashes?.get(file);
5002
+ return hash != null && outputHashes.has(hash);
3777
5003
  });
5004
+ if (matches.length > 0) return {
5005
+ receiptPath,
5006
+ files: matches
5007
+ };
3778
5008
  }
3779
- const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3780
- session.resolvedByLeg.set(scope.leg, seed);
3781
- return {
3782
- seed,
3783
- origin,
3784
- legs: [...session.legs],
3785
- generation: session.generation,
3786
- mismatch: prior && session.generation === 1 ? {
3787
- leg: prior[0],
3788
- seed: prior[1]
3789
- } : null
3790
- };
5009
+ return null;
3791
5010
  }
3792
5011
 
3793
5012
  //#endregion
@@ -3808,312 +5027,493 @@ function formatPassSummary(input, style, colorGlyph = (glyph) => glyph) {
3808
5027
  }
3809
5028
 
3810
5029
  //#endregion
3811
- //#region src/telemetry.ts
3812
- const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3813
- const DEFAULT_API_URL = "https://api.afterpack.dev";
3814
- const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3815
- const TELEMETRY_PAYLOAD_VERSION = 1;
3816
- const TELEMETRY_TIMEOUT_MS = 1500;
3817
- const INSTALL_ID_ROTATION_DAYS = 30;
3818
- const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3819
- const TELEMETRY_STATE_FILE = (0, node_path.join)((0, node_os.homedir)(), ".afterpack", "telemetry.json");
3820
- const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3821
- const DATA_FIELD_WHITELIST = {
3822
- outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3823
- parseError: ["parserErrorKind"],
3824
- engineBug: [
3825
- "phase",
3826
- "transform",
3827
- "nodeKind"
3828
- ],
3829
- inflationBudget: [
3830
- "target",
3831
- "achieved",
3832
- "budgetRatio",
3833
- "inflationRatio"
3834
- ],
3835
- configParse: [
3836
- "category",
3837
- "line",
3838
- "column"
3839
- ]
5030
+ //#region src/wire.ts
5031
+ const EXTERNAL_WIRE_DIR = "_external";
5032
+ const DRIVE_PATH = /^[A-Za-z]:[\\/]/;
5033
+ const URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]+:/;
5034
+ const FILE_URL = /^file:/i;
5035
+ const PATH_CHARS = "[^\\s\"'`|!?#()<>,;:*\\\\]";
5036
+ const EMBEDDED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:[A-Za-z]:[\\\\/]|/)(?:${PATH_CHARS}|\\\\(?!/))*)`, "g");
5037
+ const ESCAPED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:\\\\/${PATH_CHARS}+)+\\\\/?)`, "g");
5038
+ var WirePathError = class extends Error {
5039
+ constructor(message) {
5040
+ super(message);
5041
+ this.name = "WirePathError";
5042
+ }
3840
5043
  };
3841
- function resolveTelemetryEnabled(option, env = {}) {
3842
- if (option !== void 0) return option;
3843
- return !(env.NODE_ENV === "test" || env.VITEST);
5044
+ function toPosix(path) {
5045
+ return path.includes("\\") ? path.replaceAll("\\", "/") : path;
3844
5046
  }
3845
- const FRAMEWORK_ENTRIES = [
3846
- {
3847
- label: "afterpack",
3848
- name: "cli"
3849
- },
3850
- {
3851
- label: "afterpack-angular",
3852
- name: "angular",
3853
- pkg: "@angular/core"
3854
- },
3855
- {
3856
- label: "afterpack-esbuild",
3857
- name: "esbuild",
3858
- pkg: "esbuild"
3859
- },
3860
- {
3861
- label: "afterpack-next",
3862
- name: "next",
3863
- pkg: "next"
3864
- },
3865
- {
3866
- label: "afterpack-rollup",
3867
- name: "rollup",
3868
- pkg: "rollup"
3869
- },
3870
- {
3871
- label: "afterpack-vite",
3872
- name: "vite",
3873
- pkg: "vite"
3874
- },
3875
- {
3876
- label: "afterpack-webpack",
3877
- name: "webpack",
3878
- pkg: "webpack"
3879
- }
3880
- ];
3881
- const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3882
- const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3883
- function frameworkFromLabel(label) {
3884
- return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
5047
+ function lastSegment(path) {
5048
+ const parts = toPosix(path).split("/").filter((p) => p !== "");
5049
+ return parts[parts.length - 1] ?? "file";
3885
5050
  }
3886
- const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3887
- function detectFrameworkVersion(projectRoot, framework) {
3888
- const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3889
- if (!pkgName) return null;
3890
- let deps;
5051
+ function isUnder(child, parent) {
5052
+ const rel = (0, node_path.relative)(parent, child);
5053
+ return rel === "" || !(0, node_path.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${node_path.sep}`);
5054
+ }
5055
+ function relativeWithin(file, baseDir) {
5056
+ const rel = (0, node_path.relative)((0, node_path.resolve)(baseDir), (0, node_path.resolve)(file));
5057
+ if (rel === "" || (0, node_path.isAbsolute)(rel) || DRIVE_PATH.test(rel)) return null;
5058
+ if (rel === ".." || rel.startsWith(`..${node_path.sep}`)) return null;
5059
+ return toPosix(rel);
5060
+ }
5061
+ function osUsername() {
3891
5062
  try {
3892
- const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(projectRoot, "package.json"), "utf8"));
3893
- deps = {
3894
- ...pkg.dependencies,
3895
- ...pkg.devDependencies
3896
- };
5063
+ return (0, node_os.userInfo)().username;
3897
5064
  } catch {
3898
5065
  return null;
3899
5066
  }
3900
- const raw = deps[pkgName];
3901
- if (typeof raw !== "string") return null;
3902
- const range = raw.trim();
3903
- return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3904
- }
3905
- function complexityLabel(preset, complexity) {
3906
- if (preset !== void 0) return preset;
3907
- return complexity === void 0 ? "default" : "custom";
3908
- }
3909
- const FILE_COUNT_BUCKETS = [
3910
- 1,
3911
- 5,
3912
- 20,
3913
- 100,
3914
- 500,
3915
- 2e3
3916
- ];
3917
- function fileCountBucket(count) {
3918
- if (!Number.isFinite(count) || count <= 0) return "0";
3919
- let lower = 1;
3920
- for (const upper of FILE_COUNT_BUCKETS) {
3921
- if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3922
- lower = upper + 1;
3923
- }
3924
- return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3925
5067
  }
3926
- const DURATION_BUCKETS_MS = [
3927
- [1e3, "<1s"],
3928
- [5e3, "1-5s"],
3929
- [15e3, "5-15s"],
3930
- [6e4, "15-60s"],
3931
- [3e5, "60-300s"]
3932
- ];
3933
- function durationBucket(ms) {
3934
- if (!Number.isFinite(ms) || ms < 0) return "unknown";
3935
- for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3936
- return "300s+";
5068
+ function personalNames() {
5069
+ const names = new Set([(0, node_path.basename)((0, node_os.homedir)())]);
5070
+ const user = osUsername();
5071
+ if (user) names.add(user);
5072
+ return names;
3937
5073
  }
3938
- function safeScalar(value) {
3939
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
3940
- if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3941
- return null;
5074
+ function safeName(path) {
5075
+ const name = lastSegment(path);
5076
+ return personalNames().has(name) ? "file" : name;
3942
5077
  }
3943
- function telemetrySafeData(data) {
3944
- if (!data || typeof data.kind !== "string") return null;
3945
- const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3946
- if (kind === null) return null;
3947
- const out = { kind };
3948
- for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3949
- const value = safeScalar(data[field]);
3950
- if (value !== null) out[field] = value;
5078
+ function toWirePaths(files, baseDir) {
5079
+ const wire = new Map();
5080
+ const taken = new Set();
5081
+ const outside = [];
5082
+ for (const file of files) {
5083
+ if (wire.has(file)) continue;
5084
+ const rel = relativeWithin(file, baseDir);
5085
+ if (rel === null || taken.has(rel)) {
5086
+ outside.push(file);
5087
+ continue;
5088
+ }
5089
+ wire.set(file, rel);
5090
+ taken.add(rel);
5091
+ }
5092
+ let n = 0;
5093
+ for (const file of outside) {
5094
+ if (wire.has(file)) continue;
5095
+ let label;
5096
+ do {
5097
+ label = `${EXTERNAL_WIRE_DIR}/${n}/${safeName(file)}`;
5098
+ n += 1;
5099
+ } while (taken.has(label));
5100
+ wire.set(file, label);
5101
+ taken.add(label);
5102
+ }
5103
+ return wire;
5104
+ }
5105
+ function looksLocal(path) {
5106
+ return isUnder(path, (0, node_os.homedir)()) || isUnder(path, (0, node_os.tmpdir)()) || (0, node_fs.existsSync)(path);
5107
+ }
5108
+ function localPathOf(source) {
5109
+ if (DRIVE_PATH.test(source) || source.startsWith("/") || source.startsWith("\\")) return source;
5110
+ if (FILE_URL.test(source)) try {
5111
+ return (0, node_url.fileURLToPath)(source);
5112
+ } catch {
5113
+ return source.replace(FILE_URL, "").replace(/^\/\/[^/]*/, "") || "/";
3951
5114
  }
3952
- return out;
5115
+ const scheme = URL_SCHEME.exec(source);
5116
+ if (!scheme) return null;
5117
+ const rest = source.slice(scheme[0].length).replace(/^\/\/[^/]*/, "");
5118
+ const drive = rest.replace(/^\/+/, "");
5119
+ if (DRIVE_PATH.test(drive)) return drive;
5120
+ return rest.startsWith("/") && looksLocal(rest) ? rest : null;
3953
5121
  }
3954
- function telemetrySafeSpan(d) {
3955
- const span = d.span;
3956
- if (!span) return null;
3957
- const start = safeScalar(span.startByte);
3958
- const end = safeScalar(span.endByte);
3959
- if (typeof start !== "number" || typeof end !== "number") return null;
3960
- if (start < 0 || end < 0) return null;
5122
+ function bothForms(path) {
5123
+ return [...new Set([(0, node_path.resolve)(path), realPath(path)])];
5124
+ }
5125
+ function newPlace(dir, root, labels, shipped = "") {
3961
5126
  return {
3962
- startByte: start,
3963
- endByte: end
5127
+ dir,
5128
+ root,
5129
+ privateRoots: [...new Set([(0, node_os.homedir)(), root].flatMap(bothForms))],
5130
+ scratchRoots: bothForms((0, node_os.tmpdir)()),
5131
+ labels,
5132
+ shipped
3964
5133
  };
3965
5134
  }
3966
- function telemetrySafeDiagnostic(d, severity) {
5135
+ function isPrivate(path, place) {
5136
+ if (DRIVE_PATH.test(path) && !(0, node_path.isAbsolute)(path)) return true;
5137
+ if (place.privateRoots.some((r) => isUnder(path, r))) return true;
5138
+ return place.scratchRoots.some((r) => isUnder(path, r) && (0, node_path.resolve)(path) !== (0, node_path.resolve)(r));
5139
+ }
5140
+ function inProject(path, place) {
5141
+ if (DRIVE_PATH.test(path) && !(0, node_path.isAbsolute)(path)) return null;
5142
+ const real = realPath(path);
5143
+ const mapDir = realPath(place.dir);
5144
+ const home = realPath((0, node_os.homedir)());
5145
+ if (!isUnder(real, realPath(place.root))) return null;
5146
+ if (isUnder(real, home) && !isUnder(mapDir, home)) return null;
5147
+ const rel = (0, node_path.relative)(mapDir, real);
5148
+ if (rel === "" || (0, node_path.isAbsolute)(rel) || DRIVE_PATH.test(rel)) return null;
5149
+ return toPosix(rel);
5150
+ }
5151
+ function externalLabel(path, place) {
5152
+ const key = (0, node_path.resolve)(path);
5153
+ const known = place.labels.get(key);
5154
+ if (known !== void 0) return known;
5155
+ const label = `${EXTERNAL_WIRE_DIR}/${place.labels.size}/${safeName(path)}`;
5156
+ place.labels.set(key, label);
5157
+ return label;
5158
+ }
5159
+ function fitLength(target, candidate, slash) {
5160
+ const unit = `.${slash}`;
5161
+ const room = target - candidate.length;
5162
+ for (let a = Math.floor(Math.max(room, 0) / unit.length); a >= 0; a--) {
5163
+ const rest = room - a * unit.length;
5164
+ if (rest % slash.length !== 0) continue;
5165
+ const body = unit.repeat(a) + candidate;
5166
+ const extra = rest / slash.length;
5167
+ if (extra === 0) return body;
5168
+ const at = body.indexOf(slash);
5169
+ if (at < 0) continue;
5170
+ return body.slice(0, at) + slash.repeat(extra) + body.slice(at);
5171
+ }
5172
+ return null;
5173
+ }
5174
+ function sameLength(original, candidates, slash) {
5175
+ for (const candidate of candidates) {
5176
+ const fitted = fitLength(original.length, candidate, slash);
5177
+ if (fitted !== null) return fitted;
5178
+ }
5179
+ return "_".repeat(original.length);
5180
+ }
5181
+ function scrubText(text, place, keepLength) {
5182
+ if (!text.includes("/") && !text.includes("\\")) return text;
5183
+ const plain = text.replace(EMBEDDED_PATH, (whole, lead, path) => {
5184
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(path)) return whole;
5185
+ const name = inProject(path, place) ?? safeName(path);
5186
+ return `${lead}${keepLength ? sameLength(path, [name, safeName(path)], "/") : name}`;
5187
+ });
5188
+ return plain.replace(ESCAPED_PATH, (whole, lead, escaped) => {
5189
+ const path = escaped.replaceAll("\\/", "/");
5190
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(escaped)) return whole;
5191
+ const names = [inProject(path, place) ?? safeName(path), safeName(path)].map((c) => c.replaceAll("/", "\\/"));
5192
+ return `${lead}${keepLength ? sameLength(escaped, names, "\\/") : names[0]}`;
5193
+ });
5194
+ }
5195
+ function isRecord(value) {
5196
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5197
+ }
5198
+ function joinRoot(root, source) {
5199
+ return root.endsWith("/") || root.endsWith("\\") ? `${root}${source}` : `${root}/${source}`;
5200
+ }
5201
+ function newRestore() {
3967
5202
  return {
3968
- code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3969
- severity,
3970
- span: telemetrySafeSpan(d),
3971
- data: telemetrySafeData(d.data)
5203
+ sources: new Map(),
5204
+ pmPaths: new Map(),
5205
+ contents: new Map()
3972
5206
  };
3973
5207
  }
3974
- function buildTelemetryPayload(facts, ctx) {
3975
- let errorCount = 0;
3976
- let criticalCount = 0;
3977
- const alerting = [];
3978
- for (const d of facts.diagnostics) {
3979
- if (d.severity !== "error" && d.severity !== "critical") continue;
3980
- if (d.severity === "critical") criticalCount += 1;
3981
- else errorCount += 1;
3982
- alerting.push(telemetrySafeDiagnostic(d, d.severity));
3983
- }
3984
- if (alerting.length === 0) return null;
3985
- const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3986
- const env = ctx.env ?? {};
3987
- const runtime = ctx.runtime ?? {
3988
- node: process.versions.node,
3989
- platform: process.platform,
3990
- arch: process.arch
5208
+ function remember(table, wire, original) {
5209
+ const known = table.get(wire);
5210
+ if (known === void 0) table.set(wire, original);
5211
+ else if (known !== original) table.set(wire, null);
5212
+ }
5213
+ function wireMapObject(map, place, restore, top) {
5214
+ const out = { ...map };
5215
+ let changed = false;
5216
+ const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
5217
+ const rootIsLocal = root !== "" && localPathOf(root) !== null;
5218
+ if (rootIsLocal) {
5219
+ delete out.sourceRoot;
5220
+ if (top) restore.sourceRoot = root;
5221
+ changed = true;
5222
+ }
5223
+ const sentRoot = rootIsLocal ? "" : root;
5224
+ const pmPath = (r, s) => r === "" ? s : joinRoot(r, s);
5225
+ const taken = new Map();
5226
+ const claim = (wired, original, local) => {
5227
+ const owner = taken.get(wired);
5228
+ if (owner === void 0 || owner === original) {
5229
+ taken.set(wired, original);
5230
+ return wired;
5231
+ }
5232
+ const label = externalLabel(local, place);
5233
+ taken.set(label, original);
5234
+ return label;
3991
5235
  };
3992
- const framework = frameworkFromLabel(facts.label);
5236
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((source) => {
5237
+ if (typeof source !== "string") return source;
5238
+ const rooted = rootIsLocal && localPathOf(source) === null && !URL_SCHEME.test(source) ? joinRoot(root, source) : source;
5239
+ const local = localPathOf(rooted);
5240
+ let wired;
5241
+ if (local === null) {
5242
+ const scrubbed = scrubText(rooted, place, false);
5243
+ if (scrubbed === source) {
5244
+ taken.set(source, source);
5245
+ return source;
5246
+ }
5247
+ wired = claim(scrubbed, source, rooted);
5248
+ } else {
5249
+ const rel = inProject(local, place);
5250
+ wired = claim(rel ?? externalLabel(local, place), source, local);
5251
+ }
5252
+ changed = true;
5253
+ remember(restore.sources, wired, source);
5254
+ remember(restore.pmPaths, pmPath(sentRoot, wired), pmPath(root, source));
5255
+ return wired;
5256
+ });
5257
+ if (typeof map.file === "string" && localPathOf(map.file) !== null) {
5258
+ if (top) restore.file = map.file;
5259
+ out.file = safeName(map.file);
5260
+ changed = true;
5261
+ }
5262
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((content) => {
5263
+ if (typeof content !== "string") return content;
5264
+ const scrubbed = scrubText(content, place, true);
5265
+ if (scrubbed === content) return content;
5266
+ changed = true;
5267
+ remember(restore.contents, scrubbed, content);
5268
+ return scrubbed;
5269
+ });
5270
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
5271
+ if (!isRecord(section) || !isRecord(section.map)) return section;
5272
+ const nested = wireMapObject(section.map, place, restore, false);
5273
+ if (!nested.changed) return section;
5274
+ changed = true;
5275
+ return {
5276
+ ...section,
5277
+ map: nested.map
5278
+ };
5279
+ });
3993
5280
  return {
3994
- version: TELEMETRY_PAYLOAD_VERSION,
3995
- installId: ctx.installId,
3996
- framework,
3997
- frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3998
- engineVersion: safeVersion(facts.engineVersion),
3999
- clientVersion: safeVersion(facts.clientVersion),
4000
- nodeVersion: safeVersion(runtime.node) ?? "unknown",
4001
- os: safeToken(runtime.platform),
4002
- arch: safeToken(runtime.arch),
4003
- ci: env.CI === "true",
4004
- complexity: complexityLabel(facts.preset, facts.complexity),
4005
- fileCountBucket: fileCountBucket(facts.fileCount),
4006
- durationBucket: durationBucket(facts.durationMs),
4007
- diagnostics: kept,
4008
- errorCount,
4009
- criticalCount,
4010
- droppedCount: alerting.length - kept.length
5281
+ map: out,
5282
+ changed
4011
5283
  };
4012
5284
  }
4013
- const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
4014
- function safeVersion(value) {
4015
- return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
4016
- }
4017
- function safeToken(value) {
4018
- return TOKEN_PATTERN.test(value) ? value : "unknown";
4019
- }
4020
- const TELEMETRY_NOTICE = [
4021
- "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
4022
- "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
4023
- "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
4024
- "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
4025
- "AfterPack: file counts and durations, and a random install id that rotates every 30",
4026
- "AfterPack: days.",
4027
- "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
4028
- "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
4029
- "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
4030
- "AfterPack: `telemetry: { enabled: false }` in your config.",
4031
- "AfterPack: https://www.afterpack.dev/privacy"
4032
- ];
4033
- const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
4034
- const DAY_MS = 24 * 60 * 60 * 1e3;
4035
- function readState(file, now) {
5285
+ function wireSourceMapWithRestore(json, place) {
5286
+ const restore = newRestore();
5287
+ let parsed;
4036
5288
  try {
4037
- const parsed = JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
4038
- if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
4039
- installId: parsed.installId,
4040
- rotatedAt: parsed.rotatedAt,
4041
- noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
5289
+ parsed = JSON.parse(json);
5290
+ } catch {
5291
+ return {
5292
+ json: void 0,
5293
+ restore
4042
5294
  };
4043
- } catch {}
5295
+ }
5296
+ if (!isRecord(parsed)) return {
5297
+ json: void 0,
5298
+ restore
5299
+ };
5300
+ const { map, changed } = wireMapObject(parsed, place, restore, true);
4044
5301
  return {
4045
- installId: (0, node_crypto.randomUUID)(),
4046
- rotatedAt: now,
4047
- noticeShownAt: 0
5302
+ json: changed ? JSON.stringify(map) : json,
5303
+ restore
4048
5304
  };
4049
5305
  }
4050
- function writeState(file, state) {
4051
- try {
4052
- (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
4053
- (0, node_fs.writeFileSync)(file, `${JSON.stringify(state)}\n`, "utf8");
4054
- } catch {}
4055
- }
4056
- function telemetryUrl(env) {
4057
- const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
4058
- return `${base}${TELEMETRY_ENDPOINT_PATH}`;
5306
+ function lookup(table, value) {
5307
+ return table.get(value) ?? value;
5308
+ }
5309
+ function restoreMapObject(map, ctx, top) {
5310
+ let changed = false;
5311
+ const out = { ...map };
5312
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((entry) => {
5313
+ if (typeof entry !== "string") return entry;
5314
+ const back = entry === ctx.wire ? ctx.local : lookup(ctx.map.sources, entry);
5315
+ if (back !== entry) changed = true;
5316
+ return back;
5317
+ });
5318
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((entry) => {
5319
+ if (typeof entry !== "string") return entry;
5320
+ const back = lookup(ctx.map.contents, entry);
5321
+ if (back !== entry) changed = true;
5322
+ return back;
5323
+ });
5324
+ if (top && ctx.map.sourceRoot !== void 0 && !map.sourceRoot) {
5325
+ const root = ctx.map.sourceRoot;
5326
+ const entries = Object.entries(out).filter(([key]) => key !== "sourceRoot");
5327
+ const at = "sourceRoot" in map ? Object.keys(map).indexOf("sourceRoot") : -1;
5328
+ const after = entries.findIndex(([key]) => key === "sources");
5329
+ const index = at >= 0 ? at : after >= 0 ? after + 1 : entries.length;
5330
+ entries.splice(index, 0, ["sourceRoot", root]);
5331
+ for (const key of Object.keys(out)) delete out[key];
5332
+ Object.assign(out, Object.fromEntries(entries));
5333
+ changed = true;
5334
+ }
5335
+ if (top && ctx.map.file !== void 0 && typeof map.file === "string") {
5336
+ out.file = ctx.map.file;
5337
+ changed = true;
5338
+ }
5339
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
5340
+ if (!isRecord(section) || !isRecord(section.map)) return section;
5341
+ const nested = restoreMapObject(section.map, ctx, false);
5342
+ if (!nested.changed) return section;
5343
+ changed = true;
5344
+ return {
5345
+ ...section,
5346
+ map: nested.map
5347
+ };
5348
+ });
5349
+ return {
5350
+ map: out,
5351
+ changed
5352
+ };
4059
5353
  }
4060
- const TELEMETRY_BODY_LIMIT = 64 * 1024;
4061
- async function reportTelemetryNotices(response, logger) {
4062
- if (!response || response.status !== 202 || typeof response.text !== "function") return;
4063
- const declared = Number(response.headers?.get?.("content-length"));
4064
- if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
4065
- await response.body?.cancel().catch(() => {});
4066
- return;
4067
- }
4068
- const text = await response.text();
4069
- if (text.length > TELEMETRY_BODY_LIMIT) return;
4070
- let body;
5354
+ function restoreSourceMap(json, ctx) {
5355
+ let parsed;
4071
5356
  try {
4072
- body = JSON.parse(text);
5357
+ parsed = JSON.parse(json);
4073
5358
  } catch {
4074
- return;
5359
+ return json;
4075
5360
  }
4076
- if (typeof body !== "object" || body === null || Array.isArray(body)) return;
4077
- reportNotices(body.notices, logger);
5361
+ if (!isRecord(parsed)) return json;
5362
+ const { map, changed } = restoreMapObject(parsed, ctx, true);
5363
+ return changed ? JSON.stringify(map) : json;
4078
5364
  }
4079
- function createTelemetryReporter(deps = {}) {
4080
- const env = deps.env ?? process.env;
4081
- const logger = deps.logger ?? console;
4082
- const now = deps.now ?? Date.now;
4083
- const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
4084
- const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
4085
- return async (facts) => {
4086
- try {
4087
- const at = now();
4088
- const state = readState(stateFile, at);
4089
- let dirty = false;
4090
- if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
4091
- state.installId = (0, node_crypto.randomUUID)();
4092
- state.rotatedAt = at;
4093
- dirty = true;
4094
- }
4095
- if (state.noticeShownAt === 0) {
4096
- for (const line of TELEMETRY_NOTICE) logger.log(line);
4097
- state.noticeShownAt = at;
4098
- dirty = true;
5365
+ function restoredSize(size, wired, original) {
5366
+ if (typeof size !== "number") return size;
5367
+ if (size === Buffer.byteLength(wired)) return Buffer.byteLength(original);
5368
+ if (size === wired.length) return original.length;
5369
+ return size;
5370
+ }
5371
+ function restoreProtectionMap(doc, ctx) {
5372
+ if (!isRecord(doc) || !Array.isArray(doc.files)) return doc;
5373
+ return {
5374
+ ...doc,
5375
+ files: doc.files.map((entry) => {
5376
+ if (!isRecord(entry) || !isRecord(entry.file)) return entry;
5377
+ const file = entry.file;
5378
+ const next = { ...file };
5379
+ if (typeof file.path === "string") next.path = file.path === ctx.wire ? ctx.local : lookup(ctx.map.pmPaths, file.path);
5380
+ if (typeof file.originalSource === "string") {
5381
+ const original = lookup(ctx.map.contents, file.originalSource);
5382
+ if (original !== file.originalSource) {
5383
+ next.originalSource = original;
5384
+ next.inputSize = restoredSize(file.inputSize, file.originalSource, original);
5385
+ }
4099
5386
  }
4100
- if (dirty) writeState(stateFile, state);
4101
- if (facts === null) return;
4102
- const payload = buildTelemetryPayload(facts, {
4103
- installId: state.installId,
4104
- env
4105
- });
4106
- if (payload === null) return;
4107
- const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
4108
- if (typeof fetchImpl !== "function") return;
4109
- const response = await fetchImpl(telemetryUrl(env), {
4110
- method: "POST",
4111
- headers: { "content-type": "application/json" },
4112
- body: JSON.stringify(payload),
4113
- signal: AbortSignal.timeout(timeoutMs)
4114
- });
4115
- await reportTelemetryNotices(response, logger);
4116
- } catch {}
5387
+ const same = Object.keys(next).every((k) => next[k] === file[k]);
5388
+ return same ? entry : {
5389
+ ...entry,
5390
+ file: next
5391
+ };
5392
+ })
5393
+ };
5394
+ }
5395
+ function wireGlob(pattern, pairs) {
5396
+ let equivalent = true;
5397
+ const matched = [];
5398
+ for (const [local, wire] of pairs) {
5399
+ const hit = matchesPath(pattern, local);
5400
+ if (hit !== matchesPath(pattern, wire)) equivalent = false;
5401
+ if (hit) matched.push(wire);
5402
+ }
5403
+ if (!isAnchored(pattern) && equivalent && matched.length > 0) return [pattern];
5404
+ return matched.map((wire) => `/${wire}`);
5405
+ }
5406
+ function anyMatch(patterns, path) {
5407
+ return patterns.some((p) => matchesPath(p, path));
5408
+ }
5409
+ function reservedNames(entries, path) {
5410
+ const names = entries.flatMap((e) => typeof e === "string" ? [] : matchesPath(e.glob, path) ? e.names : []);
5411
+ return [...new Set(names)].sort().join("\n");
5412
+ }
5413
+ function verifyTranslation(config, out, pairs) {
5414
+ const exclude = config.paths?.exclude ?? [];
5415
+ const sentExclude = out.paths?.exclude ?? [];
5416
+ const reserved = config.identifiers?.reserved ?? [];
5417
+ const sentReserved = out.identifiers?.reserved ?? [];
5418
+ for (const [local, wire] of pairs) {
5419
+ if (anyMatch(exclude, local) !== anyMatch(sentExclude, wire)) throw new WirePathError(`could not send \`paths.exclude\` to the engine without changing which files it selects: ${wire} would be ${anyMatch(exclude, local) ? "protected" : "left unprotected"}. Rename the file or write the pattern so it does not depend on glob characters in file names.`);
5420
+ if (reservedNames(reserved, local) !== reservedNames(sentReserved, wire)) throw new WirePathError(`could not send \`identifiers.reserved\` to the engine without changing which files its globs select: ${wire} would keep a different set of names. Rename the file or write the glob so it does not depend on glob characters in file names.`);
5421
+ }
5422
+ }
5423
+ function translateConfig(config, wirePaths) {
5424
+ const exclude = config.paths?.exclude;
5425
+ const reserved = config.identifiers?.reserved;
5426
+ const origins = new Map();
5427
+ if (exclude === void 0 && reserved === void 0) return {
5428
+ config,
5429
+ origins
5430
+ };
5431
+ const pairs = [...wirePaths.entries()];
5432
+ const translate = (pattern) => {
5433
+ const patterns = wireGlob(pattern, pairs);
5434
+ for (const p of patterns) if (!origins.has(p)) origins.set(p, pattern);
5435
+ return patterns;
5436
+ };
5437
+ const out = { ...config };
5438
+ if (exclude !== void 0) out.paths = {
5439
+ ...config.paths,
5440
+ exclude: [...new Set(exclude.flatMap((pattern) => translate(pattern)))]
5441
+ };
5442
+ if (reserved !== void 0) out.identifiers = {
5443
+ ...config.identifiers,
5444
+ reserved: reserved.flatMap((entry) => typeof entry === "string" ? [entry] : translate(entry.glob).map((glob) => ({
5445
+ ...entry,
5446
+ glob
5447
+ })))
5448
+ };
5449
+ verifyTranslation(config, out, pairs);
5450
+ return {
5451
+ config: out,
5452
+ origins
5453
+ };
5454
+ }
5455
+ function escapeRegExp(text) {
5456
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5457
+ }
5458
+ function localMessage(message, wire, local, origins) {
5459
+ let out = message;
5460
+ for (const [sent, original] of origins) if (sent !== original) out = out.split(`"${sent}"`).join(`"${original}"`);
5461
+ const bounded = new RegExp(`(^|[\\s"'\`(\\[])${escapeRegExp(wire)}(?=$|[\\s"'\`)\\]:,;]|\\.(?:\\s|$))`, "g");
5462
+ return out.replace(bounded, (_m, lead) => `${lead}${local}`);
5463
+ }
5464
+ function localDiagnostics(diagnostics, localPaths, wire, local, origins) {
5465
+ if (!Array.isArray(diagnostics)) return diagnostics;
5466
+ return diagnostics.map((d) => {
5467
+ if (!isRecord(d)) return d;
5468
+ const next = { ...d };
5469
+ if (typeof d.file === "string") next.file = localPaths.get(d.file) ?? d.file;
5470
+ if (typeof d.message === "string") next.message = localMessage(d.message, wire, local, origins);
5471
+ return next.file === d.file && next.message === d.message ? d : next;
5472
+ });
5473
+ }
5474
+ function prepareWireBatch(inputs, config, baseDir, rootDir = baseDir) {
5475
+ const wirePaths = toWirePaths(inputs.map((i) => i.path), baseDir);
5476
+ const localPaths = new Map([...wirePaths].map(([local, wire]) => [wire, local]));
5477
+ const translated = translateConfig(config, wirePaths);
5478
+ const restores = new Map();
5479
+ const labels = new Map();
5480
+ const wiredInputs = inputs.map((input) => {
5481
+ const path = wirePaths.get(input.path) ?? input.path;
5482
+ const wired = {
5483
+ ...input,
5484
+ path
5485
+ };
5486
+ if (input.sourceMap !== void 0) {
5487
+ const place = newPlace((0, node_path.dirname)((0, node_path.resolve)(input.path)), rootDir, labels, input.source);
5488
+ const map = wireSourceMapWithRestore(input.sourceMap, place);
5489
+ restores.set(path, map.restore);
5490
+ if (map.json === void 0) delete wired.sourceMap;
5491
+ else wired.sourceMap = map.json;
5492
+ }
5493
+ return wired;
5494
+ });
5495
+ return {
5496
+ inputs: wiredInputs,
5497
+ config: translated.config,
5498
+ toLocal: (batch) => ({
5499
+ ...batch,
5500
+ files: batch.files.map((f) => {
5501
+ const local = localPaths.get(f.path);
5502
+ if (local === void 0) return f;
5503
+ const ctx = {
5504
+ map: restores.get(f.path) ?? newRestore(),
5505
+ wire: f.path,
5506
+ local
5507
+ };
5508
+ return {
5509
+ ...f,
5510
+ path: local,
5511
+ ...f.diagnostics === void 0 ? {} : { diagnostics: localDiagnostics(f.diagnostics, localPaths, f.path, local, translated.origins) },
5512
+ ...typeof f.sourceMap === "string" ? { sourceMap: restoreSourceMap(f.sourceMap, ctx) } : {},
5513
+ ...f.protectionMap == null ? {} : { protectionMap: restoreProtectionMap(f.protectionMap, ctx) }
5514
+ };
5515
+ })
5516
+ })
4117
5517
  };
4118
5518
  }
4119
5519
 
@@ -4150,12 +5550,19 @@ function fileFailure(f, source) {
4150
5550
  if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
4151
5551
  return null;
4152
5552
  }
4153
- async function readEngineVersion(engine) {
4154
- try {
4155
- return await engine.version?.() ?? null;
4156
- } catch {
4157
- return null;
5553
+ function bundlerMapsToRemove(input) {
5554
+ const { sweepDir: sweepDir$1, engineMaps, policy } = input;
5555
+ const bundlerMaps = new Set([...input.perFile].flat());
5556
+ if (sweepDir$1 != null) {
5557
+ const swept = collectSourceMaps(sweepDir$1).filter((path) => !policy.sourceMap || !path.endsWith(".css.map"));
5558
+ for (const path of containedSourceMaps(swept, sweepDir$1)) bundlerMaps.add(path);
4158
5559
  }
5560
+ return [...bundlerMaps].filter((path) => !engineMaps.has(path));
5561
+ }
5562
+ function removeBundlerSourceMaps(input) {
5563
+ const { sweepDir: sweepDir$1, policy, label } = input;
5564
+ removeSourceMaps(bundlerMapsToRemove(input), label);
5565
+ if (sweepDir$1 != null && !policy.sourceMap) stripCssSourceMappingURLs(collectStylesheets(sweepDir$1));
4159
5566
  }
4160
5567
  function describeLevel(preset, complexity) {
4161
5568
  if (complexity === void 0) return `preset "${preset ?? DEFAULT_PRESET}"`;
@@ -4165,22 +5572,30 @@ function describeLevel(preset, complexity) {
4165
5572
  async function runObfuscationPass(options) {
4166
5573
  const passStartedAt = options.startedAt ?? Date.now();
4167
5574
  const callerAnchored = options.startedAt !== void 0;
4168
- const { files, engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
5575
+ const { engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
4169
5576
  const logger = silenceSummaryLines(options.logger ?? DEFAULT_LOGGER, options.diagnostics);
4170
5577
  const prefix = (message) => `[${label}] ${message}`;
4171
5578
  const style = options.summaryStyle ?? "plugin";
4172
5579
  assertSupportedCore(options.client, prefix);
5580
+ const outsideBuildDir = options.emitToCaller ? [] : options.files.filter((f) => !options.inputs?.has(f) && !withinRealDir((0, node_path.dirname)(f), combinedProtectionMap.buildDir));
5581
+ const files = options.files.filter((f) => !outsideBuildDir.includes(f));
5582
+ if (outsideBuildDir.length > 0) logger.warn(prefix(`left ${outsideBuildDir.length} file(s) untouched because a symlink places them outside ${combinedProtectionMap.buildDir}: ${outsideBuildDir.join(", ")}`));
4173
5583
  const onDiskFiles = options.inputs ? files.filter((f) => !options.inputs?.has(f)) : files;
4174
5584
  const onDiskBytes = new Map(await Promise.all(onDiskFiles.map(async (filePath) => [filePath, await (0, node_fs_promises.readFile)(filePath)])));
5585
+ const home = afterpackHome(combinedProtectionMap.buildDir, { fileTarget: combinedProtectionMap.fileTarget });
5586
+ const unanchored = describeUnanchoredHome(home);
5587
+ if (unanchored) logger.log(prefix(unanchored));
4175
5588
  if (!options.emitToCaller) {
4176
- const already = detectAlreadyObfuscatedInputs(onDiskFiles, combinedProtectionMap.buildDir, onDiskBytes, prefix);
5589
+ const already = detectAlreadyObfuscatedInputs(onDiskFiles, home, onDiskBytes, prefix);
4177
5590
  if (already) throw new AlreadyObfuscatedError(prefix(formatAlreadyObfuscatedMessage({
4178
5591
  files: already.files,
4179
5592
  receiptPath: already.receiptPath,
4180
5593
  dir: combinedProtectionMap.buildDir
4181
5594
  })), already.files, already.receiptPath, combinedProtectionMap.buildDir);
4182
5595
  }
4183
- const resolvedSeed = resolveBuildSeed(options.seed, {
5596
+ if (options.outputSweep !== false) sweepOutputTree(combinedProtectionMap.buildDir, options.sourceMapSweepDir ?? (options.emitToCaller ? combinedProtectionMap.buildDir : null), label, home);
5597
+ prepareProtectionReceipt(home, label);
5598
+ const resolvedSeed = options.resolvedSeed ?? resolveBuildSeed(options.seed, {
4184
5599
  root: cwd,
4185
5600
  leg: options.buildLeg ?? combinedProtectionMap.buildDir
4186
5601
  }, {
@@ -4193,6 +5608,9 @@ async function runObfuscationPass(options) {
4193
5608
  const bundledCapture = options.capturedByFile != null;
4194
5609
  const postMinifyMode = directivesEnabled && options.postMinify === true && !bundledCapture;
4195
5610
  const sourceByPath = new Map();
5611
+ const bundlerMapsByPath = new Map();
5612
+ const sweepDir$1 = options.sourceMapSweepDir ?? null;
5613
+ const sourceMapRoot = sweepDir$1 ?? combinedProtectionMap.buildDir;
4196
5614
  let coloredRegionCount = 0;
4197
5615
  let directivesNeededMap = false;
4198
5616
  let postMinifyMapsSeen = 0;
@@ -4202,6 +5620,7 @@ async function runObfuscationPass(options) {
4202
5620
  const provided = options.inputs?.get(filePath);
4203
5621
  const source = provided ? provided.source : (onDiskBytes.get(filePath) ?? (0, node_fs.readFileSync)(filePath)).toString("utf8");
4204
5622
  sourceByPath.set(filePath, source);
5623
+ if (!provided && !options.emitToCaller) bundlerMapsByPath.set(filePath, bundlerSourceMapPaths(filePath, source, sourceMapRoot));
4205
5624
  const inputSourceMap = provided ? provided.sourceMap ?? null : discoverInputSourceMap(filePath, source);
4206
5625
  let regions;
4207
5626
  const modules = options.capturedByFile?.get(filePath);
@@ -4282,7 +5701,12 @@ async function runObfuscationPass(options) {
4282
5701
  cwd
4283
5702
  });
4284
5703
  const localEngineVersion = await readEngineVersion(engine);
4285
- const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(localEngineVersion ?? options.client?.coreVersion) ? options.sourceType : void 0;
5704
+ const gateVersion = localEngineVersion ?? options.client?.coreVersion;
5705
+ const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(gateVersion) ? options.sourceType : void 0;
5706
+ if (options.fileSourceTypes && options.engineConfig?.sourceType === void 0 && coreSupportsFileSourceType(gateVersion)) for (const input of inputs) {
5707
+ const sourceType = options.fileSourceTypes.get(input.path);
5708
+ if (sourceType !== void 0) input.sourceType = sourceType;
5709
+ }
4286
5710
  const engineConfig = buildEngineConfig({
4287
5711
  policy,
4288
5712
  seed,
@@ -4293,6 +5717,40 @@ async function runObfuscationPass(options) {
4293
5717
  engine: options.engineConfig,
4294
5718
  renameGlobals: capture.renameGlobals
4295
5719
  });
5720
+ const saltEngine = options.cloudEngineExpectation ?? (options.hashedNames ? await resolveSaltEngine(env, localEngineVersion) : null);
5721
+ let namesPlan = null;
5722
+ let hashSalt = null;
5723
+ if (options.hashedNames && saltEngine && !options.emitToCaller) {
5724
+ const { seed: _seed,...configWithoutSeed } = engineConfig;
5725
+ const namedInputs = new Map(inputs.map((input) => [input.path, {
5726
+ source: input.source,
5727
+ regions: input.regions,
5728
+ sourceType: input.sourceType
5729
+ }]));
5730
+ hashSalt = afterpackHashSalt({
5731
+ seed,
5732
+ engine: saltEngine,
5733
+ settings: {
5734
+ engine: configWithoutSeed,
5735
+ sourceMap: policy.sourceMap,
5736
+ emitSourceMappingURL: policy.emitSourceMappingURL
5737
+ }
5738
+ });
5739
+ namesPlan = planHashedNames({
5740
+ options: options.hashedNames,
5741
+ inputs: namedInputs,
5742
+ salt: hashSalt
5743
+ });
5744
+ namesPlan.preflight();
5745
+ for (const input of inputs) {
5746
+ const path = namesPlan.renamed.get(input.path) ?? input.path;
5747
+ const source = namesPlan.rewrite(input.source);
5748
+ sourceByPath.delete(input.path);
5749
+ sourceByPath.set(path, source);
5750
+ input.path = path;
5751
+ input.source = source;
5752
+ }
5753
+ }
4296
5754
  if (style !== "cli") logger.log(prefix(`obfuscating ${inputs.length} file(s) at ${describeLevel(options.preset, options.complexity)} ...`));
4297
5755
  const engineStartedAt = Date.now();
4298
5756
  const prepMs = engineStartedAt - passStartedAt;
@@ -4300,9 +5758,16 @@ async function runObfuscationPass(options) {
4300
5758
  clientVersion: options.client?.coreVersion,
4301
5759
  client: clientString(options.client)
4302
5760
  });
5761
+ let wire;
5762
+ try {
5763
+ wire = prepareWireBatch(inputs, engineConfig, combinedProtectionMap.buildDir, home.projectRoot);
5764
+ } catch (error) {
5765
+ if (error instanceof WirePathError) throw new Error(prefix(error.message));
5766
+ throw error;
5767
+ }
4303
5768
  let batch;
4304
5769
  try {
4305
- batch = await engine.processBatch(inputs, engineConfig, context);
5770
+ batch = wire.toLocal(await engine.processBatch(wire.inputs, wire.config, context));
4306
5771
  } catch (error) {
4307
5772
  const cloud = toCloudApiError(error, {
4308
5773
  identity: options.client,
@@ -4313,6 +5778,7 @@ async function runObfuscationPass(options) {
4313
5778
  throw cloud;
4314
5779
  }
4315
5780
  const engineEndedAt = Date.now();
5781
+ options.onBatch?.(inputs, batch);
4316
5782
  reportNotices(batch.notices, logger, prefix);
4317
5783
  const engineMs = engineEndedAt - engineStartedAt;
4318
5784
  const collected = collectDiagnostics(batch.files);
@@ -4327,6 +5793,10 @@ async function runObfuscationPass(options) {
4327
5793
  const telemetry = options.telemetry;
4328
5794
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4329
5795
  const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
5796
+ if (saltEngine) {
5797
+ const mismatch = cloudEngineMismatch(saltEngine, batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null);
5798
+ if (mismatch) throw new Error(prefix(mismatch));
5799
+ }
4330
5800
  if (telemetry && telemetryEnabled) {
4331
5801
  const facts = {
4332
5802
  label,
@@ -4364,8 +5834,57 @@ async function runObfuscationPass(options) {
4364
5834
  source
4365
5835
  });
4366
5836
  }
5837
+ const artifactInput = (f, source) => ({
5838
+ outPath: f.path,
5839
+ code: withSourceMappingURL(f.code, null),
5840
+ sourceMapJson: f.sourceMap ?? null,
5841
+ originalSource: source,
5842
+ policy,
5843
+ mode: "framework"
5844
+ });
5845
+ if (!options.emitToCaller && options.beforeWrite) {
5846
+ const planned = new Map();
5847
+ const expectState = (path, state) => {
5848
+ const states = planned.get(path) ?? [];
5849
+ if (!states.includes(state)) states.push(state);
5850
+ planned.set(path, states);
5851
+ };
5852
+ for (const from of namesPlan?.renamed.keys() ?? []) expectState(from, null);
5853
+ const plannedEngineMaps = new Set();
5854
+ for (const { result: f, source } of verified) {
5855
+ const artifacts = planArtifactWrites(artifactInput(f, source));
5856
+ if (artifacts.mapPath) plannedEngineMaps.add((0, node_path.resolve)(artifacts.mapPath));
5857
+ for (const write of artifacts.writes) {
5858
+ expectState(write.path, sha256Hex(write.content));
5859
+ expectState(stagedPath(write.path), null);
5860
+ }
5861
+ }
5862
+ for (const { to, text } of namesPlan?.rewrites.values() ?? []) {
5863
+ expectState(to, sha256Hex(text));
5864
+ expectState(stagedPath(to), null);
5865
+ }
5866
+ for (const map of bundlerMapsToRemove({
5867
+ perFile: bundlerMapsByPath.values(),
5868
+ sweepDir: sweepDir$1,
5869
+ engineMaps: plannedEngineMaps,
5870
+ policy
5871
+ })) expectState(map, null);
5872
+ if (sweepDir$1 != null && !policy.sourceMap) for (const css of collectStylesheets(sweepDir$1)) {
5873
+ const rewritten = namesPlan?.rewrites.get(css);
5874
+ const text = rewritten?.text ?? (0, node_fs.readFileSync)(css, "utf8");
5875
+ const stripped = withoutCssSourceMappingURL(text);
5876
+ if (stripped === text) continue;
5877
+ expectState(rewritten?.to ?? css, sha256Hex(stripped));
5878
+ expectState(stagedPath(rewritten?.to ?? css), null);
5879
+ }
5880
+ options.beforeWrite({
5881
+ renamed: namesPlan?.renamed ?? new Map(),
5882
+ planned
5883
+ });
5884
+ }
4367
5885
  const writtenFiles = [];
4368
5886
  const emittedFiles = [];
5887
+ const engineMaps = new Set();
4369
5888
  for (const { result: f, source } of verified) {
4370
5889
  if (options.emitToCaller) {
4371
5890
  outputs.push({
@@ -4377,25 +5896,38 @@ async function runObfuscationPass(options) {
4377
5896
  continue;
4378
5897
  }
4379
5898
  const written = writeArtifacts({
4380
- outPath: f.path,
4381
- code: f.code,
4382
- sourceMapJson: f.sourceMap ?? null,
5899
+ ...artifactInput(f, source),
4383
5900
  protectionMapJson: null,
4384
- originalSource: source,
4385
- policy,
4386
- mode: "framework",
5901
+ afterpackDir: home.dir,
4387
5902
  logger
4388
5903
  });
4389
5904
  writtenFiles.push(written.codePath);
4390
- if (written.mapPath) sensitiveArtifactPaths.push(written.mapPath);
5905
+ if (written.mapPath) {
5906
+ sensitiveArtifactPaths.push(written.mapPath);
5907
+ engineMaps.add((0, node_path.resolve)(written.mapPath));
5908
+ }
4391
5909
  if (written.backupPath) sensitiveArtifactPaths.push(written.backupPath);
4392
5910
  }
4393
- if (!options.emitToCaller) options.afterWrite?.();
5911
+ if (!options.emitToCaller) {
5912
+ if (namesPlan) {
5913
+ for (const [from, to] of namesPlan.renamed) if (sourceByPath.has(to)) (0, node_fs.rmSync)(from, { force: true });
5914
+ namesPlan.apply();
5915
+ if (namesPlan.renamed.size > 0) logger.log(prefix(`renamed ${namesPlan.renamed.size} content-hashed file(s) so each name follows its obfuscated bytes`));
5916
+ }
5917
+ removeBundlerSourceMaps({
5918
+ perFile: bundlerMapsByPath.values(),
5919
+ sweepDir: sweepDir$1,
5920
+ engineMaps,
5921
+ policy,
5922
+ label
5923
+ });
5924
+ options.afterWrite?.(writtenFiles);
5925
+ }
4394
5926
  const protectionMapPath = writeCombinedProtectionMap({
4395
5927
  buildDir: combinedProtectionMap.buildDir,
4396
5928
  docs: protectionMapDocs,
4397
5929
  policy,
4398
- afterpackDir: combinedProtectionMap.afterpackDir,
5930
+ afterpackDir: combinedProtectionMap.subdir ? (0, node_path.join)(home.dir, combinedProtectionMap.subdir) : home.dir,
4399
5931
  fileName: combinedProtectionMap.fileName,
4400
5932
  logger
4401
5933
  });
@@ -4417,12 +5949,15 @@ async function runObfuscationPass(options) {
4417
5949
  if (options.emitToCaller) deferredReceipt = {
4418
5950
  ...receiptFields,
4419
5951
  dir: combinedProtectionMap.buildDir,
5952
+ home,
4420
5953
  files: emittedFiles
4421
5954
  };
4422
5955
  else {
4423
5956
  receiptPath = writeProtectionReceipt({
4424
5957
  ...receiptFields,
4425
5958
  dir: combinedProtectionMap.buildDir,
5959
+ home,
5960
+ merge: combinedProtectionMap.fileTarget === true,
4426
5961
  files: writtenFiles
4427
5962
  });
4428
5963
  if (style !== "cli") logger.log(prefix(`wrote protection receipt -> ${receiptPath} (afterpack verify)`));
@@ -4461,6 +5996,8 @@ async function runObfuscationPass(options) {
4461
5996
  timing,
4462
5997
  diagnostics: diagnosticsSummary,
4463
5998
  transformedFiles,
5999
+ renamed: namesPlan?.renamed ?? new Map(),
6000
+ hashSalt,
4464
6001
  ...options.emitToCaller ? { outputs } : {}
4465
6002
  };
4466
6003
  }
@@ -4640,6 +6177,8 @@ function resolvePluginConfig(input) {
4640
6177
  }
4641
6178
 
4642
6179
  //#endregion
6180
+ exports.AFTERPACK_DIR = AFTERPACK_DIR;
6181
+ exports.AfterpackFilesError = AfterpackFilesError;
4643
6182
  exports.AlreadyObfuscatedError = AlreadyObfuscatedError;
4644
6183
  exports.CLOUD_REFUSAL_SUMMARY = CLOUD_REFUSAL_SUMMARY;
4645
6184
  exports.CONFIG_FILE_NAME = CONFIG_FILE_NAME;
@@ -4647,49 +6186,79 @@ exports.CONFIG_KEYS = CONFIG_KEYS;
4647
6186
  exports.CORE_FLOOR_SUMMARY = CORE_FLOOR_SUMMARY;
4648
6187
  exports.CloudApiError = CloudApiError;
4649
6188
  exports.CoreVersionError = CoreVersionError;
6189
+ exports.DIAG_AFTERPACK_DIR_IN_OUTPUT = DIAG_AFTERPACK_DIR_IN_OUTPUT;
4650
6190
  exports.DIAG_ALREADY_OBFUSCATED = DIAG_ALREADY_OBFUSCATED;
4651
6191
  exports.DIAG_RECEIPT_UNREADABLE = DIAG_RECEIPT_UNREADABLE;
4652
- exports.PROTECTION_RECEIPT_FILE = PROTECTION_RECEIPT_FILE;
6192
+ exports.DIAG_RECEIPT_UNWRITABLE = DIAG_RECEIPT_UNWRITABLE;
6193
+ exports.NEXT_CHUNKS_PREFIX = NEXT_CHUNKS_PREFIX;
6194
+ exports.PROTECTION_RECEIPTS_DIR = PROTECTION_RECEIPTS_DIR;
4653
6195
  exports.SEED_ENV_VAR = SEED_ENV_VAR;
4654
6196
  exports.UnreadableReceiptError = UnreadableReceiptError;
6197
+ exports.afterpackHome = afterpackHome;
6198
+ exports.angularHashToken = angularHashToken;
6199
+ exports.angularServerManifestRefusal = angularServerManifestRefusal;
4655
6200
  exports.applyBundleOutput = applyBundleOutput;
4656
6201
  exports.applyResolvedKey = applyResolvedKey;
6202
+ exports.buildDirKey = buildDirKey;
4657
6203
  exports.collectBundleJs = collectBundleJs;
4658
6204
  exports.collectJsFiles = collectJsFiles;
4659
6205
  exports.collectSourceMaps = collectSourceMaps;
4660
6206
  exports.collectStylesheets = collectStylesheets;
4661
6207
  exports.createTelemetryReporter = createTelemetryReporter;
4662
6208
  exports.decodeDataUri = decodeDataUri;
6209
+ exports.detectNextBundler = detectNextBundler;
4663
6210
  exports.discoverInputSourceMap = discoverInputSourceMap;
4664
6211
  exports.ensureAfterpackGitignore = ensureAfterpackGitignore;
4665
6212
  exports.extractSourceMappingURL = extractSourceMappingURL;
6213
+ exports.findHashTokenReference = findHashTokenReference;
4666
6214
  exports.findUpward = findUpward;
4667
6215
  exports.getPath = getPath;
4668
6216
  exports.installedRequiredLine = installedRequiredLine;
6217
+ exports.isWithinDir = isWithinDir;
4669
6218
  exports.loadConfigFile = loadConfigFile;
6219
+ exports.locateProtectionReceipt = locateProtectionReceipt;
4670
6220
  exports.mergeConfig = mergeConfig;
6221
+ exports.nextChunkToken = nextChunkToken;
4671
6222
  exports.normalizePluginOptions = normalizePluginOptions;
4672
6223
  exports.npxAlternative = npxAlternative;
4673
6224
  exports.parseCliOptions = parseCliOptions;
4674
6225
  exports.parseEnvOptions = parseEnvOptions;
4675
6226
  exports.passSettings = passSettings;
6227
+ exports.planAngularIntegrity = planAngularIntegrity;
6228
+ exports.prepareHashSalt = prepareHashSalt;
6229
+ exports.protectionReceiptPath = protectionReceiptPath;
6230
+ exports.readEngineVersion = readEngineVersion;
6231
+ exports.recomputeAngularIntegrity = recomputeAngularIntegrity;
6232
+ exports.regenerateCompressedSiblings = regenerateCompressedSiblings;
6233
+ exports.removeSourceMaps = removeSourceMaps;
6234
+ exports.reportPolicySaltBits = reportPolicySaltBits;
4676
6235
  exports.resolveClientIdentity = resolveClientIdentity;
4677
6236
  exports.resolvePluginConfig = resolvePluginConfig;
4678
6237
  exports.resolveReportPolicy = resolveReportPolicy;
4679
6238
  exports.runObfuscationPass = runObfuscationPass;
6239
+ exports.saltSettings = saltSettings;
4680
6240
  exports.sanitizeNotices = sanitizeNotices;
4681
6241
  exports.scanDirectives = scanDirectives;
4682
6242
  exports.serverAddsInfo = serverAddsInfo;
6243
+ exports.sha256Hex = sha256Hex;
4683
6244
  exports.sha256Of = sha256Of;
6245
+ exports.skipNextInternals = skipNextInternals;
4684
6246
  exports.sourceTypeForBundle = sourceTypeForBundle;
4685
6247
  exports.sourceTypeForOutputFormat = sourceTypeForOutputFormat;
6248
+ exports.sriPluginRefusal = sriPluginRefusal;
6249
+ exports.stagedPath = stagedPath;
4686
6250
  exports.stripBundleCssSourceMaps = stripBundleCssSourceMaps;
6251
+ exports.stripCssSourceMappingURLs = stripCssSourceMappingURLs;
6252
+ exports.sweepOutputTree = sweepOutputTree;
4687
6253
  exports.toEngineConfig = toEngineConfig;
4688
6254
  exports.toPluginOptions = toPluginOptions;
6255
+ exports.unreferencedHashedFiles = unreferencedHashedFiles;
6256
+ exports.unsaltedAssetsWarning = unsaltedAssetsWarning;
4689
6257
  exports.validateConfig = validateConfig;
4690
6258
  exports.verifyProtectionReceipt = verifyProtectionReceipt;
4691
6259
  exports.withSourceMappingURL = withSourceMappingURL;
4692
6260
  exports.withoutCssSourceMappingURL = withoutCssSourceMappingURL;
4693
6261
  exports.writeArtifacts = writeArtifacts;
4694
6262
  exports.writeDeferredProtectionReceipt = writeDeferredProtectionReceipt;
6263
+ exports.writeFileAtomic = writeFileAtomic;
4695
6264
  exports.writeProtectionReceipt = writeProtectionReceipt;