@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.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { createRequire } from "node:module";
2
- import { accessSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
+ import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
4
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
4
5
  import { renderProtectionMapHtml } from "@afterpack/protection-map";
5
- import { createHash, randomBytes, randomUUID } from "node:crypto";
6
6
  import { brotliCompressSync, gzipSync } from "node:zlib";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { execFileSync } from "node:child_process";
@@ -10,6 +10,106 @@ import { homedir, tmpdir, userInfo } from "node:os";
10
10
  import { readFile } from "node:fs/promises";
11
11
  import { decode } from "@jridgewell/sourcemap-codec";
12
12
 
13
+ //#region src/atomic-write.ts
14
+ const STAGED_SUFFIX = ".afterpack-tmp";
15
+ function stagedPath(path) {
16
+ return `${path}${STAGED_SUFFIX}`;
17
+ }
18
+ function sha256Hex(content) {
19
+ return createHash("sha256").update(content).digest("hex");
20
+ }
21
+ function writeFileAtomic(path, content) {
22
+ const staged = stagedPath(path);
23
+ let mode = null;
24
+ try {
25
+ mode = statSync(path).mode & 4095;
26
+ } catch {
27
+ mode = null;
28
+ }
29
+ try {
30
+ writeFileSync(staged, content);
31
+ if (mode !== null) chmodSync(staged, mode);
32
+ renameSync(staged, path);
33
+ } catch (error) {
34
+ try {
35
+ rmSync(staged, { force: true });
36
+ } catch {}
37
+ throw error;
38
+ }
39
+ }
40
+
41
+ //#endregion
42
+ //#region src/angular-integrity.ts
43
+ const SRI_ATTR = /\b(src|href)\s*=\s*"([^"]+)"[^>]*\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"/g;
44
+ const SRI_ATTR_REVERSED = /\bintegrity\s*=\s*"(sha(?:256|384|512))-[^"]*"[^>]*\b(src|href)\s*=\s*"([^"]+)"/g;
45
+ function digest(bytes, algo, enc) {
46
+ return createHash(algo).update(bytes).digest(enc);
47
+ }
48
+ function fileFor(baseDir, ref) {
49
+ if (/^[a-z][a-z0-9+.-]*:/i.test(ref) || ref.startsWith("//")) return null;
50
+ const path = ref.split(/[?#]/)[0];
51
+ if (path === "") return null;
52
+ return join(baseDir, path);
53
+ }
54
+ function planHtmlIntegrity(browserDir, planned) {
55
+ for (const html of htmlFilesUnder(browserDir)) {
56
+ const text = readFileSync(html, "utf8");
57
+ const rewrite = (algo, ref, match) => {
58
+ const file = fileFor(browserDir, ref);
59
+ if (file === null || !existsSync(file)) return match;
60
+ const hash = digest(readFileSync(file), algo, "base64");
61
+ return match.replace(/integrity\s*=\s*"sha(?:256|384|512)-[^"]*"/, `integrity="${algo}-${hash}"`);
62
+ };
63
+ let next = text.replace(SRI_ATTR, (match, _attr, ref, algo) => rewrite(algo, ref, match));
64
+ next = next.replace(SRI_ATTR_REVERSED, (match, algo, _attr, ref) => rewrite(algo, ref, match));
65
+ if (next !== text) planned.set(html, next);
66
+ }
67
+ }
68
+ function htmlFilesUnder(dir) {
69
+ const out = [];
70
+ for (const entry of readdirSync(dir, {
71
+ recursive: true,
72
+ encoding: "utf8"
73
+ })) if (entry.endsWith(".html")) out.push(join(dir, entry));
74
+ return out;
75
+ }
76
+ const PLUGIN_LABEL = "@afterpack/angular";
77
+ function planNgswHashTable(browserDir, label, planned) {
78
+ const ngsw = join(browserDir, "ngsw.json");
79
+ if (!existsSync(ngsw)) return;
80
+ const config = JSON.parse(readFileSync(ngsw, "utf8"));
81
+ const table = config.hashTable;
82
+ if (!table) return;
83
+ for (const url of Object.keys(table)) {
84
+ const file = join(browserDir, url.replace(/^\//, ""));
85
+ if (!existsSync(file) || !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.`);
86
+ table[url] = digest(planned.get(file) ?? readFileSync(file), "sha1", "hex");
87
+ }
88
+ planned.set(ngsw, `${JSON.stringify(config, null, 2)}\n`);
89
+ }
90
+ function planAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
91
+ const refusal = angularServerManifestRefusal(outputRoot);
92
+ if (refusal !== null) throw new Error(`${label}: ${refusal} — obfuscate only the browser output, or remove @afterpack/angular from the SSR build.`);
93
+ const planned = new Map();
94
+ planHtmlIntegrity(browserDir, planned);
95
+ planNgswHashTable(browserDir, label, planned);
96
+ return planned;
97
+ }
98
+ function recomputeAngularIntegrity(outputRoot, browserDir, label = PLUGIN_LABEL) {
99
+ for (const [path, text] of planAngularIntegrity(outputRoot, browserDir, label)) writeFileAtomic(path, text);
100
+ }
101
+ function angularServerManifestRefusal(outputRoot) {
102
+ const serverDir = join(outputRoot, "server");
103
+ if (!existsSync(serverDir)) return null;
104
+ for (const entry of readdirSync(serverDir)) {
105
+ if (!/angular-app-(?:engine-)?manifest\.mjs$/.test(entry)) continue;
106
+ const text = readFileSync(join(serverDir, entry), "utf8");
107
+ 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`;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ //#endregion
13
113
  //#region src/home.ts
14
114
  const AFTERPACK_DIR = ".afterpack";
15
115
  const STRONG_MARKERS = [
@@ -148,35 +248,55 @@ function appendSourceMappingURL(code, mapPath) {
148
248
  const needsNewline = code.length > 0 && !code.endsWith("\n");
149
249
  return `${code}${needsNewline ? "\n" : ""}${comment}\n`;
150
250
  }
151
- function writeArtifacts(input) {
152
- const { outPath, code, sourceMapJson, protectionMapJson, originalSource, policy } = input;
153
- const mode = input.mode ?? "single";
154
- const afterpackDir = input.afterpackDir;
155
- const logger = input.logger ?? DEFAULT_LOGGER;
251
+ function planArtifactWrites(input) {
252
+ const { outPath, code, sourceMapJson, originalSource, policy } = input;
156
253
  const hash = policy.backup && originalSource != null ? shortHash(originalSource) : void 0;
157
- const paths = resolveArtifactPaths(outPath, mode, hash);
158
- const result = {
254
+ const paths = resolveArtifactPaths(outPath, input.mode ?? "single", hash);
255
+ const plan = {
159
256
  codePath: outPath,
160
257
  mapPath: null,
161
258
  backupPath: null,
162
- protectionMapPath: null,
163
- wroteSourceMappingURL: false
259
+ wroteSourceMappingURL: false,
260
+ writes: []
164
261
  };
165
262
  if (policy.backup && originalSource != null && paths.backupPath != null) {
166
- writeFileSync(paths.backupPath, originalSource);
167
- result.backupPath = paths.backupPath;
263
+ plan.writes.push({
264
+ path: paths.backupPath,
265
+ content: originalSource
266
+ });
267
+ plan.backupPath = paths.backupPath;
168
268
  }
169
269
  const willWriteMap = policy.sourceMap && sourceMapJson != null;
170
270
  let finalCode = code;
171
271
  if (willWriteMap && policy.emitSourceMappingURL) {
172
272
  finalCode = appendSourceMappingURL(code, paths.mapPath);
173
- result.wroteSourceMappingURL = true;
273
+ plan.wroteSourceMappingURL = true;
174
274
  }
175
- writeFileSync(outPath, finalCode);
275
+ plan.writes.push({
276
+ path: outPath,
277
+ content: finalCode
278
+ });
176
279
  if (willWriteMap && sourceMapJson != null) {
177
- writeFileSync(paths.mapPath, sourceMapJson);
178
- result.mapPath = paths.mapPath;
280
+ plan.writes.push({
281
+ path: paths.mapPath,
282
+ content: sourceMapJson
283
+ });
284
+ plan.mapPath = paths.mapPath;
179
285
  }
286
+ return plan;
287
+ }
288
+ function writeArtifacts(input) {
289
+ const { protectionMapJson, policy } = input;
290
+ const mode = input.mode ?? "single";
291
+ const afterpackDir = input.afterpackDir;
292
+ const logger = input.logger ?? DEFAULT_LOGGER;
293
+ const paths = resolveArtifactPaths(input.outPath, mode);
294
+ const { writes,...planned } = planArtifactWrites(input);
295
+ for (const write of writes) writeFileAtomic(write.path, write.content);
296
+ const result = {
297
+ ...planned,
298
+ protectionMapPath: null
299
+ };
180
300
  if (mode === "single" && policy.protectionMap && protectionMapJson != null) {
181
301
  mkdirSync(afterpackDir, { recursive: true });
182
302
  ensureAfterpackGitignore(afterpackDir);
@@ -1493,7 +1613,7 @@ function stripCssSourceMappingURLs(paths) {
1493
1613
  }
1494
1614
  const without = withoutCssSourceMappingURL(css);
1495
1615
  if (without === css) continue;
1496
- writeFileSync(path, without);
1616
+ writeFileAtomic(path, without);
1497
1617
  stripped++;
1498
1618
  }
1499
1619
  return stripped;
@@ -1891,6 +2011,7 @@ function reportNotices(raw, logger, prefix = (m) => m) {
1891
2011
  //#region src/compat.ts
1892
2012
  const MIN_CORE_VERSION = "0.2.0";
1893
2013
  const SOURCE_TYPE_MIN_CORE_VERSION = "0.2.3";
2014
+ const FILE_SOURCE_TYPE_MIN_CORE_VERSION = "0.2.5";
1894
2015
  const CORE_PACKAGE = "@afterpack/core";
1895
2016
  const VERSION_PATTERN$1 = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
1896
2017
  const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -1965,6 +2086,9 @@ function isBelowVersion(version, minimum) {
1965
2086
  function coreSupportsSourceType(coreVersion) {
1966
2087
  return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, SOURCE_TYPE_MIN_CORE_VERSION);
1967
2088
  }
2089
+ function coreSupportsFileSourceType(coreVersion) {
2090
+ return releaseTriple(coreVersion) !== null && !isBelowVersion(coreVersion, FILE_SOURCE_TYPE_MIN_CORE_VERSION);
2091
+ }
1968
2092
  const CLI_PACKAGE = "afterpack";
1969
2093
  function updateCommand(identity, minVersion) {
1970
2094
  const core = `${CORE_PACKAGE}@${safeVersionString(minVersion) ?? "latest"}`;
@@ -3711,77 +3835,27 @@ function cloudEngineMismatch(engine, batchEngineVersion) {
3711
3835
  }
3712
3836
 
3713
3837
  //#endregion
3714
- //#region src/git.ts
3715
- const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
3716
- const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
3717
- function sanitizeCommitSha(value) {
3718
- if (typeof value !== "string") return null;
3719
- const sha = value.trim().toLowerCase();
3720
- return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
3721
- }
3722
- function sanitizeGitRef(value) {
3723
- if (typeof value !== "string") return null;
3724
- const ref = value.trim();
3725
- return GIT_REF_PATTERN.test(ref) ? ref : null;
3726
- }
3727
- function contextFrom(rawSha, rawRef) {
3728
- const commitSha = sanitizeCommitSha(rawSha);
3729
- const ref = sanitizeGitRef(rawRef);
3730
- if (commitSha === null && ref === null) return null;
3731
- const context = {};
3732
- if (commitSha !== null) context.commitSha = commitSha;
3733
- if (ref !== null) context.ref = ref;
3734
- return context;
3735
- }
3736
- const CI_SOURCES = [
3737
- ["GITHUB_SHA", "GITHUB_REF_NAME"],
3738
- ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
3739
- ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
3740
- ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
3741
- ["GIT_COMMIT", "BRANCH_NAME"]
3742
- ];
3743
- function ciGitContext(env) {
3744
- for (const [shaVar, refVar] of CI_SOURCES) {
3745
- const context = contextFrom(env[shaVar], env[refVar]);
3746
- if (context !== null) return context;
3747
- }
3748
- return null;
3749
- }
3750
- const GIT_PROBE_TIMEOUT_MS = 2e3;
3751
- function localGitContext(cwd) {
3752
- let lines;
3753
- try {
3754
- const out = execFileSync("git", [
3755
- "rev-parse",
3756
- "HEAD",
3757
- "--abbrev-ref",
3758
- "HEAD"
3759
- ], {
3760
- cwd,
3761
- stdio: [
3762
- "ignore",
3763
- "pipe",
3764
- "ignore"
3765
- ],
3766
- timeout: GIT_PROBE_TIMEOUT_MS,
3767
- maxBuffer: 64 * 1024
3768
- }).toString();
3769
- lines = out.split("\n").map((line) => line.trim());
3770
- } catch {
3771
- return null;
3772
- }
3773
- const ref = lines[1] === "HEAD" ? null : lines[1];
3774
- return contextFrom(lines[0], ref);
3838
+ //#region src/hash-tokens.ts
3839
+ const NEXT_CHUNKS_PREFIX = "static/chunks/";
3840
+ const TURBOPACK_CHUNK_RE = /^(?:turbopack-)?([0-9a-z~._-]{13})\.(?:js|css)$/;
3841
+ const WEBPACK_CHUNK_RE = /[-.]([0-9a-f]{16})\.js$/;
3842
+ const ANGULAR_HASHED_NAME_RE = /-([A-Z0-9]{8})\.(?:js|mjs|css)$/;
3843
+ function detectNextBundler(distDir) {
3844
+ if (existsSync(join(distDir, "turbopack"))) return "turbopack";
3845
+ if (existsSync(join(distDir, "server", "webpack-runtime.js"))) return "webpack";
3846
+ return "unknown";
3847
+ }
3848
+ function nextChunkToken(bundler, chunksPrefix = NEXT_CHUNKS_PREFIX) {
3849
+ const pattern = bundler === "turbopack" ? TURBOPACK_CHUNK_RE : bundler === "webpack" ? WEBPACK_CHUNK_RE : null;
3850
+ return (relativePath) => {
3851
+ if (pattern === null || !relativePath.startsWith(chunksPrefix)) return null;
3852
+ return pattern.exec(basename(relativePath))?.[1] ?? null;
3853
+ };
3775
3854
  }
3776
- function detectGitContext(explicit, deps = {}) {
3777
- if (explicit) {
3778
- const declared = contextFrom(explicit.commitSha, explicit.ref);
3779
- if (declared !== null) return declared;
3780
- }
3781
- const ci = ciGitContext(deps.env ?? process.env);
3782
- if (ci !== null) return ci;
3783
- return (deps.localGit ?? localGitContext)(deps.cwd);
3855
+ function skipNextInternals(relativePath) {
3856
+ return relativePath === "cache" || relativePath.startsWith("trace");
3784
3857
  }
3858
+ const angularHashToken = (relativePath) => ANGULAR_HASHED_NAME_RE.exec(basename(relativePath))?.[1] ?? null;
3785
3859
 
3786
3860
  //#endregion
3787
3861
  //#region src/hashed-names.ts
@@ -3825,8 +3899,9 @@ function alphabetOf(token) {
3825
3899
  if (/^[0-9a-z~._-]+$/.test(token)) return LOWER_ALNUM;
3826
3900
  return ALNUM;
3827
3901
  }
3828
- function regionsKey(regions) {
3829
- return regions && regions.length > 0 ? JSON.stringify(regions) : "";
3902
+ function inputKey(input = {}) {
3903
+ const regions = input.regions && input.regions.length > 0 ? JSON.stringify(input.regions) : "";
3904
+ return input.sourceType === void 0 ? regions : `${regions}\0${input.sourceType}`;
3830
3905
  }
3831
3906
  function deriveHashToken(token, salt, regions = "") {
3832
3907
  const alphabet = alphabetOf(token);
@@ -3891,6 +3966,78 @@ function isCandidate(path) {
3891
3966
  const dot = name.lastIndexOf(".");
3892
3967
  return dot < 0 || !BINARY_EXTENSIONS.has(name.slice(dot));
3893
3968
  }
3969
+ function tokenAt(root, tokenOf, path) {
3970
+ const rel = toPosix$1(relative(root, path));
3971
+ if (rel.startsWith("..")) return null;
3972
+ const token = tokenOf(rel);
3973
+ if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
3974
+ return basename(path).includes(token) ? token : null;
3975
+ }
3976
+ function unreferencedHashedFiles(options, files) {
3977
+ const owners = new Map();
3978
+ for (const file of files) {
3979
+ const token = tokenAt(options.root, options.tokenOf, file);
3980
+ if (token !== null) owners.set(token, (owners.get(token) ?? new Set()).add(file));
3981
+ }
3982
+ const pattern = tokenPattern(owners.keys());
3983
+ if (pattern === null) return [];
3984
+ const referenced = new Set();
3985
+ for (const path of listFiles(options.root, options.skip ?? (() => false))) {
3986
+ if (!isCandidate(path)) continue;
3987
+ const text = readText(path);
3988
+ if (text === null) continue;
3989
+ for (const [token] of text.matchAll(pattern)) for (const owner of owners.get(token) ?? []) if (owner !== path) referenced.add(owner);
3990
+ }
3991
+ return [...owners.values()].flatMap((set) => [...set]).filter((file) => !referenced.has(file)).sort();
3992
+ }
3993
+ const SCAN_SKIPPED_DIRS = new Set([
3994
+ "node_modules",
3995
+ ".git",
3996
+ AFTERPACK_DIR,
3997
+ ".cache",
3998
+ "cache"
3999
+ ]);
4000
+ function findHashTokenReference(paths, options, files, limits) {
4001
+ const tokens = files.map((file) => tokenAt(options.root, options.tokenOf, file)).filter((token) => token !== null);
4002
+ const pattern = tokenPattern(new Set(tokens));
4003
+ const result = {
4004
+ found: null,
4005
+ truncated: false
4006
+ };
4007
+ if (pattern === null) return result;
4008
+ let seenFiles = 0;
4009
+ let seenBytes = 0;
4010
+ const visit = (path, depth) => {
4011
+ if (result.found !== null || result.truncated || isWithinDir(options.root, path)) return;
4012
+ let stats;
4013
+ try {
4014
+ stats = statSync(path);
4015
+ } catch {
4016
+ return;
4017
+ }
4018
+ if (stats.isDirectory()) {
4019
+ if (SCAN_SKIPPED_DIRS.has(basename(path))) return;
4020
+ if (depth > limits.maxDepth) {
4021
+ result.truncated = true;
4022
+ return;
4023
+ }
4024
+ for (const entry of readdirSync(path).sort()) visit(join(path, entry), depth + 1);
4025
+ return;
4026
+ }
4027
+ if (!stats.isFile() || !isCandidate(path)) return;
4028
+ seenFiles += 1;
4029
+ seenBytes += stats.size;
4030
+ if (seenFiles > limits.maxFiles || seenBytes > limits.maxBytes) {
4031
+ result.truncated = true;
4032
+ return;
4033
+ }
4034
+ const text = readText(path);
4035
+ pattern.lastIndex = 0;
4036
+ if (text !== null && pattern.test(text)) result.found = path;
4037
+ };
4038
+ for (const path of paths) visit(path, 0);
4039
+ return result;
4040
+ }
3894
4041
  function writableDir(dir) {
3895
4042
  try {
3896
4043
  accessSync(dir, constants.W_OK);
@@ -3903,21 +4050,15 @@ function planHashedNames(input) {
3903
4050
  const { root, tokenOf } = input.options;
3904
4051
  const skip = input.options.skip ?? (() => false);
3905
4052
  const tokens = new Map();
3906
- const tokenOfPath = (path) => {
3907
- const rel = toPosix$1(relative(root, path));
3908
- if (rel.startsWith("..")) return null;
3909
- const token = tokenOf(rel);
3910
- if (token === null || token.length < MIN_TOKEN_LENGTH) return null;
3911
- return basename(path).includes(token) ? token : null;
3912
- };
3913
- const addToken = (token, regions) => {
4053
+ const tokenOfPath = (path) => tokenAt(root, tokenOf, path);
4054
+ const addToken = (token, file) => {
3914
4055
  if (tokens.has(token)) return false;
3915
- tokens.set(token, deriveHashToken(token, input.salt, regionsKey(regions)));
4056
+ tokens.set(token, deriveHashToken(token, input.salt, inputKey(file)));
3916
4057
  return true;
3917
4058
  };
3918
- for (const [path, { regions }] of input.inputs) {
4059
+ for (const [path, file] of input.inputs) {
3919
4060
  const token = tokenOfPath(path);
3920
- if (token !== null) addToken(token, regions);
4061
+ if (token !== null) addToken(token, file);
3921
4062
  }
3922
4063
  const others = new Map();
3923
4064
  if (tokens.size > 0) for (const path of listFiles(root, skip)) {
@@ -3955,13 +4096,19 @@ function planHashedNames(input) {
3955
4096
  if (next !== path) renamed.set(path, next);
3956
4097
  }
3957
4098
  const writes = [];
4099
+ const rewrites = new Map();
3958
4100
  for (const path of changed) {
3959
4101
  const to = renamedPath(path);
3960
4102
  if (to !== path) renamed.set(path, to);
4103
+ const text = rewrite(others.get(path));
4104
+ rewrites.set(path, {
4105
+ to,
4106
+ text
4107
+ });
3961
4108
  writes.push({
3962
4109
  from: path,
3963
4110
  to,
3964
- text: rewrite(others.get(path))
4111
+ text
3965
4112
  });
3966
4113
  }
3967
4114
  const preflight = () => {
@@ -3976,20 +4123,102 @@ function planHashedNames(input) {
3976
4123
  return {
3977
4124
  tokens,
3978
4125
  renamed,
4126
+ rewrites,
3979
4127
  rewrite,
3980
4128
  preflight,
3981
4129
  apply() {
3982
4130
  preflight();
4131
+ const staged = [];
4132
+ try {
4133
+ for (const write of writes) {
4134
+ writeFileSync(stagedPath(write.to), write.text);
4135
+ staged.push(stagedPath(write.to));
4136
+ }
4137
+ } catch (error) {
4138
+ for (const path of staged) rmSync(path, { force: true });
4139
+ throw error;
4140
+ }
3983
4141
  for (const write of writes) {
3984
- const tmp = `${write.to}.afterpack-tmp`;
3985
- writeFileSync(tmp, write.text);
3986
- renameSync(tmp, write.to);
4142
+ renameSync(stagedPath(write.to), write.to);
3987
4143
  if (write.to !== write.from) rmSync(write.from, { force: true });
3988
4144
  }
3989
4145
  }
3990
4146
  };
3991
4147
  }
3992
4148
 
4149
+ //#endregion
4150
+ //#region src/git.ts
4151
+ const GIT_COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/;
4152
+ const GIT_REF_PATTERN = /^[A-Za-z0-9._\-/+]{1,200}$/;
4153
+ function sanitizeCommitSha(value) {
4154
+ if (typeof value !== "string") return null;
4155
+ const sha = value.trim().toLowerCase();
4156
+ return GIT_COMMIT_SHA_PATTERN.test(sha) ? sha : null;
4157
+ }
4158
+ function sanitizeGitRef(value) {
4159
+ if (typeof value !== "string") return null;
4160
+ const ref = value.trim();
4161
+ return GIT_REF_PATTERN.test(ref) ? ref : null;
4162
+ }
4163
+ function contextFrom(rawSha, rawRef) {
4164
+ const commitSha = sanitizeCommitSha(rawSha);
4165
+ const ref = sanitizeGitRef(rawRef);
4166
+ if (commitSha === null && ref === null) return null;
4167
+ const context = {};
4168
+ if (commitSha !== null) context.commitSha = commitSha;
4169
+ if (ref !== null) context.ref = ref;
4170
+ return context;
4171
+ }
4172
+ const CI_SOURCES = [
4173
+ ["GITHUB_SHA", "GITHUB_REF_NAME"],
4174
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
4175
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
4176
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH"],
4177
+ ["GIT_COMMIT", "BRANCH_NAME"]
4178
+ ];
4179
+ function ciGitContext(env) {
4180
+ for (const [shaVar, refVar] of CI_SOURCES) {
4181
+ const context = contextFrom(env[shaVar], env[refVar]);
4182
+ if (context !== null) return context;
4183
+ }
4184
+ return null;
4185
+ }
4186
+ const GIT_PROBE_TIMEOUT_MS = 2e3;
4187
+ function localGitContext(cwd) {
4188
+ let lines;
4189
+ try {
4190
+ const out = execFileSync("git", [
4191
+ "rev-parse",
4192
+ "HEAD",
4193
+ "--abbrev-ref",
4194
+ "HEAD"
4195
+ ], {
4196
+ cwd,
4197
+ stdio: [
4198
+ "ignore",
4199
+ "pipe",
4200
+ "ignore"
4201
+ ],
4202
+ timeout: GIT_PROBE_TIMEOUT_MS,
4203
+ maxBuffer: 64 * 1024
4204
+ }).toString();
4205
+ lines = out.split("\n").map((line) => line.trim());
4206
+ } catch {
4207
+ return null;
4208
+ }
4209
+ const ref = lines[1] === "HEAD" ? null : lines[1];
4210
+ return contextFrom(lines[0], ref);
4211
+ }
4212
+ function detectGitContext(explicit, deps = {}) {
4213
+ if (explicit) {
4214
+ const declared = contextFrom(explicit.commitSha, explicit.ref);
4215
+ if (declared !== null) return declared;
4216
+ }
4217
+ const ci = ciGitContext(deps.env ?? process.env);
4218
+ if (ci !== null) return ci;
4219
+ return (deps.localGit ?? localGitContext)(deps.cwd);
4220
+ }
4221
+
3993
4222
  //#endregion
3994
4223
  //#region src/map-color.ts
3995
4224
  const UTF8 = new TextEncoder();
@@ -4209,8 +4438,8 @@ function receiptKey(buildDir) {
4209
4438
  const encoded = encodeURIComponent(buildDir).replace(/\*/g, "%2A").replace(/~/g, "%7E");
4210
4439
  if (Buffer.byteLength(encoded) <= MAX_KEY_BYTES) return encoded;
4211
4440
  const prefix = encoded.slice(0, HASHED_KEY_PREFIX_BYTES).replace(/%[0-9A-F]?$/, "");
4212
- const digest = createHash("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4213
- return `${prefix}~${digest}`;
4441
+ const digest$1 = createHash("sha256").update(buildDir, "utf8").digest("hex").slice(0, 16);
4442
+ return `${prefix}~${digest$1}`;
4214
4443
  }
4215
4444
  function receiptsDirOf(home) {
4216
4445
  return join(home.dir, PROTECTION_RECEIPTS_DIR);
@@ -4221,6 +4450,9 @@ function receiptPathIn(home) {
4221
4450
  function homeOf(target) {
4222
4451
  return typeof target === "string" ? afterpackHome(target) : target;
4223
4452
  }
4453
+ function buildDirKey(target) {
4454
+ return receiptKey(buildDirOf(homeOf(target)));
4455
+ }
4224
4456
  function protectionReceiptPath(target) {
4225
4457
  return receiptPathIn(homeOf(target));
4226
4458
  }
@@ -5030,14 +5262,18 @@ function fileFailure(f, source) {
5030
5262
  if (f.code === "" && source.trim() !== "") return sanitizeServerText(f.error) || "empty output";
5031
5263
  return null;
5032
5264
  }
5033
- function removeBundlerSourceMaps(input) {
5034
- const { sweepDir: sweepDir$1, engineMaps, policy, label } = input;
5265
+ function bundlerMapsToRemove(input) {
5266
+ const { sweepDir: sweepDir$1, engineMaps, policy } = input;
5035
5267
  const bundlerMaps = new Set([...input.perFile].flat());
5036
5268
  if (sweepDir$1 != null) {
5037
5269
  const swept = collectSourceMaps(sweepDir$1).filter((path) => !policy.sourceMap || !path.endsWith(".css.map"));
5038
5270
  for (const path of containedSourceMaps(swept, sweepDir$1)) bundlerMaps.add(path);
5039
5271
  }
5040
- removeSourceMaps([...bundlerMaps].filter((path) => !engineMaps.has(path)), label);
5272
+ return [...bundlerMaps].filter((path) => !engineMaps.has(path));
5273
+ }
5274
+ function removeBundlerSourceMaps(input) {
5275
+ const { sweepDir: sweepDir$1, policy, label } = input;
5276
+ removeSourceMaps(bundlerMapsToRemove(input), label);
5041
5277
  if (sweepDir$1 != null && !policy.sourceMap) stripCssSourceMappingURLs(collectStylesheets(sweepDir$1));
5042
5278
  }
5043
5279
  function describeLevel(preset, complexity) {
@@ -5177,7 +5413,12 @@ async function runObfuscationPass(options) {
5177
5413
  cwd
5178
5414
  });
5179
5415
  const localEngineVersion = await readEngineVersion(engine);
5180
- const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(localEngineVersion ?? options.client?.coreVersion) ? options.sourceType : void 0;
5416
+ const gateVersion = localEngineVersion ?? options.client?.coreVersion;
5417
+ const derivedSourceType = options.sourceType !== void 0 && coreSupportsSourceType(gateVersion) ? options.sourceType : void 0;
5418
+ if (options.fileSourceTypes && options.engineConfig?.sourceType === void 0 && coreSupportsFileSourceType(gateVersion)) for (const input of inputs) {
5419
+ const sourceType = options.fileSourceTypes.get(input.path);
5420
+ if (sourceType !== void 0) input.sourceType = sourceType;
5421
+ }
5181
5422
  const engineConfig = buildEngineConfig({
5182
5423
  policy,
5183
5424
  seed,
@@ -5195,7 +5436,8 @@ async function runObfuscationPass(options) {
5195
5436
  const { seed: _seed,...configWithoutSeed } = engineConfig;
5196
5437
  const namedInputs = new Map(inputs.map((input) => [input.path, {
5197
5438
  source: input.source,
5198
- regions: input.regions
5439
+ regions: input.regions,
5440
+ sourceType: input.sourceType
5199
5441
  }]));
5200
5442
  hashSalt = afterpackHashSalt({
5201
5443
  seed,
@@ -5304,6 +5546,54 @@ async function runObfuscationPass(options) {
5304
5546
  source
5305
5547
  });
5306
5548
  }
5549
+ const artifactInput = (f, source) => ({
5550
+ outPath: f.path,
5551
+ code: withSourceMappingURL(f.code, null),
5552
+ sourceMapJson: f.sourceMap ?? null,
5553
+ originalSource: source,
5554
+ policy,
5555
+ mode: "framework"
5556
+ });
5557
+ if (!options.emitToCaller && options.beforeWrite) {
5558
+ const planned = new Map();
5559
+ const expectState = (path, state) => {
5560
+ const states = planned.get(path) ?? [];
5561
+ if (!states.includes(state)) states.push(state);
5562
+ planned.set(path, states);
5563
+ };
5564
+ for (const from of namesPlan?.renamed.keys() ?? []) expectState(from, null);
5565
+ const plannedEngineMaps = new Set();
5566
+ for (const { result: f, source } of verified) {
5567
+ const artifacts = planArtifactWrites(artifactInput(f, source));
5568
+ if (artifacts.mapPath) plannedEngineMaps.add(resolve(artifacts.mapPath));
5569
+ for (const write of artifacts.writes) {
5570
+ expectState(write.path, sha256Hex(write.content));
5571
+ expectState(stagedPath(write.path), null);
5572
+ }
5573
+ }
5574
+ for (const { to, text } of namesPlan?.rewrites.values() ?? []) {
5575
+ expectState(to, sha256Hex(text));
5576
+ expectState(stagedPath(to), null);
5577
+ }
5578
+ for (const map of bundlerMapsToRemove({
5579
+ perFile: bundlerMapsByPath.values(),
5580
+ sweepDir: sweepDir$1,
5581
+ engineMaps: plannedEngineMaps,
5582
+ policy
5583
+ })) expectState(map, null);
5584
+ if (sweepDir$1 != null && !policy.sourceMap) for (const css of collectStylesheets(sweepDir$1)) {
5585
+ const rewritten = namesPlan?.rewrites.get(css);
5586
+ const text = rewritten?.text ?? readFileSync(css, "utf8");
5587
+ const stripped = withoutCssSourceMappingURL(text);
5588
+ if (stripped === text) continue;
5589
+ expectState(rewritten?.to ?? css, sha256Hex(stripped));
5590
+ expectState(stagedPath(rewritten?.to ?? css), null);
5591
+ }
5592
+ options.beforeWrite({
5593
+ renamed: namesPlan?.renamed ?? new Map(),
5594
+ planned
5595
+ });
5596
+ }
5307
5597
  const writtenFiles = [];
5308
5598
  const emittedFiles = [];
5309
5599
  const engineMaps = new Set();
@@ -5318,13 +5608,8 @@ async function runObfuscationPass(options) {
5318
5608
  continue;
5319
5609
  }
5320
5610
  const written = writeArtifacts({
5321
- outPath: f.path,
5322
- code: withSourceMappingURL(f.code, null),
5323
- sourceMapJson: f.sourceMap ?? null,
5611
+ ...artifactInput(f, source),
5324
5612
  protectionMapJson: null,
5325
- originalSource: source,
5326
- policy,
5327
- mode: "framework",
5328
5613
  afterpackDir: home.dir,
5329
5614
  logger
5330
5615
  });
@@ -5604,4 +5889,4 @@ function resolvePluginConfig(input) {
5604
5889
  }
5605
5890
 
5606
5891
  //#endregion
5607
- export { AFTERPACK_DIR, AfterpackFilesError, AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_AFTERPACK_DIR_IN_OUTPUT, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, DIAG_RECEIPT_UNWRITABLE, PROTECTION_RECEIPTS_DIR, SEED_ENV_VAR, UnreadableReceiptError, afterpackHome, applyBundleOutput, applyResolvedKey, collectBundleJs, collectJsFiles, collectSourceMaps, collectStylesheets, createTelemetryReporter, decodeDataUri, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findUpward, getPath, installedRequiredLine, loadConfigFile, locateProtectionReceipt, mergeConfig, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, prepareHashSalt, protectionReceiptPath, readEngineVersion, regenerateCompressedSiblings, removeSourceMaps, reportPolicySaltBits, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, saltSettings, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Of, sourceTypeForBundle, sourceTypeForOutputFormat, sriPluginRefusal, stripBundleCssSourceMaps, stripCssSourceMappingURLs, sweepOutputTree, toEngineConfig, toPluginOptions, unsaltedAssetsWarning, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeProtectionReceipt };
5892
+ export { AFTERPACK_DIR, AfterpackFilesError, AlreadyObfuscatedError, CLOUD_REFUSAL_SUMMARY, CONFIG_FILE_NAME, CONFIG_KEYS, CORE_FLOOR_SUMMARY, CloudApiError, CoreVersionError, DIAG_AFTERPACK_DIR_IN_OUTPUT, DIAG_ALREADY_OBFUSCATED, DIAG_RECEIPT_UNREADABLE, DIAG_RECEIPT_UNWRITABLE, NEXT_CHUNKS_PREFIX, PROTECTION_RECEIPTS_DIR, SEED_ENV_VAR, UnreadableReceiptError, afterpackHome, angularHashToken, angularServerManifestRefusal, applyBundleOutput, applyResolvedKey, buildDirKey, collectBundleJs, collectJsFiles, collectSourceMaps, collectStylesheets, createTelemetryReporter, decodeDataUri, detectNextBundler, discoverInputSourceMap, ensureAfterpackGitignore, extractSourceMappingURL, findHashTokenReference, findUpward, getPath, installedRequiredLine, isWithinDir, loadConfigFile, locateProtectionReceipt, mergeConfig, nextChunkToken, normalizePluginOptions, npxAlternative, parseCliOptions, parseEnvOptions, passSettings, planAngularIntegrity, prepareHashSalt, protectionReceiptPath, readEngineVersion, recomputeAngularIntegrity, regenerateCompressedSiblings, removeSourceMaps, reportPolicySaltBits, resolveClientIdentity, resolvePluginConfig, resolveReportPolicy, runObfuscationPass, saltSettings, sanitizeNotices, scanDirectives, serverAddsInfo, sha256Hex, sha256Of, skipNextInternals, sourceTypeForBundle, sourceTypeForOutputFormat, sriPluginRefusal, stagedPath, stripBundleCssSourceMaps, stripCssSourceMappingURLs, sweepOutputTree, toEngineConfig, toPluginOptions, unreferencedHashedFiles, unsaltedAssetsWarning, validateConfig, verifyProtectionReceipt, withSourceMappingURL, withoutCssSourceMappingURL, writeArtifacts, writeDeferredProtectionReceipt, writeFileAtomic, writeProtectionReceipt };