@afterpack/integration-utils 0.2.3 → 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.cjs CHANGED
@@ -27,10 +27,10 @@ const node_module = __toESM(require("node:module"));
27
27
  const node_zlib = __toESM(require("node:zlib"));
28
28
  const node_crypto = __toESM(require("node:crypto"));
29
29
  const node_url = __toESM(require("node:url"));
30
- const node_fs_promises = __toESM(require("node:fs/promises"));
31
30
  const node_child_process = __toESM(require("node:child_process"));
32
- const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
33
31
  const node_os = __toESM(require("node:os"));
32
+ const node_fs_promises = __toESM(require("node:fs/promises"));
33
+ const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
34
34
 
35
35
  //#region ../protection-map/codec.mjs
36
36
  const COMPACT_SCHEMA_VERSION = 5;
@@ -297,6 +297,91 @@ function renderProtectionMapHtml(raw, { template, includeLineage = true } = {})
297
297
  };
298
298
  }
299
299
 
300
+ //#endregion
301
+ //#region src/home.ts
302
+ const AFTERPACK_DIR = ".afterpack";
303
+ const STRONG_MARKERS = [
304
+ "afterpack.json",
305
+ ".git",
306
+ "package-lock.json",
307
+ "npm-shrinkwrap.json",
308
+ "pnpm-lock.yaml",
309
+ "yarn.lock",
310
+ "bun.lock",
311
+ "bun.lockb"
312
+ ];
313
+ const WEAK_MARKERS = ["package.json"];
314
+ const DIAG_AFTERPACK_DIR_IN_OUTPUT = "DIAG_AFTERPACK_DIR_IN_OUTPUT";
315
+ const DIAG_RECEIPT_UNWRITABLE = "DIAG_RECEIPT_UNWRITABLE";
316
+ var AfterpackFilesError = class extends Error {
317
+ code;
318
+ summary;
319
+ fix;
320
+ constructor(code, summary, fix) {
321
+ super(`${summary} ${fix}`);
322
+ this.name = "AfterpackFilesError";
323
+ this.code = code;
324
+ this.summary = summary;
325
+ this.fix = fix;
326
+ }
327
+ };
328
+ function realPath(path) {
329
+ const resolved = (0, node_path.resolve)(path);
330
+ try {
331
+ return node_fs.realpathSync.native(resolved);
332
+ } catch {
333
+ const parent = (0, node_path.dirname)(resolved);
334
+ return parent === resolved ? resolved : (0, node_path.join)(realPath(parent), (0, node_path.basename)(resolved));
335
+ }
336
+ }
337
+ function isWithinDir(dir, path) {
338
+ const rel = (0, node_path.relative)(dir, path);
339
+ return rel === "" || !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
340
+ }
341
+ function markerIn(dir, markers) {
342
+ return markers.find((name) => (0, node_fs.existsSync)((0, node_path.join)(dir, name))) ?? null;
343
+ }
344
+ function nearestMarker(start, markers) {
345
+ for (let current = start;;) {
346
+ const marker = markerIn(current, markers);
347
+ if (marker) return {
348
+ root: current,
349
+ marker
350
+ };
351
+ const parent = (0, node_path.dirname)(current);
352
+ if (parent === current) return null;
353
+ current = parent;
354
+ }
355
+ }
356
+ function afterpackHome(buildDir, options = {}) {
357
+ const realBuildDir = realPath(buildDir);
358
+ const ownMarker = options.fileTarget ? markerIn(realBuildDir, STRONG_MARKERS) : null;
359
+ if (ownMarker !== null) return {
360
+ dir: (0, node_path.join)(realBuildDir, AFTERPACK_DIR),
361
+ projectRoot: realBuildDir,
362
+ marker: ownMarker,
363
+ strong: true,
364
+ buildDir: realBuildDir
365
+ };
366
+ const start = (0, node_path.dirname)(realBuildDir);
367
+ const strong = nearestMarker(start, STRONG_MARKERS);
368
+ const found = strong ?? nearestMarker(start, WEAK_MARKERS);
369
+ const projectRoot = found?.root ?? start;
370
+ const dir = (0, node_path.join)(projectRoot, AFTERPACK_DIR);
371
+ 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.");
372
+ return {
373
+ dir,
374
+ projectRoot,
375
+ marker: found?.marker ?? null,
376
+ strong: strong !== null,
377
+ buildDir: realBuildDir
378
+ };
379
+ }
380
+ function describeUnanchoredHome(home) {
381
+ if (home.marker !== null) return null;
382
+ return `no lockfile, afterpack.json, .git or package.json above ${home.buildDir}, so AfterPack keeps its files beside it, in ${home.dir}`;
383
+ }
384
+
300
385
  //#endregion
301
386
  //#region src/paths.ts
302
387
  const COMBINED_PROTECTION_MAP_NAME = "protectionMap.html";
@@ -329,7 +414,6 @@ function findUpward(startDir, fileName, options = {}) {
329
414
 
330
415
  //#endregion
331
416
  //#region src/artifacts.ts
332
- const AFTERPACK_DIR = ".afterpack";
333
417
  const AFTERPACK_GITIGNORE_CONTENT = "*\n";
334
418
  const PUBLIC_SEGMENTS = new Set([
335
419
  "public",
@@ -355,7 +439,7 @@ function appendSourceMappingURL(code, mapPath) {
355
439
  function writeArtifacts(input) {
356
440
  const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
357
441
  const mode = input.mode ?? "single";
358
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
442
+ const afterpackDir = input.afterpackDir;
359
443
  const logger = input.logger ?? DEFAULT_LOGGER;
360
444
  const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
361
445
  const paths = resolveArtifactPaths(outPath, mode, hash);
@@ -713,7 +797,7 @@ function buildProjectFileTree(files) {
713
797
  }
714
798
  function writeCombinedProtectionMap(input) {
715
799
  const { buildDir, docs, policy } = input;
716
- const afterpackDir = input.afterpackDir ?? AFTERPACK_DIR;
800
+ const afterpackDir = input.afterpackDir;
717
801
  const logger = input.logger ?? DEFAULT_LOGGER;
718
802
  if (!policy.protectionMap || docs.length === 0) return null;
719
803
  (0, node_fs.mkdirSync)(afterpackDir, { recursive: true });
@@ -991,7 +1075,7 @@ const CONFIG_KEYS = [
991
1075
  tier: "free",
992
1076
  surface: "engine",
993
1077
  item: { kind: "boolean" },
994
- default: "true in development when an input map exists; false in production"
1078
+ default: "false; true in development mode when an input map exists"
995
1079
  },
996
1080
  {
997
1081
  path: "sourceMap.sourcesContent",
@@ -1000,7 +1084,7 @@ const CONFIG_KEYS = [
1000
1084
  tier: "free",
1001
1085
  surface: "engine",
1002
1086
  item: { kind: "boolean" },
1003
- default: "true in development; false in production"
1087
+ default: "false; true in development mode"
1004
1088
  },
1005
1089
  {
1006
1090
  path: "sourceMap.emitUrl",
@@ -1009,7 +1093,7 @@ const CONFIG_KEYS = [
1009
1093
  tier: "free",
1010
1094
  surface: "build",
1011
1095
  item: { kind: "boolean" },
1012
- default: "true in development; false in production"
1096
+ default: "false; true in development mode"
1013
1097
  },
1014
1098
  {
1015
1099
  path: "protectionMap.enabled",
@@ -1148,7 +1232,7 @@ const CONFIG_KEYS = [
1148
1232
  kind: "enum",
1149
1233
  values: BUILD_MODE_VALUES
1150
1234
  },
1151
- default: "detected from the environment"
1235
+ default: "production, unless NODE_ENV is development"
1152
1236
  },
1153
1237
  {
1154
1238
  path: "directives.enabled",
@@ -1269,8 +1353,8 @@ function unknownKeyMessage(path, surface) {
1269
1353
  if (group$1 && group$1.length > 0) {
1270
1354
  const list = group$1.map((child) => `\`${child}\``).join(", ");
1271
1355
  const tail$1 = group$1.length === 1 ? `did you mean ${list}?` : `its keys are ${list}`;
1272
- const canonical = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1273
- const enabled = canonical ? groupBooleanKey(canonical) : void 0;
1356
+ const canonical$1 = PREFIX_BY_NORMALIZED.get(normalizeKey(path));
1357
+ const enabled = canonical$1 ? groupBooleanKey(canonical$1) : void 0;
1274
1358
  const rule = enabled ? `; a boolean here means \`${enabled.path}\`` : "";
1275
1359
  return `\`${path}\` is a group of configuration keys, not a key itself (${surface}) — ${tail$1}${rule}`;
1276
1360
  }
@@ -1604,6 +1688,15 @@ function decodeDataUri(url) {
1604
1688
  return null;
1605
1689
  }
1606
1690
  }
1691
+ function localSourceMapPath(jsPath, url) {
1692
+ if (url.startsWith("data:") || isRemoteSourceMappingURL(url)) return null;
1693
+ const path = url.replace(/[?#].*$/, "");
1694
+ try {
1695
+ return (0, node_path.isAbsolute)(path) ? path : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(path));
1696
+ } catch {
1697
+ return null;
1698
+ }
1699
+ }
1607
1700
  function discoverInputSourceMap(jsPath, code) {
1608
1701
  const adjacent = `${jsPath}.map`;
1609
1702
  if ((0, node_fs.existsSync)(adjacent)) try {
@@ -1618,20 +1711,81 @@ function discoverInputSourceMap(jsPath, code) {
1618
1711
  const url = extractSourceMappingURL(source);
1619
1712
  if (url == null) return null;
1620
1713
  if (url.startsWith("data:")) return decodeDataUri(url);
1621
- if (isRemoteSourceMappingURL(url)) return null;
1622
- let mapPath;
1714
+ const mapPath = localSourceMapPath(jsPath, url);
1715
+ if (mapPath == null || !(0, node_fs.existsSync)(mapPath)) return null;
1623
1716
  try {
1624
- mapPath = (0, node_path.isAbsolute)(url) ? url : (0, node_path.resolve)((0, node_path.dirname)(jsPath), decodeURIComponent(url));
1717
+ return (0, node_fs.readFileSync)(mapPath, "utf8");
1625
1718
  } catch {
1626
1719
  return null;
1627
1720
  }
1628
- if (!(0, node_fs.existsSync)(mapPath)) return null;
1721
+ }
1722
+ function bundlerSourceMapPaths(jsPath, code, root) {
1723
+ const candidates = [`${jsPath}.map`];
1724
+ for (const match of code.matchAll(SOURCE_MAPPING_URL_RE)) {
1725
+ const url = match[1];
1726
+ const local = localSourceMapPath(jsPath, url);
1727
+ if (local != null) candidates.push(local);
1728
+ if (url.startsWith("/") && !url.startsWith("//")) try {
1729
+ candidates.push((0, node_path.resolve)(root, `.${decodeURIComponent(url.replace(/[?#].*$/, ""))}`));
1730
+ } catch {}
1731
+ }
1732
+ return containedSourceMaps(candidates, root);
1733
+ }
1734
+ function realpathOrNull(path) {
1629
1735
  try {
1630
- return (0, node_fs.readFileSync)(mapPath, "utf8");
1736
+ return (0, node_fs.realpathSync)(path);
1631
1737
  } catch {
1632
1738
  return null;
1633
1739
  }
1634
1740
  }
1741
+ function withinRealDir(dir, root) {
1742
+ const rootReal = realpathOrNull(root);
1743
+ const real = realpathOrNull(dir);
1744
+ if (rootReal == null || real == null) return false;
1745
+ if (real === rootReal) return true;
1746
+ return real.startsWith(rootReal.endsWith(node_path.sep) ? rootReal : `${rootReal}${node_path.sep}`);
1747
+ }
1748
+ function containedSourceMaps(paths, root) {
1749
+ const found = new Set();
1750
+ for (const path of paths) {
1751
+ if (!path.endsWith(".map")) continue;
1752
+ const lexical = (0, node_path.resolve)(path);
1753
+ if (!withinRealDir((0, node_path.dirname)(lexical), root)) continue;
1754
+ try {
1755
+ const stat = (0, node_fs.lstatSync)(lexical);
1756
+ if (stat.isFile() || stat.isSymbolicLink()) found.add(lexical);
1757
+ } catch {}
1758
+ }
1759
+ return [...found];
1760
+ }
1761
+ function removeSourceMaps(paths, label) {
1762
+ let removed = 0;
1763
+ for (const path of paths) try {
1764
+ (0, node_fs.unlinkSync)(path);
1765
+ removed++;
1766
+ } catch (error) {
1767
+ if (error.code === "ENOENT") continue;
1768
+ throw new Error(`[${label}] could not remove the source map ${path}, refusing to ship it: ${error}`);
1769
+ }
1770
+ return removed;
1771
+ }
1772
+ function stripCssSourceMappingURLs(paths) {
1773
+ let stripped = 0;
1774
+ for (const path of paths) {
1775
+ let css;
1776
+ try {
1777
+ css = (0, node_fs.readFileSync)(path, "utf8");
1778
+ } catch (error) {
1779
+ if (error.code === "ENOENT") continue;
1780
+ throw error;
1781
+ }
1782
+ const without = withoutCssSourceMappingURL(css);
1783
+ if (without === css) continue;
1784
+ (0, node_fs.writeFileSync)(path, without);
1785
+ stripped++;
1786
+ }
1787
+ return stripped;
1788
+ }
1635
1789
 
1636
1790
  //#endregion
1637
1791
  //#region src/bundle.ts
@@ -1663,6 +1817,39 @@ function sourceTypeForBundle(format, entries) {
1663
1817
  for (const entry of entries) if (entry.type !== "chunk") return void 0;
1664
1818
  return sourceTypeForOutputFormat(format);
1665
1819
  }
1820
+ const COMPRESSED_SIBLING = /\.(gz|br|zst|zz|deflate)$/;
1821
+ function entryBytes(entry) {
1822
+ if (entry.type === "chunk") return entry.code === void 0 ? null : Buffer.from(entry.code);
1823
+ if (typeof entry.source === "string") return Buffer.from(entry.source);
1824
+ if (entry.source !== void 0) return Buffer.from(entry.source);
1825
+ return null;
1826
+ }
1827
+ function regenerateCompressedSiblings(bundle, obfuscated, label) {
1828
+ for (const [name, entry] of Object.entries(bundle)) {
1829
+ const match = COMPRESSED_SIBLING.exec(name);
1830
+ if (match === null) continue;
1831
+ const base = name.slice(0, -match[0].length);
1832
+ if (!obfuscated.has(base)) continue;
1833
+ const bytes = entryBytes(bundle[base]);
1834
+ if (bytes === null) continue;
1835
+ if (match[1] === "gz") entry.source = (0, node_zlib.gzipSync)(bytes);
1836
+ else if (match[1] === "br") entry.source = (0, node_zlib.brotliCompressSync)(bytes);
1837
+ 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.`);
1838
+ }
1839
+ }
1840
+ const SRI_PLUGIN_NAME = /subresource|integrity|(?:^|[^a-z])sri(?:[^a-z]|$)/i;
1841
+ function sriPluginRefusal(plugins, label) {
1842
+ const found = (plugins ?? []).find((plugin) => SRI_PLUGIN_NAME.test(plugin?.name ?? ""));
1843
+ if (!found) return null;
1844
+ 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.`;
1845
+ }
1846
+ function unsaltedAssetsWarning(entries, salted) {
1847
+ const fileNames = [];
1848
+ for (const entry of entries.values()) if (entry.type !== "chunk" && !salted.has(entry.fileName)) fileNames.push(entry.fileName);
1849
+ fileNames.sort();
1850
+ if (fileNames.length === 0) return null;
1851
+ 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.`;
1852
+ }
1666
1853
  function dataUri(json) {
1667
1854
  return `data:application/json;charset=utf-8;base64,${Buffer.from(json, "utf8").toString("base64")}`;
1668
1855
  }
@@ -1791,7 +1978,7 @@ function collectJsFiles(target, options = {}) {
1791
1978
  if (!stat.isDirectory()) return isCollectableJs((0, node_path.basename)(target)) ? [target] : [];
1792
1979
  return walkJs(target, options.include ?? [], false, options.onNestedProject);
1793
1980
  }
1794
- function entriesOf(dir) {
1981
+ function entriesOf$1(dir) {
1795
1982
  try {
1796
1983
  return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
1797
1984
  } catch {
@@ -1810,12 +1997,13 @@ function isNestedProject(dir) {
1810
1997
  }
1811
1998
  function walkJs(dir, include, readmitted, onNestedProject) {
1812
1999
  const out = [];
1813
- for (const entry of entriesOf(dir)) {
2000
+ for (const entry of entriesOf$1(dir)) {
1814
2001
  const name = entry.name;
1815
2002
  const full = (0, node_path.join)(dir, name);
1816
2003
  const kind = kindOf(entry, full);
1817
2004
  if (kind === null) continue;
1818
2005
  if (kind === "dir") {
2006
+ if (name === AFTERPACK_DIR) continue;
1819
2007
  const skipped = name === NODE_MODULES;
1820
2008
  if (!skipped && !readmitted && isNestedProject(full)) {
1821
2009
  onNestedProject?.(full);
@@ -1834,13 +2022,15 @@ const SOURCE_MAP_RE = /\.(?:[cm]?js|css)\.map$/;
1834
2022
  function collectFiles(dir, accept) {
1835
2023
  if (!(0, node_fs.existsSync)(dir)) return [];
1836
2024
  const out = [];
1837
- for (const entry of entriesOf(dir)) {
2025
+ for (const entry of entriesOf$1(dir)) {
1838
2026
  const name = entry.name;
1839
2027
  const full = (0, node_path.join)(dir, name);
1840
2028
  const kind = kindOf(entry, full);
1841
2029
  if (kind === null) continue;
1842
- if (kind === "dir") out.push(...collectFiles(full, accept));
1843
- else if (accept(name)) out.push(full);
2030
+ if (kind === "dir") {
2031
+ if (name === NODE_MODULES || name === AFTERPACK_DIR || isNestedProject(full)) continue;
2032
+ out.push(...collectFiles(full, accept));
2033
+ } else if (accept(name)) out.push(full);
1844
2034
  }
1845
2035
  return out;
1846
2036
  }
@@ -2347,10 +2537,10 @@ function spaceFormIssue(path, raw, surface) {
2347
2537
  }
2348
2538
  function kebabIssue(key, surface) {
2349
2539
  const suggestion = suggestKey(key);
2350
- const canonical = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2540
+ const canonical$1 = suggestion ? ` — the canonical form is \`${spellKey(suggestion, surface)}\`` : " — keys are dot-delimited camelCase";
2351
2541
  return {
2352
2542
  path: key,
2353
- message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical}`
2543
+ message: `kebab-case is not a configuration key (\`${spellKey(key, surface)}\`)${canonical$1}`
2354
2544
  };
2355
2545
  }
2356
2546
  function parseAssignment(key, raw, surface) {
@@ -2689,7 +2879,7 @@ function reportDiagnostics(input) {
2689
2879
  //#region src/policy.ts
2690
2880
  function detectProduction(env = {}, opts = {}) {
2691
2881
  if (opts.build?.mode !== void 0) return opts.build.mode === "production";
2692
- return env.NODE_ENV === "production" || env.CI === "true";
2882
+ return env.NODE_ENV !== "development";
2693
2883
  }
2694
2884
  function resolveReportPolicy(env = {}, userOpts = {}, signals = {}) {
2695
2885
  const isProduction = detectProduction(env, userOpts);
@@ -3256,145 +3446,905 @@ function captureDirectiveRegions(inputs, handAuthored, enabled = true) {
3256
3446
  }
3257
3447
 
3258
3448
  //#endregion
3259
- //#region src/git.ts
3260
- const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
3261
- const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
3262
- function sanitizeCommitSha(value) {
3263
- if (typeof value !== "string") return null;
3264
- const sha = value.trim().toLowerCase();
3265
- return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
3266
- }
3267
- function sanitizeGitRef(value) {
3268
- if (typeof value !== "string") return null;
3269
- const ref = value.trim();
3270
- return GIT_REF_PATTERN.test(ref) ? ref : null;
3271
- }
3272
- function contextFrom(rawSha, rawRef) {
3273
- const commitSha = sanitizeCommitSha(rawSha);
3274
- const ref = sanitizeGitRef(rawRef);
3275
- if (commitSha === null && ref === null) return null;
3276
- const context = {};
3277
- if (commitSha !== null) context.commitSha = commitSha;
3278
- if (ref !== null) context.ref = ref;
3279
- return context;
3280
- }
3281
- const CI_SOURCES = [
3282
- ["GITHUB_SHA", "GITHUB_REF_NAME"],
3283
- ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
3284
- ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
3285
- ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
3286
- ["GIT_COMMIT", "BRANCH_NAME"]
3287
- ];
3288
- function ciGitContext(env) {
3289
- for (const [shaVar, refVar] of CI_SOURCES) {
3290
- const context = contextFrom(env[shaVar], env[refVar]);
3291
- if (context !== null) return context;
3292
- }
3293
- return null;
3449
+ //#region src/seed.ts
3450
+ function randomSeed() {
3451
+ const b = (0, node_crypto.randomBytes)(8);
3452
+ const hi = b.readUInt32BE(0) & 2097151;
3453
+ const lo = b.readUInt32BE(4);
3454
+ return hi * 4294967296 + lo;
3294
3455
  }
3295
- const GIT_PROBE_TIMEOUT_MS = 2e3;
3296
- function localGitContext(cwd) {
3297
- let lines;
3456
+ function gitHead() {
3298
3457
  try {
3299
- const out = (0, node_child_process.execFileSync)("git", [
3300
- "rev-parse",
3301
- "HEAD",
3302
- "--abbrev-ref",
3303
- "HEAD"
3304
- ], {
3305
- cwd,
3306
- stdio: [
3307
- "ignore",
3308
- "pipe",
3309
- "ignore"
3310
- ],
3311
- timeout: GIT_PROBE_TIMEOUT_MS,
3312
- maxBuffer: 64 * 1024
3313
- }).toString();
3314
- lines = out.split("\n").map((line) => line.trim());
3458
+ const out = (0, node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], { stdio: [
3459
+ "ignore",
3460
+ "pipe",
3461
+ "ignore"
3462
+ ] }).toString().trim();
3463
+ return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3315
3464
  } catch {
3316
3465
  return null;
3317
3466
  }
3318
- const ref = lines[1] === "HEAD" ? null : lines[1];
3319
- return contextFrom(lines[0], ref);
3320
3467
  }
3321
- function detectGitContext(explicit, deps = {}) {
3322
- if (explicit) {
3323
- const declared = contextFrom(explicit.commitSha, explicit.ref);
3324
- if (declared !== null) return declared;
3325
- }
3326
- const ci = ciGitContext(deps.env ?? process.env);
3327
- if (ci !== null) return ci;
3328
- return (deps.localGit ?? localGitContext)(deps.cwd);
3468
+ const SEED_ENV_VAR = "AFTERPACK_SEED";
3469
+ function parseSeedValue(raw) {
3470
+ return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3329
3471
  }
3330
-
3331
- //#endregion
3332
- //#region src/map-color.ts
3333
- const UTF8 = new TextEncoder();
3334
- const utf8Len = (s) => UTF8.encode(s).length;
3335
- const NON_ASCII = /[\u0080-\uFFFF]/;
3336
- const HIGH_SURROGATE_START = 55296;
3337
- const HIGH_SURROGATE_END = 56319;
3338
- const LOW_SURROGATE_START = 56320;
3339
- const LOW_SURROGATE_END = 57343;
3340
- function charToByteTable(line) {
3341
- const table = new Array(line.length + 1);
3342
- let bytes = 0;
3343
- let i = 0;
3344
- while (i < line.length) {
3345
- table[i] = bytes;
3346
- const code = line.charCodeAt(i);
3347
- if (code < 128) {
3348
- bytes += 1;
3349
- i += 1;
3350
- continue;
3351
- }
3352
- if (code < 2048) {
3353
- bytes += 2;
3354
- i += 1;
3355
- continue;
3356
- }
3357
- if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
3358
- const low = line.charCodeAt(i + 1);
3359
- if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
3360
- table[i + 1] = bytes + 3;
3361
- bytes += 4;
3362
- i += 2;
3363
- continue;
3364
- }
3365
- }
3366
- bytes += 3;
3367
- i += 1;
3472
+ const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3473
+ function sharedSeedState() {
3474
+ const holder = globalThis;
3475
+ holder[SEED_STATE] ??= {
3476
+ sessions: new Map(),
3477
+ ownEnvExports: []
3478
+ };
3479
+ return holder[SEED_STATE];
3480
+ }
3481
+ const { sessions, ownEnvExports } = sharedSeedState();
3482
+ function isOwnEnvExport(env, value) {
3483
+ return ownEnvExports.some((e) => e.env === env && e.value === value);
3484
+ }
3485
+ function openGeneration(root, leg) {
3486
+ let session = sessions.get(root);
3487
+ if (!session) {
3488
+ session = {
3489
+ seed: void 0,
3490
+ generation: 1,
3491
+ legs: [],
3492
+ resolvedByLeg: new Map(),
3493
+ gitFallbackWarned: false
3494
+ };
3495
+ sessions.set(root, session);
3496
+ } else if (session.legs.includes(leg)) {
3497
+ session.seed = void 0;
3498
+ session.generation += 1;
3499
+ session.legs = [];
3500
+ session.resolvedByLeg.clear();
3501
+ session.gitFallbackWarned = false;
3368
3502
  }
3369
- table[line.length] = bytes;
3370
- return table;
3503
+ session.legs.push(leg);
3504
+ return session;
3371
3505
  }
3372
- var ChunkByteIndex = class {
3373
- starts;
3374
- ascii;
3375
- tables;
3376
- totalBytes;
3377
- constructor(lines) {
3378
- this.lines = lines;
3379
- this.starts = new Array(lines.length);
3380
- this.ascii = new Array(lines.length);
3381
- this.tables = new Array(lines.length).fill(null);
3382
- let acc = 0;
3383
- for (let i = 0; i < lines.length; i++) {
3384
- const line = lines[i];
3385
- this.starts[i] = acc;
3386
- const isAscii = !NON_ASCII.test(line);
3387
- this.ascii[i] = isAscii;
3388
- acc += (isAscii ? line.length : utf8Len(line)) + 1;
3506
+ function resolveWithinSession(input, session, env, deps) {
3507
+ if (typeof input === "number") return {
3508
+ seed: input,
3509
+ origin: "option"
3510
+ };
3511
+ if (typeof input === "string" && input !== "git") return {
3512
+ seed: input,
3513
+ origin: "option"
3514
+ };
3515
+ if (input === "git") {
3516
+ const head = (deps.gitHead ?? gitHead)();
3517
+ if (head) return {
3518
+ seed: head,
3519
+ origin: "git"
3520
+ };
3521
+ if (!session.gitFallbackWarned) {
3522
+ session.gitFallbackWarned = true;
3523
+ (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
3389
3524
  }
3390
- this.totalBytes = lines.length === 0 ? 0 : acc - 1;
3391
3525
  }
3392
- byteOf(line, col) {
3393
- if (line < 0 || line >= this.lines.length) return this.totalBytes;
3394
- const text = this.lines[line];
3395
- const clamped = col < 0 ? 0 : col < text.length ? col : text.length;
3396
- if (this.ascii[line]) return this.starts[line] + clamped;
3397
- let table = this.tables[line];
3526
+ const fromEnv = env[SEED_ENV_VAR];
3527
+ if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3528
+ seed: parseSeedValue(fromEnv),
3529
+ origin: "env"
3530
+ };
3531
+ if (session.seed !== void 0) return {
3532
+ seed: session.seed,
3533
+ origin: "session"
3534
+ };
3535
+ return {
3536
+ seed: (deps.randomSeed ?? randomSeed)(),
3537
+ origin: "fresh"
3538
+ };
3539
+ }
3540
+ function resolveBuildSeed(input, scope, deps = {}) {
3541
+ const env = deps.env ?? process.env;
3542
+ const session = openGeneration(scope.root, scope.leg);
3543
+ const { seed, origin } = resolveWithinSession(input, session, env, deps);
3544
+ if (origin === "env" || origin === "fresh") session.seed = seed;
3545
+ if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3546
+ const value = String(seed);
3547
+ env[SEED_ENV_VAR] = value;
3548
+ const stale = ownEnvExports.findIndex((e) => e.env === env);
3549
+ if (stale >= 0) ownEnvExports.splice(stale, 1);
3550
+ ownEnvExports.push({
3551
+ env,
3552
+ value
3553
+ });
3554
+ }
3555
+ const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3556
+ session.resolvedByLeg.set(scope.leg, seed);
3557
+ return {
3558
+ seed,
3559
+ origin,
3560
+ legs: [...session.legs],
3561
+ generation: session.generation,
3562
+ mismatch: prior && session.generation === 1 ? {
3563
+ leg: prior[0],
3564
+ seed: prior[1]
3565
+ } : null
3566
+ };
3567
+ }
3568
+
3569
+ //#endregion
3570
+ //#region src/telemetry.ts
3571
+ const API_URL_ENV_VAR$1 = "AFTERPACK_API_URL";
3572
+ const DEFAULT_API_URL = "https://api.afterpack.dev";
3573
+ const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3574
+ const TELEMETRY_PAYLOAD_VERSION = 1;
3575
+ const TELEMETRY_TIMEOUT_MS = 1500;
3576
+ const INSTALL_ID_ROTATION_DAYS = 30;
3577
+ const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3578
+ const TELEMETRY_STATE_FILE = (0, node_path.join)((0, node_os.homedir)(), ".afterpack", "telemetry.json");
3579
+ const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3580
+ const DATA_FIELD_WHITELIST = {
3581
+ outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3582
+ parseError: ["parserErrorKind"],
3583
+ engineBug: [
3584
+ "phase",
3585
+ "transform",
3586
+ "nodeKind"
3587
+ ],
3588
+ inflationBudget: [
3589
+ "target",
3590
+ "achieved",
3591
+ "budgetRatio",
3592
+ "inflationRatio"
3593
+ ],
3594
+ configParse: [
3595
+ "category",
3596
+ "line",
3597
+ "column"
3598
+ ]
3599
+ };
3600
+ function resolveTelemetryEnabled(option, env = {}) {
3601
+ if (option !== void 0) return option;
3602
+ return !(env.NODE_ENV === "test" || env.VITEST);
3603
+ }
3604
+ const FRAMEWORK_ENTRIES = [
3605
+ {
3606
+ label: "afterpack",
3607
+ name: "cli"
3608
+ },
3609
+ {
3610
+ label: "afterpack-angular",
3611
+ name: "angular",
3612
+ pkg: "@angular/core"
3613
+ },
3614
+ {
3615
+ label: "afterpack-esbuild",
3616
+ name: "esbuild",
3617
+ pkg: "esbuild"
3618
+ },
3619
+ {
3620
+ label: "afterpack-next",
3621
+ name: "next",
3622
+ pkg: "next"
3623
+ },
3624
+ {
3625
+ label: "afterpack-rollup",
3626
+ name: "rollup",
3627
+ pkg: "rollup"
3628
+ },
3629
+ {
3630
+ label: "afterpack-vite",
3631
+ name: "vite",
3632
+ pkg: "vite"
3633
+ },
3634
+ {
3635
+ label: "afterpack-webpack",
3636
+ name: "webpack",
3637
+ pkg: "webpack"
3638
+ }
3639
+ ];
3640
+ const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3641
+ const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3642
+ function frameworkFromLabel(label) {
3643
+ return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
3644
+ }
3645
+ const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3646
+ function detectFrameworkVersion(projectRoot, framework) {
3647
+ const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3648
+ if (!pkgName) return null;
3649
+ let deps;
3650
+ try {
3651
+ const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(projectRoot, "package.json"), "utf8"));
3652
+ deps = {
3653
+ ...pkg.dependencies,
3654
+ ...pkg.devDependencies
3655
+ };
3656
+ } catch {
3657
+ return null;
3658
+ }
3659
+ const raw = deps[pkgName];
3660
+ if (typeof raw !== "string") return null;
3661
+ const range = raw.trim();
3662
+ return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3663
+ }
3664
+ function complexityLabel(preset, complexity) {
3665
+ if (preset !== void 0) return preset;
3666
+ return complexity === void 0 ? "default" : "custom";
3667
+ }
3668
+ const FILE_COUNT_BUCKETS = [
3669
+ 1,
3670
+ 5,
3671
+ 20,
3672
+ 100,
3673
+ 500,
3674
+ 2e3
3675
+ ];
3676
+ function fileCountBucket(count) {
3677
+ if (!Number.isFinite(count) || count <= 0) return "0";
3678
+ let lower = 1;
3679
+ for (const upper of FILE_COUNT_BUCKETS) {
3680
+ if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3681
+ lower = upper + 1;
3682
+ }
3683
+ return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
3684
+ }
3685
+ const DURATION_BUCKETS_MS = [
3686
+ [1e3, "<1s"],
3687
+ [5e3, "1-5s"],
3688
+ [15e3, "5-15s"],
3689
+ [6e4, "15-60s"],
3690
+ [3e5, "60-300s"]
3691
+ ];
3692
+ function durationBucket(ms) {
3693
+ if (!Number.isFinite(ms) || ms < 0) return "unknown";
3694
+ for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3695
+ return "300s+";
3696
+ }
3697
+ function safeScalar(value) {
3698
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
3699
+ if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
3700
+ return null;
3701
+ }
3702
+ function telemetrySafeData(data) {
3703
+ if (!data || typeof data.kind !== "string") return null;
3704
+ const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3705
+ if (kind === null) return null;
3706
+ const out = { kind };
3707
+ for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3708
+ const value = safeScalar(data[field]);
3709
+ if (value !== null) out[field] = value;
3710
+ }
3711
+ return out;
3712
+ }
3713
+ function telemetrySafeSpan(d) {
3714
+ const span = d.span;
3715
+ if (!span) return null;
3716
+ const start = safeScalar(span.startByte);
3717
+ const end = safeScalar(span.endByte);
3718
+ if (typeof start !== "number" || typeof end !== "number") return null;
3719
+ if (start < 0 || end < 0) return null;
3720
+ return {
3721
+ startByte: start,
3722
+ endByte: end
3723
+ };
3724
+ }
3725
+ function telemetrySafeDiagnostic(d, severity) {
3726
+ return {
3727
+ code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3728
+ severity,
3729
+ span: telemetrySafeSpan(d),
3730
+ data: telemetrySafeData(d.data)
3731
+ };
3732
+ }
3733
+ function buildTelemetryPayload(facts, ctx) {
3734
+ let errorCount = 0;
3735
+ let criticalCount = 0;
3736
+ const alerting = [];
3737
+ for (const d of facts.diagnostics) {
3738
+ if (d.severity !== "error" && d.severity !== "critical") continue;
3739
+ if (d.severity === "critical") criticalCount += 1;
3740
+ else errorCount += 1;
3741
+ alerting.push(telemetrySafeDiagnostic(d, d.severity));
3742
+ }
3743
+ if (alerting.length === 0) return null;
3744
+ const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3745
+ const env = ctx.env ?? {};
3746
+ const runtime = ctx.runtime ?? {
3747
+ node: process.versions.node,
3748
+ platform: process.platform,
3749
+ arch: process.arch
3750
+ };
3751
+ const framework = frameworkFromLabel(facts.label);
3752
+ return {
3753
+ version: TELEMETRY_PAYLOAD_VERSION,
3754
+ installId: ctx.installId,
3755
+ framework,
3756
+ frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3757
+ engineVersion: safeVersion(facts.engineVersion),
3758
+ clientVersion: safeVersion(facts.clientVersion),
3759
+ nodeVersion: safeVersion(runtime.node) ?? "unknown",
3760
+ os: safeToken(runtime.platform),
3761
+ arch: safeToken(runtime.arch),
3762
+ ci: env.CI === "true",
3763
+ complexity: complexityLabel(facts.preset, facts.complexity),
3764
+ fileCountBucket: fileCountBucket(facts.fileCount),
3765
+ durationBucket: durationBucket(facts.durationMs),
3766
+ diagnostics: kept,
3767
+ errorCount,
3768
+ criticalCount,
3769
+ droppedCount: alerting.length - kept.length
3770
+ };
3771
+ }
3772
+ const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
3773
+ function safeVersion(value) {
3774
+ return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
3775
+ }
3776
+ function safeToken(value) {
3777
+ return TOKEN_PATTERN.test(value) ? value : "unknown";
3778
+ }
3779
+ const TELEMETRY_NOTICE = [
3780
+ "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
3781
+ "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
3782
+ "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
3783
+ "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
3784
+ "AfterPack: file counts and durations, and a random install id that rotates every 30",
3785
+ "AfterPack: days.",
3786
+ "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
3787
+ "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
3788
+ "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
3789
+ "AfterPack: `telemetry: { enabled: false }` in your config.",
3790
+ "AfterPack: https://www.afterpack.dev/privacy"
3791
+ ];
3792
+ const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3793
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3794
+ function readState(file, now) {
3795
+ try {
3796
+ const parsed = JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
3797
+ if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
3798
+ installId: parsed.installId,
3799
+ rotatedAt: parsed.rotatedAt,
3800
+ noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
3801
+ };
3802
+ } catch {}
3803
+ return {
3804
+ installId: (0, node_crypto.randomUUID)(),
3805
+ rotatedAt: now,
3806
+ noticeShownAt: 0
3807
+ };
3808
+ }
3809
+ function writeState(file, state) {
3810
+ try {
3811
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
3812
+ (0, node_fs.writeFileSync)(file, `${JSON.stringify(state)}\n`, "utf8");
3813
+ } catch {}
3814
+ }
3815
+ function telemetryUrl(env) {
3816
+ const base = (env[API_URL_ENV_VAR$1] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3817
+ return `${base}${TELEMETRY_ENDPOINT_PATH}`;
3818
+ }
3819
+ const TELEMETRY_BODY_LIMIT = 64 * 1024;
3820
+ async function reportTelemetryNotices(response, logger) {
3821
+ if (!response || response.status !== 202 || typeof response.text !== "function") return;
3822
+ const declared = Number(response.headers?.get?.("content-length"));
3823
+ if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
3824
+ await response.body?.cancel().catch(() => {});
3825
+ return;
3826
+ }
3827
+ const text = await response.text();
3828
+ if (text.length > TELEMETRY_BODY_LIMIT) return;
3829
+ let body;
3830
+ try {
3831
+ body = JSON.parse(text);
3832
+ } catch {
3833
+ return;
3834
+ }
3835
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
3836
+ reportNotices(body.notices, logger);
3837
+ }
3838
+ function createTelemetryReporter(deps = {}) {
3839
+ const env = deps.env ?? process.env;
3840
+ const logger = deps.logger ?? console;
3841
+ const now = deps.now ?? Date.now;
3842
+ const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
3843
+ const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
3844
+ return async (facts) => {
3845
+ try {
3846
+ const at = now();
3847
+ const state = readState(stateFile, at);
3848
+ let dirty = false;
3849
+ if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
3850
+ state.installId = (0, node_crypto.randomUUID)();
3851
+ state.rotatedAt = at;
3852
+ dirty = true;
3853
+ }
3854
+ if (state.noticeShownAt === 0) {
3855
+ for (const line of TELEMETRY_NOTICE) logger.log(line);
3856
+ state.noticeShownAt = at;
3857
+ dirty = true;
3858
+ }
3859
+ if (dirty) writeState(stateFile, state);
3860
+ if (facts === null) return;
3861
+ const payload = buildTelemetryPayload(facts, {
3862
+ installId: state.installId,
3863
+ env
3864
+ });
3865
+ if (payload === null) return;
3866
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3867
+ if (typeof fetchImpl !== "function") return;
3868
+ const response = await fetchImpl(telemetryUrl(env), {
3869
+ method: "POST",
3870
+ headers: { "content-type": "application/json" },
3871
+ body: JSON.stringify(payload),
3872
+ signal: AbortSignal.timeout(timeoutMs)
3873
+ });
3874
+ await reportTelemetryNotices(response, logger);
3875
+ } catch {}
3876
+ };
3877
+ }
3878
+
3879
+ //#endregion
3880
+ //#region src/hash-salt.ts
3881
+ const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3882
+ const VERSION_ENDPOINT_PATH = "/v1/version";
3883
+ const VERSION_PROBE_TIMEOUT_MS = 2e3;
3884
+ function canonical(value) {
3885
+ if (Array.isArray(value)) return value.map(canonical);
3886
+ if (value === null || typeof value !== "object") return value;
3887
+ const out = {};
3888
+ for (const key of Object.keys(value).sort()) {
3889
+ const item = value[key];
3890
+ if (item !== void 0) out[key] = canonical(item);
3891
+ }
3892
+ return out;
3893
+ }
3894
+ function afterpackHashSalt(input) {
3895
+ const payload = JSON.stringify(canonical({
3896
+ salt: "afterpack-output-name/1",
3897
+ seed: String(input.seed),
3898
+ engineVersion: input.engine.engineVersion,
3899
+ nonce: input.engine.nonce,
3900
+ cloud: input.engine.cloud,
3901
+ settings: input.settings
3902
+ }));
3903
+ return (0, node_crypto.createHash)("sha256").update(payload).digest("hex").slice(0, 32);
3904
+ }
3905
+ function isCloudBuild(env) {
3906
+ const key = env.AFTERPACK_KEY;
3907
+ return typeof key === "string" && key.trim() !== "";
3908
+ }
3909
+ function versionEndpoint(env) {
3910
+ const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
3911
+ return `${base}${VERSION_ENDPOINT_PATH}`;
3912
+ }
3913
+ async function resolveSaltEngine(env, localEngineVersion, deps = {}) {
3914
+ if (!isCloudBuild(env)) return {
3915
+ engineVersion: localEngineVersion,
3916
+ nonce: null,
3917
+ cloud: false,
3918
+ probedCloudVersion: null,
3919
+ probeFailed: false
3920
+ };
3921
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3922
+ let probed = null;
3923
+ if (typeof fetchImpl === "function") try {
3924
+ const response = await fetchImpl(versionEndpoint(env), { signal: AbortSignal.timeout(deps.timeoutMs ?? VERSION_PROBE_TIMEOUT_MS) });
3925
+ if (response.ok) {
3926
+ const body = await response.json();
3927
+ if (typeof body.engineVersion === "string" && body.engineVersion !== "") probed = body.engineVersion;
3928
+ }
3929
+ } catch {
3930
+ probed = null;
3931
+ }
3932
+ if (probed === null) return {
3933
+ engineVersion: null,
3934
+ nonce: (0, node_crypto.randomUUID)(),
3935
+ cloud: true,
3936
+ probedCloudVersion: null,
3937
+ probeFailed: true
3938
+ };
3939
+ return {
3940
+ engineVersion: probed,
3941
+ nonce: null,
3942
+ cloud: true,
3943
+ probedCloudVersion: probed,
3944
+ probeFailed: false
3945
+ };
3946
+ }
3947
+ 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.";
3948
+ function saltSettings(settings, extra = {}) {
3949
+ const { seed: _seed, diagnostics: _diagnostics, artifactOptions, engineConfig,...rest } = settings;
3950
+ const { git: _git, telemetry: _telemetry,...output } = artifactOptions ?? {};
3951
+ const { seed: _engineSeed,...engine } = engineConfig ?? {};
3952
+ return {
3953
+ ...rest,
3954
+ engineConfig: engine,
3955
+ artifactOptions: output,
3956
+ ...extra
3957
+ };
3958
+ }
3959
+ function reportPolicySaltBits(env, artifactOptions, hasBundlerSourcemap) {
3960
+ const policy = resolveReportPolicy(env, artifactOptions ?? {}, { hasBundlerSourcemap });
3961
+ return {
3962
+ sourceMap: policy.sourceMap,
3963
+ emitSourceMappingURL: policy.emitSourceMappingURL
3964
+ };
3965
+ }
3966
+ async function prepareHashSalt(input) {
3967
+ const env = input.env ?? process.env;
3968
+ const resolvedSeed = resolveBuildSeed(input.seed, {
3969
+ root: input.root,
3970
+ leg: input.leg
3971
+ }, {
3972
+ env,
3973
+ warn: input.warn
3974
+ });
3975
+ const engine = await resolveSaltEngine(env, input.localEngineVersion, { fetchImpl: input.fetchImpl });
3976
+ if (engine.probeFailed) input.warn?.(PROBE_FAILED_WARNING);
3977
+ return {
3978
+ resolvedSeed,
3979
+ engine,
3980
+ salt: afterpackHashSalt({
3981
+ seed: resolvedSeed.seed,
3982
+ engine,
3983
+ settings: input.settings
3984
+ })
3985
+ };
3986
+ }
3987
+ async function readEngineVersion(engine) {
3988
+ try {
3989
+ return await engine.version?.() ?? null;
3990
+ } catch {
3991
+ return null;
3992
+ }
3993
+ }
3994
+ function cloudEngineMismatch(engine, batchEngineVersion) {
3995
+ if (!engine.cloud || engine.probedCloudVersion === null) return null;
3996
+ if (batchEngineVersion === null) return null;
3997
+ if (batchEngineVersion === engine.probedCloudVersion) return null;
3998
+ 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.`;
3999
+ }
4000
+
4001
+ //#endregion
4002
+ //#region src/git.ts
4003
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
4004
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
4005
+ function sanitizeCommitSha(value) {
4006
+ if (typeof value !== "string") return null;
4007
+ const sha = value.trim().toLowerCase();
4008
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
4009
+ }
4010
+ function sanitizeGitRef(value) {
4011
+ if (typeof value !== "string") return null;
4012
+ const ref = value.trim();
4013
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
4014
+ }
4015
+ function contextFrom(rawSha, rawRef) {
4016
+ const commitSha = sanitizeCommitSha(rawSha);
4017
+ const ref = sanitizeGitRef(rawRef);
4018
+ if (commitSha === null && ref === null) return null;
4019
+ const context = {};
4020
+ if (commitSha !== null) context.commitSha = commitSha;
4021
+ if (ref !== null) context.ref = ref;
4022
+ return context;
4023
+ }
4024
+ const CI_SOURCES = [
4025
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
4026
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
4027
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
4028
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
4029
+ ["GIT_COMMIT", "BRANCH_NAME"]
4030
+ ];
4031
+ function ciGitContext(env) {
4032
+ for (const [shaVar, refVar] of CI_SOURCES) {
4033
+ const context = contextFrom(env[shaVar], env[refVar]);
4034
+ if (context !== null) return context;
4035
+ }
4036
+ return null;
4037
+ }
4038
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
4039
+ function localGitContext(cwd) {
4040
+ let lines;
4041
+ try {
4042
+ const out = (0, node_child_process.execFileSync)("git", [
4043
+ "rev-parse",
4044
+ "HEAD",
4045
+ "--abbrev-ref",
4046
+ "HEAD"
4047
+ ], {
4048
+ cwd,
4049
+ stdio: [
4050
+ "ignore",
4051
+ "pipe",
4052
+ "ignore"
4053
+ ],
4054
+ timeout: GIT_PROBE_TIMEOUT_MS,
4055
+ maxBuffer: 64 * 1024
4056
+ }).toString();
4057
+ lines = out.split("\n").map((line) => line.trim());
4058
+ } catch {
4059
+ return null;
4060
+ }
4061
+ const ref = lines[1] === "HEAD" ? null : lines[1];
4062
+ return contextFrom(lines[0], ref);
4063
+ }
4064
+ function detectGitContext(explicit, deps = {}) {
4065
+ if (explicit) {
4066
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
4067
+ if (declared !== null) return declared;
4068
+ }
4069
+ const ci = ciGitContext(deps.env ?? process.env);
4070
+ if (ci !== null) return ci;
4071
+ return (deps.localGit ?? localGitContext)(deps.cwd);
4072
+ }
4073
+
4074
+ //#endregion
4075
+ //#region src/hashed-names.ts
4076
+ const LOWER_HEX = "0123456789abcdef";
4077
+ const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
4078
+ const UPPER_ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
4079
+ const LOWER_ALNUM = "0123456789abcdefghijklmnopqrstuvwxyz";
4080
+ const ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4081
+ const MIN_TOKEN_LENGTH = 6;
4082
+ const BINARY_EXTENSIONS = new Set([
4083
+ ".png",
4084
+ ".jpg",
4085
+ ".jpeg",
4086
+ ".gif",
4087
+ ".webp",
4088
+ ".avif",
4089
+ ".ico",
4090
+ ".bmp",
4091
+ ".woff",
4092
+ ".woff2",
4093
+ ".ttf",
4094
+ ".otf",
4095
+ ".eot",
4096
+ ".wasm",
4097
+ ".gz",
4098
+ ".br",
4099
+ ".zst",
4100
+ ".zip",
4101
+ ".pdf",
4102
+ ".mp3",
4103
+ ".mp4",
4104
+ ".webm",
4105
+ ".ogg",
4106
+ ".wav",
4107
+ ".pack"
4108
+ ]);
4109
+ function alphabetOf(token) {
4110
+ if (/^[0-9a-f]+$/.test(token)) return LOWER_HEX;
4111
+ if (/^[A-Z2-7]+$/.test(token)) return BASE32;
4112
+ if (/^[0-9A-Z]+$/.test(token)) return UPPER_ALNUM;
4113
+ if (/^[0-9a-z~._-]+$/.test(token)) return LOWER_ALNUM;
4114
+ return ALNUM;
4115
+ }
4116
+ function regionsKey(regions) {
4117
+ return regions && regions.length > 0 ? JSON.stringify(regions) : "";
4118
+ }
4119
+ function deriveHashToken(token, salt, regions = "") {
4120
+ const alphabet = alphabetOf(token);
4121
+ let out = "";
4122
+ for (let round = 0; out.length < token.length; round++) {
4123
+ const bytes = (0, node_crypto.createHash)("sha256").update(`${salt}\0${token}\0${regions}\0${round}`).digest();
4124
+ for (const byte of bytes) {
4125
+ if (out.length === token.length) break;
4126
+ out += alphabet[byte % alphabet.length];
4127
+ }
4128
+ }
4129
+ return out;
4130
+ }
4131
+ function escapeRegExp$1(text) {
4132
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4133
+ }
4134
+ function tokenPattern(tokens) {
4135
+ const list = [...tokens].sort((a, b) => b.length - a.length || (a < b ? -1 : 1));
4136
+ if (list.length === 0) return null;
4137
+ return new RegExp(`(?<![A-Za-z0-9])(?:${list.map(escapeRegExp$1).join("|")})(?![A-Za-z0-9])`, "g");
4138
+ }
4139
+ function toPosix$1(path) {
4140
+ return node_path.sep === "/" ? path : path.split(node_path.sep).join("/");
4141
+ }
4142
+ function readText(path) {
4143
+ let bytes;
4144
+ try {
4145
+ bytes = (0, node_fs.readFileSync)(path);
4146
+ } catch {
4147
+ return null;
4148
+ }
4149
+ if (bytes.subarray(0, 8192).includes(0)) return null;
4150
+ try {
4151
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
4152
+ } catch {
4153
+ return null;
4154
+ }
4155
+ }
4156
+ function listFiles(root, skip) {
4157
+ const out = [];
4158
+ const walk$1 = (dir) => {
4159
+ let entries;
4160
+ try {
4161
+ entries = (0, node_fs.readdirSync)(dir, { withFileTypes: true });
4162
+ } catch {
4163
+ return;
4164
+ }
4165
+ for (const entry of entries) {
4166
+ const full = (0, node_path.join)(dir, entry.name);
4167
+ const rel = toPosix$1((0, node_path.relative)(root, full));
4168
+ if (entry.name === AFTERPACK_DIR || entry.name === "node_modules" || skip(rel)) continue;
4169
+ if (entry.isDirectory()) walk$1(full);
4170
+ else if (entry.isFile()) out.push(full);
4171
+ }
4172
+ };
4173
+ walk$1(root);
4174
+ return out;
4175
+ }
4176
+ function isCandidate(path) {
4177
+ const name = (0, node_path.basename)(path).toLowerCase();
4178
+ if (name.endsWith(".map")) return false;
4179
+ const dot = name.lastIndexOf(".");
4180
+ return dot < 0 || !BINARY_EXTENSIONS.has(name.slice(dot));
4181
+ }
4182
+ function writableDir(dir) {
4183
+ try {
4184
+ (0, node_fs.accessSync)(dir, node_fs.constants.W_OK);
4185
+ return true;
4186
+ } catch {
4187
+ return false;
4188
+ }
4189
+ }
4190
+ function planHashedNames(input) {
4191
+ const { root, tokenOf } = input.options;
4192
+ const skip = input.options.skip ?? (() => false);
4193
+ const tokens = new Map();
4194
+ const tokenOfPath = (path) => {
4195
+ const rel = toPosix$1((0, node_path.relative)(root, path));
4196
+ if (rel.startsWith("..")) return null;
4197
+ const token = tokenOf(rel);
4198
+ if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
4199
+ return (0, node_path.basename)(path).includes(token) ? token : null;
4200
+ };
4201
+ const addToken = (token, regions) => {
4202
+ if (tokens.has(token)) return false;
4203
+ tokens.set(token, deriveHashToken(token, input.salt, regionsKey(regions)));
4204
+ return true;
4205
+ };
4206
+ for (const [path, { regions }] of input.inputs) {
4207
+ const token = tokenOfPath(path);
4208
+ if (token !== null) addToken(token, regions);
4209
+ }
4210
+ const others = new Map();
4211
+ if (tokens.size > 0) for (const path of listFiles(root, skip)) {
4212
+ if (input.inputs.has(path) || !isCandidate(path)) continue;
4213
+ const text = readText(path);
4214
+ if (text !== null) others.set(path, text);
4215
+ }
4216
+ const changed = new Set();
4217
+ let grew = tokens.size > 0;
4218
+ while (grew) {
4219
+ grew = false;
4220
+ const pattern$1 = tokenPattern(tokens.keys());
4221
+ if (pattern$1 === null) break;
4222
+ for (const [path, text] of others) {
4223
+ if (changed.has(path)) continue;
4224
+ pattern$1.lastIndex = 0;
4225
+ if (!pattern$1.test(text)) continue;
4226
+ changed.add(path);
4227
+ const token = tokenOfPath(path);
4228
+ if (token !== null && addToken(token)) grew = true;
4229
+ }
4230
+ }
4231
+ const pattern = tokenPattern(tokens.keys());
4232
+ const rewrite = (text) => pattern === null ? text : text.replace(pattern, (token) => tokens.get(token) ?? token);
4233
+ const renamedPath = (path) => {
4234
+ const token = tokenOfPath(path);
4235
+ if (token === null || !tokens.has(token)) return path;
4236
+ const name = (0, node_path.basename)(path);
4237
+ const at = name.lastIndexOf(token);
4238
+ return (0, node_path.join)((0, node_path.dirname)(path), `${name.slice(0, at)}${tokens.get(token)}${name.slice(at + token.length)}`);
4239
+ };
4240
+ const renamed = new Map();
4241
+ for (const path of input.inputs.keys()) {
4242
+ const next = renamedPath(path);
4243
+ if (next !== path) renamed.set(path, next);
4244
+ }
4245
+ const writes = [];
4246
+ for (const path of changed) {
4247
+ const to = renamedPath(path);
4248
+ if (to !== path) renamed.set(path, to);
4249
+ writes.push({
4250
+ from: path,
4251
+ to,
4252
+ text: rewrite(others.get(path))
4253
+ });
4254
+ }
4255
+ const preflight = () => {
4256
+ const unwritable = new Set();
4257
+ for (const [from, to] of renamed) {
4258
+ if (!writableDir((0, node_path.dirname)(from))) unwritable.add((0, node_path.dirname)(from));
4259
+ if (!writableDir((0, node_path.dirname)(to))) unwritable.add((0, node_path.dirname)(to));
4260
+ }
4261
+ for (const write of writes) if (!writableDir((0, node_path.dirname)(write.to))) unwritable.add((0, node_path.dirname)(write.to));
4262
+ if (unwritable.size > 0) throw new Error(`cannot rename content-hashed files: these directories are not writable: ${[...unwritable].sort().join(", ")}`);
4263
+ };
4264
+ return {
4265
+ tokens,
4266
+ renamed,
4267
+ rewrite,
4268
+ preflight,
4269
+ apply() {
4270
+ preflight();
4271
+ for (const write of writes) {
4272
+ const tmp = `${write.to}.afterpack-tmp`;
4273
+ (0, node_fs.writeFileSync)(tmp, write.text);
4274
+ (0, node_fs.renameSync)(tmp, write.to);
4275
+ if (write.to !== write.from) (0, node_fs.rmSync)(write.from, { force: true });
4276
+ }
4277
+ }
4278
+ };
4279
+ }
4280
+
4281
+ //#endregion
4282
+ //#region src/map-color.ts
4283
+ const UTF8 = new TextEncoder();
4284
+ const utf8Len = (s) => UTF8.encode(s).length;
4285
+ const NON_ASCII = /[\u0080-\uFFFF]/;
4286
+ const HIGH_SURROGATE_START = 55296;
4287
+ const HIGH_SURROGATE_END = 56319;
4288
+ const LOW_SURROGATE_START = 56320;
4289
+ const LOW_SURROGATE_END = 57343;
4290
+ function charToByteTable(line) {
4291
+ const table = new Array(line.length + 1);
4292
+ let bytes = 0;
4293
+ let i = 0;
4294
+ while (i < line.length) {
4295
+ table[i] = bytes;
4296
+ const code = line.charCodeAt(i);
4297
+ if (code < 128) {
4298
+ bytes += 1;
4299
+ i += 1;
4300
+ continue;
4301
+ }
4302
+ if (code < 2048) {
4303
+ bytes += 2;
4304
+ i += 1;
4305
+ continue;
4306
+ }
4307
+ if (code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END && i + 1 < line.length) {
4308
+ const low = line.charCodeAt(i + 1);
4309
+ if (low >= LOW_SURROGATE_START && low <= LOW_SURROGATE_END) {
4310
+ table[i + 1] = bytes + 3;
4311
+ bytes += 4;
4312
+ i += 2;
4313
+ continue;
4314
+ }
4315
+ }
4316
+ bytes += 3;
4317
+ i += 1;
4318
+ }
4319
+ table[line.length] = bytes;
4320
+ return table;
4321
+ }
4322
+ var ChunkByteIndex = class {
4323
+ starts;
4324
+ ascii;
4325
+ tables;
4326
+ totalBytes;
4327
+ constructor(lines) {
4328
+ this.lines = lines;
4329
+ this.starts = new Array(lines.length);
4330
+ this.ascii = new Array(lines.length);
4331
+ this.tables = new Array(lines.length).fill(null);
4332
+ let acc = 0;
4333
+ for (let i = 0; i < lines.length; i++) {
4334
+ const line = lines[i];
4335
+ this.starts[i] = acc;
4336
+ const isAscii = !NON_ASCII.test(line);
4337
+ this.ascii[i] = isAscii;
4338
+ acc += (isAscii ? line.length : utf8Len(line)) + 1;
4339
+ }
4340
+ this.totalBytes = lines.length === 0 ? 0 : acc - 1;
4341
+ }
4342
+ byteOf(line, col) {
4343
+ if (line < 0 || line >= this.lines.length) return this.totalBytes;
4344
+ const text = this.lines[line];
4345
+ const clamped = col < 0 ? 0 : col < text.length ? col : text.length;
4346
+ if (this.ascii[line]) return this.starts[line] + clamped;
4347
+ let table = this.tables[line];
3398
4348
  if (table === null) {
3399
4349
  table = charToByteTable(text);
3400
4350
  this.tables[line] = table;
@@ -3525,7 +4475,8 @@ function coverGenerated(segments$1, start, end, index) {
3525
4475
 
3526
4476
  //#endregion
3527
4477
  //#region src/receipt.ts
3528
- const PROTECTION_RECEIPT_FILE = ".afterpack-protection.json";
4478
+ const PROTECTION_RECEIPTS_DIR = "receipts";
4479
+ const STALE_OUTPUT_RECEIPT_FILE = ".afterpack-protection.json";
3529
4480
  const PROTECTION_RECEIPT_SCHEMA = 1;
3530
4481
  function sha256OfBytes(bytes) {
3531
4482
  return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex");
@@ -3536,6 +4487,93 @@ function sha256Of(path) {
3536
4487
  function receiptPathOf(dir, file) {
3537
4488
  return (0, node_path.relative)(dir, file).split(node_path.sep).join("/");
3538
4489
  }
4490
+ const MAX_KEY_BYTES = 180;
4491
+ const HASHED_KEY_PREFIX_BYTES = 120;
4492
+ function buildDirOf(home) {
4493
+ const rel = (0, node_path.relative)(home.projectRoot, home.buildDir).split(node_path.sep).join("/");
4494
+ return rel === "" ? "." : rel;
4495
+ }
4496
+ function receiptKey(buildDir) {
4497
+ const encoded = encodeURIComponent(buildDir).replace(/\*/g, "%2A").replace(/~/g, "%7E");
4498
+ if (Buffer.byteLength(encoded) <= MAX_KEY_BYTES) return encoded;
4499
+ const prefix = encoded.slice(0, HASHED_KEY_PREFIX_BYTES).replace(/%[0-9A-F]?$/, "");
4500
+ const digest = (0, node_crypto.createHash)("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4501
+ return `${prefix}~${digest}`;
4502
+ }
4503
+ function receiptsDirOf(home) {
4504
+ return (0, node_path.join)(home.dir, PROTECTION_RECEIPTS_DIR);
4505
+ }
4506
+ function receiptPathIn(home) {
4507
+ return (0, node_path.join)(receiptsDirOf(home), `${receiptKey(buildDirOf(home))}.json`);
4508
+ }
4509
+ function homeOf(target) {
4510
+ return typeof target === "string" ? afterpackHome(target) : target;
4511
+ }
4512
+ function protectionReceiptPath(target) {
4513
+ return receiptPathIn(homeOf(target));
4514
+ }
4515
+ function prepareProtectionReceipt(target, label) {
4516
+ const home = homeOf(target);
4517
+ const path = receiptPathIn(home);
4518
+ try {
4519
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
4520
+ ensureAfterpackGitignore(home.dir);
4521
+ const existed = (0, node_fs.existsSync)(path);
4522
+ (0, node_fs.closeSync)((0, node_fs.openSync)(path, "a"));
4523
+ if (!existed) (0, node_fs.unlinkSync)(path);
4524
+ } catch (error) {
4525
+ throw new AfterpackFilesError(DIAG_RECEIPT_UNWRITABLE, `[${label}] cannot write the protection receipt ${path}, so no file was rewritten: ${error}`, `Make ${(0, node_path.dirname)(path)} a writable directory, then build again.`);
4526
+ }
4527
+ return path;
4528
+ }
4529
+ function entriesOf(dir) {
4530
+ try {
4531
+ return (0, node_fs.readdirSync)(dir, { withFileTypes: true });
4532
+ } catch {
4533
+ return [];
4534
+ }
4535
+ }
4536
+ function removeStaleReceipt(path, label) {
4537
+ try {
4538
+ (0, node_fs.unlinkSync)(path);
4539
+ } catch (error) {
4540
+ if (error.code === "ENOENT") return;
4541
+ throw new Error(`[${label}] could not remove the stale protection receipt ${path}, refusing to ship it: ${error}`);
4542
+ }
4543
+ }
4544
+ function refuseShippedAfterpackDir(path, buildDir, label) {
4545
+ 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.`);
4546
+ }
4547
+ function sweepDir(dir, context, recursive) {
4548
+ for (const entry of entriesOf(dir)) {
4549
+ const full = (0, node_path.join)(dir, entry.name);
4550
+ if (entry.name === STALE_OUTPUT_RECEIPT_FILE) removeStaleReceipt(full, context.label);
4551
+ else if (entry.isDirectory()) {
4552
+ if (entry.name === AFTERPACK_DIR) {
4553
+ if (context.ownHome !== null && realPath(full) === context.ownHome) continue;
4554
+ refuseShippedAfterpackDir(full, context.buildDir, context.label);
4555
+ }
4556
+ if (!recursive || entry.name === "node_modules") continue;
4557
+ sweepDir(full, context, true);
4558
+ }
4559
+ }
4560
+ }
4561
+ function sweepOutputTree(buildDir, walkedDir, label, ownHome = null) {
4562
+ const context = {
4563
+ buildDir,
4564
+ label,
4565
+ ownHome: ownHome?.strong ? realPath(ownHome.dir) : null
4566
+ };
4567
+ const walksBuildDir = walkedDir !== null && realPath(walkedDir) === realPath(buildDir);
4568
+ sweepDir(buildDir, context, walksBuildDir);
4569
+ if (walkedDir !== null && !walksBuildDir) sweepDir(walkedDir, context, true);
4570
+ }
4571
+ function keptEntries(path, replaced) {
4572
+ if (!(0, node_fs.existsSync)(path)) return [];
4573
+ const previous = parseReceipt(path);
4574
+ if (previous.error !== void 0 || previous.receipt.schema !== PROTECTION_RECEIPT_SCHEMA) return [];
4575
+ return previous.receipt.files.filter((entry) => !replaced.has(entry.path));
4576
+ }
3539
4577
  function writeDeferredProtectionReceipt(deferred) {
3540
4578
  const survivingFiles = deferred.files.filter((file) => (0, node_fs.existsSync)(file));
3541
4579
  if (survivingFiles.length === 0) return null;
@@ -3555,13 +4593,22 @@ function writeProtectionReceipt(input) {
3555
4593
  seedOrigin: input.seedOrigin,
3556
4594
  bundler: input.bundler,
3557
4595
  buildId: input.buildId,
4596
+ buildDir: ".",
3558
4597
  files: input.files.map((file) => ({
3559
4598
  path: receiptPathOf(input.dir, file),
3560
4599
  sha256: sha256Of(file),
3561
4600
  transformed: transformed.has(file)
3562
4601
  })).sort((a, b) => a.path.localeCompare(b.path))
3563
4602
  };
3564
- const path = (0, node_path.join)(input.dir, PROTECTION_RECEIPT_FILE);
4603
+ const home = input.home ?? afterpackHome(input.dir);
4604
+ receipt.buildDir = buildDirOf(home);
4605
+ const path = receiptPathIn(home);
4606
+ if (input.merge) {
4607
+ const replaced = new Set(receipt.files.map((entry) => entry.path));
4608
+ receipt.files = [...keptEntries(path, replaced), ...receipt.files].sort((a, b) => a.path.localeCompare(b.path));
4609
+ }
4610
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
4611
+ ensureAfterpackGitignore(home.dir);
3565
4612
  (0, node_fs.writeFileSync)(path, `${JSON.stringify(receipt, null, 2)}\n`);
3566
4613
  return path;
3567
4614
  }
@@ -3609,8 +4656,7 @@ var UnreadableReceiptError = class extends Error {
3609
4656
  this.schema = schema;
3610
4657
  }
3611
4658
  };
3612
- function verifyProtectionReceipt(dir, expectedBuildId) {
3613
- const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
4659
+ function verifyProtectionReceipt(receiptPath, dir, expectedBuildId) {
3614
4660
  if (!(0, node_fs.existsSync)(receiptPath)) return {
3615
4661
  receiptPath,
3616
4662
  receipt: null,
@@ -3642,152 +4688,93 @@ function verifyProtectionReceipt(dir, expectedBuildId) {
3642
4688
  problems
3643
4689
  };
3644
4690
  }
3645
- function findReceiptDir(startDir) {
3646
- const receiptPath = findUpward(startDir, PROTECTION_RECEIPT_FILE);
3647
- return receiptPath ? (0, node_path.dirname)(receiptPath) : null;
3648
- }
3649
- function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
3650
- const dir = findReceiptDir(startDir);
3651
- if (!dir) return null;
3652
- const receiptPath = (0, node_path.join)(dir, PROTECTION_RECEIPT_FILE);
3653
- const result = parseReceipt(receiptPath);
3654
- if (result.error !== void 0) {
3655
- const schema = result.newerSchema;
3656
- if (schema === null) return null;
3657
- throw new UnreadableReceiptError(prefix(`${receiptPath} was written by a newer AfterPack (receipt schema ${schema}), so this version cannot tell whether these files are already obfuscated — update afterpack, or rebuild from source and delete the receipt before running it again.`), receiptPath, schema);
3658
- }
3659
- const outputHashes = new Set(result.receipt.files.map((f) => f.sha256));
3660
- if (outputHashes.size === 0) return null;
3661
- const matches = files.filter((file) => {
3662
- const bytes = bytesByPath?.get(file);
3663
- if (bytes !== void 0) return outputHashes.has(sha256OfBytes(bytes));
3664
- return (0, node_fs.existsSync)(file) && outputHashes.has(sha256Of(file));
3665
- });
3666
- return matches.length > 0 ? {
3667
- receiptPath,
3668
- files: matches
3669
- } : null;
3670
- }
3671
-
3672
- //#endregion
3673
- //#region src/seed.ts
3674
- function randomSeed() {
3675
- const b = (0, node_crypto.randomBytes)(8);
3676
- const hi = b.readUInt32BE(0) & 2097151;
3677
- const lo = b.readUInt32BE(4);
3678
- return hi * 4294967296 + lo;
3679
- }
3680
- function gitHead() {
3681
- try {
3682
- const out = (0, node_child_process.execFileSync)("git", ["rev-parse", "HEAD"], { stdio: [
3683
- "ignore",
3684
- "pipe",
3685
- "ignore"
3686
- ] }).toString().trim();
3687
- return /^[0-9a-f]{7,64}$/i.test(out) ? out : null;
3688
- } catch {
3689
- return null;
3690
- }
3691
- }
3692
- const SEED_ENV_VAR = "AFTERPACK_SEED";
3693
- function parseSeedValue(raw) {
3694
- return /^-?\d+$/.test(raw) ? Number(raw) : raw;
3695
- }
3696
- const SEED_STATE = Symbol.for("afterpack.integration-utils.seed-sessions");
3697
- function sharedSeedState() {
3698
- const holder = globalThis;
3699
- holder[SEED_STATE] ??= {
3700
- sessions: new Map(),
3701
- ownEnvExports: []
4691
+ function receiptsIn(home) {
4692
+ const dir = receiptsDirOf(home);
4693
+ return entriesOf(dir).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => (0, node_path.join)(dir, entry.name)).sort();
4694
+ }
4695
+ function filesByName(dir) {
4696
+ const byName = new Map();
4697
+ const walk$1 = (current, rel) => {
4698
+ for (const entry of entriesOf(current)) {
4699
+ if (entry.name === "node_modules" || entry.name === AFTERPACK_DIR) continue;
4700
+ const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
4701
+ if (entry.isDirectory()) walk$1((0, node_path.join)(current, entry.name), childRel);
4702
+ else if (entry.isFile()) byName.set(entry.name, [...byName.get(entry.name) ?? [], childRel]);
4703
+ }
3702
4704
  };
3703
- return holder[SEED_STATE];
3704
- }
3705
- const { sessions, ownEnvExports } = sharedSeedState();
3706
- function isOwnEnvExport(env, value) {
3707
- return ownEnvExports.some((e) => e.env === env && e.value === value);
3708
- }
3709
- function openGeneration(root, leg) {
3710
- let session = sessions.get(root);
3711
- if (!session) {
3712
- session = {
3713
- seed: void 0,
3714
- generation: 1,
3715
- legs: [],
3716
- resolvedByLeg: new Map(),
3717
- gitFallbackWarned: false
3718
- };
3719
- sessions.set(root, session);
3720
- } else if (session.legs.includes(leg)) {
3721
- session.seed = void 0;
3722
- session.generation += 1;
3723
- session.legs = [];
3724
- session.resolvedByLeg.clear();
3725
- session.gitFallbackWarned = false;
4705
+ walk$1(dir, "");
4706
+ return byName;
4707
+ }
4708
+ function copyMatches(dir, home, skip) {
4709
+ const receipts = receiptsIn(home).filter((path) => !skip.has(path));
4710
+ if (receipts.length === 0) return [];
4711
+ const byName = filesByName(dir);
4712
+ const matches = [];
4713
+ for (const receiptPath of receipts) {
4714
+ const parsed = parseReceipt(receiptPath);
4715
+ if (parsed.error !== void 0 || parsed.receipt.files.length === 0) continue;
4716
+ const { files, buildDir } = parsed.receipt;
4717
+ const first = files[0].path;
4718
+ for (const rel of byName.get(first.split("/").pop() ?? first) ?? []) {
4719
+ if (rel !== first && !rel.endsWith(`/${first}`)) continue;
4720
+ const prefix = rel.slice(0, rel.length - first.length);
4721
+ const copyDir = (0, node_path.join)(dir, ...prefix.split("/").filter(Boolean));
4722
+ if (!files.every((entry) => (0, node_fs.existsSync)((0, node_path.join)(copyDir, entry.path)))) continue;
4723
+ matches.push({
4724
+ receiptPath,
4725
+ dir: copyDir,
4726
+ copiedFrom: typeof buildDir === "string" ? (0, node_path.join)(home.projectRoot, buildDir) : null,
4727
+ hashesMatch: files.every((entry) => sha256Of((0, node_path.join)(copyDir, entry.path)) === entry.sha256),
4728
+ prefix
4729
+ });
4730
+ }
3726
4731
  }
3727
- session.legs.push(leg);
3728
- return session;
4732
+ return matches.sort((a, b) => Number(b.hashesMatch) - Number(a.hashesMatch) || a.prefix.length - b.prefix.length || a.receiptPath.localeCompare(b.receiptPath));
3729
4733
  }
3730
- function resolveWithinSession(input, session, env, deps) {
3731
- if (typeof input === "number") return {
3732
- seed: input,
3733
- origin: "option"
4734
+ function locateProtectionReceipt(dir, options = {}) {
4735
+ const homes = [afterpackHome(dir), afterpackHome(dir, { fileTarget: true })];
4736
+ const exact = [...new Set(homes.map(receiptPathIn))];
4737
+ const found = exact.find((path) => (0, node_fs.existsSync)(path));
4738
+ if (found) return {
4739
+ receiptPath: found,
4740
+ dir,
4741
+ copiedFrom: null
3734
4742
  };
3735
- if (typeof input === "string" && input !== "git") return {
3736
- seed: input,
3737
- origin: "option"
4743
+ if (options.copies === false) return null;
4744
+ const best = copyMatches(dir, homes[0], new Set(exact))[0];
4745
+ return best ? {
4746
+ receiptPath: best.receiptPath,
4747
+ dir: best.dir,
4748
+ copiedFrom: best.copiedFrom
4749
+ } : null;
4750
+ }
4751
+ function detectAlreadyObfuscatedInputs(files, startDir, bytesByPath, prefix = (m) => m) {
4752
+ const hashOf = (file) => {
4753
+ const bytes = bytesByPath?.get(file);
4754
+ if (bytes !== void 0) return sha256OfBytes(bytes);
4755
+ return (0, node_fs.existsSync)(file) ? sha256Of(file) : null;
3738
4756
  };
3739
- if (input === "git") {
3740
- const head = (deps.gitHead ?? gitHead)();
3741
- if (head) return {
3742
- seed: head,
3743
- origin: "git"
3744
- };
3745
- if (!session.gitFallbackWarned) {
3746
- session.gitFallbackWarned = true;
3747
- (deps.warn ?? ((m) => console.warn(m)))("[afterpack] seed \"git\": no git repository / HEAD found; using a fresh random seed for this build.");
4757
+ let hashes = null;
4758
+ for (const receiptPath of receiptsIn(homeOf(startDir))) {
4759
+ const result = parseReceipt(receiptPath);
4760
+ if (result.error !== void 0) {
4761
+ const schema = result.newerSchema;
4762
+ if (schema === null) continue;
4763
+ throw new UnreadableReceiptError(prefix(`${receiptPath} was written by a newer AfterPack (receipt schema ${schema}), so this version cannot tell whether these files are already obfuscated — update afterpack, or rebuild from source and delete the receipt before running it again.`), receiptPath, schema);
3748
4764
  }
3749
- }
3750
- const fromEnv = env[SEED_ENV_VAR];
3751
- if (fromEnv != null && fromEnv !== "" && !isOwnEnvExport(env, fromEnv)) return {
3752
- seed: parseSeedValue(fromEnv),
3753
- origin: "env"
3754
- };
3755
- if (session.seed !== void 0) return {
3756
- seed: session.seed,
3757
- origin: "session"
3758
- };
3759
- return {
3760
- seed: (deps.randomSeed ?? randomSeed)(),
3761
- origin: "fresh"
3762
- };
3763
- }
3764
- function resolveBuildSeed(input, scope, deps = {}) {
3765
- const env = deps.env ?? process.env;
3766
- const session = openGeneration(scope.root, scope.leg);
3767
- const { seed, origin } = resolveWithinSession(input, session, env, deps);
3768
- if (origin === "env" || origin === "fresh") session.seed = seed;
3769
- if (origin === "fresh" && (deps.exportToEnv ?? true)) {
3770
- const value = String(seed);
3771
- env[SEED_ENV_VAR] = value;
3772
- const stale = ownEnvExports.findIndex((e) => e.env === env);
3773
- if (stale >= 0) ownEnvExports.splice(stale, 1);
3774
- ownEnvExports.push({
3775
- env,
3776
- value
4765
+ const outputHashes = new Set(result.receipt.files.filter((f) => f.transformed !== false).map((f) => f.sha256));
4766
+ if (outputHashes.size === 0) continue;
4767
+ hashes ??= new Map(files.map((file) => [file, hashOf(file)]));
4768
+ const matches = files.filter((file) => {
4769
+ const hash = hashes?.get(file);
4770
+ return hash != null && outputHashes.has(hash);
3777
4771
  });
4772
+ if (matches.length > 0) return {
4773
+ receiptPath,
4774
+ files: matches
4775
+ };
3778
4776
  }
3779
- const prior = [...session.resolvedByLeg].find(([, s]) => s !== seed);
3780
- session.resolvedByLeg.set(scope.leg, seed);
3781
- return {
3782
- seed,
3783
- origin,
3784
- legs: [...session.legs],
3785
- generation: session.generation,
3786
- mismatch: prior && session.generation === 1 ? {
3787
- leg: prior[0],
3788
- seed: prior[1]
3789
- } : null
3790
- };
4777
+ return null;
3791
4778
  }
3792
4779
 
3793
4780
  //#endregion
@@ -3808,312 +4795,493 @@ function formatPassSummary(input, style, colorGlyph = (glyph) => glyph) {
3808
4795
  }
3809
4796
 
3810
4797
  //#endregion
3811
- //#region src/telemetry.ts
3812
- const API_URL_ENV_VAR = "AFTERPACK_API_URL";
3813
- const DEFAULT_API_URL = "https://api.afterpack.dev";
3814
- const TELEMETRY_ENDPOINT_PATH = "/v1/telemetry/build";
3815
- const TELEMETRY_PAYLOAD_VERSION = 1;
3816
- const TELEMETRY_TIMEOUT_MS = 1500;
3817
- const INSTALL_ID_ROTATION_DAYS = 30;
3818
- const TELEMETRY_DIAGNOSTIC_LIMIT = 20;
3819
- const TELEMETRY_STATE_FILE = (0, node_path.join)((0, node_os.homedir)(), ".afterpack", "telemetry.json");
3820
- const TOKEN_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
3821
- const DATA_FIELD_WHITELIST = {
3822
- outputUnparseable: ["parserErrorKind", "outputByteOffset"],
3823
- parseError: ["parserErrorKind"],
3824
- engineBug: [
3825
- "phase",
3826
- "transform",
3827
- "nodeKind"
3828
- ],
3829
- inflationBudget: [
3830
- "target",
3831
- "achieved",
3832
- "budgetRatio",
3833
- "inflationRatio"
3834
- ],
3835
- configParse: [
3836
- "category",
3837
- "line",
3838
- "column"
3839
- ]
4798
+ //#region src/wire.ts
4799
+ const EXTERNAL_WIRE_DIR = "_external";
4800
+ const DRIVE_PATH = /^[A-Za-z]:[\\/]/;
4801
+ const URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]+:/;
4802
+ const FILE_URL = /^file:/i;
4803
+ const PATH_CHARS = "[^\\s\"'`|!?#()<>,;:*\\\\]";
4804
+ const EMBEDDED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:[A-Za-z]:[\\\\/]|/)(?:${PATH_CHARS}|\\\\(?!/))*)`, "g");
4805
+ const ESCAPED_PATH = new RegExp(`(^|[^A-Za-z0-9._~/\\\\-])((?:\\\\/${PATH_CHARS}+)+\\\\/?)`, "g");
4806
+ var WirePathError = class extends Error {
4807
+ constructor(message) {
4808
+ super(message);
4809
+ this.name = "WirePathError";
4810
+ }
3840
4811
  };
3841
- function resolveTelemetryEnabled(option, env = {}) {
3842
- if (option !== void 0) return option;
3843
- return !(env.NODE_ENV === "test" || env.VITEST);
4812
+ function toPosix(path) {
4813
+ return path.includes("\\") ? path.replaceAll("\\", "/") : path;
3844
4814
  }
3845
- const FRAMEWORK_ENTRIES = [
3846
- {
3847
- label: "afterpack",
3848
- name: "cli"
3849
- },
3850
- {
3851
- label: "afterpack-angular",
3852
- name: "angular",
3853
- pkg: "@angular/core"
3854
- },
3855
- {
3856
- label: "afterpack-esbuild",
3857
- name: "esbuild",
3858
- pkg: "esbuild"
3859
- },
3860
- {
3861
- label: "afterpack-next",
3862
- name: "next",
3863
- pkg: "next"
3864
- },
3865
- {
3866
- label: "afterpack-rollup",
3867
- name: "rollup",
3868
- pkg: "rollup"
3869
- },
3870
- {
3871
- label: "afterpack-vite",
3872
- name: "vite",
3873
- pkg: "vite"
3874
- },
3875
- {
3876
- label: "afterpack-webpack",
3877
- name: "webpack",
3878
- pkg: "webpack"
3879
- }
3880
- ];
3881
- const FRAMEWORK_BY_LABEL = new Map(FRAMEWORK_ENTRIES.map((e) => [e.label, e.name]));
3882
- const FRAMEWORK_PACKAGE_BY_NAME = new Map(FRAMEWORK_ENTRIES.flatMap((e) => e.pkg ? [[e.name, e.pkg]] : []));
3883
- function frameworkFromLabel(label) {
3884
- return FRAMEWORK_BY_LABEL.get(label.split(":")[0]) ?? "unknown";
4815
+ function lastSegment(path) {
4816
+ const parts = toPosix(path).split("/").filter((p) => p !== "");
4817
+ return parts[parts.length - 1] ?? "file";
3885
4818
  }
3886
- const VERSION_RANGE_PATTERN = /^[\sv0-9.\-+*xX^~><=|]{1,32}$/;
3887
- function detectFrameworkVersion(projectRoot, framework) {
3888
- const pkgName = FRAMEWORK_PACKAGE_BY_NAME.get(framework);
3889
- if (!pkgName) return null;
3890
- let deps;
4819
+ function isUnder(child, parent) {
4820
+ const rel = (0, node_path.relative)(parent, child);
4821
+ return rel === "" || !(0, node_path.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${node_path.sep}`);
4822
+ }
4823
+ function relativeWithin(file, baseDir) {
4824
+ const rel = (0, node_path.relative)((0, node_path.resolve)(baseDir), (0, node_path.resolve)(file));
4825
+ if (rel === "" || (0, node_path.isAbsolute)(rel) || DRIVE_PATH.test(rel)) return null;
4826
+ if (rel === ".." || rel.startsWith(`..${node_path.sep}`)) return null;
4827
+ return toPosix(rel);
4828
+ }
4829
+ function osUsername() {
3891
4830
  try {
3892
- const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(projectRoot, "package.json"), "utf8"));
3893
- deps = {
3894
- ...pkg.dependencies,
3895
- ...pkg.devDependencies
3896
- };
4831
+ return (0, node_os.userInfo)().username;
3897
4832
  } catch {
3898
4833
  return null;
3899
4834
  }
3900
- const raw = deps[pkgName];
3901
- if (typeof raw !== "string") return null;
3902
- const range = raw.trim();
3903
- return VERSION_RANGE_PATTERN.test(range) && /[0-9*xX]/.test(range) ? range : null;
3904
- }
3905
- function complexityLabel(preset, complexity) {
3906
- if (preset !== void 0) return preset;
3907
- return complexity === void 0 ? "default" : "custom";
3908
4835
  }
3909
- const FILE_COUNT_BUCKETS = [
3910
- 1,
3911
- 5,
3912
- 20,
3913
- 100,
3914
- 500,
3915
- 2e3
3916
- ];
3917
- function fileCountBucket(count) {
3918
- if (!Number.isFinite(count) || count <= 0) return "0";
3919
- let lower = 1;
3920
- for (const upper of FILE_COUNT_BUCKETS) {
3921
- if (count <= upper) return lower === upper ? `${upper}` : `${lower}-${upper}`;
3922
- lower = upper + 1;
4836
+ function personalNames() {
4837
+ const names = new Set([(0, node_path.basename)((0, node_os.homedir)())]);
4838
+ const user = osUsername();
4839
+ if (user) names.add(user);
4840
+ return names;
4841
+ }
4842
+ function safeName(path) {
4843
+ const name = lastSegment(path);
4844
+ return personalNames().has(name) ? "file" : name;
4845
+ }
4846
+ function toWirePaths(files, baseDir) {
4847
+ const wire = new Map();
4848
+ const taken = new Set();
4849
+ const outside = [];
4850
+ for (const file of files) {
4851
+ if (wire.has(file)) continue;
4852
+ const rel = relativeWithin(file, baseDir);
4853
+ if (rel === null || taken.has(rel)) {
4854
+ outside.push(file);
4855
+ continue;
4856
+ }
4857
+ wire.set(file, rel);
4858
+ taken.add(rel);
4859
+ }
4860
+ let n = 0;
4861
+ for (const file of outside) {
4862
+ if (wire.has(file)) continue;
4863
+ let label;
4864
+ do {
4865
+ label = `${EXTERNAL_WIRE_DIR}/${n}/${safeName(file)}`;
4866
+ n += 1;
4867
+ } while (taken.has(label));
4868
+ wire.set(file, label);
4869
+ taken.add(label);
4870
+ }
4871
+ return wire;
4872
+ }
4873
+ function looksLocal(path) {
4874
+ return isUnder(path, (0, node_os.homedir)()) || isUnder(path, (0, node_os.tmpdir)()) || (0, node_fs.existsSync)(path);
4875
+ }
4876
+ function localPathOf(source) {
4877
+ if (DRIVE_PATH.test(source) || source.startsWith("/") || source.startsWith("\\")) return source;
4878
+ if (FILE_URL.test(source)) try {
4879
+ return (0, node_url.fileURLToPath)(source);
4880
+ } catch {
4881
+ return source.replace(FILE_URL, "").replace(/^\/\/[^/]*/, "") || "/";
3923
4882
  }
3924
- return `${FILE_COUNT_BUCKETS[FILE_COUNT_BUCKETS.length - 1]}+`;
4883
+ const scheme = URL_SCHEME.exec(source);
4884
+ if (!scheme) return null;
4885
+ const rest = source.slice(scheme[0].length).replace(/^\/\/[^/]*/, "");
4886
+ const drive = rest.replace(/^\/+/, "");
4887
+ if (DRIVE_PATH.test(drive)) return drive;
4888
+ return rest.startsWith("/") && looksLocal(rest) ? rest : null;
3925
4889
  }
3926
- const DURATION_BUCKETS_MS = [
3927
- [1e3, "<1s"],
3928
- [5e3, "1-5s"],
3929
- [15e3, "5-15s"],
3930
- [6e4, "15-60s"],
3931
- [3e5, "60-300s"]
3932
- ];
3933
- function durationBucket(ms) {
3934
- if (!Number.isFinite(ms) || ms < 0) return "unknown";
3935
- for (const [upper, label] of DURATION_BUCKETS_MS) if (ms < upper) return label;
3936
- return "300s+";
4890
+ function bothForms(path) {
4891
+ return [...new Set([(0, node_path.resolve)(path), realPath(path)])];
3937
4892
  }
3938
- function safeScalar(value) {
3939
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
3940
- if (typeof value === "string") return TOKEN_PATTERN.test(value) ? value : null;
4893
+ function newPlace(dir, root, labels, shipped = "") {
4894
+ return {
4895
+ dir,
4896
+ root,
4897
+ privateRoots: [...new Set([(0, node_os.homedir)(), root].flatMap(bothForms))],
4898
+ scratchRoots: bothForms((0, node_os.tmpdir)()),
4899
+ labels,
4900
+ shipped
4901
+ };
4902
+ }
4903
+ function isPrivate(path, place) {
4904
+ if (DRIVE_PATH.test(path) && !(0, node_path.isAbsolute)(path)) return true;
4905
+ if (place.privateRoots.some((r) => isUnder(path, r))) return true;
4906
+ return place.scratchRoots.some((r) => isUnder(path, r) && (0, node_path.resolve)(path) !== (0, node_path.resolve)(r));
4907
+ }
4908
+ function inProject(path, place) {
4909
+ if (DRIVE_PATH.test(path) && !(0, node_path.isAbsolute)(path)) return null;
4910
+ const real = realPath(path);
4911
+ const mapDir = realPath(place.dir);
4912
+ const home = realPath((0, node_os.homedir)());
4913
+ if (!isUnder(real, realPath(place.root))) return null;
4914
+ if (isUnder(real, home) && !isUnder(mapDir, home)) return null;
4915
+ const rel = (0, node_path.relative)(mapDir, real);
4916
+ if (rel === "" || (0, node_path.isAbsolute)(rel) || DRIVE_PATH.test(rel)) return null;
4917
+ return toPosix(rel);
4918
+ }
4919
+ function externalLabel(path, place) {
4920
+ const key = (0, node_path.resolve)(path);
4921
+ const known = place.labels.get(key);
4922
+ if (known !== void 0) return known;
4923
+ const label = `${EXTERNAL_WIRE_DIR}/${place.labels.size}/${safeName(path)}`;
4924
+ place.labels.set(key, label);
4925
+ return label;
4926
+ }
4927
+ function fitLength(target, candidate, slash) {
4928
+ const unit = `.${slash}`;
4929
+ const room = target - candidate.length;
4930
+ for (let a = Math.floor(Math.max(room, 0) / unit.length); a >= 0; a--) {
4931
+ const rest = room - a * unit.length;
4932
+ if (rest % slash.length !== 0) continue;
4933
+ const body = unit.repeat(a) + candidate;
4934
+ const extra = rest / slash.length;
4935
+ if (extra === 0) return body;
4936
+ const at = body.indexOf(slash);
4937
+ if (at < 0) continue;
4938
+ return body.slice(0, at) + slash.repeat(extra) + body.slice(at);
4939
+ }
3941
4940
  return null;
3942
4941
  }
3943
- function telemetrySafeData(data) {
3944
- if (!data || typeof data.kind !== "string") return null;
3945
- const kind = TOKEN_PATTERN.test(data.kind) ? data.kind : null;
3946
- if (kind === null) return null;
3947
- const out = { kind };
3948
- for (const field of DATA_FIELD_WHITELIST[kind] ?? []) {
3949
- const value = safeScalar(data[field]);
3950
- if (value !== null) out[field] = value;
4942
+ function sameLength(original, candidates, slash) {
4943
+ for (const candidate of candidates) {
4944
+ const fitted = fitLength(original.length, candidate, slash);
4945
+ if (fitted !== null) return fitted;
3951
4946
  }
3952
- return out;
4947
+ return "_".repeat(original.length);
3953
4948
  }
3954
- function telemetrySafeSpan(d) {
3955
- const span = d.span;
3956
- if (!span) return null;
3957
- const start = safeScalar(span.startByte);
3958
- const end = safeScalar(span.endByte);
3959
- if (typeof start !== "number" || typeof end !== "number") return null;
3960
- if (start < 0 || end < 0) return null;
4949
+ function scrubText(text, place, keepLength) {
4950
+ if (!text.includes("/") && !text.includes("\\")) return text;
4951
+ const plain = text.replace(EMBEDDED_PATH, (whole, lead, path) => {
4952
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(path)) return whole;
4953
+ const name = inProject(path, place) ?? safeName(path);
4954
+ return `${lead}${keepLength ? sameLength(path, [name, safeName(path)], "/") : name}`;
4955
+ });
4956
+ return plain.replace(ESCAPED_PATH, (whole, lead, escaped) => {
4957
+ const path = escaped.replaceAll("\\/", "/");
4958
+ if (!isPrivate(path, place) || keepLength && place.shipped.includes(escaped)) return whole;
4959
+ const names = [inProject(path, place) ?? safeName(path), safeName(path)].map((c) => c.replaceAll("/", "\\/"));
4960
+ return `${lead}${keepLength ? sameLength(escaped, names, "\\/") : names[0]}`;
4961
+ });
4962
+ }
4963
+ function isRecord(value) {
4964
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4965
+ }
4966
+ function joinRoot(root, source) {
4967
+ return root.endsWith("/") || root.endsWith("\\") ? `${root}${source}` : `${root}/${source}`;
4968
+ }
4969
+ function newRestore() {
3961
4970
  return {
3962
- startByte: start,
3963
- endByte: end
4971
+ sources: new Map(),
4972
+ pmPaths: new Map(),
4973
+ contents: new Map()
3964
4974
  };
3965
4975
  }
3966
- function telemetrySafeDiagnostic(d, severity) {
4976
+ function remember(table, wire, original) {
4977
+ const known = table.get(wire);
4978
+ if (known === void 0) table.set(wire, original);
4979
+ else if (known !== original) table.set(wire, null);
4980
+ }
4981
+ function wireMapObject(map, place, restore, top) {
4982
+ const out = { ...map };
4983
+ let changed = false;
4984
+ const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
4985
+ const rootIsLocal = root !== "" && localPathOf(root) !== null;
4986
+ if (rootIsLocal) {
4987
+ delete out.sourceRoot;
4988
+ if (top) restore.sourceRoot = root;
4989
+ changed = true;
4990
+ }
4991
+ const sentRoot = rootIsLocal ? "" : root;
4992
+ const pmPath = (r, s) => r === "" ? s : joinRoot(r, s);
4993
+ const taken = new Map();
4994
+ const claim = (wired, original, local) => {
4995
+ const owner = taken.get(wired);
4996
+ if (owner === void 0 || owner === original) {
4997
+ taken.set(wired, original);
4998
+ return wired;
4999
+ }
5000
+ const label = externalLabel(local, place);
5001
+ taken.set(label, original);
5002
+ return label;
5003
+ };
5004
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((source) => {
5005
+ if (typeof source !== "string") return source;
5006
+ const rooted = rootIsLocal && localPathOf(source) === null && !URL_SCHEME.test(source) ? joinRoot(root, source) : source;
5007
+ const local = localPathOf(rooted);
5008
+ let wired;
5009
+ if (local === null) {
5010
+ const scrubbed = scrubText(rooted, place, false);
5011
+ if (scrubbed === source) {
5012
+ taken.set(source, source);
5013
+ return source;
5014
+ }
5015
+ wired = claim(scrubbed, source, rooted);
5016
+ } else {
5017
+ const rel = inProject(local, place);
5018
+ wired = claim(rel ?? externalLabel(local, place), source, local);
5019
+ }
5020
+ changed = true;
5021
+ remember(restore.sources, wired, source);
5022
+ remember(restore.pmPaths, pmPath(sentRoot, wired), pmPath(root, source));
5023
+ return wired;
5024
+ });
5025
+ if (typeof map.file === "string" && localPathOf(map.file) !== null) {
5026
+ if (top) restore.file = map.file;
5027
+ out.file = safeName(map.file);
5028
+ changed = true;
5029
+ }
5030
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((content) => {
5031
+ if (typeof content !== "string") return content;
5032
+ const scrubbed = scrubText(content, place, true);
5033
+ if (scrubbed === content) return content;
5034
+ changed = true;
5035
+ remember(restore.contents, scrubbed, content);
5036
+ return scrubbed;
5037
+ });
5038
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
5039
+ if (!isRecord(section) || !isRecord(section.map)) return section;
5040
+ const nested = wireMapObject(section.map, place, restore, false);
5041
+ if (!nested.changed) return section;
5042
+ changed = true;
5043
+ return {
5044
+ ...section,
5045
+ map: nested.map
5046
+ };
5047
+ });
3967
5048
  return {
3968
- code: TOKEN_PATTERN.test(d.code) ? d.code : "DIAG_UNKNOWN",
3969
- severity,
3970
- span: telemetrySafeSpan(d),
3971
- data: telemetrySafeData(d.data)
5049
+ map: out,
5050
+ changed
3972
5051
  };
3973
5052
  }
3974
- function buildTelemetryPayload(facts, ctx) {
3975
- let errorCount = 0;
3976
- let criticalCount = 0;
3977
- const alerting = [];
3978
- for (const d of facts.diagnostics) {
3979
- if (d.severity !== "error" && d.severity !== "critical") continue;
3980
- if (d.severity === "critical") criticalCount += 1;
3981
- else errorCount += 1;
3982
- alerting.push(telemetrySafeDiagnostic(d, d.severity));
5053
+ function wireSourceMapWithRestore(json, place) {
5054
+ const restore = newRestore();
5055
+ let parsed;
5056
+ try {
5057
+ parsed = JSON.parse(json);
5058
+ } catch {
5059
+ return {
5060
+ json: void 0,
5061
+ restore
5062
+ };
3983
5063
  }
3984
- if (alerting.length === 0) return null;
3985
- const kept = alerting.slice(-TELEMETRY_DIAGNOSTIC_LIMIT);
3986
- const env = ctx.env ?? {};
3987
- const runtime = ctx.runtime ?? {
3988
- node: process.versions.node,
3989
- platform: process.platform,
3990
- arch: process.arch
5064
+ if (!isRecord(parsed)) return {
5065
+ json: void 0,
5066
+ restore
3991
5067
  };
3992
- const framework = frameworkFromLabel(facts.label);
5068
+ const { map, changed } = wireMapObject(parsed, place, restore, true);
3993
5069
  return {
3994
- version: TELEMETRY_PAYLOAD_VERSION,
3995
- installId: ctx.installId,
3996
- framework,
3997
- frameworkVersion: detectFrameworkVersion(facts.projectRoot, framework),
3998
- engineVersion: safeVersion(facts.engineVersion),
3999
- clientVersion: safeVersion(facts.clientVersion),
4000
- nodeVersion: safeVersion(runtime.node) ?? "unknown",
4001
- os: safeToken(runtime.platform),
4002
- arch: safeToken(runtime.arch),
4003
- ci: env.CI === "true",
4004
- complexity: complexityLabel(facts.preset, facts.complexity),
4005
- fileCountBucket: fileCountBucket(facts.fileCount),
4006
- durationBucket: durationBucket(facts.durationMs),
4007
- diagnostics: kept,
4008
- errorCount,
4009
- criticalCount,
4010
- droppedCount: alerting.length - kept.length
5070
+ json: changed ? JSON.stringify(map) : json,
5071
+ restore
4011
5072
  };
4012
5073
  }
4013
- const VERSION_PATTERN = /^[0-9][0-9A-Za-z.\-+]{0,31}$/;
4014
- function safeVersion(value) {
4015
- return typeof value === "string" && VERSION_PATTERN.test(value) ? value : null;
4016
- }
4017
- function safeToken(value) {
4018
- return TOKEN_PATTERN.test(value) ? value : "unknown";
4019
- }
4020
- const TELEMETRY_NOTICE = [
4021
- "AfterPack: anonymous build diagnostics are ON (this notice prints once).",
4022
- "AfterPack: A build that reports an error-level diagnostic (a refused or partial build)",
4023
- "AfterPack: sends that diagnostic's code, severity, byte offsets and typed engine",
4024
- "AfterPack: fields, plus engine version, integration, Node version, OS/arch, bucketed",
4025
- "AfterPack: file counts and durations, and a random install id that rotates every 30",
4026
- "AfterPack: days.",
4027
- "AfterPack: It never sends your source, file names, paths, project name, diagnostic",
4028
- "AfterPack: message text, or exact byte counts. A clean build sends nothing.",
4029
- "AfterPack: Turn it off with AFTERPACK_telemetry_enabled=false, --telemetry.enabled=false, or",
4030
- "AfterPack: `telemetry: { enabled: false }` in your config.",
4031
- "AfterPack: https://www.afterpack.dev/privacy"
4032
- ];
4033
- const INSTALL_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
4034
- const DAY_MS = 24 * 60 * 60 * 1e3;
4035
- function readState(file, now) {
4036
- try {
4037
- const parsed = JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
4038
- if (typeof parsed.installId === "string" && INSTALL_ID_PATTERN.test(parsed.installId) && typeof parsed.rotatedAt === "number") return {
4039
- installId: parsed.installId,
4040
- rotatedAt: parsed.rotatedAt,
4041
- noticeShownAt: typeof parsed.noticeShownAt === "number" ? parsed.noticeShownAt : 0
5074
+ function lookup(table, value) {
5075
+ return table.get(value) ?? value;
5076
+ }
5077
+ function restoreMapObject(map, ctx, top) {
5078
+ let changed = false;
5079
+ const out = { ...map };
5080
+ if (Array.isArray(map.sources)) out.sources = map.sources.map((entry) => {
5081
+ if (typeof entry !== "string") return entry;
5082
+ const back = entry === ctx.wire ? ctx.local : lookup(ctx.map.sources, entry);
5083
+ if (back !== entry) changed = true;
5084
+ return back;
5085
+ });
5086
+ if (Array.isArray(map.sourcesContent)) out.sourcesContent = map.sourcesContent.map((entry) => {
5087
+ if (typeof entry !== "string") return entry;
5088
+ const back = lookup(ctx.map.contents, entry);
5089
+ if (back !== entry) changed = true;
5090
+ return back;
5091
+ });
5092
+ if (top && ctx.map.sourceRoot !== void 0 && !map.sourceRoot) {
5093
+ const root = ctx.map.sourceRoot;
5094
+ const entries = Object.entries(out).filter(([key]) => key !== "sourceRoot");
5095
+ const at = "sourceRoot" in map ? Object.keys(map).indexOf("sourceRoot") : -1;
5096
+ const after = entries.findIndex(([key]) => key === "sources");
5097
+ const index = at >= 0 ? at : after >= 0 ? after + 1 : entries.length;
5098
+ entries.splice(index, 0, ["sourceRoot", root]);
5099
+ for (const key of Object.keys(out)) delete out[key];
5100
+ Object.assign(out, Object.fromEntries(entries));
5101
+ changed = true;
5102
+ }
5103
+ if (top && ctx.map.file !== void 0 && typeof map.file === "string") {
5104
+ out.file = ctx.map.file;
5105
+ changed = true;
5106
+ }
5107
+ if (Array.isArray(map.sections)) out.sections = map.sections.map((section) => {
5108
+ if (!isRecord(section) || !isRecord(section.map)) return section;
5109
+ const nested = restoreMapObject(section.map, ctx, false);
5110
+ if (!nested.changed) return section;
5111
+ changed = true;
5112
+ return {
5113
+ ...section,
5114
+ map: nested.map
4042
5115
  };
4043
- } catch {}
5116
+ });
4044
5117
  return {
4045
- installId: (0, node_crypto.randomUUID)(),
4046
- rotatedAt: now,
4047
- noticeShownAt: 0
5118
+ map: out,
5119
+ changed
4048
5120
  };
4049
5121
  }
4050
- function writeState(file, state) {
4051
- try {
4052
- (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
4053
- (0, node_fs.writeFileSync)(file, `${JSON.stringify(state)}\n`, "utf8");
4054
- } catch {}
4055
- }
4056
- function telemetryUrl(env) {
4057
- const base = (env[API_URL_ENV_VAR] ?? DEFAULT_API_URL).replace(/\/+$/, "");
4058
- return `${base}${TELEMETRY_ENDPOINT_PATH}`;
4059
- }
4060
- const TELEMETRY_BODY_LIMIT = 64 * 1024;
4061
- async function reportTelemetryNotices(response, logger) {
4062
- if (!response || response.status !== 202 || typeof response.text !== "function") return;
4063
- const declared = Number(response.headers?.get?.("content-length"));
4064
- if (Number.isFinite(declared) && declared > TELEMETRY_BODY_LIMIT) {
4065
- await response.body?.cancel().catch(() => {});
4066
- return;
4067
- }
4068
- const text = await response.text();
4069
- if (text.length > TELEMETRY_BODY_LIMIT) return;
4070
- let body;
5122
+ function restoreSourceMap(json, ctx) {
5123
+ let parsed;
4071
5124
  try {
4072
- body = JSON.parse(text);
5125
+ parsed = JSON.parse(json);
4073
5126
  } catch {
4074
- return;
5127
+ return json;
4075
5128
  }
4076
- if (typeof body !== "object" || body === null || Array.isArray(body)) return;
4077
- reportNotices(body.notices, logger);
5129
+ if (!isRecord(parsed)) return json;
5130
+ const { map, changed } = restoreMapObject(parsed, ctx, true);
5131
+ return changed ? JSON.stringify(map) : json;
4078
5132
  }
4079
- function createTelemetryReporter(deps = {}) {
4080
- const env = deps.env ?? process.env;
4081
- const logger = deps.logger ?? console;
4082
- const now = deps.now ?? Date.now;
4083
- const stateFile = deps.stateFile ?? TELEMETRY_STATE_FILE;
4084
- const timeoutMs = deps.timeoutMs ?? TELEMETRY_TIMEOUT_MS;
4085
- return async (facts) => {
4086
- try {
4087
- const at = now();
4088
- const state = readState(stateFile, at);
4089
- let dirty = false;
4090
- if (at - state.rotatedAt >= INSTALL_ID_ROTATION_DAYS * DAY_MS) {
4091
- state.installId = (0, node_crypto.randomUUID)();
4092
- state.rotatedAt = at;
4093
- dirty = true;
4094
- }
4095
- if (state.noticeShownAt === 0) {
4096
- for (const line of TELEMETRY_NOTICE) logger.log(line);
4097
- state.noticeShownAt = at;
4098
- dirty = true;
5133
+ function restoredSize(size, wired, original) {
5134
+ if (typeof size !== "number") return size;
5135
+ if (size === Buffer.byteLength(wired)) return Buffer.byteLength(original);
5136
+ if (size === wired.length) return original.length;
5137
+ return size;
5138
+ }
5139
+ function restoreProtectionMap(doc, ctx) {
5140
+ if (!isRecord(doc) || !Array.isArray(doc.files)) return doc;
5141
+ return {
5142
+ ...doc,
5143
+ files: doc.files.map((entry) => {
5144
+ if (!isRecord(entry) || !isRecord(entry.file)) return entry;
5145
+ const file = entry.file;
5146
+ const next = { ...file };
5147
+ if (typeof file.path === "string") next.path = file.path === ctx.wire ? ctx.local : lookup(ctx.map.pmPaths, file.path);
5148
+ if (typeof file.originalSource === "string") {
5149
+ const original = lookup(ctx.map.contents, file.originalSource);
5150
+ if (original !== file.originalSource) {
5151
+ next.originalSource = original;
5152
+ next.inputSize = restoredSize(file.inputSize, file.originalSource, original);
5153
+ }
4099
5154
  }
4100
- if (dirty) writeState(stateFile, state);
4101
- if (facts === null) return;
4102
- const payload = buildTelemetryPayload(facts, {
4103
- installId: state.installId,
4104
- env
4105
- });
4106
- if (payload === null) return;
4107
- const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
4108
- if (typeof fetchImpl !== "function") return;
4109
- const response = await fetchImpl(telemetryUrl(env), {
4110
- method: "POST",
4111
- headers: { "content-type": "application/json" },
4112
- body: JSON.stringify(payload),
4113
- signal: AbortSignal.timeout(timeoutMs)
4114
- });
4115
- await reportTelemetryNotices(response, logger);
4116
- } catch {}
5155
+ const same = Object.keys(next).every((k) => next[k] === file[k]);
5156
+ return same ? entry : {
5157
+ ...entry,
5158
+ file: next
5159
+ };
5160
+ })
5161
+ };
5162
+ }
5163
+ function wireGlob(pattern, pairs) {
5164
+ let equivalent = true;
5165
+ const matched = [];
5166
+ for (const [local, wire] of pairs) {
5167
+ const hit = matchesPath(pattern, local);
5168
+ if (hit !== matchesPath(pattern, wire)) equivalent = false;
5169
+ if (hit) matched.push(wire);
5170
+ }
5171
+ if (!isAnchored(pattern) && equivalent && matched.length > 0) return [pattern];
5172
+ return matched.map((wire) => `/${wire}`);
5173
+ }
5174
+ function anyMatch(patterns, path) {
5175
+ return patterns.some((p) => matchesPath(p, path));
5176
+ }
5177
+ function reservedNames(entries, path) {
5178
+ const names = entries.flatMap((e) => typeof e === "string" ? [] : matchesPath(e.glob, path) ? e.names : []);
5179
+ return [...new Set(names)].sort().join("\n");
5180
+ }
5181
+ function verifyTranslation(config, out, pairs) {
5182
+ const exclude = config.paths?.exclude ?? [];
5183
+ const sentExclude = out.paths?.exclude ?? [];
5184
+ const reserved = config.identifiers?.reserved ?? [];
5185
+ const sentReserved = out.identifiers?.reserved ?? [];
5186
+ for (const [local, wire] of pairs) {
5187
+ 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.`);
5188
+ 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.`);
5189
+ }
5190
+ }
5191
+ function translateConfig(config, wirePaths) {
5192
+ const exclude = config.paths?.exclude;
5193
+ const reserved = config.identifiers?.reserved;
5194
+ const origins = new Map();
5195
+ if (exclude === void 0 && reserved === void 0) return {
5196
+ config,
5197
+ origins
5198
+ };
5199
+ const pairs = [...wirePaths.entries()];
5200
+ const translate = (pattern) => {
5201
+ const patterns = wireGlob(pattern, pairs);
5202
+ for (const p of patterns) if (!origins.has(p)) origins.set(p, pattern);
5203
+ return patterns;
5204
+ };
5205
+ const out = { ...config };
5206
+ if (exclude !== void 0) out.paths = {
5207
+ ...config.paths,
5208
+ exclude: [...new Set(exclude.flatMap((pattern) => translate(pattern)))]
5209
+ };
5210
+ if (reserved !== void 0) out.identifiers = {
5211
+ ...config.identifiers,
5212
+ reserved: reserved.flatMap((entry) => typeof entry === "string" ? [entry] : translate(entry.glob).map((glob) => ({
5213
+ ...entry,
5214
+ glob
5215
+ })))
5216
+ };
5217
+ verifyTranslation(config, out, pairs);
5218
+ return {
5219
+ config: out,
5220
+ origins
5221
+ };
5222
+ }
5223
+ function escapeRegExp(text) {
5224
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5225
+ }
5226
+ function localMessage(message, wire, local, origins) {
5227
+ let out = message;
5228
+ for (const [sent, original] of origins) if (sent !== original) out = out.split(`"${sent}"`).join(`"${original}"`);
5229
+ const bounded = new RegExp(`(^|[\\s"'\`(\\[])${escapeRegExp(wire)}(?=$|[\\s"'\`)\\]:,;]|\\.(?:\\s|$))`, "g");
5230
+ return out.replace(bounded, (_m, lead) => `${lead}${local}`);
5231
+ }
5232
+ function localDiagnostics(diagnostics, localPaths, wire, local, origins) {
5233
+ if (!Array.isArray(diagnostics)) return diagnostics;
5234
+ return diagnostics.map((d) => {
5235
+ if (!isRecord(d)) return d;
5236
+ const next = { ...d };
5237
+ if (typeof d.file === "string") next.file = localPaths.get(d.file) ?? d.file;
5238
+ if (typeof d.message === "string") next.message = localMessage(d.message, wire, local, origins);
5239
+ return next.file === d.file && next.message === d.message ? d : next;
5240
+ });
5241
+ }
5242
+ function prepareWireBatch(inputs, config, baseDir, rootDir = baseDir) {
5243
+ const wirePaths = toWirePaths(inputs.map((i) => i.path), baseDir);
5244
+ const localPaths = new Map([...wirePaths].map(([local, wire]) => [wire, local]));
5245
+ const translated = translateConfig(config, wirePaths);
5246
+ const restores = new Map();
5247
+ const labels = new Map();
5248
+ const wiredInputs = inputs.map((input) => {
5249
+ const path = wirePaths.get(input.path) ?? input.path;
5250
+ const wired = {
5251
+ ...input,
5252
+ path
5253
+ };
5254
+ if (input.sourceMap !== void 0) {
5255
+ const place = newPlace((0, node_path.dirname)((0, node_path.resolve)(input.path)), rootDir, labels, input.source);
5256
+ const map = wireSourceMapWithRestore(input.sourceMap, place);
5257
+ restores.set(path, map.restore);
5258
+ if (map.json === void 0) delete wired.sourceMap;
5259
+ else wired.sourceMap = map.json;
5260
+ }
5261
+ return wired;
5262
+ });
5263
+ return {
5264
+ inputs: wiredInputs,
5265
+ config: translated.config,
5266
+ toLocal: (batch) => ({
5267
+ ...batch,
5268
+ files: batch.files.map((f) => {
5269
+ const local = localPaths.get(f.path);
5270
+ if (local === void 0) return f;
5271
+ const ctx = {
5272
+ map: restores.get(f.path) ?? newRestore(),
5273
+ wire: f.path,
5274
+ local
5275
+ };
5276
+ return {
5277
+ ...f,
5278
+ path: local,
5279
+ ...f.diagnostics === void 0 ? {} : { diagnostics: localDiagnostics(f.diagnostics, localPaths, f.path, local, translated.origins) },
5280
+ ...typeof f.sourceMap === "string" ? { sourceMap: restoreSourceMap(f.sourceMap, ctx) } : {},
5281
+ ...f.protectionMap == null ? {} : { protectionMap: restoreProtectionMap(f.protectionMap, ctx) }
5282
+ };
5283
+ })
5284
+ })
4117
5285
  };
4118
5286
  }
4119
5287
 
@@ -4150,12 +5318,15 @@ function fileFailure(f, source) {
4150
5318
  if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
4151
5319
  return null;
4152
5320
  }
4153
- async function readEngineVersion(engine) {
4154
- try {
4155
- return await engine.version?.() ?? null;
4156
- } catch {
4157
- return null;
5321
+ function removeBundlerSourceMaps(input) {
5322
+ const { sweepDir: sweepDir$1, engineMaps, policy, label } = input;
5323
+ const bundlerMaps = new Set([...input.perFile].flat());
5324
+ if (sweepDir$1 != null) {
5325
+ const swept = collectSourceMaps(sweepDir$1).filter((path) => !policy.sourceMap || !path.endsWith(".css.map"));
5326
+ for (const path of containedSourceMaps(swept, sweepDir$1)) bundlerMaps.add(path);
4158
5327
  }
5328
+ removeSourceMaps([...bundlerMaps].filter((path) => !engineMaps.has(path)), label);
5329
+ if (sweepDir$1 != null && !policy.sourceMap) stripCssSourceMappingURLs(collectStylesheets(sweepDir$1));
4159
5330
  }
4160
5331
  function describeLevel(preset, complexity) {
4161
5332
  if (complexity === void 0) return `preset "${preset ?? DEFAULT_PRESET}"`;
@@ -4165,22 +5336,30 @@ function describeLevel(preset, complexity) {
4165
5336
  async function runObfuscationPass(options) {
4166
5337
  const passStartedAt = options.startedAt ?? Date.now();
4167
5338
  const callerAnchored = options.startedAt !== void 0;
4168
- const { files, engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
5339
+ const { engine, label, cwd, combinedProtectionMap, artifactOptions = {}, env = process.env } = options;
4169
5340
  const logger = silenceSummaryLines(options.logger ?? DEFAULT_LOGGER, options.diagnostics);
4170
5341
  const prefix = (message) => `[${label}] ${message}`;
4171
5342
  const style = options.summaryStyle ?? "plugin";
4172
5343
  assertSupportedCore(options.client, prefix);
5344
+ const outsideBuildDir = options.emitToCaller ? [] : options.files.filter((f) => !options.inputs?.has(f) && !withinRealDir((0, node_path.dirname)(f), combinedProtectionMap.buildDir));
5345
+ const files = options.files.filter((f) => !outsideBuildDir.includes(f));
5346
+ if (outsideBuildDir.length > 0) logger.warn(prefix(`left ${outsideBuildDir.length} file(s) untouched because a symlink places them outside ${combinedProtectionMap.buildDir}: ${outsideBuildDir.join(", ")}`));
4173
5347
  const onDiskFiles = options.inputs ? files.filter((f) => !options.inputs?.has(f)) : files;
4174
5348
  const onDiskBytes = new Map(await Promise.all(onDiskFiles.map(async (filePath) => [filePath, await (0, node_fs_promises.readFile)(filePath)])));
5349
+ const home = afterpackHome(combinedProtectionMap.buildDir, { fileTarget: combinedProtectionMap.fileTarget });
5350
+ const unanchored = describeUnanchoredHome(home);
5351
+ if (unanchored) logger.log(prefix(unanchored));
4175
5352
  if (!options.emitToCaller) {
4176
- const already = detectAlreadyObfuscatedInputs(onDiskFiles, combinedProtectionMap.buildDir, onDiskBytes, prefix);
5353
+ const already = detectAlreadyObfuscatedInputs(onDiskFiles, home, onDiskBytes, prefix);
4177
5354
  if (already) throw new AlreadyObfuscatedError(prefix(formatAlreadyObfuscatedMessage({
4178
5355
  files: already.files,
4179
5356
  receiptPath: already.receiptPath,
4180
5357
  dir: combinedProtectionMap.buildDir
4181
5358
  })), already.files, already.receiptPath, combinedProtectionMap.buildDir);
4182
5359
  }
4183
- const resolvedSeed = resolveBuildSeed(options.seed, {
5360
+ if (options.outputSweep !== false) sweepOutputTree(combinedProtectionMap.buildDir, options.sourceMapSweepDir ?? (options.emitToCaller ? combinedProtectionMap.buildDir : null), label, home);
5361
+ prepareProtectionReceipt(home, label);
5362
+ const resolvedSeed = options.resolvedSeed ?? resolveBuildSeed(options.seed, {
4184
5363
  root: cwd,
4185
5364
  leg: options.buildLeg ?? combinedProtectionMap.buildDir
4186
5365
  }, {
@@ -4193,6 +5372,9 @@ async function runObfuscationPass(options) {
4193
5372
  const bundledCapture = options.capturedByFile != null;
4194
5373
  const postMinifyMode = directivesEnabled && options.postMinify === true && !bundledCapture;
4195
5374
  const sourceByPath = new Map();
5375
+ const bundlerMapsByPath = new Map();
5376
+ const sweepDir$1 = options.sourceMapSweepDir ?? null;
5377
+ const sourceMapRoot = sweepDir$1 ?? combinedProtectionMap.buildDir;
4196
5378
  let coloredRegionCount = 0;
4197
5379
  let directivesNeededMap = false;
4198
5380
  let postMinifyMapsSeen = 0;
@@ -4202,6 +5384,7 @@ async function runObfuscationPass(options) {
4202
5384
  const provided = options.inputs?.get(filePath);
4203
5385
  const source = provided ? provided.source : (onDiskBytes.get(filePath) ?? (0, node_fs.readFileSync)(filePath)).toString("utf8");
4204
5386
  sourceByPath.set(filePath, source);
5387
+ if (!provided && !options.emitToCaller) bundlerMapsByPath.set(filePath, bundlerSourceMapPaths(filePath, source, sourceMapRoot));
4205
5388
  const inputSourceMap = provided ? provided.sourceMap ?? null : discoverInputSourceMap(filePath, source);
4206
5389
  let regions;
4207
5390
  const modules = options.capturedByFile?.get(filePath);
@@ -4293,6 +5476,39 @@ async function runObfuscationPass(options) {
4293
5476
  engine: options.engineConfig,
4294
5477
  renameGlobals: capture.renameGlobals
4295
5478
  });
5479
+ const saltEngine = options.cloudEngineExpectation ?? (options.hashedNames ? await resolveSaltEngine(env, localEngineVersion) : null);
5480
+ let namesPlan = null;
5481
+ let hashSalt = null;
5482
+ if (options.hashedNames && saltEngine && !options.emitToCaller) {
5483
+ const { seed: _seed,...configWithoutSeed } = engineConfig;
5484
+ const namedInputs = new Map(inputs.map((input) => [input.path, {
5485
+ source: input.source,
5486
+ regions: input.regions
5487
+ }]));
5488
+ hashSalt = afterpackHashSalt({
5489
+ seed,
5490
+ engine: saltEngine,
5491
+ settings: {
5492
+ engine: configWithoutSeed,
5493
+ sourceMap: policy.sourceMap,
5494
+ emitSourceMappingURL: policy.emitSourceMappingURL
5495
+ }
5496
+ });
5497
+ namesPlan = planHashedNames({
5498
+ options: options.hashedNames,
5499
+ inputs: namedInputs,
5500
+ salt: hashSalt
5501
+ });
5502
+ namesPlan.preflight();
5503
+ for (const input of inputs) {
5504
+ const path = namesPlan.renamed.get(input.path) ?? input.path;
5505
+ const source = namesPlan.rewrite(input.source);
5506
+ sourceByPath.delete(input.path);
5507
+ sourceByPath.set(path, source);
5508
+ input.path = path;
5509
+ input.source = source;
5510
+ }
5511
+ }
4296
5512
  if (style !== "cli") logger.log(prefix(`obfuscating ${inputs.length} file(s) at ${describeLevel(options.preset, options.complexity)} ...`));
4297
5513
  const engineStartedAt = Date.now();
4298
5514
  const prepMs = engineStartedAt - passStartedAt;
@@ -4300,9 +5516,16 @@ async function runObfuscationPass(options) {
4300
5516
  clientVersion: options.client?.coreVersion,
4301
5517
  client: clientString(options.client)
4302
5518
  });
5519
+ let wire;
5520
+ try {
5521
+ wire = prepareWireBatch(inputs, engineConfig, combinedProtectionMap.buildDir, home.projectRoot);
5522
+ } catch (error) {
5523
+ if (error instanceof WirePathError) throw new Error(prefix(error.message));
5524
+ throw error;
5525
+ }
4303
5526
  let batch;
4304
5527
  try {
4305
- batch = await engine.processBatch(inputs, engineConfig, context);
5528
+ batch = wire.toLocal(await engine.processBatch(wire.inputs, wire.config, context));
4306
5529
  } catch (error) {
4307
5530
  const cloud = toCloudApiError(error, {
4308
5531
  identity: options.client,
@@ -4313,6 +5536,7 @@ async function runObfuscationPass(options) {
4313
5536
  throw cloud;
4314
5537
  }
4315
5538
  const engineEndedAt = Date.now();
5539
+ options.onBatch?.(inputs, batch);
4316
5540
  reportNotices(batch.notices, logger, prefix);
4317
5541
  const engineMs = engineEndedAt - engineStartedAt;
4318
5542
  const collected = collectDiagnostics(batch.files);
@@ -4327,6 +5551,10 @@ async function runObfuscationPass(options) {
4327
5551
  const telemetry = options.telemetry;
4328
5552
  const telemetryEnabled = telemetry != null && resolveTelemetryEnabled(artifactOptions.telemetry?.enabled, env);
4329
5553
  const engineVersion = (batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null) ?? localEngineVersion;
5554
+ if (saltEngine) {
5555
+ const mismatch = cloudEngineMismatch(saltEngine, batch.source === "cloud" ? safeVersionString(batch.engineVersion) : null);
5556
+ if (mismatch) throw new Error(prefix(mismatch));
5557
+ }
4330
5558
  if (telemetry && telemetryEnabled) {
4331
5559
  const facts = {
4332
5560
  label,
@@ -4366,6 +5594,7 @@ async function runObfuscationPass(options) {
4366
5594
  }
4367
5595
  const writtenFiles = [];
4368
5596
  const emittedFiles = [];
5597
+ const engineMaps = new Set();
4369
5598
  for (const { result: f, source } of verified) {
4370
5599
  if (options.emitToCaller) {
4371
5600
  outputs.push({
@@ -4378,24 +5607,42 @@ async function runObfuscationPass(options) {
4378
5607
  }
4379
5608
  const written = writeArtifacts({
4380
5609
  outPath: f.path,
4381
- code: f.code,
5610
+ code: withSourceMappingURL(f.code, null),
4382
5611
  sourceMapJson: f.sourceMap ?? null,
4383
5612
  protectionMapJson: null,
4384
5613
  originalSource: source,
4385
5614
  policy,
4386
5615
  mode: "framework",
5616
+ afterpackDir: home.dir,
4387
5617
  logger
4388
5618
  });
4389
5619
  writtenFiles.push(written.codePath);
4390
- if (written.mapPath) sensitiveArtifactPaths.push(written.mapPath);
5620
+ if (written.mapPath) {
5621
+ sensitiveArtifactPaths.push(written.mapPath);
5622
+ engineMaps.add((0, node_path.resolve)(written.mapPath));
5623
+ }
4391
5624
  if (written.backupPath) sensitiveArtifactPaths.push(written.backupPath);
4392
5625
  }
4393
- if (!options.emitToCaller) options.afterWrite?.();
5626
+ if (!options.emitToCaller) {
5627
+ if (namesPlan) {
5628
+ for (const [from, to] of namesPlan.renamed) if (sourceByPath.has(to)) (0, node_fs.rmSync)(from, { force: true });
5629
+ namesPlan.apply();
5630
+ if (namesPlan.renamed.size > 0) logger.log(prefix(`renamed ${namesPlan.renamed.size} content-hashed file(s) so each name follows its obfuscated bytes`));
5631
+ }
5632
+ removeBundlerSourceMaps({
5633
+ perFile: bundlerMapsByPath.values(),
5634
+ sweepDir: sweepDir$1,
5635
+ engineMaps,
5636
+ policy,
5637
+ label
5638
+ });
5639
+ options.afterWrite?.(writtenFiles);
5640
+ }
4394
5641
  const protectionMapPath = writeCombinedProtectionMap({
4395
5642
  buildDir: combinedProtectionMap.buildDir,
4396
5643
  docs: protectionMapDocs,
4397
5644
  policy,
4398
- afterpackDir: combinedProtectionMap.afterpackDir,
5645
+ afterpackDir: combinedProtectionMap.subdir ? (0, node_path.join)(home.dir, combinedProtectionMap.subdir) : home.dir,
4399
5646
  fileName: combinedProtectionMap.fileName,
4400
5647
  logger
4401
5648
  });
@@ -4417,12 +5664,15 @@ async function runObfuscationPass(options) {
4417
5664
  if (options.emitToCaller) deferredReceipt = {
4418
5665
  ...receiptFields,
4419
5666
  dir: combinedProtectionMap.buildDir,
5667
+ home,
4420
5668
  files: emittedFiles
4421
5669
  };
4422
5670
  else {
4423
5671
  receiptPath = writeProtectionReceipt({
4424
5672
  ...receiptFields,
4425
5673
  dir: combinedProtectionMap.buildDir,
5674
+ home,
5675
+ merge: combinedProtectionMap.fileTarget === true,
4426
5676
  files: writtenFiles
4427
5677
  });
4428
5678
  if (style !== "cli") logger.log(prefix(`wrote protection receipt -> ${receiptPath} (afterpack verify)`));
@@ -4461,6 +5711,8 @@ async function runObfuscationPass(options) {
4461
5711
  timing,
4462
5712
  diagnostics: diagnosticsSummary,
4463
5713
  transformedFiles,
5714
+ renamed: namesPlan?.renamed ?? new Map(),
5715
+ hashSalt,
4464
5716
  ...options.emitToCaller ? { outputs } : {}
4465
5717
  };
4466
5718
  }
@@ -4640,6 +5892,8 @@ function resolvePluginConfig(input) {
4640
5892
  }
4641
5893
 
4642
5894
  //#endregion
5895
+ exports.AFTERPACK_DIR = AFTERPACK_DIR;
5896
+ exports.AfterpackFilesError = AfterpackFilesError;
4643
5897
  exports.AlreadyObfuscatedError = AlreadyObfuscatedError;
4644
5898
  exports.CLOUD_REFUSAL_SUMMARY = CLOUD_REFUSAL_SUMMARY;
4645
5899
  exports.CONFIG_FILE_NAME = CONFIG_FILE_NAME;
@@ -4647,11 +5901,14 @@ exports.CONFIG_KEYS = CONFIG_KEYS;
4647
5901
  exports.CORE_FLOOR_SUMMARY = CORE_FLOOR_SUMMARY;
4648
5902
  exports.CloudApiError = CloudApiError;
4649
5903
  exports.CoreVersionError = CoreVersionError;
5904
+ exports.DIAG_AFTERPACK_DIR_IN_OUTPUT = DIAG_AFTERPACK_DIR_IN_OUTPUT;
4650
5905
  exports.DIAG_ALREADY_OBFUSCATED = DIAG_ALREADY_OBFUSCATED;
4651
5906
  exports.DIAG_RECEIPT_UNREADABLE = DIAG_RECEIPT_UNREADABLE;
4652
- exports.PROTECTION_RECEIPT_FILE = PROTECTION_RECEIPT_FILE;
5907
+ exports.DIAG_RECEIPT_UNWRITABLE = DIAG_RECEIPT_UNWRITABLE;
5908
+ exports.PROTECTION_RECEIPTS_DIR = PROTECTION_RECEIPTS_DIR;
4653
5909
  exports.SEED_ENV_VAR = SEED_ENV_VAR;
4654
5910
  exports.UnreadableReceiptError = UnreadableReceiptError;
5911
+ exports.afterpackHome = afterpackHome;
4655
5912
  exports.applyBundleOutput = applyBundleOutput;
4656
5913
  exports.applyResolvedKey = applyResolvedKey;
4657
5914
  exports.collectBundleJs = collectBundleJs;
@@ -4667,25 +5924,37 @@ exports.findUpward = findUpward;
4667
5924
  exports.getPath = getPath;
4668
5925
  exports.installedRequiredLine = installedRequiredLine;
4669
5926
  exports.loadConfigFile = loadConfigFile;
5927
+ exports.locateProtectionReceipt = locateProtectionReceipt;
4670
5928
  exports.mergeConfig = mergeConfig;
4671
5929
  exports.normalizePluginOptions = normalizePluginOptions;
4672
5930
  exports.npxAlternative = npxAlternative;
4673
5931
  exports.parseCliOptions = parseCliOptions;
4674
5932
  exports.parseEnvOptions = parseEnvOptions;
4675
5933
  exports.passSettings = passSettings;
5934
+ exports.prepareHashSalt = prepareHashSalt;
5935
+ exports.protectionReceiptPath = protectionReceiptPath;
5936
+ exports.readEngineVersion = readEngineVersion;
5937
+ exports.regenerateCompressedSiblings = regenerateCompressedSiblings;
5938
+ exports.removeSourceMaps = removeSourceMaps;
5939
+ exports.reportPolicySaltBits = reportPolicySaltBits;
4676
5940
  exports.resolveClientIdentity = resolveClientIdentity;
4677
5941
  exports.resolvePluginConfig = resolvePluginConfig;
4678
5942
  exports.resolveReportPolicy = resolveReportPolicy;
4679
5943
  exports.runObfuscationPass = runObfuscationPass;
5944
+ exports.saltSettings = saltSettings;
4680
5945
  exports.sanitizeNotices = sanitizeNotices;
4681
5946
  exports.scanDirectives = scanDirectives;
4682
5947
  exports.serverAddsInfo = serverAddsInfo;
4683
5948
  exports.sha256Of = sha256Of;
4684
5949
  exports.sourceTypeForBundle = sourceTypeForBundle;
4685
5950
  exports.sourceTypeForOutputFormat = sourceTypeForOutputFormat;
5951
+ exports.sriPluginRefusal = sriPluginRefusal;
4686
5952
  exports.stripBundleCssSourceMaps = stripBundleCssSourceMaps;
5953
+ exports.stripCssSourceMappingURLs = stripCssSourceMappingURLs;
5954
+ exports.sweepOutputTree = sweepOutputTree;
4687
5955
  exports.toEngineConfig = toEngineConfig;
4688
5956
  exports.toPluginOptions = toPluginOptions;
5957
+ exports.unsaltedAssetsWarning = unsaltedAssetsWarning;
4689
5958
  exports.validateConfig = validateConfig;
4690
5959
  exports.verifyProtectionReceipt = verifyProtectionReceipt;
4691
5960
  exports.withSourceMappingURL = withSourceMappingURL;