@powerhousedao/host-core 6.2.3-dev.73 → 6.2.3-dev.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,457 @@
1
- import { $ as envSitesOf, $t as PluginError, A as probeHostsFolder, At as driveDeclarationSchema, B as resolveRunnerModule, Bt as isToken, C as computeOutputsHash, Ct as reactorHostSchema, D as lintHostImports, Dt as runnerBaseSchema, E as lintHostImportGraph, Et as refineStartOrder, F as ONE_SHOT_VERBS, Ft as concatTokenSchema, G as resolveHostOutputs, Gt as ref, H as validateHost, Ht as keyTokenSchema, I as RunnerError, It as envTokenSchema, J as planCompound, Jt as tokenable, K as PlanError, Kt as tokenKeyOf, L as getVerb, Lt as envTokenable, M as scanHostImports, Mt as projectDriveIdWith, N as stripComments, Nt as TOKEN_ESCAPE_KEY, O as lintOutputsFile, Ot as runnerKindSchema, P as CONNECT_RUNNER, Pt as TOKEN_KEYS, Q as checkTokenSites, Qt as resolvePluginContributions, R as isSchemaLike, Rt as findToken, S as OUTPUTS_FILE, St as reactorBackendSchema, T as findNonStaticValue, Tt as reactorSchema, U as TokenResolutionError, Ut as mapTokenSchema, V as validateDeclaredHost, Vt as itemTokenSchema, W as describeMapElements, Wt as outputTokenSchema, X as findRemovedForms, Xt as findDeadConnectConfig, Y as substituteBuiltinEnv, Yt as CONNECT_PLUGIN_OWNED_SLICES, Z as checkOutputPaths, Zt as resolveHostPlugins, _ as readRunRecord, _t as emittedHostSchemas, a as loadProducers, an as pluginEntryObjectSchema, at as describeToken, b as runRecordSchema, bt as profileSchema, c as runRecordOutputSource, cn as resolveOrder, ct as unwrapEscapes, d as resolveUserDataPlaceholders, dn as runProvideHook, dt as compoundHostSchema, en as entryActiveForVerb, et as outputRefsOf, f as clearRunRecord, fn as runTransformHook, ft as compoundWiringSchema, g as readProjectName, gt as emitHostJsonSchema, h as probeRun, ht as defineHostSchemas, i as compoundOutputSource, in as normalizePluginEntry, it as collectTokenSites, j as readOutputsFileHash, jt as drivesSchema, k as loadHost, kt as buildDriveDeclarationSchema, l as runnerOutputsSchema, ln as runObserveHook, lt as childWrapperSchema, m as listRunRecords, mt as declaredHostSchemas, n as runnerHandleSchema, nn as mergeContributions, nt as refKey, o as processResolveEnv, on as pluginEntrySchema, ot as formatPath, p as isPidAlive, pt as declaredGenericCompoundHostSchema, q as memberForRef, qt as tokenSchema, r as toStartedHandle, rn as normalizePluginEntries, rt as schemaAtPath, s as producerOutputsSchemas, sn as registerHostType, st as renderTokens, t as runCompound, tn as hostTypeSatisfies, tt as outputSitesOf, u as defaultUserDataDir, un as runObserveHookSequential, ut as childrenSchema, v as writeRunRecord, vt as genericCompoundHostSchema, w as describeHostOutputs, wt as reactorProtocolSchema, x as HostLoadError, xt as reactorBackendKindSchema, y as runRecordMemberSchema, yt as makeHostSchemas, z as listVerbs, zt as forbidRef } from "./compound-B6RZMA0Y.mjs";
1
+ import { $ as unsetEnvMessage, $t as keyTokenSchema, A as lintHostImportGraph, At as makeHostSchemas, B as RunnerError, Bt as buildDriveDeclarationSchema, C as runRecordMemberSchema, Cn as runTransformHook, Ct as compoundWiringSchema, D as computeOutputsHash, Dt as emitHostJsonSchema, E as OUTPUTS_FILE, Et as defineHostSchemas, F as readOutputsFileHash, Ft as reactorProtocolSchema, G as knownVerbIssues, Gt as TOKEN_KEYS, H as hostSchemaIssues, Ht as drivesSchema, I as scanHostImports, It as reactorSchema, J as validateDeclaredHost, Jt as envTokenable, K as listVerbs, Kt as concatTokenSchema, L as stripComments, Lt as refineStartOrder, M as lintOutputsFile, Mt as reactorBackendKindSchema, N as loadHost, Nt as reactorBackendSchema, O as describeHostOutputs, Ot as emittedHostSchemas, P as probeHostsFolder, Pt as reactorHostSchema, Q as resolveHostOutputs, Qt as itemTokenSchema, R as CONNECT_RUNNER, Rt as runnerBaseSchema, S as writeRunRecord, Sn as runProvideHook, St as compoundHostSchema, T as HostLoadError, Tt as declaredHostSchemas, U as isSchemaLike, Ut as projectDriveIdWith, V as getVerb, Vt as driveDeclarationSchema, W as kindShapeIssues, Wt as TOKEN_ESCAPE_KEY, X as TokenResolutionError, Xt as forbidRef, Y as validateHost, Yt as findToken, Z as describeMapElements, Zt as isToken, _ as isPidAlive, _n as pluginEntrySchema, _t as isPlainObject, a as takesCspRegistrySync, an as tokenable, at as substituteBuiltinEnv, b as readProjectName, bn as runObserveHook, bt as childWrapperSchema, c as compoundOutputSource, cn as resolveHostPlugins, ct as checkTokenSites, d as producerOutputsSchemas, dn as entryActiveForVerb, dt as outputSitesOf, en as mapTokenSchema, et as PlanError, f as runRecordOutputSource, fn as hostTypeSatisfies, ft as refKey, g as clearRunRecord, gn as pluginEntryObjectSchema, gt as formatPath, h as resolveUserDataPlaceholders, hn as normalizePluginEntry, ht as describeToken, i as runCompound, in as tokenSchema, it as isBuiltinEnvName, j as lintHostImports, jt as profileSchema, k as findNonStaticValue, kt as genericCompoundHostSchema, l as loadProducers, ln as resolvePluginContributions, lt as envSitesOf, m as defaultUserDataDir, mn as normalizePluginEntries, mt as collectTokenSites, n as memberVerbOf, nn as ref, nt as planCompound, o as runnerHandleSchema, on as CONNECT_PLUGIN_OWNED_SLICES, ot as findRemovedForms, p as runnerOutputsSchema, pn as mergeContributions, pt as schemaAtPath, q as resolveRunnerModule, qt as envTokenSchema, r as prepareMember, rn as tokenKeyOf, rt as BUILTIN_ENV_NAMES, s as toStartedHandle, sn as findDeadConnectConfig, st as checkOutputPaths, t as compoundStartVerb, tn as outputTokenSchema, tt as memberForRef, u as processResolveEnv, un as PluginError, ut as outputRefsOf, v as listRunRecords, vn as registerHostType, vt as renderTokens, w as runRecordSchema, wt as declaredGenericCompoundHostSchema, x as readRunRecord, xn as runObserveHookSequential, xt as childrenSchema, y as probeRun, yn as resolveOrder, yt as unwrapEscapes, z as ONE_SHOT_VERBS, zt as runnerKindSchema } from "./compound-Gjt5rBfF.mjs";
2
+ import { createRequire } from "node:module";
2
3
  import crypto from "node:crypto";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { spawn } from "node:child_process";
3
8
  import { DRIVE_ICON_MAX_BYTES, resolveImageRef } from "@powerhousedao/shared/connect/image-ref";
9
+ //#region src/spawn-host.ts
10
+ var SpawnHostError = class extends Error {
11
+ phase;
12
+ outputTail;
13
+ exit;
14
+ constructor(message, phase, outputTail, exit) {
15
+ super(outputTail ? `${message}\n--- output tail ---\n${outputTail}` : message);
16
+ this.phase = phase;
17
+ this.outputTail = outputTail;
18
+ this.exit = exit;
19
+ this.name = "SpawnHostError";
20
+ }
21
+ };
22
+ const READY_TIMEOUT_MS = 12e4;
23
+ const STOP_TIMEOUT_MS = 3e4;
24
+ const POLL_MS = 100;
25
+ const CLOSE_WAIT_MS = 1e3;
26
+ const BASE_ENV_KEYS = [
27
+ "PATH",
28
+ "HOME",
29
+ "TMPDIR"
30
+ ];
31
+ const WIN32_ENV_KEYS = [
32
+ "SystemRoot",
33
+ "USERPROFILE",
34
+ "APPDATA",
35
+ "LOCALAPPDATA",
36
+ "TEMP",
37
+ "TMP",
38
+ "ComSpec",
39
+ "PATHEXT"
40
+ ];
41
+ /** The child's whole env: no other `process.env` key reaches it. */
42
+ function childEnv(dataDir, env = {}) {
43
+ if ("PH_USER_DATA_DIR" in env) throw new Error("spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.");
44
+ const keys = process.platform === "win32" ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS] : BASE_ENV_KEYS;
45
+ const base = {};
46
+ for (const key of keys) {
47
+ const value = process.env[key];
48
+ if (value !== void 0) base[key] = value;
49
+ }
50
+ return {
51
+ ...base,
52
+ FEATURE_UNIFORM_RUNNERS_ENABLED: "1",
53
+ PH_USER_DATA_DIR: dataDir,
54
+ PH_NO_TELEMETRY: "1",
55
+ PH_NO_DOTENV: "1",
56
+ ...env
57
+ };
58
+ }
59
+ function resolvePhCliEntry(projectRoot) {
60
+ const pkgPath = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href).resolve("@powerhousedao/ph-cli/package.json");
61
+ return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
62
+ }
63
+ /** Readiness waits for a record; refuse a host/verb that writes none. */
64
+ async function assertWritesRecord(projectRoot, host, verb) {
65
+ if (verb !== void 0 && ONE_SHOT_VERBS.has(verb)) throw new Error(`spawnHost: "${verb}" is a one-shot verb; it writes no run record to wait for.`);
66
+ const loaded = await loadHost(projectRoot, host);
67
+ const specifier = loaded.host.runner.module;
68
+ const runner = await resolveRunnerModule(projectRoot, specifier);
69
+ if (runner.kind === "compound") {
70
+ 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.`);
71
+ return;
72
+ }
73
+ 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.`);
74
+ }
75
+ const sleep = (ms) => new Promise((resolve) => {
76
+ setTimeout(resolve, ms).unref();
77
+ });
78
+ const live = /* @__PURE__ */ new Set();
79
+ let exitHookInstalled = false;
80
+ function track(child) {
81
+ live.add(child);
82
+ child.once("exit", () => live.delete(child));
83
+ if (exitHookInstalled) return;
84
+ exitHookInstalled = true;
85
+ process.once("exit", () => {
86
+ for (const running of live) running.kill("SIGTERM");
87
+ });
88
+ }
89
+ /**
90
+ * `ph run <host> [verb]` as a child; ready when its run record appears.
91
+ *
92
+ * The child shares this process's group, so a terminal Ctrl-C reaches both.
93
+ * It runs the project's own ph-cli: one older than PH_NO_DOTENV reads the
94
+ * project's `.env` anyway.
95
+ */
96
+ async function spawnHost(options) {
97
+ const projectRoot = path.resolve(options.projectRoot);
98
+ const dataDir = path.resolve(options.dataDir);
99
+ const env = childEnv(dataDir, options.env);
100
+ const readerEnv = { PH_USER_DATA_DIR: dataDir };
101
+ const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;
102
+ const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;
103
+ const { signal } = options;
104
+ if (signal?.aborted) throw new SpawnHostError("spawnHost: aborted before start.", "aborted", "");
105
+ await assertWritesRecord(projectRoot, options.host, options.verb);
106
+ const cli = options.cli ?? resolvePhCliEntry(projectRoot);
107
+ fs.mkdirSync(dataDir, { recursive: true });
108
+ const log = options.logFile ? fs.createWriteStream(options.logFile, { flags: "a" }) : void 0;
109
+ let tail = "";
110
+ log?.on("error", (error) => {
111
+ tail = (tail + `logFile: ${error.message}\n`).slice(-8192);
112
+ });
113
+ const args = [
114
+ cli,
115
+ "run",
116
+ options.host
117
+ ];
118
+ if (options.verb !== void 0) args.push(options.verb);
119
+ const child = spawn(process.execPath, args, {
120
+ cwd: projectRoot,
121
+ env,
122
+ stdio: [
123
+ "ignore",
124
+ "pipe",
125
+ "pipe"
126
+ ],
127
+ windowsHide: true
128
+ });
129
+ track(child);
130
+ const onChunk = (stream) => (chunk) => {
131
+ tail = (tail + chunk).slice(-8192);
132
+ log?.write(chunk);
133
+ try {
134
+ options.onOutput?.(stream, chunk);
135
+ } catch (error) {
136
+ const message = error instanceof Error ? error.message : String(error);
137
+ tail = (tail + `onOutput: ${message}\n`).slice(-8192);
138
+ }
139
+ };
140
+ child.stdout.setEncoding("utf8").on("data", onChunk("stdout"));
141
+ child.stderr.setEncoding("utf8").on("data", onChunk("stderr"));
142
+ let forced = false;
143
+ let exit;
144
+ const exited = new Promise((resolve) => {
145
+ const done = (code, sig) => {
146
+ if (exit) return;
147
+ exit = {
148
+ code,
149
+ signal: sig,
150
+ forced
151
+ };
152
+ signal?.removeEventListener("abort", onAbort);
153
+ resolve(exit);
154
+ };
155
+ child.once("exit", done);
156
+ child.once("error", (error) => {
157
+ tail = (tail + `${error.message}\n`).slice(-8192);
158
+ if (child.pid === void 0) done(null, null);
159
+ });
160
+ });
161
+ const closed = new Promise((resolve) => {
162
+ child.once("close", () => {
163
+ log?.end();
164
+ resolve();
165
+ });
166
+ });
167
+ const pid = child.pid;
168
+ const ownRecords = () => pid === void 0 ? [] : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);
169
+ const kill = (sig) => {
170
+ if (pid === void 0) return;
171
+ try {
172
+ process.kill(pid, sig);
173
+ } catch {}
174
+ };
175
+ const clearOwnRecords = () => {
176
+ for (const record of ownRecords()) clearRunRecord(projectRoot, record.host, readerEnv);
177
+ };
178
+ let stopping;
179
+ const stop = () => {
180
+ stopping ??= (async () => {
181
+ if (!exit) {
182
+ kill("SIGTERM");
183
+ let timer;
184
+ const timedOut = await Promise.race([exited.then(() => false), new Promise((resolve) => {
185
+ timer = setTimeout(() => resolve(true), stopTimeoutMs);
186
+ })]);
187
+ clearTimeout(timer);
188
+ if (timedOut) {
189
+ forced = true;
190
+ kill("SIGKILL");
191
+ }
192
+ }
193
+ const result = await exited;
194
+ clearOwnRecords();
195
+ return result;
196
+ })();
197
+ return stopping;
198
+ };
199
+ function onAbort() {
200
+ stop();
201
+ }
202
+ signal?.addEventListener("abort", onAbort, { once: true });
203
+ const deadline = Date.now() + readyTimeoutMs;
204
+ for (;;) {
205
+ const aborted = signal?.aborted ?? false;
206
+ if (exit && !aborted) {
207
+ clearOwnRecords();
208
+ let timer;
209
+ await Promise.race([closed, new Promise((resolve) => {
210
+ timer = setTimeout(resolve, CLOSE_WAIT_MS);
211
+ })]);
212
+ clearTimeout(timer);
213
+ const how = exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;
214
+ throw new SpawnHostError(`spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`, "exited", tail, exit);
215
+ }
216
+ const record = aborted ? void 0 : ownRecords().at(0);
217
+ if (record) return {
218
+ pid: record.pid,
219
+ dataDir,
220
+ record,
221
+ outputs: record.outputs,
222
+ members: record.members,
223
+ exited,
224
+ stop
225
+ };
226
+ if (aborted || Date.now() >= deadline) {
227
+ const phase = aborted ? "aborted" : "timeout";
228
+ const stopped = await stop();
229
+ 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, tail, stopped);
230
+ }
231
+ await Promise.race([sleep(POLL_MS), exited]);
232
+ }
233
+ }
234
+ //#endregion
235
+ //#region src/check-host.ts
236
+ /** The `ph run` pipeline up to the verb, collecting every issue; starts nothing. */
237
+ async function checkHost(name, options) {
238
+ const result = {
239
+ issues: [],
240
+ deferred: []
241
+ };
242
+ const file = `hosts/${name}/host.js`;
243
+ const issue = issuer(result, file);
244
+ const verb = options.verb ?? "run";
245
+ let host;
246
+ let runner;
247
+ try {
248
+ host = (await loadHost(options.projectRoot, name)).host;
249
+ runner = await resolveRunnerModule(options.projectRoot, host.runner.module);
250
+ } catch (error) {
251
+ issue("load", "", error);
252
+ return result;
253
+ }
254
+ const specifier = host.runner.module;
255
+ if (runner.kind === "compound") {
256
+ await checkCompound(result, options, {
257
+ file,
258
+ host,
259
+ runner,
260
+ specifier,
261
+ verb
262
+ });
263
+ return result;
264
+ }
265
+ const refs = outputRefsOf(host);
266
+ const producers = await loadProducers(options.projectRoot, refs);
267
+ await checkSubject(result, options, {
268
+ file,
269
+ host,
270
+ runner,
271
+ specifier,
272
+ verb,
273
+ outputsSchemaOf: producerOutputsSchemas(producers),
274
+ self: "outputs"
275
+ });
276
+ return result;
277
+ }
278
+ /** Declared validation; returns whether its tokens and its shape passed. */
279
+ function checkDeclared(result, subject, outputsSchemaOf) {
280
+ const issue = issuer(result, subject.file);
281
+ const { host, runner, specifier } = subject;
282
+ try {
283
+ getVerb(runner, specifier, subject.verb);
284
+ } catch (error) {
285
+ issue("declared", "", error);
286
+ }
287
+ const tokenIssues = [
288
+ ...findRemovedForms(host),
289
+ ...checkTokenSites(host),
290
+ ...outputsSchemaOf ? checkOutputPaths(host, outputsSchemaOf) : []
291
+ ];
292
+ for (const i of tokenIssues) issue("declared", i);
293
+ const shapeIssues = runner.declaredHostSchema ? schemaIssuesOf(runner, runner.declaredHostSchema, specifier, host, true) : kindShapeIssues(runner.kind, specifier, host);
294
+ for (const i of shapeIssues) issue("declared", i);
295
+ return {
296
+ tokens: tokenIssues.length === 0,
297
+ shape: shapeIssues.length === 0
298
+ };
299
+ }
300
+ function schemaIssuesOf(runner, schema, specifier, host, allowTokens) {
301
+ const checked = hostSchemaIssues(runner, schema, specifier, host, { tokens: allowTokens ? "allow" : "forbid" });
302
+ return [...checked.issues, ...checked.schemaIssues ?? []];
303
+ }
304
+ async function checkSubject(result, options, subject) {
305
+ const issue = issuer(result, subject.file);
306
+ const { runner, specifier, file } = subject;
307
+ const declared = checkDeclared(result, subject, subject.outputsSchemaOf);
308
+ const resolveEnv = processResolveEnv(options.projectRoot, options.env);
309
+ const patch = subject.patch ?? ((host) => host);
310
+ if (ONE_SHOT_VERBS.has(subject.verb)) {
311
+ if (!declared.tokens || !declared.shape) return;
312
+ const host = patch(substituteBuiltinEnv(subject.host, resolveEnv.builtins ?? {}));
313
+ const schema = runner.declaredHostSchema ?? runner.hostSchema;
314
+ for (const i of schemaIssuesOf(runner, schema, specifier, host, true)) issue("resolved", i);
315
+ return;
316
+ }
317
+ const unset = envSitesOf(subject.host).filter((site) => !site.optional && !isBuiltinEnvName(site.name) && options.env[site.name] === void 0);
318
+ for (const site of unset) issue("resolve", {
319
+ path: site.path,
320
+ message: unsetEnvMessage(site.name)
321
+ });
322
+ if (!declared.tokens || unset.length > 0) return;
323
+ let resolved;
324
+ let deferred = [];
325
+ try {
326
+ if (options.outputs) resolved = resolveHostOutputs(subject.host, {
327
+ outputs: options.outputs,
328
+ ...resolveEnv
329
+ });
330
+ else {
331
+ const partial = resolveHostOutputs(subject.host, resolveEnv, { deferSelf: subject.self });
332
+ resolved = partial.host;
333
+ deferred = partial.deferred;
334
+ }
335
+ } catch (error) {
336
+ if (error instanceof TokenResolutionError && error.detail) issue("resolve", {
337
+ path: error.detail.path,
338
+ message: error.detail.reason
339
+ });
340
+ else issue("resolve", "", error);
341
+ return;
342
+ }
343
+ result.deferred.push(...deferred.map((d) => ({
344
+ ...d,
345
+ file
346
+ })));
347
+ if (!declared.shape) return;
348
+ const allow = deferred.length > 0;
349
+ const schema = allow ? runner.declaredHostSchema ?? runner.hostSchema : runner.hostSchema;
350
+ const checked = hostSchemaIssues(runner, schema, specifier, patch(resolved), { tokens: allow ? "allow" : "forbid" });
351
+ const resolvedIssues = [...checked.issues, ...checked.schemaIssues ?? []];
352
+ for (const i of resolvedIssues) issue("resolved", i);
353
+ if (resolvedIssues.length > 0 || !runner.checkBoot) return;
354
+ try {
355
+ const boot = await runner.checkBoot(checked.data, {
356
+ projectRoot: options.projectRoot,
357
+ verb: subject.verb,
358
+ env: options.env,
359
+ file
360
+ });
361
+ for (const i of boot) issue("boot", {
362
+ ...i,
363
+ path: i.path ?? ""
364
+ });
365
+ } catch (error) {
366
+ issue("boot", "", error);
367
+ }
368
+ }
369
+ async function checkCompound(result, options, subject) {
370
+ const issue = issuer(result, subject.file);
371
+ const { host, runner, specifier } = subject;
372
+ const declared = checkDeclared(result, subject);
373
+ if (!declared.tokens || !declared.shape) return;
374
+ if (!runner.declaredHostSchema) {
375
+ const own = schemaIssuesOf(runner, runner.hostSchema, specifier, host, true);
376
+ for (const i of own) issue("resolved", i);
377
+ if (own.length > 0) return;
378
+ }
379
+ const children = isPlainObject(host.children) ? host.children : {};
380
+ const wiring = isPlainObject(host.config) ? host.config : {};
381
+ const verb = compoundStartVerb(subject.verb, host.runner);
382
+ const prepared = [];
383
+ for (const [key, member] of Object.entries(children)) try {
384
+ prepared.push(await prepareMember(options.projectRoot, key, member));
385
+ } catch (error) {
386
+ issuer(result, `hosts/${member.host}/host.js`)("load", "", error);
387
+ }
388
+ const members = Object.entries(children).map(([key, m]) => ({
389
+ key,
390
+ host: m.host
391
+ }));
392
+ if (prepared.length === members.length) try {
393
+ planCompound(prepared.map((m) => ({
394
+ key: m.key,
395
+ host: m.member.host,
396
+ refs: outputSitesOf(m.draft).map(({ ref, path }) => ({
397
+ ref,
398
+ path
399
+ }))
400
+ })), wiring.startOrder);
401
+ } catch (error) {
402
+ issue("declared", "", error);
403
+ }
404
+ const byKey = new Map(prepared.map((m) => [m.key, m]));
405
+ const outputsSchemaOf = (ref) => {
406
+ const target = memberForRef(ref, members);
407
+ if ("error" in target) return { error: target.error };
408
+ const producer = byKey.get(target.key);
409
+ return producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member "${target.key}"`) : { error: `names member "${target.key}", which was not prepared.` };
410
+ };
411
+ for (const m of prepared) {
412
+ const csp = wiring.cspRegistrySync === true && takesCspRegistrySync(m);
413
+ await checkSubject(result, options, {
414
+ file: m.file,
415
+ host: m.draft,
416
+ runner: m.runner,
417
+ specifier: m.specifier,
418
+ verb: memberVerbOf(verb, m.draft.runner),
419
+ outputsSchemaOf,
420
+ self: { members },
421
+ ...csp ? { patch: (resolved) => ({
422
+ ...resolved,
423
+ runner: {
424
+ ...resolved.runner,
425
+ cspRegistrySync: true
426
+ }
427
+ }) } : {}
428
+ });
429
+ }
430
+ }
431
+ function issuer(result, file) {
432
+ return (stage, found, error) => {
433
+ if (typeof found !== "string") {
434
+ const { path, message, hint } = found;
435
+ result.issues.push({
436
+ stage,
437
+ file,
438
+ path,
439
+ message,
440
+ ...hint ? { hint } : {}
441
+ });
442
+ return;
443
+ }
444
+ const [message, hint] = (error instanceof Error ? error.message : String(error)).split("\n Hint: ");
445
+ result.issues.push({
446
+ stage,
447
+ file,
448
+ path: found,
449
+ message,
450
+ ...hint ? { hint } : {}
451
+ });
452
+ };
453
+ }
454
+ //#endregion
4
455
  //#region src/drives.ts
5
456
  const sha256Hex = (input) => crypto.createHash("sha256").update(input).digest("hex");
6
457
  function projectDriveId(projectRoot, slug) {
@@ -168,20 +619,27 @@ function projectReactorToConnect(reactor) {
168
619
  if (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };
169
620
  return { connect };
170
621
  }
622
+ /** Each pre-set env var that CONTRADICTS the host's protocol block, as a
623
+ * message naming the var, the host value and the env value. An env var that
624
+ * merely matches, or is unset, is fine. */
625
+ function protocolConflicts(protocol, env, hostFile = "the host file") {
626
+ if (!protocol) return [];
627
+ return Object.entries(protocolEnv(protocol)).flatMap(([varName, hostValue]) => {
628
+ const envValue = env[varName];
629
+ if (envValue === void 0 || envValue === hostValue) return [];
630
+ return [`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`];
631
+ });
632
+ }
171
633
  /**
172
634
  * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS
173
635
  * the host's protocol block, fail loudly naming the var, the host value, and
174
- * the env value. An env var that merely matches, or is unset, is fine (phase-2
175
- * transition keeps an operator's explicit env as an escape hatch unless it
176
- * disagrees with the protocol — see the WBS precedence note).
636
+ * the env value (phase-2 transition keeps an operator's explicit env as an
637
+ * escape hatch unless it disagrees with the protocol — see the WBS
638
+ * precedence note).
177
639
  */
178
640
  function assertProtocolConsistency(protocol, env, hostFile = "the host file") {
179
- if (!protocol) return;
180
- const expected = protocolEnv(protocol);
181
- for (const [varName, hostValue] of Object.entries(expected)) {
182
- const envValue = env[varName];
183
- if (envValue !== void 0 && envValue !== hostValue) throw new Error(`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`);
184
- }
641
+ const conflict = protocolConflicts(protocol, env, hostFile).at(0);
642
+ if (conflict) throw new Error(conflict);
185
643
  }
186
644
  //#endregion
187
645
  //#region src/backend-projection.ts
@@ -446,6 +904,6 @@ function expectHost(input) {
446
904
  return expectation;
447
905
  }
448
906
  //#endregion
449
- export { CONNECT_PLUGIN_OWNED_SLICES, CONNECT_RUNNER, HostLoadError, ONE_SHOT_VERBS, OUTPUTS_FILE, PlanError, PluginError, RunnerError, TOKEN_ESCAPE_KEY, TOKEN_KEYS, TokenResolutionError, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, buildDriveDeclarationSchema, checkOutputPaths, checkTokenSites, childWrapperSchema, childrenSchema, clearRunRecord, collectTokenSites, compoundHostSchema, compoundOutputSource, compoundWiringSchema, computeOutputsHash, concatTokenSchema, declaredGenericCompoundHostSchema, declaredHostSchemas, defaultUserDataDir, defineHostSchemas, describeHostOutputs, describeMapElements, describeToken, driveDeclarationSchema, drivesSchema, emitHostJsonSchema, emittedHostSchemas, entryActiveForVerb, envSitesOf, envTokenSchema, envTokenable, expectHost, explainDrivePlan, findDeadConnectConfig, findNonStaticValue, findRemovedForms, findToken, forbidRef, formatPath, genericCompoundHostSchema, getVerb, hostTypeSatisfies, isPidAlive, isSchemaLike, isStructuralMultiReactor, isToken, itemTokenSchema, keyTokenSchema, lintHostImportGraph, lintHostImports, lintOutputsFile, listRunRecords, listVerbs, loadHost, loadProducers, makeHostSchemas, mapTokenSchema, memberForRef, mergeContributions, mergeDefaultDrives, mergeDrivePlan, normalizePluginEntries, normalizePluginEntry, outputRefsOf, outputSitesOf, outputTokenSchema, planCompound, pluginEntryObjectSchema, pluginEntrySchema, primaryBackend, probeHostsFolder, probeRun, processResolveEnv, producerOutputsSchemas, profileSchema, projectDriveId, projectDriveIdWith, projectDrivesIntoConnect, projectReactorToConnect, projectReactorToSwitchboard, protocolEnv, reactorBackendKindSchema, reactorBackendSchema, reactorClientMode, reactorHostSchema, reactorProtocolSchema, reactorSchema, readOutputsFileHash, readProjectName, readRunRecord, rebaseDriveUrl, ref, refKey, refineStartOrder, registerHostType, remoteBackendUrls, renderTokens, resolveDriveDeclaration, resolveHostOutputs, resolveHostPlugins, resolveOrder, resolvePluginContributions, resolveRunnerModule, resolveUserDataPlaceholders, runCompound, runObserveHook, runObserveHookSequential, runProvideHook, runRecordMemberSchema, runRecordOutputSource, runRecordSchema, runTransformHook, runnerBaseSchema, runnerHandleSchema, runnerKindSchema, runnerOutputsSchema, scanHostImports, schemaAtPath, seedDrives, stripComments, substituteBuiltinEnv, toStartedHandle, tokenKeyOf, tokenSchema, tokenable, unwrapEscapes, validateDeclaredHost, validateHost, writeRunRecord };
907
+ export { BUILTIN_ENV_NAMES, CONNECT_PLUGIN_OWNED_SLICES, CONNECT_RUNNER, HostLoadError, ONE_SHOT_VERBS, OUTPUTS_FILE, PlanError, PluginError, RunnerError, SpawnHostError, TOKEN_ESCAPE_KEY, TOKEN_KEYS, TokenResolutionError, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, buildDriveDeclarationSchema, checkHost, checkOutputPaths, checkTokenSites, childWrapperSchema, childrenSchema, clearRunRecord, collectTokenSites, compoundHostSchema, compoundOutputSource, compoundWiringSchema, computeOutputsHash, concatTokenSchema, declaredGenericCompoundHostSchema, declaredHostSchemas, defaultUserDataDir, defineHostSchemas, describeHostOutputs, describeMapElements, describeToken, driveDeclarationSchema, drivesSchema, emitHostJsonSchema, emittedHostSchemas, entryActiveForVerb, envSitesOf, envTokenSchema, envTokenable, expectHost, explainDrivePlan, findDeadConnectConfig, findNonStaticValue, findRemovedForms, findToken, forbidRef, formatPath, genericCompoundHostSchema, getVerb, hostSchemaIssues, hostTypeSatisfies, isBuiltinEnvName, isPidAlive, isSchemaLike, isStructuralMultiReactor, isToken, itemTokenSchema, keyTokenSchema, kindShapeIssues, knownVerbIssues, lintHostImportGraph, lintHostImports, lintOutputsFile, listRunRecords, listVerbs, loadHost, loadProducers, makeHostSchemas, mapTokenSchema, memberForRef, mergeContributions, mergeDefaultDrives, mergeDrivePlan, normalizePluginEntries, normalizePluginEntry, outputRefsOf, outputSitesOf, outputTokenSchema, planCompound, pluginEntryObjectSchema, pluginEntrySchema, primaryBackend, probeHostsFolder, probeRun, processResolveEnv, producerOutputsSchemas, profileSchema, projectDriveId, projectDriveIdWith, projectDrivesIntoConnect, projectReactorToConnect, projectReactorToSwitchboard, protocolConflicts, protocolEnv, reactorBackendKindSchema, reactorBackendSchema, reactorClientMode, reactorHostSchema, reactorProtocolSchema, reactorSchema, readOutputsFileHash, readProjectName, readRunRecord, rebaseDriveUrl, ref, refKey, refineStartOrder, registerHostType, remoteBackendUrls, renderTokens, resolveDriveDeclaration, resolveHostOutputs, resolveHostPlugins, resolveOrder, resolvePluginContributions, resolveRunnerModule, resolveUserDataPlaceholders, runCompound, runObserveHook, runObserveHookSequential, runProvideHook, runRecordMemberSchema, runRecordOutputSource, runRecordSchema, runTransformHook, runnerBaseSchema, runnerHandleSchema, runnerKindSchema, runnerOutputsSchema, scanHostImports, schemaAtPath, seedDrives, spawnHost, stripComments, substituteBuiltinEnv, toStartedHandle, tokenKeyOf, tokenSchema, tokenable, unwrapEscapes, validateDeclaredHost, validateHost, writeRunRecord };
450
908
 
451
909
  //# sourceMappingURL=index.mjs.map