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