@afterpack/integration-utils 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -21,17 +21,117 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  }) : target, mod));
22
22
 
23
23
  //#endregion
24
+ const node_crypto = __toESM(require("node:crypto"));
24
25
  const node_fs = __toESM(require("node:fs"));
25
26
  const node_path = __toESM(require("node:path"));
26
27
  const node_module = __toESM(require("node:module"));
27
28
  const node_zlib = __toESM(require("node:zlib"));
28
- const node_crypto = __toESM(require("node:crypto"));
29
29
  const node_url = __toESM(require("node:url"));
30
30
  const node_child_process = __toESM(require("node:child_process"));
31
31
  const node_os = __toESM(require("node:os"));
32
32
  const node_fs_promises = __toESM(require("node:fs/promises"));
33
33
  const __jridgewell_sourcemap_codec = __toESM(require("@jridgewell/sourcemap-codec"));
34
34
 
35
+ //#region src/atomic-write.ts
36
+ const STAGED_SUFFIX = ".afterpack-tmp";
37
+ function stagedPath(path) {
38
+ return `${path}${STAGED_SUFFIX}`;
39
+ }
40
+ function sha256Hex(content) {
41
+ return (0, node_crypto.createHash)("sha256").update(content).digest("hex");
42
+ }
43
+ function writeFileAtomic(path, content) {
44
+ const staged = stagedPath(path);
45
+ let mode = null;
46
+ try {
47
+ mode = (0, node_fs.statSync)(path).mode & 4095;
48
+ } catch {
49
+ mode = null;
50
+ }
51
+ try {
52
+ (0, node_fs.writeFileSync)(staged, content);
53
+ if (mode !== null) (0, node_fs.chmodSync)(staged, mode);
54
+ (0, node_fs.renameSync)(staged, path);
55
+ } catch (error) {
56
+ try {
57
+ (0, node_fs.rmSync)(staged, { force: true });
58
+ } catch {}
59
+ throw error;
60
+ }
61
+ }
62
+
63
+ //#endregion
64
+ //#region src/angular-integrity.ts
65
+ const SRI_ATTR = /\b(src|href)\s*=\s*"([^"]+)"[^>]*\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"/g;
66
+ const SRI_ATTR_REVERSED = /\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"[^>]*\b(src|href)\s*=\s*"([^"]+)"/g;
67
+ function digest(bytes, algo, enc) {
68
+ return (0, node_crypto.createHash)(algo).update(bytes).digest(enc);
69
+ }
70
+ function fileFor(baseDir, ref) {
71
+ if (/^[a-z][a-z0-9+.-]*:/i.test(ref) || ref.startsWith("//")) return null;
72
+ const path = ref.split(/[?#]/)[0];
73
+ if (path === "") return null;
74
+ return (0, node_path.join)(baseDir, path);
75
+ }
76
+ function planHtmlIntegrity(browserDir, planned) {
77
+ for (const html of htmlFilesUnder(browserDir)) {
78
+ const text = (0, node_fs.readFileSync)(html, "utf8");
79
+ const rewrite = (algo, ref, match) => {
80
+ const file = fileFor(browserDir, ref);
81
+ if (file === null || !(0, node_fs.existsSync)(file)) return match;
82
+ const hash = digest((0, node_fs.readFileSync)(file), algo, "base64");
83
+ return match.replace(/integrity\s*=\s*"sha(?:256|384|512)-[^"]*"/, `integrity="${algo}-${hash}"`);
84
+ };
85
+ let next = text.replace(SRI_ATTR, (match, _attr, ref, algo) => rewrite(algo, ref, match));
86
+ next = next.replace(SRI_ATTR_REVERSED, (match, algo, _attr, ref) => rewrite(algo, ref, match));
87
+ if (next !== text) planned.set(html, next);
88
+ }
89
+ }
90
+ function htmlFilesUnder(dir) {
91
+ const out = [];
92
+ for (const entry of (0, node_fs.readdirSync)(dir, {
93
+ recursive: true,
94
+ encoding: "utf8"
95
+ })) if (entry.endsWith(".html")) out.push((0, node_path.join)(dir, entry));
96
+ return out;
97
+ }
98
+ const PLUGIN_LABEL = "@afterpack/angular";
99
+ function planNgswHashTable(browserDir, label, planned) {
100
+ const ngsw = (0, node_path.join)(browserDir, "ngsw.json");
101
+ if (!(0, node_fs.existsSync)(ngsw)) return;
102
+ const config = JSON.parse((0, node_fs.readFileSync)(ngsw, "utf8"));
103
+ const table = config.hashTable;
104
+ if (!table) return;
105
+ for (const url of Object.keys(table)) {
106
+ const file = (0, node_path.join)(browserDir, url.replace(/^\//, ""));
107
+ if (!(0, node_fs.existsSync)(file) || !(0, node_fs.statSync)(file).isFile()) throw new Error(`${label}: ngsw.json names ${url}, which is not in the browser output after obfuscation. AfterPack cannot recompute the service worker hash table. Rebuild, or disable the service worker for this build.`);
108
+ table[url] = digest(planned.get(file) ?? (0, node_fs.readFileSync)(file), "sha1", "hex");
109
+ }
110
+ planned.set(ngsw, `${JSON.stringify(config, null, 2)}\n`);
111
+ }
112
+ function planAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
113
+ const refusal = angularServerManifestRefusal(outputRoot);
114
+ if (refusal !== null) throw new Error(`${label}: ${refusal} — obfuscate only the browser output, or remove @afterpack/angular from the SSR build.`);
115
+ const planned = new Map();
116
+ planHtmlIntegrity(browserDir, planned);
117
+ planNgswHashTable(browserDir, label, planned);
118
+ return planned;
119
+ }
120
+ function recomputeAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
121
+ for (const [path, text] of planAngularIntegrity(outputRoot, browserDir, label)) writeFileAtomic(path, text);
122
+ }
123
+ function angularServerManifestRefusal(outputRoot) {
124
+ const serverDir = (0, node_path.join)(outputRoot, "server");
125
+ if (!(0, node_fs.existsSync)(serverDir)) return null;
126
+ for (const entry of (0, node_fs.readdirSync)(serverDir)) {
127
+ if (!/angular-app-(?:engine-)?manifest\.mjs$/.test(entry)) continue;
128
+ const text = (0, node_fs.readFileSync)((0, node_path.join)(serverDir, entry), "utf8");
129
+ if (/\bhash\s*:\s*['"`]/.test(text) || /\bintegrity\s*:/.test(text)) return `${entry} embeds asset hashes that AfterPack cannot recompute after renaming and obfuscating the browser output, so the SSR ETags would be stale. This Angular server build is not supported`;
130
+ }
131
+ return null;
132
+ }
133
+
134
+ //#endregion
35
135
  //#region ../protection-map/codec.mjs
36
136
  const COMPACT_SCHEMA_VERSION = 5;
37
137
  const DICT_FIELDS = [
@@ -436,35 +536,55 @@ function appendSourceMappingURL(code, mapPath) {
436
536
  const needsNewline = code.length > 0 && !code.endsWith("\n");
437
537
  return `${code}${needsNewline ? "\n" : ""}${comment}\n`;
438
538
  }
439
- function writeArtifacts(input) {
440
- const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
441
- const mode = input.mode ?? "single";
442
- const afterpackDir = input.afterpackDir;
443
- const logger = input.logger ?? DEFAULT_LOGGER;
539
+ function planArtifactWrites(input) {
540
+ const { outPath, code, sourceMapJson, originalSource, policy } = input;
444
541
  const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
445
- const paths = resolveArtifactPaths(outPath, mode, hash);
446
- const result = {
542
+ const paths = resolveArtifactPaths(outPath, input.mode ?? "single", hash);
543
+ const plan = {
447
544
  codePath: outPath,
448
545
  mapPath: null,
449
546
  backupPath: null,
450
- protectionMapPath: null,
451
- wroteSourceMappingURL: false
547
+ wroteSourceMappingURL: false,
548
+ writes: []
452
549
  };
453
550
  if (policy.backup && originalSource != null && paths.backupPath != null) {
454
- (0, node_fs.writeFileSync)(paths.backupPath, originalSource);
455
- result.backupPath = paths.backupPath;
551
+ plan.writes.push({
552
+ path: paths.backupPath,
553
+ content: originalSource
554
+ });
555
+ plan.backupPath = paths.backupPath;
456
556
  }
457
557
  const willWriteMap = policy.sourceMap && sourceMapJson != null;
458
558
  let finalCode = code;
459
559
  if (willWriteMap && policy.emitSourceMappingURL) {
460
560
  finalCode = appendSourceMappingURL(code, paths.mapPath);
461
- result.wroteSourceMappingURL = true;
561
+ plan.wroteSourceMappingURL = true;
462
562
  }
463
- (0, node_fs.writeFileSync)(outPath, finalCode);
563
+ plan.writes.push({
564
+ path: outPath,
565
+ content: finalCode
566
+ });
464
567
  if (willWriteMap && sourceMapJson != null) {
465
- (0, node_fs.writeFileSync)(paths.mapPath, sourceMapJson);
466
- result.mapPath = paths.mapPath;
568
+ plan.writes.push({
569
+ path: paths.mapPath,
570
+ content: sourceMapJson
571
+ });
572
+ plan.mapPath = paths.mapPath;
467
573
  }
574
+ return plan;
575
+ }
576
+ function writeArtifacts(input) {
577
+ const { protectionMapJson, policy } = input;
578
+ const mode = input.mode ?? "single";
579
+ const afterpackDir = input.afterpackDir;
580
+ const logger = input.logger ?? DEFAULT_LOGGER;
581
+ const paths = resolveArtifactPaths(input.outPath, mode);
582
+ const { writes,...planned } = planArtifactWrites(input);
583
+ for (const write of writes) writeFileAtomic(write.path, write.content);
584
+ const result = {
585
+ ...planned,
586
+ protectionMapPath: null
587
+ };
468
588
  if (mode === "single" && policy.protectionMap && protectionMapJson != null) {
469
589
  (0, node_fs.mkdirSync)(afterpackDir, { recursive: true });
470
590
  ensureAfterpackGitignore(afterpackDir);
@@ -1781,7 +1901,7 @@ function stripCssSourceMappingURLs(paths) {
1781
1901
  }
1782
1902
  const without = withoutCssSourceMappingURL(css);
1783
1903
  if (without === css) continue;
1784
- (0, node_fs.writeFileSync)(path, without);
1904
+ writeFileAtomic(path, without);
1785
1905
  stripped++;
1786
1906
  }
1787
1907
  return stripped;
@@ -2179,6 +2299,7 @@ function reportNotices(raw, logger, prefix = (m) => m) {
2179
2299
  //#region src/compat.ts
2180
2300
  const MIN_CORE_VERSION = "0.2.0";
2181
2301
  const SOURCE_TYPE_MIN_CORE_VERSION = "0.2.3";
2302
+ const FILE_SOURCE_TYPE_MIN_CORE_VERSION = "0.2.5";
2182
2303
  const CORE_PACKAGE = "@afterpack/core";
2183
2304
  const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
2184
2305
  const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -2253,6 +2374,9 @@ function isBelowVersion(version, minimum) {
2253
2374
  function coreSupportsSourceType(coreVersion) {
2254
2375
  return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, SOURCE_TYPE_MIN_CORE_VERSION);
2255
2376
  }
2377
+ function coreSupportsFileSourceType(coreVersion) {
2378
+ return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, FILE_SOURCE_TYPE_MIN_CORE_VERSION);
2379
+ }
2256
2380
  const CLI_PACKAGE = "afterpack";
2257
2381
  function updateCommand(identity, minVersion) {
2258
2382
  const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
@@ -3999,77 +4123,27 @@ function cloudEngineMismatch(engine, batchEngineVersion) {
3999
4123
  }
4000
4124
 
4001
4125
  //#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);
4126
+ //#region src/hash-tokens.ts
4127
+ const NEXT_CHUNKS_PREFIX = "static/chunks/";
4128
+ const TURBOPACK_CHUNK_RE = /^(?:turbopack-)?([0-9a-z~._-]{13})\.(?:js|css)$/;
4129
+ const WEBPACK_CHUNK_RE = /[-.]([0-9a-f]{16})\.js$/;
4130
+ const ANGULAR_HASHED_NAME_RE = /-([A-Z0-9]{8})\.(?:js|mjs|css)$/;
4131
+ function detectNextBundler(distDir) {
4132
+ if ((0, node_fs.existsSync)((0, node_path.join)(distDir, "turbopack"))) return "turbopack";
4133
+ if ((0, node_fs.existsSync)((0, node_path.join)(distDir, "server", "webpack-runtime.js"))) return "webpack";
4134
+ return "unknown";
4135
+ }
4136
+ function nextChunkToken(bundler, chunksPrefix = NEXT_CHUNKS_PREFIX) {
4137
+ const pattern = bundler === "turbopack" ? TURBOPACK_CHUNK_RE : bundler === "webpack" ? WEBPACK_CHUNK_RE : null;
4138
+ return (relativePath) => {
4139
+ if (pattern === null || !relativePath.startsWith(chunksPrefix)) return null;
4140
+ return pattern.exec((0, node_path.basename)(relativePath))?.[1] ?? null;
4141
+ };
4063
4142
  }
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);
4143
+ function skipNextInternals(relativePath) {
4144
+ return relativePath === "cache" || relativePath.startsWith("trace");
4072
4145
  }
4146
+ const angularHashToken = (relativePath) => ANGULAR_HASHED_NAME_RE.exec((0, node_path.basename)(relativePath))?.[1] ?? null;
4073
4147
 
4074
4148
  //#endregion
4075
4149
  //#region src/hashed-names.ts
@@ -4113,8 +4187,9 @@ function alphabetOf(token) {
4113
4187
  if (/^[0-9a-z~._-]+$/.test(token)) return LOWER_ALNUM;
4114
4188
  return ALNUM;
4115
4189
  }
4116
- function regionsKey(regions) {
4117
- return regions && regions.length > 0 ? JSON.stringify(regions) : "";
4190
+ function inputKey(input = {}) {
4191
+ const regions = input.regions && input.regions.length > 0 ? JSON.stringify(input.regions) : "";
4192
+ return input.sourceType === void 0 ? regions : `${regions}\0${input.sourceType}`;
4118
4193
  }
4119
4194
  function deriveHashToken(token, salt, regions = "") {
4120
4195
  const alphabet = alphabetOf(token);
@@ -4179,6 +4254,78 @@ function isCandidate(path) {
4179
4254
  const dot = name.lastIndexOf(".");
4180
4255
  return dot < 0 || !BINARY_EXTENSIONS.has(name.slice(dot));
4181
4256
  }
4257
+ function tokenAt(root, tokenOf, path) {
4258
+ const rel = toPosix$1((0, node_path.relative)(root, path));
4259
+ if (rel.startsWith("..")) return null;
4260
+ const token = tokenOf(rel);
4261
+ if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
4262
+ return (0, node_path.basename)(path).includes(token) ? token : null;
4263
+ }
4264
+ function unreferencedHashedFiles(options, files) {
4265
+ const owners = new Map();
4266
+ for (const file of files) {
4267
+ const token = tokenAt(options.root, options.tokenOf, file);
4268
+ if (token !== null) owners.set(token, (owners.get(token) ?? new Set()).add(file));
4269
+ }
4270
+ const pattern = tokenPattern(owners.keys());
4271
+ if (pattern === null) return [];
4272
+ const referenced = new Set();
4273
+ for (const path of listFiles(options.root, options.skip ?? (() => false))) {
4274
+ if (!isCandidate(path)) continue;
4275
+ const text = readText(path);
4276
+ if (text === null) continue;
4277
+ for (const [token] of text.matchAll(pattern)) for (const owner of owners.get(token) ?? []) if (owner !== path) referenced.add(owner);
4278
+ }
4279
+ return [...owners.values()].flatMap((set) => [...set]).filter((file) => !referenced.has(file)).sort();
4280
+ }
4281
+ const SCAN_SKIPPED_DIRS = new Set([
4282
+ "node_modules",
4283
+ ".git",
4284
+ AFTERPACK_DIR,
4285
+ ".cache",
4286
+ "cache"
4287
+ ]);
4288
+ function findHashTokenReference(paths, options, files, limits) {
4289
+ const tokens = files.map((file) => tokenAt(options.root, options.tokenOf, file)).filter((token) => token !== null);
4290
+ const pattern = tokenPattern(new Set(tokens));
4291
+ const result = {
4292
+ found: null,
4293
+ truncated: false
4294
+ };
4295
+ if (pattern === null) return result;
4296
+ let seenFiles = 0;
4297
+ let seenBytes = 0;
4298
+ const visit = (path, depth) => {
4299
+ if (result.found !== null || result.truncated || isWithinDir(options.root, path)) return;
4300
+ let stats;
4301
+ try {
4302
+ stats = (0, node_fs.statSync)(path);
4303
+ } catch {
4304
+ return;
4305
+ }
4306
+ if (stats.isDirectory()) {
4307
+ if (SCAN_SKIPPED_DIRS.has((0, node_path.basename)(path))) return;
4308
+ if (depth > limits.maxDepth) {
4309
+ result.truncated = true;
4310
+ return;
4311
+ }
4312
+ for (const entry of (0, node_fs.readdirSync)(path).sort()) visit((0, node_path.join)(path, entry), depth + 1);
4313
+ return;
4314
+ }
4315
+ if (!stats.isFile() || !isCandidate(path)) return;
4316
+ seenFiles += 1;
4317
+ seenBytes += stats.size;
4318
+ if (seenFiles > limits.maxFiles || seenBytes > limits.maxBytes) {
4319
+ result.truncated = true;
4320
+ return;
4321
+ }
4322
+ const text = readText(path);
4323
+ pattern.lastIndex = 0;
4324
+ if (text !== null && pattern.test(text)) result.found = path;
4325
+ };
4326
+ for (const path of paths) visit(path, 0);
4327
+ return result;
4328
+ }
4182
4329
  function writableDir(dir) {
4183
4330
  try {
4184
4331
  (0, node_fs.accessSync)(dir, node_fs.constants.W_OK);
@@ -4191,21 +4338,15 @@ function planHashedNames(input) {
4191
4338
  const { root, tokenOf } = input.options;
4192
4339
  const skip = input.options.skip ?? (() => false);
4193
4340
  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) => {
4341
+ const tokenOfPath = (path) => tokenAt(root, tokenOf, path);
4342
+ const addToken = (token, file) => {
4202
4343
  if (tokens.has(token)) return false;
4203
- tokens.set(token, deriveHashToken(token, input.salt, regionsKey(regions)));
4344
+ tokens.set(token, deriveHashToken(token, input.salt, inputKey(file)));
4204
4345
  return true;
4205
4346
  };
4206
- for (const [path, { regions }] of input.inputs) {
4347
+ for (const [path, file] of input.inputs) {
4207
4348
  const token = tokenOfPath(path);
4208
- if (token !== null) addToken(token, regions);
4349
+ if (token !== null) addToken(token, file);
4209
4350
  }
4210
4351
  const others = new Map();
4211
4352
  if (tokens.size > 0) for (const path of listFiles(root, skip)) {
@@ -4243,13 +4384,19 @@ function planHashedNames(input) {
4243
4384
  if (next !== path) renamed.set(path, next);
4244
4385
  }
4245
4386
  const writes = [];
4387
+ const rewrites = new Map();
4246
4388
  for (const path of changed) {
4247
4389
  const to = renamedPath(path);
4248
4390
  if (to !== path) renamed.set(path, to);
4391
+ const text = rewrite(others.get(path));
4392
+ rewrites.set(path, {
4393
+ to,
4394
+ text
4395
+ });
4249
4396
  writes.push({
4250
4397
  from: path,
4251
4398
  to,
4252
- text: rewrite(others.get(path))
4399
+ text
4253
4400
  });
4254
4401
  }
4255
4402
  const preflight = () => {
@@ -4264,20 +4411,102 @@ function planHashedNames(input) {
4264
4411
  return {
4265
4412
  tokens,
4266
4413
  renamed,
4414
+ rewrites,
4267
4415
  rewrite,
4268
4416
  preflight,
4269
4417
  apply() {
4270
4418
  preflight();
4419
+ const staged = [];
4420
+ try {
4421
+ for (const write of writes) {
4422
+ (0, node_fs.writeFileSync)(stagedPath(write.to), write.text);
4423
+ staged.push(stagedPath(write.to));
4424
+ }
4425
+ } catch (error) {
4426
+ for (const path of staged) (0, node_fs.rmSync)(path, { force: true });
4427
+ throw error;
4428
+ }
4271
4429
  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);
4430
+ (0, node_fs.renameSync)(stagedPath(write.to), write.to);
4275
4431
  if (write.to !== write.from) (0, node_fs.rmSync)(write.from, { force: true });
4276
4432
  }
4277
4433
  }
4278
4434
  };
4279
4435
  }
4280
4436
 
4437
+ //#endregion
4438
+ //#region src/git.ts
4439
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
4440
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
4441
+ function sanitizeCommitSha(value) {
4442
+ if (typeof value !== "string") return null;
4443
+ const sha = value.trim().toLowerCase();
4444
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
4445
+ }
4446
+ function sanitizeGitRef(value) {
4447
+ if (typeof value !== "string") return null;
4448
+ const ref = value.trim();
4449
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
4450
+ }
4451
+ function contextFrom(rawSha, rawRef) {
4452
+ const commitSha = sanitizeCommitSha(rawSha);
4453
+ const ref = sanitizeGitRef(rawRef);
4454
+ if (commitSha === null && ref === null) return null;
4455
+ const context = {};
4456
+ if (commitSha !== null) context.commitSha = commitSha;
4457
+ if (ref !== null) context.ref = ref;
4458
+ return context;
4459
+ }
4460
+ const CI_SOURCES = [
4461
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
4462
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
4463
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
4464
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
4465
+ ["GIT_COMMIT", "BRANCH_NAME"]
4466
+ ];
4467
+ function ciGitContext(env) {
4468
+ for (const [shaVar, refVar] of CI_SOURCES) {
4469
+ const context = contextFrom(env[shaVar], env[refVar]);
4470
+ if (context !== null) return context;
4471
+ }
4472
+ return null;
4473
+ }
4474
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
4475
+ function localGitContext(cwd) {
4476
+ let lines;
4477
+ try {
4478
+ const out = (0, node_child_process.execFileSync)("git", [
4479
+ "rev-parse",
4480
+ "HEAD",
4481
+ "--abbrev-ref",
4482
+ "HEAD"
4483
+ ], {
4484
+ cwd,
4485
+ stdio: [
4486
+ "ignore",
4487
+ "pipe",
4488
+ "ignore"
4489
+ ],
4490
+ timeout: GIT_PROBE_TIMEOUT_MS,
4491
+ maxBuffer: 64 * 1024
4492
+ }).toString();
4493
+ lines = out.split("\n").map((line) => line.trim());
4494
+ } catch {
4495
+ return null;
4496
+ }
4497
+ const ref = lines[1] === "HEAD" ? null : lines[1];
4498
+ return contextFrom(lines[0], ref);
4499
+ }
4500
+ function detectGitContext(explicit, deps = {}) {
4501
+ if (explicit) {
4502
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
4503
+ if (declared !== null) return declared;
4504
+ }
4505
+ const ci = ciGitContext(deps.env ?? process.env);
4506
+ if (ci !== null) return ci;
4507
+ return (deps.localGit ?? localGitContext)(deps.cwd);
4508
+ }
4509
+
4281
4510
  //#endregion
4282
4511
  //#region src/map-color.ts
4283
4512
  const UTF8 = new TextEncoder();
@@ -4497,8 +4726,8 @@ function receiptKey(buildDir) {
4497
4726
  const encoded = encodeURIComponent(buildDir).replace(/\*/g, "%2A").replace(/~/g, "%7E");
4498
4727
  if (Buffer.byteLength(encoded) <= MAX_KEY_BYTES) return encoded;
4499
4728
  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}`;
4729
+ const digest$1 = (0, node_crypto.createHash)("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4730
+ return `${prefix}~${digest$1}`;
4502
4731
  }
4503
4732
  function receiptsDirOf(home) {
4504
4733
  return (0, node_path.join)(home.dir, PROTECTION_RECEIPTS_DIR);
@@ -4509,6 +4738,9 @@ function receiptPathIn(home) {
4509
4738
  function homeOf(target) {
4510
4739
  return typeof target === "string" ? afterpackHome(target) : target;
4511
4740
  }
4741
+ function buildDirKey(target) {
4742
+ return receiptKey(buildDirOf(homeOf(target)));
4743
+ }
4512
4744
  function protectionReceiptPath(target) {
4513
4745
  return receiptPathIn(homeOf(target));
4514
4746
  }
@@ -5318,14 +5550,18 @@ function fileFailure(f, source) {
5318
5550
  if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
5319
5551
  return null;
5320
5552
  }
5321
- function removeBundlerSourceMaps(input) {
5322
- const { sweepDir: sweepDir$1, engineMaps, policy, label } = input;
5553
+ function bundlerMapsToRemove(input) {
5554
+ const { sweepDir: sweepDir$1, engineMaps, policy } = input;
5323
5555
  const bundlerMaps = new Set([...input.perFile].flat());
5324
5556
  if (sweepDir$1 != null) {
5325
5557
  const swept = collectSourceMaps(sweepDir$1).filter((path) => !policy.sourceMap || !path.endsWith(".css.map"));
5326
5558
  for (const path of containedSourceMaps(swept, sweepDir$1)) bundlerMaps.add(path);
5327
5559
  }
5328
- removeSourceMaps([...bundlerMaps].filter((path) => !engineMaps.has(path)), label);
5560
+ return [...bundlerMaps].filter((path) => !engineMaps.has(path));
5561
+ }
5562
+ function removeBundlerSourceMaps(input) {
5563
+ const { sweepDir: sweepDir$1, policy, label } = input;
5564
+ removeSourceMaps(bundlerMapsToRemove(input), label);
5329
5565
  if (sweepDir$1 != null && !policy.sourceMap) stripCssSourceMappingURLs(collectStylesheets(sweepDir$1));
5330
5566
  }
5331
5567
  function describeLevel(preset, complexity) {
@@ -5465,7 +5701,12 @@ async function runObfuscationPass(options) {
5465
5701
  cwd
5466
5702
  });
5467
5703
  const localEngineVersion = await readEngineVersion(engine);
5468
- const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(localEngineVersion ?? options.client?.coreVersion) ? options.sourceType : void 0;
5704
+ const gateVersion = localEngineVersion ?? options.client?.coreVersion;
5705
+ const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(gateVersion) ? options.sourceType : void 0;
5706
+ if (options.fileSourceTypes && options.engineConfig?.sourceType === void 0 && coreSupportsFileSourceType(gateVersion)) for (const input of inputs) {
5707
+ const sourceType = options.fileSourceTypes.get(input.path);
5708
+ if (sourceType !== void 0) input.sourceType = sourceType;
5709
+ }
5469
5710
  const engineConfig = buildEngineConfig({
5470
5711
  policy,
5471
5712
  seed,
@@ -5483,7 +5724,8 @@ async function runObfuscationPass(options) {
5483
5724
  const { seed: _seed,...configWithoutSeed } = engineConfig;
5484
5725
  const namedInputs = new Map(inputs.map((input) => [input.path, {
5485
5726
  source: input.source,
5486
- regions: input.regions
5727
+ regions: input.regions,
5728
+ sourceType: input.sourceType
5487
5729
  }]));
5488
5730
  hashSalt = afterpackHashSalt({
5489
5731
  seed,
@@ -5592,6 +5834,54 @@ async function runObfuscationPass(options) {
5592
5834
  source
5593
5835
  });
5594
5836
  }
5837
+ const artifactInput = (f, source) => ({
5838
+ outPath: f.path,
5839
+ code: withSourceMappingURL(f.code, null),
5840
+ sourceMapJson: f.sourceMap ?? null,
5841
+ originalSource: source,
5842
+ policy,
5843
+ mode: "framework"
5844
+ });
5845
+ if (!options.emitToCaller && options.beforeWrite) {
5846
+ const planned = new Map();
5847
+ const expectState = (path, state) => {
5848
+ const states = planned.get(path) ?? [];
5849
+ if (!states.includes(state)) states.push(state);
5850
+ planned.set(path, states);
5851
+ };
5852
+ for (const from of namesPlan?.renamed.keys() ?? []) expectState(from, null);
5853
+ const plannedEngineMaps = new Set();
5854
+ for (const { result: f, source } of verified) {
5855
+ const artifacts = planArtifactWrites(artifactInput(f, source));
5856
+ if (artifacts.mapPath) plannedEngineMaps.add((0, node_path.resolve)(artifacts.mapPath));
5857
+ for (const write of artifacts.writes) {
5858
+ expectState(write.path, sha256Hex(write.content));
5859
+ expectState(stagedPath(write.path), null);
5860
+ }
5861
+ }
5862
+ for (const { to, text } of namesPlan?.rewrites.values() ?? []) {
5863
+ expectState(to, sha256Hex(text));
5864
+ expectState(stagedPath(to), null);
5865
+ }
5866
+ for (const map of bundlerMapsToRemove({
5867
+ perFile: bundlerMapsByPath.values(),
5868
+ sweepDir: sweepDir$1,
5869
+ engineMaps: plannedEngineMaps,
5870
+ policy
5871
+ })) expectState(map, null);
5872
+ if (sweepDir$1 != null && !policy.sourceMap) for (const css of collectStylesheets(sweepDir$1)) {
5873
+ const rewritten = namesPlan?.rewrites.get(css);
5874
+ const text = rewritten?.text ?? (0, node_fs.readFileSync)(css, "utf8");
5875
+ const stripped = withoutCssSourceMappingURL(text);
5876
+ if (stripped === text) continue;
5877
+ expectState(rewritten?.to ?? css, sha256Hex(stripped));
5878
+ expectState(stagedPath(rewritten?.to ?? css), null);
5879
+ }
5880
+ options.beforeWrite({
5881
+ renamed: namesPlan?.renamed ?? new Map(),
5882
+ planned
5883
+ });
5884
+ }
5595
5885
  const writtenFiles = [];
5596
5886
  const emittedFiles = [];
5597
5887
  const engineMaps = new Set();
@@ -5606,13 +5896,8 @@ async function runObfuscationPass(options) {
5606
5896
  continue;
5607
5897
  }
5608
5898
  const written = writeArtifacts({
5609
- outPath: f.path,
5610
- code: withSourceMappingURL(f.code, null),
5611
- sourceMapJson: f.sourceMap ?? null,
5899
+ ...artifactInput(f, source),
5612
5900
  protectionMapJson: null,
5613
- originalSource: source,
5614
- policy,
5615
- mode: "framework",
5616
5901
  afterpackDir: home.dir,
5617
5902
  logger
5618
5903
  });
@@ -5905,35 +6190,45 @@ exports.DIAG_AFTERPACK_DIR_IN_OUTPUT = DIAG_AFTERPACK_DIR_IN_OUTPUT;
5905
6190
  exports.DIAG_ALREADY_OBFUSCATED = DIAG_ALREADY_OBFUSCATED;
5906
6191
  exports.DIAG_RECEIPT_UNREADABLE = DIAG_RECEIPT_UNREADABLE;
5907
6192
  exports.DIAG_RECEIPT_UNWRITABLE = DIAG_RECEIPT_UNWRITABLE;
6193
+ exports.NEXT_CHUNKS_PREFIX = NEXT_CHUNKS_PREFIX;
5908
6194
  exports.PROTECTION_RECEIPTS_DIR = PROTECTION_RECEIPTS_DIR;
5909
6195
  exports.SEED_ENV_VAR = SEED_ENV_VAR;
5910
6196
  exports.UnreadableReceiptError = UnreadableReceiptError;
5911
6197
  exports.afterpackHome = afterpackHome;
6198
+ exports.angularHashToken = angularHashToken;
6199
+ exports.angularServerManifestRefusal = angularServerManifestRefusal;
5912
6200
  exports.applyBundleOutput = applyBundleOutput;
5913
6201
  exports.applyResolvedKey = applyResolvedKey;
6202
+ exports.buildDirKey = buildDirKey;
5914
6203
  exports.collectBundleJs = collectBundleJs;
5915
6204
  exports.collectJsFiles = collectJsFiles;
5916
6205
  exports.collectSourceMaps = collectSourceMaps;
5917
6206
  exports.collectStylesheets = collectStylesheets;
5918
6207
  exports.createTelemetryReporter = createTelemetryReporter;
5919
6208
  exports.decodeDataUri = decodeDataUri;
6209
+ exports.detectNextBundler = detectNextBundler;
5920
6210
  exports.discoverInputSourceMap = discoverInputSourceMap;
5921
6211
  exports.ensureAfterpackGitignore = ensureAfterpackGitignore;
5922
6212
  exports.extractSourceMappingURL = extractSourceMappingURL;
6213
+ exports.findHashTokenReference = findHashTokenReference;
5923
6214
  exports.findUpward = findUpward;
5924
6215
  exports.getPath = getPath;
5925
6216
  exports.installedRequiredLine = installedRequiredLine;
6217
+ exports.isWithinDir = isWithinDir;
5926
6218
  exports.loadConfigFile = loadConfigFile;
5927
6219
  exports.locateProtectionReceipt = locateProtectionReceipt;
5928
6220
  exports.mergeConfig = mergeConfig;
6221
+ exports.nextChunkToken = nextChunkToken;
5929
6222
  exports.normalizePluginOptions = normalizePluginOptions;
5930
6223
  exports.npxAlternative = npxAlternative;
5931
6224
  exports.parseCliOptions = parseCliOptions;
5932
6225
  exports.parseEnvOptions = parseEnvOptions;
5933
6226
  exports.passSettings = passSettings;
6227
+ exports.planAngularIntegrity = planAngularIntegrity;
5934
6228
  exports.prepareHashSalt = prepareHashSalt;
5935
6229
  exports.protectionReceiptPath = protectionReceiptPath;
5936
6230
  exports.readEngineVersion = readEngineVersion;
6231
+ exports.recomputeAngularIntegrity = recomputeAngularIntegrity;
5937
6232
  exports.regenerateCompressedSiblings = regenerateCompressedSiblings;
5938
6233
  exports.removeSourceMaps = removeSourceMaps;
5939
6234
  exports.reportPolicySaltBits = reportPolicySaltBits;
@@ -5945,15 +6240,19 @@ exports.saltSettings = saltSettings;
5945
6240
  exports.sanitizeNotices = sanitizeNotices;
5946
6241
  exports.scanDirectives = scanDirectives;
5947
6242
  exports.serverAddsInfo = serverAddsInfo;
6243
+ exports.sha256Hex = sha256Hex;
5948
6244
  exports.sha256Of = sha256Of;
6245
+ exports.skipNextInternals = skipNextInternals;
5949
6246
  exports.sourceTypeForBundle = sourceTypeForBundle;
5950
6247
  exports.sourceTypeForOutputFormat = sourceTypeForOutputFormat;
5951
6248
  exports.sriPluginRefusal = sriPluginRefusal;
6249
+ exports.stagedPath = stagedPath;
5952
6250
  exports.stripBundleCssSourceMaps = stripBundleCssSourceMaps;
5953
6251
  exports.stripCssSourceMappingURLs = stripCssSourceMappingURLs;
5954
6252
  exports.sweepOutputTree = sweepOutputTree;
5955
6253
  exports.toEngineConfig = toEngineConfig;
5956
6254
  exports.toPluginOptions = toPluginOptions;
6255
+ exports.unreferencedHashedFiles = unreferencedHashedFiles;
5957
6256
  exports.unsaltedAssetsWarning = unsaltedAssetsWarning;
5958
6257
  exports.validateConfig = validateConfig;
5959
6258
  exports.verifyProtectionReceipt = verifyProtectionReceipt;
@@ -5961,4 +6260,5 @@ exports.withSourceMappingURL = withSourceMappingURL;
5961
6260
  exports.withoutCssSourceMappingURL = withoutCssSourceMappingURL;
5962
6261
  exports.writeArtifacts = writeArtifacts;
5963
6262
  exports.writeDeferredProtectionReceipt = writeDeferredProtectionReceipt;
6263
+ exports.writeFileAtomic = writeFileAtomic;
5964
6264
  exports.writeProtectionReceipt = writeProtectionReceipt;