@powerhousedao/host-core 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.
@@ -0,0 +1,3296 @@
1
+ import { createRequire } from "node:module";
2
+ import { createHash } from "node:crypto";
3
+ import fs, { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { z } from "zod";
7
+ import { TOKEN_ESCAPE_KEY, TOKEN_KEYS, concatTokenSchema, envTokenSchema, envTokenable, findToken, forbidRef, isToken, itemTokenSchema, keyTokenSchema, mapTokenSchema, outputTokenSchema, ref, switchboardOfDrive, tokenKeyOf, tokenSchema, tokenable } from "@powerhousedao/shared/host-tokens";
8
+ import { isOriginPlaceholderUrl } from "@powerhousedao/shared/connect/origin-placeholder";
9
+ import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
10
+ //#region src/plugins.ts
11
+ /**
12
+ * R1 — the host plugin framework (bridge-runners-to-plugins plan,
13
+ * customization-references/host-core as the blueprint).
14
+ *
15
+ * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
16
+ * contributions are declarative, serializable surface. Host RUNTIMES define
17
+ * the hook vocabulary and interleave their own wiring between stages — they
18
+ * are never plugins themselves.
19
+ *
20
+ * host.js carries the COMPOSITION as `runner.plugins` entries:
21
+ * string | { module, enabled?, verbs?, config? }
22
+ * Presence is activation (enabled defaults true); `verbs` scopes an entry to
23
+ * matching run verbs; `config` is validated against the plugin's declared
24
+ * zod schema. Entries resolve from the PROJECT's dependency tree exactly
25
+ * like runner modules.
26
+ */
27
+ var PluginError = class extends Error {
28
+ constructor(message, hint) {
29
+ super(hint ? `${message}\n Hint: ${hint}` : message);
30
+ this.name = "PluginError";
31
+ }
32
+ };
33
+ const pluginEntryObjectSchema = z.strictObject({
34
+ module: z.string().min(1),
35
+ /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
36
+ enabled: z.boolean().optional(),
37
+ /** "*" (default) or the run verbs this entry is active for. */
38
+ verbs: z.union([z.literal("*"), z.array(z.string().min(1)).min(1)]).optional(),
39
+ /** Validated against the plugin's declared configSchema at resolution. */
40
+ config: z.record(z.string(), z.unknown()).optional()
41
+ });
42
+ const pluginEntrySchema = z.union([z.string().min(1), pluginEntryObjectSchema]);
43
+ function normalizePluginEntry(entry) {
44
+ if (typeof entry === "string") return {
45
+ module: entry,
46
+ enabled: true,
47
+ verbs: "*",
48
+ config: {}
49
+ };
50
+ return {
51
+ module: entry.module,
52
+ enabled: entry.enabled ?? true,
53
+ verbs: entry.verbs ?? "*",
54
+ config: entry.config ?? {}
55
+ };
56
+ }
57
+ /** Module is the identity key: a duplicate makes override targeting and
58
+ * ordering ambiguous, so it fails loudly. */
59
+ function normalizePluginEntries(entries, where) {
60
+ const normalized = entries.map(normalizePluginEntry);
61
+ const seen = /* @__PURE__ */ new Set();
62
+ for (const entry of normalized) {
63
+ if (seen.has(entry.module)) throw new PluginError(`${where}: plugin "${entry.module}" is listed twice.`, "Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.");
64
+ seen.add(entry.module);
65
+ }
66
+ return normalized;
67
+ }
68
+ function entryActiveForVerb(entry, verb) {
69
+ if (!entry.enabled) return false;
70
+ return entry.verbs === "*" || entry.verbs.includes(verb);
71
+ }
72
+ /**
73
+ * The appliesTo hierarchy. "reactor" is the base every reactor host extends;
74
+ * "compound" is its own branch (plugins over the member set — e.g. the clint
75
+ * proxy). Host runtimes register their id with a parent; compatibility walks
76
+ * the parent chain.
77
+ */
78
+ const HOST_TYPE_PARENTS = {
79
+ reactor: null,
80
+ compound: null,
81
+ connect: "reactor",
82
+ switchboard: "reactor",
83
+ mastra: "reactor"
84
+ };
85
+ function registerHostType(id, parent) {
86
+ if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) throw new PluginError(`Host type "${id}" is already registered with parent "${String(HOST_TYPE_PARENTS[id])}".`);
87
+ HOST_TYPE_PARENTS[id] = parent;
88
+ }
89
+ function hostTypeSatisfies(hostType, appliesTo) {
90
+ let current = hostType;
91
+ while (current !== null) {
92
+ if (current === appliesTo) return true;
93
+ current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
94
+ }
95
+ return false;
96
+ }
97
+ /** Registration order, bucketed pre → normal → post (stable within buckets),
98
+ * then dependsOn topo-sorted within the bucketed order. */
99
+ function resolveOrder(plugins) {
100
+ const buckets = {
101
+ pre: [],
102
+ normal: [],
103
+ post: []
104
+ };
105
+ for (const plugin of plugins) buckets[plugin.enforce ?? "normal"].push(plugin);
106
+ const bucketed = [
107
+ ...buckets.pre,
108
+ ...buckets.normal,
109
+ ...buckets.post
110
+ ];
111
+ const byName = new Map(bucketed.map((p) => [p.name, p]));
112
+ for (const plugin of bucketed) for (const dep of plugin.dependsOn ?? []) if (!byName.has(dep)) throw new PluginError(`Plugin "${plugin.name}" depends on missing plugin "${dep}".`, "dependsOn names PLUGINS only — the host runtime is implied and never named.");
113
+ const ordered = [];
114
+ const state = /* @__PURE__ */ new Map();
115
+ const visit = (plugin, chain) => {
116
+ const mark = state.get(plugin.name);
117
+ if (mark === "done") return;
118
+ if (mark === "visiting") throw new PluginError(`Plugin dependency cycle: ${[...chain, plugin.name].join(" -> ")}.`);
119
+ state.set(plugin.name, "visiting");
120
+ for (const dep of plugin.dependsOn ?? []) visit(byName.get(dep), [...chain, plugin.name]);
121
+ state.set(plugin.name, "done");
122
+ ordered.push(plugin);
123
+ };
124
+ for (const plugin of bucketed) visit(plugin, []);
125
+ return ordered;
126
+ }
127
+ async function runProvideHook(name, plugins, ctx) {
128
+ const impls = plugins.filter((p) => typeof p.hooks?.[name] === "function");
129
+ if (impls.length > 1) throw new PluginError(`Hook "${name}" is provided by ${impls.map((p) => `"${p.name}"`).join(" and ")} — provide hooks have one winner.`);
130
+ const impl = impls[0]?.hooks?.[name];
131
+ return impl ? await impl(ctx) : void 0;
132
+ }
133
+ async function runTransformHook(name, plugins, ctx, seed) {
134
+ let value = seed;
135
+ for (const plugin of plugins) {
136
+ const impl = plugin.hooks?.[name];
137
+ if (typeof impl === "function") value = await impl(value, ctx);
138
+ }
139
+ return value;
140
+ }
141
+ /** Sequential observe, in plugin order — for lifecycle moments whose order
142
+ * is load-bearing (teardown: the switchboard stops privacy before workflows
143
+ * before the api, per the carve map). */
144
+ async function runObserveHookSequential(name, plugins, ctx) {
145
+ for (const plugin of plugins) {
146
+ const impl = plugin.hooks?.[name];
147
+ if (typeof impl === "function") await impl(ctx);
148
+ }
149
+ }
150
+ async function runObserveHook(name, plugins, ctx) {
151
+ await Promise.all(plugins.map(async (plugin) => {
152
+ const impl = plugin.hooks?.[name];
153
+ if (typeof impl === "function") await impl(ctx);
154
+ }));
155
+ }
156
+ /** Array kinds concatenate in provenance-then-order sequence (built-in first,
157
+ * so later sources read as overrides where consumers want last-wins). */
158
+ function mergeContributions(resolved) {
159
+ const rank = {
160
+ "built-in": 0,
161
+ local: 1,
162
+ dependency: 2
163
+ };
164
+ const sorted = [...resolved].sort((a, b) => rank[a.provenance] - rank[b.provenance]);
165
+ const merged = {};
166
+ for (const { plugin, provenance } of sorted) for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {
167
+ if (!values) continue;
168
+ const bucket = merged[kind] ??= [];
169
+ for (const value of values) bucket.push({
170
+ value,
171
+ source: {
172
+ pluginName: plugin.name,
173
+ provenance
174
+ }
175
+ });
176
+ }
177
+ return merged;
178
+ }
179
+ //#endregion
180
+ //#region src/plugins-resolve.ts
181
+ /**
182
+ * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core
183
+ * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the
184
+ * PROJECT dependency tree, exactly like runner modules.
185
+ */
186
+ function isHostPluginShape(value) {
187
+ return value !== null && typeof value === "object" && typeof value.name === "string";
188
+ }
189
+ /**
190
+ * Resolve host.js plugin entries into live plugins for one host boot:
191
+ * verb-filter → module resolution from the project tree (default condition,
192
+ * like runners) → factory/object contract → config validation → appliesTo.
193
+ */
194
+ async function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {
195
+ const normalized = normalizePluginEntries(entries, where);
196
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
197
+ const resolved = [];
198
+ for (const entry of normalized) {
199
+ if (!entryActiveForVerb(entry, verb)) continue;
200
+ let file;
201
+ try {
202
+ file = projectRequire.resolve(entry.module);
203
+ } catch {
204
+ throw new PluginError(`${where}: cannot resolve plugin "${entry.module}" from ${projectRoot}.`, "Plugins resolve from the project dependency tree, exactly like runner modules.");
205
+ }
206
+ const exported = (await import(pathToFileURL(file).href)).default;
207
+ let plugin;
208
+ if (typeof exported === "function") plugin = exported(entry.config);
209
+ else if (isHostPluginShape(exported)) {
210
+ if (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin "${entry.module}" takes no config, but the entry passes one.`);
211
+ plugin = exported;
212
+ } else throw new PluginError(`${where}: "${entry.module}" does not default-export a plugin object or factory.`, "Export `{ name, hooks?, contributions? }` or `(config) => plugin`.");
213
+ if (plugin.configSchema) {
214
+ const parsed = plugin.configSchema.safeParse(entry.config);
215
+ if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
216
+ }
217
+ const appliesTo = plugin.appliesTo ?? "reactor";
218
+ if (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin "${plugin.name}" applies to "${appliesTo}" hosts, but this host is "${hostType}".`);
219
+ resolved.push({
220
+ entry,
221
+ plugin,
222
+ provenance: "dependency"
223
+ });
224
+ }
225
+ return resolved;
226
+ }
227
+ /**
228
+ * LENIENT resolution for diagnostics (`ph run <host> --explain drives`):
229
+ * collects the drive contributions of the entries active for `verb`. Unlike
230
+ * resolveHostPlugins it does not know the host type (so appliesTo is not
231
+ * checked) and does not fail on a specifier the project tree cannot resolve
232
+ * — the entry is listed under `unresolved` instead. Config is still validated
233
+ * against the plugin's schema, so a bad entry surfaces here too.
234
+ */
235
+ async function resolvePluginContributions(projectRoot, verb, entries, where) {
236
+ const normalized = normalizePluginEntries(entries, where);
237
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
238
+ const plan = {
239
+ drives: [],
240
+ unresolved: []
241
+ };
242
+ for (const entry of normalized) {
243
+ if (!entryActiveForVerb(entry, verb)) continue;
244
+ let file;
245
+ try {
246
+ file = projectRequire.resolve(entry.module);
247
+ } catch {
248
+ plan.unresolved.push(entry.module);
249
+ continue;
250
+ }
251
+ const exported = (await import(pathToFileURL(file).href)).default;
252
+ let plugin;
253
+ if (typeof exported === "function") plugin = exported(entry.config);
254
+ else if (isHostPluginShape(exported)) plugin = exported;
255
+ else {
256
+ plan.unresolved.push(entry.module);
257
+ continue;
258
+ }
259
+ if (plugin.configSchema) {
260
+ const parsed = plugin.configSchema.safeParse(entry.config);
261
+ if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
262
+ }
263
+ for (const declaration of plugin.contributions?.drives ?? []) plan.drives.push({
264
+ declaration,
265
+ source: plugin.name
266
+ });
267
+ }
268
+ return plan;
269
+ }
270
+ /**
271
+ * The connect config slices each built-in Connect plugin owns, by specifier
272
+ * (typed-host-configs 1.6). Under a declared composition Connect zeroes a
273
+ * slice whose plugin is absent — presence is activation — so an authored
274
+ * value there is dead config. Connect's built-ins are browser modules with no
275
+ * Node-resolvable identity, so their ownership is declared here as data; a
276
+ * Connect test pins it to plugin-host's zeroing.
277
+ */
278
+ const CONNECT_PLUGIN_OWNED_SLICES = {
279
+ "@powerhousedao/connect/plugins/generic": { slices: [
280
+ {
281
+ path: "drives.allowAddDrive",
282
+ absent: false,
283
+ entryKey: "allowAddDrive"
284
+ },
285
+ {
286
+ path: "drives.sections",
287
+ absent: {
288
+ remote: {
289
+ enabled: false,
290
+ allowAdd: false,
291
+ allowDelete: false
292
+ },
293
+ local: {
294
+ enabled: false,
295
+ allowAdd: false,
296
+ allowDelete: false
297
+ }
298
+ },
299
+ entryKey: "sections"
300
+ },
301
+ {
302
+ path: "drives.icons",
303
+ absent: null,
304
+ entryKey: "icons"
305
+ },
306
+ {
307
+ path: "home.background",
308
+ absent: null,
309
+ entryKey: "homeBackground"
310
+ }
311
+ ] },
312
+ "@powerhousedao/connect/plugins/sentry": { slices: [{
313
+ path: "sentry.dsn",
314
+ absent: null,
315
+ entryKey: "dsn"
316
+ }] },
317
+ "@powerhousedao/connect/plugins/openpanel": {
318
+ slices: [
319
+ {
320
+ path: "openPanel.clientId",
321
+ absent: "",
322
+ entryKey: "clientId"
323
+ },
324
+ {
325
+ path: "openPanel.trackUiEvents",
326
+ absent: false,
327
+ entryKey: "trackUiEvents"
328
+ },
329
+ {
330
+ path: "openPanel.trackOperations",
331
+ absent: false,
332
+ entryKey: "trackOperations"
333
+ }
334
+ ],
335
+ inertUnless: "openPanel.clientId"
336
+ },
337
+ "@powerhousedao/connect/plugins/assistant": { slices: [{
338
+ path: "ai.assistantEnabled",
339
+ absent: false
340
+ }] },
341
+ "@powerhousedao/vetra-studio/connect": { slices: [{
342
+ path: "app.studioMode",
343
+ absent: false
344
+ }] },
345
+ "@powerhousedao/connect/plugins/workflows": { slices: [{
346
+ path: "app.workflowsEnabled",
347
+ absent: false
348
+ }] }
349
+ };
350
+ function valueAt$1(root, dotted) {
351
+ let current = root;
352
+ for (const key of dotted.split(".")) {
353
+ if (current === null || typeof current !== "object") return void 0;
354
+ current = current[key];
355
+ }
356
+ return current;
357
+ }
358
+ /** Whether Connect already serves what the author wrote: every authored leaf
359
+ * equals the served one. An unset leaf asks for nothing, so a partial object
360
+ * (`sections: { remote: { enabled: false } }`) is satisfied by the zeroed
361
+ * slice. */
362
+ function alreadyServed(authored, served) {
363
+ if (authored === void 0 || Object.is(authored, served)) return true;
364
+ if (authored === null || served === null || typeof authored !== "object" || typeof served !== "object" || Array.isArray(authored) !== Array.isArray(served)) return false;
365
+ if (Array.isArray(authored) && authored.length !== served.length) return false;
366
+ const want = authored;
367
+ const have = served;
368
+ return Object.keys(want).every((key) => alreadyServed(want[key], have[key]));
369
+ }
370
+ /**
371
+ * Dead-config warnings for a Connect host (typed-host-configs 1.6): an
372
+ * authored connect config value whose owning plugin is not in the
373
+ * composition active for `verb`. Connect zeroes such a slice, so the value
374
+ * has no effect — e.g. Sektar's `connect.drives.allowAddDrive: true` without
375
+ * the generic plugin.
376
+ *
377
+ * Nothing is reported when the host declares no composition
378
+ * (`runner.plugins` absent: the classic boot serves the config as is), or
379
+ * when Connect already serves every leaf of the authored value. Warnings, not
380
+ * errors: the host still boots, it just does not do what the value says.
381
+ */
382
+ function findDeadConnectConfig(config, entries, verb, where) {
383
+ if (!config || entries === void 0) return [];
384
+ const active = new Set(normalizePluginEntries(entries, where).filter((entry) => entryActiveForVerb(entry, verb)).map((entry) => entry.module));
385
+ const warnings = [];
386
+ for (const [owner, { slices, inertUnless }] of Object.entries(CONNECT_PLUGIN_OWNED_SLICES)) {
387
+ if (active.has(owner)) continue;
388
+ if (inertUnless !== void 0) {
389
+ const gate = slices.find((slice) => slice.path === inertUnless);
390
+ if (alreadyServed(valueAt$1(config, inertUnless), gate?.absent)) continue;
391
+ }
392
+ for (const { path: slicePath, absent, entryKey } of slices) {
393
+ const value = valueAt$1(config, slicePath);
394
+ if (alreadyServed(value, absent)) continue;
395
+ const move = entryKey === void 0 ? `compose "${owner}" (presence is the switch)` : `compose "${owner}" and set \`${entryKey}\` in its entry config`;
396
+ warnings.push({
397
+ path: slicePath,
398
+ value,
399
+ served: absent,
400
+ owner,
401
+ message: `${where}: config.${slicePath} is dead config: it is owned by plugin "${owner}", which this host does not compose for verb "${verb}", so Connect serves ${JSON.stringify(absent)} instead of ${JSON.stringify(value)}.\n Hint: ${move}, or delete the value.`
402
+ });
403
+ }
404
+ }
405
+ return warnings;
406
+ }
407
+ //#endregion
408
+ //#region src/drive-schema.ts
409
+ /**
410
+ * The schema half of drives.ts, zod only so `./schema` stays neutral.
411
+ * - slug: the SEEDING KEY (idempotence); id optional (stable identity).
412
+ * - preferredEditor: stored at header.meta.preferredEditor; Connect config's
413
+ * `app` is the legacy alias.
414
+ * - remote.url: a drive served elsewhere; local fields are ignored for it.
415
+ * Token-able (`$output` on a producer's `drives.<slug>.url`).
416
+ */
417
+ function buildDriveDeclarationSchema(urlField) {
418
+ return z.strictObject({
419
+ slug: z.string().min(1),
420
+ id: z.string().min(1).optional(),
421
+ /** Derive the id from the project path, like generateProjectDriveId — the
422
+ * same ids classic `ph vetra` produces. `true` serves the drive under the
423
+ * hashed slug too (the vetra drive's slug IS its hashed id); `"id"` hashes
424
+ * only the id and keeps the declared slug (the classic Workflows drive:
425
+ * `/d/workflows`, id `workflows-<hash>`). */
426
+ projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
427
+ /** What a missing drive is created as. Default powerhouse/document-drive. */
428
+ documentType: z.enum(["powerhouse/document-drive", "powerhouse/reactor-drive"]).optional(),
429
+ name: z.string().min(1).optional(),
430
+ icon: z.string().optional(),
431
+ preferredEditor: z.string().optional(),
432
+ sharingType: z.enum([
433
+ "public",
434
+ "private",
435
+ "shared"
436
+ ]).optional(),
437
+ availableOffline: z.boolean().optional(),
438
+ remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional()
439
+ });
440
+ }
441
+ const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);
442
+ const drivesSchema = z.array(driveDeclarationSchema);
443
+ /** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with
444
+ * the hash function injected, so neutral consumers (a browser monitor) can
445
+ * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to
446
+ * node:crypto as `projectDriveId`. */
447
+ function projectDriveIdWith(sha256Hex, projectRoot, slug) {
448
+ return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;
449
+ }
450
+ //#endregion
451
+ //#region src/host-schemas.ts
452
+ /**
453
+ * The zod single source for host.js blocks (typed-host-configs G1). Every
454
+ * host type is z.input/z.output of these schemas; nothing is hand-mirrored.
455
+ * Top-level host objects and the `reactor` block are STRICT (a typo fails);
456
+ * `runner` stays loose until each runner declares its options (T2), and
457
+ * `config` is runner-defined.
458
+ *
459
+ * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`
460
+ * (required, a switchboard drive address), `reactor.drives` (whole list, e.g. `$map`),
461
+ * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.
462
+ */
463
+ /** A host's `name` keys its run record, `.ph/run/<name>.json`, so it must be
464
+ * one safe path segment. */
465
+ const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
466
+ const HOST_NAME_MAX_LENGTH = 128;
467
+ const HOST_NAME_MESSAGE = "A host name is used as a file name, so use only letters, digits, '.', '_' and '-', start with a letter or digit, and keep it to 128 characters.";
468
+ const hostNameSchema = z.string().min(1).max(128, HOST_NAME_MESSAGE).regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);
469
+ /**
470
+ * A URL, or one written against the page origin (`${origin}/graphql`): the
471
+ * browser resolves the placeholder when it loads Connect's config, for a
472
+ * member whose own server proxies the switchboard's paths.
473
+ */
474
+ const originOrUrlSchema = z.union([z.url(), z.string().refine(isOriginPlaceholderUrl, { message: "a URL, or ${origin}/<path> for a proxied sibling" })]);
475
+ const profileSchema = z.strictObject({
476
+ appId: z.string().min(1).optional(),
477
+ name: z.string().min(1).optional(),
478
+ description: z.string().optional(),
479
+ icon: z.string().optional()
480
+ });
481
+ const reactorProtocolSchema = z.strictObject({
482
+ featureFlags: z.strictObject({
483
+ documentDecisions: z.boolean().optional(),
484
+ authEnforcement: z.boolean().optional(),
485
+ authGroups: z.boolean().optional(),
486
+ authConditions: z.boolean().optional(),
487
+ undoV3: z.boolean().optional()
488
+ }).optional(),
489
+ createSignaturePolicy: z.enum(["legacy", "v2-required"]).optional(),
490
+ unsupportedStoredDocuments: z.enum(["refuse", "read-only"]).optional()
491
+ });
492
+ const runnerKindSchema = z.enum(["reactor", "compound"]);
493
+ const reactorBackendKindSchema = z.enum([
494
+ "in-process",
495
+ "worker",
496
+ "remote"
497
+ ]);
498
+ const samePath = (a, b) => {
499
+ const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "");
500
+ return norm(a) === norm(b);
501
+ };
502
+ /** Compound wiring: the generic compound runner's `config` block.
503
+ * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a
504
+ * member consumes another member's drives through `$output` tokens.) */
505
+ const compoundWiringSchema = z.strictObject({
506
+ /** Member start order; must name declared children and agree with the
507
+ * output-token dependencies (resolve/plan.ts). Optional: without it the
508
+ * order is derived from the tokens. Unnamed members start after the named
509
+ * ones, in declaration order. */
510
+ startOrder: z.array(z.string().min(1)).optional(),
511
+ /** Write .ph/run/<host>.json (default true). */
512
+ runtimeRecord: z.boolean().optional(),
513
+ /** Patch the baked CSP for the runtime registry on a served Connect
514
+ * member (forwarded as `runner.cspRegistrySync` to every member whose
515
+ * runner is `@powerhousedao/ph-cli/runners/connect`). */
516
+ cspRegistrySync: z.boolean().optional()
517
+ });
518
+ /** `config.startOrder ⊆ keys(children)`, checked where both are visible.
519
+ * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host
520
+ * schema: zod refuses to `.extend()` a refined object. */
521
+ function refineStartOrder(host, ctx) {
522
+ const startOrder = host.config?.startOrder;
523
+ if (!Array.isArray(startOrder)) return;
524
+ const members = Object.keys(host.children);
525
+ startOrder.forEach((name, index) => {
526
+ if (startOrder.indexOf(name) !== index) {
527
+ ctx.addIssue({
528
+ code: "custom",
529
+ path: [
530
+ "config",
531
+ "startOrder",
532
+ index
533
+ ],
534
+ message: `startOrder names "${String(name)}" twice; each member starts once.`
535
+ });
536
+ return;
537
+ }
538
+ if (typeof name === "string" && members.includes(name)) return;
539
+ ctx.addIssue({
540
+ code: "custom",
541
+ path: [
542
+ "config",
543
+ "startOrder",
544
+ index
545
+ ],
546
+ message: `startOrder names "${String(name)}", which is not a member. Members: ${members.join(", ") || "(none)"}.`
547
+ });
548
+ });
549
+ }
550
+ const ALLOW_TOKENS = {
551
+ any: tokenable,
552
+ env: envTokenable
553
+ };
554
+ const FORBID_TOKENS = {
555
+ any: (schema) => z.union([schema]),
556
+ env: (schema) => z.union([schema])
557
+ };
558
+ /** The replacement a non-drive `remote.url` message names. */
559
+ function useDriveUrl(host = "switchboard", member) {
560
+ return `remote: { url: ${host}.drives.<slug>.url } with ${host} from ../${host}/outputs.js, or remote: { url: { $output: { host: "${host}"${member ? `, member: "${member}"` : ""}, path: ["drives", "<slug>", "url"] } } }`;
561
+ }
562
+ /** The `$output` of a declared `remote.url` that reads `endpoints.graphql`. */
563
+ function endpointsGraphqlRef(url) {
564
+ if (typeof url !== "object" || url === null || !("$output" in url)) return;
565
+ const ref = url.$output;
566
+ if (typeof ref !== "object" || ref === null) return void 0;
567
+ const { host, member, path } = ref;
568
+ if (typeof host !== "string" || !Array.isArray(path)) return void 0;
569
+ if (path.join(".") !== "endpoints.graphql") return void 0;
570
+ return {
571
+ host,
572
+ ...typeof member === "string" ? { member } : {}
573
+ };
574
+ }
575
+ /** The slug a drive link names: a `drives.<slug>.url` token's slug or a
576
+ * literal address's served slug; undefined when only runtime knows it. */
577
+ function linkedSlug(url) {
578
+ if (typeof url === "string") return switchboardOfDrive(url)?.slug;
579
+ const ref = typeof url === "object" && url !== null && "$output" in url ? url.$output : void 0;
580
+ const path = Array.isArray(ref?.path) ? ref.path : [];
581
+ return path.length === 3 && path[0] === "drives" && typeof path[1] === "string" && path[2] === "url" ? path[1] : void 0;
582
+ }
583
+ /** The drives a declared host names (home drives, `reactor.drives`, plugin
584
+ * `config.drive` links), or undefined when one is known only at runtime. */
585
+ function knownDriveSlugs(host) {
586
+ const reactor = host.reactor ?? {};
587
+ const slugs = [];
588
+ for (const backend of Object.values(reactor.backends ?? {})) {
589
+ if (backend.kind !== "remote") continue;
590
+ const slug = linkedSlug(backend.remote?.url);
591
+ if (slug === void 0) return void 0;
592
+ slugs.push(slug);
593
+ }
594
+ if (reactor.drives !== void 0) {
595
+ if (!Array.isArray(reactor.drives)) return void 0;
596
+ for (const drive of reactor.drives) if (typeof drive.slug === "string") slugs.push(drive.slug);
597
+ }
598
+ const plugins = Array.isArray(host.runner?.plugins) ? host.runner.plugins : [];
599
+ for (const entry of plugins) {
600
+ const config = typeof entry === "object" && entry !== null && "config" in entry ? entry.config : void 0;
601
+ if (typeof config !== "object" || config === null) continue;
602
+ if (!("drive" in config) || config.drive === void 0) continue;
603
+ const slug = linkedSlug(config.drive);
604
+ if (slug === void 0) return void 0;
605
+ slugs.push(slug);
606
+ }
607
+ for (const drive of connectDefaultDrives(host.config)) {
608
+ if (typeof drive !== "object" || drive === null || !("url" in drive)) continue;
609
+ const slug = linkedSlug(drive.url);
610
+ if (slug === void 0) return void 0;
611
+ slugs.push(slug);
612
+ }
613
+ return slugs;
614
+ }
615
+ /** A Connect host's `config.drives.defaultDrives`, unchecked. */
616
+ function connectDefaultDrives(config) {
617
+ const drives = typeof config === "object" && config !== null && "drives" in config ? config.drives : void 0;
618
+ const list = typeof drives === "object" && drives !== null && "defaultDrives" in drives ? drives.defaultDrives : void 0;
619
+ return Array.isArray(list) ? list : [];
620
+ }
621
+ /** Declared form, at host level so plugin drives are seen: a placement key
622
+ * must name a drive the host names, when every drive is knowable. A host
623
+ * with no remote backend is not checked: its plugins may contribute drives
624
+ * (a switchboard's workflows drive) that no field names. */
625
+ function refineDeclaredPlacementKeys(host, ctx) {
626
+ const placed = Object.keys(host.reactor?.placement?.drives ?? {});
627
+ if (placed.length === 0) return;
628
+ if (!Object.values(host.reactor?.backends ?? {}).some((b) => b.kind === "remote")) return;
629
+ const known = knownDriveSlugs(host);
630
+ if (!known) return;
631
+ const names = (slug, served) => served === slug || served.startsWith(`${slug}-`) && /^[0-9a-f]{8}$/.test(served.slice(slug.length + 1));
632
+ for (const slug of placed) {
633
+ if (known.some((served) => names(slug, served))) continue;
634
+ ctx.addIssue({
635
+ code: "custom",
636
+ path: [
637
+ "reactor",
638
+ "placement",
639
+ "drives",
640
+ slug
641
+ ],
642
+ message: `placement.drives.${slug} names no drive this host links to or declares (${[...new Set(known)].join(", ") || "none"}).`
643
+ });
644
+ }
645
+ }
646
+ /** Resolved-form checks across backends, drives and placement: one base is
647
+ * one remote backend, and a drive placed on a remote is on its switchboard. */
648
+ function refineResolvedReactor(reactor, ctx) {
649
+ const backends = reactor.backends ?? {};
650
+ const baseOf = /* @__PURE__ */ new Map();
651
+ const byBase = /* @__PURE__ */ new Map();
652
+ const linked = /* @__PURE__ */ new Map();
653
+ const link = (slug, base) => linked.set(slug, (linked.get(slug) ?? /* @__PURE__ */ new Set()).add(base));
654
+ for (const [name, backend] of Object.entries(backends)) {
655
+ const url = backend.remote?.url;
656
+ if (backend.kind !== "remote" || typeof url !== "string") continue;
657
+ const home = switchboardOfDrive(url);
658
+ if (!home) continue;
659
+ baseOf.set(name, home.base);
660
+ link(home.slug, home.base);
661
+ const first = byBase.get(home.base);
662
+ if (first === void 0) {
663
+ byBase.set(home.base, name);
664
+ continue;
665
+ }
666
+ ctx.addIssue({
667
+ code: "custom",
668
+ path: [
669
+ "backends",
670
+ name,
671
+ "remote",
672
+ "url"
673
+ ],
674
+ message: `backends "${first}" and "${name}" both open drives on the same switchboard (${home.base}). Keep "${first}", and list the second drive under reactor.drives with its remote.url instead.`
675
+ });
676
+ }
677
+ const kept = /* @__PURE__ */ new Set();
678
+ (Array.isArray(reactor.drives) ? reactor.drives : []).forEach((drive, index) => {
679
+ if (!drive.remote) {
680
+ kept.add(drive.slug);
681
+ return;
682
+ }
683
+ const at = switchboardOfDrive(drive.remote.url);
684
+ if (at || drive.remote.url === "") {
685
+ if (at) link(drive.slug, at.base);
686
+ return;
687
+ }
688
+ ctx.addIssue({
689
+ code: "custom",
690
+ path: [
691
+ "drives",
692
+ index,
693
+ "remote",
694
+ "url"
695
+ ],
696
+ message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${drive.remote.url}: sync needs the drive. Use url: switchboard.drives.<slug>.url, or url: { $output: { host: "switchboard", path: ["drives", "<slug>", "url"] } }.`
697
+ });
698
+ });
699
+ const nameOf = (base) => byBase.get(base) ?? base;
700
+ for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
701
+ const at = [
702
+ "placement",
703
+ "drives",
704
+ slug
705
+ ];
706
+ const on = [...linked.get(slug) ?? []];
707
+ if (on.length > 0 && kept.has(slug)) {
708
+ ctx.addIssue({
709
+ code: "custom",
710
+ path: at,
711
+ message: `Drive "${slug}" is both this reactor's own drive and on ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
712
+ });
713
+ continue;
714
+ }
715
+ if (on.length > 1) {
716
+ ctx.addIssue({
717
+ code: "custom",
718
+ path: at,
719
+ message: `Drive "${slug}" is on both ${on.map(nameOf).join(" and ")}. Rename one, or link only one.`
720
+ });
721
+ continue;
722
+ }
723
+ const base = baseOf.get(name);
724
+ if (base === void 0) continue;
725
+ if (on.length === 0) {
726
+ if (!kept.has(slug)) continue;
727
+ ctx.addIssue({
728
+ code: "custom",
729
+ path: at,
730
+ message: `placement.drives.${slug} opens drive "${slug}" on "${name}", but this reactor keeps that drive itself. Only a drive on a switchboard can open there without a copy.`
731
+ });
732
+ continue;
733
+ }
734
+ if (on[0] === base) continue;
735
+ ctx.addIssue({
736
+ code: "custom",
737
+ path: at,
738
+ message: `placement.drives.${slug} opens drive "${slug}" on "${name}" (${base}), but the drive is on ${on[0]}. Place it on the backend for that switchboard.`
739
+ });
740
+ }
741
+ }
742
+ /** `remote` keys that tune a connection, so only a remote backend has them. */
743
+ const REMOTE_ONLY_KEYS = [
744
+ "requestTimeoutMs",
745
+ "breaker",
746
+ "realtime"
747
+ ];
748
+ /**
749
+ * Builds the host schema set. "allow" (declared form) accepts `T | Token` in
750
+ * every token-able field; "forbid" (resolved form) accepts `T` only.
751
+ */
752
+ function buildHostSchemas(tokenField) {
753
+ const resolved = tokenField === FORBID_TOKENS;
754
+ const reactorBackendSchema = z.strictObject({
755
+ kind: reactorBackendKindSchema,
756
+ storage: z.strictObject({
757
+ kind: z.enum([
758
+ "idb",
759
+ "memory",
760
+ "path",
761
+ "postgres"
762
+ ]),
763
+ /** `"${userData}/…"` sugar or `{ $env: "NAME" }`. */
764
+ dataDir: tokenField.env(z.string()).optional(),
765
+ url: z.string().optional()
766
+ }).optional(),
767
+ readModel: z.strictObject({ url: z.string().optional() }).optional(),
768
+ packages: z.strictObject({
769
+ cdnUrl: z.string().optional(),
770
+ specs: z.array(z.string()).optional(),
771
+ /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */
772
+ dynamic: z.boolean().optional()
773
+ }).optional(),
774
+ remote: z.strictObject({
775
+ url: tokenField.any(originOrUrlSchema),
776
+ /** Give up on one request to this switchboard after this long. Default 30_000. */
777
+ requestTimeoutMs: z.number().int().positive().optional(),
778
+ /** After `failures` failed requests in a row, send nothing for
779
+ * `openMs`. Default { failures: 3, openMs: 30_000 }. `false`:
780
+ * never stop trying. */
781
+ breaker: z.union([z.literal(false), z.strictObject({
782
+ failures: z.number().int().min(1).optional(),
783
+ openMs: z.number().int().nonnegative().optional()
784
+ })]).optional(),
785
+ /** Live updates over a socket (the router's GraphQL
786
+ * subscriptions, not drive sync). Default true. */
787
+ realtime: z.boolean().optional()
788
+ }).optional()
789
+ }).superRefine((backend, ctx) => {
790
+ if (backend.kind === "remote" && !backend.remote) ctx.addIssue({
791
+ code: "custom",
792
+ path: ["remote", "url"],
793
+ message: `a "remote" backend needs remote.url, a switchboard drive address: ${useDriveUrl()}.`
794
+ });
795
+ if (backend.kind !== "remote" && backend.remote) for (const key of REMOTE_ONLY_KEYS) {
796
+ if (backend.remote[key] === void 0) continue;
797
+ ctx.addIssue({
798
+ code: "custom",
799
+ path: ["remote", key],
800
+ message: `remote.${key} applies only to a "remote" backend; this one is "${backend.kind}".`
801
+ });
802
+ }
803
+ const url = backend.remote?.url;
804
+ const graphqlRef = resolved ? void 0 : endpointsGraphqlRef(url);
805
+ if (graphqlRef) ctx.addIssue({
806
+ code: "custom",
807
+ path: ["remote", "url"],
808
+ message: `remote.url reads ${graphqlRef.host}'s endpoints.graphql; it must be a switchboard drive address (<switchboard>/d/<slug>): sync needs the drive. Use ${useDriveUrl(graphqlRef.host, graphqlRef.member)}.`
809
+ });
810
+ if (resolved && typeof url === "string" && !switchboardOfDrive(url)) ctx.addIssue({
811
+ code: "custom",
812
+ path: ["remote", "url"],
813
+ message: `remote.url must be a switchboard drive address (<switchboard>/d/<slug>), not ${url}: sync needs the drive. Use ${useDriveUrl()}.`
814
+ });
815
+ const store = backend.storage;
816
+ const storeDir = store?.kind === "path" ? store.dataDir : void 0;
817
+ const readModel = backend.readModel?.url;
818
+ if (typeof storeDir === "string" && readModel && samePath(storeDir, readModel)) ctx.addIssue({
819
+ code: "custom",
820
+ path: ["readModel", "url"],
821
+ message: `readModel.url must not be the reactor's storage dir (${readModel}): two PGlite instances on one data dir corrupt it. Omit readModel.url to get the classic <root>/.ph/read-storage next to the reactor store.`
822
+ });
823
+ });
824
+ const reactorSchema = z.strictObject({
825
+ backends: z.record(z.string(), reactorBackendSchema).optional(),
826
+ placement: z.strictObject({
827
+ primary: z.string().optional(),
828
+ /** Declared drive slug → backend name. A local backend keeps a
829
+ * synced copy; the drive's own remote backend opens it there with
830
+ * no copy. An unlisted drive keeps a synced copy. */
831
+ drives: z.record(z.string().min(1), z.string().min(1)).optional(),
832
+ /** The backend new drives (and documents outside a drive) are
833
+ * created on. A switchboard keeps no copy in this browser.
834
+ * Default: the browser reactor, else the only switchboard. */
835
+ newDrives: z.string().min(1).optional()
836
+ }).optional(),
837
+ router: z.strictObject({
838
+ /** Wait this long for a reactor to say whether it holds a
839
+ * document. 0: no bound. Default 3_000. */
840
+ probeTimeoutMs: z.number().int().nonnegative().optional(),
841
+ /** Look again after this long for a document found on a later
842
+ * backend. Default 30_000. */
843
+ provisionalRouteMs: z.number().int().nonnegative().optional()
844
+ }).optional(),
845
+ protocol: reactorProtocolSchema.optional(),
846
+ /** DEPRECATED (dies in R2): workflows become a listed plugin. */
847
+ workflows: z.boolean().optional(),
848
+ renown: z.strictObject({
849
+ url: z.string().optional(),
850
+ networkId: z.string().optional(),
851
+ chainId: z.number().int().optional()
852
+ }).optional(),
853
+ namespace: z.string().min(1).optional(),
854
+ drives: tokenField.any(z.array(buildDriveDeclarationSchema(tokenField.any))).optional()
855
+ }).superRefine((reactor, ctx) => {
856
+ const backends = reactor.backends ?? {};
857
+ for (const [slug, name] of Object.entries(reactor.placement?.drives ?? {})) {
858
+ if (Object.hasOwn(backends, name)) continue;
859
+ ctx.addIssue({
860
+ code: "custom",
861
+ path: [
862
+ "placement",
863
+ "drives",
864
+ slug
865
+ ],
866
+ message: `placement.drives.${slug} names backend "${name}", which is not in backends (${Object.keys(backends).join(", ") || "none"}).`
867
+ });
868
+ }
869
+ const newDrives = reactor.placement?.newDrives;
870
+ if (newDrives !== void 0 && !Object.hasOwn(backends, newDrives)) ctx.addIssue({
871
+ code: "custom",
872
+ path: ["placement", "newDrives"],
873
+ message: `placement.newDrives names backend "${newDrives}", which is not in backends (${Object.keys(backends).join(", ") || "none"}).`
874
+ });
875
+ if (resolved) refineResolvedReactor(reactor, ctx);
876
+ });
877
+ /** Common runner options; runner modules extend it with their own. */
878
+ const runnerBaseSchema = z.looseObject({
879
+ module: z.string().min(1),
880
+ defaultVerb: z.string().min(1).optional(),
881
+ port: z.number().int().positive().optional(),
882
+ /** Bind address; each runner documents its default. */
883
+ host: z.string().min(1).optional(),
884
+ /** THE COMPOSITION: plugin entries; presence is activation. */
885
+ plugins: z.array(pluginEntrySchema).optional()
886
+ });
887
+ /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,
888
+ * which key-merges over the member's own. Plugins live in `runner.plugins`
889
+ * (as on a standalone host); there is no wrapper-level `plugins`. */
890
+ const childWrapperSchema = z.strictObject({
891
+ host: z.string().min(1),
892
+ runner: runnerBaseSchema.partial().extend({ port: z.number().int().min(0).max(65535).optional() }).optional(),
893
+ config: z.looseObject({}).optional(),
894
+ reactor: reactorSchema.optional()
895
+ });
896
+ const childrenSchema = z.record(z.string(), childWrapperSchema);
897
+ return {
898
+ reactorBackendSchema,
899
+ reactorSchema,
900
+ runnerBaseSchema,
901
+ childWrapperSchema,
902
+ childrenSchema,
903
+ reactorHostSchema: z.strictObject({
904
+ name: hostNameSchema,
905
+ runner: runnerBaseSchema,
906
+ config: z.looseObject({}).optional(),
907
+ profile: profileSchema.optional(),
908
+ reactor: reactorSchema.optional()
909
+ }),
910
+ compoundHostSchema: z.strictObject({
911
+ name: hostNameSchema,
912
+ runner: runnerBaseSchema,
913
+ children: childrenSchema,
914
+ config: z.looseObject({}).optional(),
915
+ profile: profileSchema.optional()
916
+ }),
917
+ /** This set's field wrapper, for a runner's OWN token-able fields inside
918
+ * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,
919
+ * `T` only. Both modes share one static type. */
920
+ tokenable: tokenField.any,
921
+ /** As `tokenable`, but the only token accepted is `$env`. */
922
+ envTokenable: tokenField.env
923
+ };
924
+ }
925
+ /** The host schema set in declared ("allow": token-able fields take tokens)
926
+ * or resolved ("forbid") form. */
927
+ function makeHostSchemas(options) {
928
+ return buildHostSchemas(options.tokens === "allow" ? ALLOW_TOKENS : FORBID_TOKENS);
929
+ }
930
+ /** The issues a host-level refinement raises, outside a zod parse. */
931
+ function collectIssues(host, refine) {
932
+ if (typeof host !== "object" || host === null || !("reactor" in host)) return [];
933
+ const issues = [];
934
+ refine(host, { addIssue: (issue) => {
935
+ issues.push({
936
+ path: (issue.path ?? []).filter((part) => typeof part !== "symbol"),
937
+ message: issue.message ?? ""
938
+ });
939
+ } });
940
+ return issues;
941
+ }
942
+ /** withPlacementKeys' check, for a merged declared host parsed some other way. */
943
+ function placementKeyIssues(host) {
944
+ return collectIssues(host, refineDeclaredPlacementKeys);
945
+ }
946
+ const CONNECT_PRIMARY_MESSAGE = "Connect doesn't use placement.primary. To choose where new drives go, use placement.newDrives.";
947
+ /**
948
+ * A Connect host's placement rules, in either form. The router's primary is
949
+ * the browser reactor, else the `newDrives` switchboard, else the only one,
950
+ * so `placement.primary` means nothing here, and a Connect with several
951
+ * switchboards and no browser reactor must say where new drives go. Apply it
952
+ * last to the Connect runner's schema: `.superRefine(refineConnectReactor)`.
953
+ */
954
+ function refineConnectReactor(host, ctx) {
955
+ const reactor = host.reactor;
956
+ if (!reactor) return;
957
+ if (reactor.placement?.primary !== void 0) ctx.addIssue({
958
+ code: "custom",
959
+ path: [
960
+ "reactor",
961
+ "placement",
962
+ "primary"
963
+ ],
964
+ message: CONNECT_PRIMARY_MESSAGE
965
+ });
966
+ const backends = Object.entries(reactor.backends ?? {});
967
+ const remotes = backends.filter(([, backend]) => backend.kind === "remote").map(([name]) => name);
968
+ if (remotes.length > 1 && remotes.length === backends.length && reactor.placement?.newDrives === void 0) ctx.addIssue({
969
+ code: "custom",
970
+ path: [
971
+ "reactor",
972
+ "placement",
973
+ "newDrives"
974
+ ],
975
+ message: `This Connect keeps no reactor in the browser and links ${remotes.length} switchboards (${remotes.join(", ")}). Set placement.newDrives to the one new drives are created on.`
976
+ });
977
+ }
978
+ /** refineConnectReactor's check, for a Connect host parsed some other way. */
979
+ function connectReactorIssues(host) {
980
+ return collectIssues(host, refineConnectReactor);
981
+ }
982
+ /** Adds the host-level placement key check to a runner's declared schema. */
983
+ function withPlacementKeys(schema) {
984
+ if (!(schema instanceof z.ZodType)) return schema;
985
+ return schema.superRefine((host, ctx) => {
986
+ if (typeof host === "object" && host !== null && "reactor" in host) refineDeclaredPlacementKeys(host, ctx);
987
+ });
988
+ }
989
+ /**
990
+ * One runner definition, two schemas (3.5): `build` runs over the DECLARED
991
+ * set (tokens allowed; its z.input types host files) and the RESOLVED set
992
+ * (no tokens; `validateHost` checks it before the verb). Export both, type
993
+ * the host as `z.input<typeof declaredHostSchema>`, refine last inside the
994
+ * builder (zod can't extend a refined object), and wrap the runner's own
995
+ * token-able fields with `s.tokenable` / `s.envTokenable`.
996
+ */
997
+ function defineHostSchemas(build) {
998
+ return {
999
+ declaredHostSchema: withPlacementKeys(build(declaredSchemas)),
1000
+ hostSchema: build(resolvedSchemas)
1001
+ };
1002
+ }
1003
+ const declaredSchemas = makeHostSchemas({ tokens: "allow" });
1004
+ const resolvedSchemas = makeHostSchemas({ tokens: "forbid" });
1005
+ const declaredHostSchemas = declaredSchemas;
1006
+ const reactorBackendSchema = resolvedSchemas.reactorBackendSchema;
1007
+ const reactorSchema = resolvedSchemas.reactorSchema;
1008
+ const runnerBaseSchema = resolvedSchemas.runnerBaseSchema;
1009
+ const childWrapperSchema = resolvedSchemas.childWrapperSchema;
1010
+ const childrenSchema = resolvedSchemas.childrenSchema;
1011
+ const reactorHostSchema = resolvedSchemas.reactorHostSchema;
1012
+ const compoundHostSchema = resolvedSchemas.compoundHostSchema;
1013
+ /** The generic compound runner's host: the base with its wiring config. */
1014
+ const genericCompound = defineHostSchemas((s) => s.compoundHostSchema.extend({ config: compoundWiringSchema.optional() }).superRefine(refineStartOrder));
1015
+ const genericCompoundHostSchema = genericCompound.hostSchema;
1016
+ const declaredGenericCompoundHostSchema = genericCompound.declaredHostSchema;
1017
+ const SCHEMA_BASE = "https://powerhouse.inc/schemas";
1018
+ /** One host schema as an editor JSON Schema with a stable `$id` — the
1019
+ * per-runner emission helper (runner packages emit their own hostSchema). */
1020
+ function emitHostJsonSchema(name, schema) {
1021
+ return {
1022
+ $id: `${SCHEMA_BASE}/${name}.schema.json`,
1023
+ ...z.toJSONSchema(schema, { io: "input" })
1024
+ };
1025
+ }
1026
+ /** The emitted-schema set, keyed by published filename. Pure — the
1027
+ * emit-schemas script writes these and the drift test re-derives them. */
1028
+ function emittedHostSchemas() {
1029
+ return {
1030
+ "host-reactor.schema.json": emitHostJsonSchema("host-reactor", declaredSchemas.reactorHostSchema),
1031
+ "host-compound.schema.json": emitHostJsonSchema("host-compound", declaredSchemas.compoundHostSchema)
1032
+ };
1033
+ }
1034
+ //#endregion
1035
+ //#region src/resolve/walk.ts
1036
+ function isPlainObject(value) {
1037
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1038
+ const proto = Object.getPrototypeOf(value);
1039
+ return proto === Object.prototype || proto === null;
1040
+ }
1041
+ /** `a.b[2].c` (or `<root>`). */
1042
+ function formatPath(path) {
1043
+ let out = "";
1044
+ for (const segment of path) if (typeof segment === "number") out += `[${segment}]`;
1045
+ else out += out ? `.${segment}` : segment;
1046
+ return out || "<root>";
1047
+ }
1048
+ /** Is this object a `$$` escape (`{ $$: literal }`)? */
1049
+ function isEscape(value) {
1050
+ const keys = Object.keys(value);
1051
+ return keys.length === 1 && keys[0] === TOKEN_ESCAPE_KEY;
1052
+ }
1053
+ /** Every token in `value`, in document order. `$concat` parts and `$map`
1054
+ * operands (`over`, then the `to` template) are visited: they may hold tokens
1055
+ * themselves. Each site carries the `$map` scopes it sits in. A `$$` escape
1056
+ * hides its operand. */
1057
+ function collectTokenSites(value) {
1058
+ const sites = [];
1059
+ visit(value, [], "root", [], sites);
1060
+ return sites;
1061
+ }
1062
+ function visit(value, path, position, scopes, sites) {
1063
+ const key = tokenKeyOf(value);
1064
+ if (key && isPlainObject(value)) {
1065
+ sites.push({
1066
+ path,
1067
+ key,
1068
+ token: value,
1069
+ position,
1070
+ scopes
1071
+ });
1072
+ const operand = value[key];
1073
+ if (key === "$concat" && Array.isArray(operand)) operand.forEach((part, index) => visit(part, [
1074
+ ...path,
1075
+ "$concat",
1076
+ index
1077
+ ], "concat", scopes, sites));
1078
+ if (key === "$map" && isPlainObject(operand)) {
1079
+ const at = [...path, "$map"];
1080
+ if ("over" in operand) visit(operand.over, [...at, "over"], "over", scopes, sites);
1081
+ if ("to" in operand) {
1082
+ const scope = {
1083
+ path,
1084
+ token: value,
1085
+ ...typeof operand.as === "string" ? { as: operand.as } : {}
1086
+ };
1087
+ visit(operand.to, [...at, "to"], "template", [...scopes, scope], sites);
1088
+ }
1089
+ }
1090
+ return;
1091
+ }
1092
+ if (Array.isArray(value)) {
1093
+ value.forEach((child, index) => visit(child, [...path, index], "element", scopes, sites));
1094
+ return;
1095
+ }
1096
+ if (!isPlainObject(value) || isEscape(value)) return;
1097
+ for (const [childKey, child] of Object.entries(value)) visit(child, [...path, childKey], "property", scopes, sites);
1098
+ }
1099
+ /** An `$item` path as text: `url`, `drives.x`, `<element>` for `[]`. */
1100
+ function pathText(path) {
1101
+ if (path.length === 0) return "<element>";
1102
+ return formatPath(path.filter((p) => typeof p === "string" || typeof p === "number"));
1103
+ }
1104
+ /** A one-line human rendering of a token, for `--explain` and messages. */
1105
+ function describeToken(token) {
1106
+ const key = tokenKeyOf(token);
1107
+ if (!key || !isPlainObject(token)) return JSON.stringify(token);
1108
+ const operand = token[key];
1109
+ if (key === "$output" && isPlainObject(operand)) return `$output ${typeof operand.host === "string" ? operand.host : "?"}${typeof operand.member === "string" ? ` (member ${operand.member})` : ""} › ${Array.isArray(operand.path) ? formatPath(operand.path.filter((p) => typeof p === "string" || typeof p === "number")) : "?"}`;
1110
+ if (key === "$env") {
1111
+ if (typeof operand === "string") return `$env ${operand}`;
1112
+ if (isPlainObject(operand) && typeof operand.name === "string") return `$env ${operand.name} (optional)`;
1113
+ }
1114
+ if (key === "$item") {
1115
+ const named = isPlainObject(operand) ? operand : void 0;
1116
+ const raw = named ? named.path : operand;
1117
+ const path = Array.isArray(raw) ? pathText(raw) : "?";
1118
+ return `$item${named && typeof named.as === "string" ? `(${named.as})` : ""} ${path}`;
1119
+ }
1120
+ if (key === "$key") return typeof operand === "string" ? `$key(${operand})` : "$key";
1121
+ if (key === "$map" && isPlainObject(operand)) {
1122
+ const as = typeof operand.as === "string" ? ` as ${operand.as}` : "";
1123
+ const into = operand.into === "record" ? " into record" : "";
1124
+ return `$map over [${describeToken(operand.over)}]${as}${into} → ${JSON.stringify(render(operand.to))}`;
1125
+ }
1126
+ if (key === "$concat" && Array.isArray(operand)) return `$concat ${operand.map((part) => typeof part === "string" ? JSON.stringify(part) : typeof part === "number" ? String(part) : `[${describeToken(part)}]`).join(" + ")}`;
1127
+ return `${key} ${JSON.stringify(operand)}`;
1128
+ }
1129
+ /** A display copy of `value` with every token replaced by `«description»`
1130
+ * (for printing declared hosts, e.g. `--explain drives`). */
1131
+ function renderTokens(value) {
1132
+ return render(value);
1133
+ }
1134
+ function render(value) {
1135
+ if (tokenKeyOf(value)) return `«${describeToken(value)}»`;
1136
+ if (Array.isArray(value)) return value.map(render);
1137
+ if (!isPlainObject(value) || isEscape(value)) return value;
1138
+ const out = {};
1139
+ for (const [key, child] of Object.entries(value)) out[key] = render(child);
1140
+ return out;
1141
+ }
1142
+ /** A copy of `value` with every `$$` escape replaced by its operand (the
1143
+ * literal it protects). Run after the no-token walk. */
1144
+ function unwrapEscapes(value) {
1145
+ return unwrap(value);
1146
+ }
1147
+ function unwrap(value) {
1148
+ if (Array.isArray(value)) return value.map(unwrap);
1149
+ if (!isPlainObject(value)) return value;
1150
+ if (isEscape(value)) return structuredClone(value[TOKEN_ESCAPE_KEY]);
1151
+ const out = {};
1152
+ for (const [key, child] of Object.entries(value)) out[key] = unwrap(child);
1153
+ return out;
1154
+ }
1155
+ //#endregion
1156
+ //#region src/resolve/declared.ts
1157
+ function refOf(site) {
1158
+ const operand = site.token.$output;
1159
+ if (!isPlainObject(operand) || typeof operand.host !== "string") return;
1160
+ return typeof operand.member === "string" ? {
1161
+ host: operand.host,
1162
+ member: operand.member
1163
+ } : { host: operand.host };
1164
+ }
1165
+ function pathOf(site) {
1166
+ const operand = site.token.$output;
1167
+ if (!isPlainObject(operand) || !Array.isArray(operand.path)) return [];
1168
+ return operand.path.filter((p) => typeof p === "string" || typeof p === "number");
1169
+ }
1170
+ function refKey(ref) {
1171
+ return ref.member ? `${ref.host}#${ref.member}` : ref.host;
1172
+ }
1173
+ /** The distinct producers a host's `$output` tokens name, in document order. */
1174
+ function outputRefsOf(host) {
1175
+ const seen = /* @__PURE__ */ new Map();
1176
+ for (const site of collectTokenSites(host)) {
1177
+ if (site.key !== "$output") continue;
1178
+ const ref = refOf(site);
1179
+ if (ref && !seen.has(refKey(ref))) seen.set(refKey(ref), ref);
1180
+ }
1181
+ return [...seen.values()];
1182
+ }
1183
+ /** Every `$output` token with its host path and producer (for the plan and
1184
+ * `--explain outputs`). */
1185
+ function outputSitesOf(host) {
1186
+ return collectTokenSites(host).flatMap((site) => {
1187
+ if (site.key !== "$output") return [];
1188
+ const ref = refOf(site);
1189
+ return ref ? [{
1190
+ path: formatPath(site.path),
1191
+ ref,
1192
+ outputPath: pathOf(site)
1193
+ }] : [];
1194
+ });
1195
+ }
1196
+ /** Every `$env` token with its host path (for `--explain outputs`). */
1197
+ function envSitesOf(host) {
1198
+ return collectTokenSites(host).flatMap((site) => {
1199
+ if (site.key !== "$env") return [];
1200
+ const operand = site.token.$env;
1201
+ if (typeof operand === "string") return [{
1202
+ path: formatPath(site.path),
1203
+ name: operand,
1204
+ optional: false
1205
+ }];
1206
+ if (isPlainObject(operand) && typeof operand.name === "string") return [{
1207
+ path: formatPath(site.path),
1208
+ name: operand.name,
1209
+ optional: true
1210
+ }];
1211
+ return [];
1212
+ });
1213
+ }
1214
+ /** The binding name an `$item`/`$key` site names (undefined: innermost). */
1215
+ function bindingNameOf(site) {
1216
+ const operand = site.token[site.key];
1217
+ if (site.key === "$key") return typeof operand === "string" ? operand : void 0;
1218
+ if (site.key === "$item" && isPlainObject(operand)) return typeof operand.as === "string" ? operand.as : void 0;
1219
+ }
1220
+ /** The enclosing `$map` an `$item`/`$key` site binds to, or why none. */
1221
+ function scopeOf(site) {
1222
+ const name = bindingNameOf(site);
1223
+ if (site.scopes.length === 0) return { error: `${site.key} is used outside any $map; it reads the element a $map template is rendering, so it is legal only inside a $map's \`to\` (or a nested $map's \`over\`).` };
1224
+ if (name === void 0) return site.scopes[site.scopes.length - 1];
1225
+ for (let i = site.scopes.length - 1; i >= 0; i--) if (site.scopes[i].as === name) return site.scopes[i];
1226
+ const named = site.scopes.flatMap((s) => s.as ? [`"${s.as}"`] : []);
1227
+ return { error: `${describeToken(site.token)} names the $map binding "${name}", which no enclosing $map declares (enclosing bindings: ${named.join(", ") || "none; add as: \"" + name + "\" to the outer $map"}).` };
1228
+ }
1229
+ /** Item path of an `$item` site. */
1230
+ function itemPathOf(site) {
1231
+ const operand = site.token.$item;
1232
+ const raw = isPlainObject(operand) ? operand.path : operand;
1233
+ return Array.isArray(raw) ? raw.filter((p) => typeof p === "string" || typeof p === "number") : [];
1234
+ }
1235
+ /** Operator shapes and placement: malformed operands, `$item`/`$key`
1236
+ * outside any `$map` or naming an unknown binding, and
1237
+ * `{ $env: { name, optional: true } }` anywhere but the direct value of an
1238
+ * object property (it omits that property when unset). */
1239
+ function checkTokenSites(host) {
1240
+ const issues = [];
1241
+ for (const site of collectTokenSites(host)) {
1242
+ const path = formatPath(site.path);
1243
+ if (!tokenSchema.safeParse(site.token).success) {
1244
+ issues.push({
1245
+ path,
1246
+ message: `malformed ${site.key} token ${JSON.stringify(site.token)}. Shapes: { $output: { host, member?, path: [...] } }, { $concat: [string | number | token, ...] }, { $env: "NAME" } or { $env: { name: "NAME", optional: true } }, { $map: { over: $output | $item, as?: "name", to: template, into?: "record" } }, { $item: [path] } or { $item: { as: "name", path: [...] } }, { $key: true } or { $key: "name" }.`
1247
+ });
1248
+ continue;
1249
+ }
1250
+ if (site.key === "$item" || site.key === "$key") {
1251
+ const scope = scopeOf(site);
1252
+ if ("error" in scope) issues.push({
1253
+ path,
1254
+ message: scope.error
1255
+ });
1256
+ continue;
1257
+ }
1258
+ const operand = site.token.$env;
1259
+ if (site.key === "$env" && isPlainObject(operand) && site.position !== "property") {
1260
+ const where = site.position === "concat" ? "a $concat part" : site.position === "element" ? "an array element" : site.position === "template" ? "the whole $map template" : "the whole host";
1261
+ issues.push({
1262
+ path,
1263
+ message: `{ $env: { name, optional: true } } is legal only as the direct value of an object property (it omits that property when ${String(operand.name)} is unset), not as ${where}. Use { $env: ${JSON.stringify(operand.name)} } here.`
1264
+ });
1265
+ }
1266
+ }
1267
+ return issues;
1268
+ }
1269
+ function defOf(schema) {
1270
+ if (!isPlainObjectLike(schema)) return void 0;
1271
+ const internals = schema._zod;
1272
+ if (!isPlainObjectLike(internals)) return void 0;
1273
+ const def = internals.def;
1274
+ if (!isPlainObjectLike(def) || typeof def.type !== "string") return void 0;
1275
+ return {
1276
+ ...def,
1277
+ type: def.type
1278
+ };
1279
+ }
1280
+ function isPlainObjectLike(value) {
1281
+ return (typeof value === "object" || typeof value === "function") && value !== null;
1282
+ }
1283
+ const WRAPPERS = /* @__PURE__ */ new Set([
1284
+ "optional",
1285
+ "nullable",
1286
+ "default",
1287
+ "prefault",
1288
+ "readonly",
1289
+ "nonoptional",
1290
+ "catch",
1291
+ "success"
1292
+ ]);
1293
+ /** The schema at `path` inside a zod schema (walking objects, records,
1294
+ * arrays, tuples, unions and wrappers), or why the path does not exist. */
1295
+ function schemaAtPath(schema, path) {
1296
+ let current = schema;
1297
+ for (let i = 0; i <= path.length; i++) {
1298
+ for (let guard = 0; guard < 32; guard++) {
1299
+ const def = defOf(current);
1300
+ if (!def) break;
1301
+ if (WRAPPERS.has(def.type)) current = def.innerType;
1302
+ else if (def.type === "lazy" && typeof def.getter === "function") {
1303
+ const getter = def.getter;
1304
+ current = getter();
1305
+ } else if (def.type === "pipe") {
1306
+ const out = defOf(def.out);
1307
+ current = out && out.type !== "transform" ? def.out : def.in;
1308
+ } else break;
1309
+ }
1310
+ if (i === path.length) return {
1311
+ ok: true,
1312
+ schema: current
1313
+ };
1314
+ const segment = path[i];
1315
+ const def = defOf(current);
1316
+ if (!def) return {
1317
+ ok: false,
1318
+ at: i,
1319
+ reason: "is not a schema"
1320
+ };
1321
+ switch (def.type) {
1322
+ case "any":
1323
+ case "unknown": return {
1324
+ ok: true,
1325
+ schema: current
1326
+ };
1327
+ case "object": {
1328
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1329
+ if (typeof segment === "string" && segment in shape) {
1330
+ current = shape[segment];
1331
+ break;
1332
+ }
1333
+ const catchall = defOf(def.catchall);
1334
+ if (catchall && catchall.type !== "never") {
1335
+ current = def.catchall;
1336
+ break;
1337
+ }
1338
+ const keys = Object.keys(shape);
1339
+ return {
1340
+ ok: false,
1341
+ at: i,
1342
+ reason: `has no key ${JSON.stringify(segment)} (keys: ${keys.join(", ") || "none"})`
1343
+ };
1344
+ }
1345
+ case "record":
1346
+ if (typeof segment !== "string") return {
1347
+ ok: false,
1348
+ at: i,
1349
+ reason: "is a record (string keys)"
1350
+ };
1351
+ current = def.valueType;
1352
+ break;
1353
+ case "array":
1354
+ if (typeof segment !== "number") return {
1355
+ ok: false,
1356
+ at: i,
1357
+ reason: "is an array (numeric index)"
1358
+ };
1359
+ current = def.element;
1360
+ break;
1361
+ case "tuple": {
1362
+ const items = Array.isArray(def.items) ? def.items : [];
1363
+ if (typeof segment !== "number" || segment >= items.length) return {
1364
+ ok: false,
1365
+ at: i,
1366
+ reason: `is a ${items.length}-tuple`
1367
+ };
1368
+ current = items[segment];
1369
+ break;
1370
+ }
1371
+ case "union": {
1372
+ const options = Array.isArray(def.options) ? def.options : [];
1373
+ for (const option of options) {
1374
+ const hit = schemaAtPath(option, path.slice(i));
1375
+ if (hit.ok) return hit;
1376
+ }
1377
+ return {
1378
+ ok: false,
1379
+ at: i,
1380
+ reason: "matches no union member"
1381
+ };
1382
+ }
1383
+ default: return {
1384
+ ok: false,
1385
+ at: i,
1386
+ reason: `is a ${def.type}, not a container`
1387
+ };
1388
+ }
1389
+ }
1390
+ return {
1391
+ ok: true,
1392
+ schema: current
1393
+ };
1394
+ }
1395
+ /** Whether the object schema at `path` names `key` in its shape (a
1396
+ * catchall does not count): what a runner's schema explicitly declares,
1397
+ * e.g. `runner.cspRegistrySync`. A union declares a key any member does. */
1398
+ function declaresKey(schema, path, key) {
1399
+ const at = schemaAtPath(schema, path);
1400
+ if (!at.ok) return false;
1401
+ const def = defOf(at.schema);
1402
+ if (def?.type === "object") return isPlainObjectLike(def.shape) && key in def.shape;
1403
+ if (def?.type === "union" && Array.isArray(def.options)) return def.options.some((option) => declaresKey(option, [], key));
1404
+ return false;
1405
+ }
1406
+ /** Whether a (property) schema admits an absent value on the OUTPUT side:
1407
+ * `.optional()` does; `.default()`/`.prefault()` fill it in, and
1408
+ * `.nonoptional()` forbids it. */
1409
+ function mayBeAbsent(schema) {
1410
+ let current = schema;
1411
+ for (let guard = 0; guard < 32; guard++) {
1412
+ const internals = isPlainObjectLike(current) ? current._zod : void 0;
1413
+ if (isPlainObjectLike(internals) && internals.optout === "optional") return true;
1414
+ const def = defOf(current);
1415
+ if (!def) return false;
1416
+ if (def.type === "optional") return true;
1417
+ if (def.type === "default" || def.type === "prefault" || def.type === "nonoptional" || !WRAPPERS.has(def.type)) return false;
1418
+ current = def.innerType;
1419
+ }
1420
+ return false;
1421
+ }
1422
+ /** Whether `key` may be absent from a value of the object schema `schema`:
1423
+ * an optional property, or (in a union) one some member makes optional or
1424
+ * lacks. A record value or an array element is never optional. */
1425
+ function optionalKeyIn(schema, key) {
1426
+ const unwrapped = schemaAtPath(schema, []);
1427
+ const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
1428
+ if (def?.type === "object") {
1429
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1430
+ return key in shape && mayBeAbsent(shape[key]);
1431
+ }
1432
+ if (def?.type === "union" && Array.isArray(def.options)) return def.options.some((option) => {
1433
+ const inner = schemaAtPath(option, []);
1434
+ const optionDef = inner.ok ? defOf(inner.schema) : void 0;
1435
+ const shape = optionDef?.type === "object" && isPlainObjectLike(optionDef.shape) ? optionDef.shape : void 0;
1436
+ return shape !== void 0 && (!(key in shape) || mayBeAbsent(shape[key]));
1437
+ });
1438
+ return false;
1439
+ }
1440
+ /**
1441
+ * Whether the field `path[at]` is OPTIONAL in `schema` (a producer's
1442
+ * `outputsSchema`, or a `$map` element schema), given that `path[0..at-1]`
1443
+ * exists: the codegen'd `OutputToken<T | undefined>` / `ItemToken<T |
1444
+ * undefined>` positions, whose rendered property the resolver omits when
1445
+ * the field is absent. False for a record key, an array index, or a path
1446
+ * the schema does not describe.
1447
+ */
1448
+ function isOptionalField(schema, path, at) {
1449
+ const key = path[at];
1450
+ if (typeof key !== "string") return false;
1451
+ const parent = schemaAtPath(schema, path.slice(0, at));
1452
+ return parent.ok && optionalKeyIn(parent.schema, key);
1453
+ }
1454
+ /** The element schema of a collection schema (array element, record
1455
+ * value), or undefined when the schema does not say. */
1456
+ function elementSchemaOf(schema) {
1457
+ const collection = collectionOf(schema);
1458
+ return collection.kind === "array" || collection.kind === "record" ? collection.element : void 0;
1459
+ }
1460
+ /** The collection kind of a schema (unwrapped): array, record, unknown (no
1461
+ * check possible) or something else. */
1462
+ function collectionOf(schema) {
1463
+ const unwrapped = schemaAtPath(schema, []);
1464
+ const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
1465
+ if (!def) return { kind: "unknown" };
1466
+ if (def.type === "array") return {
1467
+ kind: "array",
1468
+ element: def.element
1469
+ };
1470
+ if (def.type === "record") return {
1471
+ kind: "record",
1472
+ element: def.valueType
1473
+ };
1474
+ if (def.type === "object") {
1475
+ const catchall = defOf(def.catchall);
1476
+ if (catchall && catchall.type !== "never") {
1477
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1478
+ return Object.keys(shape).length === 0 ? {
1479
+ kind: "record",
1480
+ element: def.catchall
1481
+ } : {
1482
+ kind: "record",
1483
+ element: void 0
1484
+ };
1485
+ }
1486
+ }
1487
+ if (def.type === "tuple") return {
1488
+ kind: "array",
1489
+ element: void 0
1490
+ };
1491
+ if (def.type === "any" || def.type === "unknown" || def.type === "union") return { kind: "unknown" };
1492
+ return {
1493
+ kind: "other",
1494
+ type: def.type
1495
+ };
1496
+ }
1497
+ /** Every `$output` token's producer exists and its path is valid against
1498
+ * the producer's `outputsSchema`; every `$map`'s `over` is a collection
1499
+ * there (a record under `into: "record"`), and every `$item` path exists
1500
+ * in the element schema of the map it binds. */
1501
+ function checkOutputPaths(host, outputsSchemaOf) {
1502
+ const issues = [];
1503
+ const elements = /* @__PURE__ */ new Map();
1504
+ const elementOf = (scope) => "error" in scope ? void 0 : elements.get(scope.token);
1505
+ for (const site of collectTokenSites(host)) {
1506
+ if (!tokenSchema.safeParse(site.token).success) continue;
1507
+ if (site.key === "$map") {
1508
+ elements.set(site.token, checkMap(site, outputsSchemaOf, elementOf, issues));
1509
+ continue;
1510
+ }
1511
+ if (site.key === "$item") {
1512
+ const scope = scopeOf(site);
1513
+ const element = elementOf(scope);
1514
+ if (!element || element.element === void 0 || "error" in scope) continue;
1515
+ const itemPath = itemPathOf(site);
1516
+ const hit = schemaAtPath(element.element, itemPath);
1517
+ if (!hit.ok) {
1518
+ const parent = itemPath.slice(0, hit.at);
1519
+ issues.push({
1520
+ path: formatPath(site.path),
1521
+ message: `${describeToken(site.token)}: the element${parent.length ? `'s ${formatPath(parent)}` : ""} of the $map at ${formatPath(scope.path)}${scope.as ? ` (as "${scope.as}")` : ""} ${hit.reason} (element of ${element.label}).`
1522
+ });
1523
+ }
1524
+ continue;
1525
+ }
1526
+ if (site.key !== "$output") continue;
1527
+ const ref = refOf(site);
1528
+ if (!ref) continue;
1529
+ const path = formatPath(site.path);
1530
+ const lookup = outputsSchemaOf(ref);
1531
+ if ("error" in lookup) {
1532
+ issues.push({
1533
+ path,
1534
+ message: lookup.error
1535
+ });
1536
+ continue;
1537
+ }
1538
+ const outputPath = pathOf(site);
1539
+ const hit = schemaAtPath(lookup.schema, outputPath);
1540
+ if (!hit.ok) {
1541
+ const parent = outputPath.slice(0, hit.at);
1542
+ const where = parent.length ? `outputs.${formatPath(parent)}` : "the outputs";
1543
+ issues.push({
1544
+ path,
1545
+ message: `${describeToken(site.token)}: ${where} ${hit.reason} in the outputsSchema of ${lookup.label}.`
1546
+ });
1547
+ }
1548
+ }
1549
+ return issues;
1550
+ }
1551
+ /** A `$map`'s `over` against its schema: a collection (a record under
1552
+ * `into: "record"`). Returns the element schema for the map's `$item`s. */
1553
+ function checkMap(site, outputsSchemaOf, elementOf, issues) {
1554
+ const operand = site.token.$map;
1555
+ if (!isPlainObject(operand)) return void 0;
1556
+ const over = operand.over;
1557
+ const into = operand.into === "record";
1558
+ let schema;
1559
+ let label;
1560
+ if (isPlainObject(over) && "$output" in over) {
1561
+ const overSite = {
1562
+ ...site,
1563
+ key: "$output",
1564
+ token: over
1565
+ };
1566
+ const ref = refOf(overSite);
1567
+ if (!ref) return void 0;
1568
+ const lookup = outputsSchemaOf(ref);
1569
+ if ("error" in lookup) return void 0;
1570
+ const hit = schemaAtPath(lookup.schema, pathOf(overSite));
1571
+ if (!hit.ok) return void 0;
1572
+ schema = hit.schema;
1573
+ label = `${describeToken(over)} in the outputsSchema of ${lookup.label}`;
1574
+ } else if (isPlainObject(over) && "$item" in over) {
1575
+ const overSite = {
1576
+ ...site,
1577
+ key: "$item",
1578
+ token: over
1579
+ };
1580
+ const outer = elementOf(scopeOf(overSite));
1581
+ if (!outer || outer.element === void 0) return void 0;
1582
+ const hit = schemaAtPath(outer.element, itemPathOf(overSite));
1583
+ if (!hit.ok) return void 0;
1584
+ schema = hit.schema;
1585
+ label = `${describeToken(over)} (element of ${outer.label})`;
1586
+ } else return;
1587
+ const path = formatPath(site.path);
1588
+ const collection = collectionOf(schema);
1589
+ if (collection.kind === "unknown") return void 0;
1590
+ if (collection.kind === "other") {
1591
+ issues.push({
1592
+ path,
1593
+ message: `$map over ${label} is a ${collection.type}, not an array or a record; a $map iterates a collection.`
1594
+ });
1595
+ return;
1596
+ }
1597
+ if (into && collection.kind === "array") {
1598
+ issues.push({
1599
+ path,
1600
+ message: `$map with into: "record" maps over ${label}, which is an array: an array has no keys to keep. Drop into: "record" (the result is an array) or map over a record.`
1601
+ });
1602
+ return;
1603
+ }
1604
+ return {
1605
+ element: collection.element,
1606
+ label
1607
+ };
1608
+ }
1609
+ //#endregion
1610
+ //#region src/resolve/removed-forms.ts
1611
+ function outputToken(host, path, member) {
1612
+ return `{ $output: { host: "${host}"${member ? `, member: "${member}"` : ""}, path: [${path.map((p) => JSON.stringify(p)).join(", ")}] } }`;
1613
+ }
1614
+ function isDriveReference(value) {
1615
+ if (!isPlainObject(value)) return false;
1616
+ const keys = Object.keys(value).sort();
1617
+ return keys.length === 2 && keys[0] === "from" && keys[1] === "slug" && typeof value.from === "string" && typeof value.slug === "string";
1618
+ }
1619
+ function checkReactor(reactor, base, found) {
1620
+ if (!isPlainObject(reactor) || !isPlainObject(reactor.backends)) return;
1621
+ for (const [name, backend] of Object.entries(reactor.backends)) {
1622
+ if (!isPlainObject(backend) || !isPlainObject(backend.remote)) continue;
1623
+ const host = backend.remote.host;
1624
+ if (host === void 0) continue;
1625
+ const producer = typeof host === "string" ? host : "switchboard";
1626
+ found.push({
1627
+ path: `${base}reactor.backends.${name}.remote.host`,
1628
+ message: `remote: { host } was removed; use a drive address: remote: { url: ${producer}.drives.<slug>.url } with ${producer} from ../${producer}/outputs.js, or remote: { url: ${outputToken(producer, [
1629
+ "drives",
1630
+ "<slug>",
1631
+ "url"
1632
+ ])} }.`
1633
+ });
1634
+ }
1635
+ }
1636
+ function checkPlugins(runner, base, memberHosts, found) {
1637
+ if (!isPlainObject(runner) || !Array.isArray(runner.plugins)) return;
1638
+ runner.plugins.forEach((entry, index) => {
1639
+ if (!isPlainObject(entry) || !isPlainObject(entry.config)) return;
1640
+ for (const [key, value] of Object.entries(entry.config)) {
1641
+ if (!isDriveReference(value)) continue;
1642
+ const host = memberHosts[value.from] ?? value.from;
1643
+ const member = memberHosts[value.from] ? value.from : void 0;
1644
+ found.push({
1645
+ path: `${base}runner.plugins[${index}].config.${key}`,
1646
+ message: `${key}: { from, slug } was removed; use ${host}.drives.${value.slug}.url from ../${host}/outputs.js, or ${outputToken(host, [
1647
+ "drives",
1648
+ value.slug,
1649
+ "url"
1650
+ ])}${member ? ` (add member: "${member}" if two members run host "${host}")` : ""}.`
1651
+ });
1652
+ }
1653
+ });
1654
+ }
1655
+ /** Every removed form in a host file (reactor or compound), in document
1656
+ * order. Compound wrappers are checked too. */
1657
+ function findRemovedForms(host) {
1658
+ const found = [];
1659
+ if (!isPlainObject(host)) return found;
1660
+ const children = isPlainObject(host.children) ? host.children : void 0;
1661
+ const memberHosts = {};
1662
+ for (const [key, wrapper] of Object.entries(children ?? {})) if (isPlainObject(wrapper) && typeof wrapper.host === "string") memberHosts[key] = wrapper.host;
1663
+ checkReactor(host.reactor, "", found);
1664
+ checkPlugins(host.runner, "", memberHosts, found);
1665
+ for (const [key, wrapper] of Object.entries(children ?? {})) {
1666
+ if (!isPlainObject(wrapper)) continue;
1667
+ checkReactor(wrapper.reactor, `children.${key}.`, found);
1668
+ checkPlugins(wrapper.runner, `children.${key}.`, memberHosts, found);
1669
+ }
1670
+ if (children && isPlainObject(host.config)) for (const key of ["projectDrivesIntoConnect", "drivesPublicBase"]) {
1671
+ if (host.config[key] === void 0) continue;
1672
+ found.push({
1673
+ path: `config.${key}`,
1674
+ message: `config.${key} was removed; declare the drives on the member that consumes them, by output token: reactor.drives: [{ slug: "<slug>", remote: { url: ${outputToken("switchboard", [
1675
+ "drives",
1676
+ "<slug>",
1677
+ "url"
1678
+ ])} } }].`
1679
+ });
1680
+ }
1681
+ return found;
1682
+ }
1683
+ //#endregion
1684
+ //#region src/env-substitution.ts
1685
+ /** The always-resolvable `$env` names (also the `"${name}"` sugar). */
1686
+ const BUILTIN_ENV_NAMES = ["userData", "projectRoot"];
1687
+ function isBuiltinEnvName(name) {
1688
+ return BUILTIN_ENV_NAMES.includes(name);
1689
+ }
1690
+ const BUILTIN = new RegExp(`\\$\\{(${BUILTIN_ENV_NAMES.join("|")})\\}`, "g");
1691
+ function substitute(text, env) {
1692
+ return text.replace(BUILTIN, (match, name) => env[name] ?? match);
1693
+ }
1694
+ /** Deep-substitute the built-ins that `env` provides in every string; an
1695
+ * absent built-in is left as written. The input is never mutated. */
1696
+ function substituteBuiltinEnv(value, env) {
1697
+ return substituteValue(value, env);
1698
+ }
1699
+ function substituteValue(value, env) {
1700
+ if (typeof value === "string") return substitute(value, env);
1701
+ if (Array.isArray(value)) return value.map((v) => substituteValue(v, env));
1702
+ if (value !== null && typeof value === "object") {
1703
+ const out = {};
1704
+ for (const [k, v] of Object.entries(value)) out[k] = substituteValue(v, env);
1705
+ return out;
1706
+ }
1707
+ return value;
1708
+ }
1709
+ //#endregion
1710
+ //#region src/resolve/plan.ts
1711
+ /**
1712
+ * The dependency plan (pipeline step 4): which compound member consumes
1713
+ * which member's outputs, and the start order that follows. Producers start
1714
+ * before consumers; `config.startOrder` is optional and, when given, must
1715
+ * agree with the tokens. Cycles fail. Pure.
1716
+ */
1717
+ var PlanError = class extends Error {
1718
+ constructor(message) {
1719
+ super(message);
1720
+ this.name = "PlanError";
1721
+ }
1722
+ };
1723
+ /** The member a ref names: the unique member running `ref.host`, or the
1724
+ * member `ref.member` when given (it must run `ref.host`). */
1725
+ function memberForRef(ref, members) {
1726
+ if (ref.member !== void 0) {
1727
+ const named = members.find((m) => m.key === ref.member);
1728
+ if (!named) return { error: `names member "${ref.member}", which this compound does not declare (members: ${members.map((m) => m.key).join(", ")}).` };
1729
+ if (named.host !== ref.host) return { error: `names member "${ref.member}" of host "${ref.host}", but that member runs host "${named.host}".` };
1730
+ return { key: named.key };
1731
+ }
1732
+ const running = members.filter((m) => m.host === ref.host);
1733
+ if (running.length === 1) return { key: running[0].key };
1734
+ if (running.length === 0) return { error: `names host "${ref.host}", which no member of this compound runs (members run: ${[...new Set(members.map((m) => m.host))].join(", ")}).` };
1735
+ return { error: `names host "${ref.host}", which members ${running.map((m) => `"${m.key}"`).join(" and ")} both run; add member: "<key>" to pick one.` };
1736
+ }
1737
+ function edgesOf(members) {
1738
+ const edges = [];
1739
+ const problems = [];
1740
+ for (const member of members) {
1741
+ const seen = /* @__PURE__ */ new Set();
1742
+ for (const { ref, path } of member.refs) {
1743
+ const target = memberForRef(ref, members);
1744
+ if ("error" in target) {
1745
+ problems.push(`${member.key}: ${path} ${target.error}`);
1746
+ continue;
1747
+ }
1748
+ if (target.key === member.key) {
1749
+ problems.push(`${member.key}: ${path} reads ${refKey(ref)}'s outputs, which is this member itself.`);
1750
+ continue;
1751
+ }
1752
+ if (seen.has(target.key)) continue;
1753
+ seen.add(target.key);
1754
+ edges.push({
1755
+ consumer: member.key,
1756
+ producer: target.key,
1757
+ path
1758
+ });
1759
+ }
1760
+ }
1761
+ if (problems.length > 0) throw new PlanError(problems.join("\n"));
1762
+ return edges;
1763
+ }
1764
+ /** Declared start order: the named members first, then the rest in
1765
+ * declaration order. */
1766
+ function declaredOrder(members, startOrder) {
1767
+ const keys = members.map((m) => m.key);
1768
+ const named = [...new Set(startOrder)].filter((k) => keys.includes(k));
1769
+ return [...named, ...keys.filter((k) => !named.includes(k))];
1770
+ }
1771
+ function planCompound(members, startOrder) {
1772
+ const edges = edgesOf(members);
1773
+ if (startOrder) {
1774
+ const order = declaredOrder(members, startOrder);
1775
+ const index = new Map(order.map((k, i) => [k, i]));
1776
+ const bad = edges.filter((e) => (index.get(e.producer) ?? 0) > (index.get(e.consumer) ?? 0));
1777
+ if (bad.length > 0) throw new PlanError(bad.map((e) => `config.startOrder starts "${e.consumer}" before "${e.producer}", but ${e.consumer}.${e.path} consumes "${e.producer}"'s outputs. Reorder startOrder (or omit it: the order follows the tokens).`).join("\n"));
1778
+ return {
1779
+ order,
1780
+ edges,
1781
+ source: "startOrder"
1782
+ };
1783
+ }
1784
+ const pending = new Map(members.map((m) => [m.key, /* @__PURE__ */ new Set()]));
1785
+ for (const e of edges) pending.get(e.consumer)?.add(e.producer);
1786
+ const order = [];
1787
+ while (order.length < members.length) {
1788
+ const next = members.find((m) => !order.includes(m.key) && pending.get(m.key)?.size === 0);
1789
+ if (!next) {
1790
+ const stuck = members.filter((m) => !order.includes(m.key));
1791
+ throw new PlanError(`output tokens form a cycle between ${stuck.map((m) => `"${m.key}"`).join(", ")}: ${edges.filter((e) => stuck.some((m) => m.key === e.consumer) && stuck.some((m) => m.key === e.producer)).map((e) => `${e.consumer} (${e.path}) needs ${e.producer}`).join("; ")}.`);
1792
+ }
1793
+ order.push(next.key);
1794
+ for (const set of pending.values()) set.delete(next.key);
1795
+ }
1796
+ return {
1797
+ order,
1798
+ edges,
1799
+ source: "tokens"
1800
+ };
1801
+ }
1802
+ //#endregion
1803
+ //#region src/resolve/resolve.ts
1804
+ var TokenResolutionError = class extends Error {
1805
+ /** The host path that failed and the reason, without the file prefix. */
1806
+ detail;
1807
+ constructor(message, detail) {
1808
+ super(message);
1809
+ this.name = "TokenResolutionError";
1810
+ if (detail) this.detail = detail;
1811
+ }
1812
+ };
1813
+ /** Why a required `$env` cannot resolve. */
1814
+ function unsetEnvMessage(name) {
1815
+ return `reads $env ${name}, which is not set. Set ${name} in the environment of the process that resolves this host (or declare { $env: { name: "${name}", optional: true } } to omit the property when unset).`;
1816
+ }
1817
+ /** A resolved `{ $env: { name, optional: true } }` whose variable is unset,
1818
+ * or an `$output`/`$item` reading an absent optional field: its enclosing
1819
+ * property is omitted. */
1820
+ const OMIT = Symbol("omit");
1821
+ /** `reactor.drives["workflows"]` (or `…[2]` for an array element). */
1822
+ function elementText(binding) {
1823
+ const key = typeof binding.key === "number" ? `[${binding.key}]` : `[${JSON.stringify(binding.key)}]`;
1824
+ return `${formatPath(binding.path)}${key}`;
1825
+ }
1826
+ /** Provenance of `$map`-rendered arrays: element index → the input key
1827
+ * (record key, or array index) it was rendered from. Lets resolved
1828
+ * validation name the element key, not just the result index. */
1829
+ const renderedKeys = /* @__PURE__ */ new WeakMap();
1830
+ /**
1831
+ * The `$map` elements an issue path (from resolved validation of a resolved
1832
+ * host) passes through, as text: `$map element "workflows"`. Undefined when
1833
+ * the path crosses no `$map`-rendered array. Walk the SAME object
1834
+ * `resolveHostOutputs` returned (provenance is by identity).
1835
+ */
1836
+ function describeMapElements(host, path) {
1837
+ const found = [];
1838
+ let current = host;
1839
+ for (const segment of path) if (Array.isArray(current) && typeof segment === "number") {
1840
+ const key = renderedKeys.get(current)?.[segment];
1841
+ if (key !== void 0) found.push(`$map element ${typeof key === "number" ? `[${key}]` : JSON.stringify(key)}`);
1842
+ current = current[segment];
1843
+ } else if (isPlainObject(current) && typeof segment === "string") current = current[segment];
1844
+ else break;
1845
+ return found.length ? found.join(" › ") : void 0;
1846
+ }
1847
+ /** A deep copy of a resolved (JSON-shaped) value that keeps the `$map`
1848
+ * provenance of its rendered arrays (structuredClone would drop it). */
1849
+ function cloneWithProvenance(value) {
1850
+ if (Array.isArray(value)) {
1851
+ const copy = value.map(cloneWithProvenance);
1852
+ const keys = renderedKeys.get(value);
1853
+ if (keys) renderedKeys.set(copy, keys);
1854
+ return copy;
1855
+ }
1856
+ if (isPlainObject(value)) {
1857
+ const copy = {};
1858
+ for (const [key, child] of Object.entries(value)) copy[key] = cloneWithProvenance(child);
1859
+ return copy;
1860
+ }
1861
+ return value;
1862
+ }
1863
+ /** The value at `path` inside `root` (output data: records and arrays). */
1864
+ function walkPath(root, path) {
1865
+ let current = root;
1866
+ for (let i = 0; i < path.length; i++) {
1867
+ const segment = path[i];
1868
+ const next = Array.isArray(current) ? typeof segment === "number" ? current[segment] : void 0 : isPlainObject(current) && typeof segment === "string" ? current[segment] : void 0;
1869
+ if (next === void 0) {
1870
+ const has = isPlainObject(current) ? Object.keys(current).join(", ") || "nothing" : Array.isArray(current) ? `${current.length} elements` : JSON.stringify(current);
1871
+ return {
1872
+ ok: false,
1873
+ at: i,
1874
+ has
1875
+ };
1876
+ }
1877
+ current = next;
1878
+ }
1879
+ return {
1880
+ ok: true,
1881
+ value: current
1882
+ };
1883
+ }
1884
+ /** The schema at `path` inside `schema`, when both are known. */
1885
+ function schemaOf(schema, path) {
1886
+ if (schema === void 0) return void 0;
1887
+ const hit = schemaAtPath(schema, path);
1888
+ return hit.ok ? hit.schema : void 0;
1889
+ }
1890
+ function pathSegments(path) {
1891
+ return path.filter((p) => typeof p === "string" || typeof p === "number");
1892
+ }
1893
+ var Resolver = class {
1894
+ sources;
1895
+ self;
1896
+ deferred = [];
1897
+ /** What the last OMIT stood for, for the "nothing to omit" errors. */
1898
+ omitted = "an optional $env";
1899
+ constructor(sources, self) {
1900
+ this.sources = sources;
1901
+ this.self = self;
1902
+ }
1903
+ /** The member keys a token reads (`$output` on a member's host), when
1904
+ * resolving a compound's own fields with `deferSelf`. */
1905
+ selfRefs(token, trail) {
1906
+ if (!this.self) return [];
1907
+ const keys = /* @__PURE__ */ new Set();
1908
+ for (const site of collectTokenSites(token)) {
1909
+ const operand = site.token.$output;
1910
+ if (site.key !== "$output" || !isPlainObject(operand)) continue;
1911
+ if (typeof operand.host !== "string") continue;
1912
+ const ref = typeof operand.member === "string" ? {
1913
+ host: operand.host,
1914
+ member: operand.member
1915
+ } : { host: operand.host };
1916
+ if (this.self === "outputs") {
1917
+ keys.add(refKey(ref));
1918
+ continue;
1919
+ }
1920
+ if (!this.self.members.some((m) => m.host === ref.host)) continue;
1921
+ const target = memberForRef(ref, this.self.members);
1922
+ if ("error" in target) this.fail([...trail, ...site.path], `in a compound ${target.error}`);
1923
+ keys.add(target.key);
1924
+ }
1925
+ return [...keys];
1926
+ }
1927
+ fail(trail, message, scope = []) {
1928
+ const where = this.sources.where ? `${this.sources.where}: ` : "";
1929
+ const inside = scope.length ? ` (rendering $map element ${scope.map(elementText).join(" › ")})` : "";
1930
+ const path = formatPath(trail);
1931
+ throw new TokenResolutionError(`${where}\`${path}\` ${message}${inside}`, {
1932
+ path,
1933
+ reason: `${message}${inside}`
1934
+ });
1935
+ }
1936
+ value(value, trail, scope = []) {
1937
+ if (typeof value === "string") return this.sources.builtins ? substituteBuiltinEnv(value, this.sources.builtins) : value;
1938
+ if (Array.isArray(value)) return value.map((child, index) => {
1939
+ const out = this.value(child, [...trail, index], scope);
1940
+ if (out === OMIT) this.fail([...trail, index], `is ${this.omitted} inside an array.`, scope);
1941
+ return out;
1942
+ });
1943
+ if (!isPlainObject(value)) return value;
1944
+ if (isEscape(value)) return structuredClone(value);
1945
+ if (tokenKeyOf(value)) {
1946
+ const members = scope.length === 0 ? this.selfRefs(value, trail) : [];
1947
+ if (members.length > 0) {
1948
+ this.deferred.push({
1949
+ trail,
1950
+ token: value,
1951
+ members
1952
+ });
1953
+ return structuredClone(value);
1954
+ }
1955
+ return this.token(value, trail, scope);
1956
+ }
1957
+ const out = {};
1958
+ for (const [key, child] of Object.entries(value)) {
1959
+ if (typeof this.self === "object" && trail.length === 0 && key === "children") {
1960
+ out[key] = child;
1961
+ continue;
1962
+ }
1963
+ const resolved = this.value(child, [...trail, key], scope);
1964
+ if (resolved !== OMIT) out[key] = resolved;
1965
+ }
1966
+ return out;
1967
+ }
1968
+ token(token, trail, scope = []) {
1969
+ if (!tokenSchema.safeParse(token).success) this.fail(trail, `is a malformed token: ${JSON.stringify(token)}.`, scope);
1970
+ switch (tokenKeyOf(token)) {
1971
+ case "$output": return this.output(token, trail, scope);
1972
+ case "$env": return this.env(token.$env, trail, scope);
1973
+ case "$concat": return this.concat(token.$concat, trail, scope);
1974
+ case "$map": return this.map(token.$map, trail, scope);
1975
+ case "$item": return this.item(token.$item, trail, scope);
1976
+ case "$key": return this.key(token.$key, trail, scope);
1977
+ default: return this.fail(trail, `is not a token.`, scope);
1978
+ }
1979
+ }
1980
+ /** The binding an `$item`/`$key` names: the innermost map, or the
1981
+ * enclosing map whose `as` is `name`. */
1982
+ binding(name, operator, trail, scope) {
1983
+ if (scope.length === 0) return this.fail(trail, `uses ${operator} outside any $map; ${operator} reads the element a $map template is rendering.`);
1984
+ if (name === void 0) return scope[scope.length - 1];
1985
+ for (let i = scope.length - 1; i >= 0; i--) if (scope[i].as === name) return scope[i];
1986
+ const named = scope.flatMap((b) => b.as ? [`"${b.as}"`] : []);
1987
+ return this.fail(trail, `uses ${operator} with binding "${name}", which no enclosing $map declares (as: ${named.join(", ") || "none"}).`, scope);
1988
+ }
1989
+ map(operand, trail, scope) {
1990
+ if (!isPlainObject(operand)) return this.fail(trail, "is a malformed $map token.", scope);
1991
+ const into = operand.into === "record";
1992
+ const as = typeof operand.as === "string" ? operand.as : void 0;
1993
+ const read = this.readWithSchema(operand.over, [
1994
+ ...trail,
1995
+ "$map",
1996
+ "over"
1997
+ ], scope);
1998
+ const over = read.value;
1999
+ if (over === OMIT) return OMIT;
2000
+ const element = read.schema === void 0 ? void 0 : elementSchemaOf(read.schema);
2001
+ const render = (key, item) => {
2002
+ const inner = [...scope, {
2003
+ path: trail,
2004
+ key,
2005
+ item,
2006
+ ...as !== void 0 ? { as } : {},
2007
+ ...element !== void 0 ? { schema: element } : {}
2008
+ }];
2009
+ const at = [
2010
+ ...trail,
2011
+ "$map",
2012
+ "to"
2013
+ ];
2014
+ const out = this.value(operand.to, at, inner);
2015
+ if (out === OMIT) return this.fail(at, `is ${this.omitted} as the whole $map template; there is no property to omit.`, inner);
2016
+ return out;
2017
+ };
2018
+ if (Array.isArray(over)) {
2019
+ if (into) return this.fail(trail, `is a $map with into: "record", but its over (${describeToken(operand.over)}) resolved to an array, which has no keys to keep. Drop into: "record" (the result is an array) or map over a record.`, scope);
2020
+ const rendered = over.map((item, index) => render(index, item));
2021
+ renderedKeys.set(rendered, over.map((_, index) => index));
2022
+ return rendered;
2023
+ }
2024
+ if (isPlainObject(over)) {
2025
+ const keys = Object.keys(over).sort();
2026
+ if (!into) {
2027
+ const rendered = keys.map((key) => render(key, over[key]));
2028
+ renderedKeys.set(rendered, keys);
2029
+ return rendered;
2030
+ }
2031
+ const out = {};
2032
+ for (const key of keys) out[key] = render(key, over[key]);
2033
+ return out;
2034
+ }
2035
+ return this.fail(trail, `is a $map whose over (${describeToken(operand.over)}) resolved to ${JSON.stringify(over)}${into ? `; into: "record" needs a record` : ", which is not an array or a record"}.`, scope);
2036
+ }
2037
+ item(operand, trail, scope) {
2038
+ return this.readItem(operand, trail, scope).value;
2039
+ }
2040
+ /** A `$map`'s `over` with the schema describing it, when it reads a
2041
+ * schema'd `$output` (or an `$item` of a schema'd element). */
2042
+ readWithSchema(value, trail, scope) {
2043
+ const key = tokenKeyOf(value);
2044
+ if (isPlainObject(value) && (key === "$output" || key === "$item") && tokenSchema.safeParse(value).success) return key === "$output" ? this.readOutput(value, trail, scope) : this.readItem(value.$item, trail, scope);
2045
+ return { value: this.value(value, trail, scope) };
2046
+ }
2047
+ omit(what) {
2048
+ this.omitted = what;
2049
+ return { value: OMIT };
2050
+ }
2051
+ readItem(operand, trail, scope) {
2052
+ const named = isPlainObject(operand) ? operand : void 0;
2053
+ const name = named && typeof named.as === "string" ? named.as : void 0;
2054
+ const raw = named ? named.path : operand;
2055
+ const path = pathSegments(Array.isArray(raw) ? raw : []);
2056
+ const binding = this.binding(name, "$item", trail, scope);
2057
+ const hit = walkPath(binding.item, path);
2058
+ if (!hit.ok) {
2059
+ if (binding.schema !== void 0 && isOptionalField(binding.schema, path, hit.at)) return this.omit("an absent optional $item field");
2060
+ const missing = formatPath(path.slice(0, hit.at + 1));
2061
+ return this.fail(trail, `reads $item ${formatPath(path)}, but $map element ${elementText(binding)} has no ${missing} (it has: ${hit.has}).`, scope);
2062
+ }
2063
+ return {
2064
+ value: structuredClone(hit.value),
2065
+ schema: schemaOf(binding.schema, path)
2066
+ };
2067
+ }
2068
+ key(operand, trail, scope) {
2069
+ const name = typeof operand === "string" ? operand : void 0;
2070
+ return this.binding(name, "$key", trail, scope).key;
2071
+ }
2072
+ output(token, trail, scope = []) {
2073
+ return this.readOutput(token, trail, scope).value;
2074
+ }
2075
+ readOutput(token, trail, scope) {
2076
+ const operand = token.$output;
2077
+ if (!isPlainObject(operand) || typeof operand.host !== "string") return this.fail(trail, "is a malformed $output token.", scope);
2078
+ const ref = typeof operand.member === "string" ? {
2079
+ host: operand.host,
2080
+ member: operand.member
2081
+ } : { host: operand.host };
2082
+ const path = pathSegments(Array.isArray(operand.path) ? operand.path : []);
2083
+ if (!this.sources.outputs) return this.fail(trail, `reads ${describeToken(token)}, but no outputs are available here.`, scope);
2084
+ const lookup = this.sources.outputs.lookup(ref);
2085
+ if (lookup.status === "unavailable") {
2086
+ const where = this.sources.where ? `${this.sources.where}: ` : "";
2087
+ const path = formatPath(trail);
2088
+ const reason = `${lookup.message}\n (needed by \`${path}\`: ${describeToken(token)})`;
2089
+ throw new TokenResolutionError(`${where}${reason}`, {
2090
+ path,
2091
+ reason
2092
+ });
2093
+ }
2094
+ const hit = walkPath(lookup.outputs, path);
2095
+ if (!hit.ok) {
2096
+ if (lookup.schema !== void 0 && isOptionalField(lookup.schema, path, hit.at)) return this.omit("an absent optional output");
2097
+ const parent = path.slice(0, hit.at);
2098
+ const container = parent.length ? `outputs.${formatPath(parent)}` : "its outputs";
2099
+ const missing = formatPath(path.slice(0, hit.at + 1));
2100
+ return this.fail(trail, `reads ${describeToken(token)}, but host "${ref.host}" has no output at ${missing} (${container} has: ${hit.has}).`, scope);
2101
+ }
2102
+ return {
2103
+ value: structuredClone(hit.value),
2104
+ schema: schemaOf(lookup.schema, path)
2105
+ };
2106
+ }
2107
+ env(operand, trail, scope = []) {
2108
+ const optional = isPlainObject(operand);
2109
+ const name = optional ? operand.name : operand;
2110
+ if (typeof name !== "string") return this.fail(trail, "is a malformed $env token.", scope);
2111
+ const builtins = this.sources.builtins;
2112
+ if (isBuiltinEnvName(name) && builtins?.[name]) return builtins[name];
2113
+ const value = this.sources.env?.[name];
2114
+ if (value !== void 0) return value;
2115
+ if (optional) return this.omit("an optional $env").value;
2116
+ return this.fail(trail, unsetEnvMessage(name), scope);
2117
+ }
2118
+ concat(parts, trail, scope = []) {
2119
+ if (!Array.isArray(parts)) return this.fail(trail, "is a malformed $concat token.", scope);
2120
+ return parts.map((part, index) => {
2121
+ const at = [
2122
+ ...trail,
2123
+ "$concat",
2124
+ index
2125
+ ];
2126
+ const value = this.value(part, at, scope);
2127
+ if (value === OMIT) return this.fail(at, `is ${this.omitted} inside $concat.`, scope);
2128
+ if (typeof value === "string") return value;
2129
+ if (typeof value === "number") return String(value);
2130
+ return this.fail(at, `resolved to ${JSON.stringify(value)}; every $concat part must be a string or a number.`, scope);
2131
+ }).join("");
2132
+ }
2133
+ };
2134
+ function resolveHostOutputs(host, sources, options) {
2135
+ const resolver = new Resolver(sources, options?.deferSelf);
2136
+ const out = resolver.value(host, []);
2137
+ if (out === OMIT) resolver.fail([], `is ${resolver.omitted} with nothing to omit it from.`);
2138
+ const partial = out;
2139
+ if (!options) return partial;
2140
+ const sites = resolver.deferred;
2141
+ return {
2142
+ host: partial,
2143
+ deferred: sites.map((d) => ({
2144
+ path: formatPath(d.trail),
2145
+ members: d.members
2146
+ })),
2147
+ needs: [...new Set(sites.flatMap((d) => d.members))],
2148
+ finish(outputs) {
2149
+ const done = cloneWithProvenance(partial);
2150
+ const late = new Resolver({
2151
+ ...sources,
2152
+ outputs
2153
+ });
2154
+ for (const site of sites) {
2155
+ const value = late.token(site.token, site.trail);
2156
+ if (value === OMIT && typeof site.trail.at(-1) === "number") late.fail(site.trail, `is ${late.omitted} inside an array.`);
2157
+ setAt(done, site.trail, value === OMIT ? void 0 : value, value === OMIT);
2158
+ }
2159
+ return done;
2160
+ }
2161
+ };
2162
+ }
2163
+ function setAt(root, trail, value, omit) {
2164
+ let current = root;
2165
+ for (const key of trail.slice(0, -1)) if (Array.isArray(current) && typeof key === "number") current = current[key];
2166
+ else if (isPlainObject(current) && typeof key === "string") current = current[key];
2167
+ else return;
2168
+ const last = trail[trail.length - 1];
2169
+ if (Array.isArray(current) && typeof last === "number") current[last] = value;
2170
+ else if (isPlainObject(current) && typeof last === "string") {
2171
+ if (omit) delete current[last];
2172
+ else current[last] = value;
2173
+ }
2174
+ }
2175
+ //#endregion
2176
+ //#region src/runner-resolver.ts
2177
+ /**
2178
+ * Resolves a host's `runner.module` specifier from the PROJECT's dependency
2179
+ * tree (not ph-cli's), imports it, and checks the runner-module contract:
2180
+ * `{ run, hostSchema, kind, outputsSchema?, verbs?, ...optionalVerbs }`.
2181
+ */
2182
+ var RunnerError = class extends Error {
2183
+ constructor(message, hint) {
2184
+ super(hint ? `${message}\n Hint: ${hint}` : message);
2185
+ this.name = "RunnerError";
2186
+ }
2187
+ };
2188
+ /** Whether a value is zod-shaped (has a `safeParse` function): a runner's
2189
+ * `outputsSchema`, a plugin's config schema. */
2190
+ function isSchemaLike(value) {
2191
+ return typeof value === "object" && value !== null && "safeParse" in value && typeof value.safeParse === "function";
2192
+ }
2193
+ /** The Connect runner's specifier: compounds forward `cspRegistrySync` to
2194
+ * it, and `--explain` prints its dead-config warnings. */
2195
+ const CONNECT_RUNNER = "@powerhousedao/ph-cli/runners/connect";
2196
+ /** Exports that are part of the contract but are not verbs. */
2197
+ const NON_VERB_EXPORTS = /* @__PURE__ */ new Set([
2198
+ "hostSchema",
2199
+ "declaredHostSchema",
2200
+ "outputsSchema",
2201
+ "verbs",
2202
+ "kind",
2203
+ "checkBoot",
2204
+ "default"
2205
+ ]);
2206
+ /** ph-cli's runners are ph-run's plus the verbs that build. A packaged app has
2207
+ * only ph-run, and its host files, generated against ph-cli's, name ph-cli's. */
2208
+ function runnerFallback(specifier) {
2209
+ const name = /^@powerhousedao\/ph-cli\/(runners\/.+)$/.exec(specifier)?.[1];
2210
+ return name ? `@powerhousedao/ph-run/${name}` : void 0;
2211
+ }
2212
+ async function resolveRunnerModule(projectRoot, specifier) {
2213
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
2214
+ const resolveFirst = (candidates) => {
2215
+ const [first, ...rest] = candidates;
2216
+ try {
2217
+ return projectRequire.resolve(first);
2218
+ } catch (error) {
2219
+ if (rest.length === 0) throw error;
2220
+ return resolveFirst(rest);
2221
+ }
2222
+ };
2223
+ let resolved;
2224
+ try {
2225
+ const fallback = runnerFallback(specifier);
2226
+ resolved = resolveFirst(fallback ? [specifier, fallback] : [specifier]);
2227
+ } catch {
2228
+ throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project (install it, then retry).");
2229
+ }
2230
+ const module = await import(pathToFileURL(resolved).href);
2231
+ if (typeof module.run !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`run\` function (required verb).`);
2232
+ const hostSchema = module.hostSchema;
2233
+ if (!hostSchema || typeof hostSchema.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`hostSchema\` — runners validate their own host shape.`);
2234
+ const declared = module.declaredHostSchema;
2235
+ if (declared !== void 0 && typeof declared.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" exports a \`declaredHostSchema\` without safeParse.`);
2236
+ if (module.checkBoot !== void 0 && typeof module.checkBoot !== "function") throw new RunnerError(`Runner "${specifier}" exports a \`checkBoot\` that is not a function.`);
2237
+ const verbs = module.verbs;
2238
+ if (verbs !== void 0 && (!Array.isArray(verbs) || !verbs.every((verb) => typeof verb === "string" && typeof module[verb] === "function"))) throw new RunnerError(`Runner "${specifier}" exports \`verbs\` ${JSON.stringify(verbs)}, which must list names of exported functions.`);
2239
+ if (!runnerKindSchema.safeParse(module.kind).success) throw new RunnerError(`Runner "${specifier}" does not export a valid \`kind\` (got ${JSON.stringify(module.kind)}; expected "reactor" | "compound").`);
2240
+ return module;
2241
+ }
2242
+ /** Verbs that produce something and start nothing (`build`): no outputs, no
2243
+ * record, no lock — and no token resolution, since what they read (output
2244
+ * dirs, packages) never comes from another host's outputs. Their verb gets
2245
+ * the declared host (tokens may remain in token-able fields). */
2246
+ const ONE_SHOT_VERBS = /* @__PURE__ */ new Set(["build"]);
2247
+ function listVerbs(runner) {
2248
+ if (runner.verbs) return runner.verbs.filter((name) => typeof runner[name] === "function").toSorted();
2249
+ return Object.entries(runner).filter(([name, value]) => typeof value === "function" && !NON_VERB_EXPORTS.has(name)).map(([name]) => name).sort();
2250
+ }
2251
+ function getVerb(runner, specifier, verb) {
2252
+ const candidate = runner[verb];
2253
+ if (typeof candidate !== "function" || !listVerbs(runner).includes(verb)) throw new RunnerError(`Runner "${specifier}" does not support the verb "${verb}". Supported verbs: ${listVerbs(runner).join(", ")}.`);
2254
+ return candidate;
2255
+ }
2256
+ function isRecord$2(value) {
2257
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2258
+ }
2259
+ /** reactor XOR children, decided by the runner's declared `kind`. */
2260
+ function kindShapeIssues(kind, specifier, host) {
2261
+ if (kind === "reactor" && host.children !== void 0) return [{
2262
+ path: "children",
2263
+ message: `"${specifier}" is a reactor runner, so the host must not declare \`children\`.`,
2264
+ hint: "`children` belongs to compound hosts; a reactor host configures its own `reactor` block."
2265
+ }];
2266
+ if (kind === "compound" && host.reactor !== void 0) return [{
2267
+ path: "reactor",
2268
+ message: `"${specifier}" is a compound runner, so the host must not declare \`reactor\`.`,
2269
+ hint: "A compound's reactors are its members': configure them in the member host or a wrapper's `reactor` override."
2270
+ }];
2271
+ return [];
2272
+ }
2273
+ function assertKindShape(kind, specifier, host, file) {
2274
+ const issue = kindShapeIssues(kind, specifier, host).at(0);
2275
+ if (issue) throw new RunnerError(`${file}: ${issue.message}`, issue.hint);
2276
+ }
2277
+ /** `runner.defaultVerb` and every plugin entry's `verbs` must name verbs
2278
+ * this runner exports. */
2279
+ function knownVerbIssues(runner, specifier, host) {
2280
+ const options = host.runner;
2281
+ if (!isRecord$2(options)) return [];
2282
+ const verbs = listVerbs(runner);
2283
+ const unknownVerb = (verb) => typeof verb === "string" && !verbs.includes(verb);
2284
+ const issues = [];
2285
+ if (unknownVerb(options.defaultVerb)) issues.push({
2286
+ path: "runner.defaultVerb",
2287
+ message: `runner.defaultVerb "${options.defaultVerb}" is not a verb of "${specifier}". Supported verbs: ${verbs.join(", ")}.`
2288
+ });
2289
+ (Array.isArray(options.plugins) ? options.plugins : []).forEach((entry, index) => {
2290
+ if (!isRecord$2(entry) || !Array.isArray(entry.verbs)) return;
2291
+ const scoped = entry.verbs;
2292
+ for (const bad of scoped.filter(unknownVerb)) issues.push({
2293
+ path: `runner.plugins[${index}].verbs`,
2294
+ message: `plugin "${String(entry.module)}" is scoped to verb "${bad}", which "${specifier}" does not export. Supported verbs: ${verbs.join(", ")}.`
2295
+ });
2296
+ });
2297
+ return issues;
2298
+ }
2299
+ function formatIssues(issues) {
2300
+ return issues.map((i) => ` - ${i.path}: ${i.message}`).join("\n");
2301
+ }
2302
+ function valueAt(host, path) {
2303
+ let current = host;
2304
+ for (const key of path) if (Array.isArray(current) && typeof key === "number") current = current[key];
2305
+ else if (isRecord$2(current) && typeof key === "string") current = current[key];
2306
+ else return;
2307
+ return current;
2308
+ }
2309
+ /**
2310
+ * Resolved validation (pipeline step 6): validate a RESOLVED host against
2311
+ * its runner's `hostSchema` and return the PARSED host (what the verb
2312
+ * receives). Run `resolveHostOutputs` first; a token still present fails
2313
+ * with its path.
2314
+ */
2315
+ function validateHost(runner, specifier, host, file, options = {}) {
2316
+ return parseHost(runner, options.tokens === "allow" ? runner.declaredHostSchema ?? runner.hostSchema : runner.hostSchema, specifier, host, file, options);
2317
+ }
2318
+ /** What `validateHost` checks, as data: nothing throws. */
2319
+ function hostSchemaIssues(runner, schema, specifier, host, options = {}) {
2320
+ const issues = [];
2321
+ if (isRecord$2(host)) {
2322
+ issues.push(...kindShapeIssues(runner.kind, specifier, host));
2323
+ if (options.tokens !== "allow") {
2324
+ const token = findToken(host);
2325
+ if (token) issues.push({
2326
+ path: token.path,
2327
+ message: `\`${token.path}\` is an unresolved output token (${token.key}).`,
2328
+ hint: "Resolve the host (resolveHostOutputs) before validating it for a verb; `ph run` does this."
2329
+ });
2330
+ }
2331
+ issues.push(...knownVerbIssues(runner, specifier, host));
2332
+ }
2333
+ const result = schema.safeParse(unwrapEscapes(host));
2334
+ if (result.success) return {
2335
+ issues,
2336
+ data: result.data
2337
+ };
2338
+ return {
2339
+ issues,
2340
+ schemaIssues: result.error.issues.map((issue) => {
2341
+ const element = describeMapElements(host, issue.path);
2342
+ const dotted = (issue.path.map(String).join(".") || "<root>") + (element ? ` (${element})` : "");
2343
+ const message = issue.code !== "custom" && tokenKeyOf(valueAt(host, issue.path)) ? "this field does not take an output token (it is not token-able); spell the value literally." : issue.message;
2344
+ return {
2345
+ path: formatPath(issue.path.filter((key) => typeof key === "string" || typeof key === "number")),
2346
+ message: element ? `${message} (${element})` : message,
2347
+ printed: `${dotted}: ${message}`
2348
+ };
2349
+ })
2350
+ };
2351
+ }
2352
+ function parseHost(runner, schema, specifier, host, file, options) {
2353
+ const checked = hostSchemaIssues(runner, schema, specifier, host, options);
2354
+ const first = checked.issues.at(0);
2355
+ if (first) throw new RunnerError(`${file}: ${first.message}`, first.hint);
2356
+ if (checked.schemaIssues) throw new RunnerError(`${file} failed validation against the hostSchema of "${specifier}":\n${checked.schemaIssues.map((issue) => ` - ${issue.printed}`).join("\n") || " (no details reported)"}`);
2357
+ return checked.data;
2358
+ }
2359
+ /**
2360
+ * Declared validation (pipeline step 3): the removed cross-host forms
2361
+ * (each error names its token form), token shapes and `$env` `optional`
2362
+ * placement, `$output` paths against the producers' `outputsSchema`s, then
2363
+ * the runner's `declaredHostSchema` (tokens allowed in token-able fields).
2364
+ * Reads no environment value and needs no producer running. Throws on the
2365
+ * first failing stage; resolve, then `validateHost`, before a verb runs.
2366
+ */
2367
+ function validateDeclaredHost(runner, specifier, host, file, options = {}) {
2368
+ const removed = findRemovedForms(host);
2369
+ if (removed.length > 0) throw new RunnerError(`${file}: removed form:\n${formatIssues(removed)}`);
2370
+ const issues = checkTokenSites(host);
2371
+ if (options.outputsSchemaOf) issues.push(...checkOutputPaths(host, options.outputsSchemaOf));
2372
+ if (issues.length > 0) throw new RunnerError(`${file}: invalid output token:\n${formatIssues(issues)}`);
2373
+ if (isRecord$2(host)) assertKindShape(runner.kind, specifier, host, file);
2374
+ if (!runner.declaredHostSchema) return;
2375
+ parseHost(runner, runner.declaredHostSchema, specifier, host, file, { tokens: "allow" });
2376
+ }
2377
+ //#endregion
2378
+ //#region src/host-loader.ts
2379
+ /**
2380
+ * Loads and pre-validates a `hosts/<name>/host.js` definition.
2381
+ *
2382
+ * A host file is a static PROJECTION of powerhouse.config.json: plain ESM,
2383
+ * default-exporting a data object. Three gates run before any runner sees it:
2384
+ * 1. import lint — the only legal imports are the project's
2385
+ * powerhouse.config.json, sibling `../<host>/host.js` files and sibling
2386
+ * generated `../<host>/outputs.js` token trees (host files are data, not
2387
+ * programs; `process.` is banned, environment values go through `$env`).
2388
+ * An imported outputs.js whose schema hash no longer matches its
2389
+ * producer fails here ("run `ph generate hosts`");
2390
+ * 2. static check — the exported object must survive a JSON round trip
2391
+ * (functions, undefined, class instances, Dates etc. are rejected,
2392
+ * reporting the offending path);
2393
+ * 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children
2394
+ * rule. Full validation is the runner's `hostSchema` (phase 2).
2395
+ *
2396
+ * This module never exits the process — callers own error presentation.
2397
+ */
2398
+ const HOST_FILE = "host.js";
2399
+ const CONFIG_IMPORT_SUFFIX = "powerhouse.config.json";
2400
+ var HostLoadError = class extends Error {
2401
+ constructor(message, hint) {
2402
+ super(hint ? `${message}\n Hint: ${hint}` : message);
2403
+ this.name = "HostLoadError";
2404
+ }
2405
+ };
2406
+ /** A `hosts/` folder with no `<name>/host.js` inside is "empty" — the guard
2407
+ * state: callers warn loudly and fall back to legacy rather than activating
2408
+ * the new architecture off a stray `mkdir hosts`. */
2409
+ function probeHostsFolder(projectRoot) {
2410
+ const dir = path.join(projectRoot, "hosts");
2411
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return { kind: "absent" };
2412
+ const hosts = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, HOST_FILE))).map((entry) => entry.name).sort();
2413
+ return hosts.length === 0 ? {
2414
+ kind: "empty",
2415
+ dir
2416
+ } : {
2417
+ kind: "present",
2418
+ dir,
2419
+ hosts
2420
+ };
2421
+ }
2422
+ /** Sibling imports: `../<host>/host.js` — source material for derived
2423
+ * compositions (full-inclusion wrappers compute over them with plain JS) —
2424
+ * and `../<host>/outputs.js`, the generated `$output` token tree. */
2425
+ const SIBLING_IMPORT = /^\.\.\/([A-Za-z0-9_-]+)\/(host\.js|outputs\.js)$/;
2426
+ /** The generated per-host token tree (`ph generate hosts`). */
2427
+ const OUTPUTS_FILE = "outputs.js";
2428
+ const GENERATE_HINT = "Run `ph generate hosts` to (re)generate hosts/<name>/outputs.js from the producer's runner outputsSchema and declared drives.";
2429
+ /**
2430
+ * One pass over JS source that blanks every comment and, with
2431
+ * `literals: "blank"`, the CONTENTS of string literals and template-literal
2432
+ * text (quotes, backticks and `${`/`}` kept). A template's `${…}` holes are
2433
+ * code: they are scanned like the rest (strings, nested templates and braces
2434
+ * inside them included). Every newline survives, so line-anchored checks and
2435
+ * line numbers still match the original source. Regex literals are not
2436
+ * recognised (host files are data; a regex is not one).
2437
+ */
2438
+ function scanSource(source, literals) {
2439
+ const blank = (text) => text.replace(/[^\n]/g, " ");
2440
+ const literal = (text) => literals === "blank" ? blank(text) : text;
2441
+ let out = "";
2442
+ let i = 0;
2443
+ const holes = [];
2444
+ /** Template text from `i` (just after a backtick or a hole's `}`) up to
2445
+ * and including its closing backtick, or up to and including the next
2446
+ * `${` (pushing a hole). */
2447
+ const templateText = () => {
2448
+ let j = i;
2449
+ while (j < source.length) {
2450
+ const ch = source[j];
2451
+ if (ch === "\\") {
2452
+ j += 2;
2453
+ continue;
2454
+ }
2455
+ if (ch === "`") break;
2456
+ if (ch === "$" && source[j + 1] === "{") break;
2457
+ j++;
2458
+ }
2459
+ out += literal(source.slice(i, Math.min(j, source.length)));
2460
+ if (j >= source.length) i = source.length;
2461
+ else if (source[j] === "`") {
2462
+ out += "`";
2463
+ i = j + 1;
2464
+ } else {
2465
+ out += "${";
2466
+ holes.push(0);
2467
+ i = j + 2;
2468
+ }
2469
+ };
2470
+ while (i < source.length) {
2471
+ const ch = source[i];
2472
+ const next = source[i + 1];
2473
+ if (ch === "/" && next === "/") {
2474
+ const end = source.indexOf("\n", i);
2475
+ const stop = end === -1 ? source.length : end;
2476
+ out += blank(source.slice(i, stop));
2477
+ i = stop;
2478
+ continue;
2479
+ }
2480
+ if (ch === "/" && next === "*") {
2481
+ const end = source.indexOf("*/", i + 2);
2482
+ const stop = end === -1 ? source.length : end + 2;
2483
+ out += blank(source.slice(i, stop));
2484
+ i = stop;
2485
+ continue;
2486
+ }
2487
+ if (ch === "\"" || ch === "'") {
2488
+ let j = i + 1;
2489
+ while (j < source.length && source[j] !== ch && source[j] !== "\n") j += source[j] === "\\" ? 2 : 1;
2490
+ const close = source[j] === ch ? ch : "";
2491
+ out += ch + literal(source.slice(i + 1, Math.min(j, source.length)));
2492
+ out += close;
2493
+ i = close ? j + 1 : j;
2494
+ continue;
2495
+ }
2496
+ if (ch === "`") {
2497
+ out += "`";
2498
+ i++;
2499
+ templateText();
2500
+ continue;
2501
+ }
2502
+ if (holes.length > 0 && ch === "{") holes[holes.length - 1]++;
2503
+ if (holes.length > 0 && ch === "}") {
2504
+ if (holes[holes.length - 1] === 0) {
2505
+ holes.pop();
2506
+ out += "}";
2507
+ i++;
2508
+ templateText();
2509
+ continue;
2510
+ }
2511
+ holes[holes.length - 1]--;
2512
+ }
2513
+ out += ch;
2514
+ i++;
2515
+ }
2516
+ return out;
2517
+ }
2518
+ /** Blank out `//` and block comments, keeping string and template literals
2519
+ * (URLs contain `//`) and every newline, so line-anchored checks still see
2520
+ * the code's own lines. A JSDoc `import("…")` type is a comment, not code. */
2521
+ function stripComments(source) {
2522
+ return scanSource(source, "keep");
2523
+ }
2524
+ /** Blank out comments and the contents of string literals and
2525
+ * template-literal text, so a word inside a string (a URL, a description,
2526
+ * an apostrophe in template text) is neither mistaken for code nor able to
2527
+ * hide code. Template `${…}` holes are code and are kept. */
2528
+ function blankLiterals(source) {
2529
+ return scanSource(source, "blank");
2530
+ }
2531
+ const PROCESS_ACCESS = /(?<![.\w$])process\s*(?:\?\.|\.|\[)/;
2532
+ /** Host files and generated outputs.js are data: reading the environment
2533
+ * through `process.` is banned (typed-host-configs decision 9). Environment
2534
+ * values go through `$env`, which resolves at start in the resolving
2535
+ * process. Comments are already stripped, so a mention there is fine. */
2536
+ function rejectProcessAccess(source, file) {
2537
+ const match = PROCESS_ACCESS.exec(blankLiterals(source));
2538
+ if (!match) return;
2539
+ const line = source.slice(0, match.index).split("\n").length;
2540
+ throw new HostLoadError(`${file}:${line} reads \`process.\` — host files cannot read the environment directly.`, "Use an $env token instead: { $env: \"NAME\" } (fails when unset), or { $env: { name: \"NAME\", optional: true } } as a property value to omit the property when unset. It resolves when the host starts.");
2541
+ }
2542
+ /** Lints a host file and returns what it imports. Rejects every import
2543
+ * except the project's powerhouse.config.json, SIBLING host files (R1:
2544
+ * derived compositions) and sibling generated outputs.js token trees; any
2545
+ * dynamic `import(...)` or `require(...)`; and any `process.` access.
2546
+ * Source-level enforcement: the JSON round trip below is the hard gate; this
2547
+ * one produces the better error. */
2548
+ function scanHostImports(rawSource, file) {
2549
+ const source = stripComments(rawSource);
2550
+ const imports = {
2551
+ hosts: [],
2552
+ outputs: []
2553
+ };
2554
+ for (const match of source.matchAll(/^\s*import\b[^;'"]*?from\s+["']([^"']+)["']/gm)) {
2555
+ const specifier = match[1];
2556
+ if (specifier.endsWith(CONFIG_IMPORT_SUFFIX)) continue;
2557
+ const sibling = SIBLING_IMPORT.exec(specifier);
2558
+ if (sibling) {
2559
+ (sibling[2] === HOST_FILE ? imports.hosts : imports.outputs).push(sibling[1]);
2560
+ continue;
2561
+ }
2562
+ throw new HostLoadError(`${file} imports "${specifier}" — a host file may only import the project's powerhouse.config.json, sibling hosts/<name>/host.js files or generated hosts/<name>/${OUTPUTS_FILE} token trees.`, "Host files are static projections; code belongs in plugins or the runner.");
2563
+ }
2564
+ if (/^\s*import\s+["']/m.test(source)) throw new HostLoadError(`${file} contains a side-effect import — a host file may only import the project's powerhouse.config.json or sibling host files.`);
2565
+ if (/\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} uses dynamic import()/require() — host files are static data.`);
2566
+ rejectProcessAccess(source, file);
2567
+ return imports;
2568
+ }
2569
+ /** {@link scanHostImports}, returning only the sibling host names (for cycle
2570
+ * detection). */
2571
+ function lintHostImports(rawSource, file) {
2572
+ return scanHostImports(rawSource, file).hosts;
2573
+ }
2574
+ /** A generated `outputs.js` is plain data: no imports of any kind, no
2575
+ * dynamic import/require, no `process.`. */
2576
+ function lintOutputsFile(rawSource, file) {
2577
+ const source = stripComments(rawSource);
2578
+ if (/^\s*import\b/m.test(source) || /^\s*export\b[^;]*?\bfrom\s+["']/m.test(source) || /\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} imports a module — a generated ${OUTPUTS_FILE} is plain data.`, "Regenerate it with `ph generate hosts` instead of editing it.");
2579
+ rejectProcessAccess(source, file);
2580
+ }
2581
+ /** Walks the sibling-import graph from `hostName`, linting every visited file
2582
+ * (and every outputs.js it imports) and failing on a cycle (an ESM circular
2583
+ * would otherwise surface as an undefined default export with no useful
2584
+ * message). Returns the hosts whose outputs.js the graph imports, sorted. */
2585
+ function lintHostImportGraph(hostsDir, hostName) {
2586
+ const state = /* @__PURE__ */ new Map();
2587
+ const producers = /* @__PURE__ */ new Set();
2588
+ const visit = (name, chain) => {
2589
+ const mark = state.get(name);
2590
+ if (mark === "done") return;
2591
+ if (mark === "visiting") throw new HostLoadError(`Host import cycle: ${[...chain, name].map((n) => `hosts/${n}`).join(" -> ")}.`, "Hoist the shared data into one host (or powerhouse.config.json) instead of importing both ways.");
2592
+ const file = path.join(hostsDir, name, HOST_FILE);
2593
+ if (!existsSync(file)) throw new HostLoadError(`hosts/${chain[chain.length - 1] ?? name} imports sibling "hosts/${name}/host.js", which does not exist.`);
2594
+ state.set(name, "visiting");
2595
+ const imports = scanHostImports(readFileSync(file, "utf8"), file);
2596
+ for (const producer of imports.outputs) {
2597
+ if (producers.has(producer)) continue;
2598
+ const outputsFile = path.join(hostsDir, producer, OUTPUTS_FILE);
2599
+ if (!existsSync(outputsFile)) throw new HostLoadError(`hosts/${name}/host.js imports "hosts/${producer}/${OUTPUTS_FILE}", which does not exist.`, GENERATE_HINT);
2600
+ lintOutputsFile(readFileSync(outputsFile, "utf8"), outputsFile);
2601
+ producers.add(producer);
2602
+ }
2603
+ for (const sibling of imports.hosts) visit(sibling, [...chain, name]);
2604
+ state.set(name, "done");
2605
+ };
2606
+ visit(hostName, []);
2607
+ return [...producers].sort();
2608
+ }
2609
+ /** Returns the path of the first value that would not survive a JSON round
2610
+ * trip, or undefined when the object is fully static. */
2611
+ function findNonStaticValue(value, trail = "") {
2612
+ if (value === null) return void 0;
2613
+ const kind = typeof value;
2614
+ if (kind === "string" || kind === "number" || kind === "boolean") return;
2615
+ if (kind !== "object") return `${trail || "<root>"} (${kind})`;
2616
+ if (Array.isArray(value)) {
2617
+ for (let i = 0; i < value.length; i++) {
2618
+ const hit = findNonStaticValue(value[i], `${trail}[${i}]`);
2619
+ if (hit) return hit;
2620
+ }
2621
+ return;
2622
+ }
2623
+ const proto = Object.getPrototypeOf(value);
2624
+ if (proto !== Object.prototype && proto !== null) return `${trail || "<root>"} (non-plain object)`;
2625
+ for (const [key, child] of Object.entries(value)) {
2626
+ const hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);
2627
+ if (hit) return hit;
2628
+ }
2629
+ }
2630
+ function assertHostShape(host, file) {
2631
+ if (typeof host.name !== "string" || host.name.length === 0) throw new HostLoadError(`${file}: \`name\` must be a non-empty string.`);
2632
+ const runner = host.runner;
2633
+ if (runner === null || typeof runner !== "object" || typeof runner.module !== "string") throw new HostLoadError(`${file}: \`runner\` must be an object with a \`module\` specifier string.`);
2634
+ if (host.reactor !== void 0 && host.children !== void 0) throw new HostLoadError(`${file}: \`reactor\` and \`children\` are mutually exclusive — a host is a reactor runner or a compound runner, never both.`);
2635
+ }
2636
+ async function loadHost(projectRoot, hostName) {
2637
+ return importHost(projectRoot, hostName, true);
2638
+ }
2639
+ async function importHost(projectRoot, hostName, checkOutputs) {
2640
+ const probe = probeHostsFolder(projectRoot);
2641
+ if (probe.kind === "absent") throw new HostLoadError(`No hosts/ folder found in ${projectRoot}.`, "Scaffold one with `ph init --uniform-runners` (or create hosts/<name>/host.js).");
2642
+ if (probe.kind === "empty") throw new HostLoadError(`hosts/ exists at ${probe.dir} but contains no <name>/host.js.`, "An empty hosts/ folder does not activate the uniform-runners architecture; add a host definition or remove the folder.");
2643
+ if (!probe.hosts.includes(hostName)) throw new HostLoadError(`Unknown host "${hostName}". Available hosts: ${probe.hosts.join(", ")}.`);
2644
+ const file = path.join(probe.dir, hostName, HOST_FILE);
2645
+ const producers = lintHostImportGraph(probe.dir, hostName);
2646
+ if (checkOutputs) for (const producer of producers) await assertOutputsFileFresh(projectRoot, probe.dir, hostName, producer);
2647
+ const host = (await import(pathToFileURL(file).href)).default;
2648
+ if (host === null || typeof host !== "object" || Array.isArray(host)) throw new HostLoadError(`${file} must default-export the host object (\`export default { name, runner, ... }\`).`);
2649
+ const nonStatic = findNonStaticValue(host);
2650
+ if (nonStatic) throw new HostLoadError(`${file} exports a non-static value at \`${nonStatic}\` — host files must survive a JSON round trip.`, "Runtime behavior belongs in the runner; host files only carry data.");
2651
+ assertHostShape(host, file);
2652
+ return {
2653
+ name: hostName,
2654
+ dir: path.dirname(file),
2655
+ file,
2656
+ host
2657
+ };
2658
+ }
2659
+ const OUTPUTS_HASH_EXPORT = /^export const outputsHash = "([^"]+)";$/m;
2660
+ /** The hash a generated outputs.js carries, or undefined. */
2661
+ function readOutputsFileHash(source) {
2662
+ return OUTPUTS_HASH_EXPORT.exec(source)?.[1];
2663
+ }
2664
+ function canonicalJson(value) {
2665
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
2666
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, child]) => child !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(",")}}`;
2667
+ return JSON.stringify(value);
2668
+ }
2669
+ /** sha256 over the canonical JSON of the generator's inputs. The host name
2670
+ * is one: every token in the file carries it, so a copied or renamed host
2671
+ * folder makes its outputs.js stale. */
2672
+ function computeOutputsHash(input) {
2673
+ return `sha256:${createHash("sha256").update(canonicalJson({
2674
+ v: 1,
2675
+ host: input.host,
2676
+ runnerModule: input.runnerModule,
2677
+ outputsSchema: input.outputsSchema,
2678
+ drives: [...new Set(input.drives)].sort()
2679
+ })).digest("hex").slice(0, 32)}`;
2680
+ }
2681
+ function isZodSchema(value) {
2682
+ return value !== null && typeof value === "object" && "_zod" in value;
2683
+ }
2684
+ function isRecord$1(value) {
2685
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2686
+ }
2687
+ /** Local (non-remote) slugs from a drive declaration list. */
2688
+ function localDriveSlugs(drives) {
2689
+ if (!Array.isArray(drives)) return [];
2690
+ return drives.flatMap((drive) => isRecord$1(drive) && typeof drive.slug === "string" && drive.remote === void 0 ? [drive.slug] : []);
2691
+ }
2692
+ /**
2693
+ * Describes the outputs a host's creation produces, for `ph generate hosts`
2694
+ * and the loader's staleness check: the runner's `outputsSchema` as JSON
2695
+ * Schema and the host's declared local drives (the keys `drives.<slug>` of a
2696
+ * switchboard-like runner). Returns undefined when the runner exports no
2697
+ * `outputsSchema` (the host produces nothing a token can reference).
2698
+ *
2699
+ * Plugin-contributed drives are collected across every verb (verb scoping
2700
+ * is ignored: a drive any verb serves is referenceable). Plugins the project
2701
+ * tree cannot resolve contribute nothing, exactly as at boot. The implicit
2702
+ * default drive a switchboard serves when it declares none is NOT a known
2703
+ * key (it is not declared); reach it with a literal `$output` token.
2704
+ */
2705
+ async function describeHostOutputs(projectRoot, hostName) {
2706
+ const { host, file } = await importHost(projectRoot, hostName, false);
2707
+ const runnerModule = host.runner.module;
2708
+ const schema = (await resolveRunnerModule(projectRoot, runnerModule)).outputsSchema;
2709
+ if (!isZodSchema(schema)) return void 0;
2710
+ const { $schema: _dialect, ...outputsSchema } = z.toJSONSchema(schema, {
2711
+ io: "output",
2712
+ unrepresentable: "any"
2713
+ });
2714
+ const reactor = host.reactor;
2715
+ const drives = localDriveSlugs(isRecord$1(reactor) ? reactor.drives : []);
2716
+ const entries = (host.runner.plugins ?? []).map((entry) => typeof entry === "string" ? entry : {
2717
+ ...entry,
2718
+ verbs: "*"
2719
+ });
2720
+ if (entries.length > 0) {
2721
+ const plan = await resolvePluginContributions(projectRoot, "*", entries, path.relative(projectRoot, file));
2722
+ drives.push(...localDriveSlugs(plan.drives.map((drive) => drive.declaration)));
2723
+ }
2724
+ const sortedDrives = [...new Set(drives)].sort();
2725
+ return {
2726
+ host: hostName,
2727
+ runnerModule,
2728
+ outputsSchema,
2729
+ drives: sortedDrives,
2730
+ hash: computeOutputsHash({
2731
+ host: hostName,
2732
+ runnerModule,
2733
+ outputsSchema,
2734
+ drives: sortedDrives
2735
+ })
2736
+ };
2737
+ }
2738
+ async function assertOutputsFileFresh(projectRoot, hostsDir, consumer, producer) {
2739
+ const rel = `hosts/${producer}/${OUTPUTS_FILE}`;
2740
+ const actual = readOutputsFileHash(readFileSync(path.join(hostsDir, producer, OUTPUTS_FILE), "utf8"));
2741
+ if (!existsSync(path.join(hostsDir, producer, HOST_FILE))) throw new HostLoadError(`hosts/${consumer} imports ${rel}, but there is no hosts/${producer}/host.js to produce it.`, "Delete the orphaned outputs.js and fix the import.");
2742
+ const description = await describeHostOutputs(projectRoot, producer);
2743
+ if (!description) throw new HostLoadError(`hosts/${consumer} imports ${rel}, but hosts/${producer}'s runner declares no outputsSchema, so it produces no outputs.`);
2744
+ if (actual !== description.hash) throw new HostLoadError(`${rel} is stale (its producer's outputsSchema or declared drives changed since it was generated); run \`ph generate hosts\`.`, actual === void 0 ? `${rel} carries no outputsHash export; it was not generated by \`ph generate hosts\`.` : `expected ${description.hash}, found ${actual}.`);
2745
+ }
2746
+ //#endregion
2747
+ //#region src/run-record-schema.ts
2748
+ /**
2749
+ * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running
2750
+ * host and its members produced. Validated on read; a v1 (or any invalid)
2751
+ * record reads as "not running". `projectName` is kept beyond the plan's
2752
+ * sketch because the live/foreign probe needs it. `host` is the host's
2753
+ * `name` (the file key), not its folder.
2754
+ */
2755
+ const outputsSchema = z.record(z.string(), z.unknown());
2756
+ const runRecordMemberSchema = z.strictObject({
2757
+ /** The member's host folder (`children.<key>.host`). */
2758
+ host: z.string().min(1),
2759
+ runnerModule: z.string().min(1),
2760
+ kind: runnerKindSchema,
2761
+ verb: z.string().min(1),
2762
+ outputs: outputsSchema
2763
+ });
2764
+ const runRecordSchema = z.strictObject({
2765
+ version: z.literal(2),
2766
+ host: hostNameSchema,
2767
+ projectName: z.string(),
2768
+ kind: runnerKindSchema,
2769
+ verb: z.string().min(1),
2770
+ pid: z.number().int(),
2771
+ startedAt: z.string(),
2772
+ /** Standalone hosts: the runner's outputs. */
2773
+ outputs: outputsSchema.optional(),
2774
+ /** Compounds: one entry per started member, keyed by member name. */
2775
+ members: z.record(z.string(), runRecordMemberSchema).optional(),
2776
+ /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */
2777
+ extra: z.record(z.string(), z.unknown()).optional()
2778
+ });
2779
+ //#endregion
2780
+ //#region src/run-record.ts
2781
+ const runDir = (projectDir, env = process.env) => path.join(resolvePhDir(projectDir, env), "run");
2782
+ function recordPath(projectDir, hostName, env) {
2783
+ const dir = runDir(projectDir, env);
2784
+ const file = path.resolve(dir, `${hostName}.json`);
2785
+ if (!hostNameSchema.safeParse(hostName).success || path.dirname(file) !== path.resolve(dir)) throw new Error(`"${hostName}" can't name a run record. ${HOST_NAME_MESSAGE}`);
2786
+ return file;
2787
+ }
2788
+ function readRunRecord(projectDir, hostName, env = process.env) {
2789
+ let raw;
2790
+ try {
2791
+ raw = JSON.parse(fs.readFileSync(recordPath(projectDir, hostName, env), "utf8"));
2792
+ } catch {
2793
+ return;
2794
+ }
2795
+ const parsed = runRecordSchema.safeParse(raw);
2796
+ return parsed.success ? parsed.data : void 0;
2797
+ }
2798
+ /** Every valid v2 record under `.ph/run/` (invalid and v1 files skipped). */
2799
+ function listRunRecords(projectDir, env = process.env) {
2800
+ let files;
2801
+ try {
2802
+ files = fs.readdirSync(runDir(projectDir, env));
2803
+ } catch {
2804
+ return [];
2805
+ }
2806
+ return files.filter((file) => file.endsWith(".json")).flatMap((file) => {
2807
+ const record = readRunRecord(projectDir, file.slice(0, -5), env);
2808
+ return record ? [record] : [];
2809
+ });
2810
+ }
2811
+ /** The project identity the live/foreign probe compares: package.json
2812
+ * `name`, else the folder name. */
2813
+ function readProjectName(projectDir) {
2814
+ try {
2815
+ const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8"));
2816
+ if (typeof pkg.name === "string" && pkg.name) return pkg.name;
2817
+ } catch {}
2818
+ return path.basename(path.resolve(projectDir));
2819
+ }
2820
+ function writeRunRecord(projectDir, record) {
2821
+ const target = recordPath(projectDir, record.host);
2822
+ const valid = runRecordSchema.parse(record);
2823
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2824
+ fs.writeFileSync(target, `${JSON.stringify(valid, null, 2)}\n`);
2825
+ }
2826
+ function clearRunRecord(projectDir, hostName, env = process.env) {
2827
+ try {
2828
+ fs.rmSync(recordPath(projectDir, hostName, env));
2829
+ } catch {}
2830
+ }
2831
+ function isPidAlive(pid) {
2832
+ try {
2833
+ process.kill(pid, 0);
2834
+ return true;
2835
+ } catch (error) {
2836
+ return error.code === "EPERM";
2837
+ }
2838
+ }
2839
+ /**
2840
+ * Decide whether the recorded instance is this project's live host.
2841
+ *
2842
+ * pid liveness alone proves nothing (pids are reused), and the recorded
2843
+ * projectName is what separates "my instance" from "a different project that
2844
+ * happens to hold this storage root" — the confusion the vetra lock exists to
2845
+ * prevent. A stale record (dead pid) is reported so the caller can clear it; a
2846
+ * foreign one (live pid, different project) is left alone.
2847
+ */
2848
+ function probeRun(projectDir, hostName, projectName, env = process.env) {
2849
+ const record = readRunRecord(projectDir, hostName, env);
2850
+ if (!record) return { status: "none" };
2851
+ if (!isPidAlive(record.pid)) return {
2852
+ status: "stale",
2853
+ record
2854
+ };
2855
+ if (record.projectName !== projectName) return {
2856
+ status: "foreign",
2857
+ record
2858
+ };
2859
+ return {
2860
+ status: "live",
2861
+ record
2862
+ };
2863
+ }
2864
+ //#endregion
2865
+ //#region src/child-wrapper.ts
2866
+ /** Generic compound rule: `reactor`/`config` replace, `runner` key-merges. */
2867
+ function applyChildWrapper(base, wrapper) {
2868
+ const reactor = wrapper.reactor ?? base.reactor;
2869
+ const config = wrapper.config ?? base.config;
2870
+ return {
2871
+ ...base,
2872
+ runner: {
2873
+ ...base.runner,
2874
+ ...wrapper.runner
2875
+ },
2876
+ ...config !== void 0 ? { config } : {},
2877
+ ...reactor !== void 0 ? { reactor } : {}
2878
+ };
2879
+ }
2880
+ //#endregion
2881
+ //#region src/placeholders.ts
2882
+ /**
2883
+ * `${userData}` resolution for host files (desktop shape): storage paths in a
2884
+ * host must not derive from the instance name (renames must stay safe), so
2885
+ * the host file writes `${userData}/.ph/reactor-storage` and the RUNNER
2886
+ * resolves it at start. `${userData}` is a PROJECT-SHAPED root: its `.ph`
2887
+ * subtree carries the same names the classic commands use under
2888
+ * `<project>/.ph` (see `resolvePhDir`). In the CLI it IS the project root, so
2889
+ * `ph run desktop` in a project shares the one `.ph` tree `ph vetra` uses;
2890
+ * a shell (Tauri) points it at the OS profile via PH_USER_DATA_DIR, and the
2891
+ * whole `.ph` tree — stores, identity, run records — follows.
2892
+ */
2893
+ function defaultUserDataDir(projectRoot, env = process.env) {
2894
+ return env.PH_USER_DATA_DIR ?? path.resolve(projectRoot);
2895
+ }
2896
+ /** Deep-substitute `${userData}` in every string of a JSON-shaped value.
2897
+ * Non-strings pass through; the input is never mutated. */
2898
+ function resolveUserDataPlaceholders(value, userData) {
2899
+ return substituteBuiltinEnv(value, { userData });
2900
+ }
2901
+ //#endregion
2902
+ //#region src/resolve/node.ts
2903
+ /** Load every producer host a set of refs names (each once). */
2904
+ async function loadProducers(projectRoot, refs) {
2905
+ const producers = /* @__PURE__ */ new Map();
2906
+ for (const { host: folder } of refs) {
2907
+ if (producers.has(folder)) continue;
2908
+ try {
2909
+ const loaded = await loadHost(projectRoot, folder);
2910
+ const specifier = loaded.host.runner.module;
2911
+ producers.set(folder, {
2912
+ folder,
2913
+ name: loaded.host.name,
2914
+ specifier,
2915
+ runner: await resolveRunnerModule(projectRoot, specifier)
2916
+ });
2917
+ } catch (error) {
2918
+ producers.set(folder, { error: `names host "${folder}", which cannot be loaded: ${error instanceof Error ? error.message : String(error)}` });
2919
+ }
2920
+ }
2921
+ return producers;
2922
+ }
2923
+ /** The outputs schema of a runner module, or why it has none. */
2924
+ function runnerOutputsSchema(runner, specifier, label) {
2925
+ const schema = runner.outputsSchema;
2926
+ if (schema === void 0 || schema === null) return { error: `${label} runs "${specifier}", which exports no outputsSchema, so it produces no outputs a token can read.` };
2927
+ return {
2928
+ schema,
2929
+ label: `"${specifier}" (${label})`
2930
+ };
2931
+ }
2932
+ /** Declared-validation lookup for a standalone host's producers. */
2933
+ function producerOutputsSchemas(producers) {
2934
+ return (ref) => {
2935
+ const info = producers.get(ref.host);
2936
+ if (!info) return { error: `names host "${ref.host}", which was not loaded.` };
2937
+ if ("error" in info) return { error: info.error };
2938
+ return runnerOutputsSchema(info.runner, info.specifier, `host "${ref.host}"`);
2939
+ };
2940
+ }
2941
+ /** Further `.ph` roots whose live run records a standalone `$output` reads
2942
+ * (`path.delimiter`-separated): a launcher that gives each child its own
2943
+ * PH_USER_DATA_DIR names its siblings' here. Locks never read them. */
2944
+ const OUTPUT_DATA_DIRS_ENV = "PH_OUTPUT_DATA_DIRS";
2945
+ /** The other roots, each once, never the process's own. */
2946
+ function siblingEnvs(projectRoot, env) {
2947
+ const own = path.resolve(defaultUserDataDir(projectRoot, env));
2948
+ return [...new Set((env["PH_OUTPUT_DATA_DIRS"] ?? "").split(path.delimiter).filter((dir) => dir !== "").map((dir) => path.resolve(dir)))].filter((dir) => dir !== own).map((dir) => ({ PH_USER_DATA_DIR: dir }));
2949
+ }
2950
+ /**
2951
+ * Standalone `$output` source: the producer's live v2 run record. Its own
2952
+ * standalone record under the process's `.ph` root first (keyed by the
2953
+ * producer's `name`); else exactly one of: a standalone record under a
2954
+ * PH_OUTPUT_DATA_DIRS root, or a member running that host in a live compound
2955
+ * of this project under any root. A missing, stale, foreign or output-less
2956
+ * record means "not running", and the lookup fails naming the producer and
2957
+ * how to start it (no fallback to the producer's declared config, no
2958
+ * waiting).
2959
+ */
2960
+ function runRecordOutputSource(projectRoot, options) {
2961
+ const { consumer, producers, projectName } = options;
2962
+ const env = options.env ?? process.env;
2963
+ const siblings = siblingEnvs(projectRoot, env);
2964
+ return { lookup(ref) {
2965
+ const notRunning = `${consumer} needs outputs from host "${ref.host}", which is not running. Start it first: ph run ${ref.host} (or run a compound that includes it).`;
2966
+ const info = producers.get(ref.host);
2967
+ const schema = info && !("error" in info) ? info.runner.outputsSchema : void 0;
2968
+ const withSchema = schema !== void 0 && schema !== null ? { schema } : {};
2969
+ const standalone = [];
2970
+ if (ref.member === void 0 && info && !("error" in info)) {
2971
+ const probe = probeRun(projectRoot, info.name, projectName, env);
2972
+ if (probe.status === "live" && probe.record.outputs) return {
2973
+ status: "available",
2974
+ outputs: probe.record.outputs,
2975
+ ...withSchema
2976
+ };
2977
+ for (const sibling of siblings) {
2978
+ const other = probeRun(projectRoot, info.name, projectName, sibling);
2979
+ if (other.status === "live" && other.record.outputs) standalone.push({
2980
+ label: `"${info.name}" (pid ${other.record.pid})`,
2981
+ outputs: other.record.outputs
2982
+ });
2983
+ }
2984
+ }
2985
+ const members = [env, ...siblings].flatMap((root) => listRunRecords(projectRoot, root)).filter((record) => record.members !== void 0 && record.projectName === projectName && isPidAlive(record.pid)).flatMap((record) => Object.entries(record.members ?? {}).filter(([key, member]) => member.host === ref.host && (ref.member === void 0 || key === ref.member)).map(([key, member]) => ({
2986
+ label: `member "${key}" of "${record.host}"`,
2987
+ outputs: member.outputs
2988
+ })));
2989
+ const found = [...standalone, ...members];
2990
+ if (found.length === 1) return {
2991
+ status: "available",
2992
+ outputs: found[0].outputs,
2993
+ ...withSchema
2994
+ };
2995
+ if (found.length > 1) return {
2996
+ status: "unavailable",
2997
+ message: `${consumer} needs outputs from host "${ref.host}", which runs as ${found.map((m) => m.label).join(" and ")}; stop all but one, or run ${ref.host} on its own.`
2998
+ };
2999
+ return {
3000
+ status: "unavailable",
3001
+ message: notRunning
3002
+ };
3003
+ } };
3004
+ }
3005
+ /** The resolving process's `$env` inputs: its environment plus the
3006
+ * always-resolvable built-ins (`userData` honours PH_USER_DATA_DIR). */
3007
+ function processResolveEnv(projectRoot, env = process.env) {
3008
+ return {
3009
+ env,
3010
+ builtins: {
3011
+ userData: defaultUserDataDir(projectRoot, env),
3012
+ projectRoot: path.resolve(projectRoot)
3013
+ }
3014
+ };
3015
+ }
3016
+ //#endregion
3017
+ //#region src/resolve/sources.ts
3018
+ /**
3019
+ * The compound output source: a member's `$output` tokens read the live
3020
+ * `RunnerHandle.outputs` of the members started before it. `schemas` (member
3021
+ * key → its runner's `outputsSchema`) lets an absent optional output field
3022
+ * omit the consuming property. Pure (the run-record source for standalone
3023
+ * hosts is node: ./node.ts).
3024
+ */
3025
+ function compoundOutputSource(members, started, compound, schemas) {
3026
+ return { lookup(ref) {
3027
+ const target = memberForRef(ref, members);
3028
+ if ("error" in target) return {
3029
+ status: "unavailable",
3030
+ message: `compound "${compound}": a token ${target.error}`
3031
+ };
3032
+ if (!started.has(target.key)) return {
3033
+ status: "unavailable",
3034
+ message: `compound "${compound}": member "${target.key}" (host "${ref.host}") has not started yet; a producer must start before its consumers.`
3035
+ };
3036
+ const schema = schemas?.get(target.key);
3037
+ return {
3038
+ status: "available",
3039
+ outputs: started.get(target.key),
3040
+ ...schema !== void 0 ? { schema } : {}
3041
+ };
3042
+ } };
3043
+ }
3044
+ //#endregion
3045
+ //#region src/runner-handle.ts
3046
+ /** The data half of a handle, validated by the compound. `ready`/`shutdown`
3047
+ * are functions and promises, so they are checked as TS fields, not here. */
3048
+ const runnerHandleSchema = z.looseObject({ outputs: z.record(z.string(), z.unknown()).optional() });
3049
+ function isRecord(value) {
3050
+ return typeof value === "object" && value !== null;
3051
+ }
3052
+ function isPromiseLike(value) {
3053
+ return isRecord(value) && typeof value.then === "function";
3054
+ }
3055
+ function isCallable(value) {
3056
+ return typeof value === "function";
3057
+ }
3058
+ /** Normalize what a verb returned. `undefined` (a self-sustaining bridge)
3059
+ * is an empty handle; anything else must match runnerHandleSchema. */
3060
+ function toStartedHandle(value, where) {
3061
+ if (value === void 0 || value === null) return { outputs: {} };
3062
+ const parsed = runnerHandleSchema.safeParse(value);
3063
+ if (!parsed.success) throw new Error(`${where} returned an invalid runner handle:\n${z.prettifyError(parsed.error)}`);
3064
+ const live = isRecord(value) ? value : {};
3065
+ const shutdown = live.shutdown;
3066
+ return {
3067
+ ...parsed.data,
3068
+ outputs: parsed.data.outputs ?? {},
3069
+ ...isPromiseLike(live.ready) ? { ready: live.ready } : {},
3070
+ ...isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {}
3071
+ };
3072
+ }
3073
+ //#endregion
3074
+ //#region src/compound.ts
3075
+ async function memberDraft(projectRoot, member) {
3076
+ return applyChildWrapper((await loadHost(projectRoot, member.host)).host, member);
3077
+ }
3078
+ /** Whether a member receives the compound's `cspRegistrySync` wiring (as
3079
+ * `runner.cspRegistrySync`): its runner declares that option (any specifier
3080
+ * that reaches the Connect runner), or it names the Connect runner. A
3081
+ * member's role is its runner, not its folder. */
3082
+ function takesCspRegistrySync(m) {
3083
+ return m.specifier === "@powerhousedao/ph-cli/runners/connect" || declaresKey(m.runner.hostSchema, ["runner"], "cspRegistrySync");
3084
+ }
3085
+ /**
3086
+ * Windows has no SIGTERM, so a supervisor asks a stack to stop through its
3087
+ * stdin: a line, or the pipe closing, which also covers the supervisor dying.
3088
+ * Only when it asks to: a stack started from a script may have no stdin.
3089
+ */
3090
+ function stopStreamOf(env, stdin) {
3091
+ return env["PH_STOP_ON_STDIN"] === "1" ? stdin() : void 0;
3092
+ }
3093
+ function whenStreamStops(stream, stop) {
3094
+ let stopped = false;
3095
+ const once = () => {
3096
+ if (stopped) return;
3097
+ stopped = true;
3098
+ stop();
3099
+ };
3100
+ for (const event of [
3101
+ "data",
3102
+ "end",
3103
+ "close",
3104
+ "error"
3105
+ ]) stream.once(event, once);
3106
+ stream.resume();
3107
+ }
3108
+ /** The verb the generic compound starts its members at for its own `verb`:
3109
+ * `run` follows the compound's defaultVerb. */
3110
+ function compoundStartVerb(verb, runner) {
3111
+ return verb === "run" ? runner.defaultVerb ?? "run" : verb;
3112
+ }
3113
+ /** At compound verb "run" each member runs its own (merged) defaultVerb —
3114
+ * what lets a desktop compound pair a switchboard at `run` with a connect at
3115
+ * `serve`. An explicit forwarded verb stays uniform across members. */
3116
+ function memberVerbOf(compoundVerb, runner) {
3117
+ return compoundVerb === "run" ? runner.defaultVerb ?? "run" : compoundVerb;
3118
+ }
3119
+ async function runCompound(hostInput, ctx, options) {
3120
+ const compoundFile = `hosts/${hostInput.name}`;
3121
+ const removed = findRemovedForms(hostInput);
3122
+ if (removed.length > 0) throw new RunnerError(`${compoundFile}: removed form:\n${removed.map((r) => ` - ${r.path}: ${r.message}`).join("\n")}`);
3123
+ const parsed = declaredGenericCompoundHostSchema.safeParse(hostInput);
3124
+ if (!parsed.success) throw new Error(`${compoundFile}: invalid compound host:\n${z.prettifyError(parsed.error)}`);
3125
+ const host = parsed.data;
3126
+ const projectRoot = ctx.projectRoot;
3127
+ const wiring = host.config ?? {};
3128
+ const verb = ctx.verb;
3129
+ const oneShotCompound = ONE_SHOT_VERBS.has(verb);
3130
+ const keepsRecord = wiring.runtimeRecord !== false && !oneShotCompound;
3131
+ let stopRequested = false;
3132
+ let stopFromStream = () => {
3133
+ stopRequested = true;
3134
+ };
3135
+ if (options.stopStream && !oneShotCompound) {
3136
+ whenStreamStops(options.stopStream, () => stopFromStream());
3137
+ const outputs = options.supervisedOutputs ?? [process.stdout, process.stderr];
3138
+ for (const output of outputs) output.on("error", () => void 0);
3139
+ }
3140
+ const probe = oneShotCompound ? void 0 : probeRun(projectRoot, host.name, options.projectName);
3141
+ if (probe?.status === "live") throw new Error(`${host.name} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`);
3142
+ if (probe?.status === "foreign") throw new Error(`.ph/run/${host.name}.json describes a live "${probe.record.projectName}", but this project is "${options.projectName}". Refusing to start a second instance.`);
3143
+ const prepared = await prepareMembers(projectRoot, host.children);
3144
+ const plan = planCompound(prepared.map((m) => ({
3145
+ key: m.key,
3146
+ host: m.member.host,
3147
+ refs: outputSitesOf(m.draft).map(({ ref, path }) => ({
3148
+ ref,
3149
+ path
3150
+ }))
3151
+ })), wiring.startOrder);
3152
+ const byKey = new Map(prepared.map((m) => [m.key, m]));
3153
+ const members = prepared.map((m) => ({
3154
+ key: m.key,
3155
+ host: m.member.host
3156
+ }));
3157
+ for (const m of prepared) validateDeclaredHost(m.runner, m.specifier, m.draft, m.file, { outputsSchemaOf: (ref) => {
3158
+ const target = memberForRef(ref, members);
3159
+ if ("error" in target) return { error: target.error };
3160
+ const producer = byKey.get(target.key);
3161
+ return producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member "${target.key}"`) : { error: `names member "${target.key}", which was not prepared.` };
3162
+ } });
3163
+ if (wiring.cspRegistrySync && !prepared.some(takesCspRegistrySync)) console.warn(`${compoundFile}: config.cspRegistrySync is set, but no member's runner declares runner.cspRegistrySync (members run: ${prepared.map((m) => m.specifier).join(", ")}); the baked Connect CSP is not patched for the runtime registry.`);
3164
+ const started = [];
3165
+ const liveOutputs = /* @__PURE__ */ new Map();
3166
+ const outputs = compoundOutputSource(members, liveOutputs, host.name, new Map(prepared.map((m) => [m.key, m.runner.outputsSchema])));
3167
+ const resolveEnv = processResolveEnv(projectRoot, ctx.env);
3168
+ let stopping;
3169
+ const shutdown = () => stopping ??= (async () => {
3170
+ for (const m of [...started].reverse()) try {
3171
+ await m.handle.shutdown?.();
3172
+ } catch {}
3173
+ if (keepsRecord) clearRunRecord(projectRoot, host.name);
3174
+ })();
3175
+ try {
3176
+ for (const name of plan.order) {
3177
+ const m = byKey.get(name);
3178
+ if (!m) continue;
3179
+ const memberVerb = memberVerbOf(verb, m.draft.runner);
3180
+ const oneShot = ONE_SHOT_VERBS.has(memberVerb);
3181
+ const resolved = oneShot ? substituteBuiltinEnv(m.draft, resolveEnv.builtins ?? {}) : resolveHostOutputs(m.draft, {
3182
+ outputs,
3183
+ ...resolveEnv,
3184
+ where: m.file
3185
+ });
3186
+ if (wiring.cspRegistrySync && takesCspRegistrySync(m)) resolved.runner = {
3187
+ ...resolved.runner,
3188
+ cspRegistrySync: true
3189
+ };
3190
+ const validated = validateHost(m.runner, m.specifier, resolved, m.file, oneShot ? { tokens: "allow" } : {});
3191
+ const fn = getVerb(m.runner, m.specifier, memberVerb);
3192
+ const where = `${name} (${m.specifier} ${memberVerb})`;
3193
+ const handle = toStartedHandle(await fn(validated, {
3194
+ projectRoot,
3195
+ env: ctx.env,
3196
+ verb: memberVerb,
3197
+ parent: {
3198
+ host: host.name,
3199
+ verb
3200
+ }
3201
+ }), where);
3202
+ started.push({
3203
+ name,
3204
+ member: m.member,
3205
+ specifier: m.specifier,
3206
+ kind: m.runner.kind,
3207
+ verb: memberVerb,
3208
+ handle,
3209
+ outputs: handle.outputs
3210
+ });
3211
+ if (handle.ready) await handle.ready;
3212
+ let memberOutputs = handle.outputs;
3213
+ if (!oneShot && isSchemaLike(m.runner.outputsSchema)) {
3214
+ const checked = m.runner.outputsSchema.safeParse(handle.outputs);
3215
+ if (!checked.success) throw new Error(`${where} reported outputs that fail its outputsSchema:\n${checked.error.issues.map((i) => ` - ${i.path.map(String).join(".") || "<root>"}: ${i.message}`).join("\n")}`);
3216
+ if (!isPlainObject(checked.data)) throw new Error(`${where}: its outputsSchema parsed the outputs to ${JSON.stringify(checked.data)}, not an object.`);
3217
+ memberOutputs = checked.data;
3218
+ }
3219
+ started[started.length - 1].outputs = memberOutputs;
3220
+ liveOutputs.set(name, memberOutputs);
3221
+ }
3222
+ } catch (error) {
3223
+ await shutdown();
3224
+ throw error;
3225
+ }
3226
+ if (keepsRecord) {
3227
+ const recordMembers = {};
3228
+ for (const m of started) recordMembers[m.name] = {
3229
+ host: m.member.host,
3230
+ runnerModule: m.specifier,
3231
+ kind: m.kind,
3232
+ verb: m.verb,
3233
+ outputs: m.outputs
3234
+ };
3235
+ writeRunRecord(projectRoot, {
3236
+ version: 2,
3237
+ host: host.name,
3238
+ projectName: options.projectName,
3239
+ kind: "compound",
3240
+ verb,
3241
+ pid: process.pid,
3242
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
3243
+ members: recordMembers,
3244
+ ...options.recordExtra ? { extra: options.recordExtra } : {}
3245
+ });
3246
+ }
3247
+ const exit = options.exit ?? ((code) => process.exit(code));
3248
+ let signalled;
3249
+ const handleSignal = (signal) => {
3250
+ if (signalled) return signalled;
3251
+ const code = signal === "SIGINT" ? 130 : 143;
3252
+ signalled = shutdown().finally(() => exit(code));
3253
+ return signalled;
3254
+ };
3255
+ if (options.installSignalHandlers !== false) {
3256
+ process.on("exit", () => {
3257
+ if (keepsRecord) clearRunRecord(projectRoot, host.name);
3258
+ });
3259
+ process.on("SIGINT", () => void handleSignal("SIGINT"));
3260
+ process.on("SIGTERM", () => void handleSignal("SIGTERM"));
3261
+ }
3262
+ stopFromStream = () => {
3263
+ const limit = options.stopStreamLimitMs ?? 15e3;
3264
+ setTimeout(() => exit(143), limit).unref();
3265
+ handleSignal("SIGTERM");
3266
+ };
3267
+ if (stopRequested) stopFromStream();
3268
+ return {
3269
+ started,
3270
+ shutdown,
3271
+ handleSignal
3272
+ };
3273
+ }
3274
+ /** Load every member's draft and runner, in declaration order. */
3275
+ async function prepareMembers(projectRoot, children) {
3276
+ const out = [];
3277
+ for (const [key, member] of Object.entries(children)) out.push(await prepareMember(projectRoot, key, member));
3278
+ return out;
3279
+ }
3280
+ /** One member's draft and runner. */
3281
+ async function prepareMember(projectRoot, key, member) {
3282
+ const draft = await memberDraft(projectRoot, member);
3283
+ const specifier = draft.runner.module;
3284
+ return {
3285
+ key,
3286
+ member,
3287
+ draft,
3288
+ specifier,
3289
+ runner: await resolveRunnerModule(projectRoot, specifier),
3290
+ file: `hosts/${member.host}/host.js`
3291
+ };
3292
+ }
3293
+ //#endregion
3294
+ export { TokenResolutionError as $, driveDeclarationSchema as $t, computeOutputsHash as A, registerHostType as An, compoundWiringSchema as At, stripComments as B, originOrUrlSchema as Bt, readProjectName as C, entryActiveForVerb as Cn, CONNECT_PRIMARY_MESSAGE as Ct, runRecordSchema as D, normalizePluginEntry as Dn, childWrapperSchema as Dt, runRecordMemberSchema as E, normalizePluginEntries as En, HOST_NAME_PATTERN as Et, lintOutputsFile as F, runTransformHook as Fn, emitHostJsonSchema as Ft, hostSchemaIssues as G, reactorHostSchema as Gt, ONE_SHOT_VERBS as H, profileSchema as Ht, loadHost as I, emittedHostSchemas as It, knownVerbIssues as J, refineConnectReactor as Jt, isSchemaLike as K, reactorProtocolSchema as Kt, probeHostsFolder as L, genericCompoundHostSchema as Lt, findNonStaticValue as M, runObserveHook as Mn, declaredGenericCompoundHostSchema as Mt, lintHostImportGraph as N, runObserveHookSequential as Nn, declaredHostSchemas as Nt, HostLoadError as O, pluginEntryObjectSchema as On, childrenSchema as Ot, lintHostImports as P, runProvideHook as Pn, defineHostSchemas as Pt, validateHost as Q, buildDriveDeclarationSchema as Qt, readOutputsFileHash as R, hostNameSchema as Rt, probeRun as S, PluginError as Sn, unwrapEscapes as St, writeRunRecord as T, mergeContributions as Tn, HOST_NAME_MESSAGE as Tt, RunnerError as U, reactorBackendKindSchema as Ut, CONNECT_RUNNER as V, placementKeyIssues as Vt, getVerb as W, reactorBackendSchema as Wt, resolveRunnerModule as X, runnerBaseSchema as Xt, listVerbs as Y, refineStartOrder as Yt, validateDeclaredHost as Z, runnerKindSchema as Zt, resolveUserDataPlaceholders as _, tokenable as _n, collectTokenSites as _t, stopStreamOf as a, envTokenSchema as an, planCompound as at, isPidAlive as b, resolveHostPlugins as bn, isPlainObject as bt, toStartedHandle as c, forbidRef as cn, substituteBuiltinEnv as ct, loadProducers as d, keyTokenSchema as dn, checkTokenSites as dt, drivesSchema as en, describeMapElements as et, processResolveEnv as f, mapTokenSchema as fn, envSitesOf as ft, defaultUserDataDir as g, tokenSchema as gn, schemaAtPath as gt, runnerOutputsSchema as h, tokenKeyOf as hn, refKey as ht, runCompound as i, concatTokenSchema as in, memberForRef as it, describeHostOutputs as j, resolveOrder as jn, connectReactorIssues as jt, OUTPUTS_FILE as k, pluginEntrySchema as kn, compoundHostSchema as kt, compoundOutputSource as l, isToken as ln, findRemovedForms as lt, runRecordOutputSource as m, ref as mn, outputSitesOf as mt, memberVerbOf as n, TOKEN_ESCAPE_KEY as nn, unsetEnvMessage as nt, takesCspRegistrySync as o, envTokenable as on, BUILTIN_ENV_NAMES as ot, producerOutputsSchemas as p, outputTokenSchema as pn, outputRefsOf as pt, kindShapeIssues as q, reactorSchema as qt, prepareMember as r, TOKEN_KEYS as rn, PlanError as rt, runnerHandleSchema as s, findToken as sn, isBuiltinEnvName as st, compoundStartVerb as t, projectDriveIdWith as tn, resolveHostOutputs as tt, OUTPUT_DATA_DIRS_ENV as u, itemTokenSchema as un, checkOutputPaths as ut, applyChildWrapper as v, CONNECT_PLUGIN_OWNED_SLICES as vn, describeToken as vt, readRunRecord as w, hostTypeSatisfies as wn, HOST_NAME_MAX_LENGTH as wt, listRunRecords as x, resolvePluginContributions as xn, renderTokens as xt, clearRunRecord as y, findDeadConnectConfig as yn, formatPath as yt, scanHostImports as z, makeHostSchemas as zt };
3295
+
3296
+ //# sourceMappingURL=compound-DO_mvh0O.mjs.map