@afterpack/integration-utils 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,100 @@
1
1
  import { createRequire } from "node:module";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { accessSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
4
4
  import { renderProtectionMapHtml } from "@afterpack/protection-map";
5
5
  import { createHash, randomBytes, randomUUID } from "node:crypto";
6
+ import { brotliCompressSync, gzipSync } from "node:zlib";
6
7
  import { fileURLToPath } from "node:url";
7
- import { readFile } from "node:fs/promises";
8
8
  import { execFileSync } from "node:child_process";
9
+ import { homedir, tmpdir, userInfo } from "node:os";
10
+ import { readFile } from "node:fs/promises";
9
11
  import { decode } from "@jridgewell/sourcemap-codec";
10
- import { homedir } from "node:os";
11
12
 
13
+ //#region src/home.ts
14
+ const AFTERPACK_DIR = ".afterpack";
15
+ const STRONG_MARKERS = [
16
+ "afterpack.json",
17
+ ".git",
18
+ "package-lock.json",
19
+ "npm-shrinkwrap.json",
20
+ "pnpm-lock.yaml",
21
+ "yarn.lock",
22
+ "bun.lock",
23
+ "bun.lockb"
24
+ ];
25
+ const WEAK_MARKERS = ["package.json"];
26
+ const DIAG_AFTERPACK_DIR_IN_OUTPUT = "DIAG_AFTERPACK_DIR_IN_OUTPUT";
27
+ const DIAG_RECEIPT_UNWRITABLE = "DIAG_RECEIPT_UNWRITABLE";
28
+ var AfterpackFilesError = class extends Error {
29
+ code;
30
+ summary;
31
+ fix;
32
+ constructor(code, summary, fix) {
33
+ super(`${summary} ${fix}`);
34
+ this.name = "AfterpackFilesError";
35
+ this.code = code;
36
+ this.summary = summary;
37
+ this.fix = fix;
38
+ }
39
+ };
40
+ function realPath(path) {
41
+ const resolved = resolve(path);
42
+ try {
43
+ return realpathSync.native(resolved);
44
+ } catch {
45
+ const parent = dirname(resolved);
46
+ return parent === resolved ? resolved : join(realPath(parent), basename(resolved));
47
+ }
48
+ }
49
+ function isWithinDir(dir, path) {
50
+ const rel = relative(dir, path);
51
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
52
+ }
53
+ function markerIn(dir, markers) {
54
+ return markers.find((name) => existsSync(join(dir, name))) ?? null;
55
+ }
56
+ function nearestMarker(start, markers) {
57
+ for (let current = start;;) {
58
+ const marker = markerIn(current, markers);
59
+ if (marker) return {
60
+ root: current,
61
+ marker
62
+ };
63
+ const parent = dirname(current);
64
+ if (parent === current) return null;
65
+ current = parent;
66
+ }
67
+ }
68
+ function afterpackHome(buildDir, options = {}) {
69
+ const realBuildDir = realPath(buildDir);
70
+ const ownMarker = options.fileTarget ? markerIn(realBuildDir, STRONG_MARKERS) : null;
71
+ if (ownMarker !== null) return {
72
+ dir: join(realBuildDir, AFTERPACK_DIR),
73
+ projectRoot: realBuildDir,
74
+ marker: ownMarker,
75
+ strong: true,
76
+ buildDir: realBuildDir
77
+ };
78
+ const start = dirname(realBuildDir);
79
+ const strong = nearestMarker(start, STRONG_MARKERS);
80
+ const found = strong ?? nearestMarker(start, WEAK_MARKERS);
81
+ const projectRoot = found?.root ?? start;
82
+ const dir = join(projectRoot, AFTERPACK_DIR);
83
+ 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.");
84
+ return {
85
+ dir,
86
+ projectRoot,
87
+ marker: found?.marker ?? null,
88
+ strong: strong !== null,
89
+ buildDir: realBuildDir
90
+ };
91
+ }
92
+ function describeUnanchoredHome(home) {
93
+ if (home.marker !== null) return null;
94
+ return `no lockfile, afterpack.json, .git or package.json above ${home.buildDir}, so AfterPack keeps its files beside it, in ${home.dir}`;
95
+ }
96
+
97
+ //#endregion
12
98
  //#region src/paths.ts
13
99
  const COMBINED_PROTECTION_MAP_NAME = "protectionMap.html";
14
100
  function shortHash(content) {
@@ -40,7 +126,6 @@ function findUpward(startDir, fileName, options = {}) {
40
126
 
41
127
  //#endregion
42
128
  //#region src/artifacts.ts
43
- const AFTERPACK_DIR = ".afterpack";
44
129
  const AFTERPACK_GITIGNORE_CONTENT = "*\n";
45
130
  const PUBLIC_SEGMENTS = new Set([
46
131
  "public",
@@ -66,7 +151,7 @@ function appendSourceMappingURL(code, mapPath) {
66
151
  function writeArtifacts(input) {
67
152
  const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
68
153
  const mode = input.mode ?? "single";
69
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
154
+ const afterpackDir = input.afterpackDir;
70
155
  const logger = input.logger ?? DEFAULT_LOGGER;
71
156
  const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
72
157
  const paths = resolveArtifactPaths(outPath, mode, hash);
@@ -424,7 +509,7 @@ function buildProjectFileTree(files) {
424
509
  }
425
510
  function writeCombinedProtectionMap(input) {
426
511
  const { buildDir, docs, policy } = input;
427
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
512
+ const afterpackDir = input.afterpackDir;
428
513
  const logger = input.logger ?? DEFAULT_LOGGER;
429
514
  if (!policy.protectionMap || docs.length === 0) return null;
430
515
  mkdirSync(afterpackDir, { recursive: true });
@@ -702,7 +787,7 @@ const CONFIG_KEYS = [
702
787
  tier: "free",
703
788
  surface: "engine",
704
789
  item: { kind: "boolean" },
705
- default: "true in development when an input map exists; false in production"
790
+ default: "false; true in development mode when an input map exists"
706
791
  },
707
792
  {
708
793
  path: "sourceMap.sourcesContent",
@@ -711,7 +796,7 @@ const CONFIG_KEYS = [
711
796
  tier: "free",
712
797
  surface: "engine",
713
798
  item: { kind: "boolean" },
714
- default: "true in development; false in production"
799
+ default: "false; true in development mode"
715
800
  },
716
801
  {
717
802
  path: "sourceMap.emitUrl",
@@ -720,7 +805,7 @@ const CONFIG_KEYS = [
720
805
  tier: "free",
721
806
  surface: "build",
722
807
  item: { kind: "boolean" },
723
- default: "true in development; false in production"
808
+ default: "false; true in development mode"
724
809
  },
725
810
  {
726
811
  path: "protectionMap.enabled",
@@ -859,7 +944,7 @@ const CONFIG_KEYS = [
859
944
  kind: "enum",
860
945
  values: BUILD_MODE_VALUES
861
946
  },
862
- default: "detected from the environment"
947
+ default: "production, unless NODE_ENV is development"
863
948
  },
864
949
  {
865
950
  path: "directives.enabled",
@@ -907,15 +992,6 @@ const CONFIG_KEYS = [
907
992
  item: { kind: "boolean" },
908
993
  default: "true"
909
994
  },
910
- {
911
- path: "allowUnobfuscated",
912
- shape: "scalar",
913
- scope: "program",
914
- tier: "free",
915
- surface: "build",
916
- item: { kind: "boolean" },
917
- default: "false"
918
- },
919
995
  {
920
996
  path: "key",
921
997
  shape: "scalar",
@@ -989,8 +1065,8 @@ function unknownKeyMessage(path, surface) {
989
1065
  if (group$1 && group$1.length > 0) {
990
1066
  const list = group$1.map((child) => `\`${child}\``).join(", ");
991
1067
  const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
992
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
993
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1068
+ const canonical$1 = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1069
+ const enabled = canonical$1 ? groupBooleanKey(canonical$1) : void 0;
994
1070
  const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
995
1071
  return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
996
1072
  }
@@ -1269,7 +1345,6 @@ function toPluginOptions(config) {
1269
1345
  backup: read("build.backup"),
1270
1346
  mode: read("build.mode")
1271
1347
  }),
1272
- allowUnobfuscated: read("allowUnobfuscated"),
1273
1348
  telemetry: set({ enabled: read("telemetry.enabled") })
1274
1349
  },
1275
1350
  seed: read("seed"),
@@ -1325,6 +1400,15 @@ function decodeDataUri(url) {
1325
1400
  return null;
1326
1401
  }
1327
1402
  }
1403
+ function localSourceMapPath(jsPath, url) {
1404
+ if (url.startsWith("data:") || isRemoteSourceMappingURL(url)) return null;
1405
+ const path = url.replace(/[?#].*$/, "");
1406
+ try {
1407
+ return isAbsolute(path) ? path : resolve(dirname(jsPath), decodeURIComponent(path));
1408
+ } catch {
1409
+ return null;
1410
+ }
1411
+ }
1328
1412
  function discoverInputSourceMap(jsPath, code) {
1329
1413
  const adjacent = `${jsPath}.map`;
1330
1414
  if (existsSync(adjacent)) try {
@@ -1339,20 +1423,81 @@ function discoverInputSourceMap(jsPath, code) {
1339
1423
  const url = extractSourceMappingURL(source);
1340
1424
  if (url == null) return null;
1341
1425
  if (url.startsWith("data:")) return decodeDataUri(url);
1342
- if (isRemoteSourceMappingURL(url)) return null;
1343
- let mapPath;
1426
+ const mapPath = localSourceMapPath(jsPath, url);
1427
+ if (mapPath == null || !existsSync(mapPath)) return null;
1344
1428
  try {
1345
- mapPath = isAbsolute(url) ? url : resolve(dirname(jsPath), decodeURIComponent(url));
1429
+ return readFileSync(mapPath, "utf8");
1346
1430
  } catch {
1347
1431
  return null;
1348
1432
  }
1349
- if (!existsSync(mapPath)) return null;
1433
+ }
1434
+ function bundlerSourceMapPaths(jsPath, code, root) {
1435
+ const candidates = [`${jsPath}.map`];
1436
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) {
1437
+ const url = match[1];
1438
+ const local = localSourceMapPath(jsPath, url);
1439
+ if (local != null) candidates.push(local);
1440
+ if (url.startsWith("/") && !url.startsWith("//")) try {
1441
+ candidates.push(resolve(root, `.${decodeURIComponent(url.replace(/[?#].*$/, ""))}`));
1442
+ } catch {}
1443
+ }
1444
+ return containedSourceMaps(candidates, root);
1445
+ }
1446
+ function realpathOrNull(path) {
1350
1447
  try {
1351
- return readFileSync(mapPath, "utf8");
1448
+ return realpathSync(path);
1352
1449
  } catch {
1353
1450
  return null;
1354
1451
  }
1355
1452
  }
1453
+ function withinRealDir(dir, root) {
1454
+ const rootReal = realpathOrNull(root);
1455
+ const real = realpathOrNull(dir);
1456
+ if (rootReal == null || real == null) return false;
1457
+ if (real === rootReal) return true;
1458
+ return real.startsWith(rootReal.endsWith(sep) ? rootReal : `${rootReal}${sep}`);
1459
+ }
1460
+ function containedSourceMaps(paths, root) {
1461
+ const found = new Set();
1462
+ for (const path of paths) {
1463
+ if (!path.endsWith(".map")) continue;
1464
+ const lexical = resolve(path);
1465
+ if (!withinRealDir(dirname(lexical), root)) continue;
1466
+ try {
1467
+ const stat = lstatSync(lexical);
1468
+ if (stat.isFile() || stat.isSymbolicLink()) found.add(lexical);
1469
+ } catch {}
1470
+ }
1471
+ return [...found];
1472
+ }
1473
+ function removeSourceMaps(paths, label) {
1474
+ let removed = 0;
1475
+ for (const path of paths) try {
1476
+ unlinkSync(path);
1477
+ removed++;
1478
+ } catch (error) {
1479
+ if (error.code === "ENOENT") continue;
1480
+ throw new Error(`[${label}] could not remove the source map ${path}, refusing to ship it: ${error}`);
1481
+ }
1482
+ return removed;
1483
+ }
1484
+ function stripCssSourceMappingURLs(paths) {
1485
+ let stripped = 0;
1486
+ for (const path of paths) {
1487
+ let css;
1488
+ try {
1489
+ css = readFileSync(path, "utf8");
1490
+ } catch (error) {
1491
+ if (error.code === "ENOENT") continue;
1492
+ throw error;
1493
+ }
1494
+ const without = withoutCssSourceMappingURL(css);
1495
+ if (without === css) continue;
1496
+ writeFileSync(path, without);
1497
+ stripped++;
1498
+ }
1499
+ return stripped;
1500
+ }
1356
1501
 
1357
1502
  //#endregion
1358
1503
  //#region src/bundle.ts
@@ -1384,6 +1529,39 @@ function sourceTypeForBundle(format, entries) {
1384
1529
  for (const entry of entries) if (entry.type !== "chunk") return void 0;
1385
1530
  return sourceTypeForOutputFormat(format);
1386
1531
  }
1532
+ const COMPRESSED_SIBLING = /\.(gz|br|zst|zz|deflate)$/;
1533
+ function entryBytes(entry) {
1534
+ if (entry.type === "chunk") return entry.code === void 0 ? null : Buffer.from(entry.code);
1535
+ if (typeof entry.source === "string") return Buffer.from(entry.source);
1536
+ if (entry.source !== void 0) return Buffer.from(entry.source);
1537
+ return null;
1538
+ }
1539
+ function regenerateCompressedSiblings(bundle, obfuscated, label) {
1540
+ for (const [name, entry] of Object.entries(bundle)) {
1541
+ const match = COMPRESSED_SIBLING.exec(name);
1542
+ if (match === null) continue;
1543
+ const base = name.slice(0, -match[0].length);
1544
+ if (!obfuscated.has(base)) continue;
1545
+ const bytes = entryBytes(bundle[base]);
1546
+ if (bytes === null) continue;
1547
+ if (match[1] === "gz") entry.source = gzipSync(bytes);
1548
+ else if (match[1] === "br") entry.source = brotliCompressSync(bytes);
1549
+ 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.`);
1550
+ }
1551
+ }
1552
+ const SRI_PLUGIN_NAME = /subresource|integrity|(?:^|[^a-z])sri(?:[^a-z]|$)/i;
1553
+ function sriPluginRefusal(plugins, label) {
1554
+ const found = (plugins ?? []).find((plugin) => SRI_PLUGIN_NAME.test(plugin?.name ?? ""));
1555
+ if (!found) return null;
1556
+ 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.`;
1557
+ }
1558
+ function unsaltedAssetsWarning(entries, salted) {
1559
+ const fileNames = [];
1560
+ for (const entry of entries.values()) if (entry.type !== "chunk" && !salted.has(entry.fileName)) fileNames.push(entry.fileName);
1561
+ fileNames.sort();
1562
+ if (fileNames.length === 0) return null;
1563
+ 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.`;
1564
+ }
1387
1565
  function dataUri(json) {
1388
1566
  return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
1389
1567
  }
@@ -1512,7 +1690,7 @@ function collectJsFiles(target, options = {}) {
1512
1690
  if (!stat.isDirectory()) return isCollectableJs(basename(target)) ? [target] : [];
1513
1691
  return walkJs(target, options.include ?? [], false, options.onNestedProject);
1514
1692
  }
1515
- function entriesOf(dir) {
1693
+ function entriesOf$1(dir) {
1516
1694
  try {
1517
1695
  return readdirSync(dir, { withFileTypes: true });
1518
1696
  } catch {
@@ -1531,12 +1709,13 @@ function isNestedProject(dir) {
1531
1709
  }
1532
1710
  function walkJs(dir, include, readmitted, onNestedProject) {
1533
1711
  const out = [];
1534
- for (const entry of entriesOf(dir)) {
1712
+ for (const entry of entriesOf$1(dir)) {
1535
1713
  const name = entry.name;
1536
1714
  const full = join(dir, name);
1537
1715
  const kind = kindOf(entry, full);
1538
1716
  if (kind === null) continue;
1539
1717
  if (kind === "dir") {
1718
+ if (name === AFTERPACK_DIR) continue;
1540
1719
  const skipped = name === NODE_MODULES;
1541
1720
  if (!skipped && !readmitted && isNestedProject(full)) {
1542
1721
  onNestedProject?.(full);
@@ -1555,13 +1734,15 @@ const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
1555
1734
  function collectFiles(dir, accept) {
1556
1735
  if (!existsSync(dir)) return [];
1557
1736
  const out = [];
1558
- for (const entry of entriesOf(dir)) {
1737
+ for (const entry of entriesOf$1(dir)) {
1559
1738
  const name = entry.name;
1560
1739
  const full = join(dir, name);
1561
1740
  const kind = kindOf(entry, full);
1562
1741
  if (kind === null) continue;
1563
- if (kind === "dir") out.push(...collectFiles(full, accept));
1564
- else if (accept(name)) out.push(full);
1742
+ if (kind === "dir") {
1743
+ if (name === NODE_MODULES || name === AFTERPACK_DIR || isNestedProject(full)) continue;
1744
+ out.push(...collectFiles(full, accept));
1745
+ } else if (accept(name)) out.push(full);
1565
1746
  }
1566
1747
  return out;
1567
1748
  }
@@ -2068,10 +2249,10 @@ function spaceFormIssue(path, raw, surface) {
2068
2249
  }
2069
2250
  function kebabIssue(key, surface) {
2070
2251
  const suggestion = suggestKey(key);
2071
- const canonical = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2252
+ const canonical$1 = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2072
2253
  return {
2073
2254
  path: key,
2074
- message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical}`
2255
+ message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical$1}`
2075
2256
  };
2076
2257
  }
2077
2258
  function parseAssignment(key, raw, surface) {
@@ -2410,7 +2591,7 @@ function reportDiagnostics(input) {
2410
2591
  //#region src/policy.ts
2411
2592
  function detectProduction(env = {}, opts = {}) {
2412
2593
  if (opts.build?.mode !== void 0) return opts.build.mode === "production";
2413
- return env.NODE_ENV === "production" || env.CI === "true";
2594
+ return env.NODE_ENV !== "development";
2414
2595
  }
2415
2596
  function resolveReportPolicy(env = {}, userOpts = {}, signals = {}) {
2416
2597
  const isProduction = detectProduction(env, userOpts);
@@ -2977,123 +3158,883 @@ function captureDirectiveRegions(inputs, handAuthored, enabled = true) {
2977
3158
  }
2978
3159
 
2979
3160
  //#endregion
2980
- //#region src/git.ts
2981
- const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
2982
- const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
2983
- function sanitizeCommitSha(value) {
2984
- if (typeof value !== "string") return null;
2985
- const sha = value.trim().toLowerCase();
2986
- return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
2987
- }
2988
- function sanitizeGitRef(value) {
2989
- if (typeof value !== "string") return null;
2990
- const ref = value.trim();
2991
- return GIT_REF_PATTERN.test(ref) ? ref : null;
2992
- }
2993
- function contextFrom(rawSha, rawRef) {
2994
- const commitSha = sanitizeCommitSha(rawSha);
2995
- const ref = sanitizeGitRef(rawRef);
2996
- if (commitSha === null && ref === null) return null;
2997
- const context = {};
2998
- if (commitSha !== null) context.commitSha = commitSha;
2999
- if (ref !== null) context.ref = ref;
3000
- return context;
3001
- }
3002
- const CI_SOURCES = [
3003
- ["GITHUB_SHA", "GITHUB_REF_NAME"],
3004
- ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
3005
- ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
3006
- ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
3007
- ["GIT_COMMIT", "BRANCH_NAME"]
3008
- ];
3009
- function ciGitContext(env) {
3010
- for (const [shaVar, refVar] of CI_SOURCES) {
3011
- const context = contextFrom(env[shaVar], env[refVar]);
3012
- if (context !== null) return context;
3013
- }
3014
- return null;
3161
+ //#region src/seed.ts
3162
+ function randomSeed() {
3163
+ const b = randomBytes(8);
3164
+ const hi = b.readUInt32BE(0) & 2097151;
3165
+ const lo = b.readUInt32BE(4);
3166
+ return hi * 4294967296 + lo;
3015
3167
  }
3016
- const GIT_PROBE_TIMEOUT_MS = 2e3;
3017
- function localGitContext(cwd) {
3018
- let lines;
3168
+ function gitHead() {
3019
3169
  try {
3020
- const out = execFileSync("git", [
3021
- "rev-parse",
3022
- "HEAD",
3023
- "--abbrev-ref",
3024
- "HEAD"
3025
- ], {
3026
- cwd,
3027
- stdio: [
3028
- "ignore",
3029
- "pipe",
3030
- "ignore"
3031
- ],
3032
- timeout: GIT_PROBE_TIMEOUT_MS,
3033
- maxBuffer: 64 * 1024
3034
- }).toString();
3035
- lines = out.split("\n").map((line) => line.trim());
3170
+ const out = execFileSync("git", ["rev-parse", "HEAD"], { stdio: [
3171
+ "ignore",
3172
+ "pipe",
3173
+ "ignore"
3174
+ ] }).toString().trim();
3175
+ return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3036
3176
  } catch {
3037
3177
  return null;
3038
3178
  }
3039
- const ref = lines[1] === "HEAD" ? null : lines[1];
3040
- return contextFrom(lines[0], ref);
3041
3179
  }
3042
- function detectGitContext(explicit, deps = {}) {
3043
- if (explicit) {
3044
- const declared = contextFrom(explicit.commitSha, explicit.ref);
3045
- if (declared !== null) return declared;
3180
+ const SEED_ENV_VAR = "AFTERPACK_SEED";
3181
+ function parseSeedValue(raw) {
3182
+ return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3183
+ }
3184
+ const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3185
+ function sharedSeedState() {
3186
+ const holder = globalThis;
3187
+ holder[SEED_STATE] ??= {
3188
+ sessions: new Map(),
3189
+ ownEnvExports: []
3190
+ };
3191
+ return holder[SEED_STATE];
3192
+ }
3193
+ const { sessions, ownEnvExports } = sharedSeedState();
3194
+ function isOwnEnvExport(env, value) {
3195
+ return ownEnvExports.some((e) => e.env === env && e.value === value);
3196
+ }
3197
+ function openGeneration(root, leg) {
3198
+ let session = sessions.get(root);
3199
+ if (!session) {
3200
+ session = {
3201
+ seed: void 0,
3202
+ generation: 1,
3203
+ legs: [],
3204
+ resolvedByLeg: new Map(),
3205
+ gitFallbackWarned: false
3206
+ };
3207
+ sessions.set(root, session);
3208
+ } else if (session.legs.includes(leg)) {
3209
+ session.seed = void 0;
3210
+ session.generation += 1;
3211
+ session.legs = [];
3212
+ session.resolvedByLeg.clear();
3213
+ session.gitFallbackWarned = false;
3046
3214
  }
3047
- const ci = ciGitContext(deps.env ?? process.env);
3048
- if (ci !== null) return ci;
3049
- return (deps.localGit ?? localGitContext)(deps.cwd);
3215
+ session.legs.push(leg);
3216
+ return session;
3050
3217
  }
3051
-
3052
- //#endregion
3053
- //#region src/map-color.ts
3054
- const UTF8 = new TextEncoder();
3055
- const utf8Len = (s) => UTF8.encode(s).length;
3056
- const NON_ASCII = /[\u0080-\uFFFF]/;
3057
- const HIGH_SURROGATE_START = 55296;
3058
- const HIGH_SURROGATE_END = 56319;
3059
- const LOW_SURROGATE_START = 56320;
3060
- const LOW_SURROGATE_END = 57343;
3061
- function charToByteTable(line) {
3062
- const table = new Array(line.length + 1);
3063
- let bytes = 0;
3064
- let i = 0;
3065
- while (i < line.length) {
3066
- table[i] = bytes;
3067
- const code = line.charCodeAt(i);
3068
- if (code < 128) {
3069
- bytes += 1;
3070
- i += 1;
3071
- continue;
3072
- }
3073
- if (code < 2048) {
3074
- bytes += 2;
3075
- i += 1;
3076
- continue;
3077
- }
3078
- if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
3079
- const low = line.charCodeAt(i + 1);
3080
- if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
3081
- table[i + 1] = bytes + 3;
3082
- bytes += 4;
3083
- i += 2;
3084
- continue;
3085
- }
3218
+ function resolveWithinSession(input, session, env, deps) {
3219
+ if (typeof input === "number") return {
3220
+ seed: input,
3221
+ origin: "option"
3222
+ };
3223
+ if (typeof input === "string" && input !== "git") return {
3224
+ seed: input,
3225
+ origin: "option"
3226
+ };
3227
+ if (input === "git") {
3228
+ const head = (deps.gitHead ?? gitHead)();
3229
+ if (head) return {
3230
+ seed: head,
3231
+ origin: "git"
3232
+ };
3233
+ if (!session.gitFallbackWarned) {
3234
+ session.gitFallbackWarned = true;
3235
+ (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
3086
3236
  }
3087
- bytes += 3;
3088
- i += 1;
3089
3237
  }
3090
- table[line.length] = bytes;
3091
- return table;
3238
+ const fromEnv = env[SEED_ENV_VAR];
3239
+ if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3240
+ seed: parseSeedValue(fromEnv),
3241
+ origin: "env"
3242
+ };
3243
+ if (session.seed !== void 0) return {
3244
+ seed: session.seed,
3245
+ origin: "session"
3246
+ };
3247
+ return {
3248
+ seed: (deps.randomSeed ?? randomSeed)(),
3249
+ origin: "fresh"
3250
+ };
3092
3251
  }
3093
- var ChunkByteIndex = class {
3094
- starts;
3095
- ascii;
3096
- tables;
3252
+ function resolveBuildSeed(input, scope, deps = {}) {
3253
+ const env = deps.env ?? process.env;
3254
+ const session = openGeneration(scope.root, scope.leg);
3255
+ const { seed, origin } = resolveWithinSession(input, session, env, deps);
3256
+ if (origin === "env" || origin === "fresh") session.seed = seed;
3257
+ if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3258
+ const value = String(seed);
3259
+ env[SEED_ENV_VAR] = value;
3260
+ const stale = ownEnvExports.findIndex((e) => e.env === env);
3261
+ if (stale >= 0) ownEnvExports.splice(stale, 1);
3262
+ ownEnvExports.push({
3263
+ env,
3264
+ value
3265
+ });
3266
+ }
3267
+ const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3268
+ session.resolvedByLeg.set(scope.leg, seed);
3269
+ return {
3270
+ seed,
3271
+ origin,
3272
+ legs: [...session.legs],
3273
+ generation: session.generation,
3274
+ mismatch: prior && session.generation === 1 ? {
3275
+ leg: prior[0],
3276
+ seed: prior[1]
3277
+ } : null
3278
+ };
3279
+ }
3280
+
3281
+ //#endregion
3282
+ //#region src/telemetry.ts
3283
+ const API_URL_ENV_VAR$1 = "AFTERPACK_API_URL";
3284
+ const DEFAULT_API_URL = "https://api.afterpack.dev";
3285
+ const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3286
+ const TELEMETRY_PAYLOAD_VERSION = 1;
3287
+ const TELEMETRY_TIMEOUT_MS = 1500;
3288
+ const INSTALL_ID_ROTATION_DAYS = 30;
3289
+ const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3290
+ const TELEMETRY_STATE_FILE = join(homedir(), ".afterpack", "telemetry.json");
3291
+ const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3292
+ const DATA_FIELD_WHITELIST = {
3293
+ outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3294
+ parseError: ["parserErrorKind"],
3295
+ engineBug: [
3296
+ "phase",
3297
+ "transform",
3298
+ "nodeKind"
3299
+ ],
3300
+ inflationBudget: [
3301
+ "target",
3302
+ "achieved",
3303
+ "budgetRatio",
3304
+ "inflationRatio"
3305
+ ],
3306
+ configParse: [
3307
+ "category",
3308
+ "line",
3309
+ "column"
3310
+ ]
3311
+ };
3312
+ function resolveTelemetryEnabled(option, env = {}) {
3313
+ if (option !== void 0) return option;
3314
+ return !(env.NODE_ENV === "test" || env.VITEST);
3315
+ }
3316
+ const FRAMEWORK_ENTRIES = [
3317
+ {
3318
+ label: "afterpack",
3319
+ name: "cli"
3320
+ },
3321
+ {
3322
+ label: "afterpack-angular",
3323
+ name: "angular",
3324
+ pkg: "@angular/core"
3325
+ },
3326
+ {
3327
+ label: "afterpack-esbuild",
3328
+ name: "esbuild",
3329
+ pkg: "esbuild"
3330
+ },
3331
+ {
3332
+ label: "afterpack-next",
3333
+ name: "next",
3334
+ pkg: "next"
3335
+ },
3336
+ {
3337
+ label: "afterpack-rollup",
3338
+ name: "rollup",
3339
+ pkg: "rollup"
3340
+ },
3341
+ {
3342
+ label: "afterpack-vite",
3343
+ name: "vite",
3344
+ pkg: "vite"
3345
+ },
3346
+ {
3347
+ label: "afterpack-webpack",
3348
+ name: "webpack",
3349
+ pkg: "webpack"
3350
+ }
3351
+ ];
3352
+ const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3353
+ const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3354
+ function frameworkFromLabel(label) {
3355
+ return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
3356
+ }
3357
+ const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3358
+ function detectFrameworkVersion(projectRoot, framework) {
3359
+ const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3360
+ if (!pkgName) return null;
3361
+ let deps;
3362
+ try {
3363
+ const pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
3364
+ deps = {
3365
+ ...pkg.dependencies,
3366
+ ...pkg.devDependencies
3367
+ };
3368
+ } catch {
3369
+ return null;
3370
+ }
3371
+ const raw = deps[pkgName];
3372
+ if (typeof raw !== "string") return null;
3373
+ const range = raw.trim();
3374
+ return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3375
+ }
3376
+ function complexityLabel(preset, complexity) {
3377
+ if (preset !== void 0) return preset;
3378
+ return complexity === void 0 ? "default" : "custom";
3379
+ }
3380
+ const FILE_COUNT_BUCKETS = [
3381
+ 1,
3382
+ 5,
3383
+ 20,
3384
+ 100,
3385
+ 500,
3386
+ 2e3
3387
+ ];
3388
+ function fileCountBucket(count) {
3389
+ if (!Number.isFinite(count) || count <= 0) return "0";
3390
+ let lower = 1;
3391
+ for (const upper of FILE_COUNT_BUCKETS) {
3392
+ if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3393
+ lower = upper + 1;
3394
+ }
3395
+ return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3396
+ }
3397
+ const DURATION_BUCKETS_MS = [
3398
+ [1e3, "<1s"],
3399
+ [5e3, "1-5s"],
3400
+ [15e3, "5-15s"],
3401
+ [6e4, "15-60s"],
3402
+ [3e5, "60-300s"]
3403
+ ];
3404
+ function durationBucket(ms) {
3405
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
3406
+ for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3407
+ return "300s+";
3408
+ }
3409
+ function safeScalar(value) {
3410
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3411
+ if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3412
+ return null;
3413
+ }
3414
+ function telemetrySafeData(data) {
3415
+ if (!data || typeof data.kind !== "string") return null;
3416
+ const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3417
+ if (kind === null) return null;
3418
+ const out = { kind };
3419
+ for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3420
+ const value = safeScalar(data[field]);
3421
+ if (value !== null) out[field] = value;
3422
+ }
3423
+ return out;
3424
+ }
3425
+ function telemetrySafeSpan(d) {
3426
+ const span = d.span;
3427
+ if (!span) return null;
3428
+ const start = safeScalar(span.startByte);
3429
+ const end = safeScalar(span.endByte);
3430
+ if (typeof start !== "number" || typeof end !== "number") return null;
3431
+ if (start < 0 || end < 0) return null;
3432
+ return {
3433
+ startByte: start,
3434
+ endByte: end
3435
+ };
3436
+ }
3437
+ function telemetrySafeDiagnostic(d, severity) {
3438
+ return {
3439
+ code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3440
+ severity,
3441
+ span: telemetrySafeSpan(d),
3442
+ data: telemetrySafeData(d.data)
3443
+ };
3444
+ }
3445
+ function buildTelemetryPayload(facts, ctx) {
3446
+ let errorCount = 0;
3447
+ let criticalCount = 0;
3448
+ const alerting = [];
3449
+ for (const d of facts.diagnostics) {
3450
+ if (d.severity !== "error" && d.severity !== "critical") continue;
3451
+ if (d.severity === "critical") criticalCount += 1;
3452
+ else errorCount += 1;
3453
+ alerting.push(telemetrySafeDiagnostic(d, d.severity));
3454
+ }
3455
+ if (alerting.length === 0) return null;
3456
+ const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3457
+ const env = ctx.env ?? {};
3458
+ const runtime = ctx.runtime ?? {
3459
+ node: process.versions.node,
3460
+ platform: process.platform,
3461
+ arch: process.arch
3462
+ };
3463
+ const framework = frameworkFromLabel(facts.label);
3464
+ return {
3465
+ version: TELEMETRY_PAYLOAD_VERSION,
3466
+ installId: ctx.installId,
3467
+ framework,
3468
+ frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3469
+ engineVersion: safeVersion(facts.engineVersion),
3470
+ clientVersion: safeVersion(facts.clientVersion),
3471
+ nodeVersion: safeVersion(runtime.node) ?? "unknown",
3472
+ os: safeToken(runtime.platform),
3473
+ arch: safeToken(runtime.arch),
3474
+ ci: env.CI === "true",
3475
+ complexity: complexityLabel(facts.preset, facts.complexity),
3476
+ fileCountBucket: fileCountBucket(facts.fileCount),
3477
+ durationBucket: durationBucket(facts.durationMs),
3478
+ diagnostics: kept,
3479
+ errorCount,
3480
+ criticalCount,
3481
+ droppedCount: alerting.length - kept.length
3482
+ };
3483
+ }
3484
+ const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3485
+ function safeVersion(value) {
3486
+ return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3487
+ }
3488
+ function safeToken(value) {
3489
+ return TOKEN_PATTERN.test(value) ? value : "unknown";
3490
+ }
3491
+ const TELEMETRY_NOTICE = [
3492
+ "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3493
+ "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3494
+ "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3495
+ "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3496
+ "AfterPack: file counts and durations, and a random install id that rotates every 30",
3497
+ "AfterPack: days.",
3498
+ "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3499
+ "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3500
+ "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3501
+ "AfterPack: `telemetry: { enabled: false }` in your config.",
3502
+ "AfterPack: https://www.afterpack.dev/privacy"
3503
+ ];
3504
+ const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3505
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3506
+ function readState(file, now) {
3507
+ try {
3508
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
3509
+ if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3510
+ installId: parsed.installId,
3511
+ rotatedAt: parsed.rotatedAt,
3512
+ noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
3513
+ };
3514
+ } catch {}
3515
+ return {
3516
+ installId: randomUUID(),
3517
+ rotatedAt: now,
3518
+ noticeShownAt: 0
3519
+ };
3520
+ }
3521
+ function writeState(file, state) {
3522
+ try {
3523
+ mkdirSync(dirname(file), { recursive: true });
3524
+ writeFileSync(file, `${JSON.stringify(state)}\n`, "utf8");
3525
+ } catch {}
3526
+ }
3527
+ function telemetryUrl(env) {
3528
+ const base = (env[API_URL_ENV_VAR$1] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3529
+ return `${base}${TELEMETRY_ENDPOINT_PATH}`;
3530
+ }
3531
+ const TELEMETRY_BODY_LIMIT = 64 * 1024;
3532
+ async function reportTelemetryNotices(response, logger) {
3533
+ if (!response || response.status !== 202 || typeof response.text !== "function") return;
3534
+ const declared = Number(response.headers?.get?.("content-length"));
3535
+ if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3536
+ await response.body?.cancel().catch(() => {});
3537
+ return;
3538
+ }
3539
+ const text = await response.text();
3540
+ if (text.length > TELEMETRY_BODY_LIMIT) return;
3541
+ let body;
3542
+ try {
3543
+ body = JSON.parse(text);
3544
+ } catch {
3545
+ return;
3546
+ }
3547
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3548
+ reportNotices(body.notices, logger);
3549
+ }
3550
+ function createTelemetryReporter(deps = {}) {
3551
+ const env = deps.env ?? process.env;
3552
+ const logger = deps.logger ?? console;
3553
+ const now = deps.now ?? Date.now;
3554
+ const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3555
+ const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3556
+ return async (facts) => {
3557
+ try {
3558
+ const at = now();
3559
+ const state = readState(stateFile, at);
3560
+ let dirty = false;
3561
+ if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3562
+ state.installId = randomUUID();
3563
+ state.rotatedAt = at;
3564
+ dirty = true;
3565
+ }
3566
+ if (state.noticeShownAt === 0) {
3567
+ for (const line of TELEMETRY_NOTICE) logger.log(line);
3568
+ state.noticeShownAt = at;
3569
+ dirty = true;
3570
+ }
3571
+ if (dirty) writeState(stateFile, state);
3572
+ if (facts === null) return;
3573
+ const payload = buildTelemetryPayload(facts, {
3574
+ installId: state.installId,
3575
+ env
3576
+ });
3577
+ if (payload === null) return;
3578
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3579
+ if (typeof fetchImpl !== "function") return;
3580
+ const response = await fetchImpl(telemetryUrl(env), {
3581
+ method: "POST",
3582
+ headers: { "content-type": "application/json" },
3583
+ body: JSON.stringify(payload),
3584
+ signal: AbortSignal.timeout(timeoutMs)
3585
+ });
3586
+ await reportTelemetryNotices(response, logger);
3587
+ } catch {}
3588
+ };
3589
+ }
3590
+
3591
+ //#endregion
3592
+ //#region src/hash-salt.ts
3593
+ const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3594
+ const VERSION_ENDPOINT_PATH = "/v1/version";
3595
+ const VERSION_PROBE_TIMEOUT_MS = 2e3;
3596
+ function canonical(value) {
3597
+ if (Array.isArray(value)) return value.map(canonical);
3598
+ if (value === null || typeof value !== "object") return value;
3599
+ const out = {};
3600
+ for (const key of Object.keys(value).sort()) {
3601
+ const item = value[key];
3602
+ if (item !== void 0) out[key] = canonical(item);
3603
+ }
3604
+ return out;
3605
+ }
3606
+ function afterpackHashSalt(input) {
3607
+ const payload = JSON.stringify(canonical({
3608
+ salt: "afterpack-output-name/1",
3609
+ seed: String(input.seed),
3610
+ engineVersion: input.engine.engineVersion,
3611
+ nonce: input.engine.nonce,
3612
+ cloud: input.engine.cloud,
3613
+ settings: input.settings
3614
+ }));
3615
+ return createHash("sha256").update(payload).digest("hex").slice(0, 32);
3616
+ }
3617
+ function isCloudBuild(env) {
3618
+ const key = env.AFTERPACK_KEY;
3619
+ return typeof key === "string" && key.trim() !== "";
3620
+ }
3621
+ function versionEndpoint(env) {
3622
+ const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3623
+ return `${base}${VERSION_ENDPOINT_PATH}`;
3624
+ }
3625
+ async function resolveSaltEngine(env, localEngineVersion, deps = {}) {
3626
+ if (!isCloudBuild(env)) return {
3627
+ engineVersion: localEngineVersion,
3628
+ nonce: null,
3629
+ cloud: false,
3630
+ probedCloudVersion: null,
3631
+ probeFailed: false
3632
+ };
3633
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3634
+ let probed = null;
3635
+ if (typeof fetchImpl === "function") try {
3636
+ const response = await fetchImpl(versionEndpoint(env), { signal: AbortSignal.timeout(deps.timeoutMs ?? VERSION_PROBE_TIMEOUT_MS) });
3637
+ if (response.ok) {
3638
+ const body = await response.json();
3639
+ if (typeof body.engineVersion === "string" && body.engineVersion !== "") probed = body.engineVersion;
3640
+ }
3641
+ } catch {
3642
+ probed = null;
3643
+ }
3644
+ if (probed === null) return {
3645
+ engineVersion: null,
3646
+ nonce: randomUUID(),
3647
+ cloud: true,
3648
+ probedCloudVersion: null,
3649
+ probeFailed: true
3650
+ };
3651
+ return {
3652
+ engineVersion: probed,
3653
+ nonce: null,
3654
+ cloud: true,
3655
+ probedCloudVersion: probed,
3656
+ probeFailed: false
3657
+ };
3658
+ }
3659
+ 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.";
3660
+ function saltSettings(settings, extra = {}) {
3661
+ const { seed: _seed, diagnostics: _diagnostics, artifactOptions, engineConfig,...rest } = settings;
3662
+ const { git: _git, telemetry: _telemetry,...output } = artifactOptions ?? {};
3663
+ const { seed: _engineSeed,...engine } = engineConfig ?? {};
3664
+ return {
3665
+ ...rest,
3666
+ engineConfig: engine,
3667
+ artifactOptions: output,
3668
+ ...extra
3669
+ };
3670
+ }
3671
+ function reportPolicySaltBits(env, artifactOptions, hasBundlerSourcemap) {
3672
+ const policy = resolveReportPolicy(env, artifactOptions ?? {}, { hasBundlerSourcemap });
3673
+ return {
3674
+ sourceMap: policy.sourceMap,
3675
+ emitSourceMappingURL: policy.emitSourceMappingURL
3676
+ };
3677
+ }
3678
+ async function prepareHashSalt(input) {
3679
+ const env = input.env ?? process.env;
3680
+ const resolvedSeed = resolveBuildSeed(input.seed, {
3681
+ root: input.root,
3682
+ leg: input.leg
3683
+ }, {
3684
+ env,
3685
+ warn: input.warn
3686
+ });
3687
+ const engine = await resolveSaltEngine(env, input.localEngineVersion, { fetchImpl: input.fetchImpl });
3688
+ if (engine.probeFailed) input.warn?.(PROBE_FAILED_WARNING);
3689
+ return {
3690
+ resolvedSeed,
3691
+ engine,
3692
+ salt: afterpackHashSalt({
3693
+ seed: resolvedSeed.seed,
3694
+ engine,
3695
+ settings: input.settings
3696
+ })
3697
+ };
3698
+ }
3699
+ async function readEngineVersion(engine) {
3700
+ try {
3701
+ return await engine.version?.() ?? null;
3702
+ } catch {
3703
+ return null;
3704
+ }
3705
+ }
3706
+ function cloudEngineMismatch(engine, batchEngineVersion) {
3707
+ if (!engine.cloud || engine.probedCloudVersion === null) return null;
3708
+ if (batchEngineVersion === null) return null;
3709
+ if (batchEngineVersion === engine.probedCloudVersion) return null;
3710
+ 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.`;
3711
+ }
3712
+
3713
+ //#endregion
3714
+ //#region src/git.ts
3715
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
3716
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
3717
+ function sanitizeCommitSha(value) {
3718
+ if (typeof value !== "string") return null;
3719
+ const sha = value.trim().toLowerCase();
3720
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
3721
+ }
3722
+ function sanitizeGitRef(value) {
3723
+ if (typeof value !== "string") return null;
3724
+ const ref = value.trim();
3725
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
3726
+ }
3727
+ function contextFrom(rawSha, rawRef) {
3728
+ const commitSha = sanitizeCommitSha(rawSha);
3729
+ const ref = sanitizeGitRef(rawRef);
3730
+ if (commitSha === null && ref === null) return null;
3731
+ const context = {};
3732
+ if (commitSha !== null) context.commitSha = commitSha;
3733
+ if (ref !== null) context.ref = ref;
3734
+ return context;
3735
+ }
3736
+ const CI_SOURCES = [
3737
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
3738
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
3739
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
3740
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
3741
+ ["GIT_COMMIT", "BRANCH_NAME"]
3742
+ ];
3743
+ function ciGitContext(env) {
3744
+ for (const [shaVar, refVar] of CI_SOURCES) {
3745
+ const context = contextFrom(env[shaVar], env[refVar]);
3746
+ if (context !== null) return context;
3747
+ }
3748
+ return null;
3749
+ }
3750
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
3751
+ function localGitContext(cwd) {
3752
+ let lines;
3753
+ try {
3754
+ const out = execFileSync("git", [
3755
+ "rev-parse",
3756
+ "HEAD",
3757
+ "--abbrev-ref",
3758
+ "HEAD"
3759
+ ], {
3760
+ cwd,
3761
+ stdio: [
3762
+ "ignore",
3763
+ "pipe",
3764
+ "ignore"
3765
+ ],
3766
+ timeout: GIT_PROBE_TIMEOUT_MS,
3767
+ maxBuffer: 64 * 1024
3768
+ }).toString();
3769
+ lines = out.split("\n").map((line) => line.trim());
3770
+ } catch {
3771
+ return null;
3772
+ }
3773
+ const ref = lines[1] === "HEAD" ? null : lines[1];
3774
+ return contextFrom(lines[0], ref);
3775
+ }
3776
+ function detectGitContext(explicit, deps = {}) {
3777
+ if (explicit) {
3778
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
3779
+ if (declared !== null) return declared;
3780
+ }
3781
+ const ci = ciGitContext(deps.env ?? process.env);
3782
+ if (ci !== null) return ci;
3783
+ return (deps.localGit ?? localGitContext)(deps.cwd);
3784
+ }
3785
+
3786
+ //#endregion
3787
+ //#region src/hashed-names.ts
3788
+ const LOWER_HEX = "0123456789abcdef";
3789
+ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
3790
+ const UPPER_ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3791
+ const LOWER_ALNUM = "0123456789abcdefghijklmnopqrstuvwxyz";
3792
+ const ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
3793
+ const MIN_TOKEN_LENGTH = 6;
3794
+ const BINARY_EXTENSIONS = new Set([
3795
+ ".png",
3796
+ ".jpg",
3797
+ ".jpeg",
3798
+ ".gif",
3799
+ ".webp",
3800
+ ".avif",
3801
+ ".ico",
3802
+ ".bmp",
3803
+ ".woff",
3804
+ ".woff2",
3805
+ ".ttf",
3806
+ ".otf",
3807
+ ".eot",
3808
+ ".wasm",
3809
+ ".gz",
3810
+ ".br",
3811
+ ".zst",
3812
+ ".zip",
3813
+ ".pdf",
3814
+ ".mp3",
3815
+ ".mp4",
3816
+ ".webm",
3817
+ ".ogg",
3818
+ ".wav",
3819
+ ".pack"
3820
+ ]);
3821
+ function alphabetOf(token) {
3822
+ if (/^[0-9a-f]+$/.test(token)) return LOWER_HEX;
3823
+ if (/^[A-Z2-7]+$/.test(token)) return BASE32;
3824
+ if (/^[0-9A-Z]+$/.test(token)) return UPPER_ALNUM;
3825
+ if (/^[0-9a-z~._-]+$/.test(token)) return LOWER_ALNUM;
3826
+ return ALNUM;
3827
+ }
3828
+ function regionsKey(regions) {
3829
+ return regions && regions.length > 0 ? JSON.stringify(regions) : "";
3830
+ }
3831
+ function deriveHashToken(token, salt, regions = "") {
3832
+ const alphabet = alphabetOf(token);
3833
+ let out = "";
3834
+ for (let round = 0; out.length < token.length; round++) {
3835
+ const bytes = createHash("sha256").update(`${salt}\0${token}\0${regions}\0${round}`).digest();
3836
+ for (const byte of bytes) {
3837
+ if (out.length === token.length) break;
3838
+ out += alphabet[byte % alphabet.length];
3839
+ }
3840
+ }
3841
+ return out;
3842
+ }
3843
+ function escapeRegExp$1(text) {
3844
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3845
+ }
3846
+ function tokenPattern(tokens) {
3847
+ const list = [...tokens].sort((a, b) => b.length - a.length || (a < b ? -1 : 1));
3848
+ if (list.length === 0) return null;
3849
+ return new RegExp(`(?<![A-Za-z0-9])(?:${list.map(escapeRegExp$1).join("|")})(?![A-Za-z0-9])`, "g");
3850
+ }
3851
+ function toPosix$1(path) {
3852
+ return sep === "/" ? path : path.split(sep).join("/");
3853
+ }
3854
+ function readText(path) {
3855
+ let bytes;
3856
+ try {
3857
+ bytes = readFileSync(path);
3858
+ } catch {
3859
+ return null;
3860
+ }
3861
+ if (bytes.subarray(0, 8192).includes(0)) return null;
3862
+ try {
3863
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
3864
+ } catch {
3865
+ return null;
3866
+ }
3867
+ }
3868
+ function listFiles(root, skip) {
3869
+ const out = [];
3870
+ const walk$1 = (dir) => {
3871
+ let entries;
3872
+ try {
3873
+ entries = readdirSync(dir, { withFileTypes: true });
3874
+ } catch {
3875
+ return;
3876
+ }
3877
+ for (const entry of entries) {
3878
+ const full = join(dir, entry.name);
3879
+ const rel = toPosix$1(relative(root, full));
3880
+ if (entry.name === AFTERPACK_DIR || entry.name === "node_modules" || skip(rel)) continue;
3881
+ if (entry.isDirectory()) walk$1(full);
3882
+ else if (entry.isFile()) out.push(full);
3883
+ }
3884
+ };
3885
+ walk$1(root);
3886
+ return out;
3887
+ }
3888
+ function isCandidate(path) {
3889
+ const name = basename(path).toLowerCase();
3890
+ if (name.endsWith(".map")) return false;
3891
+ const dot = name.lastIndexOf(".");
3892
+ return dot < 0 || !BINARY_EXTENSIONS.has(name.slice(dot));
3893
+ }
3894
+ function writableDir(dir) {
3895
+ try {
3896
+ accessSync(dir, constants.W_OK);
3897
+ return true;
3898
+ } catch {
3899
+ return false;
3900
+ }
3901
+ }
3902
+ function planHashedNames(input) {
3903
+ const { root, tokenOf } = input.options;
3904
+ const skip = input.options.skip ?? (() => false);
3905
+ const tokens = new Map();
3906
+ const tokenOfPath = (path) => {
3907
+ const rel = toPosix$1(relative(root, path));
3908
+ if (rel.startsWith("..")) return null;
3909
+ const token = tokenOf(rel);
3910
+ if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
3911
+ return basename(path).includes(token) ? token : null;
3912
+ };
3913
+ const addToken = (token, regions) => {
3914
+ if (tokens.has(token)) return false;
3915
+ tokens.set(token, deriveHashToken(token, input.salt, regionsKey(regions)));
3916
+ return true;
3917
+ };
3918
+ for (const [path, { regions }] of input.inputs) {
3919
+ const token = tokenOfPath(path);
3920
+ if (token !== null) addToken(token, regions);
3921
+ }
3922
+ const others = new Map();
3923
+ if (tokens.size > 0) for (const path of listFiles(root, skip)) {
3924
+ if (input.inputs.has(path) || !isCandidate(path)) continue;
3925
+ const text = readText(path);
3926
+ if (text !== null) others.set(path, text);
3927
+ }
3928
+ const changed = new Set();
3929
+ let grew = tokens.size > 0;
3930
+ while (grew) {
3931
+ grew = false;
3932
+ const pattern$1 = tokenPattern(tokens.keys());
3933
+ if (pattern$1 === null) break;
3934
+ for (const [path, text] of others) {
3935
+ if (changed.has(path)) continue;
3936
+ pattern$1.lastIndex = 0;
3937
+ if (!pattern$1.test(text)) continue;
3938
+ changed.add(path);
3939
+ const token = tokenOfPath(path);
3940
+ if (token !== null && addToken(token)) grew = true;
3941
+ }
3942
+ }
3943
+ const pattern = tokenPattern(tokens.keys());
3944
+ const rewrite = (text) => pattern === null ? text : text.replace(pattern, (token) => tokens.get(token) ?? token);
3945
+ const renamedPath = (path) => {
3946
+ const token = tokenOfPath(path);
3947
+ if (token === null || !tokens.has(token)) return path;
3948
+ const name = basename(path);
3949
+ const at = name.lastIndexOf(token);
3950
+ return join(dirname(path), `${name.slice(0, at)}${tokens.get(token)}${name.slice(at + token.length)}`);
3951
+ };
3952
+ const renamed = new Map();
3953
+ for (const path of input.inputs.keys()) {
3954
+ const next = renamedPath(path);
3955
+ if (next !== path) renamed.set(path, next);
3956
+ }
3957
+ const writes = [];
3958
+ for (const path of changed) {
3959
+ const to = renamedPath(path);
3960
+ if (to !== path) renamed.set(path, to);
3961
+ writes.push({
3962
+ from: path,
3963
+ to,
3964
+ text: rewrite(others.get(path))
3965
+ });
3966
+ }
3967
+ const preflight = () => {
3968
+ const unwritable = new Set();
3969
+ for (const [from, to] of renamed) {
3970
+ if (!writableDir(dirname(from))) unwritable.add(dirname(from));
3971
+ if (!writableDir(dirname(to))) unwritable.add(dirname(to));
3972
+ }
3973
+ for (const write of writes) if (!writableDir(dirname(write.to))) unwritable.add(dirname(write.to));
3974
+ if (unwritable.size > 0) throw new Error(`cannot rename content-hashed files: these directories are not writable: ${[...unwritable].sort().join(", ")}`);
3975
+ };
3976
+ return {
3977
+ tokens,
3978
+ renamed,
3979
+ rewrite,
3980
+ preflight,
3981
+ apply() {
3982
+ preflight();
3983
+ for (const write of writes) {
3984
+ const tmp = `${write.to}.afterpack-tmp`;
3985
+ writeFileSync(tmp, write.text);
3986
+ renameSync(tmp, write.to);
3987
+ if (write.to !== write.from) rmSync(write.from, { force: true });
3988
+ }
3989
+ }
3990
+ };
3991
+ }
3992
+
3993
+ //#endregion
3994
+ //#region src/map-color.ts
3995
+ const UTF8 = new TextEncoder();
3996
+ const utf8Len = (s) => UTF8.encode(s).length;
3997
+ const NON_ASCII = /[\u0080-\uFFFF]/;
3998
+ const HIGH_SURROGATE_START = 55296;
3999
+ const HIGH_SURROGATE_END = 56319;
4000
+ const LOW_SURROGATE_START = 56320;
4001
+ const LOW_SURROGATE_END = 57343;
4002
+ function charToByteTable(line) {
4003
+ const table = new Array(line.length + 1);
4004
+ let bytes = 0;
4005
+ let i = 0;
4006
+ while (i < line.length) {
4007
+ table[i] = bytes;
4008
+ const code = line.charCodeAt(i);
4009
+ if (code < 128) {
4010
+ bytes += 1;
4011
+ i += 1;
4012
+ continue;
4013
+ }
4014
+ if (code < 2048) {
4015
+ bytes += 2;
4016
+ i += 1;
4017
+ continue;
4018
+ }
4019
+ if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
4020
+ const low = line.charCodeAt(i + 1);
4021
+ if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
4022
+ table[i + 1] = bytes + 3;
4023
+ bytes += 4;
4024
+ i += 2;
4025
+ continue;
4026
+ }
4027
+ }
4028
+ bytes += 3;
4029
+ i += 1;
4030
+ }
4031
+ table[line.length] = bytes;
4032
+ return table;
4033
+ }
4034
+ var ChunkByteIndex = class {
4035
+ starts;
4036
+ ascii;
4037
+ tables;
3097
4038
  totalBytes;
3098
4039
  constructor(lines) {
3099
4040
  this.lines = lines;
@@ -3241,21 +4182,109 @@ function coverGenerated(segments$1, start, end, index) {
3241
4182
  if (last && a <= last[1]) last[1] = Math.max(last[1], b);
3242
4183
  else merged.push([a, b]);
3243
4184
  }
3244
- return merged;
4185
+ return merged;
4186
+ }
4187
+
4188
+ //#endregion
4189
+ //#region src/receipt.ts
4190
+ const PROTECTION_RECEIPTS_DIR = "receipts";
4191
+ const STALE_OUTPUT_RECEIPT_FILE = ".afterpack-protection.json";
4192
+ const PROTECTION_RECEIPT_SCHEMA = 1;
4193
+ function sha256OfBytes(bytes) {
4194
+ return createHash("sha256").update(bytes).digest("hex");
4195
+ }
4196
+ function sha256Of(path) {
4197
+ return sha256OfBytes(readFileSync(path));
4198
+ }
4199
+ function receiptPathOf(dir, file) {
4200
+ return relative(dir, file).split(sep).join("/");
4201
+ }
4202
+ const MAX_KEY_BYTES = 180;
4203
+ const HASHED_KEY_PREFIX_BYTES = 120;
4204
+ function buildDirOf(home) {
4205
+ const rel = relative(home.projectRoot, home.buildDir).split(sep).join("/");
4206
+ return rel === "" ? "." : rel;
4207
+ }
4208
+ function receiptKey(buildDir) {
4209
+ const encoded = encodeURIComponent(buildDir).replace(/\*/g, "%2A").replace(/~/g, "%7E");
4210
+ if (Buffer.byteLength(encoded) <= MAX_KEY_BYTES) return encoded;
4211
+ const prefix = encoded.slice(0, HASHED_KEY_PREFIX_BYTES).replace(/%[0-9A-F]?$/, "");
4212
+ const digest = createHash("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4213
+ return `${prefix}~${digest}`;
4214
+ }
4215
+ function receiptsDirOf(home) {
4216
+ return join(home.dir, PROTECTION_RECEIPTS_DIR);
4217
+ }
4218
+ function receiptPathIn(home) {
4219
+ return join(receiptsDirOf(home), `${receiptKey(buildDirOf(home))}.json`);
4220
+ }
4221
+ function homeOf(target) {
4222
+ return typeof target === "string" ? afterpackHome(target) : target;
4223
+ }
4224
+ function protectionReceiptPath(target) {
4225
+ return receiptPathIn(homeOf(target));
4226
+ }
4227
+ function prepareProtectionReceipt(target, label) {
4228
+ const home = homeOf(target);
4229
+ const path = receiptPathIn(home);
4230
+ try {
4231
+ mkdirSync(dirname(path), { recursive: true });
4232
+ ensureAfterpackGitignore(home.dir);
4233
+ const existed = existsSync(path);
4234
+ closeSync(openSync(path, "a"));
4235
+ if (!existed) unlinkSync(path);
4236
+ } catch (error) {
4237
+ throw new AfterpackFilesError(DIAG_RECEIPT_UNWRITABLE, `[${label}] cannot write the protection receipt ${path}, so no file was rewritten: ${error}`, `Make ${dirname(path)} a writable directory, then build again.`);
4238
+ }
4239
+ return path;
4240
+ }
4241
+ function entriesOf(dir) {
4242
+ try {
4243
+ return readdirSync(dir, { withFileTypes: true });
4244
+ } catch {
4245
+ return [];
4246
+ }
3245
4247
  }
3246
-
3247
- //#endregion
3248
- //#region src/receipt.ts
3249
- const PROTECTION_RECEIPT_FILE = ".afterpack-protection.json";
3250
- const PROTECTION_RECEIPT_SCHEMA = 1;
3251
- function sha256OfBytes(bytes) {
3252
- return createHash("sha256").update(bytes).digest("hex");
4248
+ function removeStaleReceipt(path, label) {
4249
+ try {
4250
+ unlinkSync(path);
4251
+ } catch (error) {
4252
+ if (error.code === "ENOENT") return;
4253
+ throw new Error(`[${label}] could not remove the stale protection receipt ${path}, refusing to ship it: ${error}`);
4254
+ }
3253
4255
  }
3254
- function sha256Of(path) {
3255
- return sha256OfBytes(readFileSync(path));
4256
+ function refuseShippedAfterpackDir(path, buildDir, label) {
4257
+ 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.`);
3256
4258
  }
3257
- function receiptPathOf(dir, file) {
3258
- return relative(dir, file).split(sep).join("/");
4259
+ function sweepDir(dir, context, recursive) {
4260
+ for (const entry of entriesOf(dir)) {
4261
+ const full = join(dir, entry.name);
4262
+ if (entry.name === STALE_OUTPUT_RECEIPT_FILE) removeStaleReceipt(full, context.label);
4263
+ else if (entry.isDirectory()) {
4264
+ if (entry.name === AFTERPACK_DIR) {
4265
+ if (context.ownHome !== null && realPath(full) === context.ownHome) continue;
4266
+ refuseShippedAfterpackDir(full, context.buildDir, context.label);
4267
+ }
4268
+ if (!recursive || entry.name === "node_modules") continue;
4269
+ sweepDir(full, context, true);
4270
+ }
4271
+ }
4272
+ }
4273
+ function sweepOutputTree(buildDir, walkedDir, label, ownHome = null) {
4274
+ const context = {
4275
+ buildDir,
4276
+ label,
4277
+ ownHome: ownHome?.strong ? realPath(ownHome.dir) : null
4278
+ };
4279
+ const walksBuildDir = walkedDir !== null && realPath(walkedDir) === realPath(buildDir);
4280
+ sweepDir(buildDir, context, walksBuildDir);
4281
+ if (walkedDir !== null && !walksBuildDir) sweepDir(walkedDir, context, true);
4282
+ }
4283
+ function keptEntries(path, replaced) {
4284
+ if (!existsSync(path)) return [];
4285
+ const previous = parseReceipt(path);
4286
+ if (previous.error !== void 0 || previous.receipt.schema !== PROTECTION_RECEIPT_SCHEMA) return [];
4287
+ return previous.receipt.files.filter((entry) => !replaced.has(entry.path));
3259
4288
  }
3260
4289
  function writeDeferredProtectionReceipt(deferred) {
3261
4290
  const survivingFiles = deferred.files.filter((file) => existsSync(file));
@@ -3276,13 +4305,22 @@ function writeProtectionReceipt(input) {
3276
4305
  seedOrigin: input.seedOrigin,
3277
4306
  bundler: input.bundler,
3278
4307
  buildId: input.buildId,
4308
+ buildDir: ".",
3279
4309
  files: input.files.map((file) => ({
3280
4310
  path: receiptPathOf(input.dir, file),
3281
4311
  sha256: sha256Of(file),
3282
4312
  transformed: transformed.has(file)
3283
4313
  })).sort((a, b) => a.path.localeCompare(b.path))
3284
4314
  };
3285
- const path = join(input.dir, PROTECTION_RECEIPT_FILE);
4315
+ const home = input.home ?? afterpackHome(input.dir);
4316
+ receipt.buildDir = buildDirOf(home);
4317
+ const path = receiptPathIn(home);
4318
+ if (input.merge) {
4319
+ const replaced = new Set(receipt.files.map((entry) => entry.path));
4320
+ receipt.files = [...keptEntries(path, replaced), ...receipt.files].sort((a, b) => a.path.localeCompare(b.path));
4321
+ }
4322
+ mkdirSync(dirname(path), { recursive: true });
4323
+ ensureAfterpackGitignore(home.dir);
3286
4324
  writeFileSync(path, `${JSON.stringify(receipt, null, 2)}\n`);
3287
4325
  return path;
3288
4326
  }
@@ -3330,8 +4368,7 @@ var UnreadableReceiptError = class extends Error {
3330
4368
  this.schema = schema;
3331
4369
  }
3332
4370
  };
3333
- function verifyProtectionReceipt(dir, expectedBuildId) {
3334
- const receiptPath = join(dir, PROTECTION_RECEIPT_FILE);
4371
+ function verifyProtectionReceipt(receiptPath, dir, expectedBuildId) {
3335
4372
  if (!existsSync(receiptPath)) return {
3336
4373
  receiptPath,
3337
4374
  receipt: null,
@@ -3363,152 +4400,93 @@ function verifyProtectionReceipt(dir, expectedBuildId) {
3363
4400
  problems
3364
4401
  };
3365
4402
  }
3366
- function findReceiptDir(startDir) {
3367
- const receiptPath = findUpward(startDir, PROTECTION_RECEIPT_FILE);
3368
- return receiptPath ? dirname(receiptPath) : null;
3369
- }
3370
- function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
3371
- const dir = findReceiptDir(startDir);
3372
- if (!dir) return null;
3373
- const receiptPath = join(dir, PROTECTION_RECEIPT_FILE);
3374
- const result = parseReceipt(receiptPath);
3375
- if (result.error !== void 0) {
3376
- const schema = result.newerSchema;
3377
- if (schema === null) return null;
3378
- 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);
3379
- }
3380
- const outputHashes = new Set(result.receipt.files.map((f) => f.sha256));
3381
- if (outputHashes.size === 0) return null;
3382
- const matches = files.filter((file) => {
3383
- const bytes = bytesByPath?.get(file);
3384
- if (bytes !== void 0) return outputHashes.has(sha256OfBytes(bytes));
3385
- return existsSync(file) && outputHashes.has(sha256Of(file));
3386
- });
3387
- return matches.length > 0 ? {
3388
- receiptPath,
3389
- files: matches
3390
- } : null;
3391
- }
3392
-
3393
- //#endregion
3394
- //#region src/seed.ts
3395
- function randomSeed() {
3396
- const b = randomBytes(8);
3397
- const hi = b.readUInt32BE(0) & 2097151;
3398
- const lo = b.readUInt32BE(4);
3399
- return hi * 4294967296 + lo;
3400
- }
3401
- function gitHead() {
3402
- try {
3403
- const out = execFileSync("git", ["rev-parse", "HEAD"], { stdio: [
3404
- "ignore",
3405
- "pipe",
3406
- "ignore"
3407
- ] }).toString().trim();
3408
- return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3409
- } catch {
3410
- return null;
3411
- }
3412
- }
3413
- const SEED_ENV_VAR = "AFTERPACK_SEED";
3414
- function parseSeedValue(raw) {
3415
- return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3416
- }
3417
- const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3418
- function sharedSeedState() {
3419
- const holder = globalThis;
3420
- holder[SEED_STATE] ??= {
3421
- sessions: new Map(),
3422
- ownEnvExports: []
3423
- };
3424
- return holder[SEED_STATE];
3425
- }
3426
- const { sessions, ownEnvExports } = sharedSeedState();
3427
- function isOwnEnvExport(env, value) {
3428
- return ownEnvExports.some((e) => e.env === env && e.value === value);
3429
- }
3430
- function openGeneration(root, leg) {
3431
- let session = sessions.get(root);
3432
- if (!session) {
3433
- session = {
3434
- seed: void 0,
3435
- generation: 1,
3436
- legs: [],
3437
- resolvedByLeg: new Map(),
3438
- gitFallbackWarned: false
3439
- };
3440
- sessions.set(root, session);
3441
- } else if (session.legs.includes(leg)) {
3442
- session.seed = void 0;
3443
- session.generation += 1;
3444
- session.legs = [];
3445
- session.resolvedByLeg.clear();
3446
- session.gitFallbackWarned = false;
3447
- }
3448
- session.legs.push(leg);
3449
- return session;
3450
- }
3451
- function resolveWithinSession(input, session, env, deps) {
3452
- if (typeof input === "number") return {
3453
- seed: input,
3454
- origin: "option"
3455
- };
3456
- if (typeof input === "string" && input !== "git") return {
3457
- seed: input,
3458
- origin: "option"
4403
+ function receiptsIn(home) {
4404
+ const dir = receiptsDirOf(home);
4405
+ return entriesOf(dir).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => join(dir, entry.name)).sort();
4406
+ }
4407
+ function filesByName(dir) {
4408
+ const byName = new Map();
4409
+ const walk$1 = (current, rel) => {
4410
+ for (const entry of entriesOf(current)) {
4411
+ if (entry.name === "node_modules" || entry.name === AFTERPACK_DIR) continue;
4412
+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
4413
+ if (entry.isDirectory()) walk$1(join(current, entry.name), childRel);
4414
+ else if (entry.isFile()) byName.set(entry.name, [...byName.get(entry.name) ?? [], childRel]);
4415
+ }
3459
4416
  };
3460
- if (input === "git") {
3461
- const head = (deps.gitHead ?? gitHead)();
3462
- if (head) return {
3463
- seed: head,
3464
- origin: "git"
3465
- };
3466
- if (!session.gitFallbackWarned) {
3467
- session.gitFallbackWarned = true;
3468
- (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
4417
+ walk$1(dir, "");
4418
+ return byName;
4419
+ }
4420
+ function copyMatches(dir, home, skip) {
4421
+ const receipts = receiptsIn(home).filter((path) => !skip.has(path));
4422
+ if (receipts.length === 0) return [];
4423
+ const byName = filesByName(dir);
4424
+ const matches = [];
4425
+ for (const receiptPath of receipts) {
4426
+ const parsed = parseReceipt(receiptPath);
4427
+ if (parsed.error !== void 0 || parsed.receipt.files.length === 0) continue;
4428
+ const { files, buildDir } = parsed.receipt;
4429
+ const first = files[0].path;
4430
+ for (const rel of byName.get(first.split("/").pop() ?? first) ?? []) {
4431
+ if (rel !== first && !rel.endsWith(`/${first}`)) continue;
4432
+ const prefix = rel.slice(0, rel.length - first.length);
4433
+ const copyDir = join(dir, ...prefix.split("/").filter(Boolean));
4434
+ if (!files.every((entry) => existsSync(join(copyDir, entry.path)))) continue;
4435
+ matches.push({
4436
+ receiptPath,
4437
+ dir: copyDir,
4438
+ copiedFrom: typeof buildDir === "string" ? join(home.projectRoot, buildDir) : null,
4439
+ hashesMatch: files.every((entry) => sha256Of(join(copyDir, entry.path)) === entry.sha256),
4440
+ prefix
4441
+ });
3469
4442
  }
3470
4443
  }
3471
- const fromEnv = env[SEED_ENV_VAR];
3472
- if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3473
- seed: parseSeedValue(fromEnv),
3474
- origin: "env"
3475
- };
3476
- if (session.seed !== void 0) return {
3477
- seed: session.seed,
3478
- origin: "session"
3479
- };
3480
- return {
3481
- seed: (deps.randomSeed ?? randomSeed)(),
3482
- origin: "fresh"
4444
+ return matches.sort((a, b) => Number(b.hashesMatch) - Number(a.hashesMatch) || a.prefix.length - b.prefix.length || a.receiptPath.localeCompare(b.receiptPath));
4445
+ }
4446
+ function locateProtectionReceipt(dir, options = {}) {
4447
+ const homes = [afterpackHome(dir), afterpackHome(dir, { fileTarget: true })];
4448
+ const exact = [...new Set(homes.map(receiptPathIn))];
4449
+ const found = exact.find((path) => existsSync(path));
4450
+ if (found) return {
4451
+ receiptPath: found,
4452
+ dir,
4453
+ copiedFrom: null
3483
4454
  };
4455
+ if (options.copies === false) return null;
4456
+ const best = copyMatches(dir, homes[0], new Set(exact))[0];
4457
+ return best ? {
4458
+ receiptPath: best.receiptPath,
4459
+ dir: best.dir,
4460
+ copiedFrom: best.copiedFrom
4461
+ } : null;
3484
4462
  }
3485
- function resolveBuildSeed(input, scope, deps = {}) {
3486
- const env = deps.env ?? process.env;
3487
- const session = openGeneration(scope.root, scope.leg);
3488
- const { seed, origin } = resolveWithinSession(input, session, env, deps);
3489
- if (origin === "env" || origin === "fresh") session.seed = seed;
3490
- if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3491
- const value = String(seed);
3492
- env[SEED_ENV_VAR] = value;
3493
- const stale = ownEnvExports.findIndex((e) => e.env === env);
3494
- if (stale >= 0) ownEnvExports.splice(stale, 1);
3495
- ownEnvExports.push({
3496
- env,
3497
- value
4463
+ function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
4464
+ const hashOf = (file) => {
4465
+ const bytes = bytesByPath?.get(file);
4466
+ if (bytes !== void 0) return sha256OfBytes(bytes);
4467
+ return existsSync(file) ? sha256Of(file) : null;
4468
+ };
4469
+ let hashes = null;
4470
+ for (const receiptPath of receiptsIn(homeOf(startDir))) {
4471
+ const result = parseReceipt(receiptPath);
4472
+ if (result.error !== void 0) {
4473
+ const schema = result.newerSchema;
4474
+ if (schema === null) continue;
4475
+ 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);
4476
+ }
4477
+ const outputHashes = new Set(result.receipt.files.filter((f) => f.transformed !== false).map((f) => f.sha256));
4478
+ if (outputHashes.size === 0) continue;
4479
+ hashes ??= new Map(files.map((file) => [file, hashOf(file)]));
4480
+ const matches = files.filter((file) => {
4481
+ const hash = hashes?.get(file);
4482
+ return hash != null && outputHashes.has(hash);
3498
4483
  });
4484
+ if (matches.length > 0) return {
4485
+ receiptPath,
4486
+ files: matches
4487
+ };
3499
4488
  }
3500
- const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3501
- session.resolvedByLeg.set(scope.leg, seed);
3502
- return {
3503
- seed,
3504
- origin,
3505
- legs: [...session.legs],
3506
- generation: session.generation,
3507
- mismatch: prior && session.generation === 1 ? {
3508
- leg: prior[0],
3509
- seed: prior[1]
3510
- } : null
3511
- };
4489
+ return null;
3512
4490
  }
3513
4491
 
3514
4492
  //#endregion
@@ -3524,317 +4502,498 @@ function fmtElapsed(ms) {
3524
4502
  function formatPassSummary(input, style, colorGlyph = (glyph) => glyph) {
3525
4503
  const head = style === "cli" ? colorGlyph("✓") : `[${input.label}]`;
3526
4504
  const files = input.fileCount === 1 ? "file" : "files";
3527
- const tail = (input.unobfuscatedCount > 0 ? ` · ${input.unobfuscatedCount} shipped UNOBFUSCATED (fallback, cleartext)` : "") + (input.noOpCount > 0 ? ` · ${input.noOpCount} no-op (unchanged)` : "");
4505
+ const tail = input.noOpCount > 0 ? ` · ${input.noOpCount} no-op (unchanged)` : "";
3528
4506
  return `${head} Protected ${input.fileCount} ${files} · ${fmtBytes(input.inputBytes)} → ${fmtBytes(input.outputBytes)}${tail} · ${fmtElapsed(input.elapsedMs)}`;
3529
4507
  }
3530
4508
 
3531
4509
  //#endregion
3532
- //#region src/telemetry.ts
3533
- const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3534
- const DEFAULT_API_URL = "https://api.afterpack.dev";
3535
- const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3536
- const TELEMETRY_PAYLOAD_VERSION = 1;
3537
- const TELEMETRY_TIMEOUT_MS = 1500;
3538
- const INSTALL_ID_ROTATION_DAYS = 30;
3539
- const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3540
- const TELEMETRY_STATE_FILE = join(homedir(), ".afterpack", "telemetry.json");
3541
- const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3542
- const DATA_FIELD_WHITELIST = {
3543
- outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3544
- parseError: ["parserErrorKind"],
3545
- engineBug: [
3546
- "phase",
3547
- "transform",
3548
- "nodeKind"
3549
- ],
3550
- inflationBudget: [
3551
- "target",
3552
- "achieved",
3553
- "budgetRatio",
3554
- "inflationRatio"
3555
- ],
3556
- configParse: [
3557
- "category",
3558
- "line",
3559
- "column"
3560
- ]
4510
+ //#region src/wire.ts
4511
+ const EXTERNAL_WIRE_DIR = "_external";
4512
+ const DRIVE_PATH = /^[A-Za-z]:[\\/]/;
4513
+ const URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]+:/;
4514
+ const FILE_URL = /^file:/i;
4515
+ const PATH_CHARS = "[^\\s\"'`|!?#()<>,;:*\\\\]";
4516
+ const EMBEDDED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:[A-Za-z]:[\\\\/]|/)(?:${PATH_CHARS}|\\\\(?!/))*)`, "g");
4517
+ const ESCAPED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:\\\\/${PATH_CHARS}+)+\\\\/?)`, "g");
4518
+ var WirePathError = class extends Error {
4519
+ constructor(message) {
4520
+ super(message);
4521
+ this.name = "WirePathError";
4522
+ }
3561
4523
  };
3562
- function resolveTelemetryEnabled(option, env = {}) {
3563
- if (option !== void 0) return option;
3564
- return !(env.NODE_ENV === "test" || env.VITEST);
4524
+ function toPosix(path) {
4525
+ return path.includes("\\") ? path.replaceAll("\\", "/") : path;
3565
4526
  }
3566
- const FRAMEWORK_ENTRIES = [
3567
- {
3568
- label: "afterpack",
3569
- name: "cli"
3570
- },
3571
- {
3572
- label: "afterpack-angular",
3573
- name: "angular",
3574
- pkg: "@angular/core"
3575
- },
3576
- {
3577
- label: "afterpack-esbuild",
3578
- name: "esbuild",
3579
- pkg: "esbuild"
3580
- },
3581
- {
3582
- label: "afterpack-next",
3583
- name: "next",
3584
- pkg: "next"
3585
- },
3586
- {
3587
- label: "afterpack-rollup",
3588
- name: "rollup",
3589
- pkg: "rollup"
3590
- },
3591
- {
3592
- label: "afterpack-vite",
3593
- name: "vite",
3594
- pkg: "vite"
3595
- },
3596
- {
3597
- label: "afterpack-webpack",
3598
- name: "webpack",
3599
- pkg: "webpack"
3600
- }
3601
- ];
3602
- const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3603
- const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3604
- function frameworkFromLabel(label) {
3605
- return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
4527
+ function lastSegment(path) {
4528
+ const parts = toPosix(path).split("/").filter((p) => p !== "");
4529
+ return parts[parts.length - 1] ?? "file";
3606
4530
  }
3607
- const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3608
- function detectFrameworkVersion(projectRoot, framework) {
3609
- const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3610
- if (!pkgName) return null;
3611
- let deps;
4531
+ function isUnder(child, parent) {
4532
+ const rel = relative(parent, child);
4533
+ return rel === "" || !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
4534
+ }
4535
+ function relativeWithin(file, baseDir) {
4536
+ const rel = relative(resolve(baseDir), resolve(file));
4537
+ if (rel === "" || isAbsolute(rel) || DRIVE_PATH.test(rel)) return null;
4538
+ if (rel === ".." || rel.startsWith(`..${sep}`)) return null;
4539
+ return toPosix(rel);
4540
+ }
4541
+ function osUsername() {
3612
4542
  try {
3613
- const pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
3614
- deps = {
3615
- ...pkg.dependencies,
3616
- ...pkg.devDependencies
3617
- };
4543
+ return userInfo().username;
3618
4544
  } catch {
3619
4545
  return null;
3620
4546
  }
3621
- const raw = deps[pkgName];
3622
- if (typeof raw !== "string") return null;
3623
- const range = raw.trim();
3624
- return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3625
4547
  }
3626
- function complexityLabel(preset, complexity) {
3627
- if (preset !== void 0) return preset;
3628
- return complexity === void 0 ? "default" : "custom";
4548
+ function personalNames() {
4549
+ const names = new Set([basename(homedir())]);
4550
+ const user = osUsername();
4551
+ if (user) names.add(user);
4552
+ return names;
4553
+ }
4554
+ function safeName(path) {
4555
+ const name = lastSegment(path);
4556
+ return personalNames().has(name) ? "file" : name;
4557
+ }
4558
+ function toWirePaths(files, baseDir) {
4559
+ const wire = new Map();
4560
+ const taken = new Set();
4561
+ const outside = [];
4562
+ for (const file of files) {
4563
+ if (wire.has(file)) continue;
4564
+ const rel = relativeWithin(file, baseDir);
4565
+ if (rel === null || taken.has(rel)) {
4566
+ outside.push(file);
4567
+ continue;
4568
+ }
4569
+ wire.set(file, rel);
4570
+ taken.add(rel);
4571
+ }
4572
+ let n = 0;
4573
+ for (const file of outside) {
4574
+ if (wire.has(file)) continue;
4575
+ let label;
4576
+ do {
4577
+ label = `${EXTERNAL_WIRE_DIR}/${n}/${safeName(file)}`;
4578
+ n += 1;
4579
+ } while (taken.has(label));
4580
+ wire.set(file, label);
4581
+ taken.add(label);
4582
+ }
4583
+ return wire;
3629
4584
  }
3630
- const FILE_COUNT_BUCKETS = [
3631
- 1,
3632
- 5,
3633
- 20,
3634
- 100,
3635
- 500,
3636
- 2e3
3637
- ];
3638
- function fileCountBucket(count) {
3639
- if (!Number.isFinite(count) || count <= 0) return "0";
3640
- let lower = 1;
3641
- for (const upper of FILE_COUNT_BUCKETS) {
3642
- if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3643
- lower = upper + 1;
4585
+ function looksLocal(path) {
4586
+ return isUnder(path, homedir()) || isUnder(path, tmpdir()) || existsSync(path);
4587
+ }
4588
+ function localPathOf(source) {
4589
+ if (DRIVE_PATH.test(source) || source.startsWith("/") || source.startsWith("\\")) return source;
4590
+ if (FILE_URL.test(source)) try {
4591
+ return fileURLToPath(source);
4592
+ } catch {
4593
+ return source.replace(FILE_URL, "").replace(/^\/\/[^/]*/, "") || "/";
3644
4594
  }
3645
- return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
4595
+ const scheme = URL_SCHEME.exec(source);
4596
+ if (!scheme) return null;
4597
+ const rest = source.slice(scheme[0].length).replace(/^\/\/[^/]*/, "");
4598
+ const drive = rest.replace(/^\/+/, "");
4599
+ if (DRIVE_PATH.test(drive)) return drive;
4600
+ return rest.startsWith("/") && looksLocal(rest) ? rest : null;
3646
4601
  }
3647
- const DURATION_BUCKETS_MS = [
3648
- [1e3, "<1s"],
3649
- [5e3, "1-5s"],
3650
- [15e3, "5-15s"],
3651
- [6e4, "15-60s"],
3652
- [3e5, "60-300s"]
3653
- ];
3654
- function durationBucket(ms) {
3655
- if (!Number.isFinite(ms) || ms < 0) return "unknown";
3656
- for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3657
- return "300s+";
4602
+ function bothForms(path) {
4603
+ return [...new Set([resolve(path), realPath(path)])];
3658
4604
  }
3659
- function safeScalar(value) {
3660
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
3661
- if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
4605
+ function newPlace(dir, root, labels, shipped = "") {
4606
+ return {
4607
+ dir,
4608
+ root,
4609
+ privateRoots: [...new Set([homedir(), root].flatMap(bothForms))],
4610
+ scratchRoots: bothForms(tmpdir()),
4611
+ labels,
4612
+ shipped
4613
+ };
4614
+ }
4615
+ function isPrivate(path, place) {
4616
+ if (DRIVE_PATH.test(path) && !isAbsolute(path)) return true;
4617
+ if (place.privateRoots.some((r) => isUnder(path, r))) return true;
4618
+ return place.scratchRoots.some((r) => isUnder(path, r) && resolve(path) !== resolve(r));
4619
+ }
4620
+ function inProject(path, place) {
4621
+ if (DRIVE_PATH.test(path) && !isAbsolute(path)) return null;
4622
+ const real = realPath(path);
4623
+ const mapDir = realPath(place.dir);
4624
+ const home = realPath(homedir());
4625
+ if (!isUnder(real, realPath(place.root))) return null;
4626
+ if (isUnder(real, home) && !isUnder(mapDir, home)) return null;
4627
+ const rel = relative(mapDir, real);
4628
+ if (rel === "" || isAbsolute(rel) || DRIVE_PATH.test(rel)) return null;
4629
+ return toPosix(rel);
4630
+ }
4631
+ function externalLabel(path, place) {
4632
+ const key = resolve(path);
4633
+ const known = place.labels.get(key);
4634
+ if (known !== void 0) return known;
4635
+ const label = `${EXTERNAL_WIRE_DIR}/${place.labels.size}/${safeName(path)}`;
4636
+ place.labels.set(key, label);
4637
+ return label;
4638
+ }
4639
+ function fitLength(target, candidate, slash) {
4640
+ const unit = `.${slash}`;
4641
+ const room = target - candidate.length;
4642
+ for (let a = Math.floor(Math.max(room, 0) / unit.length); a >= 0; a--) {
4643
+ const rest = room - a * unit.length;
4644
+ if (rest % slash.length !== 0) continue;
4645
+ const body = unit.repeat(a) + candidate;
4646
+ const extra = rest / slash.length;
4647
+ if (extra === 0) return body;
4648
+ const at = body.indexOf(slash);
4649
+ if (at < 0) continue;
4650
+ return body.slice(0, at) + slash.repeat(extra) + body.slice(at);
4651
+ }
3662
4652
  return null;
3663
4653
  }
3664
- function telemetrySafeData(data) {
3665
- if (!data || typeof data.kind !== "string") return null;
3666
- const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3667
- if (kind === null) return null;
3668
- const out = { kind };
3669
- for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3670
- const value = safeScalar(data[field]);
3671
- if (value !== null) out[field] = value;
4654
+ function sameLength(original, candidates, slash) {
4655
+ for (const candidate of candidates) {
4656
+ const fitted = fitLength(original.length, candidate, slash);
4657
+ if (fitted !== null) return fitted;
3672
4658
  }
3673
- return out;
4659
+ return "_".repeat(original.length);
4660
+ }
4661
+ function scrubText(text, place, keepLength) {
4662
+ if (!text.includes("/") && !text.includes("\\")) return text;
4663
+ const plain = text.replace(EMBEDDED_PATH, (whole, lead, path) => {
4664
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(path)) return whole;
4665
+ const name = inProject(path, place) ?? safeName(path);
4666
+ return `${lead}${keepLength ? sameLength(path, [name, safeName(path)], "/") : name}`;
4667
+ });
4668
+ return plain.replace(ESCAPED_PATH, (whole, lead, escaped) => {
4669
+ const path = escaped.replaceAll("\\/", "/");
4670
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(escaped)) return whole;
4671
+ const names = [inProject(path, place) ?? safeName(path), safeName(path)].map((c) => c.replaceAll("/", "\\/"));
4672
+ return `${lead}${keepLength ? sameLength(escaped, names, "\\/") : names[0]}`;
4673
+ });
3674
4674
  }
3675
- function telemetrySafeSpan(d) {
3676
- const span = d.span;
3677
- if (!span) return null;
3678
- const start = safeScalar(span.startByte);
3679
- const end = safeScalar(span.endByte);
3680
- if (typeof start !== "number" || typeof end !== "number") return null;
3681
- if (start < 0 || end < 0) return null;
4675
+ function isRecord(value) {
4676
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4677
+ }
4678
+ function joinRoot(root, source) {
4679
+ return root.endsWith("/") || root.endsWith("\\") ? `${root}${source}` : `${root}/${source}`;
4680
+ }
4681
+ function newRestore() {
3682
4682
  return {
3683
- startByte: start,
3684
- endByte: end
4683
+ sources: new Map(),
4684
+ pmPaths: new Map(),
4685
+ contents: new Map()
3685
4686
  };
3686
4687
  }
3687
- function telemetrySafeDiagnostic(d, severity) {
4688
+ function remember(table, wire, original) {
4689
+ const known = table.get(wire);
4690
+ if (known === void 0) table.set(wire, original);
4691
+ else if (known !== original) table.set(wire, null);
4692
+ }
4693
+ function wireMapObject(map, place, restore, top) {
4694
+ const out = { ...map };
4695
+ let changed = false;
4696
+ const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
4697
+ const rootIsLocal = root !== "" && localPathOf(root) !== null;
4698
+ if (rootIsLocal) {
4699
+ delete out.sourceRoot;
4700
+ if (top) restore.sourceRoot = root;
4701
+ changed = true;
4702
+ }
4703
+ const sentRoot = rootIsLocal ? "" : root;
4704
+ const pmPath = (r, s) => r === "" ? s : joinRoot(r, s);
4705
+ const taken = new Map();
4706
+ const claim = (wired, original, local) => {
4707
+ const owner = taken.get(wired);
4708
+ if (owner === void 0 || owner === original) {
4709
+ taken.set(wired, original);
4710
+ return wired;
4711
+ }
4712
+ const label = externalLabel(local, place);
4713
+ taken.set(label, original);
4714
+ return label;
4715
+ };
4716
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((source) => {
4717
+ if (typeof source !== "string") return source;
4718
+ const rooted = rootIsLocal && localPathOf(source) === null && !URL_SCHEME.test(source) ? joinRoot(root, source) : source;
4719
+ const local = localPathOf(rooted);
4720
+ let wired;
4721
+ if (local === null) {
4722
+ const scrubbed = scrubText(rooted, place, false);
4723
+ if (scrubbed === source) {
4724
+ taken.set(source, source);
4725
+ return source;
4726
+ }
4727
+ wired = claim(scrubbed, source, rooted);
4728
+ } else {
4729
+ const rel = inProject(local, place);
4730
+ wired = claim(rel ?? externalLabel(local, place), source, local);
4731
+ }
4732
+ changed = true;
4733
+ remember(restore.sources, wired, source);
4734
+ remember(restore.pmPaths, pmPath(sentRoot, wired), pmPath(root, source));
4735
+ return wired;
4736
+ });
4737
+ if (typeof map.file === "string" && localPathOf(map.file) !== null) {
4738
+ if (top) restore.file = map.file;
4739
+ out.file = safeName(map.file);
4740
+ changed = true;
4741
+ }
4742
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((content) => {
4743
+ if (typeof content !== "string") return content;
4744
+ const scrubbed = scrubText(content, place, true);
4745
+ if (scrubbed === content) return content;
4746
+ changed = true;
4747
+ remember(restore.contents, scrubbed, content);
4748
+ return scrubbed;
4749
+ });
4750
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
4751
+ if (!isRecord(section) || !isRecord(section.map)) return section;
4752
+ const nested = wireMapObject(section.map, place, restore, false);
4753
+ if (!nested.changed) return section;
4754
+ changed = true;
4755
+ return {
4756
+ ...section,
4757
+ map: nested.map
4758
+ };
4759
+ });
3688
4760
  return {
3689
- code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3690
- severity,
3691
- span: telemetrySafeSpan(d),
3692
- data: telemetrySafeData(d.data)
4761
+ map: out,
4762
+ changed
3693
4763
  };
3694
4764
  }
3695
- function buildTelemetryPayload(facts, ctx) {
3696
- let errorCount = 0;
3697
- let criticalCount = 0;
3698
- const alerting = [];
3699
- for (const d of facts.diagnostics) {
3700
- if (d.severity !== "error" && d.severity !== "critical") continue;
3701
- if (d.severity === "critical") criticalCount += 1;
3702
- else errorCount += 1;
3703
- alerting.push(telemetrySafeDiagnostic(d, d.severity));
4765
+ function wireSourceMapWithRestore(json, place) {
4766
+ const restore = newRestore();
4767
+ let parsed;
4768
+ try {
4769
+ parsed = JSON.parse(json);
4770
+ } catch {
4771
+ return {
4772
+ json: void 0,
4773
+ restore
4774
+ };
3704
4775
  }
3705
- if (alerting.length === 0) return null;
3706
- const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3707
- const env = ctx.env ?? {};
3708
- const runtime = ctx.runtime ?? {
3709
- node: process.versions.node,
3710
- platform: process.platform,
3711
- arch: process.arch
4776
+ if (!isRecord(parsed)) return {
4777
+ json: void 0,
4778
+ restore
3712
4779
  };
3713
- const framework = frameworkFromLabel(facts.label);
4780
+ const { map, changed } = wireMapObject(parsed, place, restore, true);
3714
4781
  return {
3715
- version: TELEMETRY_PAYLOAD_VERSION,
3716
- installId: ctx.installId,
3717
- framework,
3718
- frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3719
- engineVersion: safeVersion(facts.engineVersion),
3720
- clientVersion: safeVersion(facts.clientVersion),
3721
- nodeVersion: safeVersion(runtime.node) ?? "unknown",
3722
- os: safeToken(runtime.platform),
3723
- arch: safeToken(runtime.arch),
3724
- ci: env.CI === "true",
3725
- complexity: complexityLabel(facts.preset, facts.complexity),
3726
- fileCountBucket: fileCountBucket(facts.fileCount),
3727
- durationBucket: durationBucket(facts.durationMs),
3728
- diagnostics: kept,
3729
- errorCount,
3730
- criticalCount,
3731
- droppedCount: alerting.length - kept.length
4782
+ json: changed ? JSON.stringify(map) : json,
4783
+ restore
3732
4784
  };
3733
4785
  }
3734
- const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3735
- function safeVersion(value) {
3736
- return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3737
- }
3738
- function safeToken(value) {
3739
- return TOKEN_PATTERN.test(value) ? value : "unknown";
3740
- }
3741
- const TELEMETRY_NOTICE = [
3742
- "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3743
- "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3744
- "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3745
- "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3746
- "AfterPack: file counts and durations, and a random install id that rotates every 30",
3747
- "AfterPack: days.",
3748
- "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3749
- "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3750
- "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3751
- "AfterPack: `telemetry: { enabled: false }` in your config.",
3752
- "AfterPack: https://www.afterpack.dev/privacy"
3753
- ];
3754
- const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3755
- const DAY_MS = 24 * 60 * 60 * 1e3;
3756
- function readState(file, now) {
3757
- try {
3758
- const parsed = JSON.parse(readFileSync(file, "utf8"));
3759
- if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3760
- installId: parsed.installId,
3761
- rotatedAt: parsed.rotatedAt,
3762
- noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
4786
+ function lookup(table, value) {
4787
+ return table.get(value) ?? value;
4788
+ }
4789
+ function restoreMapObject(map, ctx, top) {
4790
+ let changed = false;
4791
+ const out = { ...map };
4792
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((entry) => {
4793
+ if (typeof entry !== "string") return entry;
4794
+ const back = entry === ctx.wire ? ctx.local : lookup(ctx.map.sources, entry);
4795
+ if (back !== entry) changed = true;
4796
+ return back;
4797
+ });
4798
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((entry) => {
4799
+ if (typeof entry !== "string") return entry;
4800
+ const back = lookup(ctx.map.contents, entry);
4801
+ if (back !== entry) changed = true;
4802
+ return back;
4803
+ });
4804
+ if (top && ctx.map.sourceRoot !== void 0 && !map.sourceRoot) {
4805
+ const root = ctx.map.sourceRoot;
4806
+ const entries = Object.entries(out).filter(([key]) => key !== "sourceRoot");
4807
+ const at = "sourceRoot" in map ? Object.keys(map).indexOf("sourceRoot") : -1;
4808
+ const after = entries.findIndex(([key]) => key === "sources");
4809
+ const index = at >= 0 ? at : after >= 0 ? after + 1 : entries.length;
4810
+ entries.splice(index, 0, ["sourceRoot", root]);
4811
+ for (const key of Object.keys(out)) delete out[key];
4812
+ Object.assign(out, Object.fromEntries(entries));
4813
+ changed = true;
4814
+ }
4815
+ if (top && ctx.map.file !== void 0 && typeof map.file === "string") {
4816
+ out.file = ctx.map.file;
4817
+ changed = true;
4818
+ }
4819
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
4820
+ if (!isRecord(section) || !isRecord(section.map)) return section;
4821
+ const nested = restoreMapObject(section.map, ctx, false);
4822
+ if (!nested.changed) return section;
4823
+ changed = true;
4824
+ return {
4825
+ ...section,
4826
+ map: nested.map
3763
4827
  };
3764
- } catch {}
4828
+ });
3765
4829
  return {
3766
- installId: randomUUID(),
3767
- rotatedAt: now,
3768
- noticeShownAt: 0
4830
+ map: out,
4831
+ changed
3769
4832
  };
3770
4833
  }
3771
- function writeState(file, state) {
4834
+ function restoreSourceMap(json, ctx) {
4835
+ let parsed;
3772
4836
  try {
3773
- mkdirSync(dirname(file), { recursive: true });
3774
- writeFileSync(file, `${JSON.stringify(state)}\n`, "utf8");
3775
- } catch {}
3776
- }
3777
- function telemetryUrl(env) {
3778
- const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3779
- return `${base}${TELEMETRY_ENDPOINT_PATH}`;
4837
+ parsed = JSON.parse(json);
4838
+ } catch {
4839
+ return json;
4840
+ }
4841
+ if (!isRecord(parsed)) return json;
4842
+ const { map, changed } = restoreMapObject(parsed, ctx, true);
4843
+ return changed ? JSON.stringify(map) : json;
4844
+ }
4845
+ function restoredSize(size, wired, original) {
4846
+ if (typeof size !== "number") return size;
4847
+ if (size === Buffer.byteLength(wired)) return Buffer.byteLength(original);
4848
+ if (size === wired.length) return original.length;
4849
+ return size;
4850
+ }
4851
+ function restoreProtectionMap(doc, ctx) {
4852
+ if (!isRecord(doc) || !Array.isArray(doc.files)) return doc;
4853
+ return {
4854
+ ...doc,
4855
+ files: doc.files.map((entry) => {
4856
+ if (!isRecord(entry) || !isRecord(entry.file)) return entry;
4857
+ const file = entry.file;
4858
+ const next = { ...file };
4859
+ if (typeof file.path === "string") next.path = file.path === ctx.wire ? ctx.local : lookup(ctx.map.pmPaths, file.path);
4860
+ if (typeof file.originalSource === "string") {
4861
+ const original = lookup(ctx.map.contents, file.originalSource);
4862
+ if (original !== file.originalSource) {
4863
+ next.originalSource = original;
4864
+ next.inputSize = restoredSize(file.inputSize, file.originalSource, original);
4865
+ }
4866
+ }
4867
+ const same = Object.keys(next).every((k) => next[k] === file[k]);
4868
+ return same ? entry : {
4869
+ ...entry,
4870
+ file: next
4871
+ };
4872
+ })
4873
+ };
3780
4874
  }
3781
- const TELEMETRY_BODY_LIMIT = 64 * 1024;
3782
- async function reportTelemetryNotices(response, logger) {
3783
- if (!response || response.status !== 202 || typeof response.text !== "function") return;
3784
- const declared = Number(response.headers?.get?.("content-length"));
3785
- if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3786
- await response.body?.cancel().catch(() => {});
3787
- return;
4875
+ function wireGlob(pattern, pairs) {
4876
+ let equivalent = true;
4877
+ const matched = [];
4878
+ for (const [local, wire] of pairs) {
4879
+ const hit = matchesPath(pattern, local);
4880
+ if (hit !== matchesPath(pattern, wire)) equivalent = false;
4881
+ if (hit) matched.push(wire);
3788
4882
  }
3789
- const text = await response.text();
3790
- if (text.length > TELEMETRY_BODY_LIMIT) return;
3791
- let body;
3792
- try {
3793
- body = JSON.parse(text);
3794
- } catch {
3795
- return;
4883
+ if (!isAnchored(pattern) && equivalent && matched.length > 0) return [pattern];
4884
+ return matched.map((wire) => `/${wire}`);
4885
+ }
4886
+ function anyMatch(patterns, path) {
4887
+ return patterns.some((p) => matchesPath(p, path));
4888
+ }
4889
+ function reservedNames(entries, path) {
4890
+ const names = entries.flatMap((e) => typeof e === "string" ? [] : matchesPath(e.glob, path) ? e.names : []);
4891
+ return [...new Set(names)].sort().join("\n");
4892
+ }
4893
+ function verifyTranslation(config, out, pairs) {
4894
+ const exclude = config.paths?.exclude ?? [];
4895
+ const sentExclude = out.paths?.exclude ?? [];
4896
+ const reserved = config.identifiers?.reserved ?? [];
4897
+ const sentReserved = out.identifiers?.reserved ?? [];
4898
+ for (const [local, wire] of pairs) {
4899
+ 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.`);
4900
+ 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.`);
3796
4901
  }
3797
- if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3798
- reportNotices(body.notices, logger);
3799
4902
  }
3800
- function createTelemetryReporter(deps = {}) {
3801
- const env = deps.env ?? process.env;
3802
- const logger = deps.logger ?? console;
3803
- const now = deps.now ?? Date.now;
3804
- const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3805
- const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3806
- return async (facts) => {
3807
- try {
3808
- const at = now();
3809
- const state = readState(stateFile, at);
3810
- let dirty = false;
3811
- if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3812
- state.installId = randomUUID();
3813
- state.rotatedAt = at;
3814
- dirty = true;
3815
- }
3816
- if (state.noticeShownAt === 0) {
3817
- for (const line of TELEMETRY_NOTICE) logger.log(line);
3818
- state.noticeShownAt = at;
3819
- dirty = true;
3820
- }
3821
- if (dirty) writeState(stateFile, state);
3822
- if (facts === null) return;
3823
- const payload = buildTelemetryPayload(facts, {
3824
- installId: state.installId,
3825
- env
3826
- });
3827
- if (payload === null) return;
3828
- const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3829
- if (typeof fetchImpl !== "function") return;
3830
- const response = await fetchImpl(telemetryUrl(env), {
3831
- method: "POST",
3832
- headers: { "content-type": "application/json" },
3833
- body: JSON.stringify(payload),
3834
- signal: AbortSignal.timeout(timeoutMs)
3835
- });
3836
- await reportTelemetryNotices(response, logger);
3837
- } catch {}
4903
+ function translateConfig(config, wirePaths) {
4904
+ const exclude = config.paths?.exclude;
4905
+ const reserved = config.identifiers?.reserved;
4906
+ const origins = new Map();
4907
+ if (exclude === void 0 && reserved === void 0) return {
4908
+ config,
4909
+ origins
4910
+ };
4911
+ const pairs = [...wirePaths.entries()];
4912
+ const translate = (pattern) => {
4913
+ const patterns = wireGlob(pattern, pairs);
4914
+ for (const p of patterns) if (!origins.has(p)) origins.set(p, pattern);
4915
+ return patterns;
4916
+ };
4917
+ const out = { ...config };
4918
+ if (exclude !== void 0) out.paths = {
4919
+ ...config.paths,
4920
+ exclude: [...new Set(exclude.flatMap((pattern) => translate(pattern)))]
4921
+ };
4922
+ if (reserved !== void 0) out.identifiers = {
4923
+ ...config.identifiers,
4924
+ reserved: reserved.flatMap((entry) => typeof entry === "string" ? [entry] : translate(entry.glob).map((glob) => ({
4925
+ ...entry,
4926
+ glob
4927
+ })))
4928
+ };
4929
+ verifyTranslation(config, out, pairs);
4930
+ return {
4931
+ config: out,
4932
+ origins
4933
+ };
4934
+ }
4935
+ function escapeRegExp(text) {
4936
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4937
+ }
4938
+ function localMessage(message, wire, local, origins) {
4939
+ let out = message;
4940
+ for (const [sent, original] of origins) if (sent !== original) out = out.split(`"${sent}"`).join(`"${original}"`);
4941
+ const bounded = new RegExp(`(^|[\\s"'\`(\\[])${escapeRegExp(wire)}(?=$|[\\s"'\`)\\]:,;]|\\.(?:\\s|$))`, "g");
4942
+ return out.replace(bounded, (_m, lead) => `${lead}${local}`);
4943
+ }
4944
+ function localDiagnostics(diagnostics, localPaths, wire, local, origins) {
4945
+ if (!Array.isArray(diagnostics)) return diagnostics;
4946
+ return diagnostics.map((d) => {
4947
+ if (!isRecord(d)) return d;
4948
+ const next = { ...d };
4949
+ if (typeof d.file === "string") next.file = localPaths.get(d.file) ?? d.file;
4950
+ if (typeof d.message === "string") next.message = localMessage(d.message, wire, local, origins);
4951
+ return next.file === d.file && next.message === d.message ? d : next;
4952
+ });
4953
+ }
4954
+ function prepareWireBatch(inputs, config, baseDir, rootDir = baseDir) {
4955
+ const wirePaths = toWirePaths(inputs.map((i) => i.path), baseDir);
4956
+ const localPaths = new Map([...wirePaths].map(([local, wire]) => [wire, local]));
4957
+ const translated = translateConfig(config, wirePaths);
4958
+ const restores = new Map();
4959
+ const labels = new Map();
4960
+ const wiredInputs = inputs.map((input) => {
4961
+ const path = wirePaths.get(input.path) ?? input.path;
4962
+ const wired = {
4963
+ ...input,
4964
+ path
4965
+ };
4966
+ if (input.sourceMap !== void 0) {
4967
+ const place = newPlace(dirname(resolve(input.path)), rootDir, labels, input.source);
4968
+ const map = wireSourceMapWithRestore(input.sourceMap, place);
4969
+ restores.set(path, map.restore);
4970
+ if (map.json === void 0) delete wired.sourceMap;
4971
+ else wired.sourceMap = map.json;
4972
+ }
4973
+ return wired;
4974
+ });
4975
+ return {
4976
+ inputs: wiredInputs,
4977
+ config: translated.config,
4978
+ toLocal: (batch) => ({
4979
+ ...batch,
4980
+ files: batch.files.map((f) => {
4981
+ const local = localPaths.get(f.path);
4982
+ if (local === void 0) return f;
4983
+ const ctx = {
4984
+ map: restores.get(f.path) ?? newRestore(),
4985
+ wire: f.path,
4986
+ local
4987
+ };
4988
+ return {
4989
+ ...f,
4990
+ path: local,
4991
+ ...f.diagnostics === void 0 ? {} : { diagnostics: localDiagnostics(f.diagnostics, localPaths, f.path, local, translated.origins) },
4992
+ ...typeof f.sourceMap === "string" ? { sourceMap: restoreSourceMap(f.sourceMap, ctx) } : {},
4993
+ ...f.protectionMap == null ? {} : { protectionMap: restoreProtectionMap(f.protectionMap, ctx) }
4994
+ };
4995
+ })
4996
+ })
3838
4997
  };
3839
4998
  }
3840
4999
 
@@ -3867,16 +5026,19 @@ function fileFailure(f, source) {
3867
5026
  if (reason) return reason;
3868
5027
  return f.status === "failure" ? "empty output" : `the engine reported status "${sanitizeServerText(f.status, 32)}"`;
3869
5028
  }
3870
- if (typeof f.unobfuscated !== "boolean") return "the engine result does not say whether the file was obfuscated";
5029
+ if (f.unobfuscated === true) return "the engine could not obfuscate it and returned the original source — update @afterpack/core";
3871
5030
  if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
3872
5031
  return null;
3873
5032
  }
3874
- async function readEngineVersion(engine) {
3875
- try {
3876
- return await engine.version?.() ?? null;
3877
- } catch {
3878
- return null;
5033
+ function removeBundlerSourceMaps(input) {
5034
+ const { sweepDir: sweepDir$1, engineMaps, policy, label } = input;
5035
+ const bundlerMaps = new Set([...input.perFile].flat());
5036
+ if (sweepDir$1 != null) {
5037
+ const swept = collectSourceMaps(sweepDir$1).filter((path) => !policy.sourceMap || !path.endsWith(".css.map"));
5038
+ for (const path of containedSourceMaps(swept, sweepDir$1)) bundlerMaps.add(path);
3879
5039
  }
5040
+ removeSourceMaps([...bundlerMaps].filter((path) => !engineMaps.has(path)), label);
5041
+ if (sweepDir$1 != null && !policy.sourceMap) stripCssSourceMappingURLs(collectStylesheets(sweepDir$1));
3880
5042
  }
3881
5043
  function describeLevel(preset, complexity) {
3882
5044
  if (complexity === void 0) return `preset "${preset ?? DEFAULT_PRESET}"`;
@@ -3886,22 +5048,30 @@ function describeLevel(preset, complexity) {
3886
5048
  async function runObfuscationPass(options) {
3887
5049
  const passStartedAt = options.startedAt ?? Date.now();
3888
5050
  const callerAnchored = options.startedAt !== void 0;
3889
- const { files, engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
5051
+ const { engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
3890
5052
  const logger = silenceSummaryLines(options.logger ?? DEFAULT_LOGGER, options.diagnostics);
3891
5053
  const prefix = (message) => `[${label}] ${message}`;
3892
5054
  const style = options.summaryStyle ?? "plugin";
3893
5055
  assertSupportedCore(options.client, prefix);
5056
+ const outsideBuildDir = options.emitToCaller ? [] : options.files.filter((f) => !options.inputs?.has(f) && !withinRealDir(dirname(f), combinedProtectionMap.buildDir));
5057
+ const files = options.files.filter((f) => !outsideBuildDir.includes(f));
5058
+ if (outsideBuildDir.length > 0) logger.warn(prefix(`left ${outsideBuildDir.length} file(s) untouched because a symlink places them outside ${combinedProtectionMap.buildDir}: ${outsideBuildDir.join(", ")}`));
3894
5059
  const onDiskFiles = options.inputs ? files.filter((f) => !options.inputs?.has(f)) : files;
3895
5060
  const onDiskBytes = new Map(await Promise.all(onDiskFiles.map(async (filePath) => [filePath, await readFile(filePath)])));
5061
+ const home = afterpackHome(combinedProtectionMap.buildDir, { fileTarget: combinedProtectionMap.fileTarget });
5062
+ const unanchored = describeUnanchoredHome(home);
5063
+ if (unanchored) logger.log(prefix(unanchored));
3896
5064
  if (!options.emitToCaller) {
3897
- const already = detectAlreadyObfuscatedInputs(onDiskFiles, combinedProtectionMap.buildDir, onDiskBytes, prefix);
5065
+ const already = detectAlreadyObfuscatedInputs(onDiskFiles, home, onDiskBytes, prefix);
3898
5066
  if (already) throw new AlreadyObfuscatedError(prefix(formatAlreadyObfuscatedMessage({
3899
5067
  files: already.files,
3900
5068
  receiptPath: already.receiptPath,
3901
5069
  dir: combinedProtectionMap.buildDir
3902
5070
  })), already.files, already.receiptPath, combinedProtectionMap.buildDir);
3903
5071
  }
3904
- const resolvedSeed = resolveBuildSeed(options.seed, {
5072
+ if (options.outputSweep !== false) sweepOutputTree(combinedProtectionMap.buildDir, options.sourceMapSweepDir ?? (options.emitToCaller ? combinedProtectionMap.buildDir : null), label, home);
5073
+ prepareProtectionReceipt(home, label);
5074
+ const resolvedSeed = options.resolvedSeed ?? resolveBuildSeed(options.seed, {
3905
5075
  root: cwd,
3906
5076
  leg: options.buildLeg ?? combinedProtectionMap.buildDir
3907
5077
  }, {
@@ -3914,6 +5084,9 @@ async function runObfuscationPass(options) {
3914
5084
  const bundledCapture = options.capturedByFile != null;
3915
5085
  const postMinifyMode = directivesEnabled && options.postMinify === true && !bundledCapture;
3916
5086
  const sourceByPath = new Map();
5087
+ const bundlerMapsByPath = new Map();
5088
+ const sweepDir$1 = options.sourceMapSweepDir ?? null;
5089
+ const sourceMapRoot = sweepDir$1 ?? combinedProtectionMap.buildDir;
3917
5090
  let coloredRegionCount = 0;
3918
5091
  let directivesNeededMap = false;
3919
5092
  let postMinifyMapsSeen = 0;
@@ -3923,6 +5096,7 @@ async function runObfuscationPass(options) {
3923
5096
  const provided = options.inputs?.get(filePath);
3924
5097
  const source = provided ? provided.source : (onDiskBytes.get(filePath) ?? readFileSync(filePath)).toString("utf8");
3925
5098
  sourceByPath.set(filePath, source);
5099
+ if (!provided && !options.emitToCaller) bundlerMapsByPath.set(filePath, bundlerSourceMapPaths(filePath, source, sourceMapRoot));
3926
5100
  const inputSourceMap = provided ? provided.sourceMap ?? null : discoverInputSourceMap(filePath, source);
3927
5101
  let regions;
3928
5102
  const modules = options.capturedByFile?.get(filePath);
@@ -4014,6 +5188,39 @@ async function runObfuscationPass(options) {
4014
5188
  engine: options.engineConfig,
4015
5189
  renameGlobals: capture.renameGlobals
4016
5190
  });
5191
+ const saltEngine = options.cloudEngineExpectation ?? (options.hashedNames ? await resolveSaltEngine(env, localEngineVersion) : null);
5192
+ let namesPlan = null;
5193
+ let hashSalt = null;
5194
+ if (options.hashedNames && saltEngine && !options.emitToCaller) {
5195
+ const { seed: _seed,...configWithoutSeed } = engineConfig;
5196
+ const namedInputs = new Map(inputs.map((input) => [input.path, {
5197
+ source: input.source,
5198
+ regions: input.regions
5199
+ }]));
5200
+ hashSalt = afterpackHashSalt({
5201
+ seed,
5202
+ engine: saltEngine,
5203
+ settings: {
5204
+ engine: configWithoutSeed,
5205
+ sourceMap: policy.sourceMap,
5206
+ emitSourceMappingURL: policy.emitSourceMappingURL
5207
+ }
5208
+ });
5209
+ namesPlan = planHashedNames({
5210
+ options: options.hashedNames,
5211
+ inputs: namedInputs,
5212
+ salt: hashSalt
5213
+ });
5214
+ namesPlan.preflight();
5215
+ for (const input of inputs) {
5216
+ const path = namesPlan.renamed.get(input.path) ?? input.path;
5217
+ const source = namesPlan.rewrite(input.source);
5218
+ sourceByPath.delete(input.path);
5219
+ sourceByPath.set(path, source);
5220
+ input.path = path;
5221
+ input.source = source;
5222
+ }
5223
+ }
4017
5224
  if (style !== "cli") logger.log(prefix(`obfuscating ${inputs.length} file(s) at ${describeLevel(options.preset, options.complexity)} ...`));
4018
5225
  const engineStartedAt = Date.now();
4019
5226
  const prepMs = engineStartedAt - passStartedAt;
@@ -4021,9 +5228,16 @@ async function runObfuscationPass(options) {
4021
5228
  clientVersion: options.client?.coreVersion,
4022
5229
  client: clientString(options.client)
4023
5230
  });
5231
+ let wire;
5232
+ try {
5233
+ wire = prepareWireBatch(inputs, engineConfig, combinedProtectionMap.buildDir, home.projectRoot);
5234
+ } catch (error) {
5235
+ if (error instanceof WirePathError) throw new Error(prefix(error.message));
5236
+ throw error;
5237
+ }
4024
5238
  let batch;
4025
5239
  try {
4026
- batch = await engine.processBatch(inputs, engineConfig, context);
5240
+ batch = wire.toLocal(await engine.processBatch(wire.inputs, wire.config, context));
4027
5241
  } catch (error) {
4028
5242
  const cloud = toCloudApiError(error, {
4029
5243
  identity: options.client,
@@ -4034,6 +5248,7 @@ async function runObfuscationPass(options) {
4034
5248
  throw cloud;
4035
5249
  }
4036
5250
  const engineEndedAt = Date.now();
5251
+ options.onBatch?.(inputs, batch);
4037
5252
  reportNotices(batch.notices, logger, prefix);
4038
5253
  const engineMs = engineEndedAt - engineStartedAt;
4039
5254
  const collected = collectDiagnostics(batch.files);
@@ -4048,6 +5263,10 @@ async function runObfuscationPass(options) {
4048
5263
  const telemetry = options.telemetry;
4049
5264
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4050
5265
  const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
5266
+ if (saltEngine) {
5267
+ const mismatch = cloudEngineMismatch(saltEngine, batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null);
5268
+ if (mismatch) throw new Error(prefix(mismatch));
5269
+ }
4051
5270
  if (telemetry && telemetryEnabled) {
4052
5271
  const facts = {
4053
5272
  label,
@@ -4067,7 +5286,6 @@ async function runObfuscationPass(options) {
4067
5286
  const outputs = [];
4068
5287
  let inputBytes = 0;
4069
5288
  let outputBytes = 0;
4070
- const unobfuscatedFiles = [];
4071
5289
  let noOp = 0;
4072
5290
  const transformedFiles = [];
4073
5291
  const verified = [];
@@ -4078,8 +5296,7 @@ async function runObfuscationPass(options) {
4078
5296
  if (failure !== null) throw new Error(prefix(`failed to obfuscate ${f.path}: ${failure}`));
4079
5297
  inputBytes += Buffer.byteLength(source);
4080
5298
  outputBytes += Buffer.byteLength(f.code);
4081
- if (f.unobfuscated === true) unobfuscatedFiles.push(basename(f.path));
4082
- else if (f.code === source) noOp += 1;
5299
+ if (f.code === source) noOp += 1;
4083
5300
  else transformedFiles.push(f.path);
4084
5301
  if (policy.protectionMap && f.protectionMap != null) protectionMapDocs.push(f.protectionMap);
4085
5302
  verified.push({
@@ -4087,10 +5304,9 @@ async function runObfuscationPass(options) {
4087
5304
  source
4088
5305
  });
4089
5306
  }
4090
- if (unobfuscatedFiles.length > 0) if (artifactOptions.allowUnobfuscated === true) for (const name of unobfuscatedFiles) logger.warn(prefix(`${name} could not be obfuscated and SHIPPED AS CLEARTEXT (allowUnobfuscated:true). This is an engine bug — please report it.`));
4091
- else throw new Error(prefix(`${unobfuscatedFiles.length} file(s) could not be obfuscated and would ship as cleartext: ${unobfuscatedFiles.join(", ")} — fix the engine or set allowUnobfuscated:true`));
4092
5307
  const writtenFiles = [];
4093
5308
  const emittedFiles = [];
5309
+ const engineMaps = new Set();
4094
5310
  for (const { result: f, source } of verified) {
4095
5311
  if (options.emitToCaller) {
4096
5312
  outputs.push({
@@ -4103,24 +5319,42 @@ async function runObfuscationPass(options) {
4103
5319
  }
4104
5320
  const written = writeArtifacts({
4105
5321
  outPath: f.path,
4106
- code: f.code,
5322
+ code: withSourceMappingURL(f.code, null),
4107
5323
  sourceMapJson: f.sourceMap ?? null,
4108
5324
  protectionMapJson: null,
4109
5325
  originalSource: source,
4110
5326
  policy,
4111
5327
  mode: "framework",
5328
+ afterpackDir: home.dir,
4112
5329
  logger
4113
5330
  });
4114
5331
  writtenFiles.push(written.codePath);
4115
- if (written.mapPath) sensitiveArtifactPaths.push(written.mapPath);
5332
+ if (written.mapPath) {
5333
+ sensitiveArtifactPaths.push(written.mapPath);
5334
+ engineMaps.add(resolve(written.mapPath));
5335
+ }
4116
5336
  if (written.backupPath) sensitiveArtifactPaths.push(written.backupPath);
4117
5337
  }
4118
- if (!options.emitToCaller) options.afterWrite?.();
5338
+ if (!options.emitToCaller) {
5339
+ if (namesPlan) {
5340
+ for (const [from, to] of namesPlan.renamed) if (sourceByPath.has(to)) rmSync(from, { force: true });
5341
+ namesPlan.apply();
5342
+ if (namesPlan.renamed.size > 0) logger.log(prefix(`renamed ${namesPlan.renamed.size} content-hashed file(s) so each name follows its obfuscated bytes`));
5343
+ }
5344
+ removeBundlerSourceMaps({
5345
+ perFile: bundlerMapsByPath.values(),
5346
+ sweepDir: sweepDir$1,
5347
+ engineMaps,
5348
+ policy,
5349
+ label
5350
+ });
5351
+ options.afterWrite?.(writtenFiles);
5352
+ }
4119
5353
  const protectionMapPath = writeCombinedProtectionMap({
4120
5354
  buildDir: combinedProtectionMap.buildDir,
4121
5355
  docs: protectionMapDocs,
4122
5356
  policy,
4123
- afterpackDir: combinedProtectionMap.afterpackDir,
5357
+ afterpackDir: combinedProtectionMap.subdir ? join(home.dir, combinedProtectionMap.subdir) : home.dir,
4124
5358
  fileName: combinedProtectionMap.fileName,
4125
5359
  logger
4126
5360
  });
@@ -4142,12 +5376,15 @@ async function runObfuscationPass(options) {
4142
5376
  if (options.emitToCaller) deferredReceipt = {
4143
5377
  ...receiptFields,
4144
5378
  dir: combinedProtectionMap.buildDir,
5379
+ home,
4145
5380
  files: emittedFiles
4146
5381
  };
4147
5382
  else {
4148
5383
  receiptPath = writeProtectionReceipt({
4149
5384
  ...receiptFields,
4150
5385
  dir: combinedProtectionMap.buildDir,
5386
+ home,
5387
+ merge: combinedProtectionMap.fileTarget === true,
4151
5388
  files: writtenFiles
4152
5389
  });
4153
5390
  if (style !== "cli") logger.log(prefix(`wrote protection receipt -> ${receiptPath} (afterpack verify)`));
@@ -4172,7 +5409,6 @@ async function runObfuscationPass(options) {
4172
5409
  fileCount: files.length,
4173
5410
  inputBytes,
4174
5411
  outputBytes,
4175
- unobfuscatedCount: unobfuscatedFiles.length,
4176
5412
  noOpCount: noOp,
4177
5413
  elapsedMs: totalMs
4178
5414
  }, style, options.colorGlyph) + seedSuffix);
@@ -4187,6 +5423,8 @@ async function runObfuscationPass(options) {
4187
5423
  timing,
4188
5424
  diagnostics: diagnosticsSummary,
4189
5425
  transformedFiles,
5426
+ renamed: namesPlan?.renamed ?? new Map(),
5427
+ hashSalt,
4190
5428
  ...options.emitToCaller ? { outputs } : {}
4191
5429
  };
4192
5430
  }
@@ -4366,4 +5604,4 @@ function resolvePluginConfig(input) {
4366
5604
  }
4367
5605
 
4368
5606
  //#endregion
4369
- export { AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, PROTECTION_RECEIPT_FILE, SEED_ENV_VAR, UnreadableReceiptError, applyBundleOutput, applyResolvedKey, collectBundleJs, collectJsFiles, collectSourceMaps, collectStylesheets, createTelemetryReporter, decodeDataUri, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findUpward, getPath, installedRequiredLine, loadConfigFile, mergeConfig, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Of, sourceTypeForBundle, sourceTypeForOutputFormat, stripBundleCssSourceMaps, toEngineConfig, toPluginOptions, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeProtectionReceipt };
5607
+ export { AFTERPACK_DIR, AfterpackFilesError, AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_AFTERPACK_DIR_IN_OUTPUT, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, DIAG_RECEIPT_UNWRITABLE, PROTECTION_RECEIPTS_DIR, SEED_ENV_VAR, UnreadableReceiptError, afterpackHome, applyBundleOutput, applyResolvedKey, collectBundleJs, collectJsFiles, collectSourceMaps, collectStylesheets, createTelemetryReporter, decodeDataUri, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findUpward, getPath, installedRequiredLine, loadConfigFile, locateProtectionReceipt, mergeConfig, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, prepareHashSalt, protectionReceiptPath, readEngineVersion, regenerateCompressedSiblings, removeSourceMaps, reportPolicySaltBits, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, saltSettings, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Of, sourceTypeForBundle, sourceTypeForOutputFormat, sriPluginRefusal, stripBundleCssSourceMaps, stripCssSourceMappingURLs, sweepOutputTree, toEngineConfig, toPluginOptions, unsaltedAssetsWarning, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeProtectionReceipt };