@powerhousedao/host-core 6.3.0-dev.8 → 6.4.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{compound-CBqPgk38.d.mts → compound-D2dh2VUh.d.mts} +332 -22
- package/dist/compound-D2dh2VUh.d.mts.map +1 -0
- package/dist/{compound-DKi56SSx.mjs → compound-n-bO0qKh.mjs} +1616 -487
- package/dist/compound-n-bO0qKh.mjs.map +1 -0
- package/dist/{env-substitution-C_fVirPh.d.mts → env-substitution-Ct39KFvA.d.mts} +7 -3
- package/dist/env-substitution-Ct39KFvA.d.mts.map +1 -0
- package/dist/{env-substitution-BXGohOGN.mjs → env-substitution-FJ5Nua4M.mjs} +29 -10
- package/dist/env-substitution-FJ5Nua4M.mjs.map +1 -0
- package/dist/{host-schemas-BM7F21lf.d.mts → host-schemas-B6_-P11_.d.mts} +52 -19
- package/dist/host-schemas-B6_-P11_.d.mts.map +1 -0
- package/dist/index.d.mts +194 -129
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +51 -355
- package/dist/index.mjs.map +1 -1
- package/dist/kill-tree.d.mts +8 -0
- package/dist/kill-tree.d.mts.map +1 -0
- package/dist/kill-tree.mjs +73 -0
- package/dist/kill-tree.mjs.map +1 -0
- package/dist/plugins-DP3YlIWx.mjs +309 -0
- package/dist/plugins-DP3YlIWx.mjs.map +1 -0
- package/dist/{plugins-Uk84BRay.d.mts → plugins-Dsmfhbn7.d.mts} +53 -3
- package/dist/plugins-Dsmfhbn7.d.mts.map +1 -0
- package/dist/plugins.d.mts +2 -2
- package/dist/plugins.mjs +2 -174
- package/dist/projection.d.mts +12 -18
- package/dist/projection.d.mts.map +1 -1
- package/dist/projection.mjs +17 -10
- package/dist/projection.mjs.map +1 -1
- package/dist/runners/compound.d.mts +9 -3
- package/dist/runners/compound.d.mts.map +1 -1
- package/dist/runners/compound.mjs +1 -1
- package/dist/schema.d.mts +6 -4
- package/dist/schema.d.mts.map +1 -1
- package/dist/schema.mjs +5 -4
- package/dist/schema.mjs.map +1 -1
- package/package.json +9 -3
- package/dist/compound-CBqPgk38.d.mts.map +0 -1
- package/dist/compound-DKi56SSx.mjs.map +0 -1
- package/dist/env-substitution-BXGohOGN.mjs.map +0 -1
- package/dist/env-substitution-C_fVirPh.d.mts.map +0 -1
- package/dist/host-schemas-BM7F21lf.d.mts.map +0 -1
- package/dist/plugins-Uk84BRay.d.mts.map +0 -1
- package/dist/plugins.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,385 +1,61 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import {
|
|
1
|
+
import { $ as computeOutputsHash, $n as runProvideHook, $t as resolveHostPlugins, A as STOP_RUN_TIMEOUT_MS, An as placementKeyIssues, At as resolveHostOutputs, B as probeRun, Bn as runnerKindSchema, Bt as checkTokenSites, C as applyChildWrapper, Cn as emitHostJsonSchema, Ct as packageBuildRefusal, D as COMPOUND_MEMBER_ENV, Dn as makeHostSchemas, Dt as TokenResolutionError, E as spawnHost, En as hostNameSchema, Et as validateHost, F as stopChannelPath, Fn as reactorProtocolSchema, Ft as BUILTIN_ENV_NAMES, G as writeRunRecord, Gn as normalizePluginEntries, Gt as schemaAtPath, H as readRunRecord, Hn as entryActiveForVerb, Ht as outputRefsOf, I as stopRun, In as reactorSchema, It as isBuiltinEnvName, J as checkRunnerArgv, Jn as pluginEntrySchema, Jt as formatPath, K as runRecordMemberSchema, Kn as normalizePluginEntry, Kt as collectTokenSites, L as clearRunRecord, Ln as refineConnectReactor, Lt as substituteBuiltinEnv, M as installStopChannel, Mn as reactorBackendKindSchema, Mt as PlanError, N as listenForStop, Nn as reactorBackendSchema, Nt as memberForRef, O as takeCompoundMember, On as memberProcessSchema, Ot as describeMapElements, P as requestStop, Pn as reactorHostSchema, Pt as planCompound, Q as OUTPUTS_FILE, Qn as runObserveHookSequential, Qt as findDeadConnectConfig, R as isPidAlive, Rn as refineStartOrder, Rt as findRemovedForms, S as resolveUserDataPlaceholders, Sn as defineHostSchemas, Sr as tokenable, St as listVerbs, T as SpawnHostError, Tn as genericCompoundHostSchema, Tt as validateDeclaredHost, U as recordKeyOf, Un as hostTypeSatisfies, Ut as outputSitesOf, V as readProjectName, Vn as PluginError, Vt as envSitesOf, W as runRecordKey, Wn as mergeContributions, Wt as refKey, X as splitCompoundArgv, Xn as resolveOrder, Xt as renderTokens, Y as isRunnerArgsSchema, Yn as registerHostType, Yt as isPlainObject, Z as splitRunArgv, Zn as runObserveHook, Zt as unwrapEscapes, _ as processResolveEnv, _n as compoundHostSchema, _r as mapTokenSchema, _t as getVerb, a as memberProcessOf, an as locateHost, ar as drivesSchema, at as loadHost, b as runnerOutputsSchema, bn as declaredGenericCompoundHostSchema, br as tokenKeyOf, bt as kindShapeIssues, c as prepareMember, cn as CONNECT_PRIMARY_MESSAGE, cr as TOKEN_KEYS, ct as probeHostsFolder, d as takesCspRegistrySync, dn as HOST_NAME_PATTERN, dr as envTokenable, dt as stripComments, en as resolvePluginContributions, er as runTransformHook, et as describeHostOutputs, f as runnerHandleSchema, fn as HOST_REF_MESSAGE, fr as findToken, ft as withoutHostsMessage, g as loadProducers, gn as childrenSchema, gr as keyTokenSchema, gt as STORE_VERBS, h as OUTPUT_DATA_DIRS_ENV, hn as childWrapperSchema, hr as itemTokenSchema, ht as RunnerError, i as memberCycle, in as hostFileLabel, ir as driveDeclarationSchema, it as lintOutputsFile, j as askToStop, jn as profileSchema, jt as unsetEnvMessage, k as STOP_ON_STDIN_ENV, kn as originOrUrlSchema, kt as emptyMaps, l as runCompound, ln as HOST_NAME_MAX_LENGTH, lr as concatTokenSchema, lt as readOutputsFileHash, m as compoundOutputSource, mn as PACKAGE_NAME_PATTERN, mr as isToken, mt as ONE_SHOT_VERBS, n as compoundStartVerb, nn as findHostPackage, nr as defaultConnectComposition, nt as lintHostImportGraph, o as memberVerbOf, on as parseHostRef, or as projectDriveIdWith, ot as loadHostFresh, p as toStartedHandle, pn as HOST_REF_PATTERN, pr as forbidRef, pt as CONNECT_RUNNER, q as runRecordSchema, qn as pluginEntryObjectSchema, qt as describeToken, r as holdStopRequests, rn as formatHostRef, rr as buildDriveDeclarationSchema, rt as lintHostImports, s as planForeground, sn as resolvePackageRoot, sr as TOKEN_ESCAPE_KEY, st as moduleRootOf, t as STOP_STREAM_LIMIT_MS, tn as HostLoadError, tr as CONNECT_PLUGIN_OWNED_SLICES, tt as findNonStaticValue, u as stopStreamOf, un as HOST_NAME_MESSAGE, ur as envTokenSchema, ut as scanHostImports, v as producerOutputsSchemas, vn as compoundWiringSchema, vr as outputTokenSchema, vt as hostSchemaIssues, w as SPAWN_STOPPING_NOTE, wn as emittedHostSchemas, wt as resolveRunnerModule, x as defaultUserDataDir, xn as declaredHostSchemas, xr as tokenSchema, xt as knownVerbIssues, y as runRecordOutputSource, yn as connectReactorIssues, yr as ref, yt as isSchemaLike, z as listRunRecords, zn as runnerBaseSchema, zt as checkOutputPaths } from "./compound-n-bO0qKh.mjs";
|
|
2
|
+
import { killTree } from "./kill-tree.mjs";
|
|
3
3
|
import crypto from "node:crypto";
|
|
4
|
-
import fs from "node:fs";
|
|
5
4
|
import path from "node:path";
|
|
6
|
-
import { pathToFileURL } from "node:url";
|
|
7
5
|
import { z } from "zod";
|
|
8
6
|
import { driveAddressMessage, switchboardOfDrive, switchboardOfDrive as switchboardOfDrive$1 } from "@powerhousedao/shared/host-tokens";
|
|
9
7
|
import { ORIGIN_PLACEHOLDER, SWITCHBOARD_PROXY_PATHS, isHtmlNavigation, isOriginPlaceholderUrl, isSwitchboardProxyPath, resolveOriginPlaceholders, toOriginPlaceholder, withOriginPlaceholders } from "@powerhousedao/shared/connect/origin-placeholder";
|
|
10
|
-
import { spawn } from "node:child_process";
|
|
11
|
-
import net from "node:net";
|
|
12
8
|
import { DEFAULT_CONNECT_STUDIO_PORT, DEFAULT_SWITCHBOARD_PORT } from "@powerhousedao/shared/clis/constants";
|
|
13
9
|
import { DRIVE_ICON_MAX_BYTES, resolveImageRef } from "@powerhousedao/shared/connect/image-ref";
|
|
14
|
-
//#region src/stop-channel.ts
|
|
15
|
-
/**
|
|
16
|
-
* Windows has no SIGTERM: `process.kill(pid, "SIGTERM")` ends the process at
|
|
17
|
-
* once, so no handler runs and a stack's stores are left as a crash leaves
|
|
18
|
-
* them. A started host therefore listens on a pipe named after its pid, and
|
|
19
|
-
* a connection to it is delivered as the SIGTERM it stands for. Elsewhere
|
|
20
|
-
* the signal itself does this, and there is no channel.
|
|
21
|
-
*/
|
|
22
|
-
function stopChannelPath(pid, platform = process.platform) {
|
|
23
|
-
return platform === "win32" ? `\\\\.\\pipe\\ph-stop-${pid}` : void 0;
|
|
24
|
-
}
|
|
25
|
-
/** Calls `onStop` for each connection to `channel`. The server holds no
|
|
26
|
-
* process open, and one that cannot listen leaves the host running without
|
|
27
|
-
* a channel rather than not running. */
|
|
28
|
-
function listenForStop(channel, onStop) {
|
|
29
|
-
const server = net.createServer((socket) => {
|
|
30
|
-
socket.on("error", () => void 0);
|
|
31
|
-
socket.end();
|
|
32
|
-
onStop();
|
|
33
|
-
});
|
|
34
|
-
server.on("error", () => void 0);
|
|
35
|
-
server.listen(channel);
|
|
36
|
-
server.unref();
|
|
37
|
-
return server;
|
|
38
|
-
}
|
|
39
|
-
let installed = false;
|
|
40
|
-
/** What a host's process calls once before it starts anything: from then on
|
|
41
|
-
* {@link requestStop} reaches its SIGTERM handlers on every platform. */
|
|
42
|
-
function installStopChannel() {
|
|
43
|
-
const channel = stopChannelPath(process.pid);
|
|
44
|
-
if (!channel || installed) return;
|
|
45
|
-
installed = true;
|
|
46
|
-
listenForStop(channel, () => {
|
|
47
|
-
if (!process.emit("SIGTERM", "SIGTERM")) process.exit(143);
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
const ASK_TIMEOUT_MS = 2e3;
|
|
51
|
-
/** Connects to a stop channel; true once the listener took the request. */
|
|
52
|
-
function askToStop(channel, timeoutMs = ASK_TIMEOUT_MS) {
|
|
53
|
-
return new Promise((resolve) => {
|
|
54
|
-
let connected = false;
|
|
55
|
-
const socket = net.connect(channel);
|
|
56
|
-
socket.setTimeout(timeoutMs, () => socket.destroy());
|
|
57
|
-
socket.once("connect", () => connected = true);
|
|
58
|
-
socket.on("error", () => void 0);
|
|
59
|
-
socket.once("close", () => resolve(connected));
|
|
60
|
-
socket.resume();
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Asks the process to stop as SIGTERM would. False when it could not be
|
|
65
|
-
* asked: on Windows a process without a stop channel (started by an older
|
|
66
|
-
* version, or not a host), which only a kill ends.
|
|
67
|
-
*/
|
|
68
|
-
async function requestStop(pid, platform = process.platform) {
|
|
69
|
-
const channel = stopChannelPath(pid, platform);
|
|
70
|
-
if (channel) return askToStop(channel);
|
|
71
|
-
try {
|
|
72
|
-
process.kill(pid, "SIGTERM");
|
|
73
|
-
} catch {}
|
|
74
|
-
return true;
|
|
75
|
-
}
|
|
76
|
-
const STOP_RUN_TIMEOUT_MS = 6e4;
|
|
77
|
-
/** Asks the project's running `hostName` to stop and waits until its process
|
|
78
|
-
* is gone. It never kills: a host that does not answer keeps running. */
|
|
79
|
-
async function stopRun(projectDir, hostName, options = {}) {
|
|
80
|
-
const env = options.env ?? process.env;
|
|
81
|
-
const projectName = readProjectName(projectDir);
|
|
82
|
-
const probe = probeRun(projectDir, hostName, projectName, env);
|
|
83
|
-
if (probe.status === "none" || probe.status === "stale") return { status: "none" };
|
|
84
|
-
const { pid } = probe.record;
|
|
85
|
-
if (probe.status === "foreign") return {
|
|
86
|
-
status: "foreign",
|
|
87
|
-
pid,
|
|
88
|
-
projectName: probe.record.projectName
|
|
89
|
-
};
|
|
90
|
-
if (!await requestStop(pid)) return {
|
|
91
|
-
status: "unreachable",
|
|
92
|
-
pid
|
|
93
|
-
};
|
|
94
|
-
const deadline = Date.now() + (options.timeoutMs ?? 6e4);
|
|
95
|
-
while (isPidAlive(pid)) {
|
|
96
|
-
if (Date.now() >= deadline) return {
|
|
97
|
-
status: "timeout",
|
|
98
|
-
pid
|
|
99
|
-
};
|
|
100
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
101
|
-
}
|
|
102
|
-
if (readRunRecord(projectDir, hostName, env)?.pid === pid) clearRunRecord(projectDir, hostName, env);
|
|
103
|
-
return {
|
|
104
|
-
status: "stopped",
|
|
105
|
-
pid
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
//#endregion
|
|
109
|
-
//#region src/spawn-host.ts
|
|
110
|
-
/** The tail line before which a timed-out or aborted run's output is its own. */
|
|
111
|
-
const SPAWN_STOPPING_NOTE = "spawnHost: stopping it";
|
|
112
|
-
var SpawnHostError = class extends Error {
|
|
113
|
-
phase;
|
|
114
|
-
outputTail;
|
|
115
|
-
exit;
|
|
116
|
-
constructor(message, phase, outputTail, exit) {
|
|
117
|
-
super(outputTail ? `${message}\n--- output tail ---\n${outputTail}` : message);
|
|
118
|
-
this.phase = phase;
|
|
119
|
-
this.outputTail = outputTail;
|
|
120
|
-
this.exit = exit;
|
|
121
|
-
this.name = "SpawnHostError";
|
|
122
|
-
}
|
|
123
|
-
};
|
|
124
|
-
const READY_TIMEOUT_MS = 12e4;
|
|
125
|
-
const STOP_TIMEOUT_MS = 3e4;
|
|
126
|
-
const POLL_MS = 100;
|
|
127
|
-
const CLOSE_WAIT_MS = 1e3;
|
|
128
|
-
const BASE_ENV_KEYS = [
|
|
129
|
-
"PATH",
|
|
130
|
-
"HOME",
|
|
131
|
-
"TMPDIR"
|
|
132
|
-
];
|
|
133
|
-
const WIN32_ENV_KEYS = [
|
|
134
|
-
"SystemRoot",
|
|
135
|
-
"USERPROFILE",
|
|
136
|
-
"APPDATA",
|
|
137
|
-
"LOCALAPPDATA",
|
|
138
|
-
"TEMP",
|
|
139
|
-
"TMP",
|
|
140
|
-
"ComSpec",
|
|
141
|
-
"PATHEXT"
|
|
142
|
-
];
|
|
143
|
-
/** The child's whole env: no other `process.env` key reaches it. */
|
|
144
|
-
function childEnv(dataDir, env = {}) {
|
|
145
|
-
if ("PH_USER_DATA_DIR" in env) throw new Error("spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.");
|
|
146
|
-
const keys = process.platform === "win32" ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS] : BASE_ENV_KEYS;
|
|
147
|
-
const base = {};
|
|
148
|
-
for (const key of keys) {
|
|
149
|
-
const value = process.env[key];
|
|
150
|
-
if (value !== void 0) base[key] = value;
|
|
151
|
-
}
|
|
152
|
-
return {
|
|
153
|
-
...base,
|
|
154
|
-
PH_USER_DATA_DIR: dataDir,
|
|
155
|
-
PH_NO_TELEMETRY: "1",
|
|
156
|
-
PH_NO_DOTENV: "1",
|
|
157
|
-
...env
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
function resolvePhCliEntry(projectRoot) {
|
|
161
|
-
const pkgPath = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href).resolve("@powerhousedao/ph-cli/package.json");
|
|
162
|
-
return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
|
|
163
|
-
}
|
|
164
|
-
/** Readiness waits for a record; refuse a host/verb that writes none. */
|
|
165
|
-
async function assertWritesRecord(projectRoot, host, verb) {
|
|
166
|
-
if (verb !== void 0 && (ONE_SHOT_VERBS.has(verb) || STORE_VERBS.has(verb))) throw new Error(`spawnHost: "${verb}" is a one-shot verb; it writes no run record to wait for.`);
|
|
167
|
-
const loaded = await loadHost(projectRoot, host);
|
|
168
|
-
const specifier = loaded.host.runner.module;
|
|
169
|
-
const runner = await resolveRunnerModule(projectRoot, specifier);
|
|
170
|
-
if (runner.kind === "compound") {
|
|
171
|
-
if (loaded.host.config?.runtimeRecord === false) throw new Error(`spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`);
|
|
172
|
-
return;
|
|
173
|
-
}
|
|
174
|
-
if (!isSchemaLike(runner.outputsSchema)) throw new Error(`spawnHost: hosts/${host} runs "${specifier}", which exports no outputsSchema, so it writes no run record to wait for.`);
|
|
175
|
-
}
|
|
176
|
-
const sleep = (ms) => new Promise((resolve) => {
|
|
177
|
-
setTimeout(resolve, ms).unref();
|
|
178
|
-
});
|
|
179
|
-
const live = /* @__PURE__ */ new Set();
|
|
180
|
-
let exitHookInstalled = false;
|
|
181
|
-
function track(child) {
|
|
182
|
-
live.add(child);
|
|
183
|
-
child.once("exit", () => live.delete(child));
|
|
184
|
-
if (exitHookInstalled) return;
|
|
185
|
-
exitHookInstalled = true;
|
|
186
|
-
process.once("exit", () => {
|
|
187
|
-
for (const running of live) running.kill("SIGTERM");
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
/**
|
|
191
|
-
* `ph run <host> [verb]` as a child; ready when its run record appears.
|
|
192
|
-
*
|
|
193
|
-
* The child shares this process's group, so a terminal Ctrl-C reaches both.
|
|
194
|
-
* It runs the project's own ph-cli: one older than PH_NO_DOTENV reads the
|
|
195
|
-
* project's `.env` anyway.
|
|
196
|
-
*/
|
|
197
|
-
async function spawnHost(options) {
|
|
198
|
-
const projectRoot = path.resolve(options.projectRoot);
|
|
199
|
-
const dataDir = path.resolve(options.dataDir);
|
|
200
|
-
const env = childEnv(dataDir, options.env);
|
|
201
|
-
const readerEnv = { PH_USER_DATA_DIR: dataDir };
|
|
202
|
-
const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;
|
|
203
|
-
const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;
|
|
204
|
-
const { signal } = options;
|
|
205
|
-
if (signal?.aborted) throw new SpawnHostError("spawnHost: aborted before start.", "aborted", "");
|
|
206
|
-
await assertWritesRecord(projectRoot, options.host, options.verb);
|
|
207
|
-
const cli = options.cli ?? resolvePhCliEntry(projectRoot);
|
|
208
|
-
fs.mkdirSync(dataDir, { recursive: true });
|
|
209
|
-
const log = options.logFile ? fs.createWriteStream(options.logFile, { flags: "a" }) : void 0;
|
|
210
|
-
let tail = "";
|
|
211
|
-
log?.on("error", (error) => {
|
|
212
|
-
tail = (tail + `logFile: ${error.message}\n`).slice(-8192);
|
|
213
|
-
});
|
|
214
|
-
const args = [
|
|
215
|
-
cli,
|
|
216
|
-
"run",
|
|
217
|
-
options.host
|
|
218
|
-
];
|
|
219
|
-
if (options.verb !== void 0) args.push(options.verb);
|
|
220
|
-
const child = spawn(process.execPath, args, {
|
|
221
|
-
cwd: projectRoot,
|
|
222
|
-
env,
|
|
223
|
-
stdio: [
|
|
224
|
-
"ignore",
|
|
225
|
-
"pipe",
|
|
226
|
-
"pipe"
|
|
227
|
-
],
|
|
228
|
-
windowsHide: true
|
|
229
|
-
});
|
|
230
|
-
track(child);
|
|
231
|
-
const onChunk = (stream) => (chunk) => {
|
|
232
|
-
tail = (tail + chunk).slice(-8192);
|
|
233
|
-
log?.write(chunk);
|
|
234
|
-
try {
|
|
235
|
-
options.onOutput?.(stream, chunk);
|
|
236
|
-
} catch (error) {
|
|
237
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
238
|
-
tail = (tail + `onOutput: ${message}\n`).slice(-8192);
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
child.stdout.setEncoding("utf8").on("data", onChunk("stdout"));
|
|
242
|
-
child.stderr.setEncoding("utf8").on("data", onChunk("stderr"));
|
|
243
|
-
let forced = false;
|
|
244
|
-
let exit;
|
|
245
|
-
const exited = new Promise((resolve) => {
|
|
246
|
-
const done = (code, sig) => {
|
|
247
|
-
if (exit) return;
|
|
248
|
-
exit = {
|
|
249
|
-
code,
|
|
250
|
-
signal: sig,
|
|
251
|
-
forced
|
|
252
|
-
};
|
|
253
|
-
signal?.removeEventListener("abort", onAbort);
|
|
254
|
-
resolve(exit);
|
|
255
|
-
};
|
|
256
|
-
child.once("exit", done);
|
|
257
|
-
child.once("error", (error) => {
|
|
258
|
-
tail = (tail + `${error.message}\n`).slice(-8192);
|
|
259
|
-
if (child.pid === void 0) done(null, null);
|
|
260
|
-
});
|
|
261
|
-
});
|
|
262
|
-
const closed = new Promise((resolve) => {
|
|
263
|
-
child.once("close", () => {
|
|
264
|
-
log?.end();
|
|
265
|
-
resolve();
|
|
266
|
-
});
|
|
267
|
-
});
|
|
268
|
-
const pid = child.pid;
|
|
269
|
-
const ownRecords = () => pid === void 0 ? [] : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);
|
|
270
|
-
const kill = (sig) => {
|
|
271
|
-
if (pid === void 0) return;
|
|
272
|
-
try {
|
|
273
|
-
process.kill(pid, sig);
|
|
274
|
-
} catch {}
|
|
275
|
-
};
|
|
276
|
-
const clearOwnRecords = () => {
|
|
277
|
-
for (const record of ownRecords()) clearRunRecord(projectRoot, record.host, readerEnv);
|
|
278
|
-
};
|
|
279
|
-
let stopping;
|
|
280
|
-
const stop = () => {
|
|
281
|
-
stopping ??= (async () => {
|
|
282
|
-
if (!exit) {
|
|
283
|
-
kill("SIGTERM");
|
|
284
|
-
let timer;
|
|
285
|
-
const timedOut = await Promise.race([exited.then(() => false), new Promise((resolve) => {
|
|
286
|
-
timer = setTimeout(() => resolve(true), stopTimeoutMs);
|
|
287
|
-
})]);
|
|
288
|
-
clearTimeout(timer);
|
|
289
|
-
if (timedOut) {
|
|
290
|
-
forced = true;
|
|
291
|
-
kill("SIGKILL");
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
const result = await exited;
|
|
295
|
-
clearOwnRecords();
|
|
296
|
-
return result;
|
|
297
|
-
})();
|
|
298
|
-
return stopping;
|
|
299
|
-
};
|
|
300
|
-
function onAbort() {
|
|
301
|
-
stop();
|
|
302
|
-
}
|
|
303
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
304
|
-
const deadline = Date.now() + readyTimeoutMs;
|
|
305
|
-
for (;;) {
|
|
306
|
-
const aborted = signal?.aborted ?? false;
|
|
307
|
-
if (exit && !aborted) {
|
|
308
|
-
clearOwnRecords();
|
|
309
|
-
let timer;
|
|
310
|
-
await Promise.race([closed, new Promise((resolve) => {
|
|
311
|
-
timer = setTimeout(resolve, CLOSE_WAIT_MS);
|
|
312
|
-
})]);
|
|
313
|
-
clearTimeout(timer);
|
|
314
|
-
const how = exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;
|
|
315
|
-
throw new SpawnHostError(`spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`, "exited", tail, exit);
|
|
316
|
-
}
|
|
317
|
-
const record = aborted ? void 0 : ownRecords().at(0);
|
|
318
|
-
if (record) return {
|
|
319
|
-
pid: record.pid,
|
|
320
|
-
dataDir,
|
|
321
|
-
record,
|
|
322
|
-
outputs: record.outputs,
|
|
323
|
-
members: record.members,
|
|
324
|
-
exited,
|
|
325
|
-
stop
|
|
326
|
-
};
|
|
327
|
-
if (aborted || Date.now() >= deadline) {
|
|
328
|
-
const phase = aborted ? "aborted" : "timeout";
|
|
329
|
-
const ended = tail === "" || tail.endsWith("\n") ? "" : "\n";
|
|
330
|
-
const ran = `${tail}${ended}${SPAWN_STOPPING_NOTE}\n`;
|
|
331
|
-
tail = "";
|
|
332
|
-
const stopped = await stop();
|
|
333
|
-
let timer;
|
|
334
|
-
await Promise.race([closed, new Promise((resolve) => {
|
|
335
|
-
timer = setTimeout(resolve, CLOSE_WAIT_MS);
|
|
336
|
-
})]);
|
|
337
|
-
clearTimeout(timer);
|
|
338
|
-
throw new SpawnHostError(phase === "aborted" ? `spawnHost: aborted before ph run ${options.host} was ready.` : `spawnHost: ph run ${options.host} wrote no run record within ${readyTimeoutMs} ms.`, phase, ran + tail, stopped);
|
|
339
|
-
}
|
|
340
|
-
await Promise.race([sleep(POLL_MS), exited]);
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
//#endregion
|
|
344
10
|
//#region src/check-host.ts
|
|
345
|
-
/** The `ph run` pipeline up to the verb, collecting every issue; starts
|
|
11
|
+
/** The `ph run` pipeline up to the verb, collecting every issue; starts
|
|
12
|
+
* nothing. `name` is a ref: a project host, or `<package>/<host>`. */
|
|
346
13
|
async function checkHost(name, options) {
|
|
347
14
|
const result = {
|
|
348
15
|
issues: [],
|
|
349
16
|
warnings: [],
|
|
350
17
|
deferred: []
|
|
351
18
|
};
|
|
352
|
-
|
|
353
|
-
const issue = issuer(result, file);
|
|
19
|
+
let file = `hosts/${name}/host.js`;
|
|
354
20
|
const verb = options.verb ?? "run";
|
|
355
21
|
let host;
|
|
356
22
|
let runner;
|
|
23
|
+
let hostPackage;
|
|
357
24
|
try {
|
|
358
|
-
|
|
359
|
-
|
|
25
|
+
const loaded = await loadHost(options.projectRoot, name);
|
|
26
|
+
host = loaded.host;
|
|
27
|
+
hostPackage = loaded.package;
|
|
28
|
+
file = hostFileLabel(loaded.name, hostPackage);
|
|
29
|
+
runner = await resolveRunnerModule(moduleRootOf(options.projectRoot, loaded), host.runner.module);
|
|
360
30
|
} catch (error) {
|
|
361
|
-
|
|
31
|
+
issuer(result, file)("load", "", error);
|
|
362
32
|
return result;
|
|
363
33
|
}
|
|
364
34
|
const specifier = host.runner.module;
|
|
35
|
+
if (hostPackage && ONE_SHOT_VERBS.has(verb)) {
|
|
36
|
+
issuer(result, file)("declared", packageBuildRefusal(name, hostPackage, verb));
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
365
39
|
if (runner.kind === "compound") {
|
|
366
40
|
await checkCompound(result, options, {
|
|
367
41
|
file,
|
|
368
42
|
host,
|
|
369
43
|
runner,
|
|
370
44
|
specifier,
|
|
371
|
-
verb
|
|
45
|
+
verb,
|
|
46
|
+
hostPackage
|
|
372
47
|
});
|
|
373
48
|
return result;
|
|
374
49
|
}
|
|
375
50
|
const refs = outputRefsOf(host);
|
|
376
|
-
const producers = await loadProducers(options.projectRoot, refs);
|
|
51
|
+
const producers = await loadProducers(options.projectRoot, refs, hostPackage);
|
|
377
52
|
await checkSubject(result, options, {
|
|
378
53
|
file,
|
|
379
54
|
host,
|
|
380
55
|
runner,
|
|
381
56
|
specifier,
|
|
382
57
|
verb,
|
|
58
|
+
hostPackage,
|
|
383
59
|
outputsSchemaOf: producerOutputsSchemas(producers),
|
|
384
60
|
self: "outputs"
|
|
385
61
|
});
|
|
@@ -415,7 +91,7 @@ async function checkSubject(result, options, subject) {
|
|
|
415
91
|
const issue = issuer(result, subject.file);
|
|
416
92
|
const { runner, specifier, file } = subject;
|
|
417
93
|
const declared = checkDeclared(result, subject, subject.outputsSchemaOf);
|
|
418
|
-
const resolveEnv = processResolveEnv(options.projectRoot, options.env);
|
|
94
|
+
const resolveEnv = processResolveEnv(options.projectRoot, options.env, subject.hostPackage);
|
|
419
95
|
const patch = subject.patch ?? ((host) => host);
|
|
420
96
|
if (ONE_SHOT_VERBS.has(subject.verb)) {
|
|
421
97
|
if (!declared.tokens || !declared.shape) return;
|
|
@@ -491,16 +167,27 @@ async function checkCompound(result, options, subject) {
|
|
|
491
167
|
const verb = compoundStartVerb(subject.verb, host.runner);
|
|
492
168
|
const prepared = [];
|
|
493
169
|
for (const [key, member] of Object.entries(children)) try {
|
|
494
|
-
prepared.push(await prepareMember(options.projectRoot, key, member));
|
|
170
|
+
prepared.push(await prepareMember(options.projectRoot, key, member, subject.hostPackage));
|
|
495
171
|
} catch (error) {
|
|
496
172
|
issuer(result, `hosts/${member.host}/host.js`)("load", "", error);
|
|
497
173
|
}
|
|
174
|
+
try {
|
|
175
|
+
const cycle = await memberCycle(options.projectRoot, prepared);
|
|
176
|
+
if (cycle) issue("declared", {
|
|
177
|
+
path: "children",
|
|
178
|
+
message: `compound member cycle: ${cycle.join(" -> ")}.`,
|
|
179
|
+
hint: "A compound cannot run itself, directly or through another compound."
|
|
180
|
+
});
|
|
181
|
+
} catch (error) {
|
|
182
|
+
issue("load", "children", error);
|
|
183
|
+
}
|
|
498
184
|
const members = Object.entries(children).map(([key, m]) => ({
|
|
499
185
|
key,
|
|
500
186
|
host: m.host
|
|
501
187
|
}));
|
|
188
|
+
let foreground;
|
|
502
189
|
if (prepared.length === members.length) try {
|
|
503
|
-
planCompound(prepared.map((m) => ({
|
|
190
|
+
const plan = planCompound(prepared.map((m) => ({
|
|
504
191
|
key: m.key,
|
|
505
192
|
host: m.member.host,
|
|
506
193
|
refs: outputSitesOf(m.draft).map(({ ref, path }) => ({
|
|
@@ -508,6 +195,9 @@ async function checkCompound(result, options, subject) {
|
|
|
508
195
|
path
|
|
509
196
|
}))
|
|
510
197
|
})), wiring.startOrder);
|
|
198
|
+
const planned = planForeground(prepared, plan, wiring);
|
|
199
|
+
for (const i of planned.issues) issue("declared", i);
|
|
200
|
+
foreground = planned.foreground;
|
|
511
201
|
} catch (error) {
|
|
512
202
|
issue("declared", "", error);
|
|
513
203
|
}
|
|
@@ -520,13 +210,23 @@ async function checkCompound(result, options, subject) {
|
|
|
520
210
|
return producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member "${target.key}"`) : { error: `names member "${target.key}", which was not prepared.` };
|
|
521
211
|
};
|
|
522
212
|
for (const m of prepared) {
|
|
213
|
+
const isForeground = m.key === foreground;
|
|
214
|
+
if (isForeground && ONE_SHOT_VERBS.has(verb)) continue;
|
|
215
|
+
if (m.hostPackage && ONE_SHOT_VERBS.has(verb)) {
|
|
216
|
+
issue("declared", {
|
|
217
|
+
...packageBuildRefusal(m.ref, m.hostPackage, verb),
|
|
218
|
+
path: `children.${m.key}`
|
|
219
|
+
});
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
523
222
|
const csp = wiring.cspRegistrySync === true && takesCspRegistrySync(m);
|
|
524
223
|
await checkSubject(result, options, {
|
|
525
224
|
file: m.file,
|
|
526
225
|
host: m.draft,
|
|
527
226
|
runner: m.runner,
|
|
528
227
|
specifier: m.specifier,
|
|
529
|
-
|
|
228
|
+
...m.hostPackage ? { hostPackage: m.hostPackage } : {},
|
|
229
|
+
verb: isForeground ? m.draft.runner.defaultVerb ?? "run" : memberVerbOf(verb, m.draft.runner),
|
|
530
230
|
outputsSchemaOf,
|
|
531
231
|
self: { members },
|
|
532
232
|
...csp ? { patch: (resolved) => ({
|
|
@@ -915,7 +615,6 @@ function reactorBlockToSwitchboardConfig(reactor) {
|
|
|
915
615
|
};
|
|
916
616
|
if (reactor?.protocol) layer.protocol = reactor.protocol;
|
|
917
617
|
if (backend?.packages?.dynamic) layer.packages = { dynamic: true };
|
|
918
|
-
if (reactor?.workflows !== void 0) layer.features = { workflows: reactor.workflows };
|
|
919
618
|
return layer;
|
|
920
619
|
}
|
|
921
620
|
const LOCAL_BACKEND_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
|
|
@@ -933,8 +632,7 @@ function browserBackend(reactor) {
|
|
|
933
632
|
* - remote backend(s) only -> `remote`
|
|
934
633
|
* - a worker backend -> `worker`
|
|
935
634
|
* - anything else local -> `in-process`
|
|
936
|
-
* `undefined` when no backends are declared
|
|
937
|
-
* legacy reactorWorker/multiReactor behaviour untouched.
|
|
635
|
+
* `undefined` when no backends are declared: Connect then runs `in-process`.
|
|
938
636
|
*/
|
|
939
637
|
function reactorClientMode(reactor) {
|
|
940
638
|
const backends = reactor?.backends;
|
|
@@ -975,8 +673,7 @@ function unservedConnectStorage(reactor) {
|
|
|
975
673
|
* connect.reactor (same shape), backend topology → instance.reactorWorker
|
|
976
674
|
* (the browser reactor's kind), instance.reactorClient, instance.storage
|
|
977
675
|
* (the browser reactor's store), and with a
|
|
978
|
-
* switchboard instance.remoteBackends and instance.router
|
|
979
|
-
* app.workflowsEnabled. */
|
|
676
|
+
* switchboard instance.remoteBackends and instance.router. */
|
|
980
677
|
function projectReactorToConnect(reactor) {
|
|
981
678
|
const connect = {};
|
|
982
679
|
if (reactor?.protocol) connect.reactor = reactor.protocol;
|
|
@@ -995,7 +692,6 @@ function projectReactorToConnect(reactor) {
|
|
|
995
692
|
...router ? { router } : {}
|
|
996
693
|
};
|
|
997
694
|
}
|
|
998
|
-
if (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };
|
|
999
695
|
return { connect };
|
|
1000
696
|
}
|
|
1001
697
|
/** Whether an env value means what the host's value does. The switchboard
|
|
@@ -1271,6 +967,6 @@ function expectHost(input) {
|
|
|
1271
967
|
return expectation;
|
|
1272
968
|
}
|
|
1273
969
|
//#endregion
|
|
1274
|
-
export { BUILTIN_ENV_NAMES, CONNECT_PLUGIN_OWNED_SLICES, CONNECT_PRIMARY_MESSAGE, CONNECT_RUNNER, HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE, HOST_NAME_PATTERN, HostLoadError, ONE_SHOT_VERBS, ORIGIN_PLACEHOLDER, OUTPUTS_FILE, OUTPUT_DATA_DIRS_ENV, PlanError, PluginError, RunnerError, SPAWN_STOPPING_NOTE, STOP_RUN_TIMEOUT_MS, STORE_VERBS, SWITCHBOARD_PROXY_PATHS, SpawnHostError, TOKEN_ESCAPE_KEY, TOKEN_KEYS, TokenResolutionError, applyChildWrapper, askToStop, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, browserBackend, buildDriveDeclarationSchema, checkHost, checkOutputPaths, checkRunnerArgv, checkTokenSites, childWrapperSchema, childrenSchema, clearRunRecord, collectTokenSites, compoundHostSchema, compoundOutputSource, compoundWiringSchema, computeOutputsHash, concatTokenSchema, connectReactorIssues, declaredGenericCompoundHostSchema, declaredHostSchemas, defaultConnectComposition, defaultUserDataDir, defineHostSchemas, describeHostOutputs, describeMapElements, describeToken, driveAddressMessage, driveDeclarationSchema, drivesSchema, emitHostJsonSchema, emittedHostSchemas, emptyMaps, entryActiveForVerb, envSitesOf, envTokenSchema, envTokenable, expectHost, explainDrivePlan, exportHost, findDeadConnectConfig, findNonStaticValue, findRemovedForms, findToken, forbidRef, formatPath, genericCompoundHostSchema, getVerb, hostExportSchema, hostNameSchema, hostSchemaIssues, hostTypeSatisfies, installStopChannel, isBuiltinEnvName, isHtmlNavigation, isOriginPlaceholderUrl, isPidAlive, isRunnerArgsSchema, isSchemaLike, isStructuralMultiReactor, isSwitchboardProxyPath, isToken, itemTokenSchema, keyTokenSchema, kindShapeIssues, knownVerbIssues, lintHostImportGraph, lintHostImports, lintOutputsFile, listRunRecords, listVerbs, listenForStop, loadHost, loadProducers, makeHostSchemas, mapTokenSchema, memberForRef, mergeContributions, mergeDefaultDrives, mergeDrivePlan, normalizePluginEntries, normalizePluginEntry, originOrUrlSchema, outputRefsOf, outputSitesOf, outputTokenSchema, placeConnectDrives, placementKeyIssues, planCompound, pluginEntryObjectSchema, pluginEntrySchema, primaryBackend, probeHostsFolder, probeRun, processResolveEnv, producerOutputsSchemas, profileSchema, projectDriveId, projectDriveIdWith, projectDrivesIntoConnect, projectReactorToConnect, protocolConflicts, protocolEnv, protocolEnvAgrees, reactorBackendKindSchema, reactorBackendSchema, reactorBlockToSwitchboardConfig, reactorClientMode, reactorHostSchema, reactorProtocolSchema, reactorSchema, readOutputsFileHash, readProjectName, readRunRecord, rebaseDriveUrl, ref, refKey, refineConnectReactor, refineStartOrder, registerHostType, remoteBackendUrls, remoteBackends, renderTokens, requestStop, resolveDriveDeclaration, resolveHostOutputs, resolveHostPlugins, resolveOrder, resolveOriginPlaceholders, resolvePluginContributions, resolveRunnerModule, resolveUserDataPlaceholders, runCompound, runObserveHook, runObserveHookSequential, runProvideHook, runRecordMemberSchema, runRecordOutputSource, runRecordSchema, runTransformHook, runnerBaseSchema, runnerHandleSchema, runnerKindSchema, runnerOutputsSchema, scanHostImports, schemaAtPath, seedDrives, spawnHost, splitCompoundArgv, splitRunArgv, stopChannelPath, stopRun, stripComments, substituteBuiltinEnv, switchboardOfDrive, toOriginPlaceholder, toStartedHandle, tokenKeyOf, tokenSchema, tokenable, unservedConnectStorage, unwrapEscapes, validateDeclaredHost, validateHost, withOriginPlaceholders, writeRunRecord };
|
|
970
|
+
export { BUILTIN_ENV_NAMES, COMPOUND_MEMBER_ENV, CONNECT_PLUGIN_OWNED_SLICES, CONNECT_PRIMARY_MESSAGE, CONNECT_RUNNER, HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE, HOST_NAME_PATTERN, HOST_REF_MESSAGE, HOST_REF_PATTERN, HostLoadError, ONE_SHOT_VERBS, ORIGIN_PLACEHOLDER, OUTPUTS_FILE, OUTPUT_DATA_DIRS_ENV, PACKAGE_NAME_PATTERN, PlanError, PluginError, RunnerError, SPAWN_STOPPING_NOTE, STOP_ON_STDIN_ENV, STOP_RUN_TIMEOUT_MS, STOP_STREAM_LIMIT_MS, STORE_VERBS, SWITCHBOARD_PROXY_PATHS, SpawnHostError, TOKEN_ESCAPE_KEY, TOKEN_KEYS, TokenResolutionError, applyChildWrapper, askToStop, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, browserBackend, buildDriveDeclarationSchema, checkHost, checkOutputPaths, checkRunnerArgv, checkTokenSites, childWrapperSchema, childrenSchema, clearRunRecord, collectTokenSites, compoundHostSchema, compoundOutputSource, compoundWiringSchema, computeOutputsHash, concatTokenSchema, connectReactorIssues, declaredGenericCompoundHostSchema, declaredHostSchemas, defaultConnectComposition, defaultUserDataDir, defineHostSchemas, describeHostOutputs, describeMapElements, describeToken, driveAddressMessage, driveDeclarationSchema, drivesSchema, emitHostJsonSchema, emittedHostSchemas, emptyMaps, entryActiveForVerb, envSitesOf, envTokenSchema, envTokenable, expectHost, explainDrivePlan, exportHost, findDeadConnectConfig, findHostPackage, findNonStaticValue, findRemovedForms, findToken, forbidRef, formatHostRef, formatPath, genericCompoundHostSchema, getVerb, holdStopRequests, hostExportSchema, hostFileLabel, hostNameSchema, hostSchemaIssues, hostTypeSatisfies, installStopChannel, isBuiltinEnvName, isHtmlNavigation, isOriginPlaceholderUrl, isPidAlive, isRunnerArgsSchema, isSchemaLike, isStructuralMultiReactor, isSwitchboardProxyPath, isToken, itemTokenSchema, keyTokenSchema, killTree, kindShapeIssues, knownVerbIssues, lintHostImportGraph, lintHostImports, lintOutputsFile, listRunRecords, listVerbs, listenForStop, loadHost, loadHostFresh, loadProducers, locateHost, makeHostSchemas, mapTokenSchema, memberCycle, memberForRef, memberProcessOf, memberProcessSchema, mergeContributions, mergeDefaultDrives, mergeDrivePlan, moduleRootOf, normalizePluginEntries, normalizePluginEntry, originOrUrlSchema, outputRefsOf, outputSitesOf, outputTokenSchema, packageBuildRefusal, parseHostRef, placeConnectDrives, placementKeyIssues, planCompound, planForeground, pluginEntryObjectSchema, pluginEntrySchema, primaryBackend, probeHostsFolder, probeRun, processResolveEnv, producerOutputsSchemas, profileSchema, projectDriveId, projectDriveIdWith, projectDrivesIntoConnect, projectReactorToConnect, protocolConflicts, protocolEnv, protocolEnvAgrees, reactorBackendKindSchema, reactorBackendSchema, reactorBlockToSwitchboardConfig, reactorClientMode, reactorHostSchema, reactorProtocolSchema, reactorSchema, readOutputsFileHash, readProjectName, readRunRecord, rebaseDriveUrl, recordKeyOf, ref, refKey, refineConnectReactor, refineStartOrder, registerHostType, remoteBackendUrls, remoteBackends, renderTokens, requestStop, resolveDriveDeclaration, resolveHostOutputs, resolveHostPlugins, resolveOrder, resolveOriginPlaceholders, resolvePackageRoot, resolvePluginContributions, resolveRunnerModule, resolveUserDataPlaceholders, runCompound, runObserveHook, runObserveHookSequential, runProvideHook, runRecordKey, runRecordMemberSchema, runRecordOutputSource, runRecordSchema, runTransformHook, runnerBaseSchema, runnerHandleSchema, runnerKindSchema, runnerOutputsSchema, scanHostImports, schemaAtPath, seedDrives, spawnHost, splitCompoundArgv, splitRunArgv, stopChannelPath, stopRun, stopStreamOf, stripComments, substituteBuiltinEnv, switchboardOfDrive, takeCompoundMember, toOriginPlaceholder, toStartedHandle, tokenKeyOf, tokenSchema, tokenable, unservedConnectStorage, unwrapEscapes, validateDeclaredHost, validateHost, withOriginPlaceholders, withoutHostsMessage, writeRunRecord };
|
|
1275
971
|
|
|
1276
972
|
//# sourceMappingURL=index.mjs.map
|