@powerhousedao/ph-cli 6.2.3-dev.1 → 6.2.3-dev.100
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/README.md +21 -0
- package/dist/{auth-AR3VxAIk.mjs → auth-BFUq7CvE.mjs} +3 -3
- package/dist/{auth-AR3VxAIk.mjs.map → auth-BFUq7CvE.mjs.map} +1 -1
- package/dist/auth-CNhbN5UM.mjs +4 -0
- package/dist/authoring-mode-DWbbsuWh.mjs +23 -0
- package/dist/authoring-mode-DWbbsuWh.mjs.map +1 -0
- package/dist/build-C1mmZvlb.mjs +3011 -0
- package/dist/build-C1mmZvlb.mjs.map +1 -0
- package/dist/build-Ws5hhqol.mjs +4 -0
- package/dist/check-Cco7-UC2.mjs +65 -0
- package/dist/check-Cco7-UC2.mjs.map +1 -0
- package/dist/check-CjFMilhk.mjs +4 -0
- package/dist/check-DvG9Xy4c.mjs +60 -0
- package/dist/check-DvG9Xy4c.mjs.map +1 -0
- package/dist/{cli-connect-override-D3hh4aH_.mjs → cli-connect-override-D3N3gbp_.mjs} +39 -27
- package/dist/cli-connect-override-D3N3gbp_.mjs.map +1 -0
- package/dist/cli.d.mts +2 -1
- package/dist/cli.mjs +54 -1178
- package/dist/cli.mjs.map +1 -1
- package/dist/compound-DO_mvh0O-Dp1YPhR0.mjs +2806 -0
- package/dist/compound-DO_mvh0O-Dp1YPhR0.mjs.map +1 -0
- package/dist/connect-build-COdexcA8.mjs +322 -0
- package/dist/connect-build-COdexcA8.mjs.map +1 -0
- package/dist/{connect-config-BWGiW3IB.mjs → connect-config-C6hKMsUG.mjs} +19 -12
- package/dist/connect-config-C6hKMsUG.mjs.map +1 -0
- package/dist/connect-preview-CdFvlANO.mjs +49 -0
- package/dist/connect-preview-CdFvlANO.mjs.map +1 -0
- package/dist/connect-studio-C7Bbh50O.mjs +81 -0
- package/dist/connect-studio-C7Bbh50O.mjs.map +1 -0
- package/dist/connect-studio-xQNYl142.mjs +4 -0
- package/dist/definitions-worker.d.mts +98 -0
- package/dist/definitions-worker.d.mts.map +1 -0
- package/dist/definitions-worker.mjs +28 -0
- package/dist/definitions-worker.mjs.map +1 -0
- package/dist/dist-B-_lMGlB.mjs +480 -0
- package/dist/dist-B-_lMGlB.mjs.map +1 -0
- package/dist/evidence-Dchpoogs.mjs +120 -0
- package/dist/evidence-Dchpoogs.mjs.map +1 -0
- package/dist/explain-lynfOtDg.mjs +230 -0
- package/dist/explain-lynfOtDg.mjs.map +1 -0
- package/dist/export-YkeGUZjR.mjs +42 -0
- package/dist/export-YkeGUZjR.mjs.map +1 -0
- package/dist/external-M25AgDIE.d.mts +4277 -0
- package/dist/external-M25AgDIE.d.mts.map +1 -0
- package/dist/feature-flags-xwqcHEWC.mjs +4 -0
- package/dist/files-D6_euBBn.mjs +457 -0
- package/dist/files-D6_euBBn.mjs.map +1 -0
- package/dist/generate-all-_7S0Iii2.mjs +36 -0
- package/dist/generate-all-_7S0Iii2.mjs.map +1 -0
- package/dist/generate-app-hm6CJ_4O.mjs +72 -0
- package/dist/generate-app-hm6CJ_4O.mjs.map +1 -0
- package/dist/generate-desktop-shell-CEcE_1gb.mjs +323 -0
- package/dist/generate-desktop-shell-CEcE_1gb.mjs.map +1 -0
- package/dist/generate-document-model-DCjzz3Sa.mjs +114 -0
- package/dist/generate-document-model-DCjzz3Sa.mjs.map +1 -0
- package/dist/generate-editor-DdoapkEK.mjs +64 -0
- package/dist/generate-editor-DdoapkEK.mjs.map +1 -0
- package/dist/generate-hosts-BFmPIW2X.mjs +18 -0
- package/dist/generate-hosts-BFmPIW2X.mjs.map +1 -0
- package/dist/generate-hosts-RWj7WPHZ.mjs +4 -0
- package/dist/generate-migration-file-yK8uA70U.mjs +20 -0
- package/dist/generate-migration-file-yK8uA70U.mjs.map +1 -0
- package/dist/generate-piece-5Nyr2UZj.mjs +73 -0
- package/dist/generate-piece-5Nyr2UZj.mjs.map +1 -0
- package/dist/generate-piece-action-DqR8BcoO.mjs +31 -0
- package/dist/generate-piece-action-DqR8BcoO.mjs.map +1 -0
- package/dist/generate-piece-trigger-CZaDD-cc.mjs +30 -0
- package/dist/generate-piece-trigger-CZaDD-cc.mjs.map +1 -0
- package/dist/generate-processor-BVjOsfjJ.mjs +58 -0
- package/dist/generate-processor-BVjOsfjJ.mjs.map +1 -0
- package/dist/generate-subgraph-CrHbYK91.mjs +64 -0
- package/dist/generate-subgraph-CrHbYK91.mjs.map +1 -0
- package/dist/get-version-BBiGShxz.mjs +11 -0
- package/dist/get-version-BBiGShxz.mjs.map +1 -0
- package/dist/index-BdxG1c0H.d.mts +188 -0
- package/dist/index-BdxG1c0H.d.mts.map +1 -0
- package/dist/{init-BZP6gvYd.mjs → init-BjwbWklG.mjs} +24 -15
- package/dist/init-BjwbWklG.mjs.map +1 -0
- package/dist/inspect-BpVHe9vz.mjs +46 -0
- package/dist/inspect-BpVHe9vz.mjs.map +1 -0
- package/dist/{inspect-DXjbQEV_.mjs → inspect-zWJnBDMJ.mjs} +11 -4
- package/dist/inspect-zWJnBDMJ.mjs.map +1 -0
- package/dist/install-added-dependencies-DnZFR3aE.mjs +18 -0
- package/dist/install-added-dependencies-DnZFR3aE.mjs.map +1 -0
- package/dist/keyframes-bFo9iDhT.mjs +201 -0
- package/dist/keyframes-bFo9iDhT.mjs.map +1 -0
- package/dist/mcp-BK-qb1ZS.mjs +262 -0
- package/dist/mcp-BK-qb1ZS.mjs.map +1 -0
- package/dist/migrate-B-MM9TlS.mjs +177 -0
- package/dist/migrate-B-MM9TlS.mjs.map +1 -0
- package/dist/module-dir-1avCXsBi.mjs +17 -0
- package/dist/module-dir-1avCXsBi.mjs.map +1 -0
- package/dist/npm-args-g1Tgel4s.mjs +78 -0
- package/dist/npm-args-g1Tgel4s.mjs.map +1 -0
- package/dist/offered-routes-imports-CQInWI6y.mjs +4 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs +96 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs.map +1 -0
- package/dist/ph-cli-commands-DwSp4Sbq.mjs +1770 -0
- package/dist/ph-cli-commands-DwSp4Sbq.mjs.map +1 -0
- package/dist/ph-cli-commands-HLM5KIpd.mjs +4 -0
- package/dist/{registry-auth-DxEWCJu2.mjs → registry-auth-Bm5AR-fB.mjs} +4 -4
- package/dist/{registry-auth-DxEWCJu2.mjs.map → registry-auth-Bm5AR-fB.mjs.map} +1 -1
- package/dist/render-BO-Nwn2H.mjs +71 -0
- package/dist/render-BO-Nwn2H.mjs.map +1 -0
- package/dist/render-DdieUjtg.mjs +4 -0
- package/dist/run-DEKE4MJY.mjs +111 -0
- package/dist/run-DEKE4MJY.mjs.map +1 -0
- package/dist/run-DP3fNgPv.mjs +4 -0
- package/dist/run-sugar-D9lIzhAx.mjs +39 -0
- package/dist/run-sugar-D9lIzhAx.mjs.map +1 -0
- package/dist/runners/connect.d.mts +17 -0
- package/dist/runners/connect.d.mts.map +1 -0
- package/dist/runners/connect.mjs +63 -0
- package/dist/runners/connect.mjs.map +1 -0
- package/dist/runners/switchboard.d.mts +11 -0
- package/dist/runners/switchboard.d.mts.map +1 -0
- package/dist/runners/switchboard.mjs +21 -0
- package/dist/runners/switchboard.mjs.map +1 -0
- package/dist/schemas-DzgKfQIx.mjs +6024 -0
- package/dist/schemas-DzgKfQIx.mjs.map +1 -0
- package/dist/scripts/emit-runner-schemas.ts +24 -0
- package/dist/scripts/generate-commands-docs.ts +17 -0
- package/dist/scripts/manage-environment +0 -0
- package/dist/scripts/setup.sh +0 -0
- package/dist/{switchboard-migrate-NQ7LHWSi.mjs → switchboard-migrate-Docb8Cjv.mjs} +6 -5
- package/dist/{switchboard-migrate-NQ7LHWSi.mjs.map → switchboard-migrate-Docb8Cjv.mjs.map} +1 -1
- package/dist/switchboard-proxy-CGfMtENM.mjs +37 -0
- package/dist/switchboard-proxy-CGfMtENM.mjs.map +1 -0
- package/dist/{switchboard-reset-BcQXlcVf.mjs → switchboard-reset-MtTB_GAI.mjs} +8 -6
- package/dist/switchboard-reset-MtTB_GAI.mjs.map +1 -0
- package/dist/sync-connect-routes-BtAsFPXN.mjs +4 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs +25 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs.map +1 -0
- package/dist/{utils-C4isxXSO.mjs → utils-9KyRM0mf.mjs} +6 -34
- package/dist/{utils-C4isxXSO.mjs.map → utils-9KyRM0mf.mjs.map} +1 -1
- package/dist/utils-TO9lB8Xs.mjs +4 -0
- package/dist/verify-l5f7BDmy.mjs +71 -0
- package/dist/verify-l5f7BDmy.mjs.map +1 -0
- package/dist/{vetra-DkF6EJMY.mjs → vetra-DSFzAl_1.mjs} +115 -148
- package/dist/vetra-DSFzAl_1.mjs.map +1 -0
- package/dist/vetra-launch-DQDZxGTV.mjs +343 -0
- package/dist/vetra-launch-DQDZxGTV.mjs.map +1 -0
- package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs +19 -0
- package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +1 -0
- package/package.json +45 -18
- package/dist/auth-BNkN6kS9.mjs +0 -4
- package/dist/build-C-A5-ipO.mjs +0 -4
- package/dist/build-uQXq6_HU.mjs +0 -71
- package/dist/build-uQXq6_HU.mjs.map +0 -1
- package/dist/cli-connect-override-D3hh4aH_.mjs.map +0 -1
- package/dist/connect-build-WL4axo4z.mjs +0 -43
- package/dist/connect-build-WL4axo4z.mjs.map +0 -1
- package/dist/connect-config-BWGiW3IB.mjs.map +0 -1
- package/dist/connect-preview-D7ypzFDc.mjs +0 -28
- package/dist/connect-preview-D7ypzFDc.mjs.map +0 -1
- package/dist/connect-studio-BIQzyq5B.mjs +0 -5
- package/dist/connect-studio-D6rfWCNB.mjs +0 -31
- package/dist/connect-studio-D6rfWCNB.mjs.map +0 -1
- package/dist/generate-all-DrT4ZxHX.mjs +0 -30
- package/dist/generate-all-DrT4ZxHX.mjs.map +0 -1
- package/dist/generate-app-DNNqA-H3.mjs +0 -48
- package/dist/generate-app-DNNqA-H3.mjs.map +0 -1
- package/dist/generate-document-model-BJXyODfm.mjs +0 -34
- package/dist/generate-document-model-BJXyODfm.mjs.map +0 -1
- package/dist/generate-editor-BejvaVVT.mjs +0 -48
- package/dist/generate-editor-BejvaVVT.mjs.map +0 -1
- package/dist/generate-processor-_WOx-mMe.mjs +0 -40
- package/dist/generate-processor-_WOx-mMe.mjs.map +0 -1
- package/dist/generate-subgraph-BsHUstpl.mjs +0 -38
- package/dist/generate-subgraph-BsHUstpl.mjs.map +0 -1
- package/dist/init-BZP6gvYd.mjs.map +0 -1
- package/dist/inspect-DXjbQEV_.mjs.map +0 -1
- package/dist/migrate-jGKfE02L.mjs +0 -83
- package/dist/migrate-jGKfE02L.mjs.map +0 -1
- package/dist/switchboard-CJMoMzWx.mjs +0 -75
- package/dist/switchboard-CJMoMzWx.mjs.map +0 -1
- package/dist/switchboard-iRFugh8I.mjs +0 -4
- package/dist/switchboard-reset-BcQXlcVf.mjs.map +0 -1
- package/dist/utils-BzwczAW-.mjs +0 -4
- package/dist/vetra-DkF6EJMY.mjs.map +0 -1
|
@@ -0,0 +1,3011 @@
|
|
|
1
|
+
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a50f62aa-4997-5d8a-a8e5-63f40b3c4ad4")}catch(e){}}();
|
|
3
|
+
import { t as getVersion } from "./get-version-BBiGShxz.mjs";
|
|
4
|
+
import { _ as pendingPrefix, a as writeReleaseApproval, c as PH_CLI_BINDING, d as listed, g as LOCK_FILE, h as BUILD_DIRECTORY, i as revisionFiles, l as RELEASE_APPROVAL_PATH, m as packageRevision, o as packRelease, p as changedPaths, s as packedDigests, t as packagePath, v as takeoverPrefix } from "./files-D6_euBBn.mjs";
|
|
5
|
+
import { d as object, f as record, g as union, i as boolean, l as looseObject, m as string, r as array, s as json } from "./schemas-DzgKfQIx.mjs";
|
|
6
|
+
import { n as OFFERED_ROUTES_MODULE, r as syncProjectConnectRoutes, t as HOST_ROUTES_DIR } from "./sync-connect-routes-t0Slg-P6.mjs";
|
|
7
|
+
import { r as noConnectImports } from "./offered-routes-imports-CalXK9dh.mjs";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import { accessSync, chmodSync, constants, cpSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
|
|
10
|
+
import path, { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
11
|
+
import { execFileSync, execSync, fork, spawn } from "node:child_process";
|
|
12
|
+
import { SpawnError, spawnAsync } from "@powerhousedao/shared/clis";
|
|
13
|
+
import { assertPiecesOutDir, buildPieces, createDetectionCache, expandEntryGlobs, externalDependencyVersions, externalDepsPlugin, pieceListPath, planPieces, projectPath, syncDistManifest, undeclaredExternalDependencies } from "@powerhousedao/shared/build-pieces";
|
|
14
|
+
import { detect, resolveCommand } from "package-manager-detector";
|
|
15
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
16
|
+
import { pathWithin, realPathThroughExistingParent } from "@powerhousedao/shared/clis/real-paths";
|
|
17
|
+
import { hostname, tmpdir } from "node:os";
|
|
18
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
19
|
+
import { satisfies } from "semver";
|
|
20
|
+
import { browserEntry, buildBrowserBuildConfig, buildNodeBuildConfig, findBundledSharedDeps } from "@powerhousedao/shared/build-config";
|
|
21
|
+
import { EXTERNALIZABLE_SHARED_SPECIFIERS, findSharedImports } from "@powerhousedao/shared/connect";
|
|
22
|
+
import { readPackage } from "read-pkg";
|
|
23
|
+
import { build, globalLogger } from "tsdown";
|
|
24
|
+
import { localPackageNames, packageStyleEntry, packageStylesheet } from "@powerhousedao/shared/clis/package-style";
|
|
25
|
+
import { nodeFileTrace } from "@vercel/nft";
|
|
26
|
+
//#region src/services/package-build/pipeline/steps.ts
|
|
27
|
+
/** A step's decision not to finish the build. The runner rolls back first. */
|
|
28
|
+
var BuildRefusal = class extends Error {
|
|
29
|
+
exitCode;
|
|
30
|
+
constructor(message, exitCode = 1) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = "BuildRefusal";
|
|
33
|
+
this.exitCode = exitCode;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/** The process was told to stop while the build ran; it was rolled back. */
|
|
37
|
+
var BuildStopped = class extends Error {
|
|
38
|
+
signal;
|
|
39
|
+
constructor(signal) {
|
|
40
|
+
super(`The build was stopped by ${signal} before it finished.`);
|
|
41
|
+
this.name = "BuildStopped";
|
|
42
|
+
this.signal = signal;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
function dependencies(steps) {
|
|
46
|
+
const ids = /* @__PURE__ */ new Set();
|
|
47
|
+
for (const { id } of steps) {
|
|
48
|
+
if (ids.has(id)) throw new Error(`Build step "${id}" is listed twice.`);
|
|
49
|
+
ids.add(id);
|
|
50
|
+
}
|
|
51
|
+
const committed = new Set(steps.filter(({ when }) => when === "committed").map(({ id }) => id));
|
|
52
|
+
const waits = /* @__PURE__ */ new Map();
|
|
53
|
+
steps.forEach((step, index) => {
|
|
54
|
+
const previous = steps.slice(0, index).findLast(({ when }) => when === step.when);
|
|
55
|
+
const after = step.after ?? (previous === void 0 ? [] : [previous.id]);
|
|
56
|
+
for (const id of after) {
|
|
57
|
+
if (!ids.has(id)) throw new Error(`Build step "${step.id}" runs after "${id}", which no step provides.`);
|
|
58
|
+
if (step.when !== "committed" && committed.has(id)) throw new Error(`Build step "${step.id}" runs before the output is replaced, so it cannot run after "${id}", which runs once it is.`);
|
|
59
|
+
}
|
|
60
|
+
waits.set(step.id, after);
|
|
61
|
+
});
|
|
62
|
+
return waits;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The order the steps run in: list order, with each step that names `after`
|
|
66
|
+
* placed right after the last step it waits for, and every `committed` step
|
|
67
|
+
* after every other. Throws on a duplicate id, an unknown `after` id, a step
|
|
68
|
+
* that waits on a later phase, or steps that wait on each other.
|
|
69
|
+
*/
|
|
70
|
+
function orderBuildSteps(steps) {
|
|
71
|
+
const waits = dependencies(steps);
|
|
72
|
+
const placed = /* @__PURE__ */ new Set();
|
|
73
|
+
const ordered = [];
|
|
74
|
+
while (ordered.length < steps.length) {
|
|
75
|
+
const ready = steps.filter(({ id }) => !placed.has(id) && waits.get(id).every((wait) => placed.has(wait)));
|
|
76
|
+
if (ready.length === 0) {
|
|
77
|
+
const waiting = steps.filter(({ id }) => !placed.has(id)).map(({ id }) => `"${id}"`);
|
|
78
|
+
throw new Error(`Build steps ${waiting.join(", ")} wait on each other.`);
|
|
79
|
+
}
|
|
80
|
+
const phase = ready.some(({ when }) => when !== "committed") ? ready.filter(({ when }) => when !== "committed") : ready;
|
|
81
|
+
const next = phase.find((step) => step.after !== void 0) ?? phase[0];
|
|
82
|
+
placed.add(next.id);
|
|
83
|
+
ordered.push(next);
|
|
84
|
+
}
|
|
85
|
+
return ordered;
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
88
|
+
//#region src/services/package-build/pipeline/run-steps.ts
|
|
89
|
+
function throwIfStopped(session) {
|
|
90
|
+
const signal = session.stopped();
|
|
91
|
+
if (signal === void 0) return;
|
|
92
|
+
session.rollback();
|
|
93
|
+
throw new BuildStopped(signal);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Runs the steps in order, commits, then runs the `committed` steps. When a
|
|
97
|
+
* step before the commit throws, `rollback` runs before the error goes on to
|
|
98
|
+
* the caller, so nothing the build wrote outlives the failure. A committed
|
|
99
|
+
* step's throw goes to the caller with the new output in place. A stop is
|
|
100
|
+
* seen once the running step settles, and before each step and the commit:
|
|
101
|
+
* no step starts after it, and the rollback waits for the step it stopped.
|
|
102
|
+
*/
|
|
103
|
+
async function runBuildSteps(steps, ctx, session) {
|
|
104
|
+
const ordered = orderBuildSteps(steps);
|
|
105
|
+
for (const step of ordered.filter(({ when }) => when !== "committed")) {
|
|
106
|
+
throwIfStopped(session);
|
|
107
|
+
try {
|
|
108
|
+
await step.run(ctx);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
session.rollback();
|
|
111
|
+
throwIfStopped(session);
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
throwIfStopped(session);
|
|
116
|
+
session.commit();
|
|
117
|
+
for (const step of ordered.filter(({ when }) => when === "committed")) {
|
|
118
|
+
throwIfStopped(session);
|
|
119
|
+
await step.run(ctx);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/services/package-build/staging/files.ts
|
|
124
|
+
function exists(path) {
|
|
125
|
+
return lstatSync(path, { throwIfNoEntry: false }) !== void 0;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Copies a file or a tree with its timestamps. A clone where the filesystem
|
|
129
|
+
* has them, a byte copy elsewhere; never a hard link, because later steps
|
|
130
|
+
* rewrite files in place.
|
|
131
|
+
*/
|
|
132
|
+
function cloneTree(from, to, filter) {
|
|
133
|
+
cpSync(from, to, {
|
|
134
|
+
recursive: true,
|
|
135
|
+
mode: constants.COPYFILE_FICLONE,
|
|
136
|
+
preserveTimestamps: true,
|
|
137
|
+
verbatimSymlinks: true,
|
|
138
|
+
...filter && { filter }
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Mirrors a tree whose files the next step unlinks before it writes (tsdown
|
|
143
|
+
* cleans its output directory that way): each file is hard linked, so no
|
|
144
|
+
* byte is copied and nothing written later reaches `from`. A file that
|
|
145
|
+
* cannot be linked, and anything else, is copied.
|
|
146
|
+
*/
|
|
147
|
+
function linkTree(from, to, filter) {
|
|
148
|
+
mkdirSync(to);
|
|
149
|
+
for (const entry of readdirSync(from, { withFileTypes: true })) {
|
|
150
|
+
const source = join(from, entry.name);
|
|
151
|
+
if (!filter(source)) continue;
|
|
152
|
+
const target = join(to, entry.name);
|
|
153
|
+
if (entry.isDirectory()) {
|
|
154
|
+
linkTree(source, target, filter);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (entry.isFile()) try {
|
|
158
|
+
linkSync(source, target);
|
|
159
|
+
continue;
|
|
160
|
+
} catch {}
|
|
161
|
+
cloneTree(source, target);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const OWNER_RWX = 448;
|
|
165
|
+
/**
|
|
166
|
+
* Gives every directory of the tree at `path` that lacks it owner read,
|
|
167
|
+
* write and search permission, which emptying it needs, and returns the
|
|
168
|
+
* modes it changed, parents first.
|
|
169
|
+
*/
|
|
170
|
+
function openDirectories(path) {
|
|
171
|
+
const changed = [];
|
|
172
|
+
const visit = (dir, rel) => {
|
|
173
|
+
const stat = lstatSync(dir, { throwIfNoEntry: false });
|
|
174
|
+
if (!stat?.isDirectory()) return;
|
|
175
|
+
const mode = stat.mode & 4095;
|
|
176
|
+
if ((mode & OWNER_RWX) !== OWNER_RWX) {
|
|
177
|
+
chmodSync(dir, mode | OWNER_RWX);
|
|
178
|
+
changed.push([rel, mode]);
|
|
179
|
+
}
|
|
180
|
+
for (const entry of readdirSync(dir)) visit(join(dir, entry), rel === "" ? entry : `${rel}/${entry}`);
|
|
181
|
+
};
|
|
182
|
+
visit(path, "");
|
|
183
|
+
return changed;
|
|
184
|
+
}
|
|
185
|
+
/** Sets back the modes `openDirectories` changed, children first. */
|
|
186
|
+
function restoreDirectoryModes(path, modes) {
|
|
187
|
+
for (const [rel, mode] of [...modes].reverse()) chmodSync(rel === "" ? path : join(path, ...rel.split("/")), mode);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Removes a tree. A directory without owner write permission keeps its
|
|
191
|
+
* entries, so on failure each directory is opened and the removal tried
|
|
192
|
+
* once more.
|
|
193
|
+
*/
|
|
194
|
+
function removeTree(path) {
|
|
195
|
+
const remove = () => rmSync(path, {
|
|
196
|
+
recursive: true,
|
|
197
|
+
force: true,
|
|
198
|
+
maxRetries: 10
|
|
199
|
+
});
|
|
200
|
+
try {
|
|
201
|
+
remove();
|
|
202
|
+
} catch (error) {
|
|
203
|
+
try {
|
|
204
|
+
openDirectories(path);
|
|
205
|
+
} catch {
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
remove();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Makes `path` a copy of `from`. A directory that is there is emptied and
|
|
213
|
+
* refilled rather than removed, so a mount point or a directory another
|
|
214
|
+
* process holds stays where it is.
|
|
215
|
+
*/
|
|
216
|
+
function replaceTree(from, path) {
|
|
217
|
+
if (!(lstatSync(path, { throwIfNoEntry: false })?.isDirectory() && lstatSync(from).isDirectory())) {
|
|
218
|
+
removeTree(path);
|
|
219
|
+
cloneTree(from, path);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
openDirectories(path);
|
|
223
|
+
for (const entry of readdirSync(path)) removeTree(join(path, entry));
|
|
224
|
+
cloneTree(from, path);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The tree by the bytes of its files and the targets of its links. Times
|
|
228
|
+
* and inodes are left out: a touch changes them, and a rewrite can keep them.
|
|
229
|
+
*/
|
|
230
|
+
function treeFingerprint(root, skipped, unmarked = /* @__PURE__ */ new Set()) {
|
|
231
|
+
const hash = createHash("sha256");
|
|
232
|
+
const visit = (path, rel) => {
|
|
233
|
+
const stat = lstatSync(path);
|
|
234
|
+
if (stat.isFile()) {
|
|
235
|
+
const bytes = readFileSync(path);
|
|
236
|
+
hash.update(`f\0${rel}\0${bytes.length}\0`).update(bytes);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (stat.isSymbolicLink()) {
|
|
240
|
+
hash.update(`l\0${rel}\0${readlinkSync(path)}\0`);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (!stat.isDirectory()) {
|
|
244
|
+
hash.update(`o\0${rel}\0`);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (rel !== "" && !unmarked.has(rel)) hash.update(`d\0${rel}\0`);
|
|
248
|
+
for (const entry of readdirSync(path).sort()) {
|
|
249
|
+
const child = rel === "" ? entry : `${rel}/${entry}`;
|
|
250
|
+
if (!skipped.has(child)) visit(join(path, entry), child);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
if (exists(root)) visit(root, "");
|
|
254
|
+
return hash.digest("hex");
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* The first entry of the tree at `path`, itself included, that the stage
|
|
258
|
+
* cannot copy as it is, and why: a FIFO, socket or device, which a copy
|
|
259
|
+
* cannot represent, or a file or directory this process cannot read. Only
|
|
260
|
+
* permissions are checked; no file is read. Entries `filter` rejects, and
|
|
261
|
+
* what they hold, are not looked at.
|
|
262
|
+
*/
|
|
263
|
+
function unstageableEntryIn(path, filter = () => true) {
|
|
264
|
+
const visit = (path, stat) => {
|
|
265
|
+
if (stat.isSymbolicLink()) return;
|
|
266
|
+
if (!stat.isFile() && !stat.isDirectory()) return {
|
|
267
|
+
path,
|
|
268
|
+
reason: "is not a file, directory or symbolic link"
|
|
269
|
+
};
|
|
270
|
+
const mode = stat.isDirectory() ? constants.R_OK | constants.X_OK : constants.R_OK;
|
|
271
|
+
try {
|
|
272
|
+
accessSync(path, mode);
|
|
273
|
+
} catch {
|
|
274
|
+
return {
|
|
275
|
+
path,
|
|
276
|
+
reason: "cannot be read"
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
if (!stat.isDirectory()) return;
|
|
280
|
+
for (const entry of readdirSync(path)) {
|
|
281
|
+
const child = join(path, entry);
|
|
282
|
+
if (!filter(child)) continue;
|
|
283
|
+
const found = visit(child, lstatSync(child));
|
|
284
|
+
if (found) return found;
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
288
|
+
return stat && visit(path, stat);
|
|
289
|
+
}
|
|
290
|
+
function entriesOf(dir) {
|
|
291
|
+
return exists(dir) ? readdirSync(dir) : [];
|
|
292
|
+
}
|
|
293
|
+
const blocker = new Int32Array(new SharedArrayBuffer(4));
|
|
294
|
+
/** Waits without returning to the event loop, so no signal handler runs meanwhile. */
|
|
295
|
+
function sleepSync(ms) {
|
|
296
|
+
Atomics.wait(blocker, 0, 0, ms);
|
|
297
|
+
}
|
|
298
|
+
/** Windows refuses to rename a directory while another process holds a file in it. */
|
|
299
|
+
function isHeldOpen(error) {
|
|
300
|
+
const code = error?.code;
|
|
301
|
+
return code === "EPERM" || code === "EBUSY" || code === "EACCES";
|
|
302
|
+
}
|
|
303
|
+
const RENAME_PATIENCE_MS = 2e3;
|
|
304
|
+
/** `rename`, retried with backoff for about two seconds while the path is held open. */
|
|
305
|
+
function renamePatiently(from, to, patienceMs = RENAME_PATIENCE_MS) {
|
|
306
|
+
const deadline = Date.now() + patienceMs;
|
|
307
|
+
for (let wait = 20;; wait = Math.min(wait * 2, 400)) try {
|
|
308
|
+
renameSync(from, to);
|
|
309
|
+
return;
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (!isHeldOpen(error) || Date.now() + wait > deadline) throw error;
|
|
312
|
+
sleepSync(wait);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/** Moves each entry of `from` into `to`, replacing what `to` holds under that name. */
|
|
316
|
+
function moveEntries(from, to) {
|
|
317
|
+
for (const entry of entriesOf(from)) {
|
|
318
|
+
const target = join(to, entry);
|
|
319
|
+
if (exists(target)) removeTree(target);
|
|
320
|
+
renamePatiently(join(from, entry), target);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/** Staging cannot run where the build would write; `message` says why. */
|
|
324
|
+
var CannotStage = class extends Error {};
|
|
325
|
+
const CANNOT_WRITE = /* @__PURE__ */ new Set([
|
|
326
|
+
"ENOTDIR",
|
|
327
|
+
"EACCES",
|
|
328
|
+
"EPERM",
|
|
329
|
+
"EROFS",
|
|
330
|
+
"ENOTSUP",
|
|
331
|
+
"EOPNOTSUPP"
|
|
332
|
+
]);
|
|
333
|
+
/** Runs `create`, turning a refusal to write `where` into `CannotStage`. */
|
|
334
|
+
async function creating(where, create) {
|
|
335
|
+
try {
|
|
336
|
+
return await create();
|
|
337
|
+
} catch (error) {
|
|
338
|
+
const code = error?.code;
|
|
339
|
+
if (typeof code === "string" && CANNOT_WRITE.has(code)) throw new CannotStage(`${where} cannot be written (${code})`);
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
//#endregion
|
|
344
|
+
//#region src/services/package-build/staging/journal.ts
|
|
345
|
+
const RUNS_DIRECTORY = join(BUILD_DIRECTORY, "runs");
|
|
346
|
+
const JOURNAL_FILE = "journal.json";
|
|
347
|
+
/**
|
|
348
|
+
* The steps of a rollback, in order, each safe to repeat:
|
|
349
|
+
* - install: the output loses what the stage put in it.
|
|
350
|
+
* - retire: the retired tree, or its entries, goes back into the output.
|
|
351
|
+
* - stage: the stage goes and the compiler outputs come back.
|
|
352
|
+
*/
|
|
353
|
+
const UNDO_STEPS = [
|
|
354
|
+
"install",
|
|
355
|
+
"retire",
|
|
356
|
+
"stage"
|
|
357
|
+
];
|
|
358
|
+
const STATES = [
|
|
359
|
+
"building",
|
|
360
|
+
"retiring",
|
|
361
|
+
"installing",
|
|
362
|
+
"rolling-back",
|
|
363
|
+
"committed"
|
|
364
|
+
];
|
|
365
|
+
/**
|
|
366
|
+
* A path inside `from` is recorded relative, in POSIX form. Any other path
|
|
367
|
+
* is recorded absolute and comes back unchanged: a relative spelling of
|
|
368
|
+
* another drive or a UNC share does not resolve back to it on Windows.
|
|
369
|
+
*/
|
|
370
|
+
function toJournalPath(from, to, paths = path) {
|
|
371
|
+
const rel = paths.relative(from, to);
|
|
372
|
+
if (paths.isAbsolute(rel) || rel === ".." || rel.startsWith(`..${paths.sep}`)) return paths.resolve(to);
|
|
373
|
+
return rel.split(paths.sep).join("/");
|
|
374
|
+
}
|
|
375
|
+
function fromJournalPath(from, recorded, paths = path) {
|
|
376
|
+
return paths.isAbsolute(recorded) ? recorded : paths.resolve(from, recorded);
|
|
377
|
+
}
|
|
378
|
+
function journalPath(runDir) {
|
|
379
|
+
return join(runDir, JOURNAL_FILE);
|
|
380
|
+
}
|
|
381
|
+
/** Replaces the journal in one rename, so a reader sees the old state or the new. */
|
|
382
|
+
function writeJournal(runDir, journal) {
|
|
383
|
+
const file = journalPath(runDir);
|
|
384
|
+
const pending = `${file}.${process.pid}.tmp`;
|
|
385
|
+
writeFileSync(pending, `${JSON.stringify(journal, null, 2)}\n`);
|
|
386
|
+
renameSync(pending, file);
|
|
387
|
+
}
|
|
388
|
+
const isString = (value) => typeof value === "string" && value !== "";
|
|
389
|
+
function parseSnapshot(value) {
|
|
390
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
391
|
+
const { path, kind, copy, created } = value;
|
|
392
|
+
if (!isString(path) || kind !== "directory" && kind !== "build-info" && kind !== "file") return;
|
|
393
|
+
if (copy !== null && !isString(copy)) return void 0;
|
|
394
|
+
if (created !== null && !isString(created)) return void 0;
|
|
395
|
+
const { modes } = value;
|
|
396
|
+
if (modes === void 0) return {
|
|
397
|
+
path,
|
|
398
|
+
kind,
|
|
399
|
+
copy,
|
|
400
|
+
created
|
|
401
|
+
};
|
|
402
|
+
if (!Array.isArray(modes) || !modes.every(isDirectoryMode)) return void 0;
|
|
403
|
+
return {
|
|
404
|
+
path,
|
|
405
|
+
kind,
|
|
406
|
+
copy,
|
|
407
|
+
created,
|
|
408
|
+
modes
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
function parsePendingBuildInfo(value) {
|
|
412
|
+
if (value === void 0) return void 0;
|
|
413
|
+
if (typeof value !== "object" || value === null) return null;
|
|
414
|
+
const { path, target } = value;
|
|
415
|
+
return isString(path) && isString(target) ? {
|
|
416
|
+
path,
|
|
417
|
+
target
|
|
418
|
+
} : null;
|
|
419
|
+
}
|
|
420
|
+
const isDirectoryMode = (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && Number.isInteger(value[1]);
|
|
421
|
+
/** The journal of a run directory, or undefined when it is missing or unreadable. */
|
|
422
|
+
function readJournal(runDir) {
|
|
423
|
+
let value;
|
|
424
|
+
try {
|
|
425
|
+
value = JSON.parse(readFileSync(journalPath(runDir), "utf8"));
|
|
426
|
+
} catch {
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
430
|
+
const record = value;
|
|
431
|
+
if (record.format !== 1 || !isString(record.runId) || typeof record.pid !== "number" || !STATES.includes(record.state) || !isString(record.output) || !isString(record.stage) || !isString(record.retired)) return;
|
|
432
|
+
const optional = (key) => record[key] === void 0 || isString(record[key]);
|
|
433
|
+
if (!optional("generatedConfig") || !optional("outputDigest")) return void 0;
|
|
434
|
+
const pending = parsePendingBuildInfo(record.pendingBuildInfo);
|
|
435
|
+
if (pending === null) return void 0;
|
|
436
|
+
const undo = UNDO_STEPS.find((step) => step === record.undo) ?? null;
|
|
437
|
+
if (record.state === "rolling-back" !== (undo !== null)) return void 0;
|
|
438
|
+
let compiler = null;
|
|
439
|
+
if (Array.isArray(record.compiler)) {
|
|
440
|
+
compiler = [];
|
|
441
|
+
for (const entry of record.compiler) {
|
|
442
|
+
const snapshot = parseSnapshot(entry);
|
|
443
|
+
if (snapshot === void 0) return void 0;
|
|
444
|
+
compiler.push(snapshot);
|
|
445
|
+
}
|
|
446
|
+
} else if (record.compiler !== null) return;
|
|
447
|
+
return {
|
|
448
|
+
format: 1,
|
|
449
|
+
runId: record.runId,
|
|
450
|
+
pid: record.pid,
|
|
451
|
+
state: record.state,
|
|
452
|
+
undo,
|
|
453
|
+
output: record.output,
|
|
454
|
+
stage: record.stage,
|
|
455
|
+
retired: record.retired,
|
|
456
|
+
compiler,
|
|
457
|
+
...isString(record.generatedConfig) && { generatedConfig: record.generatedConfig },
|
|
458
|
+
...pending !== void 0 && { pendingBuildInfo: pending },
|
|
459
|
+
...isString(record.outputDigest) && { outputDigest: record.outputDigest }
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
//#endregion
|
|
463
|
+
//#region src/services/package-build/staging/boot-id.ts
|
|
464
|
+
function readBootId() {
|
|
465
|
+
try {
|
|
466
|
+
return (process.platform === "linux" ? readFileSync("/proc/sys/kernel/random/boot_id", "utf8") : process.platform === "darwin" ? execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
|
|
467
|
+
encoding: "utf8",
|
|
468
|
+
stdio: [
|
|
469
|
+
"ignore",
|
|
470
|
+
"pipe",
|
|
471
|
+
"ignore"
|
|
472
|
+
]
|
|
473
|
+
}) : "").trim() || null;
|
|
474
|
+
} catch {
|
|
475
|
+
return null;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
let memo;
|
|
479
|
+
/**
|
|
480
|
+
* This boot of the machine, as the OS names it, or null where it cannot be
|
|
481
|
+
* read. Unlike a boot time derived from the clock, it changes only with a
|
|
482
|
+
* reboot.
|
|
483
|
+
*/
|
|
484
|
+
function currentBootId() {
|
|
485
|
+
if (memo === void 0) memo = readBootId();
|
|
486
|
+
return memo;
|
|
487
|
+
}
|
|
488
|
+
//#endregion
|
|
489
|
+
//#region src/services/package-build/staging/lock.ts
|
|
490
|
+
const POLL_MS = 100;
|
|
491
|
+
const TAKEOVER_RETRY_MS = 10;
|
|
492
|
+
const QUIET_TAKEOVER_WAIT_MS = 1e3;
|
|
493
|
+
function isOwner(value) {
|
|
494
|
+
const owner = value;
|
|
495
|
+
return typeof owner?.pid === "number" && typeof owner.runId === "string" && typeof owner.host === "string" && (typeof owner.bootId === "string" || owner.bootId === null);
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* The owner's process is gone: on this machine, it ran in another boot (so
|
|
499
|
+
* the reboot ended it), or no process is left at its pid. Another host, or a
|
|
500
|
+
* live pid in this boot or an unknown one, is not proof: such an owner may
|
|
501
|
+
* still be building. A pid reused by another process of this boot reads as
|
|
502
|
+
* live, so its lock waits until someone deletes it.
|
|
503
|
+
*/
|
|
504
|
+
const provenDead = (owner) => {
|
|
505
|
+
if (owner.host !== hostname()) return false;
|
|
506
|
+
const boot = currentBootId();
|
|
507
|
+
if (owner.bootId !== null && boot !== null && owner.bootId !== boot) return true;
|
|
508
|
+
return !isProcessAlive(owner.pid);
|
|
509
|
+
};
|
|
510
|
+
const errorCode = (error) => error.code;
|
|
511
|
+
function isProcessAlive(pid) {
|
|
512
|
+
try {
|
|
513
|
+
process.kill(pid, 0);
|
|
514
|
+
return true;
|
|
515
|
+
} catch (error) {
|
|
516
|
+
return errorCode(error) === "EPERM";
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
/** What a waiting build says about who holds a lock or takeover file. */
|
|
520
|
+
function described(value) {
|
|
521
|
+
const fields = value;
|
|
522
|
+
const parts = [
|
|
523
|
+
["host", fields?.host],
|
|
524
|
+
["pid", fields?.pid],
|
|
525
|
+
["run", fields?.runId]
|
|
526
|
+
].flatMap(([name, field]) => typeof field === "string" || typeof field === "number" ? [`${name} ${field}`] : []);
|
|
527
|
+
return parts.length > 0 ? parts.join(", ") : "owner unknown";
|
|
528
|
+
}
|
|
529
|
+
function holderOf(file) {
|
|
530
|
+
let value;
|
|
531
|
+
try {
|
|
532
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
533
|
+
} catch (error) {
|
|
534
|
+
if (errorCode(error) === "ENOENT") return void 0;
|
|
535
|
+
}
|
|
536
|
+
if (isOwner(value)) return {
|
|
537
|
+
id: value.runId,
|
|
538
|
+
dead: provenDead(value),
|
|
539
|
+
owner: described(value)
|
|
540
|
+
};
|
|
541
|
+
const stat = lstatSync(file, { throwIfNoEntry: false });
|
|
542
|
+
return stat && {
|
|
543
|
+
id: `file ${stat.ino} ${stat.mtimeMs}`,
|
|
544
|
+
dead: false,
|
|
545
|
+
owner: described(value)
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Creates `file` holding `owner`, or returns false when it exists. The file
|
|
550
|
+
* appears with its content in one link, so no reader sees it empty.
|
|
551
|
+
*/
|
|
552
|
+
function createOwned(file, owner) {
|
|
553
|
+
const pending = join(dirname(file), `${pendingPrefix(basename(file))}${owner.runId}.pending`);
|
|
554
|
+
writeFileSync(pending, JSON.stringify(owner));
|
|
555
|
+
try {
|
|
556
|
+
linkSync(pending, file);
|
|
557
|
+
return true;
|
|
558
|
+
} catch (error) {
|
|
559
|
+
if (errorCode(error) === "EEXIST") return false;
|
|
560
|
+
throw error;
|
|
561
|
+
} finally {
|
|
562
|
+
rmSync(pending, { force: true });
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
const takeoverFile = (lockFile, staleId) => join(dirname(lockFile), `${takeoverPrefix(basename(lockFile))}${encodeURIComponent(staleId)}`);
|
|
566
|
+
/**
|
|
567
|
+
* Removes `file` while it still holds the dead holder `stale`. Only the
|
|
568
|
+
* creator of the takeover file keyed to `stale` may remove it, and `stale`
|
|
569
|
+
* cannot come back, so the owner read under that file is the one removed: a
|
|
570
|
+
* contender that judged it stale before someone else took over removes
|
|
571
|
+
* nothing. A takeover file is itself taken over only from a holder proven
|
|
572
|
+
* dead, never for its age, so a paused holder keeps it. Returns what blocks
|
|
573
|
+
* the takeover, or nothing when the caller should try again.
|
|
574
|
+
*/
|
|
575
|
+
function takeOver(lockFile, file, stale, me) {
|
|
576
|
+
const guard = takeoverFile(lockFile, stale.id);
|
|
577
|
+
if (!createOwned(guard, me)) {
|
|
578
|
+
const holder = holderOf(guard);
|
|
579
|
+
if (holder === void 0) return void 0;
|
|
580
|
+
return holder.dead ? takeOver(lockFile, guard, holder, me) : {
|
|
581
|
+
file: guard,
|
|
582
|
+
holder
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
try {
|
|
586
|
+
if (holderOf(file)?.id === stale.id) removeTree(file);
|
|
587
|
+
return;
|
|
588
|
+
} finally {
|
|
589
|
+
if (holderOf(guard)?.id === me.runId) rmSync(guard, { force: true });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Takeover files left by contenders that died. Safe under the lock: one
|
|
594
|
+
* matters only while the lock holds its stale owner, and the lock is ours.
|
|
595
|
+
* A pending file goes only when its writer is proven dead: a live
|
|
596
|
+
* contender links it next.
|
|
597
|
+
*/
|
|
598
|
+
function removeTakeoverFiles(lockFile) {
|
|
599
|
+
const takeover = takeoverPrefix(basename(lockFile));
|
|
600
|
+
const pending = pendingPrefix(basename(lockFile));
|
|
601
|
+
for (const entry of readdirSync(dirname(lockFile))) {
|
|
602
|
+
const file = join(dirname(lockFile), entry);
|
|
603
|
+
if (entry.startsWith(takeover) || entry.startsWith(pending) && entry.endsWith(".pending") && holderOf(file)?.dead === true) rmSync(file, { force: true });
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Takes `.ph/build/lock`, a file created exclusively that names this run.
|
|
608
|
+
* A lock is taken over only from an owner proven dead (see `provenDead`);
|
|
609
|
+
* otherwise this waits, and says once per holder which file it waits for.
|
|
610
|
+
*/
|
|
611
|
+
async function acquireBuildLock(lockFile, runId, onWait) {
|
|
612
|
+
mkdirSync(dirname(lockFile), { recursive: true });
|
|
613
|
+
const me = {
|
|
614
|
+
pid: process.pid,
|
|
615
|
+
runId,
|
|
616
|
+
host: hostname(),
|
|
617
|
+
bootId: currentBootId()
|
|
618
|
+
};
|
|
619
|
+
const told = /* @__PURE__ */ new Set();
|
|
620
|
+
const firstBlocked = /* @__PURE__ */ new Map();
|
|
621
|
+
for (;;) {
|
|
622
|
+
if (createOwned(lockFile, me)) {
|
|
623
|
+
removeTakeoverFiles(lockFile);
|
|
624
|
+
let held = true;
|
|
625
|
+
return { release: () => {
|
|
626
|
+
if (!held) return;
|
|
627
|
+
held = false;
|
|
628
|
+
if (holderOf(lockFile)?.id === runId) rmSync(lockFile);
|
|
629
|
+
} };
|
|
630
|
+
}
|
|
631
|
+
const holder = holderOf(lockFile);
|
|
632
|
+
if (holder === void 0) continue;
|
|
633
|
+
const blocked = holder.dead ? takeOver(lockFile, lockFile, holder, me) : {
|
|
634
|
+
file: lockFile,
|
|
635
|
+
holder
|
|
636
|
+
};
|
|
637
|
+
if (blocked === void 0) {
|
|
638
|
+
await setTimeout$1(TAKEOVER_RETRY_MS);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
const key = `${blocked.file}\0${blocked.holder.id}`;
|
|
642
|
+
const since = firstBlocked.get(key) ?? Date.now();
|
|
643
|
+
firstBlocked.set(key, since);
|
|
644
|
+
if (!(blocked.file !== lockFile && Date.now() - since < QUIET_TAKEOVER_WAIT_MS) && !told.has(key)) {
|
|
645
|
+
told.add(key);
|
|
646
|
+
onWait({
|
|
647
|
+
file: blocked.file,
|
|
648
|
+
owner: blocked.holder.owner
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
await setTimeout$1(blocked.file === lockFile ? POLL_MS : TAKEOVER_RETRY_MS);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
//#endregion
|
|
655
|
+
//#region src/services/definitions/paths.ts
|
|
656
|
+
function toPosixPath(path) {
|
|
657
|
+
return path.split(sep).join("/");
|
|
658
|
+
}
|
|
659
|
+
function canonicalConfigFile(configFile) {
|
|
660
|
+
const absolute = resolve(configFile);
|
|
661
|
+
return join(realPathThroughExistingParent(dirname(absolute)), basename(absolute));
|
|
662
|
+
}
|
|
663
|
+
//#endregion
|
|
664
|
+
//#region src/services/package-build/staging/recovery.ts
|
|
665
|
+
function runPaths(packageRoot, runDir, journal) {
|
|
666
|
+
return {
|
|
667
|
+
packageRoot,
|
|
668
|
+
runDir,
|
|
669
|
+
output: fromJournalPath(packageRoot, journal.output),
|
|
670
|
+
stage: fromJournalPath(packageRoot, journal.stage),
|
|
671
|
+
retired: fromJournalPath(packageRoot, journal.retired)
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
function outputDigest(packageRoot, output, compiler) {
|
|
675
|
+
const real = realPathThroughExistingParent(output);
|
|
676
|
+
const inOutput = (recorded) => {
|
|
677
|
+
const rel = pathWithin(real, fromJournalPath(packageRoot, recorded));
|
|
678
|
+
return rel === null ? null : toPosixPath(rel);
|
|
679
|
+
};
|
|
680
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
681
|
+
const unmarked = /* @__PURE__ */ new Set();
|
|
682
|
+
for (const { path, created } of compiler) {
|
|
683
|
+
if (pathWithin(fromJournalPath(packageRoot, path), real) !== null) return;
|
|
684
|
+
const rel = inOutput(path);
|
|
685
|
+
if (rel === null) continue;
|
|
686
|
+
skipped.add(rel);
|
|
687
|
+
if (created !== null) {
|
|
688
|
+
const parts = rel.split("/");
|
|
689
|
+
const createdRel = inOutput(created);
|
|
690
|
+
const first = createdRel ? createdRel.split("/").length : 1;
|
|
691
|
+
for (let length = first; length < parts.length; length++) unmarked.add(parts.slice(0, length).join("/"));
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return treeFingerprint(output, skipped, unmarked);
|
|
695
|
+
}
|
|
696
|
+
function removeScratch(packageRoot, journal) {
|
|
697
|
+
for (const recorded of [journal.generatedConfig, journal.pendingBuildInfo?.path]) if (recorded !== void 0) removeTree(fromJournalPath(packageRoot, recorded));
|
|
698
|
+
}
|
|
699
|
+
function installBuildInfo(packageRoot, pending) {
|
|
700
|
+
if (pending === void 0) return;
|
|
701
|
+
const path = fromJournalPath(packageRoot, pending.path);
|
|
702
|
+
if (exists(path)) renamePatiently(path, fromJournalPath(packageRoot, pending.target));
|
|
703
|
+
}
|
|
704
|
+
/** Puts `from` at `to`: one rename, or entry by entry when `from` is held open. */
|
|
705
|
+
function moveTree(from, to) {
|
|
706
|
+
try {
|
|
707
|
+
renamePatiently(from, to);
|
|
708
|
+
return "renamed";
|
|
709
|
+
} catch (error) {
|
|
710
|
+
if (!isHeldOpen(error)) throw error;
|
|
711
|
+
mkdirSync(to, { recursive: true });
|
|
712
|
+
moveEntries(from, to);
|
|
713
|
+
removeTree(from);
|
|
714
|
+
return "entries";
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
/** Build info first: if a later copy fails, tsc still sees its outputs as stale. */
|
|
718
|
+
function restoreCompilerOutputs(paths, snapshots) {
|
|
719
|
+
const ordered = [...snapshots ?? []].sort((a, b) => Number(b.kind === "build-info") - Number(a.kind === "build-info"));
|
|
720
|
+
for (const snapshot of ordered) {
|
|
721
|
+
const path = fromJournalPath(paths.packageRoot, snapshot.path);
|
|
722
|
+
if (snapshot.copy !== null) {
|
|
723
|
+
replaceTree(fromJournalPath(paths.runDir, snapshot.copy), path);
|
|
724
|
+
restoreDirectoryModes(path, snapshot.modes ?? []);
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
removeTree(path);
|
|
728
|
+
if (snapshot.created !== null) removeEmptyDirectories(dirname(path), fromJournalPath(paths.packageRoot, snapshot.created));
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
/** Removes `from` and its parents up to `upTo` while each is an empty directory. */
|
|
732
|
+
function removeEmptyDirectories(from, upTo) {
|
|
733
|
+
for (let dir = from;; dir = dirname(dir)) {
|
|
734
|
+
if (!exists(dir) || entriesOf(dir).length > 0) return;
|
|
735
|
+
rmdirSync(dir);
|
|
736
|
+
if (dir === upTo || dirname(dir) === dir) return;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
const FIRST_UNDO_STEP = {
|
|
740
|
+
building: "stage",
|
|
741
|
+
retiring: "retire",
|
|
742
|
+
installing: "install"
|
|
743
|
+
};
|
|
744
|
+
/**
|
|
745
|
+
* Undoes a run: the previous output goes back in place, the stage goes, and
|
|
746
|
+
* the compiler outputs are restored, unless a later build replaced the output
|
|
747
|
+
* since they were saved (`superseded`). The journal records each step before
|
|
748
|
+
* it starts, so a rollback cut short is finished by the next build, never
|
|
749
|
+
* rolled forward; the run directory, and the snapshot in it, stay until the
|
|
750
|
+
* caller removes them.
|
|
751
|
+
*/
|
|
752
|
+
function rollBack(paths, journal) {
|
|
753
|
+
if (journal.state === "committed") return "restored";
|
|
754
|
+
const first = journal.state === "rolling-back" ? journal.undo ?? "stage" : FIRST_UNDO_STEP[journal.state];
|
|
755
|
+
const { output, retired } = paths;
|
|
756
|
+
for (const step of UNDO_STEPS.slice(UNDO_STEPS.indexOf(first))) {
|
|
757
|
+
writeJournal(paths.runDir, {
|
|
758
|
+
...journal,
|
|
759
|
+
state: "rolling-back",
|
|
760
|
+
undo: step
|
|
761
|
+
});
|
|
762
|
+
if (step === "install") {
|
|
763
|
+
if (!exists(retired)) removeTree(output);
|
|
764
|
+
else for (const entry of entriesOf(output)) removeTree(join(output, entry));
|
|
765
|
+
} else if (step === "retire") {
|
|
766
|
+
if (exists(retired)) {
|
|
767
|
+
if (exists(output)) moveEntries(retired, output);
|
|
768
|
+
else moveTree(retired, output);
|
|
769
|
+
}
|
|
770
|
+
} else {
|
|
771
|
+
removeTree(paths.stage);
|
|
772
|
+
removeTree(retired);
|
|
773
|
+
removeScratch(paths.packageRoot, journal);
|
|
774
|
+
const digest = journal.outputDigest === void 0 ? void 0 : outputDigest(paths.packageRoot, output, journal.compiler ?? []);
|
|
775
|
+
if (digest !== void 0 && digest !== journal.outputDigest) return "superseded";
|
|
776
|
+
restoreCompilerOutputs(paths, journal.compiler);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
return "restored";
|
|
780
|
+
}
|
|
781
|
+
/** Finishes a run that was installing its stage: the stage becomes the output. */
|
|
782
|
+
function rollForward(paths, journal) {
|
|
783
|
+
const { output, stage } = paths;
|
|
784
|
+
if (exists(stage)) {
|
|
785
|
+
if (exists(output)) moveEntries(stage, output);
|
|
786
|
+
else moveTree(stage, output);
|
|
787
|
+
}
|
|
788
|
+
installBuildInfo(paths.packageRoot, journal.pendingBuildInfo);
|
|
789
|
+
removeTree(stage);
|
|
790
|
+
removeTree(paths.retired);
|
|
791
|
+
removeScratch(paths.packageRoot, journal);
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Brings the package back to a consistent state after a run that died, then
|
|
795
|
+
* removes its run directory. A run that had not started to install its stage,
|
|
796
|
+
* or had started to roll back, is undone; one installing its stage is
|
|
797
|
+
* finished.
|
|
798
|
+
*/
|
|
799
|
+
function replayRun(packageRoot, runDir) {
|
|
800
|
+
const journal = readJournal(runDir);
|
|
801
|
+
let replayed = "discarded";
|
|
802
|
+
if (journal !== void 0) {
|
|
803
|
+
const paths = runPaths(packageRoot, runDir, journal);
|
|
804
|
+
if (journal.state !== "installing" && journal.state !== "committed") replayed = rollBack(paths, journal) === "superseded" ? "superseded" : "rolled-back";
|
|
805
|
+
else {
|
|
806
|
+
rollForward(paths, journal);
|
|
807
|
+
replayed = "completed";
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
removeTree(runDir);
|
|
811
|
+
return replayed;
|
|
812
|
+
}
|
|
813
|
+
/** A run's stage and retired tree beside the output named `output`. */
|
|
814
|
+
const isScratchOf = (output, entry) => entry.startsWith(`.${output}.ph-stage-`) || entry.startsWith(`.${output}.ph-old-`);
|
|
815
|
+
/**
|
|
816
|
+
* Undoes or finishes every run a dead build left behind, then removes any
|
|
817
|
+
* stage or retired tree beside `output` that no run claims any more: a
|
|
818
|
+
* bundler of a stopped build can go on writing after its rollback. Call
|
|
819
|
+
* under the lock, where no other run of this package is live.
|
|
820
|
+
*/
|
|
821
|
+
function recoverStaleRuns(packageRoot, output) {
|
|
822
|
+
const runsDir = join(packageRoot, RUNS_DIRECTORY);
|
|
823
|
+
for (const runId of entriesOf(runsDir)) {
|
|
824
|
+
const replayed = replayRun(packageRoot, join(runsDir, runId));
|
|
825
|
+
if (replayed === "rolled-back") console.warn("⚠ An earlier build of this package stopped before it finished; its partial output was removed and the previous output restored.");
|
|
826
|
+
else if (replayed === "superseded") console.warn(`⚠ An earlier build of this package stopped before it finished, and a build that wrote ${toJournalPath(packageRoot, output) || "the package root"} in place ran after it; the earlier build's partial output was removed and the newer files were kept.`);
|
|
827
|
+
else if (replayed === "completed") console.warn("⚠ An earlier build of this package stopped while it replaced its output; the replacement was completed.");
|
|
828
|
+
}
|
|
829
|
+
const beside = dirname(output);
|
|
830
|
+
for (const entry of entriesOf(beside)) if (isScratchOf(basename(output), entry)) removeTree(join(beside, entry));
|
|
831
|
+
}
|
|
832
|
+
//#endregion
|
|
833
|
+
//#region src/services/compiler-output/emit.ts
|
|
834
|
+
const withoutExtension = (path) => path.replace(/\.[^./\\]+$/, "");
|
|
835
|
+
const declares = (options) => options.declaration === true || options.composite === true;
|
|
836
|
+
/**
|
|
837
|
+
* Where tsc keeps the build info of `configFile`, by TypeScript's rule:
|
|
838
|
+
* `tsBuildInfoFile`; else beside `outFile`; else in `outDir`, at the
|
|
839
|
+
* config's place relative to `rootDir` when that is set; else beside the
|
|
840
|
+
* config.
|
|
841
|
+
*/
|
|
842
|
+
function buildInfoFile(options, configFile) {
|
|
843
|
+
const configDir = dirname(configFile);
|
|
844
|
+
const name = `${basename(configFile, extname(configFile))}.tsbuildinfo`;
|
|
845
|
+
if (options.tsBuildInfoFile !== void 0) return resolve(configDir, options.tsBuildInfoFile);
|
|
846
|
+
if (options.outFile !== void 0) return resolve(configDir, `${withoutExtension(options.outFile)}.tsbuildinfo`);
|
|
847
|
+
if (options.outDir === void 0) return resolve(configDir, name);
|
|
848
|
+
const fromRoot = options.rootDir === void 0 ? "" : relative(resolve(configDir, options.rootDir), configDir);
|
|
849
|
+
return resolve(configDir, options.outDir, fromRoot, name);
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* The files tsc writes for `outFile`: the bundle and its map unless it
|
|
853
|
+
* emits declarations only, then the declaration and its map when it
|
|
854
|
+
* declares. None without `outFile` or with `noEmit`.
|
|
855
|
+
*/
|
|
856
|
+
function outFileOutputs(options, configFile) {
|
|
857
|
+
if (options.outFile === void 0 || options.noEmit) return [];
|
|
858
|
+
const output = resolve(dirname(configFile), options.outFile);
|
|
859
|
+
const files = [];
|
|
860
|
+
if (!options.emitDeclarationOnly) files.push(output, ...options.sourceMap ? [`${output}.map`] : []);
|
|
861
|
+
if (declares(options)) {
|
|
862
|
+
const declaration = `${withoutExtension(output)}.d.ts`;
|
|
863
|
+
files.push(declaration, ...options.declarationMap ? [`${declaration}.map`] : []);
|
|
864
|
+
}
|
|
865
|
+
return files;
|
|
866
|
+
}
|
|
867
|
+
/** The declaration and output directories the options name, resolved. */
|
|
868
|
+
function outputDirectories$1(options, configDir) {
|
|
869
|
+
return [options.declarationDir, options.outDir].filter((dir) => dir !== void 0).map((dir) => resolve(configDir, dir));
|
|
870
|
+
}
|
|
871
|
+
/** Where tsc writes declarations, when it writes them to a directory of their own. */
|
|
872
|
+
function declarationDirectory(options, configDir) {
|
|
873
|
+
const dir = options.declarationDir ?? options.outDir;
|
|
874
|
+
if (!dir || !declares(options)) return void 0;
|
|
875
|
+
return resolve(configDir, dir);
|
|
876
|
+
}
|
|
877
|
+
//#endregion
|
|
878
|
+
//#region src/services/definitions/config-inputs.ts
|
|
879
|
+
const configSchema$1 = object({
|
|
880
|
+
extends: union([string(), array(string())]).optional(),
|
|
881
|
+
compilerOptions: record(string(), json()).optional()
|
|
882
|
+
});
|
|
883
|
+
function readConfig(path) {
|
|
884
|
+
const text = readFileSync(path, "utf8").replace(/^\uFEFF/, "").replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, (token) => token.startsWith("\"") ? token : "").replace(/"(?:\\.|[^"\\])*"|,\s*(?=[}\]])/g, (token) => token.startsWith("\"") ? token : "");
|
|
885
|
+
return JSON.parse(text);
|
|
886
|
+
}
|
|
887
|
+
const manifestSchema = object({
|
|
888
|
+
tsconfig: string().optional(),
|
|
889
|
+
exports: json().optional(),
|
|
890
|
+
typesVersions: record(string(), record(string(), array(string()))).optional()
|
|
891
|
+
});
|
|
892
|
+
function configDirOptions(configFile, compilerVersion) {
|
|
893
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
894
|
+
const options = (path) => {
|
|
895
|
+
if (visiting.has(path)) return {};
|
|
896
|
+
visiting.add(path);
|
|
897
|
+
const config = configSchema$1.parse(readConfig(path));
|
|
898
|
+
const bases = typeof config.extends === "string" ? [config.extends] : config.extends ?? [];
|
|
899
|
+
const inherited = {};
|
|
900
|
+
for (const base of bases) Object.assign(inherited, options(extendedConfig(path, base, compilerVersion)));
|
|
901
|
+
visiting.delete(path);
|
|
902
|
+
return {
|
|
903
|
+
...inherited,
|
|
904
|
+
...config.compilerOptions
|
|
905
|
+
};
|
|
906
|
+
};
|
|
907
|
+
const substitute = (value) => {
|
|
908
|
+
if (typeof value === "string") return value.replaceAll("${configDir}", dirname(configFile));
|
|
909
|
+
if (Array.isArray(value)) return value.map(substitute);
|
|
910
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, substitute(entry)]));
|
|
911
|
+
return value;
|
|
912
|
+
};
|
|
913
|
+
return Object.fromEntries(Object.entries(options(configFile)).filter(([, value]) => JSON.stringify(value).includes("${configDir}")).map(([key, value]) => [key, substitute(value)]));
|
|
914
|
+
}
|
|
915
|
+
function file(path) {
|
|
916
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() ? path : void 0;
|
|
917
|
+
}
|
|
918
|
+
function jsonFile(path) {
|
|
919
|
+
if (path.endsWith(".json")) return file(path);
|
|
920
|
+
return file(`${path.replace(/\.(?:js|ts)$/, "")}.json`) ?? file(`${path}.json`);
|
|
921
|
+
}
|
|
922
|
+
function matchedPath(paths, name, exports = false) {
|
|
923
|
+
if (Object.hasOwn(paths, name)) return {
|
|
924
|
+
key: name,
|
|
925
|
+
match: ""
|
|
926
|
+
};
|
|
927
|
+
const keys = Object.keys(paths).filter((key) => key.includes("*") && key.indexOf("*") === key.lastIndexOf("*") || exports && key.endsWith("/"));
|
|
928
|
+
keys.sort((a, b) => {
|
|
929
|
+
const prefix = (key) => key.includes("*") ? key.indexOf("*") + 1 : key.length;
|
|
930
|
+
return prefix(b) - prefix(a) || (exports ? Number(!a.includes("*")) - Number(!b.includes("*")) || b.length - a.length : 0);
|
|
931
|
+
});
|
|
932
|
+
for (const key of keys) {
|
|
933
|
+
const star = key.indexOf("*");
|
|
934
|
+
if (star !== -1 && name.startsWith(key.slice(0, star)) && name.endsWith(key.slice(star + 1))) return {
|
|
935
|
+
key,
|
|
936
|
+
match: name.slice(star, name.length - (key.length - star - 1))
|
|
937
|
+
};
|
|
938
|
+
if (star === -1 && name.startsWith(key)) return {
|
|
939
|
+
key,
|
|
940
|
+
match: name.slice(key.length)
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
function exportedConfig(target, directory, compilerVersion, match, pattern) {
|
|
945
|
+
if (typeof target === "string") {
|
|
946
|
+
if (!target.startsWith("./") || !pattern && match !== "" && !target.endsWith("/")) return {};
|
|
947
|
+
const path = pattern ? target.replaceAll("*", match) : target + match;
|
|
948
|
+
if (path.slice(2).split("/").some((part) => part === "." || part === ".." || part === "node_modules")) return {};
|
|
949
|
+
const resolved = jsonFile(resolve(directory, path));
|
|
950
|
+
return resolved === void 0 ? {} : { path: resolved };
|
|
951
|
+
}
|
|
952
|
+
if (target === null) return {};
|
|
953
|
+
if (Array.isArray(target)) {
|
|
954
|
+
if (target.length === 0) return {};
|
|
955
|
+
for (const entry of target) {
|
|
956
|
+
const result = exportedConfig(entry, directory, compilerVersion, match, pattern);
|
|
957
|
+
if (result !== void 0) return result;
|
|
958
|
+
}
|
|
959
|
+
} else if (typeof target === "object") {
|
|
960
|
+
for (const [condition, entry] of Object.entries(target)) if ([
|
|
961
|
+
"types",
|
|
962
|
+
"require",
|
|
963
|
+
"node",
|
|
964
|
+
"default"
|
|
965
|
+
].includes(condition) || condition.startsWith("types@") && satisfies(compilerVersion, condition.slice(6))) {
|
|
966
|
+
const result = exportedConfig(entry, directory, compilerVersion, match, pattern);
|
|
967
|
+
if (result !== void 0) return result;
|
|
968
|
+
}
|
|
969
|
+
} else return {};
|
|
970
|
+
}
|
|
971
|
+
function extendedConfig(configFile, input, compilerVersion) {
|
|
972
|
+
const specifier = input.replaceAll("\\", "/");
|
|
973
|
+
if (specifier.startsWith("./") || specifier.startsWith("../") || isAbsolute(specifier)) {
|
|
974
|
+
const path = resolve(dirname(configFile), specifier);
|
|
975
|
+
const found = file(path) ?? (!path.endsWith(".json") ? file(`${path}.json`) : void 0);
|
|
976
|
+
if (found !== void 0) return found;
|
|
977
|
+
} else {
|
|
978
|
+
const parts = specifier.split("/");
|
|
979
|
+
const nameLength = specifier.startsWith("@") ? 2 : 1;
|
|
980
|
+
const packageName = parts.slice(0, nameLength).join("/");
|
|
981
|
+
const subpath = parts.slice(nameLength).join("/");
|
|
982
|
+
const manifestAt = (directory) => {
|
|
983
|
+
const path = join(directory, "package.json");
|
|
984
|
+
if (!existsSync(path)) return void 0;
|
|
985
|
+
return manifestSchema.parse(readConfig(path));
|
|
986
|
+
};
|
|
987
|
+
const fromDirectory = (directory, pkg) => {
|
|
988
|
+
const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(([range]) => satisfies(compilerVersion, range))?.[1];
|
|
989
|
+
const entry = pkg?.tsconfig ? resolve(directory, pkg.tsconfig) : join(directory, "tsconfig");
|
|
990
|
+
if (versionPaths !== void 0) {
|
|
991
|
+
const match = matchedPath(versionPaths, entry.slice(directory.length + 1));
|
|
992
|
+
if (match !== void 0) for (const path of versionPaths[match.key] ?? []) {
|
|
993
|
+
const found = jsonFile(resolve(directory, path.replace("*", match.match)));
|
|
994
|
+
if (found !== void 0) return found;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
return (pkg?.tsconfig ? jsonFile(entry) : void 0) ?? jsonFile(join(directory, "tsconfig"));
|
|
998
|
+
};
|
|
999
|
+
for (const modules of createRequire(configFile).resolve.paths(specifier) ?? []) {
|
|
1000
|
+
const directory = join(modules, packageName);
|
|
1001
|
+
const candidate = join(modules, specifier);
|
|
1002
|
+
const nested = manifestAt(candidate);
|
|
1003
|
+
const pkg = subpath === "" ? nested : manifestAt(directory);
|
|
1004
|
+
if (subpath !== "" && nested !== void 0 && !pkg?.exports) {
|
|
1005
|
+
const found = jsonFile(candidate) ?? fromDirectory(candidate, nested);
|
|
1006
|
+
if (found !== void 0) return found;
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
if (pkg?.exports) {
|
|
1010
|
+
const exports = pkg.exports;
|
|
1011
|
+
const key = subpath === "" ? "." : `./${subpath}`;
|
|
1012
|
+
let target;
|
|
1013
|
+
let match = "";
|
|
1014
|
+
let pattern = false;
|
|
1015
|
+
if (typeof exports === "object" && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith("."))) {
|
|
1016
|
+
const matched = matchedPath(exports, key, true);
|
|
1017
|
+
if (matched !== void 0) {
|
|
1018
|
+
target = exports[matched.key];
|
|
1019
|
+
match = matched.match;
|
|
1020
|
+
pattern = matched.key.includes("*");
|
|
1021
|
+
}
|
|
1022
|
+
} else if (key === ".") target = exports;
|
|
1023
|
+
const found = target === void 0 ? void 0 : exportedConfig(target, directory, compilerVersion, match, pattern)?.path;
|
|
1024
|
+
if (found !== void 0) return found;
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
const versionPaths = Object.entries(pkg?.typesVersions ?? {}).find(([range]) => satisfies(compilerVersion, range))?.[1];
|
|
1028
|
+
if (subpath !== "" && versionPaths !== void 0) {
|
|
1029
|
+
const match = matchedPath(versionPaths, subpath);
|
|
1030
|
+
if (match !== void 0) for (const path of versionPaths[match.key] ?? []) {
|
|
1031
|
+
const found = jsonFile(resolve(directory, path.replace("*", match.match)));
|
|
1032
|
+
if (found !== void 0) return found;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
const found = jsonFile(candidate) ?? fromDirectory(candidate, pkg);
|
|
1036
|
+
if (found !== void 0) return found;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
throw new Error(`The extended TypeScript config ${JSON.stringify(specifier)} could not be resolved from ${JSON.stringify(configFile)}.`);
|
|
1040
|
+
}
|
|
1041
|
+
//#endregion
|
|
1042
|
+
//#region src/services/definitions/compiler-output.ts
|
|
1043
|
+
const lines = (stdout) => stdout.split(/\r?\n/);
|
|
1044
|
+
function listedFiles(stdout = "", directory = ".") {
|
|
1045
|
+
return lines(stdout).map((line) => line.trim()).map((line) => resolve(directory, line)).filter((line) => existsSync(line) && statSync(line).isFile());
|
|
1046
|
+
}
|
|
1047
|
+
function explainedRoots(stdout, directory) {
|
|
1048
|
+
const roots = [];
|
|
1049
|
+
let file;
|
|
1050
|
+
for (const line of lines(stdout)) if (line !== "" && line === line.trim() && /\.(?:[cm]?[jt]sx?|json)$/i.test(line)) {
|
|
1051
|
+
const path = resolve(directory, line);
|
|
1052
|
+
file = statSync(path, { throwIfNoEntry: false })?.isFile() ? path : void 0;
|
|
1053
|
+
} else if (file !== void 0 && /Root file specified|Part of 'files' list|Matched by (default )?include pattern/.test(line)) roots.push(file);
|
|
1054
|
+
return roots;
|
|
1055
|
+
}
|
|
1056
|
+
//#endregion
|
|
1057
|
+
//#region src/services/definitions/compiler.ts
|
|
1058
|
+
async function runLocal(packageRoot, agent, argv) {
|
|
1059
|
+
const command = resolveCommand(agent, "execute-local", [...argv]);
|
|
1060
|
+
if (command === null) return {
|
|
1061
|
+
ok: false,
|
|
1062
|
+
output: `${argv[0]} is not installed in this package`
|
|
1063
|
+
};
|
|
1064
|
+
try {
|
|
1065
|
+
return {
|
|
1066
|
+
ok: true,
|
|
1067
|
+
output: await spawnAsync(command.command, command.args, {
|
|
1068
|
+
cwd: packageRoot,
|
|
1069
|
+
env: {
|
|
1070
|
+
...process.env,
|
|
1071
|
+
PWD: packageRoot
|
|
1072
|
+
}
|
|
1073
|
+
})
|
|
1074
|
+
};
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
return {
|
|
1077
|
+
ok: false,
|
|
1078
|
+
output: error instanceof SpawnError && error.stdout.length !== 0 ? error.stdout : error instanceof Error ? error.message : `${argv[0]} failed`
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
const configSchema = object({
|
|
1083
|
+
compilerOptions: looseObject({
|
|
1084
|
+
declaration: boolean().optional(),
|
|
1085
|
+
composite: boolean().optional(),
|
|
1086
|
+
incremental: boolean().optional(),
|
|
1087
|
+
declarationDir: string().optional(),
|
|
1088
|
+
outDir: string().optional(),
|
|
1089
|
+
rootDir: string().optional(),
|
|
1090
|
+
noEmit: boolean().optional(),
|
|
1091
|
+
emitDeclarationOnly: boolean().optional(),
|
|
1092
|
+
sourceMap: boolean().optional(),
|
|
1093
|
+
declarationMap: boolean().optional(),
|
|
1094
|
+
jsx: string().optional(),
|
|
1095
|
+
outFile: string().optional(),
|
|
1096
|
+
tsBuildInfoFile: string().optional(),
|
|
1097
|
+
resolveJsonModule: boolean().optional()
|
|
1098
|
+
}),
|
|
1099
|
+
references: array(object({ path: string() })).optional()
|
|
1100
|
+
});
|
|
1101
|
+
var CompilerDiagnostic = class extends Error {
|
|
1102
|
+
configFile;
|
|
1103
|
+
noWrites;
|
|
1104
|
+
constructor(summary, configFile, noWrites) {
|
|
1105
|
+
super(summary);
|
|
1106
|
+
this.configFile = configFile;
|
|
1107
|
+
this.noWrites = noWrites;
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
function projectConfigFile(path) {
|
|
1111
|
+
const entry = statSync(path, { throwIfNoEntry: false });
|
|
1112
|
+
return canonicalConfigFile(entry?.isDirectory() || entry === void 0 && !path.endsWith(".json") ? join(path, "tsconfig.json") : path);
|
|
1113
|
+
}
|
|
1114
|
+
function commonSourceDirectory(files, fallback) {
|
|
1115
|
+
let root = files.length === 0 ? fallback : dirname(files[0] ?? fallback);
|
|
1116
|
+
for (const file of files) while (pathWithin(root, file) === null) {
|
|
1117
|
+
const parent = dirname(root);
|
|
1118
|
+
if (parent === root) throw new Error("TypeScript sources on different drives have no common source directory.");
|
|
1119
|
+
root = parent;
|
|
1120
|
+
}
|
|
1121
|
+
return root;
|
|
1122
|
+
}
|
|
1123
|
+
function outputFiles(project, emitsBuildInfoInBuildMode) {
|
|
1124
|
+
const { options, sources, configFile } = project;
|
|
1125
|
+
const directory = dirname(configFile);
|
|
1126
|
+
const root = project.emitRoot;
|
|
1127
|
+
const files = emitsBuildInfoInBuildMode || options.composite || options.incremental || options.tsBuildInfoFile !== void 0 ? [buildInfoFile(options, configFile)] : [];
|
|
1128
|
+
if (options.noEmit) return files;
|
|
1129
|
+
if (options.outFile !== void 0) return [...files, ...outFileOutputs(options, configFile)];
|
|
1130
|
+
const declares = options.declaration === true || options.composite === true;
|
|
1131
|
+
for (const source of sources) {
|
|
1132
|
+
if (/\.json$/i.test(source)) {
|
|
1133
|
+
if (!options.emitDeclarationOnly) {
|
|
1134
|
+
const inside = pathWithin(root, source);
|
|
1135
|
+
files.push(options.outDir === void 0 || inside === null ? source : resolve(directory, options.outDir, inside));
|
|
1136
|
+
}
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
const suffix = /\.[cm]?[jt]sx?$/i;
|
|
1140
|
+
const jsExtension = /\.[cm][jt]s$/i.test(source) ? source.slice(-4).replace("t", "j") : options.jsx === "preserve" && /[jt]sx$/i.test(source) ? ".jsx" : ".js";
|
|
1141
|
+
const declarationExtension = /\.[cm][jt]s$/i.test(source) ? source.slice(-4).replace(/j/, "t").replace(".", ".d.") : ".d.ts";
|
|
1142
|
+
const inRoot = pathWithin(root, source);
|
|
1143
|
+
const destination = (out, extension) => out === void 0 || inRoot === null ? source.replace(suffix, extension) : resolve(directory, out, inRoot.replace(suffix, extension));
|
|
1144
|
+
if (!options.emitDeclarationOnly) {
|
|
1145
|
+
const js = destination(options.outDir, jsExtension);
|
|
1146
|
+
files.push(js, ...options.sourceMap ? [js + ".map"] : []);
|
|
1147
|
+
}
|
|
1148
|
+
if (declares) {
|
|
1149
|
+
const declaration = destination(options.declarationDir ?? options.outDir, declarationExtension);
|
|
1150
|
+
files.push(declaration, ...options.declarationMap ? [declaration + ".map"] : []);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
return files;
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Reads the package's project graph through its own `tsc` and predicts what
|
|
1157
|
+
* `tsc --build` writes, without writing. Refuses a build that would write
|
|
1158
|
+
* outside the package.
|
|
1159
|
+
*/
|
|
1160
|
+
async function prepareCompile(packageRoot, agent) {
|
|
1161
|
+
try {
|
|
1162
|
+
const version = await runLocal(packageRoot, agent, ["tsc", "--version"]);
|
|
1163
|
+
const match = /Version (\d+)\.(\d+)/.exec(version.output);
|
|
1164
|
+
if (match === null) throw new Error("The installed TypeScript version could not be resolved.");
|
|
1165
|
+
const major = Number(match[1]);
|
|
1166
|
+
const minor = Number(match[2]);
|
|
1167
|
+
const emitsBuildInfoInBuildMode = major > 5 || major === 5 && minor >= 6;
|
|
1168
|
+
const defaultsRootDirToConfig = major >= 6;
|
|
1169
|
+
return {
|
|
1170
|
+
ok: true,
|
|
1171
|
+
plan: checkedCompilePlan(packageRoot, await readProjectGraph(packageRoot, agent, join(packageRoot, "tsconfig.json"), defaultsRootDirToConfig, /Version (\S+)/.exec(version.output)?.[1] ?? `${major}.${minor}.0`), emitsBuildInfoInBuildMode)
|
|
1172
|
+
};
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
if (error instanceof CompilerDiagnostic && error.noWrites && error.configFile === projectConfigFile(join(packageRoot, "tsconfig.json"))) return {
|
|
1175
|
+
ok: true,
|
|
1176
|
+
plan: {
|
|
1177
|
+
...checkedCompilePlan(packageRoot, [{
|
|
1178
|
+
configFile: error.configFile,
|
|
1179
|
+
options: { noEmit: true },
|
|
1180
|
+
sources: [],
|
|
1181
|
+
external: false,
|
|
1182
|
+
emitRoot: packageRoot,
|
|
1183
|
+
references: []
|
|
1184
|
+
}], false),
|
|
1185
|
+
preflightTypeError: error.message
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
return {
|
|
1189
|
+
ok: false,
|
|
1190
|
+
summary: error instanceof Error ? error.message : "The TypeScript output layout could not be resolved."
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
async function readProjectGraph(packageRoot, agent, configPath, defaultsRootDirToConfig, compilerVersion) {
|
|
1195
|
+
const projects = [];
|
|
1196
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1197
|
+
const rootConfig = projectConfigFile(join(packageRoot, "tsconfig.json"));
|
|
1198
|
+
const visit = async (path) => {
|
|
1199
|
+
const configFile = projectConfigFile(path);
|
|
1200
|
+
if (visited.has(configFile)) return;
|
|
1201
|
+
visited.add(configFile);
|
|
1202
|
+
let shown = await runLocal(packageRoot, agent, [
|
|
1203
|
+
"tsc",
|
|
1204
|
+
"-p",
|
|
1205
|
+
configFile,
|
|
1206
|
+
"--showConfig"
|
|
1207
|
+
]);
|
|
1208
|
+
let diagnostic;
|
|
1209
|
+
if (!shown.ok && /TS18003/.test(shown.output) && pathWithin(packageRoot, configFile) !== null) {
|
|
1210
|
+
diagnostic = shown.output;
|
|
1211
|
+
shown = await showEmptyProjectConfig(packageRoot, agent, configFile, compilerVersion);
|
|
1212
|
+
}
|
|
1213
|
+
if (!shown.ok) throw new CompilerDiagnostic(shown.output, configFile, statSync(configFile, { throwIfNoEntry: false }) === void 0);
|
|
1214
|
+
const config = configSchema.parse(JSON.parse(shown.output));
|
|
1215
|
+
const project = await refreshProject(packageRoot, agent, {
|
|
1216
|
+
...diagnostic !== void 0 && { diagnostic },
|
|
1217
|
+
configFile,
|
|
1218
|
+
options: config.compilerOptions,
|
|
1219
|
+
sources: [],
|
|
1220
|
+
references: (config.references ?? []).map((reference) => projectConfigFile(resolve(dirname(configFile), reference.path))),
|
|
1221
|
+
emitRoot: dirname(configFile),
|
|
1222
|
+
external: configFile !== rootConfig && pathWithin(packageRoot, configFile) === null
|
|
1223
|
+
}, defaultsRootDirToConfig);
|
|
1224
|
+
projects.push(project);
|
|
1225
|
+
for (const reference of project.references) await visit(reference);
|
|
1226
|
+
};
|
|
1227
|
+
await visit(configPath);
|
|
1228
|
+
return projects;
|
|
1229
|
+
}
|
|
1230
|
+
async function showEmptyProjectConfig(packageRoot, agent, configFile, compilerVersion) {
|
|
1231
|
+
const config = object({ references: configSchema.shape.references }).parse(readConfig(configFile));
|
|
1232
|
+
const directory = realPathThroughExistingParent(mkdtempSync(join(tmpdir(), ".ph-preflight-")));
|
|
1233
|
+
try {
|
|
1234
|
+
const probe = join(directory, "tsconfig.json");
|
|
1235
|
+
writeFileSync(probe, JSON.stringify({
|
|
1236
|
+
extends: configFile,
|
|
1237
|
+
compilerOptions: configDirOptions(configFile, compilerVersion),
|
|
1238
|
+
files: [configFile],
|
|
1239
|
+
include: [],
|
|
1240
|
+
references: config.references?.map(({ path }) => ({ path: resolve(dirname(configFile), path) }))
|
|
1241
|
+
}));
|
|
1242
|
+
const shown = await runLocal(packageRoot, agent, [
|
|
1243
|
+
"tsc",
|
|
1244
|
+
"-p",
|
|
1245
|
+
probe,
|
|
1246
|
+
"--showConfig"
|
|
1247
|
+
]);
|
|
1248
|
+
if (!shown.ok) return shown;
|
|
1249
|
+
const resolved = configSchema.parse(JSON.parse(shown.output));
|
|
1250
|
+
const options = resolved.compilerOptions;
|
|
1251
|
+
const rebase = (path) => {
|
|
1252
|
+
const absolute = resolve(directory, path);
|
|
1253
|
+
const inProbe = pathWithin(directory, absolute);
|
|
1254
|
+
return inProbe === null ? absolute : resolve(dirname(configFile), inProbe);
|
|
1255
|
+
};
|
|
1256
|
+
for (const key of [
|
|
1257
|
+
"outDir",
|
|
1258
|
+
"declarationDir",
|
|
1259
|
+
"rootDir",
|
|
1260
|
+
"outFile",
|
|
1261
|
+
"tsBuildInfoFile"
|
|
1262
|
+
]) {
|
|
1263
|
+
const path = options[key];
|
|
1264
|
+
if (path !== void 0) options[key] = rebase(path);
|
|
1265
|
+
}
|
|
1266
|
+
return {
|
|
1267
|
+
...shown,
|
|
1268
|
+
output: JSON.stringify(resolved)
|
|
1269
|
+
};
|
|
1270
|
+
} finally {
|
|
1271
|
+
rmSync(directory, {
|
|
1272
|
+
recursive: true,
|
|
1273
|
+
force: true
|
|
1274
|
+
});
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
async function listProjectFiles(packageRoot, agent, configFile, preserveSymlinks = false) {
|
|
1278
|
+
const listed = await runLocal(packageRoot, agent, [
|
|
1279
|
+
"tsc",
|
|
1280
|
+
"-p",
|
|
1281
|
+
configFile,
|
|
1282
|
+
"--listFilesOnly",
|
|
1283
|
+
"--explainFiles",
|
|
1284
|
+
"--pretty",
|
|
1285
|
+
"false",
|
|
1286
|
+
...preserveSymlinks ? ["--preserveSymlinks", "true"] : []
|
|
1287
|
+
]);
|
|
1288
|
+
return {
|
|
1289
|
+
...listed,
|
|
1290
|
+
files: listedFiles(listed.output, packageRoot),
|
|
1291
|
+
rootFiles: explainedRoots(listed.output, packageRoot)
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
async function refreshProject(packageRoot, agent, project, defaultsRootDirToConfig) {
|
|
1295
|
+
const listed = await listProjectFiles(packageRoot, agent, project.configFile);
|
|
1296
|
+
const { files, rootFiles } = listed;
|
|
1297
|
+
if (!listed.ok && files.length === 0 && !/TS18003/.test(listed.output)) throw new CompilerDiagnostic(listed.output, project.configFile, false);
|
|
1298
|
+
const roots = new Set(rootFiles.map((file) => realPathThroughExistingParent(file)));
|
|
1299
|
+
let sources = files.filter((file) => (/\.[cm]?[jt]sx?$/i.test(file) || project.options.resolveJsonModule === true && /\.json$/i.test(file)) && !/\.d\.[cm]?ts$/i.test(file) && (roots.has(realPathThroughExistingParent(file)) || !toPosixPath(file).includes("/node_modules/")));
|
|
1300
|
+
if (sources.some((file) => !roots.has(realPathThroughExistingParent(file)) && pathWithin(packageRoot, realPathThroughExistingParent(file)) === null)) {
|
|
1301
|
+
const spellings = (await listProjectFiles(packageRoot, agent, project.configFile, true)).files;
|
|
1302
|
+
if (spellings.length === 0) throw new Error("tsc could not classify external library inputs without writing them.");
|
|
1303
|
+
const local = new Set(spellings.filter((file) => roots.has(realPathThroughExistingParent(file)) || !toPosixPath(file).includes("/node_modules/")).map((path) => realPathThroughExistingParent(path)));
|
|
1304
|
+
const libraries = new Set(spellings.filter((file) => toPosixPath(file).includes("/node_modules/")).map((path) => realPathThroughExistingParent(path)));
|
|
1305
|
+
sources = sources.filter((file) => !libraries.has(realPathThroughExistingParent(file)) || local.has(realPathThroughExistingParent(file)));
|
|
1306
|
+
}
|
|
1307
|
+
return {
|
|
1308
|
+
...project,
|
|
1309
|
+
.../TS18003/.test(listed.output) && { diagnostic: listed.output },
|
|
1310
|
+
sources,
|
|
1311
|
+
emitRoot: resolve(dirname(project.configFile), project.options.rootDir ?? (project.options.composite || defaultsRootDirToConfig ? "." : commonSourceDirectory(sources, dirname(project.configFile))))
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
function checkedCompilePlan(packageRoot, projects, emitsBuildInfoInBuildMode) {
|
|
1315
|
+
const directories = /* @__PURE__ */ new Set();
|
|
1316
|
+
const files = /* @__PURE__ */ new Set();
|
|
1317
|
+
for (const project of projects) {
|
|
1318
|
+
if (project.external) continue;
|
|
1319
|
+
if (!project.options.noEmit) for (const path of outputDirectories$1(project.options, dirname(project.configFile))) {
|
|
1320
|
+
const target = realPathThroughExistingParent(path);
|
|
1321
|
+
if (pathWithin(packageRoot, target) === null) throw new Error(`tsc would write to ${JSON.stringify(path)} outside the package.`);
|
|
1322
|
+
if (!project.sources.some((file) => pathWithin(target, realPathThroughExistingParent(file)) !== null)) {
|
|
1323
|
+
if (pathWithin(packageRoot, path) !== null) directories.add(toPosixPath(relative(packageRoot, path)));
|
|
1324
|
+
directories.add(toPosixPath(relative(packageRoot, target)));
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
for (const path of outputFiles(project, emitsBuildInfoInBuildMode)) {
|
|
1328
|
+
if (/\.json$/i.test(path) && project.sources.includes(path)) continue;
|
|
1329
|
+
const target = realPathThroughExistingParent(path);
|
|
1330
|
+
if (pathWithin(packageRoot, target) === null) throw new Error(`tsc would write to ${JSON.stringify(path)} outside the package.`);
|
|
1331
|
+
if (pathWithin(packageRoot, path) !== null) files.add(toPosixPath(relative(packageRoot, path)));
|
|
1332
|
+
files.add(toPosixPath(relative(packageRoot, target)));
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
const root = projects.at(0);
|
|
1336
|
+
const references = projects.slice(1);
|
|
1337
|
+
if (root === void 0) throw new Error("The root TypeScript project could not be resolved.");
|
|
1338
|
+
return {
|
|
1339
|
+
...root.diagnostic !== void 0 && { preflightTypeError: root.diagnostic },
|
|
1340
|
+
projects: [root, ...references],
|
|
1341
|
+
outputs: {
|
|
1342
|
+
directories: [...directories].sort(),
|
|
1343
|
+
files: [...files].sort()
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
//#endregion
|
|
1348
|
+
//#region src/services/package-build/staging/inventory.ts
|
|
1349
|
+
const optionalString = (value) => typeof value === "string" ? value : void 0;
|
|
1350
|
+
const optionalBoolean = (value) => typeof value === "boolean" ? value : void 0;
|
|
1351
|
+
const strings = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : void 0;
|
|
1352
|
+
/** The config in `tsc --showConfig` output, or undefined when it is not JSON. */
|
|
1353
|
+
function parseShownConfig(text) {
|
|
1354
|
+
let shown;
|
|
1355
|
+
try {
|
|
1356
|
+
shown = JSON.parse(text);
|
|
1357
|
+
} catch {
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
if (typeof shown !== "object" || shown === null) return void 0;
|
|
1361
|
+
const { compilerOptions, exclude, references } = shown;
|
|
1362
|
+
return {
|
|
1363
|
+
options: emitOptions(compilerOptions),
|
|
1364
|
+
exclude: strings(exclude),
|
|
1365
|
+
references: Array.isArray(references) ? references.flatMap((reference) => {
|
|
1366
|
+
const path = reference?.path;
|
|
1367
|
+
return typeof path === "string" ? [path] : [];
|
|
1368
|
+
}) : []
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
function emitOptions(options) {
|
|
1372
|
+
if (typeof options !== "object" || options === null) return {};
|
|
1373
|
+
const record = options;
|
|
1374
|
+
return {
|
|
1375
|
+
declaration: optionalBoolean(record.declaration),
|
|
1376
|
+
composite: optionalBoolean(record.composite),
|
|
1377
|
+
incremental: optionalBoolean(record.incremental),
|
|
1378
|
+
declarationDir: optionalString(record.declarationDir),
|
|
1379
|
+
outDir: optionalString(record.outDir),
|
|
1380
|
+
outFile: optionalString(record.outFile),
|
|
1381
|
+
rootDir: optionalString(record.rootDir),
|
|
1382
|
+
tsBuildInfoFile: optionalString(record.tsBuildInfoFile),
|
|
1383
|
+
noEmit: optionalBoolean(record.noEmit),
|
|
1384
|
+
emitDeclarationOnly: optionalBoolean(record.emitDeclarationOnly),
|
|
1385
|
+
sourceMap: optionalBoolean(record.sourceMap),
|
|
1386
|
+
declarationMap: optionalBoolean(record.declarationMap)
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* What the root project's tsc writes inside the package, for the build to
|
|
1391
|
+
* snapshot and restore: its build info first, then the files `outFile`
|
|
1392
|
+
* writes, then its declaration and output directories, the build's own
|
|
1393
|
+
* output directory or one holding it included. A directory holding
|
|
1394
|
+
* `buildDirectory`, where the build keeps its runs and their snapshots, is
|
|
1395
|
+
* left out and unprotected, as without staging: a snapshot of it would copy
|
|
1396
|
+
* itself. This says what to protect, not what to carry into the stage.
|
|
1397
|
+
*/
|
|
1398
|
+
function compilerOutputInventory(options, at) {
|
|
1399
|
+
const inPackage = (path) => Boolean(pathWithin(at.packageRoot, path));
|
|
1400
|
+
const directories = outputDirectories$1(options, dirname(at.configFile)).filter(inPackage).filter((dir) => pathWithin(dir, at.buildDirectory) === null);
|
|
1401
|
+
return [
|
|
1402
|
+
...[buildInfoFile(options, at.configFile)].filter(inPackage).map((path) => ({
|
|
1403
|
+
path,
|
|
1404
|
+
kind: "build-info"
|
|
1405
|
+
})),
|
|
1406
|
+
...outFileOutputs(options, at.configFile).filter(inPackage).map((path) => ({
|
|
1407
|
+
path,
|
|
1408
|
+
kind: "file"
|
|
1409
|
+
})),
|
|
1410
|
+
...[...new Set(directories)].map((path) => ({
|
|
1411
|
+
path,
|
|
1412
|
+
kind: "directory"
|
|
1413
|
+
}))
|
|
1414
|
+
];
|
|
1415
|
+
}
|
|
1416
|
+
//#endregion
|
|
1417
|
+
//#region src/services/package-build/staging/compiler.ts
|
|
1418
|
+
function writesBesideSources(options) {
|
|
1419
|
+
if (options.noEmit || options.outFile !== void 0) return false;
|
|
1420
|
+
if (options.outDir !== void 0) return false;
|
|
1421
|
+
const declares = options.declaration === true || options.composite === true;
|
|
1422
|
+
return !options.emitDeclarationOnly || declares && !options.declarationDir;
|
|
1423
|
+
}
|
|
1424
|
+
const redirectable = ({ references, options }) => references.length === 0 && Boolean(options.incremental || options.composite || options.tsBuildInfoFile);
|
|
1425
|
+
async function compilerOutputs(config, at) {
|
|
1426
|
+
const root = compilerOutputInventory(config.options, at);
|
|
1427
|
+
const real = (path) => realPathThroughExistingParent(path);
|
|
1428
|
+
const packageIdentity = real(at.packageRoot);
|
|
1429
|
+
const inPackage = (path) => pathWithin(packageIdentity, real(path)) !== null;
|
|
1430
|
+
const referencesInPackage = config.references.some((reference) => inPackage(resolve(dirname(at.configFile), reference)));
|
|
1431
|
+
const holdsOutput = (dir) => pathWithin(real(dir), at.output) !== null;
|
|
1432
|
+
const protectsOutput = root.some(({ kind, path }) => kind === "directory" && holdsOutput(path) && !(redirectable(config) && real(path) === at.output));
|
|
1433
|
+
if (!referencesInPackage && !writesBesideSources(config.options) && !protectsOutput) return root;
|
|
1434
|
+
const prepared = await prepareCompile(at.packageRoot, at.agent);
|
|
1435
|
+
if (!prepared.ok) return root;
|
|
1436
|
+
const { directories, files } = prepared.plan.outputs;
|
|
1437
|
+
const absolute = (path) => resolve(at.packageRoot, path);
|
|
1438
|
+
const owned = (path) => inPackage(path) && pathWithin(path, at.buildDirectory) === null;
|
|
1439
|
+
const dirs = directories.map(absolute).filter((dir) => owned(dir) && !holdsOutput(dir));
|
|
1440
|
+
return [...files.map(absolute).filter((file) => owned(file) && !dirs.some((dir) => pathWithin(dir, file) !== null)).map((path) => ({
|
|
1441
|
+
path,
|
|
1442
|
+
kind: path.endsWith(".tsbuildinfo") ? "build-info" : "file"
|
|
1443
|
+
})).sort((a, b) => Number(b.kind === "build-info") - Number(a.kind === "build-info")), ...dirs.map((path) => ({
|
|
1444
|
+
path,
|
|
1445
|
+
kind: "directory"
|
|
1446
|
+
}))];
|
|
1447
|
+
}
|
|
1448
|
+
function redirectRootProject(config, at) {
|
|
1449
|
+
if (!redirectable(config)) return void 0;
|
|
1450
|
+
const { options } = config;
|
|
1451
|
+
const configDir = dirname(at.configFile);
|
|
1452
|
+
const real = (path) => realPathThroughExistingParent(path);
|
|
1453
|
+
const inOutput = (path) => pathWithin(at.output, real(path));
|
|
1454
|
+
const compilerOptions = {};
|
|
1455
|
+
const staged = [];
|
|
1456
|
+
for (const key of [
|
|
1457
|
+
"declarationDir",
|
|
1458
|
+
"outDir",
|
|
1459
|
+
"outFile"
|
|
1460
|
+
]) {
|
|
1461
|
+
const value = options[key];
|
|
1462
|
+
if (value === void 0 || key === "outFile" && options.noEmit) continue;
|
|
1463
|
+
const rel = inOutput(resolve(configDir, value));
|
|
1464
|
+
if (rel === null) continue;
|
|
1465
|
+
compilerOptions[key] = join(at.stage, rel);
|
|
1466
|
+
staged.push(...(key === "outFile" ? outFileOutputs(options, at.configFile) : [resolve(configDir, value)]).map(real));
|
|
1467
|
+
}
|
|
1468
|
+
const target = buildInfoFile(options, at.configFile);
|
|
1469
|
+
const rel = inOutput(target);
|
|
1470
|
+
let pendingBuildInfo;
|
|
1471
|
+
if (rel !== null) {
|
|
1472
|
+
compilerOptions.tsBuildInfoFile = join(at.stage, rel);
|
|
1473
|
+
staged.push(real(target));
|
|
1474
|
+
} else if (pathWithin(at.packageRoot, target) !== null && !lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
1475
|
+
pendingBuildInfo = {
|
|
1476
|
+
path: at.pending(target),
|
|
1477
|
+
target
|
|
1478
|
+
};
|
|
1479
|
+
compilerOptions.tsBuildInfoFile = pendingBuildInfo.path;
|
|
1480
|
+
staged.push(real(target));
|
|
1481
|
+
} else compilerOptions.tsBuildInfoFile = target;
|
|
1482
|
+
return {
|
|
1483
|
+
compilerOptions,
|
|
1484
|
+
exclude: config.exclude,
|
|
1485
|
+
pendingBuildInfo,
|
|
1486
|
+
staged
|
|
1487
|
+
};
|
|
1488
|
+
}
|
|
1489
|
+
//#endregion
|
|
1490
|
+
//#region src/services/package-build/staging/session.ts
|
|
1491
|
+
const isUnreadable = (error) => {
|
|
1492
|
+
const code = error?.code;
|
|
1493
|
+
return code === "EACCES" || code === "EPERM";
|
|
1494
|
+
};
|
|
1495
|
+
/** `path` is `dir` or holds it. */
|
|
1496
|
+
const isOrHolds = (path, dir) => pathWithin(path, dir) !== null;
|
|
1497
|
+
/** The outermost directory of `path`, inside the package, that does not exist. */
|
|
1498
|
+
function outermostMissing(packageRoot, path) {
|
|
1499
|
+
let missing = path;
|
|
1500
|
+
for (let parent = dirname(path); pathWithin(packageRoot, parent) && !exists(parent); parent = dirname(parent)) missing = parent;
|
|
1501
|
+
return missing;
|
|
1502
|
+
}
|
|
1503
|
+
/** A path as messages name it: from the package root, which is named so. */
|
|
1504
|
+
const shownPath = (packageRoot, path) => toJournalPath(packageRoot, path) || "the package root";
|
|
1505
|
+
const scratchBeside = (path, kind, runId) => join(dirname(path), `.${basename(path)}.ph-${kind}-${runId}`);
|
|
1506
|
+
/**
|
|
1507
|
+
* One `ph build` of one package: the output is written to a stage beside the
|
|
1508
|
+
* output directory and replaces it only on commit. Until then the previous
|
|
1509
|
+
* output and the compiler outputs tsc rewrote can be put back, by `rollback`
|
|
1510
|
+
* in this process or, after a crash, by the next build.
|
|
1511
|
+
*/
|
|
1512
|
+
var StagedBuildSession = class StagedBuildSession {
|
|
1513
|
+
runId;
|
|
1514
|
+
packageRoot;
|
|
1515
|
+
output;
|
|
1516
|
+
writesPackageDist;
|
|
1517
|
+
runDir;
|
|
1518
|
+
paths;
|
|
1519
|
+
lock;
|
|
1520
|
+
journal;
|
|
1521
|
+
status = "open";
|
|
1522
|
+
stoppedBy;
|
|
1523
|
+
seeded = false;
|
|
1524
|
+
compilerWritten = false;
|
|
1525
|
+
restored = false;
|
|
1526
|
+
redirected = [];
|
|
1527
|
+
cleanedEntries;
|
|
1528
|
+
linkCleanedEntries;
|
|
1529
|
+
constructor(fields) {
|
|
1530
|
+
this.runId = fields.runId;
|
|
1531
|
+
this.packageRoot = fields.packageRoot;
|
|
1532
|
+
this.output = fields.output;
|
|
1533
|
+
this.writesPackageDist = fields.writesPackageDist;
|
|
1534
|
+
this.cleanedEntries = fields.cleanedEntries;
|
|
1535
|
+
this.linkCleanedEntries = fields.linkCleanedEntries;
|
|
1536
|
+
this.runDir = fields.runDir;
|
|
1537
|
+
this.lock = fields.lock;
|
|
1538
|
+
this.journal = fields.journal;
|
|
1539
|
+
this.paths = runPaths(fields.packageRoot, fields.runDir, fields.journal);
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* Starts a run under `lock`, which the caller took and recovered stale
|
|
1543
|
+
* runs under; the caller still releases it when this throws. The stage
|
|
1544
|
+
* sits beside `logical`, the output as given, so the paths the bundlers
|
|
1545
|
+
* record from it are the ones an unstaged build records.
|
|
1546
|
+
*/
|
|
1547
|
+
static async open(options) {
|
|
1548
|
+
const { packageRoot, logical, runId } = options;
|
|
1549
|
+
const runDir = join(packageRoot, RUNS_DIRECTORY, runId);
|
|
1550
|
+
try {
|
|
1551
|
+
const beside = (kind) => scratchBeside(logical, kind, runId);
|
|
1552
|
+
const journal = {
|
|
1553
|
+
format: 1,
|
|
1554
|
+
runId,
|
|
1555
|
+
pid: process.pid,
|
|
1556
|
+
state: "building",
|
|
1557
|
+
undo: null,
|
|
1558
|
+
output: toJournalPath(packageRoot, logical),
|
|
1559
|
+
stage: toJournalPath(packageRoot, beside("stage")),
|
|
1560
|
+
retired: toJournalPath(packageRoot, beside("old")),
|
|
1561
|
+
compiler: null
|
|
1562
|
+
};
|
|
1563
|
+
await creating(BUILD_DIRECTORY, () => {
|
|
1564
|
+
mkdirSync(runDir, { recursive: true });
|
|
1565
|
+
writeJournal(runDir, journal);
|
|
1566
|
+
});
|
|
1567
|
+
await creating(shownPath(packageRoot, dirname(logical)), () => mkdirSync(beside("stage"), { recursive: true }));
|
|
1568
|
+
return new StagedBuildSession({
|
|
1569
|
+
...options,
|
|
1570
|
+
runDir,
|
|
1571
|
+
journal
|
|
1572
|
+
});
|
|
1573
|
+
} catch (error) {
|
|
1574
|
+
removeTree(runDir);
|
|
1575
|
+
throw error;
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
assertOpen() {
|
|
1579
|
+
if (this.status !== "open") throw new Error("The build was stopped before it finished.");
|
|
1580
|
+
}
|
|
1581
|
+
record(changes) {
|
|
1582
|
+
this.journal = {
|
|
1583
|
+
...this.journal,
|
|
1584
|
+
...changes
|
|
1585
|
+
};
|
|
1586
|
+
writeJournal(this.runDir, this.journal);
|
|
1587
|
+
}
|
|
1588
|
+
setState(state) {
|
|
1589
|
+
this.record({ state });
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* Compiler outputs strictly inside the output directory, relative to it:
|
|
1593
|
+
* tsc rewrote them in the real output, so the stage leaves them out when
|
|
1594
|
+
* it is seeded and takes them fresh at commit. A protected directory that
|
|
1595
|
+
* is the output or holds it is not one: it holds the bundles too.
|
|
1596
|
+
*/
|
|
1597
|
+
compilerOutputsInOutput() {
|
|
1598
|
+
return (this.journal.compiler ?? []).flatMap(({ path }) => {
|
|
1599
|
+
const rel = pathWithin(this.output, fromJournalPath(this.packageRoot, path));
|
|
1600
|
+
return rel ? [rel] : [];
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* The stage directory every output write targets. The first call seeds it
|
|
1605
|
+
* with the current output, minus what tsc writes afresh. With
|
|
1606
|
+
* `linkCleanedEntries`, the entries a step cleans are seeded by hard link,
|
|
1607
|
+
* since it unlinks their files before it writes and says so in the same
|
|
1608
|
+
* words as on the output; the rest, and otherwise everything, by clone.
|
|
1609
|
+
*/
|
|
1610
|
+
stage() {
|
|
1611
|
+
this.assertOpen();
|
|
1612
|
+
const { stage, output } = this.paths;
|
|
1613
|
+
if (this.seeded) return stage;
|
|
1614
|
+
removeTree(stage);
|
|
1615
|
+
if (exists(output)) {
|
|
1616
|
+
const skipped = new Set(this.compilerWritten ? [] : this.compilerOutputsInOutput().map((rel) => join(output, rel)));
|
|
1617
|
+
const keep = (source) => !skipped.has(source);
|
|
1618
|
+
const linked = (this.linkCleanedEntries ? this.cleanedEntries : []).filter((entry) => {
|
|
1619
|
+
const real = join(this.output, entry);
|
|
1620
|
+
return !this.redirected.some((path) => isOrHolds(real, path) || isOrHolds(path, real));
|
|
1621
|
+
}).map((entry) => join(output, entry)).filter((dir) => keep(dir) && lstatSync(dir, { throwIfNoEntry: false })?.isDirectory());
|
|
1622
|
+
cloneTree(output, stage, (source) => keep(source) && !linked.includes(source));
|
|
1623
|
+
for (const dir of linked) linkTree(dir, join(stage, basename(dir)), keep);
|
|
1624
|
+
} else mkdirSync(stage);
|
|
1625
|
+
this.seeded = true;
|
|
1626
|
+
return stage;
|
|
1627
|
+
}
|
|
1628
|
+
async prepareCompiler(compiler) {
|
|
1629
|
+
this.assertOpen();
|
|
1630
|
+
const redirect = redirectRootProject(compiler.config, {
|
|
1631
|
+
configFile: compiler.configFile,
|
|
1632
|
+
packageRoot: this.packageRoot,
|
|
1633
|
+
output: this.output,
|
|
1634
|
+
stage: this.paths.stage,
|
|
1635
|
+
pending: (target) => scratchBeside(target, "stage", this.runId)
|
|
1636
|
+
});
|
|
1637
|
+
let config;
|
|
1638
|
+
let staged = [];
|
|
1639
|
+
if (redirect) {
|
|
1640
|
+
config = await this.writeCompilerConfig(compiler.configFile, redirect);
|
|
1641
|
+
if (config) staged = redirect.staged;
|
|
1642
|
+
}
|
|
1643
|
+
const real = (path) => realPathThroughExistingParent(path);
|
|
1644
|
+
this.protectCompilerOutputs(compiler.outputs.filter(({ path }) => !staged.some((dir) => isOrHolds(dir, real(path)))));
|
|
1645
|
+
if (!config) return void 0;
|
|
1646
|
+
this.redirected = staged;
|
|
1647
|
+
this.stage();
|
|
1648
|
+
return config;
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Writes the config that sends the root project's outputs into the stage,
|
|
1652
|
+
* beside the package's so `${configDir}` and its relative paths mean the
|
|
1653
|
+
* same, with the package config's modification time so tsc finds the
|
|
1654
|
+
* project up to date when it would. The pending build info starts as a
|
|
1655
|
+
* copy of the real one. Undefined when the package does not let the run
|
|
1656
|
+
* write them: tsc then writes in place.
|
|
1657
|
+
*/
|
|
1658
|
+
async writeCompilerConfig(configFile, redirect) {
|
|
1659
|
+
const generated = join(dirname(configFile), `.${basename(configFile, extname(configFile))}.ph-stage-${this.runId}.json`);
|
|
1660
|
+
const pending = redirect.pendingBuildInfo;
|
|
1661
|
+
const recorded = (path) => toJournalPath(this.packageRoot, path);
|
|
1662
|
+
this.record({
|
|
1663
|
+
generatedConfig: recorded(generated),
|
|
1664
|
+
...pending && { pendingBuildInfo: {
|
|
1665
|
+
path: recorded(pending.path),
|
|
1666
|
+
target: recorded(pending.target)
|
|
1667
|
+
} }
|
|
1668
|
+
});
|
|
1669
|
+
try {
|
|
1670
|
+
await creating(shownPath(this.packageRoot, dirname(configFile)), () => {
|
|
1671
|
+
writeFileSync(generated, `${JSON.stringify({
|
|
1672
|
+
extends: `./${basename(configFile)}`,
|
|
1673
|
+
compilerOptions: redirect.compilerOptions,
|
|
1674
|
+
...redirect.exclude && { exclude: redirect.exclude }
|
|
1675
|
+
}, null, 2)}\n`);
|
|
1676
|
+
const { atime, mtime } = statSync(configFile);
|
|
1677
|
+
utimesSync(generated, atime, mtime);
|
|
1678
|
+
if (pending && exists(pending.target)) cloneTree(pending.target, pending.path);
|
|
1679
|
+
});
|
|
1680
|
+
return generated;
|
|
1681
|
+
} catch (error) {
|
|
1682
|
+
if (!(error instanceof CannotStage)) throw error;
|
|
1683
|
+
removeTree(generated);
|
|
1684
|
+
if (pending) removeTree(pending.path);
|
|
1685
|
+
this.record({
|
|
1686
|
+
generatedConfig: void 0,
|
|
1687
|
+
pendingBuildInfo: void 0
|
|
1688
|
+
});
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
/**
|
|
1693
|
+
* Copies what tsc is about to rewrite into the run, or notes it absent, so
|
|
1694
|
+
* a build that does not finish puts it back. Call before tsc runs. An
|
|
1695
|
+
* output that is or holds `.ph/build` or this run, by real path, is left
|
|
1696
|
+
* unprotected, as without staging: a copy of it would copy itself. So is
|
|
1697
|
+
* one holding something a copy cannot take: a FIFO, socket or device, or
|
|
1698
|
+
* an entry this process cannot read. The copy's directories are made
|
|
1699
|
+
* owner-writable, so the run can always be removed; the journal keeps
|
|
1700
|
+
* their modes for a restore.
|
|
1701
|
+
*/
|
|
1702
|
+
protectCompilerOutputs(outputs) {
|
|
1703
|
+
const real = (path) => realPathThroughExistingParent(path);
|
|
1704
|
+
const control = [real(join(this.packageRoot, BUILD_DIRECTORY)), real(this.runDir)];
|
|
1705
|
+
const snapshots = [...this.journal.compiler ?? []];
|
|
1706
|
+
for (const { path, kind } of outputs) {
|
|
1707
|
+
const target = real(path);
|
|
1708
|
+
if (control.some((dir) => isOrHolds(target, dir))) continue;
|
|
1709
|
+
const recorded = toJournalPath(this.packageRoot, target);
|
|
1710
|
+
if (snapshots.some((snapshot) => snapshot.path === recorded)) continue;
|
|
1711
|
+
if (exists(target)) {
|
|
1712
|
+
const copy = `compiler/${snapshots.length}`;
|
|
1713
|
+
const output = basename(this.paths.output);
|
|
1714
|
+
const snapshot = join(this.runDir, copy);
|
|
1715
|
+
const keep = (source) => !isScratchOf(output, basename(source));
|
|
1716
|
+
if (unstageableEntryIn(target, keep) !== void 0) continue;
|
|
1717
|
+
try {
|
|
1718
|
+
cloneTree(target, snapshot, keep);
|
|
1719
|
+
} catch (error) {
|
|
1720
|
+
if (!isUnreadable(error)) throw error;
|
|
1721
|
+
removeTree(snapshot);
|
|
1722
|
+
continue;
|
|
1723
|
+
}
|
|
1724
|
+
const modes = openDirectories(snapshot);
|
|
1725
|
+
snapshots.push({
|
|
1726
|
+
path: recorded,
|
|
1727
|
+
kind,
|
|
1728
|
+
copy,
|
|
1729
|
+
created: null,
|
|
1730
|
+
...modes.length > 0 && { modes }
|
|
1731
|
+
});
|
|
1732
|
+
} else {
|
|
1733
|
+
const missing = outermostMissing(this.packageRoot, target);
|
|
1734
|
+
const created = missing === target ? null : toJournalPath(this.packageRoot, missing);
|
|
1735
|
+
snapshots.push({
|
|
1736
|
+
path: recorded,
|
|
1737
|
+
kind,
|
|
1738
|
+
copy: null,
|
|
1739
|
+
created
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
const digest = snapshots.length > 0 ? outputDigest(this.packageRoot, this.paths.output, snapshots) : void 0;
|
|
1744
|
+
this.record({
|
|
1745
|
+
compiler: snapshots,
|
|
1746
|
+
...digest !== void 0 && { outputDigest: digest }
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
/**
|
|
1750
|
+
* tsc wrote into the real output directory; the stage takes its fresh
|
|
1751
|
+
* files now, before any bundle step, so a step that cleans or rewrites an
|
|
1752
|
+
* entry treats them as it would in the output.
|
|
1753
|
+
*/
|
|
1754
|
+
compilerOutputsWritten() {
|
|
1755
|
+
this.assertOpen();
|
|
1756
|
+
this.compilerWritten = true;
|
|
1757
|
+
const generated = this.journal.generatedConfig;
|
|
1758
|
+
if (generated) removeTree(fromJournalPath(this.packageRoot, generated));
|
|
1759
|
+
if (this.seeded) this.carryOverCompilerOutputs(this.paths.stage);
|
|
1760
|
+
}
|
|
1761
|
+
carryOverCompilerOutputs(stage) {
|
|
1762
|
+
for (const rel of this.compilerOutputsInOutput()) {
|
|
1763
|
+
const target = join(stage, rel);
|
|
1764
|
+
removeTree(target);
|
|
1765
|
+
const source = join(this.paths.output, rel);
|
|
1766
|
+
if (exists(source)) {
|
|
1767
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
1768
|
+
cloneTree(source, target);
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
warnNotAtomic() {
|
|
1773
|
+
const shown = toJournalPath(this.packageRoot, this.paths.output);
|
|
1774
|
+
console.warn(`⚠ Another process holds files in ${shown}, so ${shown} was replaced entry by entry instead of in one rename; while that ran, it held parts of both builds.`);
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Replaces the output with the stage: the output moves aside, the stage
|
|
1778
|
+
* takes its place, the old tree goes. The journal records each move first.
|
|
1779
|
+
* Synchronous, so no signal handler runs in between. The lock stays held
|
|
1780
|
+
* until `close`.
|
|
1781
|
+
*/
|
|
1782
|
+
commit() {
|
|
1783
|
+
const stage = this.stage();
|
|
1784
|
+
const { output, retired } = this.paths;
|
|
1785
|
+
try {
|
|
1786
|
+
this.setState("retiring");
|
|
1787
|
+
let entryByEntry = false;
|
|
1788
|
+
if (exists(output)) try {
|
|
1789
|
+
renamePatiently(output, retired);
|
|
1790
|
+
} catch (error) {
|
|
1791
|
+
if (!isHeldOpen(error)) throw error;
|
|
1792
|
+
entryByEntry = true;
|
|
1793
|
+
mkdirSync(retired);
|
|
1794
|
+
moveEntries(output, retired);
|
|
1795
|
+
}
|
|
1796
|
+
this.setState("installing");
|
|
1797
|
+
if (exists(output)) {
|
|
1798
|
+
moveEntries(stage, output);
|
|
1799
|
+
removeTree(stage);
|
|
1800
|
+
} else try {
|
|
1801
|
+
renamePatiently(stage, output);
|
|
1802
|
+
} catch (error) {
|
|
1803
|
+
if (!isHeldOpen(error)) throw error;
|
|
1804
|
+
entryByEntry = true;
|
|
1805
|
+
mkdirSync(output);
|
|
1806
|
+
moveEntries(stage, output);
|
|
1807
|
+
removeTree(stage);
|
|
1808
|
+
}
|
|
1809
|
+
installBuildInfo(this.packageRoot, this.journal.pendingBuildInfo);
|
|
1810
|
+
this.status = "committed";
|
|
1811
|
+
if (entryByEntry) this.warnNotAtomic();
|
|
1812
|
+
} catch (error) {
|
|
1813
|
+
this.rollback();
|
|
1814
|
+
throw error;
|
|
1815
|
+
}
|
|
1816
|
+
try {
|
|
1817
|
+
this.setState("committed");
|
|
1818
|
+
removeTree(retired);
|
|
1819
|
+
removeTree(this.runDir);
|
|
1820
|
+
} catch (error) {
|
|
1821
|
+
console.warn(`⚠ The build finished, but its scratch files were not all removed (${error instanceof Error ? error.message : String(error)}); the next build removes them.`);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
/**
|
|
1825
|
+
* Releases the lock a commit keeps, so steps that read the committed
|
|
1826
|
+
* output finish before another build replaces it, and drops the run a
|
|
1827
|
+
* rollback restored from. Idempotent.
|
|
1828
|
+
*/
|
|
1829
|
+
close() {
|
|
1830
|
+
try {
|
|
1831
|
+
if (this.status === "rolled-back" && this.restored) removeTree(this.runDir);
|
|
1832
|
+
} finally {
|
|
1833
|
+
this.lock.release();
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
releaseLock() {
|
|
1837
|
+
this.lock.release();
|
|
1838
|
+
}
|
|
1839
|
+
/**
|
|
1840
|
+
* Puts the previous output and compiler outputs back. Synchronous, so a
|
|
1841
|
+
* signal handler can call it; a no-op after commit. The run and its
|
|
1842
|
+
* snapshot stay until `close`, so a call after a step still running at
|
|
1843
|
+
* the first one settles restores again, undoing what that step wrote
|
|
1844
|
+
* since. A restore that failed is left to the next build. The lock stays
|
|
1845
|
+
* held until `close`.
|
|
1846
|
+
*/
|
|
1847
|
+
rollback() {
|
|
1848
|
+
if (this.status === "committed") return;
|
|
1849
|
+
if (this.status === "rolled-back" && !this.restored) return;
|
|
1850
|
+
this.status = "rolled-back";
|
|
1851
|
+
try {
|
|
1852
|
+
rollBack(this.paths, this.journal);
|
|
1853
|
+
this.journal = {
|
|
1854
|
+
...this.journal,
|
|
1855
|
+
state: "rolling-back",
|
|
1856
|
+
undo: "stage"
|
|
1857
|
+
};
|
|
1858
|
+
this.restored = true;
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
this.restored = false;
|
|
1861
|
+
console.error(`✘ The previous output could not be restored (${error instanceof Error ? error.message : String(error)}); the next build restores it.`);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
stops = /* @__PURE__ */ new Set();
|
|
1865
|
+
cancel(signal) {
|
|
1866
|
+
this.stoppedBy ??= signal;
|
|
1867
|
+
for (const stop of [...this.stops]) stop();
|
|
1868
|
+
}
|
|
1869
|
+
onCancel(stop) {
|
|
1870
|
+
this.stops.add(stop);
|
|
1871
|
+
return () => this.stops.delete(stop);
|
|
1872
|
+
}
|
|
1873
|
+
/** The signal `cancel` was called with, if it was. */
|
|
1874
|
+
stopped() {
|
|
1875
|
+
return this.stoppedBy;
|
|
1876
|
+
}
|
|
1877
|
+
};
|
|
1878
|
+
//#endregion
|
|
1879
|
+
//#region src/services/package-build/staging/open.ts
|
|
1880
|
+
/**
|
|
1881
|
+
* The first symlink among the output and its parents inside the package:
|
|
1882
|
+
* a stage beside its target would change the paths the bundlers record.
|
|
1883
|
+
*/
|
|
1884
|
+
function symlinkOnPath(packageRoot, output) {
|
|
1885
|
+
const root = realPathThroughExistingParent(packageRoot);
|
|
1886
|
+
for (let dir = output;; dir = dirname(dir)) {
|
|
1887
|
+
if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) return dir;
|
|
1888
|
+
const parent = realPathThroughExistingParent(dirname(dir));
|
|
1889
|
+
if (parent === root || pathWithin(root, parent) === null) return;
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* The output is a mount point, or otherwise on another filesystem than the
|
|
1894
|
+
* directory beside it: the stage's rename cannot replace it.
|
|
1895
|
+
*/
|
|
1896
|
+
function onAnotherFilesystem(output) {
|
|
1897
|
+
const dev = statSync(output, { throwIfNoEntry: false })?.dev;
|
|
1898
|
+
return dev !== void 0 && dev !== statSync(dirname(output)).dev;
|
|
1899
|
+
}
|
|
1900
|
+
function linkIntoOutput(logical, output, stage) {
|
|
1901
|
+
const visit = (dir) => {
|
|
1902
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
1903
|
+
const path = join(dir, entry.name);
|
|
1904
|
+
if (entry.isDirectory()) {
|
|
1905
|
+
const found = visit(path);
|
|
1906
|
+
if (found) return found;
|
|
1907
|
+
continue;
|
|
1908
|
+
}
|
|
1909
|
+
if (!entry.isSymbolicLink()) continue;
|
|
1910
|
+
const target = readlinkSync(path);
|
|
1911
|
+
const copied = isAbsolute(target) ? target : resolve(stage, relative(logical, dirname(path)), target);
|
|
1912
|
+
if (pathWithin(logical, copied) !== null) return path;
|
|
1913
|
+
if (pathWithin(output, copied) !== null) return path;
|
|
1914
|
+
}
|
|
1915
|
+
};
|
|
1916
|
+
return lstatSync(logical, { throwIfNoEntry: false })?.isDirectory() ? visit(logical) : void 0;
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* Writes the output in place, as builds did before staging: no stage or
|
|
1920
|
+
* snapshot, and nothing to commit or roll back. It holds the package's lock
|
|
1921
|
+
* until `close` when `.ph/build` can hold one. A stop signal does not stop
|
|
1922
|
+
* it, as it did not stop an unstaged build.
|
|
1923
|
+
*/
|
|
1924
|
+
var InPlaceSession = class {
|
|
1925
|
+
output;
|
|
1926
|
+
logical;
|
|
1927
|
+
writesPackageDist;
|
|
1928
|
+
lock;
|
|
1929
|
+
constructor(output, logical, writesPackageDist, lock) {
|
|
1930
|
+
this.output = output;
|
|
1931
|
+
this.logical = logical;
|
|
1932
|
+
this.writesPackageDist = writesPackageDist;
|
|
1933
|
+
this.lock = lock;
|
|
1934
|
+
}
|
|
1935
|
+
stage() {
|
|
1936
|
+
return this.logical;
|
|
1937
|
+
}
|
|
1938
|
+
prepareCompiler() {
|
|
1939
|
+
return Promise.resolve(void 0);
|
|
1940
|
+
}
|
|
1941
|
+
compilerOutputsWritten() {}
|
|
1942
|
+
commit() {}
|
|
1943
|
+
close() {
|
|
1944
|
+
this.lock?.release();
|
|
1945
|
+
}
|
|
1946
|
+
releaseLock() {
|
|
1947
|
+
this.lock?.release();
|
|
1948
|
+
}
|
|
1949
|
+
rollback() {}
|
|
1950
|
+
stops = /* @__PURE__ */ new Set();
|
|
1951
|
+
cancel() {
|
|
1952
|
+
for (const stop of [...this.stops]) stop();
|
|
1953
|
+
}
|
|
1954
|
+
stopped() {}
|
|
1955
|
+
onCancel(stop) {
|
|
1956
|
+
this.stops.add(stop);
|
|
1957
|
+
return () => this.stops.delete(stop);
|
|
1958
|
+
}
|
|
1959
|
+
};
|
|
1960
|
+
function newRunId() {
|
|
1961
|
+
return `${Date.now().toString(36)}-${process.pid}-${randomBytes(3).toString("hex")}`;
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* Takes the package's lock and finishes what dead builds left, then opens a
|
|
1965
|
+
* staged session, or an in-place one when staging cannot run as an unstaged
|
|
1966
|
+
* build would: the output or a directory on its path in the package is a
|
|
1967
|
+
* symlink, the output is on another filesystem than its parent, it holds an
|
|
1968
|
+
* entry a copy cannot take (a FIFO, socket or device, or one this process
|
|
1969
|
+
* cannot read) or a symlink into itself, it holds `.ph/build`, whose lock and
|
|
1970
|
+
* journal a swap would move away, or the stage beside it cannot be written.
|
|
1971
|
+
* Only when `.ph/build` cannot hold the lock does the build run without one,
|
|
1972
|
+
* as builds did before staging. One warning says why a build writes in place.
|
|
1973
|
+
*/
|
|
1974
|
+
async function openBuildSession(options) {
|
|
1975
|
+
const { packageRoot, outDir, cleanedEntries, linkCleanedEntries } = options;
|
|
1976
|
+
const logical = resolve(packageRoot, outDir);
|
|
1977
|
+
const output = realPathThroughExistingParent(logical);
|
|
1978
|
+
const writesPackageDist = output === realPathThroughExistingParent(join(packageRoot, "dist"));
|
|
1979
|
+
const shown = (path) => shownPath(packageRoot, path);
|
|
1980
|
+
const inPlace = (reason, lock) => {
|
|
1981
|
+
console.warn(`⚠ ${reason}, so this build writes ${shown(logical)} in place: if it does not finish, ${shown(logical)} can be left part old, part new.`);
|
|
1982
|
+
return new InPlaceSession(output, logical, writesPackageDist, lock);
|
|
1983
|
+
};
|
|
1984
|
+
const runId = newRunId();
|
|
1985
|
+
let lock;
|
|
1986
|
+
try {
|
|
1987
|
+
lock = await creating(BUILD_DIRECTORY, () => acquireBuildLock(join(packageRoot, LOCK_FILE), runId, (wait) => console.log(`Another build of this package holds ${shown(wait.file)} (${wait.owner}); waiting for it to finish... If that build is gone, delete ${shown(wait.file)}.`)));
|
|
1988
|
+
} catch (error) {
|
|
1989
|
+
if (!(error instanceof CannotStage)) throw error;
|
|
1990
|
+
return inPlace(error.message, void 0);
|
|
1991
|
+
}
|
|
1992
|
+
try {
|
|
1993
|
+
recoverStaleRuns(packageRoot, logical);
|
|
1994
|
+
const link = symlinkOnPath(packageRoot, logical);
|
|
1995
|
+
if (link !== void 0) return inPlace(`${shown(link)} is a symbolic link`, lock);
|
|
1996
|
+
if (onAnotherFilesystem(logical)) return inPlace(`${shown(logical)} is on another filesystem than the directory that holds it`, lock);
|
|
1997
|
+
const unstageable = unstageableEntryIn(logical);
|
|
1998
|
+
if (unstageable !== void 0) return inPlace(`${shown(unstageable.path)} ${unstageable.reason}`, lock);
|
|
1999
|
+
const intoOutput = linkIntoOutput(logical, output, scratchBeside(logical, "stage", runId));
|
|
2000
|
+
if (intoOutput !== void 0) return inPlace(`${shown(intoOutput)} is a symbolic link into ${shown(logical)}`, lock);
|
|
2001
|
+
const control = [BUILD_DIRECTORY, join(RUNS_DIRECTORY, runId)].find((dir) => pathWithin(output, realPathThroughExistingParent(join(packageRoot, dir))) !== null);
|
|
2002
|
+
if (control !== void 0) return inPlace(`${shown(logical)} holds ${control}`, lock);
|
|
2003
|
+
try {
|
|
2004
|
+
return await StagedBuildSession.open({
|
|
2005
|
+
packageRoot,
|
|
2006
|
+
logical,
|
|
2007
|
+
output,
|
|
2008
|
+
writesPackageDist,
|
|
2009
|
+
cleanedEntries,
|
|
2010
|
+
linkCleanedEntries,
|
|
2011
|
+
runId,
|
|
2012
|
+
lock
|
|
2013
|
+
});
|
|
2014
|
+
} catch (error) {
|
|
2015
|
+
if (!(error instanceof CannotStage)) throw error;
|
|
2016
|
+
return inPlace(error.message, lock);
|
|
2017
|
+
}
|
|
2018
|
+
} catch (error) {
|
|
2019
|
+
lock.release();
|
|
2020
|
+
throw error;
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
//#endregion
|
|
2024
|
+
//#region src/utils/offered-routes-manifest.ts
|
|
2025
|
+
function withOfferedRoutes(json, offers) {
|
|
2026
|
+
const manifest = JSON.parse(json);
|
|
2027
|
+
if (offers ? manifest.connectRoutes === true : !("connectRoutes" in manifest)) return json;
|
|
2028
|
+
if (offers) manifest.connectRoutes = true;
|
|
2029
|
+
else delete manifest.connectRoutes;
|
|
2030
|
+
return `${JSON.stringify(manifest, null, 2)}\n`;
|
|
2031
|
+
}
|
|
2032
|
+
const slashes = (path) => path.replaceAll("\\", "/");
|
|
2033
|
+
/** Sets `connectRoutes` in the manifest the package's root module imports,
|
|
2034
|
+
* leaving the project's file as it is. */
|
|
2035
|
+
function offeredRoutesManifest(projectRoot, offers) {
|
|
2036
|
+
const manifestPath = slashes(join(projectRoot, "powerhouse.manifest.json"));
|
|
2037
|
+
return {
|
|
2038
|
+
name: "ph-offered-routes-manifest",
|
|
2039
|
+
transform(code, id) {
|
|
2040
|
+
if (slashes(id) !== manifestPath) return null;
|
|
2041
|
+
return {
|
|
2042
|
+
code: withOfferedRoutes(code, offers),
|
|
2043
|
+
map: null
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
2048
|
+
/** Sets `connectRoutes` in the dist copy of the manifest. */
|
|
2049
|
+
function markOfferedRoutes(dir, offers) {
|
|
2050
|
+
const manifestPath = join(dir, "powerhouse.manifest.json");
|
|
2051
|
+
if (!existsSync(manifestPath)) return;
|
|
2052
|
+
const json = readFileSync(manifestPath, "utf-8");
|
|
2053
|
+
writeFileSync(manifestPath, withOfferedRoutes(json, offers));
|
|
2054
|
+
}
|
|
2055
|
+
//#endregion
|
|
2056
|
+
//#region src/services/package-build/steps/stage-logger.ts
|
|
2057
|
+
/**
|
|
2058
|
+
* tsdown labels each file it writes with its directory, relative to the
|
|
2059
|
+
* package. Bundles written to the stage keep the labels of the output
|
|
2060
|
+
* directory they stand in for, so the log reads as without staging.
|
|
2061
|
+
*/
|
|
2062
|
+
function stageLogger({ projectRoot, outDir, session }) {
|
|
2063
|
+
const shown = `${relative(projectRoot, resolve(projectRoot, outDir))}${sep}`;
|
|
2064
|
+
const written = `${relative(projectRoot, session.stage())}${sep}`;
|
|
2065
|
+
const label = (message) => typeof message === "string" ? message.replaceAll(written, shown) : message;
|
|
2066
|
+
const relabel = (log) => (...messages) => log(...messages.map(label));
|
|
2067
|
+
return {
|
|
2068
|
+
get level() {
|
|
2069
|
+
return globalLogger.level;
|
|
2070
|
+
},
|
|
2071
|
+
set level(level) {
|
|
2072
|
+
globalLogger.level = level;
|
|
2073
|
+
},
|
|
2074
|
+
info: relabel((...m) => globalLogger.info(...m)),
|
|
2075
|
+
warn: relabel((...m) => globalLogger.warn(...m)),
|
|
2076
|
+
warnOnce: relabel((...m) => globalLogger.warnOnce(...m)),
|
|
2077
|
+
error: relabel((...m) => globalLogger.error(...m)),
|
|
2078
|
+
success: relabel((...m) => globalLogger.success(...m)),
|
|
2079
|
+
clearScreen: (type) => globalLogger.clearScreen(type)
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
//#endregion
|
|
2083
|
+
//#region src/services/package-build/steps/bundles.ts
|
|
2084
|
+
/**
|
|
2085
|
+
* Every shared specifier imported from the entry sources; the post-build
|
|
2086
|
+
* scan compares these against the built output.
|
|
2087
|
+
*
|
|
2088
|
+
* Scoped to the specifiers the build actually externalizes: a specifier the
|
|
2089
|
+
* vendor does not publish (the bare `@powerhousedao/shared` root, an
|
|
2090
|
+
* unvendored subpath) is deliberately bundled, so reporting it as "bundled
|
|
2091
|
+
* instead of externalized" would be a false alarm.
|
|
2092
|
+
*/
|
|
2093
|
+
function findSharedImportsInSources(root, globs) {
|
|
2094
|
+
const found = /* @__PURE__ */ new Set();
|
|
2095
|
+
for (const file of expandEntryGlobs(root, globs)) {
|
|
2096
|
+
const src = readFileSync(file, "utf8");
|
|
2097
|
+
for (const spec of findSharedImports(src, EXTERNALIZABLE_SHARED_SPECIFIERS)) found.add(spec);
|
|
2098
|
+
}
|
|
2099
|
+
return [...found].sort();
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* The built JS outputs of a browser build (entry files and chunks).
|
|
2103
|
+
*/
|
|
2104
|
+
function readDistBrowserFiles(dir) {
|
|
2105
|
+
const out = [];
|
|
2106
|
+
if (!existsSync(dir)) return out;
|
|
2107
|
+
const walk = (d) => {
|
|
2108
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
2109
|
+
const p = join(d, e.name);
|
|
2110
|
+
if (e.isDirectory()) walk(p);
|
|
2111
|
+
else if (e.isFile() && e.name.endsWith(".js")) out.push({
|
|
2112
|
+
path: p,
|
|
2113
|
+
content: readFileSync(p, "utf8")
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
};
|
|
2117
|
+
walk(dir);
|
|
2118
|
+
return out;
|
|
2119
|
+
}
|
|
2120
|
+
const browserBundleStep = {
|
|
2121
|
+
id: "browser-bundle",
|
|
2122
|
+
run: async (ctx) => {
|
|
2123
|
+
const { args, projectRoot, session, trace, detection, findings } = ctx;
|
|
2124
|
+
const stage = session.stage();
|
|
2125
|
+
const sharedDeps = !args.noSharedDeps;
|
|
2126
|
+
const routesEntry = join(projectRoot, OFFERED_ROUTES_MODULE);
|
|
2127
|
+
const config = buildBrowserBuildConfig({
|
|
2128
|
+
sharedDeps,
|
|
2129
|
+
plugins: [
|
|
2130
|
+
externalDepsPlugin(trace, /* @__PURE__ */ new Map(), {
|
|
2131
|
+
root: projectRoot,
|
|
2132
|
+
browser: true,
|
|
2133
|
+
cache: detection
|
|
2134
|
+
}),
|
|
2135
|
+
offeredRoutesManifest(projectRoot, findings.offersRoutes),
|
|
2136
|
+
noConnectImports(routesEntry, join(projectRoot, HOST_ROUTES_DIR))
|
|
2137
|
+
]
|
|
2138
|
+
});
|
|
2139
|
+
await build({
|
|
2140
|
+
...config,
|
|
2141
|
+
...session.writesPackageDist && { copy: [{
|
|
2142
|
+
from: "powerhouse.manifest.json",
|
|
2143
|
+
to: stage
|
|
2144
|
+
}] },
|
|
2145
|
+
...findings.offersRoutes ? { entry: [...browserEntry, { "connect-routes": routesEntry }] } : {},
|
|
2146
|
+
outDir: join(stage, "browser"),
|
|
2147
|
+
customLogger: stageLogger(ctx)
|
|
2148
|
+
});
|
|
2149
|
+
if (sharedDeps) {
|
|
2150
|
+
const imported = findSharedImportsInSources(projectRoot, browserEntry);
|
|
2151
|
+
const bundled = findBundledSharedDeps(imported, readDistBrowserFiles(join(stage, "browser")));
|
|
2152
|
+
if (bundled.length > 0) console.warn(`⚠ shared deps bundled instead of externalized: ${bundled.join(", ")} — check your neverBundle config`);
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
};
|
|
2156
|
+
function assertExternalDependenciesDeclared(projectRoot, found, pkg) {
|
|
2157
|
+
for (const dep of found) console.log(`${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`);
|
|
2158
|
+
const undeclared = undeclaredExternalDependencies(found, pkg);
|
|
2159
|
+
if (undeclared.length === 0) return;
|
|
2160
|
+
const lines = undeclared.map((dep) => ` ${dep.name}${dep.importer ? ` (imported by ${projectPath(projectRoot, dep.importer)})` : ""}`);
|
|
2161
|
+
throw new Error(`Packages with native addons or WebAssembly modules must be listed in package.json "dependencies", "optionalDependencies" or "peerDependencies":\n${lines.join("\n")}\n\nThey stay external to the build, and installs of this package skip devDependencies.`);
|
|
2162
|
+
}
|
|
2163
|
+
const nodeBundleStep = {
|
|
2164
|
+
id: "node-bundle",
|
|
2165
|
+
run: async (ctx) => {
|
|
2166
|
+
const { args, projectRoot, session, trace, detection, findings } = ctx;
|
|
2167
|
+
await build({
|
|
2168
|
+
...buildNodeBuildConfig({
|
|
2169
|
+
sharedDeps: !args.noSharedDeps,
|
|
2170
|
+
plugins: [externalDepsPlugin(trace, findings.external, {
|
|
2171
|
+
root: projectRoot,
|
|
2172
|
+
ignoreDirs: ["editors"],
|
|
2173
|
+
forbidDirs: ["document-models", "scalars"],
|
|
2174
|
+
cache: detection
|
|
2175
|
+
})]
|
|
2176
|
+
}),
|
|
2177
|
+
outDir: join(session.stage(), "node"),
|
|
2178
|
+
customLogger: stageLogger(ctx)
|
|
2179
|
+
});
|
|
2180
|
+
findings.pkg = await readPackage({ cwd: projectRoot });
|
|
2181
|
+
assertExternalDependenciesDeclared(projectRoot, [...findings.external.values()], findings.pkg);
|
|
2182
|
+
}
|
|
2183
|
+
};
|
|
2184
|
+
/** The output entry each bundle step writes, which tsdown empties first. */
|
|
2185
|
+
const CLEANED_BY_STEP = /* @__PURE__ */ new Map([[browserBundleStep.id, "browser"], [nodeBundleStep.id, "node"]]);
|
|
2186
|
+
/** The output entries `steps` empty before they write them, by step id. */
|
|
2187
|
+
const entriesCleanedBy = (steps) => steps.flatMap(({ id }) => CLEANED_BY_STEP.get(id) ?? []);
|
|
2188
|
+
//#endregion
|
|
2189
|
+
//#region src/services/package-build/steps/connect-routes.ts
|
|
2190
|
+
const connectRoutesStep = {
|
|
2191
|
+
id: "connect-routes",
|
|
2192
|
+
run: async ({ projectRoot, findings }) => {
|
|
2193
|
+
await syncProjectConnectRoutes(projectRoot);
|
|
2194
|
+
findings.offersRoutes = existsSync(join(projectRoot, OFFERED_ROUTES_MODULE));
|
|
2195
|
+
}
|
|
2196
|
+
};
|
|
2197
|
+
//#endregion
|
|
2198
|
+
//#region src/services/package-build/steps/definitions.ts
|
|
2199
|
+
/**
|
|
2200
|
+
* The built worker beside ph-cli's own code. Run from source (under vitest),
|
|
2201
|
+
* the TypeScript worker through tsx, so a test runs the current source.
|
|
2202
|
+
*/
|
|
2203
|
+
function definitionsWorker() {
|
|
2204
|
+
const root = dirname(createRequire(import.meta.url).resolve("@powerhousedao/ph-cli/package.json"));
|
|
2205
|
+
if (!import.meta.url.endsWith(".ts")) return {
|
|
2206
|
+
path: join(root, "dist", "definitions-worker.mjs"),
|
|
2207
|
+
execArgv: []
|
|
2208
|
+
};
|
|
2209
|
+
return {
|
|
2210
|
+
path: join(root, "src", "services", "model", "definitions-worker.ts"),
|
|
2211
|
+
execArgv: ["--import", import.meta.resolve("tsx")]
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
/**
|
|
2215
|
+
* Runs the definition check in a child process: the package's own modules
|
|
2216
|
+
* can exit, hang or start timers there without reaching the build. A child
|
|
2217
|
+
* that ends without a reply, outlives `timeoutMs` or outlives a stop of the
|
|
2218
|
+
* build is killed, and the reply says why the check could not run.
|
|
2219
|
+
*/
|
|
2220
|
+
function checkInChild(projectRoot, profile, session, timeoutMs) {
|
|
2221
|
+
const worker = definitionsWorker();
|
|
2222
|
+
return new Promise((resolve) => {
|
|
2223
|
+
let reply;
|
|
2224
|
+
let killedFor;
|
|
2225
|
+
const child = fork(worker.path, [projectRoot, profile], {
|
|
2226
|
+
cwd: projectRoot,
|
|
2227
|
+
execArgv: worker.execArgv,
|
|
2228
|
+
stdio: [
|
|
2229
|
+
"ignore",
|
|
2230
|
+
2,
|
|
2231
|
+
2,
|
|
2232
|
+
"ipc"
|
|
2233
|
+
]
|
|
2234
|
+
});
|
|
2235
|
+
const kill = (why) => {
|
|
2236
|
+
killedFor ??= why;
|
|
2237
|
+
child.kill("SIGKILL");
|
|
2238
|
+
};
|
|
2239
|
+
const timer = setTimeout(() => kill(`the check did not finish within ${timeoutMs / 1e3} seconds`), timeoutMs);
|
|
2240
|
+
const unwatch = session.onCancel(() => kill("the build was stopped"));
|
|
2241
|
+
if (session.stopped()) kill("the build was stopped");
|
|
2242
|
+
const settle = (settled) => {
|
|
2243
|
+
clearTimeout(timer);
|
|
2244
|
+
unwatch();
|
|
2245
|
+
resolve(settled);
|
|
2246
|
+
};
|
|
2247
|
+
child.on("message", (message) => {
|
|
2248
|
+
reply ??= message;
|
|
2249
|
+
});
|
|
2250
|
+
child.on("error", (error) => {
|
|
2251
|
+
kill(error.message);
|
|
2252
|
+
settle({
|
|
2253
|
+
ok: false,
|
|
2254
|
+
message: error.message
|
|
2255
|
+
});
|
|
2256
|
+
});
|
|
2257
|
+
child.on("exit", (code, signal) => {
|
|
2258
|
+
settle(reply ?? {
|
|
2259
|
+
ok: false,
|
|
2260
|
+
message: killedFor ?? `the check ${signal ? `was stopped by ${signal}` : `exited with code ${code}`} before it reported`
|
|
2261
|
+
});
|
|
2262
|
+
});
|
|
2263
|
+
});
|
|
2264
|
+
}
|
|
2265
|
+
/**
|
|
2266
|
+
* Checks the package's definitions after tsc and before any bundle, when
|
|
2267
|
+
* `ph build` asks or with `--release`. Without `--release` it checks the
|
|
2268
|
+
* code-first sources the package selects, never stops the build, and skips
|
|
2269
|
+
* without a word a package that selects none. With `--release`
|
|
2270
|
+
* (experimental) it runs the release profile over every model, stored ones
|
|
2271
|
+
* included, and stops the build when the check is invalid or cannot run, a
|
|
2272
|
+
* configuration error included. The package's modules load only in the
|
|
2273
|
+
* definitions worker, which has `timeoutMs` to report.
|
|
2274
|
+
*/
|
|
2275
|
+
function definitionsStepWithin(timeoutMs) {
|
|
2276
|
+
return {
|
|
2277
|
+
id: "definitions",
|
|
2278
|
+
after: ["typecheck"],
|
|
2279
|
+
run: async ({ args, checkDefinitions, projectRoot, session, findings }) => {
|
|
2280
|
+
if (!args.release && !checkDefinitions) return;
|
|
2281
|
+
if (!args.release) {
|
|
2282
|
+
const { resolveDefinitionSelection } = await import("document-model/tooling");
|
|
2283
|
+
const selection = resolveDefinitionSelection({
|
|
2284
|
+
configFile: join(projectRoot, "powerhouse.config.json"),
|
|
2285
|
+
allowMissingConfig: true
|
|
2286
|
+
});
|
|
2287
|
+
if (selection.status !== "ready" || selection.sourceSet.sources.length === 0) return;
|
|
2288
|
+
}
|
|
2289
|
+
const { renderCheckReport } = await import("./render-DdieUjtg.mjs");
|
|
2290
|
+
const printReport = (report) => {
|
|
2291
|
+
const text = renderCheckReport(report);
|
|
2292
|
+
if (report.diagnostics.length > 0) console.warn(`⚠ The definition check reported problems; the build goes on:\n${text}`);
|
|
2293
|
+
else console.log(`✔ ${text}`);
|
|
2294
|
+
};
|
|
2295
|
+
console.log("\n▶ Checking document model definitions...");
|
|
2296
|
+
if (!args.release) {
|
|
2297
|
+
const edit = await checkInChild(projectRoot, "edit", session, timeoutMs);
|
|
2298
|
+
if (edit.ok) printReport(edit.result);
|
|
2299
|
+
else console.warn(`⚠ The definition check could not run: ${edit.message}`);
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
const release = await checkInChild(projectRoot, "release", session, timeoutMs);
|
|
2303
|
+
if (!release.ok) throw new BuildRefusal(`✘ The definition check could not run: ${release.message}`);
|
|
2304
|
+
const { status } = release.result.report;
|
|
2305
|
+
if (status === "invalid" || status === "failed") throw new BuildRefusal(`✘ The release definition check stopped the build:\n${renderCheckReport(release.result.report)}`);
|
|
2306
|
+
findings.release = release.result;
|
|
2307
|
+
printReport(release.result.report);
|
|
2308
|
+
}
|
|
2309
|
+
};
|
|
2310
|
+
}
|
|
2311
|
+
const definitionsStep = definitionsStepWithin(3e5);
|
|
2312
|
+
//#endregion
|
|
2313
|
+
//#region src/services/package-build/steps/package-checks.ts
|
|
2314
|
+
/**
|
|
2315
|
+
* A Powerhouse package's `powerhouse.manifest.json` "name" must match its
|
|
2316
|
+
* `package.json` "name" — Connect and the registry resolve installed versions
|
|
2317
|
+
* by treating the manifest name as the npm package name, so a mismatch silently
|
|
2318
|
+
* breaks resolution. Fail the build early if they diverge. No-op when the
|
|
2319
|
+
* project has no manifest (nothing to compare).
|
|
2320
|
+
*/
|
|
2321
|
+
async function assertManifestNameMatchesPackage(projectPath) {
|
|
2322
|
+
const manifestPath = join(projectPath, "powerhouse.manifest.json");
|
|
2323
|
+
if (!existsSync(manifestPath)) return;
|
|
2324
|
+
const { name: packageName } = await readPackage({ cwd: projectPath });
|
|
2325
|
+
let manifestName;
|
|
2326
|
+
try {
|
|
2327
|
+
manifestName = JSON.parse(readFileSync(manifestPath, "utf-8")).name;
|
|
2328
|
+
} catch {
|
|
2329
|
+
throw new Error(`Failed to parse "powerhouse.manifest.json" at ${manifestPath}. Make sure it is valid JSON.`);
|
|
2330
|
+
}
|
|
2331
|
+
if (manifestName !== packageName) throw new Error(`Package name mismatch — "package.json" and "powerhouse.manifest.json" must have the same "name":\n package.json "name": ${JSON.stringify(packageName)}\n powerhouse.manifest.json "name": ${JSON.stringify(manifestName)}\n\nUpdate one so they match, then run the build again.`);
|
|
2332
|
+
}
|
|
2333
|
+
const manifestNameStep = {
|
|
2334
|
+
id: "manifest-name",
|
|
2335
|
+
run: ({ projectRoot }) => assertManifestNameMatchesPackage(projectRoot)
|
|
2336
|
+
};
|
|
2337
|
+
const piecesOutDirStep = {
|
|
2338
|
+
id: "pieces-out-dir",
|
|
2339
|
+
run: ({ outDir, pieces }) => {
|
|
2340
|
+
assertPiecesOutDir({
|
|
2341
|
+
outDir,
|
|
2342
|
+
pieces: [...pieces]
|
|
2343
|
+
});
|
|
2344
|
+
return Promise.resolve();
|
|
2345
|
+
}
|
|
2346
|
+
};
|
|
2347
|
+
//#endregion
|
|
2348
|
+
//#region src/services/package-build/steps/pieces.ts
|
|
2349
|
+
const piecesStep = {
|
|
2350
|
+
id: "pieces",
|
|
2351
|
+
run: async (ctx) => {
|
|
2352
|
+
const { projectRoot, outDir, pieces, session, trace, detection, findings } = ctx;
|
|
2353
|
+
const stage = session.stage();
|
|
2354
|
+
if (!existsSync(pieceListPath({
|
|
2355
|
+
projectRoot,
|
|
2356
|
+
outDir: stage
|
|
2357
|
+
}))) return;
|
|
2358
|
+
const pkg = findings.pkg ?? await readPackage({ cwd: projectRoot });
|
|
2359
|
+
const customLogger = stageLogger(ctx);
|
|
2360
|
+
findings.built = await buildPieces({
|
|
2361
|
+
projectRoot,
|
|
2362
|
+
outDir,
|
|
2363
|
+
writeTo: stage,
|
|
2364
|
+
pieces: [...pieces]
|
|
2365
|
+
}, {
|
|
2366
|
+
name: pkg.name,
|
|
2367
|
+
version: pkg.version,
|
|
2368
|
+
license: typeof pkg.license === "string" ? pkg.license : void 0
|
|
2369
|
+
}, {
|
|
2370
|
+
bundle: (config) => build({
|
|
2371
|
+
...config,
|
|
2372
|
+
customLogger
|
|
2373
|
+
}),
|
|
2374
|
+
trace,
|
|
2375
|
+
cache: detection
|
|
2376
|
+
});
|
|
2377
|
+
}
|
|
2378
|
+
};
|
|
2379
|
+
const distManifestStep = {
|
|
2380
|
+
id: "dist-manifest",
|
|
2381
|
+
run: ({ projectRoot, pieces, session, findings }) => {
|
|
2382
|
+
syncDistManifest({
|
|
2383
|
+
projectRoot,
|
|
2384
|
+
outDir: session.stage(),
|
|
2385
|
+
pieces: [...pieces]
|
|
2386
|
+
}, findings.built, externalDependencyVersions(findings.external.values()));
|
|
2387
|
+
return Promise.resolve();
|
|
2388
|
+
}
|
|
2389
|
+
};
|
|
2390
|
+
const offeredRoutesStep = {
|
|
2391
|
+
id: "offered-routes",
|
|
2392
|
+
run: ({ session, findings }) => {
|
|
2393
|
+
markOfferedRoutes(session.stage(), findings.offersRoutes);
|
|
2394
|
+
return Promise.resolve();
|
|
2395
|
+
}
|
|
2396
|
+
};
|
|
2397
|
+
//#endregion
|
|
2398
|
+
//#region src/services/release/consumer.ts
|
|
2399
|
+
const CONDITIONS = {
|
|
2400
|
+
node: /* @__PURE__ */ new Set([
|
|
2401
|
+
"node",
|
|
2402
|
+
"import",
|
|
2403
|
+
"module-sync",
|
|
2404
|
+
"default"
|
|
2405
|
+
]),
|
|
2406
|
+
browser: /* @__PURE__ */ new Set([
|
|
2407
|
+
"browser",
|
|
2408
|
+
"import",
|
|
2409
|
+
"module",
|
|
2410
|
+
"default"
|
|
2411
|
+
])
|
|
2412
|
+
};
|
|
2413
|
+
const IMPORTABLE = /\.(m?js|cjs)$/;
|
|
2414
|
+
function resolveTarget(value, conditions) {
|
|
2415
|
+
if (typeof value === "string") return value;
|
|
2416
|
+
if (Array.isArray(value)) {
|
|
2417
|
+
for (const item of value) {
|
|
2418
|
+
const target = resolveTarget(item, conditions);
|
|
2419
|
+
if (target !== void 0) return target;
|
|
2420
|
+
}
|
|
2421
|
+
return;
|
|
2422
|
+
}
|
|
2423
|
+
if (value === null || typeof value !== "object") return void 0;
|
|
2424
|
+
for (const [key, nested] of Object.entries(value)) {
|
|
2425
|
+
if (!conditions.has(key)) continue;
|
|
2426
|
+
const target = resolveTarget(nested, conditions);
|
|
2427
|
+
if (target !== void 0) return target;
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
function targetsOf(value) {
|
|
2431
|
+
if (typeof value === "string") return [value];
|
|
2432
|
+
if (Array.isArray(value)) return value.flatMap(targetsOf);
|
|
2433
|
+
if (value === null || typeof value !== "object") return [];
|
|
2434
|
+
return Object.values(value).flatMap(targetsOf);
|
|
2435
|
+
}
|
|
2436
|
+
function subpaths(manifest) {
|
|
2437
|
+
const { exports } = manifest;
|
|
2438
|
+
if (exports === void 0) return [];
|
|
2439
|
+
if (exports !== null && typeof exports === "object" && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith("."))) return Object.entries(exports);
|
|
2440
|
+
return [[".", exports]];
|
|
2441
|
+
}
|
|
2442
|
+
const packedPath = (target) => target.replace(/^\.\//, "");
|
|
2443
|
+
function packedEntries(manifest, files, unbuilt) {
|
|
2444
|
+
const imports = {
|
|
2445
|
+
node: [],
|
|
2446
|
+
browser: []
|
|
2447
|
+
};
|
|
2448
|
+
const missing = [];
|
|
2449
|
+
const entries = subpaths(manifest);
|
|
2450
|
+
if (entries.length === 0) {
|
|
2451
|
+
imports.node.push(manifest.name);
|
|
2452
|
+
return {
|
|
2453
|
+
imports,
|
|
2454
|
+
missing
|
|
2455
|
+
};
|
|
2456
|
+
}
|
|
2457
|
+
for (const [subpath, value] of entries) {
|
|
2458
|
+
const targets = targetsOf(value).filter((target) => !target.includes("*"));
|
|
2459
|
+
const absent = targets.filter((target) => !files.has(packedPath(target)));
|
|
2460
|
+
if (unbuilt.has(subpath) && absent.length === targets.length) continue;
|
|
2461
|
+
missing.push(...absent.map((target) => `exports["${subpath}"] names ${target}`));
|
|
2462
|
+
if (subpath === "./package.json") continue;
|
|
2463
|
+
for (const consumer of ["node", "browser"]) {
|
|
2464
|
+
const target = resolveTarget(value, CONDITIONS[consumer]);
|
|
2465
|
+
if (target === void 0 || !IMPORTABLE.test(target)) continue;
|
|
2466
|
+
const specifier = `${manifest.name}${subpath.slice(1)}`;
|
|
2467
|
+
if (!subpath.includes("*")) {
|
|
2468
|
+
imports[consumer].push(specifier);
|
|
2469
|
+
continue;
|
|
2470
|
+
}
|
|
2471
|
+
const [before, after] = packedPath(target).split("*");
|
|
2472
|
+
const [subBefore, subAfter] = specifier.split("*");
|
|
2473
|
+
for (const file of [...files].sort()) {
|
|
2474
|
+
if (!file.startsWith(before) || !file.endsWith(after)) continue;
|
|
2475
|
+
const star = file.slice(before.length, file.length - after.length);
|
|
2476
|
+
if (star !== "") imports[consumer].push(`${subBefore}${star}${subAfter}`);
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
return {
|
|
2481
|
+
imports,
|
|
2482
|
+
missing
|
|
2483
|
+
};
|
|
2484
|
+
}
|
|
2485
|
+
function installed(projectRoot, name) {
|
|
2486
|
+
for (let directory = projectRoot;; directory = dirname(directory)) {
|
|
2487
|
+
const candidate = join(directory, "node_modules", ...name.split("/"));
|
|
2488
|
+
if (existsSync(join(candidate, "package.json"))) return realpathSync.native(candidate);
|
|
2489
|
+
if (dirname(directory) === directory) return void 0;
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
const IMPORT_EACH = `import { writeFileSync } from "node:fs";
|
|
2493
|
+
import { registerHooks } from "node:module";
|
|
2494
|
+
const { specifiers, conditions, resultFile } = JSON.parse(process.argv[1]);
|
|
2495
|
+
if (conditions) {
|
|
2496
|
+
registerHooks({
|
|
2497
|
+
resolve: (specifier, context, next) => next(specifier, {
|
|
2498
|
+
...context,
|
|
2499
|
+
conditions: context.conditions.includes("require")
|
|
2500
|
+
? conditions.map((name) => (name === "import" ? "require" : name))
|
|
2501
|
+
: conditions,
|
|
2502
|
+
}),
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
const failed = [];
|
|
2506
|
+
for (const specifier of specifiers) {
|
|
2507
|
+
try { await import(specifier); }
|
|
2508
|
+
catch (error) { failed.push(specifier + ": " + (error instanceof Error ? error.message : String(error)).split("\\n")[0]); }
|
|
2509
|
+
}
|
|
2510
|
+
writeFileSync(resultFile, JSON.stringify(failed));
|
|
2511
|
+
process.exit(0);
|
|
2512
|
+
`;
|
|
2513
|
+
const TIMEOUT_MS = 12e4;
|
|
2514
|
+
const STDERR_LIMIT = 65536;
|
|
2515
|
+
async function importAll(consumerRoot, consumer, specifiers, signal) {
|
|
2516
|
+
if (specifiers.length === 0) return [];
|
|
2517
|
+
const env = { ...process.env };
|
|
2518
|
+
delete env.NODE_OPTIONS;
|
|
2519
|
+
delete env.NODE_PATH;
|
|
2520
|
+
const resultFile = join(dirname(consumerRoot), `${consumer}-result.json`);
|
|
2521
|
+
const input = {
|
|
2522
|
+
specifiers,
|
|
2523
|
+
conditions: consumer === "browser" ? [...CONDITIONS.browser] : null,
|
|
2524
|
+
resultFile
|
|
2525
|
+
};
|
|
2526
|
+
const ended = await new Promise((done) => {
|
|
2527
|
+
const child = spawn(process.execPath, [
|
|
2528
|
+
"--input-type=module",
|
|
2529
|
+
"-e",
|
|
2530
|
+
IMPORT_EACH,
|
|
2531
|
+
JSON.stringify(input)
|
|
2532
|
+
], {
|
|
2533
|
+
cwd: consumerRoot,
|
|
2534
|
+
env,
|
|
2535
|
+
signal,
|
|
2536
|
+
stdio: [
|
|
2537
|
+
"ignore",
|
|
2538
|
+
"ignore",
|
|
2539
|
+
"pipe"
|
|
2540
|
+
]
|
|
2541
|
+
});
|
|
2542
|
+
let timedOut = false;
|
|
2543
|
+
const timer = setTimeout(() => {
|
|
2544
|
+
timedOut = true;
|
|
2545
|
+
child.kill();
|
|
2546
|
+
}, TIMEOUT_MS);
|
|
2547
|
+
let stderr = "";
|
|
2548
|
+
child.stderr.setEncoding("utf8");
|
|
2549
|
+
child.stderr.on("data", (chunk) => {
|
|
2550
|
+
if (stderr.length < STDERR_LIMIT) stderr += chunk;
|
|
2551
|
+
});
|
|
2552
|
+
child.on("error", (error) => done(error.message));
|
|
2553
|
+
child.on("close", (code, killedBy) => {
|
|
2554
|
+
clearTimeout(timer);
|
|
2555
|
+
if (timedOut) {
|
|
2556
|
+
done(`did not finish its imports within ${TIMEOUT_MS / 1e3} seconds`);
|
|
2557
|
+
return;
|
|
2558
|
+
}
|
|
2559
|
+
const how = killedBy === null ? `exited with ${code}` : `got ${killedBy}`;
|
|
2560
|
+
const why = stderr.trim().split("\n")[0];
|
|
2561
|
+
done(why ? `${how}: ${why}` : how);
|
|
2562
|
+
});
|
|
2563
|
+
});
|
|
2564
|
+
if (!existsSync(resultFile)) return [`${consumer} consumer did not finish: it ${ended}`];
|
|
2565
|
+
return JSON.parse(readFileSync(resultFile, "utf8")).map((failure) => `${consumer} consumer cannot import ${failure.replace(/ imported from \S*\[eval\d*\]$/, "")}`);
|
|
2566
|
+
}
|
|
2567
|
+
async function checkPackedConsumer(projectRoot, packed, unbuilt, signal) {
|
|
2568
|
+
const { manifest, files } = packed;
|
|
2569
|
+
const consumerRoot = join(packed.directory, "consumer");
|
|
2570
|
+
const modules = join(consumerRoot, "node_modules");
|
|
2571
|
+
const installRoot = join(modules, ...manifest.name.split("/"));
|
|
2572
|
+
for (const [path, bytes] of files) {
|
|
2573
|
+
const target = resolve(installRoot, path);
|
|
2574
|
+
if (!target.startsWith(`${installRoot}${sep}`)) return [`the tarball has an entry outside the package: ${path}`];
|
|
2575
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
2576
|
+
writeFileSync(target, bytes);
|
|
2577
|
+
}
|
|
2578
|
+
writeFileSync(join(consumerRoot, "package.json"), `${JSON.stringify({
|
|
2579
|
+
name: "ph-packed-consumer",
|
|
2580
|
+
private: true,
|
|
2581
|
+
type: "module"
|
|
2582
|
+
})}\n`);
|
|
2583
|
+
const runtime = /* @__PURE__ */ new Set([
|
|
2584
|
+
...Object.keys(manifest.dependencies ?? {}),
|
|
2585
|
+
...Object.keys(manifest.optionalDependencies ?? {}),
|
|
2586
|
+
...Object.keys(manifest.peerDependencies ?? {})
|
|
2587
|
+
]);
|
|
2588
|
+
for (const name of runtime) {
|
|
2589
|
+
if (name === manifest.name) continue;
|
|
2590
|
+
const from = installed(projectRoot, name);
|
|
2591
|
+
if (from === void 0) continue;
|
|
2592
|
+
const link = join(modules, ...name.split("/"));
|
|
2593
|
+
mkdirSync(dirname(link), { recursive: true });
|
|
2594
|
+
symlinkSync(from, link, process.platform === "win32" ? "junction" : "dir");
|
|
2595
|
+
}
|
|
2596
|
+
const { imports, missing } = packedEntries(manifest, new Set(files.keys()), unbuilt);
|
|
2597
|
+
const failures = await Promise.all(["node", "browser"].map((consumer) => importAll(consumerRoot, consumer, imports[consumer], signal)));
|
|
2598
|
+
return [...missing.map((entry) => `${entry}, which the package does not contain`), ...failures.flat()].map((failure) => {
|
|
2599
|
+
const shown = failure.replaceAll(`${consumerRoot}${sep}`, "").replaceAll(consumerRoot, ".");
|
|
2600
|
+
return sep === "\\" ? shown.replaceAll("\\", "/") : shown;
|
|
2601
|
+
});
|
|
2602
|
+
}
|
|
2603
|
+
//#endregion
|
|
2604
|
+
//#region src/services/release/issuance.ts
|
|
2605
|
+
const under$1 = (path, directory) => path === directory || path.startsWith(`${directory}/`);
|
|
2606
|
+
/**
|
|
2607
|
+
* Whether a release build may write an approval, and what its revision
|
|
2608
|
+
* leaves out: the replaced directory, and what tsc writes outside the
|
|
2609
|
+
* output.
|
|
2610
|
+
*/
|
|
2611
|
+
function planApproval(build) {
|
|
2612
|
+
const { release, startFiles, outputs } = build;
|
|
2613
|
+
if (!build.typesOk) return { refused: "the build went on despite tsc's type errors" };
|
|
2614
|
+
if (release === void 0 || startFiles === void 0) return { refused: "the release check did not run" };
|
|
2615
|
+
return {
|
|
2616
|
+
release,
|
|
2617
|
+
startFiles,
|
|
2618
|
+
excluded: [...outputs.slice(1), ...build.compilerOutputs.filter((path) => !outputs.some((directory) => under$1(path, directory)))]
|
|
2619
|
+
};
|
|
2620
|
+
}
|
|
2621
|
+
/**
|
|
2622
|
+
* Why the approval may not be written because the package changed while it
|
|
2623
|
+
* was built, comparing its files at the start, minus what the revision
|
|
2624
|
+
* leaves out, with `endFiles`; undefined when nothing changed.
|
|
2625
|
+
*/
|
|
2626
|
+
function changedWhileBuilt(plan, endFiles) {
|
|
2627
|
+
const leftOut = (path) => plan.excluded.some((exclusion) => under$1(path, exclusion));
|
|
2628
|
+
const changed = changedPaths(plan.startFiles.filter(({ path }) => !leftOut(path)), endFiles);
|
|
2629
|
+
return changed.length === 0 ? void 0 : `the package's files changed while it was built (${listed(changed)})`;
|
|
2630
|
+
}
|
|
2631
|
+
//#endregion
|
|
2632
|
+
//#region src/services/package-build/steps/release-approval.ts
|
|
2633
|
+
const under = (path, directory) => path === directory || path.startsWith(`${directory}/`);
|
|
2634
|
+
/**
|
|
2635
|
+
* The output directory as given, then the directory the build replaces when
|
|
2636
|
+
* that is a symlink to another place in the package: neither is a source.
|
|
2637
|
+
*/
|
|
2638
|
+
function outputDirectories(projectRoot, outDir, target) {
|
|
2639
|
+
const output = packagePath(projectRoot, outDir);
|
|
2640
|
+
const real = packagePath(projectRoot, target);
|
|
2641
|
+
return real !== ".." && !real.startsWith("../") && !isAbsolute(real) && !under(real, output) ? [output, real] : [output];
|
|
2642
|
+
}
|
|
2643
|
+
/** With `--release`, records the package's files before anything is built. */
|
|
2644
|
+
const releaseStartStep = {
|
|
2645
|
+
id: "release-start",
|
|
2646
|
+
run: ({ args, projectRoot, outDir, session, findings }) => {
|
|
2647
|
+
if (args.release) findings.releaseStart = revisionFiles(projectRoot, outputDirectories(projectRoot, outDir, session.output));
|
|
2648
|
+
return Promise.resolve();
|
|
2649
|
+
}
|
|
2650
|
+
};
|
|
2651
|
+
/** Exports `ph init` declares whose entry the build skips when its source is absent. */
|
|
2652
|
+
const OPTIONAL_EXPORTS = {
|
|
2653
|
+
"./scalars": "scalars/index.ts",
|
|
2654
|
+
"./pieces": "pieces/index.ts"
|
|
2655
|
+
};
|
|
2656
|
+
const unbuiltExports = (projectRoot, findings) => /* @__PURE__ */ new Set([...Object.entries(OPTIONAL_EXPORTS).filter(([, source]) => !existsSync(join(projectRoot, source))).map(([subpath]) => subpath), ...findings.offersRoutes ? [] : ["./connect-routes"]]);
|
|
2657
|
+
const notWritten = (why) => new BuildRefusal(`✘ No release approval was written: ${why}. The new output is in place; build again with --release to approve it.`);
|
|
2658
|
+
/**
|
|
2659
|
+
* With `--release`, once the output is replaced: records what the release
|
|
2660
|
+
* check approved and what `npm pack` publishes from the new output, unless
|
|
2661
|
+
* tsc's errors were accepted, the package changed while it was built, or the
|
|
2662
|
+
* packed tarball fails to install and import in a scratch consumer.
|
|
2663
|
+
*/
|
|
2664
|
+
const releaseApprovalStep = {
|
|
2665
|
+
id: "release-approval",
|
|
2666
|
+
when: "committed",
|
|
2667
|
+
run: async ({ args, projectRoot, outDir, session, findings }) => {
|
|
2668
|
+
if (args.release) await recordApproval(projectRoot, outputDirectories(projectRoot, outDir, session.output), findings, session);
|
|
2669
|
+
}
|
|
2670
|
+
};
|
|
2671
|
+
async function recordApproval(projectRoot, outputs, findings, session) {
|
|
2672
|
+
const plan = planApproval({
|
|
2673
|
+
typesOk: findings.typesOk,
|
|
2674
|
+
release: findings.release,
|
|
2675
|
+
startFiles: findings.releaseStart,
|
|
2676
|
+
outputs,
|
|
2677
|
+
compilerOutputs: findings.compilerOutputs.map((path) => packagePath(projectRoot, path))
|
|
2678
|
+
});
|
|
2679
|
+
if ("refused" in plan) throw notWritten(plan.refused);
|
|
2680
|
+
const { release, excluded } = plan;
|
|
2681
|
+
const [output] = outputs;
|
|
2682
|
+
const files = revisionFiles(projectRoot, [output, ...excluded]);
|
|
2683
|
+
const changed = changedWhileBuilt(plan, files);
|
|
2684
|
+
if (changed !== void 0) throw notWritten(changed);
|
|
2685
|
+
let packed;
|
|
2686
|
+
try {
|
|
2687
|
+
packed = packRelease(projectRoot);
|
|
2688
|
+
} catch (error) {
|
|
2689
|
+
throw notWritten(error instanceof Error ? error.message : String(error));
|
|
2690
|
+
}
|
|
2691
|
+
let published;
|
|
2692
|
+
const stop = new AbortController();
|
|
2693
|
+
const unwatch = session.onCancel(() => {
|
|
2694
|
+
stop.abort();
|
|
2695
|
+
packed.dispose();
|
|
2696
|
+
});
|
|
2697
|
+
try {
|
|
2698
|
+
const failures = await checkPackedConsumer(projectRoot, packed, unbuiltExports(projectRoot, findings), stop.signal);
|
|
2699
|
+
if (failures.length > 0) throw notWritten(`the packed package does not install and import in a scratch consumer: ${listed(failures)}`);
|
|
2700
|
+
published = packedDigests(packed);
|
|
2701
|
+
} finally {
|
|
2702
|
+
unwatch();
|
|
2703
|
+
packed.dispose();
|
|
2704
|
+
}
|
|
2705
|
+
const phCliVersion = getVersion();
|
|
2706
|
+
writeReleaseApproval(projectRoot, {
|
|
2707
|
+
kind: "powerhouse.release-approval",
|
|
2708
|
+
formatVersion: 1,
|
|
2709
|
+
phCliVersion,
|
|
2710
|
+
outDir: output,
|
|
2711
|
+
packageRevision: {
|
|
2712
|
+
digest: packageRevision(files, { [PH_CLI_BINDING]: phCliVersion }),
|
|
2713
|
+
excluded
|
|
2714
|
+
},
|
|
2715
|
+
publishedFiles: published,
|
|
2716
|
+
report: {
|
|
2717
|
+
profile: "release",
|
|
2718
|
+
status: release.report.status,
|
|
2719
|
+
definitions: release.report.definitions
|
|
2720
|
+
},
|
|
2721
|
+
scalars: release.scalars,
|
|
2722
|
+
hostValidation: release.host
|
|
2723
|
+
});
|
|
2724
|
+
console.log(`✔ Release approval written to ${RELEASE_APPROVAL_PATH}`);
|
|
2725
|
+
}
|
|
2726
|
+
//#endregion
|
|
2727
|
+
//#region src/services/package-build/steps/stylesheet.ts
|
|
2728
|
+
function sourcePath(projectRoot, path) {
|
|
2729
|
+
return `./${relative(projectRoot, resolve(projectRoot, path)).replaceAll("\\", "/")}`;
|
|
2730
|
+
}
|
|
2731
|
+
const stylesheetStep = {
|
|
2732
|
+
id: "stylesheet",
|
|
2733
|
+
run: ({ agent, projectRoot, session }) => {
|
|
2734
|
+
const stage = session.stage();
|
|
2735
|
+
const command = resolveCommand(agent, "execute-local", [
|
|
2736
|
+
"tailwindcss",
|
|
2737
|
+
"--input",
|
|
2738
|
+
"-",
|
|
2739
|
+
"--minify"
|
|
2740
|
+
]);
|
|
2741
|
+
if (command === null) throw new BuildRefusal("You need to have tailwindcss installed to use the `build` command.");
|
|
2742
|
+
const stylePath = join(projectRoot, "style.css");
|
|
2743
|
+
const style = existsSync(stylePath) ? readFileSync(stylePath, "utf-8") : void 0;
|
|
2744
|
+
const compiled = execSync(`${command.command} ${command.args.join(" ")}`, {
|
|
2745
|
+
cwd: projectRoot,
|
|
2746
|
+
input: packageStyleEntry(style, {
|
|
2747
|
+
browserDir: sourcePath(projectRoot, join(stage, "browser")),
|
|
2748
|
+
localPackages: localPackageNames(projectRoot)
|
|
2749
|
+
}),
|
|
2750
|
+
encoding: "utf-8",
|
|
2751
|
+
stdio: [
|
|
2752
|
+
"pipe",
|
|
2753
|
+
"pipe",
|
|
2754
|
+
"inherit"
|
|
2755
|
+
],
|
|
2756
|
+
maxBuffer: 67108864
|
|
2757
|
+
});
|
|
2758
|
+
const distDir = session.writesPackageDist ? stage : join(projectRoot, "dist");
|
|
2759
|
+
mkdirSync(distDir, { recursive: true });
|
|
2760
|
+
writeFileSync(join(distDir, "style.css"), packageStylesheet(compiled));
|
|
2761
|
+
return Promise.resolve();
|
|
2762
|
+
}
|
|
2763
|
+
};
|
|
2764
|
+
//#endregion
|
|
2765
|
+
//#region src/services/package-build/steps/typecheck.ts
|
|
2766
|
+
const TYPE_ERROR_RISK = "A package built with type errors can load and still fail at runtime.";
|
|
2767
|
+
const UNSAFE_BUILD_WARNING = "⚠ Built despite type errors. " + TYPE_ERROR_RISK + " Fix them before you publish or deploy it.";
|
|
2768
|
+
/** The root project's config, as `tsc --showConfig` prints it. */
|
|
2769
|
+
function showCompilerConfig(agent, projectRoot) {
|
|
2770
|
+
const showConfig = resolveCommand(agent, "execute-local", ["tsc", "--showConfig"]);
|
|
2771
|
+
if (showConfig === null) return void 0;
|
|
2772
|
+
try {
|
|
2773
|
+
return parseShownConfig(execSync(`${showConfig.command} ${showConfig.args.join(" ")}`, {
|
|
2774
|
+
cwd: projectRoot,
|
|
2775
|
+
encoding: "utf8",
|
|
2776
|
+
stdio: [
|
|
2777
|
+
"ignore",
|
|
2778
|
+
"pipe",
|
|
2779
|
+
"ignore"
|
|
2780
|
+
]
|
|
2781
|
+
}));
|
|
2782
|
+
} catch {
|
|
2783
|
+
return;
|
|
2784
|
+
}
|
|
2785
|
+
}
|
|
2786
|
+
function declarationsMissing(options, projectRoot) {
|
|
2787
|
+
const path = declarationDirectory(options, projectRoot);
|
|
2788
|
+
if (path === void 0) return false;
|
|
2789
|
+
return !existsSync(path) || readdirSync(path).length === 0;
|
|
2790
|
+
}
|
|
2791
|
+
function isInteractive() {
|
|
2792
|
+
return Boolean(process.stdin.isTTY) && !process.env.CI;
|
|
2793
|
+
}
|
|
2794
|
+
async function confirmBuildDespiteTypeErrors() {
|
|
2795
|
+
const hint = "Fix them and build again. --ignore-type-errors skips this check, at the risk of shipping that failure.";
|
|
2796
|
+
if (!isInteractive()) throw new BuildRefusal(`\n✘ tsc reported the type errors above. ${TYPE_ERROR_RISK}\n${hint}`);
|
|
2797
|
+
const enquirer = await import("enquirer");
|
|
2798
|
+
let confirmed;
|
|
2799
|
+
try {
|
|
2800
|
+
confirmed = (await enquirer.default.prompt({
|
|
2801
|
+
type: "confirm",
|
|
2802
|
+
name: "confirmed",
|
|
2803
|
+
message: `tsc reported the type errors above. ${TYPE_ERROR_RISK} Build anyway?`,
|
|
2804
|
+
initial: false
|
|
2805
|
+
})).confirmed;
|
|
2806
|
+
} catch {
|
|
2807
|
+
confirmed = false;
|
|
2808
|
+
}
|
|
2809
|
+
if (!confirmed) throw new BuildRefusal(`Build cancelled. ${hint}`);
|
|
2810
|
+
}
|
|
2811
|
+
//#endregion
|
|
2812
|
+
//#region src/services/package-build/steps/standard.ts
|
|
2813
|
+
/**
|
|
2814
|
+
* `ph build`'s steps in the order they run. Another phase inserts its own
|
|
2815
|
+
* with `[...standardBuildSteps, ...more]` and `after` on the step it follows.
|
|
2816
|
+
*/
|
|
2817
|
+
const standardBuildSteps = [
|
|
2818
|
+
releaseStartStep,
|
|
2819
|
+
manifestNameStep,
|
|
2820
|
+
piecesOutDirStep,
|
|
2821
|
+
connectRoutesStep,
|
|
2822
|
+
{
|
|
2823
|
+
id: "typecheck",
|
|
2824
|
+
run: async ({ agent, args, outDir, projectRoot, session, findings }) => {
|
|
2825
|
+
const config = showCompilerConfig(agent, projectRoot);
|
|
2826
|
+
const force = config !== void 0 && declarationsMissing(config.options, projectRoot);
|
|
2827
|
+
let generated;
|
|
2828
|
+
if (config !== void 0) {
|
|
2829
|
+
const configFile = join(projectRoot, "tsconfig.json");
|
|
2830
|
+
const outputs = await compilerOutputs(config, {
|
|
2831
|
+
configFile,
|
|
2832
|
+
packageRoot: projectRoot,
|
|
2833
|
+
buildDirectory: join(projectRoot, BUILD_DIRECTORY),
|
|
2834
|
+
agent,
|
|
2835
|
+
output: session.output
|
|
2836
|
+
});
|
|
2837
|
+
generated = await session.prepareCompiler({
|
|
2838
|
+
configFile,
|
|
2839
|
+
config,
|
|
2840
|
+
outputs
|
|
2841
|
+
});
|
|
2842
|
+
findings.compilerOutputs = outputs.map(({ path }) => path);
|
|
2843
|
+
}
|
|
2844
|
+
const tscCommand = resolveCommand(agent, "execute-local", [
|
|
2845
|
+
"tsc",
|
|
2846
|
+
"--build",
|
|
2847
|
+
...force ? ["--force"] : [],
|
|
2848
|
+
...generated ? [relative(projectRoot, generated)] : []
|
|
2849
|
+
]);
|
|
2850
|
+
if (tscCommand === null) throw new BuildRefusal("You need to have typescript installed to use the `build` command.");
|
|
2851
|
+
console.log("\n▶ Type-checking and emitting types via tsc...");
|
|
2852
|
+
try {
|
|
2853
|
+
execSync(`${tscCommand.command} ${tscCommand.args.join(" ")}`, { stdio: "inherit" });
|
|
2854
|
+
console.log("✔ Types emitted to", join(outDir, "types"));
|
|
2855
|
+
findings.typesOk = true;
|
|
2856
|
+
} catch {
|
|
2857
|
+
findings.typesOk = false;
|
|
2858
|
+
}
|
|
2859
|
+
session.compilerOutputsWritten();
|
|
2860
|
+
if (!findings.typesOk && !args.ignoreTypeErrors) await confirmBuildDespiteTypeErrors();
|
|
2861
|
+
}
|
|
2862
|
+
},
|
|
2863
|
+
definitionsStep,
|
|
2864
|
+
browserBundleStep,
|
|
2865
|
+
nodeBundleStep,
|
|
2866
|
+
piecesStep,
|
|
2867
|
+
distManifestStep,
|
|
2868
|
+
offeredRoutesStep,
|
|
2869
|
+
stylesheetStep,
|
|
2870
|
+
releaseApprovalStep
|
|
2871
|
+
];
|
|
2872
|
+
//#endregion
|
|
2873
|
+
//#region src/services/package-build/steps/trace.ts
|
|
2874
|
+
function createTraceFiles() {
|
|
2875
|
+
const cache = {};
|
|
2876
|
+
return (file) => traceFile(file, cache);
|
|
2877
|
+
}
|
|
2878
|
+
async function traceFile(file, cache) {
|
|
2879
|
+
const { fileList, reasons } = await nodeFileTrace([file], {
|
|
2880
|
+
base: "/",
|
|
2881
|
+
cache
|
|
2882
|
+
});
|
|
2883
|
+
const absolute = (p) => resolve("/", p);
|
|
2884
|
+
return {
|
|
2885
|
+
fileList: new Set([...fileList].map(absolute)),
|
|
2886
|
+
reasons: new Map([...reasons].map(([p, reason]) => [absolute(p), { parents: new Set([...reason.parents].map(absolute)) }]))
|
|
2887
|
+
};
|
|
2888
|
+
}
|
|
2889
|
+
//#endregion
|
|
2890
|
+
//#region src/services/package-build/run-build.ts
|
|
2891
|
+
const STOP_SIGNALS = [
|
|
2892
|
+
"SIGINT",
|
|
2893
|
+
"SIGTERM",
|
|
2894
|
+
"SIGHUP"
|
|
2895
|
+
];
|
|
2896
|
+
/**
|
|
2897
|
+
* The signal listeners signal-exit installs: each ends the process when
|
|
2898
|
+
* only signal-exit listeners are left, so they are not an embedding
|
|
2899
|
+
* process that keeps running. Read from the counts its copies share.
|
|
2900
|
+
*/
|
|
2901
|
+
function exitOnlyListeners() {
|
|
2902
|
+
const count = (emitter) => {
|
|
2903
|
+
const value = emitter?.count;
|
|
2904
|
+
return typeof value === "number" ? value : 0;
|
|
2905
|
+
};
|
|
2906
|
+
const shared = globalThis;
|
|
2907
|
+
const legacy = process;
|
|
2908
|
+
return count(shared[Symbol.for("signal-exit emitter")]) + count(legacy.__signal_exit_emitter__);
|
|
2909
|
+
}
|
|
2910
|
+
/**
|
|
2911
|
+
* Stops the build when the process is told to stop, for as long as it runs.
|
|
2912
|
+
* The handler runs first and removes itself, so the listeners already there
|
|
2913
|
+
* act as if it had never been added. When one of them keeps the process
|
|
2914
|
+
* running (an embedding process), the handler only cancels: the step runner
|
|
2915
|
+
* rolls back once the running step settles, and the lock is released after
|
|
2916
|
+
* that. Otherwise the process should end with the signal: the handler
|
|
2917
|
+
* restores the previous output at once, releases the lock and, with no
|
|
2918
|
+
* listener left, re-raises the signal. The run and its snapshot stay for
|
|
2919
|
+
* the next build to replay. The lock does not: a dead owner's lock is taken
|
|
2920
|
+
* over only from the same host, which a new container or a renamed machine
|
|
2921
|
+
* is not. A signal-exit callback can still keep the process running; then
|
|
2922
|
+
* the runner restores again from that snapshot once the running step
|
|
2923
|
+
* settles.
|
|
2924
|
+
*/
|
|
2925
|
+
function stopOnSignal(session, ownsProcess) {
|
|
2926
|
+
const stop = (signal) => {
|
|
2927
|
+
session.cancel(signal);
|
|
2928
|
+
remove();
|
|
2929
|
+
if (process.listenerCount(signal) > exitOnlyListeners()) return;
|
|
2930
|
+
session.rollback();
|
|
2931
|
+
if (ownsProcess) session.releaseLock();
|
|
2932
|
+
if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
|
|
2933
|
+
};
|
|
2934
|
+
const remove = () => {
|
|
2935
|
+
for (const signal of STOP_SIGNALS) process.removeListener(signal, stop);
|
|
2936
|
+
};
|
|
2937
|
+
for (const signal of STOP_SIGNALS) process.prependListener(signal, stop);
|
|
2938
|
+
return remove;
|
|
2939
|
+
}
|
|
2940
|
+
/**
|
|
2941
|
+
* Builds the package in the current directory: every step writes to a stage,
|
|
2942
|
+
* which replaces the output directory only when all of them succeed. A
|
|
2943
|
+
* failure, a refusal or a stop signal leaves the previous output and
|
|
2944
|
+
* compiler outputs as they were.
|
|
2945
|
+
*/
|
|
2946
|
+
async function buildPackage(args, options = {}) {
|
|
2947
|
+
const { outDir } = args;
|
|
2948
|
+
const projectRoot = process.cwd();
|
|
2949
|
+
const steps = options.steps ?? standardBuildSteps;
|
|
2950
|
+
const session = await openBuildSession({
|
|
2951
|
+
packageRoot: projectRoot,
|
|
2952
|
+
outDir,
|
|
2953
|
+
cleanedEntries: entriesCleanedBy(steps),
|
|
2954
|
+
linkCleanedEntries: options.steps === void 0
|
|
2955
|
+
});
|
|
2956
|
+
const stopListening = stopOnSignal(session, options.ownsProcess ?? false);
|
|
2957
|
+
try {
|
|
2958
|
+
const ctx = {
|
|
2959
|
+
args,
|
|
2960
|
+
projectRoot,
|
|
2961
|
+
outDir,
|
|
2962
|
+
agent: (await detect())?.agent ?? "npm",
|
|
2963
|
+
session,
|
|
2964
|
+
checkDefinitions: options.checkDefinitions ?? false,
|
|
2965
|
+
pieces: planPieces(projectRoot, outDir),
|
|
2966
|
+
detection: createDetectionCache(),
|
|
2967
|
+
trace: createTraceFiles(),
|
|
2968
|
+
findings: {
|
|
2969
|
+
offersRoutes: false,
|
|
2970
|
+
typesOk: true,
|
|
2971
|
+
compilerOutputs: [],
|
|
2972
|
+
releaseStart: void 0,
|
|
2973
|
+
release: void 0,
|
|
2974
|
+
external: /* @__PURE__ */ new Map(),
|
|
2975
|
+
pkg: void 0,
|
|
2976
|
+
built: []
|
|
2977
|
+
}
|
|
2978
|
+
};
|
|
2979
|
+
await runBuildSteps(steps, ctx, session);
|
|
2980
|
+
if (!ctx.findings.typesOk) console.warn(`\n${UNSAFE_BUILD_WARNING}`);
|
|
2981
|
+
} finally {
|
|
2982
|
+
stopListening();
|
|
2983
|
+
session.rollback();
|
|
2984
|
+
session.close();
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2987
|
+
//#endregion
|
|
2988
|
+
//#region src/services/build.ts
|
|
2989
|
+
/**
|
|
2990
|
+
* `ph build`, and the package build `ph connect build` and the switchboard
|
|
2991
|
+
* runner start from. A refusal (missing tsc or tailwindcss, type errors not
|
|
2992
|
+
* accepted, a release check that fails) prints its message and exits 1 once
|
|
2993
|
+
* the previous output is back, as these callers have always seen it.
|
|
2994
|
+
* Only `ph build` passes `checkDefinitions`, so the other callers import
|
|
2995
|
+
* none of the package's modules. A command that adds steps passes
|
|
2996
|
+
* `[...standardBuildSteps, ...its own]` as `steps`.
|
|
2997
|
+
*/
|
|
2998
|
+
async function runBuild(args, options = {}) {
|
|
2999
|
+
try {
|
|
3000
|
+
return await buildPackage(args, options);
|
|
3001
|
+
} catch (error) {
|
|
3002
|
+
if (!(error instanceof BuildRefusal)) throw error;
|
|
3003
|
+
console.error(error.message);
|
|
3004
|
+
process.exit(error.exitCode);
|
|
3005
|
+
}
|
|
3006
|
+
}
|
|
3007
|
+
//#endregion
|
|
3008
|
+
export { assertExternalDependenciesDeclared as i, createTraceFiles as n, assertManifestNameMatchesPackage as r, runBuild as t };
|
|
3009
|
+
|
|
3010
|
+
//# sourceMappingURL=build-C1mmZvlb.mjs.map
|
|
3011
|
+
//# debugId=a50f62aa-4997-5d8a-a8e5-63f40b3c4ad4
|