@powerhousedao/host-core 6.2.3-dev.85 → 6.2.3-dev.87

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["isRecord","childFolders","switchboardOfDrive"],"sources":["../src/spawn-host.ts","../src/check-host.ts","../src/host-export-schema.ts","../src/host-export.ts","../src/drives.ts","../src/backend-projection.ts","../src/reactor-config.ts","../src/connect-projection.ts","../src/expect-host.ts"],"sourcesContent":["import { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadHost } from \"./host-loader.js\";\nimport { clearRunRecord, listRunRecords } from \"./run-record.js\";\nimport type { RunRecord } from \"./run-record-schema.js\";\nimport {\n isSchemaLike,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n} from \"./runner-resolver.js\";\n\nexport interface SpawnHostOptions {\n projectRoot: string;\n /** Folder name under hosts/. */\n host: string;\n /** The child's PH_USER_DATA_DIR (created if missing). */\n dataDir: string;\n verb?: string;\n /** Merged over the clean base env; may not set PH_USER_DATA_DIR. */\n env?: Record<string, string>;\n /** ph-cli entry; default: the project's `@powerhousedao/ph-cli/dist/cli.mjs`. */\n cli?: string;\n readyTimeoutMs?: number;\n stopTimeoutMs?: number;\n /** Before ready: stop and reject. After: stop. */\n signal?: AbortSignal;\n onOutput?: (stream: \"stdout\" | \"stderr\", chunk: string) => void;\n /** Appends both streams. */\n logFile?: string;\n}\n\nexport interface HostExit {\n code: number | null;\n signal: NodeJS.Signals | null;\n /** SIGKILL after stopTimeoutMs. */\n forced: boolean;\n}\n\nexport interface SpawnedHost {\n pid: number;\n dataDir: string;\n record: RunRecord;\n outputs: Record<string, unknown> | undefined;\n members: RunRecord[\"members\"];\n /** Resolves (never rejects) when the child exits. */\n exited: Promise<HostExit>;\n /** SIGTERM, SIGKILL after stopTimeoutMs, clear a leftover record. */\n stop(): Promise<HostExit>;\n}\n\nexport type SpawnHostPhase = \"exited\" | \"timeout\" | \"aborted\";\n\nexport class SpawnHostError extends Error {\n constructor(\n message: string,\n readonly phase: SpawnHostPhase,\n readonly outputTail: string,\n readonly exit?: HostExit,\n ) {\n super(\n outputTail ? `${message}\\n--- output tail ---\\n${outputTail}` : message,\n );\n this.name = \"SpawnHostError\";\n }\n}\n\nconst READY_TIMEOUT_MS = 120_000;\nconst STOP_TIMEOUT_MS = 30_000;\nconst POLL_MS = 100;\nconst TAIL_BYTES = 8 * 1024;\n// A grandchild may hold the pipes open past the child's exit.\nconst CLOSE_WAIT_MS = 1_000;\n\nconst BASE_ENV_KEYS = [\"PATH\", \"HOME\", \"TMPDIR\"];\nconst WIN32_ENV_KEYS = [\n \"SystemRoot\",\n \"USERPROFILE\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"TEMP\",\n \"TMP\",\n \"ComSpec\",\n \"PATHEXT\",\n];\n\n/** The child's whole env: no other `process.env` key reaches it. */\nfunction childEnv(\n dataDir: string,\n env: Record<string, string> = {},\n): Record<string, string> {\n if (\"PH_USER_DATA_DIR\" in env) {\n throw new Error(\n \"spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.\",\n );\n }\n const keys =\n process.platform === \"win32\"\n ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS]\n : BASE_ENV_KEYS;\n const base: Record<string, string> = {};\n for (const key of keys) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n return {\n ...base,\n FEATURE_UNIFORM_RUNNERS_ENABLED: \"1\",\n PH_USER_DATA_DIR: dataDir,\n PH_NO_TELEMETRY: \"1\",\n PH_NO_DOTENV: \"1\",\n ...env,\n };\n}\n\nfunction resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\n/** Readiness waits for a record; refuse a host/verb that writes none. */\nasync function assertWritesRecord(\n projectRoot: string,\n host: string,\n verb: string | undefined,\n): Promise<void> {\n if (verb !== undefined && ONE_SHOT_VERBS.has(verb)) {\n throw new Error(\n `spawnHost: \"${verb}\" is a one-shot verb; it writes no run record to wait for.`,\n );\n }\n const loaded = await loadHost(projectRoot, host);\n const specifier = loaded.host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, specifier);\n if (runner.kind === \"compound\") {\n const config = (loaded.host as { config?: { runtimeRecord?: unknown } })\n .config;\n if (config?.runtimeRecord === false) {\n throw new Error(\n `spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`,\n );\n }\n return;\n }\n if (!isSchemaLike(runner.outputsSchema)) {\n throw new Error(\n `spawnHost: hosts/${host} runs \"${specifier}\", which exports no outputsSchema, so it writes no run record to wait for.`,\n );\n }\n}\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms).unref();\n });\n\n// Children still running when this process exits get SIGTERM, so a launcher\n// that exits without stop() leaves no host behind.\nconst live = new Set<ChildProcess>();\nlet exitHookInstalled = false;\nfunction track(child: ChildProcess): void {\n live.add(child);\n child.once(\"exit\", () => live.delete(child));\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n process.once(\"exit\", () => {\n for (const running of live) running.kill(\"SIGTERM\");\n });\n}\n\n/**\n * `ph run <host> [verb]` as a child; ready when its run record appears.\n *\n * The child shares this process's group, so a terminal Ctrl-C reaches both.\n * It runs the project's own ph-cli: one older than PH_NO_DOTENV reads the\n * project's `.env` anyway.\n */\nexport async function spawnHost(\n options: SpawnHostOptions,\n): Promise<SpawnedHost> {\n const projectRoot = path.resolve(options.projectRoot);\n const dataDir = path.resolve(options.dataDir);\n const env = childEnv(dataDir, options.env);\n const readerEnv = { PH_USER_DATA_DIR: dataDir };\n const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;\n const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;\n const { signal } = options;\n\n if (signal?.aborted) {\n throw new SpawnHostError(\"spawnHost: aborted before start.\", \"aborted\", \"\");\n }\n await assertWritesRecord(projectRoot, options.host, options.verb);\n const cli = options.cli ?? resolvePhCliEntry(projectRoot);\n fs.mkdirSync(dataDir, { recursive: true });\n\n const log = options.logFile\n ? fs.createWriteStream(options.logFile, { flags: \"a\" })\n : undefined;\n let tail = \"\";\n log?.on(\"error\", (error) => {\n tail = (tail + `logFile: ${error.message}\\n`).slice(-TAIL_BYTES);\n });\n const args = [cli, \"run\", options.host];\n if (options.verb !== undefined) args.push(options.verb);\n const child = spawn(process.execPath, args, {\n cwd: projectRoot,\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n track(child);\n\n const onChunk = (stream: \"stdout\" | \"stderr\") => (chunk: string) => {\n tail = (tail + chunk).slice(-TAIL_BYTES);\n log?.write(chunk);\n try {\n options.onOutput?.(stream, chunk);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n tail = (tail + `onOutput: ${message}\\n`).slice(-TAIL_BYTES);\n }\n };\n child.stdout.setEncoding(\"utf8\").on(\"data\", onChunk(\"stdout\"));\n child.stderr.setEncoding(\"utf8\").on(\"data\", onChunk(\"stderr\"));\n\n let forced = false;\n let exit: HostExit | undefined;\n const exited = new Promise<HostExit>((resolve) => {\n const done = (code: number | null, sig: NodeJS.Signals | null) => {\n if (exit) return;\n exit = { code, signal: sig, forced };\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(exit);\n };\n child.once(\"exit\", done);\n child.once(\"error\", (error) => {\n tail = (tail + `${error.message}\\n`).slice(-TAIL_BYTES);\n if (child.pid === undefined) done(null, null);\n });\n });\n\n // After the last chunk: stdio may still flush past \"exit\".\n const closed = new Promise<void>((resolve) => {\n child.once(\"close\", () => {\n log?.end();\n resolve();\n });\n });\n\n const pid = child.pid;\n const ownRecords = () =>\n pid === undefined\n ? []\n : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);\n\n const kill = (sig: NodeJS.Signals) => {\n if (pid === undefined) return;\n try {\n process.kill(pid, sig);\n } catch {\n // already gone\n }\n };\n const clearOwnRecords = () => {\n for (const record of ownRecords()) {\n clearRunRecord(projectRoot, record.host, readerEnv);\n }\n };\n\n let stopping: Promise<HostExit> | undefined;\n const stop = (): Promise<HostExit> => {\n stopping ??= (async () => {\n if (!exit) {\n kill(\"SIGTERM\");\n let timer: NodeJS.Timeout | undefined;\n const timedOut = await Promise.race([\n exited.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), stopTimeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (timedOut) {\n forced = true;\n kill(\"SIGKILL\");\n }\n }\n const result = await exited;\n // A killed child skips its exit handler's record clear.\n clearOwnRecords();\n return result;\n })();\n return stopping;\n };\n\n function onAbort() {\n void stop();\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const deadline = Date.now() + readyTimeoutMs;\n for (;;) {\n const aborted = signal?.aborted ?? false;\n // Before the record: a child killed after writing it leaves it behind.\n if (exit && !aborted) {\n clearOwnRecords();\n let timer: NodeJS.Timeout | undefined;\n await Promise.race([\n closed,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CLOSE_WAIT_MS);\n }),\n ]);\n clearTimeout(timer);\n const how =\n exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;\n throw new SpawnHostError(\n `spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`,\n \"exited\",\n tail,\n exit,\n );\n }\n const record = aborted ? undefined : ownRecords().at(0);\n if (record) {\n return {\n pid: record.pid,\n dataDir,\n record,\n outputs: record.outputs,\n members: record.members,\n exited,\n stop,\n };\n }\n if (aborted || Date.now() >= deadline) {\n const phase: SpawnHostPhase = aborted ? \"aborted\" : \"timeout\";\n const stopped = await stop();\n throw new SpawnHostError(\n phase === \"aborted\"\n ? `spawnHost: aborted before ph run ${options.host} was ready.`\n : `spawnHost: ph run ${options.host} wrote no run record within ${readyTimeoutMs} ms.`,\n phase,\n tail,\n stopped,\n );\n }\n await Promise.race([sleep(POLL_MS), exited]);\n }\n}\n","import {\n compoundStartVerb,\n memberVerbOf,\n prepareMember,\n takesCspRegistrySync,\n type PreparedMember,\n} from \"./compound.js\";\nimport { isBuiltinEnvName, substituteBuiltinEnv } from \"./env-substitution.js\";\nimport { loadHost } from \"./host-loader.js\";\nimport type { CheckStage, HostIssue } from \"./host-issues.js\";\nimport type { ChildWrapper, CompoundWiring } from \"./host-schemas.js\";\nimport {\n checkOutputPaths,\n checkTokenSites,\n envSitesOf,\n outputRefsOf,\n outputSitesOf,\n type OutputRef,\n type OutputsSchemaLookup,\n} from \"./resolve/declared.js\";\nimport {\n loadProducers,\n processResolveEnv,\n producerOutputsSchemas,\n runnerOutputsSchema,\n} from \"./resolve/node.js\";\nimport { memberForRef, planCompound } from \"./resolve/plan.js\";\nimport { findRemovedForms } from \"./resolve/removed-forms.js\";\nimport {\n resolveHostOutputs,\n TokenResolutionError,\n unsetEnvMessage,\n type DeferredToken,\n type OutputSource,\n type SelfMembers,\n} from \"./resolve/resolve.js\";\nimport { isPlainObject } from \"./resolve/walk.js\";\nimport {\n getVerb,\n hostSchemaIssues,\n kindShapeIssues,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n type HostSchemaLike,\n type RunnerIssue,\n type RunnerModule,\n} from \"./runner-resolver.js\";\n\nexport interface CheckHostOptions {\n projectRoot: string;\n /** The environment `ph run` would resolve against; `process.env` is never read. */\n env: Readonly<Record<string, string | undefined>>;\n /** Default `run`, as `ph run <name>`. */\n verb?: string;\n /** Producers' outputs. Absent: `$output` tokens are checked declared-only. */\n outputs?: OutputSource;\n}\n\nexport interface CheckDeferred extends DeferredToken {\n file: string;\n}\n\nexport interface CheckHostResult {\n issues: HostIssue[];\n /** `$output` tokens left unresolved because no `outputs` were given. */\n deferred: CheckDeferred[];\n}\n\n/** The `ph run` pipeline up to the verb, collecting every issue; starts nothing. */\nexport async function checkHost(\n name: string,\n options: CheckHostOptions,\n): Promise<CheckHostResult> {\n const result: CheckHostResult = { issues: [], deferred: [] };\n const file = `hosts/${name}/host.js`;\n const issue = issuer(result, file);\n const verb = options.verb ?? \"run\";\n let host: Record<string, unknown> & { runner: { module: string } };\n let runner: RunnerModule;\n try {\n host = (await loadHost(options.projectRoot, name)).host;\n runner = await resolveRunnerModule(options.projectRoot, host.runner.module);\n } catch (error) {\n issue(\"load\", \"\", error);\n return result;\n }\n const specifier = host.runner.module;\n\n if (runner.kind === \"compound\") {\n await checkCompound(result, options, {\n file,\n host,\n runner,\n specifier,\n verb,\n });\n return result;\n }\n\n const refs = outputRefsOf(host);\n const producers = await loadProducers(options.projectRoot, refs);\n await checkSubject(result, options, {\n file,\n host,\n runner,\n specifier,\n verb,\n outputsSchemaOf: producerOutputsSchemas(producers),\n self: \"outputs\",\n });\n return result;\n}\n\ninterface Subject {\n file: string;\n host: Record<string, unknown>;\n runner: RunnerModule;\n specifier: string;\n verb: string;\n}\n\ninterface ReactorSubject extends Subject {\n outputsSchemaOf: (ref: OutputRef) => OutputsSchemaLookup;\n /** Whose `$output` tokens stay in place when no outputs are given. */\n self: SelfMembers | \"outputs\";\n /** A compound member's wiring, applied before resolved validation. */\n patch?: (host: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Declared validation; returns whether its tokens and its shape passed. */\nfunction checkDeclared(\n result: CheckHostResult,\n subject: Subject,\n outputsSchemaOf?: (ref: OutputRef) => OutputsSchemaLookup,\n): { tokens: boolean; shape: boolean } {\n const issue = issuer(result, subject.file);\n const { host, runner, specifier } = subject;\n try {\n getVerb(runner, specifier, subject.verb);\n } catch (error) {\n issue(\"declared\", \"\", error);\n }\n const tokenIssues = [\n ...findRemovedForms(host),\n ...checkTokenSites(host),\n ...(outputsSchemaOf ? checkOutputPaths(host, outputsSchemaOf) : []),\n ];\n for (const i of tokenIssues) issue(\"declared\", i);\n const shapeIssues = runner.declaredHostSchema\n ? schemaIssuesOf(runner, runner.declaredHostSchema, specifier, host, true)\n : kindShapeIssues(runner.kind, specifier, host);\n for (const i of shapeIssues) issue(\"declared\", i);\n return { tokens: tokenIssues.length === 0, shape: shapeIssues.length === 0 };\n}\n\nfunction schemaIssuesOf(\n runner: RunnerModule,\n schema: HostSchemaLike,\n specifier: string,\n host: unknown,\n allowTokens: boolean,\n): RunnerIssue[] {\n const checked = hostSchemaIssues(runner, schema, specifier, host, {\n tokens: allowTokens ? \"allow\" : \"forbid\",\n });\n return [...checked.issues, ...(checked.schemaIssues ?? [])];\n}\n\nasync function checkSubject(\n result: CheckHostResult,\n options: CheckHostOptions,\n subject: ReactorSubject,\n): Promise<void> {\n const issue = issuer(result, subject.file);\n const { runner, specifier, file } = subject;\n const declared = checkDeclared(result, subject, subject.outputsSchemaOf);\n const resolveEnv = processResolveEnv(options.projectRoot, options.env);\n const patch = subject.patch ?? ((host) => host);\n\n // A one-shot verb (build) resolves nothing; its verb gets the declared host.\n if (ONE_SHOT_VERBS.has(subject.verb)) {\n if (!declared.tokens || !declared.shape) return;\n const host = patch(\n substituteBuiltinEnv(subject.host, resolveEnv.builtins ?? {}),\n );\n const schema = runner.declaredHostSchema ?? runner.hostSchema;\n for (const i of schemaIssuesOf(runner, schema, specifier, host, true)) {\n issue(\"resolved\", i);\n }\n return;\n }\n\n const unset = envSitesOf(subject.host).filter(\n (site) =>\n !site.optional &&\n !isBuiltinEnvName(site.name) &&\n options.env[site.name] === undefined,\n );\n for (const site of unset) {\n issue(\"resolve\", { path: site.path, message: unsetEnvMessage(site.name) });\n }\n if (!declared.tokens || unset.length > 0) return;\n\n let resolved: Record<string, unknown>;\n let deferred: DeferredToken[] = [];\n try {\n if (options.outputs) {\n resolved = resolveHostOutputs(subject.host, {\n outputs: options.outputs,\n ...resolveEnv,\n });\n } else {\n const partial = resolveHostOutputs(subject.host, resolveEnv, {\n deferSelf: subject.self,\n });\n resolved = partial.host;\n deferred = partial.deferred;\n }\n } catch (error) {\n if (error instanceof TokenResolutionError && error.detail) {\n issue(\"resolve\", {\n path: error.detail.path,\n message: error.detail.reason,\n });\n } else {\n issue(\"resolve\", \"\", error);\n }\n return;\n }\n result.deferred.push(...deferred.map((d) => ({ ...d, file })));\n if (!declared.shape) return;\n\n const allow = deferred.length > 0;\n const schema = allow\n ? (runner.declaredHostSchema ?? runner.hostSchema)\n : runner.hostSchema;\n const checked = hostSchemaIssues(runner, schema, specifier, patch(resolved), {\n tokens: allow ? \"allow\" : \"forbid\",\n });\n const resolvedIssues = [...checked.issues, ...(checked.schemaIssues ?? [])];\n for (const i of resolvedIssues) issue(\"resolved\", i);\n if (resolvedIssues.length > 0 || !runner.checkBoot) return;\n\n try {\n const boot = await runner.checkBoot(checked.data, {\n projectRoot: options.projectRoot,\n verb: subject.verb,\n env: options.env,\n file,\n });\n for (const i of boot) issue(\"boot\", { ...i, path: i.path ?? \"\" });\n } catch (error) {\n issue(\"boot\", \"\", error);\n }\n}\n\nasync function checkCompound(\n result: CheckHostResult,\n options: CheckHostOptions,\n subject: Subject,\n): Promise<void> {\n const issue = issuer(result, subject.file);\n const { host, runner, specifier } = subject;\n const declared = checkDeclared(result, subject);\n if (!declared.tokens || !declared.shape) return;\n // Without a declared schema, checkDeclared checked the kind shape only.\n if (!runner.declaredHostSchema) {\n const own = schemaIssuesOf(\n runner,\n runner.hostSchema,\n specifier,\n host,\n true,\n );\n for (const i of own) issue(\"resolved\", i);\n if (own.length > 0) return;\n }\n\n const children = (\n isPlainObject(host.children) ? host.children : {}\n ) as Record<string, ChildWrapper>;\n const wiring = (\n isPlainObject(host.config) ? host.config : {}\n ) as CompoundWiring;\n // The generic compound's mapping; a runner with its own (desktop's\n // `serve`) is checked as if it were generic.\n const verb = compoundStartVerb(\n subject.verb,\n host.runner as { defaultVerb?: string },\n );\n\n const prepared: PreparedMember[] = [];\n for (const [key, member] of Object.entries(children)) {\n try {\n prepared.push(await prepareMember(options.projectRoot, key, member));\n } catch (error) {\n issuer(result, `hosts/${member.host}/host.js`)(\"load\", \"\", error);\n }\n }\n const members = Object.entries(children).map(([key, m]) => ({\n key,\n host: m.host,\n }));\n if (prepared.length === members.length) {\n try {\n planCompound(\n prepared.map((m) => ({\n key: m.key,\n host: m.member.host,\n refs: outputSitesOf(m.draft).map(({ ref, path }) => ({\n ref,\n path,\n })),\n })),\n wiring.startOrder,\n );\n } catch (error) {\n issue(\"declared\", \"\", error);\n }\n }\n\n const byKey = new Map(prepared.map((m) => [m.key, m]));\n const outputsSchemaOf = (ref: OutputRef): OutputsSchemaLookup => {\n const target = memberForRef(ref, members);\n if (\"error\" in target) return { error: target.error };\n const producer = byKey.get(target.key);\n return producer\n ? runnerOutputsSchema(\n producer.runner,\n producer.specifier,\n `member \"${target.key}\"`,\n )\n : { error: `names member \"${target.key}\", which was not prepared.` };\n };\n for (const m of prepared) {\n const csp = wiring.cspRegistrySync === true && takesCspRegistrySync(m);\n await checkSubject(result, options, {\n file: m.file,\n host: m.draft,\n runner: m.runner,\n specifier: m.specifier,\n verb: memberVerbOf(verb, m.draft.runner),\n outputsSchemaOf,\n self: { members },\n ...(csp\n ? {\n patch: (resolved) => ({\n ...resolved,\n runner: { ...(resolved.runner as object), cspRegistrySync: true },\n }),\n }\n : {}),\n });\n }\n}\n\nfunction issuer(result: CheckHostResult, file: string) {\n return (\n stage: CheckStage,\n found: RunnerIssue | string,\n error?: unknown,\n ): void => {\n if (typeof found !== \"string\") {\n const { path, message, hint } = found;\n result.issues.push({\n stage,\n file,\n path,\n message,\n ...(hint ? { hint } : {}),\n });\n return;\n }\n const text = error instanceof Error ? error.message : String(error);\n const [message, hint] = text.split(\"\\n Hint: \");\n result.issues.push({\n stage,\n file,\n path: found,\n message,\n ...(hint ? { hint } : {}),\n });\n };\n}\n","import { z } from \"zod\";\nimport { declaredHostSchemas, type HostDefinition } from \"./host-schemas.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction childFolders(host: unknown): [key: string, folder: string][] {\n if (!isRecord(host) || !isRecord(host.children)) return [];\n return Object.entries(host.children).flatMap(([key, child]) =>\n isRecord(child) && typeof child.host === \"string\"\n ? [[key, child.host] as [string, string]]\n : [],\n );\n}\n\n// Picked by structure, as the loader does, so issues name the field.\nconst declaredHostSchema = z\n .custom<HostDefinition>()\n .superRefine((host, ctx) => {\n const schema =\n isRecord(host) && \"children\" in host\n ? declaredHostSchemas.compoundHostSchema\n : declaredHostSchemas.reactorHostSchema;\n const result = schema.safeParse(host);\n if (result.success) return;\n for (const issue of result.error.issues) {\n ctx.addIssue({\n code: \"custom\",\n message: issue.message,\n path: issue.path,\n });\n }\n });\n\n/** `ph host export`: a declared host plus its members, keyed by folder. */\nexport const hostExportSchema = z\n .strictObject({\n format: z.literal(\"ph-host-export\"),\n version: z.literal(1),\n project: z.strictObject({\n name: z.string().min(1),\n root: z.string().min(1),\n }),\n name: z.string().min(1),\n host: declaredHostSchema,\n members: z.record(z.string(), declaredHostSchema),\n })\n .superRefine((value, ctx) => {\n const reached = new Set<string>();\n const pending: [at: string[], host: unknown][] = [[[\"host\"], value.host]];\n for (let next = pending.shift(); next; next = pending.shift()) {\n const [at, host] = next;\n for (const [key, folder] of childFolders(host)) {\n if (!(folder in value.members)) {\n ctx.addIssue({\n code: \"custom\",\n path: [...at, \"children\", key, \"host\"],\n message: `Member folder \"${folder}\" is missing from members.`,\n });\n continue;\n }\n if (reached.has(folder)) continue;\n reached.add(folder);\n pending.push([[\"members\", folder], value.members[folder]]);\n }\n }\n for (const folder of Object.keys(value.members)) {\n if (reached.has(folder)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"members\", folder],\n message: `Member \"${folder}\" is not reached from the host's children.`,\n });\n }\n });\n\nexport type HostExport = z.input<typeof hostExportSchema>;\n","import path from \"node:path\";\nimport { z } from \"zod\";\nimport { hostExportSchema, type HostExport } from \"./host-export-schema.js\";\nimport { declaredHostSchemas, type HostDefinition } from \"./host-schemas.js\";\nimport { HostLoadError, loadHost } from \"./host-loader.js\";\nimport { readProjectName } from \"./run-record.js\";\n\nfunction checkHint(name: string): string {\n return `Run \\`ph host check ${name}\\`.`;\n}\n\nfunction childFolders(host: HostDefinition, name: string): string[] {\n if (!(\"children\" in host)) return [];\n const parsed = declaredHostSchemas.childrenSchema.safeParse(host.children);\n if (!parsed.success) {\n throw new HostLoadError(\n `hosts/${name}/host.js: invalid \\`children\\`:\\n${z.prettifyError(parsed.error)}`,\n checkHint(name),\n );\n }\n return Object.values(parsed.data).map((child) => child.host);\n}\n\n/** A host as declared and every member it reaches, raw `loadHost` bodies. */\nexport async function exportHost(\n projectRoot: string,\n name: string,\n): Promise<HostExport> {\n const root = path.resolve(projectRoot);\n const { host } = await loadHost(root, name);\n const members: Record<string, HostDefinition> = {};\n const visit = async (folders: string[]): Promise<void> => {\n for (const folder of folders) {\n if (folder in members) continue;\n const member = (await loadHost(root, folder)).host;\n members[folder] = member;\n await visit(childFolders(member, folder));\n }\n };\n await visit(childFolders(host, name));\n const envelope: HostExport = {\n format: \"ph-host-export\",\n version: 1,\n project: { name: readProjectName(root), root },\n name,\n host,\n members,\n };\n // What a consumer parses: `undefined` keys drop in the JSON round trip.\n const parsed = hostExportSchema.safeParse(\n JSON.parse(JSON.stringify(envelope)),\n );\n if (!parsed.success) {\n throw new HostLoadError(\n `hosts/${name}/host.js: the export is not a valid host export:\\n${z.prettifyError(parsed.error)}`,\n checkHint(name),\n );\n }\n return envelope;\n}\n","import crypto from \"node:crypto\";\nimport {\n DRIVE_ICON_MAX_BYTES,\n resolveImageRef,\n} from \"@powerhousedao/shared/connect/image-ref\";\nimport { projectDriveIdWith, type DriveDeclaration } from \"./drive-schema.js\";\n\n/**\n * R1 — core drive declarations. A reactor without drives is not a running\n * reactor, so declaring + seeding them is HOST RUNTIME work (not a plugin):\n * onReactorReady → idempotent slug-keyed seeding → onDrivesReady. Plugins\n * CONTRIBUTE declarations into the same merged list (Contributions.drives);\n * `--explain drives` prints the merged set with provenance.\n *\n * The declaration schema lives in drive-schema.ts (platform-neutral); this\n * module is the node half: resolution (image refs read files), seeding and\n * the node:crypto-bound project drive id.\n */\n\nexport {\n driveDeclarationSchema,\n drivesSchema,\n type DriveDeclaration,\n} from \"./drive-schema.js\";\n\nconst sha256Hex = (input: string): string =>\n crypto.createHash(\"sha256\").update(input).digest(\"hex\");\n\nexport function projectDriveId(projectRoot: string, slug: string): string {\n return projectDriveIdWith(sha256Hex, projectRoot, slug);\n}\n\nexport interface ResolvedDrive {\n kind: \"local\" | \"remote\";\n id: string;\n slug: string;\n name: string;\n icon?: string;\n preferredEditor?: string;\n sharingType: \"public\" | \"private\" | \"shared\";\n availableOffline: boolean;\n remoteUrl?: string;\n}\n\nexport function resolveDriveDeclaration(\n projectRoot: string,\n decl: DriveDeclaration,\n): ResolvedDrive {\n const id = decl.projectHash\n ? projectDriveId(projectRoot, decl.slug)\n : (decl.id ?? decl.slug);\n // Hash-derived drives serve under the hashed slug too (classic parity:\n // the vetra drive's slug IS its hashed id) — unless only the id is hashed.\n const slug = decl.projectHash === true ? id : decl.slug;\n if (decl.remote) {\n return {\n kind: \"remote\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n remoteUrl: decl.remote.url,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n }\n return {\n kind: \"local\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n // A project path becomes a data URI here (the icon lives in synced drive\n // state, so it is size-capped); URLs and data URIs pass through.\n icon: resolveImageRef(projectRoot, decl.icon, {\n maxBytes: DRIVE_ICON_MAX_BYTES,\n warn: (m) => console.warn(m),\n }),\n preferredEditor: decl.preferredEditor,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n}\n\n/* ------------------------------------------------------------------ seeding */\n\n/** The minimal client surface the seeder needs — runners adapt their reactor\n * clients (IReactorClient, addDefaultDrive-style helpers) onto it. */\nexport interface DriveSeederClient {\n /** Return the existing drive's id for a slug, or undefined. */\n findDriveBySlug(slug: string): Promise<string | undefined>;\n /** Create a local drive; preferredEditor lands on header.meta. */\n createDrive(drive: ResolvedDrive): Promise<void>;\n /** Attach a remote drive by URL (idempotent on the client side). */\n attachRemoteDrive(url: string): Promise<void>;\n}\n\nexport interface SeedResult {\n created: string[];\n existing: string[];\n attached: string[];\n}\n\n/** Idempotent, slug-keyed: an existing slug is left untouched (never\n * recreated, never mutated — preserveStrategy refinements live here later). */\nexport async function seedDrives(\n client: DriveSeederClient,\n drives: readonly ResolvedDrive[],\n): Promise<SeedResult> {\n const result: SeedResult = { created: [], existing: [], attached: [] };\n for (const drive of drives) {\n if (drive.kind === \"remote\") {\n await client.attachRemoteDrive(drive.remoteUrl!);\n result.attached.push(drive.slug);\n continue;\n }\n const existing = await client.findDriveBySlug(drive.slug);\n if (existing !== undefined) {\n result.existing.push(drive.slug);\n continue;\n }\n await client.createDrive(drive);\n result.created.push(drive.slug);\n }\n return result;\n}\n\n/* ------------------------------------------------------------------ explain */\n\nexport interface DrivePlanEntry {\n drive: ResolvedDrive;\n /** \"host\" for host.js declarations; a plugin name for contributions. */\n source: string;\n}\n\n/** Merge host-declared drives with plugin contributions, slug-keyed — the\n * host file wins on conflicts (it is the most explicit source). */\nexport function mergeDrivePlan(\n projectRoot: string,\n hostDeclared: readonly DriveDeclaration[],\n contributed: readonly { declaration: DriveDeclaration; source: string }[],\n): DrivePlanEntry[] {\n const plan = new Map<string, DrivePlanEntry>();\n for (const { declaration, source } of contributed) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source });\n }\n for (const declaration of hostDeclared) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source: \"host\" });\n }\n return [...plan.values()];\n}\n\nexport function explainDrivePlan(plan: readonly DrivePlanEntry[]): string {\n if (plan.length === 0) return \"(no drives declared)\";\n const lines = plan.map(({ drive, source }) => {\n const kind =\n drive.kind === \"remote\" ? `remote ${drive.remoteUrl}` : \"local\";\n const editor = drive.preferredEditor\n ? ` editor=${drive.preferredEditor}`\n : \"\";\n return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;\n });\n return [\"drives:\", ...lines].join(\"\\n\");\n}\n","import type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\n/**\n * Phase 4 (track R): project named host backends onto reactor-monitor's\n * `ReactorDescriptor` shape — the input `provision()` takes. Pure and\n * dependency-free; a type-assignability test pins the output to the real\n * `ReactorDescriptor` so an upstream field rename fails this package's tests\n * instead of silently drifting (D2.b: aligned locally, upstreaming not\n * blocked on).\n */\n\n/** The browser-provisionable storage union — reactor-monitor's\n * `ReactorStorageConfig` shape. `postgres` is the SERVER extension (D2.b): a\n * switchboard backend's storage, never a provisioned browser reactor's. */\nexport type ProjectedStorage =\n | { kind: \"idb\" }\n | { kind: \"memory\" }\n | { kind: \"path\"; dataDir: string };\n\nexport interface ProjectedDescriptor {\n kind: \"in-process\" | \"worker\" | \"remote\";\n name: string;\n storage?: ProjectedStorage;\n packages?: { cdnUrl?: string; specs?: string[]; dynamic?: boolean };\n featureFlags?: {\n documentDecisions?: boolean;\n authEnforcement?: boolean;\n authGroups?: boolean;\n authConditions?: boolean;\n };\n remote?: { url: string };\n}\n\nfunction projectStorage(\n name: string,\n storage: NonNullable<ReactorBackend[\"storage\"]>,\n): ProjectedStorage {\n switch (storage.kind) {\n case \"idb\":\n return { kind: \"idb\" };\n case \"memory\":\n return { kind: \"memory\" };\n case \"path\": {\n if (!storage.dataDir) {\n throw new Error(\n `Backend \"${name}\": storage kind \"path\" requires dataDir.`,\n );\n }\n return { kind: \"path\", dataDir: storage.dataDir };\n }\n case \"postgres\":\n throw new Error(\n `Backend \"${name}\": storage kind \"postgres\" is server-side only — ` +\n `a provisioned (in-process/worker) reactor cannot use it. Point a ` +\n `\"remote\" backend at the switchboard that owns that database instead.`,\n );\n }\n}\n\n/** One backend → one descriptor. The protocol's featureFlags ride every\n * descriptor (they are fleet consensus, not per-backend). A remote backend\n * must carry remote.url — provision() requires it. */\nexport function backendToDescriptor(\n name: string,\n backend: ReactorBackend,\n protocol?: ReactorProtocol,\n): ProjectedDescriptor {\n const descriptor: ProjectedDescriptor = {\n kind: backend.kind,\n name,\n };\n if (descriptor.kind === \"remote\") {\n const url = backend.remote?.url;\n if (!url) {\n throw new Error(\n `Backend \"${name}\" is kind \"remote\" but has no remote.url — ` +\n `a remote descriptor attaches to an already-running reactor by URL.`,\n );\n }\n descriptor.remote = { url };\n // remote attaches; it builds nothing, so local-build fields do not apply\n return descriptor;\n }\n if (backend.storage) {\n descriptor.storage = projectStorage(name, backend.storage);\n }\n if (backend.packages) descriptor.packages = backend.packages;\n if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n return descriptor;\n}\n\n/** All named backends, in placement-primary-first order (the order a\n * createReactorClients step would provision them). */\nexport function backendsToDescriptors(\n reactor: ReactorConfig | undefined,\n): ProjectedDescriptor[] {\n const backends = reactor?.backends;\n if (!backends) return [];\n const names = Object.keys(backends);\n const primary = reactor.placement?.primary;\n const ordered =\n primary && names.includes(primary)\n ? [primary, ...names.filter((n) => n !== primary)]\n : names;\n return ordered.map((name) =>\n backendToDescriptor(name, backends[name], reactor.protocol),\n );\n}\n\nconst LOCAL_KINDS = new Set<ReactorBackendKind>([\"in-process\", \"worker\"]);\n\n/**\n * Structural multi-reactor (phase 4): true when the block names BOTH a local\n * backend (in-process/worker — the tab's own reactor) and a remote one. This\n * is the shape Connect's routing client serves; a lone remote backend is an\n * attach-only host (assistant/agent shape), not a routed tab.\n */\nexport function isStructuralMultiReactor(\n reactor: ReactorConfig | undefined,\n): boolean {\n const backends = reactor?.backends;\n if (!backends) return false;\n const kinds = Object.values(backends).map((b) => b.kind);\n return (\n kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\")\n );\n}\n\n/** The remote backends' drive addresses, placement order. */\nexport function remoteBackendUrls(\n reactor: ReactorConfig | undefined,\n): string[] {\n return backendsToDescriptors(reactor)\n .filter((d) => d.kind === \"remote\")\n .map((d) => d.remote?.url)\n .filter((u): u is string => typeof u === \"string\");\n}\n\n/**\n * The remote backends by host key, placement order. A url that is not a\n * string yet (an output token, unresolved when a host builds) is skipped, as\n * in remoteBackendUrls.\n */\nexport function remoteBackends(\n reactor: ReactorConfig | undefined,\n): { name: string; url: string }[] {\n return backendsToDescriptors(reactor).flatMap((d) =>\n d.kind === \"remote\" && typeof d.remote?.url === \"string\"\n ? [{ name: d.name, url: d.remote.url }]\n : [],\n );\n}\n","/**\n * The shared `reactor` host-config block and its projections onto the\n * Switchboard config / Connect runtime config. Phase 2 of uniform-runners: makes\n * the reactor block live through the bridge runners, BEFORE track R replaces\n * the projection with reactor-monitor's provision(). The headline is\n * single-sourced `reactor.protocol` — both projections read the same block, so\n * client and server cannot diverge, and a contradicting pre-set env fails boot.\n */\n\nimport { remoteBackends } from \"./backend-projection.js\";\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\nexport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorPackageConfig,\n ReactorProtocol,\n ReactorRemoteConfig,\n ReactorStorageConfig,\n} from \"./host-schemas.js\";\n\n/** The single primary backend for phase-2 projection (multi-backend routing is\n * track R). Prefers placement.primary, else \"main\"/\"local\", else the first. */\nexport function primaryBackend(\n reactor: ReactorConfig | undefined,\n): ReactorBackend | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const names = Object.keys(backends);\n if (names.length === 0) return undefined;\n const pick =\n reactor.placement?.primary ??\n (names.includes(\"main\")\n ? \"main\"\n : names.includes(\"local\")\n ? \"local\"\n : names[0]);\n return backends[pick];\n}\n\nconst FLAG_ENV: Record<\n keyof NonNullable<ReactorProtocol[\"featureFlags\"]>,\n string\n> = {\n documentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n authEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n authGroups: \"REACTOR_AUTH_GROUPS\",\n authConditions: \"REACTOR_AUTH_CONDITIONS\",\n};\n\n/** The env vars a protocol block maps onto, with their string values. Only\n * keys the block actually sets appear. */\nexport function protocolEnv(\n protocol: ReactorProtocol | undefined,\n): Record<string, string> {\n const env: Record<string, string> = {};\n if (!protocol) return env;\n for (const [key, varName] of Object.entries(FLAG_ENV)) {\n const value = protocol.featureFlags?.[key as keyof typeof FLAG_ENV];\n if (value !== undefined) env[varName] = value ? \"true\" : \"false\";\n }\n if (protocol.createSignaturePolicy !== undefined) {\n env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n }\n if (protocol.unsupportedStoredDocuments !== undefined) {\n env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS =\n protocol.unsupportedStoredDocuments;\n }\n return env;\n}\n\n/** The switchboard config layer a reactor block maps to (the shape of\n * `@powerhousedao/switchboard/config`'s input). Only keys the block sets. */\nexport interface SwitchboardReactorLayer {\n storage?: { reactor?: { url: string }; readModel?: { url: string } };\n protocol?: ReactorProtocol;\n packages?: { dynamic: true };\n features?: { workflows: boolean };\n}\n\n/** The reactor block as a switchboard config layer. The reactor store and the\n * read model are separate fields: `readModel.url` never moves the reactor. */\nexport function reactorBlockToSwitchboardConfig(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorLayer {\n const layer: SwitchboardReactorLayer = {};\n const backend = primaryBackend(reactor);\n const storage = backend?.storage;\n const reactorUrl =\n storage?.kind === \"postgres\" ? storage.url : storage?.dataDir;\n const readModelUrl = backend?.readModel?.url;\n if (reactorUrl || readModelUrl) {\n layer.storage = {\n ...(reactorUrl ? { reactor: { url: reactorUrl } } : {}),\n ...(readModelUrl ? { readModel: { url: readModelUrl } } : {}),\n };\n }\n if (reactor?.protocol) layer.protocol = reactor.protocol;\n if (backend?.packages?.dynamic) layer.packages = { dynamic: true };\n if (reactor?.workflows !== undefined) {\n layer.features = { workflows: reactor.workflows };\n }\n return layer;\n}\n\n/** The four reactor-client shapes a Connect host can select (mirrors the\n * shared PHReactorClientMode; kept local to avoid an import cycle). */\nexport type ReactorClientMode = \"in-process\" | \"worker\" | \"remote\" | \"router\";\n\nconst LOCAL_BACKEND_KINDS = new Set<ReactorBackendKind>([\n \"in-process\",\n \"worker\",\n]);\n\n/**\n * Which reactor client the backend topology asks for:\n * - local (in-process/worker) AND remote backends -> `router`\n * - remote backend(s) only -> `remote`\n * - a worker backend -> `worker`\n * - anything else local -> `in-process`\n * `undefined` when no backends are declared — the caller then keeps the\n * legacy reactorWorker/multiReactor behaviour untouched.\n */\nexport function reactorClientMode(\n reactor: ReactorConfig | undefined,\n): ReactorClientMode | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const kinds = Object.values(backends).map((b) => b.kind);\n if (kinds.length === 0) return undefined;\n const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));\n const hasRemote = kinds.some((k) => k === \"remote\");\n if (hasLocal && hasRemote) return \"router\";\n if (hasRemote) return \"remote\";\n return primaryBackend(reactor)?.kind === \"worker\" ? \"worker\" : \"in-process\";\n}\n\nexport interface ConnectReactorProjection {\n /** Patch merged into the connect runtime config (connect.*). */\n connect: {\n reactor?: ReactorProtocol;\n instance?: {\n reactorWorker?: boolean;\n reactorClient?: ReactorClientMode;\n remoteBackends?: { name: string; url: string }[];\n };\n app?: { workflowsEnabled?: boolean };\n };\n}\n\n/** Project the reactor block onto the Connect runtime config: protocol →\n * connect.reactor (same shape), backend topology → instance.reactorWorker\n * (legacy), instance.reactorClient and instance.remoteBackends,\n * workflows → app.workflowsEnabled. */\nexport function projectReactorToConnect(\n reactor: ReactorConfig | undefined,\n): ConnectReactorProjection {\n const connect: ConnectReactorProjection[\"connect\"] = {};\n if (reactor?.protocol) connect.reactor = reactor.protocol;\n const backend = primaryBackend(reactor);\n const mode = reactorClientMode(reactor);\n if (backend?.kind !== undefined || mode !== undefined) {\n connect.instance = {\n ...(backend?.kind !== undefined\n ? { reactorWorker: backend.kind === \"worker\" }\n : {}),\n ...(mode !== undefined ? { reactorClient: mode } : {}),\n ...(mode === \"router\" || mode === \"remote\"\n ? { remoteBackends: remoteBackends(reactor) }\n : {}),\n };\n }\n if (reactor?.workflows !== undefined) {\n connect.app = { workflowsEnabled: reactor.workflows };\n }\n return { connect };\n}\n\n/** Each pre-set env var that CONTRADICTS the host's protocol block, as a\n * message naming the var, the host value and the env value. An env var that\n * merely matches, or is unset, is fine. */\nexport function protocolConflicts(\n protocol: ReactorProtocol | undefined,\n env: Readonly<Record<string, string | undefined>>,\n hostFile = \"the host file\",\n): string[] {\n if (!protocol) return [];\n return Object.entries(protocolEnv(protocol)).flatMap(\n ([varName, hostValue]) => {\n const envValue = env[varName];\n if (envValue === undefined || envValue === hostValue) return [];\n return [\n `reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment ` +\n `but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — ` +\n `a mismatch would diverge replay. Remove the env override or align the host.`,\n ];\n },\n );\n}\n\n/**\n * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n * the host's protocol block, fail loudly naming the var, the host value, and\n * the env value (phase-2 transition keeps an operator's explicit env as an\n * escape hatch unless it disagrees with the protocol — see the WBS\n * precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n const conflict = protocolConflicts(protocol, env, hostFile).at(0);\n if (conflict) throw new Error(conflict);\n}\n","import type {\n PHConnectCollection,\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n PHConnectRuntimeDefaultDrive,\n} from \"@powerhousedao/shared/clis\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { remoteBackends } from \"./backend-projection.js\";\nimport type { ReactorConfig } from \"./host-schemas.js\";\n\n/**\n * Instance-fact projection for compound hosts: the drives a compound's\n * reactor member created, projected into the Connect member's runtime-config\n * override. Pure functions, moved from ph-cli's vetra service so the generic\n * compound and the classic path share one implementation.\n */\n\nfunction isLocalDrive(\n drive: PHConnectDefaultDrive,\n): drive is Extract<PHConnectDefaultDrive, { local: true }> {\n return \"local\" in drive;\n}\n\n// Identity key for de-duplication: remote entries are keyed by URL; local\n// entries are keyed by `local:<id>` so a local drive id can never collide\n// with a remote URL that happens to be the same string.\nconst driveKey = (drive: PHConnectDefaultDrive): string =>\n isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\n\n/**\n * Concatenate groups of `connect.drives.defaultDrives` in the order given,\n * de-duplicating by drive identity (URL for remote entries, id for local\n * ones). The first occurrence of a drive wins, so earlier groups keep their\n * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first\n * even when the project's `powerhouse.config.json` lists the same drive.\n */\nexport function mergeDefaultDrives(\n ...groups: PHConnectDefaultDrive[][]\n): PHConnectDefaultDrive[] {\n const seen = new Set<string>();\n const out: PHConnectDefaultDrive[] = [];\n for (const group of groups) {\n for (const drive of group) {\n const key = driveKey(drive);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(drive);\n }\n }\n return out;\n}\n\n/**\n * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,\n * swaps the loopback origin for the public base. Browser clients behind a\n * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs\n * (e.g. a remote drive) are already public and pass through unchanged, as do\n * unparseable ones.\n */\nexport function rebaseDriveUrl(driveUrl: string, publicBase: string): string {\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n}\n\nexport interface DriveProjectionInput {\n /** Drive URLs the compound's reactor member created, in display order\n * (e.g. vetra, preview, workflows). Null/undefined entries are skipped. */\n createdDriveUrls: (string | null | undefined)[];\n /** The project's configured `connect.drives.defaultDrives`. */\n configuredDefaultDrives?: PHConnectDefaultDrive[];\n /** `--drives-public-base`: advertise proxy-reachable URLs to the browser. */\n publicBase?: string | null;\n}\n\n/**\n * The compound's drives projection: created drives first (rebased onto the\n * public base when given), then the project's configured drives, de-duplicated\n * — and `preserve-all`, because compound-injected drive lists change per\n * launch context and must never detach drives the user added by hand.\n */\nexport function projectDrivesIntoConnect(\n input: DriveProjectionInput,\n): Pick<PHConnectRuntimeConfig, \"drives\"> {\n const created: PHConnectDefaultDrive[] = input.createdDriveUrls\n .filter((url): url is string => typeof url === \"string\" && url.length > 0)\n .map((url) => ({\n url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n name: null,\n icon: null,\n }));\n return {\n drives: {\n defaultDrives: mergeDefaultDrives(\n created,\n input.configuredDefaultDrives ?? [],\n ),\n preserveStrategy: \"preserve-all\",\n },\n };\n}\n\n/** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */\nfunction servesSlug(declared: string, served: string): boolean {\n return (\n served === declared ||\n (served.startsWith(`${declared}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1)))\n );\n}\n\nexport interface PlacedConnectDrives {\n defaultDrives: PHConnectRuntimeDefaultDrive[];\n collections?: Record<string, PHConnectCollection>;\n}\n\n/** Annotates remote default drives with their backend (`sync: false` when placed on it); other remote placements become collections. */\nexport function placeConnectDrives(\n reactor: ReactorConfig | undefined,\n defaultDrives: readonly PHConnectDefaultDrive[],\n): PlacedConnectDrives {\n const remotes = remoteBackends(reactor).flatMap(({ name, url }) => {\n const at = switchboardOfDrive(url);\n return at ? [{ name, base: at.base }] : [];\n });\n if (remotes.length === 0) return { defaultDrives: [...defaultDrives] };\n const placement = Object.entries(reactor?.placement?.drives ?? {});\n const matched = new Set<string>();\n const placed = defaultDrives.map((drive): PHConnectRuntimeDefaultDrive => {\n if (!(\"url\" in drive)) return drive;\n const at = switchboardOfDrive(drive.url);\n const backend = remotes.find((remote) => remote.base === at?.base)?.name;\n if (!at || !backend) return drive;\n const entry = placement.find(([slug]) => servesSlug(slug, at.slug));\n if (entry) matched.add(entry[0]);\n return entry?.[1] === backend\n ? { ...drive, backend, sync: false }\n : { ...drive, backend };\n });\n const names = new Set(remotes.map((remote) => remote.name));\n const collections = Object.fromEntries(\n placement\n .filter(([slug, backend]) => !matched.has(slug) && names.has(backend))\n .map(([slug, backend]) => [slug, { backend, sync: false }]),\n );\n return Object.keys(collections).length > 0\n ? { defaultDrives: placed, collections }\n : { defaultDrives: placed };\n}\n","import {\n backendToDescriptor,\n isStructuralMultiReactor,\n} from \"./backend-projection.js\";\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorStorageConfig,\n RunnerKind,\n} from \"./host-schemas.js\";\nimport { reactorClientMode, type ReactorClientMode } from \"./reactor-config.js\";\nimport { envSitesOf, outputSitesOf, refKey } from \"./resolve/declared.js\";\nimport type { CompoundPlan } from \"./resolve/plan.js\";\nimport type { OutputPath } from \"./tokens.js\";\n\n/**\n * What a host amounts to once its pipeline has run (typed-host-configs G2,\n * 2.2): the reactor-client shape its backends select, the drives it serves\n * or attaches, the producers whose outputs it consumes and, for a compound,\n * the start order and each member's expectation. Pure and platform-neutral:\n * the caller runs load → declared validation → resolve → resolved\n * validation (and plugin contribution discovery) and hands over the\n * results. The returned value is JSON-only, so it can be pinned in a test\n * table or shipped to another process (a future reactor-monitor).\n */\n\n/** One backend, in placement-primary-first order. */\nexport interface ExpectedBackend {\n name: string;\n kind: ReactorBackendKind;\n storage?: ReactorStorageConfig[\"kind\"];\n /** The RESOLVED storage dir (`\"${userData}\"` sugar and `$env` applied). */\n dataDir?: string;\n /** Why a provisioned reactor (a browser tab, reactor-monitor) cannot be\n * built from this backend (`backendToDescriptor`): e.g. postgres storage\n * is server-side only, a remote backend needs `remote.url`. Absent when\n * it can. A switchboard's own backend may legitimately carry one. */\n provisionError?: string;\n}\n\n/** One drive of the merged plan: plugin contributions first, then the\n * host's own declarations (the host wins a slug). Identity is the DECLARED\n * slug: a `projectHash` drive reports the flag, not a hashed id, so the\n * expectation does not depend on where the project lives. */\nexport interface ExpectedDrive {\n slug: string;\n kind: \"local\" | \"remote\";\n /** \"host\" for `reactor.drives`; the plugin name for a contribution. */\n source: string;\n /** A remote drive's resolved URL. */\n url?: string;\n id?: string;\n projectHash?: boolean | \"id\";\n}\n\n/** One `$output` token in the declared host. */\nexport interface ConsumedOutput {\n /** Host path of the token (`reactor.backends.sb.remote.url`). */\n at: string;\n host: string;\n member?: string;\n path: OutputPath;\n}\n\nexport interface HostExpectation {\n name: string;\n kind: RunnerKind;\n /** The verb this host runs at: `runner.defaultVerb ?? \"run\"` standalone;\n * for a compound member, its own effective verb under the compound's. */\n verb: string;\n /** Reactor hosts with backends: `reactorClientMode`. */\n clientMode?: ReactorClientMode;\n /** Reactor hosts: local AND remote backends (Connect's routing client). */\n multiReactor?: boolean;\n backends?: ExpectedBackend[];\n /** The resolved URLs of the remote backends, placement order. */\n remotes?: string[];\n drives?: ExpectedDrive[];\n /** Producers its own tokens read (`host` or `host#member`), sorted. */\n dependsOn: string[];\n consumes: ConsumedOutput[];\n /** `$env` names its own tokens read, sorted (values are not recorded). */\n env: string[];\n /** Compound: member keys in start order. */\n startOrder?: string[];\n /** Compound: each member's expectation. */\n members?: Record<string, MemberExpectation>;\n}\n\nexport interface MemberExpectation extends Omit<\n HostExpectation,\n \"startOrder\" | \"members\"\n> {\n /** The member's host folder (`children.<key>.host`). */\n host: string;\n /** Member keys this member consumes (it starts after them), sorted. */\n after: string[];\n}\n\n/** A drive a plugin contributes, as plugin contribution discovery reports\n * it (`resolvePluginContributions`). */\nexport interface ContributedDriveInput {\n declaration: Record<string, unknown>;\n source: string;\n}\n\nexport interface ExpectHostInput {\n kind: RunnerKind;\n /** The host as declared (tokens in place); a compound member's draft\n * (its host.js with the wrapper applied). */\n declared: Record<string, unknown>;\n /** The resolved (and parsed) host. Default: `declared`. */\n resolved?: Record<string, unknown>;\n /** Drives the host's plugins contribute at its verb. */\n contributed?: readonly ContributedDriveInput[];\n /** Compound: its members, any order (the plan orders them). */\n members?: readonly MemberInput[];\n /** Compound: the dependency plan (`planCompound`). */\n plan?: CompoundPlan;\n}\n\nexport interface MemberInput extends Omit<ExpectHostInput, \"members\" | \"plan\"> {\n key: string;\n host: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction runnerOf(host: Record<string, unknown>): Record<string, unknown> {\n return isRecord(host.runner) ? host.runner : {};\n}\n\nfunction defaultVerbOf(host: Record<string, unknown>): string | undefined {\n const verb = runnerOf(host).defaultVerb;\n return typeof verb === \"string\" ? verb : undefined;\n}\n\n/** At compound verb \"run\" each member runs its own defaultVerb; any other\n * compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */\nfunction memberVerb(compoundVerb: string, member: Record<string, unknown>) {\n return compoundVerb === \"run\"\n ? (defaultVerbOf(member) ?? \"run\")\n : compoundVerb;\n}\n\n/** Backend names, placement-primary first (`backendsToDescriptors` order). */\nfunction orderedBackends(reactor: ReactorConfig): [string, ReactorBackend][] {\n const backends = Object.entries(reactor.backends ?? {});\n const primary = reactor.placement?.primary;\n const first = backends.filter(([name]) => name === primary);\n return [...first, ...backends.filter(([name]) => name !== primary)];\n}\n\nfunction expectBackend(\n name: string,\n backend: ReactorBackend,\n reactor: ReactorConfig,\n): ExpectedBackend {\n const out: ExpectedBackend = { name, kind: backend.kind };\n if (backend.storage) out.storage = backend.storage.kind;\n if (typeof backend.storage?.dataDir === \"string\") {\n out.dataDir = backend.storage.dataDir;\n }\n try {\n backendToDescriptor(name, backend, reactor.protocol);\n } catch (error) {\n out.provisionError = error instanceof Error ? error.message : String(error);\n }\n return out;\n}\n\nfunction expectDrive(\n declaration: Record<string, unknown>,\n source: string,\n): ExpectedDrive | undefined {\n if (typeof declaration.slug !== \"string\") return undefined;\n const remote = isRecord(declaration.remote) ? declaration.remote : undefined;\n const drive: ExpectedDrive = {\n slug: declaration.slug,\n kind: remote ? \"remote\" : \"local\",\n source,\n };\n if (remote && typeof remote.url === \"string\") drive.url = remote.url;\n if (typeof declaration.id === \"string\") drive.id = declaration.id;\n const projectHash = declaration.projectHash;\n if (typeof projectHash === \"boolean\" || projectHash === \"id\") {\n drive.projectHash = projectHash;\n }\n return drive;\n}\n\n/** The key `mergeDrivePlan` merges on: the SERVED slug, which for\n * `projectHash: true` is the hashed id (never equal to a plain slug). */\nfunction servedSlugKey(drive: ExpectedDrive): string {\n return drive.projectHash === true ? `${drive.slug}\\0hashed` : drive.slug;\n}\n\n/** Contributions first, then host declarations; keyed by served slug, the\n * host wins (and keeps the contribution's position), like `mergeDrivePlan`. */\nfunction drivePlan(\n reactor: ReactorConfig | undefined,\n contributed: readonly ContributedDriveInput[],\n): ExpectedDrive[] {\n const plan = new Map<string, ExpectedDrive>();\n for (const { declaration, source } of contributed) {\n const drive = expectDrive(declaration, source);\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n for (const declaration of reactor?.drives ?? []) {\n const drive = expectDrive(declaration, \"host\");\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n return [...plan.values()];\n}\n\n/** Token facts of the host's OWN fields (a compound's `children` are its\n * members' own). */\nfunction tokenFacts(\n declared: Record<string, unknown>,\n kind: RunnerKind,\n): Pick<HostExpectation, \"dependsOn\" | \"consumes\" | \"env\"> {\n const own =\n kind === \"compound\"\n ? Object.fromEntries(\n Object.entries(declared).filter(([key]) => key !== \"children\"),\n )\n : declared;\n const sites = outputSitesOf(own);\n const consumes = sites.map(({ path, ref, outputPath }): ConsumedOutput => ({\n at: path,\n host: ref.host,\n ...(ref.member !== undefined ? { member: ref.member } : {}),\n path: outputPath,\n }));\n return {\n dependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),\n consumes,\n env: [...new Set(envSitesOf(own).map(({ name }) => name))].sort(),\n };\n}\n\nfunction expectOwn(\n input: Omit<ExpectHostInput, \"members\" | \"plan\">,\n verb: string,\n): HostExpectation {\n const resolved = input.resolved ?? input.declared;\n const expectation: HostExpectation = {\n name: typeof resolved.name === \"string\" ? resolved.name : \"\",\n kind: input.kind,\n verb,\n ...tokenFacts(input.declared, input.kind),\n };\n if (input.kind !== \"reactor\") return expectation;\n\n const reactor = isRecord(resolved.reactor)\n ? (resolved.reactor as ReactorConfig)\n : undefined;\n const mode = reactorClientMode(reactor);\n if (mode !== undefined) expectation.clientMode = mode;\n expectation.multiReactor = isStructuralMultiReactor(reactor);\n const backends = reactor ? orderedBackends(reactor) : [];\n if (reactor && backends.length > 0) {\n expectation.backends = backends.map(([name, backend]) =>\n expectBackend(name, backend, reactor),\n );\n expectation.remotes = backends.flatMap(([, backend]) =>\n backend.kind === \"remote\" && typeof backend.remote?.url === \"string\"\n ? [backend.remote.url]\n : [],\n );\n }\n expectation.drives = drivePlan(reactor, input.contributed ?? []);\n return expectation;\n}\n\n/**\n * The expectation for one host. A reactor host's comes from its resolved\n * reactor block and contributed drives; a compound's lists its members in\n * plan order, each with the verb it runs at under the compound's own verb\n * and the members it starts after.\n */\nexport function expectHost(input: ExpectHostInput): HostExpectation {\n const verb = defaultVerbOf(input.declared) ?? \"run\";\n const expectation = expectOwn(input, verb);\n if (input.kind !== \"compound\" || !input.members) return expectation;\n\n const order = input.plan?.order ?? input.members.map((m) => m.key);\n const edges = input.plan?.edges ?? [];\n const byKey = new Map(input.members.map((m) => [m.key, m]));\n const members: Record<string, MemberExpectation> = {};\n for (const key of order) {\n const member = byKey.get(key);\n if (!member) continue;\n members[key] = {\n host: member.host,\n ...expectOwn(member, memberVerb(verb, member.declared)),\n after: [\n ...new Set(\n edges.filter((e) => e.consumer === key).map((e) => e.producer),\n ),\n ].sort(),\n };\n }\n expectation.startOrder = order.filter((key) => byKey.has(key));\n expectation.members = members;\n return expectation;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CACA;CAC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,MAAM,QAAQ,KAAK,MAAM,EAAE,GAAG;CACjE,MAAM,QAAQ,MAAM,MAAM,SAAS,CAAC;CACpC,MAAM,QAAQ,IAAI,IAAI,MAAM,QAAQ,KAAK,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;CAC1D,MAAM,UAA6C,CAAC;CACpD,KAAK,MAAM,OAAO,OAAO;EACvB,MAAM,SAAS,MAAM,IAAI,GAAG;EAC5B,IAAI,CAAC,QAAQ;EACb,QAAQ,OAAO;GACb,MAAM,OAAO;GACb,GAAG,UAAU,QAAQ,WAAW,MAAM,OAAO,QAAQ,CAAC;GACtD,OAAO,CACL,GAAG,IAAI,IACL,MAAM,QAAQ,MAAM,EAAE,aAAa,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,QAAQ,CAC/D,CACF,CAAC,CAAC,KAAK;EACT;CACF;CACA,YAAY,aAAa,MAAM,QAAQ,QAAQ,MAAM,IAAI,GAAG,CAAC;CAC7D,YAAY,UAAU;CACtB,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":["isRecord","childFolders","switchboardOfDrive"],"sources":["../src/spawn-host.ts","../src/check-host.ts","../src/host-export-schema.ts","../src/host-export.ts","../src/drives.ts","../src/backend-projection.ts","../src/reactor-config.ts","../src/connect-projection.ts","../src/expect-host.ts"],"sourcesContent":["import { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadHost } from \"./host-loader.js\";\nimport { clearRunRecord, listRunRecords } from \"./run-record.js\";\nimport type { RunRecord } from \"./run-record-schema.js\";\nimport {\n isSchemaLike,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n} from \"./runner-resolver.js\";\n\nexport interface SpawnHostOptions {\n projectRoot: string;\n /** Folder name under hosts/. */\n host: string;\n /** The child's PH_USER_DATA_DIR (created if missing). */\n dataDir: string;\n verb?: string;\n /** Merged over the clean base env; may not set PH_USER_DATA_DIR. */\n env?: Record<string, string>;\n /** ph-cli entry; default: the project's `@powerhousedao/ph-cli/dist/cli.mjs`. */\n cli?: string;\n readyTimeoutMs?: number;\n stopTimeoutMs?: number;\n /** Before ready: stop and reject. After: stop. */\n signal?: AbortSignal;\n onOutput?: (stream: \"stdout\" | \"stderr\", chunk: string) => void;\n /** Appends both streams. */\n logFile?: string;\n}\n\nexport interface HostExit {\n code: number | null;\n signal: NodeJS.Signals | null;\n /** SIGKILL after stopTimeoutMs. */\n forced: boolean;\n}\n\nexport interface SpawnedHost {\n pid: number;\n dataDir: string;\n record: RunRecord;\n outputs: Record<string, unknown> | undefined;\n members: RunRecord[\"members\"];\n /** Resolves (never rejects) when the child exits. */\n exited: Promise<HostExit>;\n /** SIGTERM, SIGKILL after stopTimeoutMs, clear a leftover record. */\n stop(): Promise<HostExit>;\n}\n\nexport type SpawnHostPhase = \"exited\" | \"timeout\" | \"aborted\";\n\nexport class SpawnHostError extends Error {\n constructor(\n message: string,\n readonly phase: SpawnHostPhase,\n readonly outputTail: string,\n readonly exit?: HostExit,\n ) {\n super(\n outputTail ? `${message}\\n--- output tail ---\\n${outputTail}` : message,\n );\n this.name = \"SpawnHostError\";\n }\n}\n\nconst READY_TIMEOUT_MS = 120_000;\nconst STOP_TIMEOUT_MS = 30_000;\nconst POLL_MS = 100;\nconst TAIL_BYTES = 8 * 1024;\n// A grandchild may hold the pipes open past the child's exit.\nconst CLOSE_WAIT_MS = 1_000;\n\nconst BASE_ENV_KEYS = [\"PATH\", \"HOME\", \"TMPDIR\"];\nconst WIN32_ENV_KEYS = [\n \"SystemRoot\",\n \"USERPROFILE\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"TEMP\",\n \"TMP\",\n \"ComSpec\",\n \"PATHEXT\",\n];\n\n/** The child's whole env: no other `process.env` key reaches it. */\nfunction childEnv(\n dataDir: string,\n env: Record<string, string> = {},\n): Record<string, string> {\n if (\"PH_USER_DATA_DIR\" in env) {\n throw new Error(\n \"spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.\",\n );\n }\n const keys =\n process.platform === \"win32\"\n ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS]\n : BASE_ENV_KEYS;\n const base: Record<string, string> = {};\n for (const key of keys) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n return {\n ...base,\n FEATURE_UNIFORM_RUNNERS_ENABLED: \"1\",\n PH_USER_DATA_DIR: dataDir,\n PH_NO_TELEMETRY: \"1\",\n PH_NO_DOTENV: \"1\",\n ...env,\n };\n}\n\nfunction resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\n/** Readiness waits for a record; refuse a host/verb that writes none. */\nasync function assertWritesRecord(\n projectRoot: string,\n host: string,\n verb: string | undefined,\n): Promise<void> {\n if (verb !== undefined && ONE_SHOT_VERBS.has(verb)) {\n throw new Error(\n `spawnHost: \"${verb}\" is a one-shot verb; it writes no run record to wait for.`,\n );\n }\n const loaded = await loadHost(projectRoot, host);\n const specifier = loaded.host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, specifier);\n if (runner.kind === \"compound\") {\n const config = (loaded.host as { config?: { runtimeRecord?: unknown } })\n .config;\n if (config?.runtimeRecord === false) {\n throw new Error(\n `spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`,\n );\n }\n return;\n }\n if (!isSchemaLike(runner.outputsSchema)) {\n throw new Error(\n `spawnHost: hosts/${host} runs \"${specifier}\", which exports no outputsSchema, so it writes no run record to wait for.`,\n );\n }\n}\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms).unref();\n });\n\n// Children still running when this process exits get SIGTERM, so a launcher\n// that exits without stop() leaves no host behind.\nconst live = new Set<ChildProcess>();\nlet exitHookInstalled = false;\nfunction track(child: ChildProcess): void {\n live.add(child);\n child.once(\"exit\", () => live.delete(child));\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n process.once(\"exit\", () => {\n for (const running of live) running.kill(\"SIGTERM\");\n });\n}\n\n/**\n * `ph run <host> [verb]` as a child; ready when its run record appears.\n *\n * The child shares this process's group, so a terminal Ctrl-C reaches both.\n * It runs the project's own ph-cli: one older than PH_NO_DOTENV reads the\n * project's `.env` anyway.\n */\nexport async function spawnHost(\n options: SpawnHostOptions,\n): Promise<SpawnedHost> {\n const projectRoot = path.resolve(options.projectRoot);\n const dataDir = path.resolve(options.dataDir);\n const env = childEnv(dataDir, options.env);\n const readerEnv = { PH_USER_DATA_DIR: dataDir };\n const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;\n const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;\n const { signal } = options;\n\n if (signal?.aborted) {\n throw new SpawnHostError(\"spawnHost: aborted before start.\", \"aborted\", \"\");\n }\n await assertWritesRecord(projectRoot, options.host, options.verb);\n const cli = options.cli ?? resolvePhCliEntry(projectRoot);\n fs.mkdirSync(dataDir, { recursive: true });\n\n const log = options.logFile\n ? fs.createWriteStream(options.logFile, { flags: \"a\" })\n : undefined;\n let tail = \"\";\n log?.on(\"error\", (error) => {\n tail = (tail + `logFile: ${error.message}\\n`).slice(-TAIL_BYTES);\n });\n const args = [cli, \"run\", options.host];\n if (options.verb !== undefined) args.push(options.verb);\n const child = spawn(process.execPath, args, {\n cwd: projectRoot,\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n track(child);\n\n const onChunk = (stream: \"stdout\" | \"stderr\") => (chunk: string) => {\n tail = (tail + chunk).slice(-TAIL_BYTES);\n log?.write(chunk);\n try {\n options.onOutput?.(stream, chunk);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n tail = (tail + `onOutput: ${message}\\n`).slice(-TAIL_BYTES);\n }\n };\n child.stdout.setEncoding(\"utf8\").on(\"data\", onChunk(\"stdout\"));\n child.stderr.setEncoding(\"utf8\").on(\"data\", onChunk(\"stderr\"));\n\n let forced = false;\n let exit: HostExit | undefined;\n const exited = new Promise<HostExit>((resolve) => {\n const done = (code: number | null, sig: NodeJS.Signals | null) => {\n if (exit) return;\n exit = { code, signal: sig, forced };\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(exit);\n };\n child.once(\"exit\", done);\n child.once(\"error\", (error) => {\n tail = (tail + `${error.message}\\n`).slice(-TAIL_BYTES);\n if (child.pid === undefined) done(null, null);\n });\n });\n\n // After the last chunk: stdio may still flush past \"exit\".\n const closed = new Promise<void>((resolve) => {\n child.once(\"close\", () => {\n log?.end();\n resolve();\n });\n });\n\n const pid = child.pid;\n const ownRecords = () =>\n pid === undefined\n ? []\n : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);\n\n const kill = (sig: NodeJS.Signals) => {\n if (pid === undefined) return;\n try {\n process.kill(pid, sig);\n } catch {\n // already gone\n }\n };\n const clearOwnRecords = () => {\n for (const record of ownRecords()) {\n clearRunRecord(projectRoot, record.host, readerEnv);\n }\n };\n\n let stopping: Promise<HostExit> | undefined;\n const stop = (): Promise<HostExit> => {\n stopping ??= (async () => {\n if (!exit) {\n kill(\"SIGTERM\");\n let timer: NodeJS.Timeout | undefined;\n const timedOut = await Promise.race([\n exited.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), stopTimeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (timedOut) {\n forced = true;\n kill(\"SIGKILL\");\n }\n }\n const result = await exited;\n // A killed child skips its exit handler's record clear.\n clearOwnRecords();\n return result;\n })();\n return stopping;\n };\n\n function onAbort() {\n void stop();\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const deadline = Date.now() + readyTimeoutMs;\n for (;;) {\n const aborted = signal?.aborted ?? false;\n // Before the record: a child killed after writing it leaves it behind.\n if (exit && !aborted) {\n clearOwnRecords();\n let timer: NodeJS.Timeout | undefined;\n await Promise.race([\n closed,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CLOSE_WAIT_MS);\n }),\n ]);\n clearTimeout(timer);\n const how =\n exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;\n throw new SpawnHostError(\n `spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`,\n \"exited\",\n tail,\n exit,\n );\n }\n const record = aborted ? undefined : ownRecords().at(0);\n if (record) {\n return {\n pid: record.pid,\n dataDir,\n record,\n outputs: record.outputs,\n members: record.members,\n exited,\n stop,\n };\n }\n if (aborted || Date.now() >= deadline) {\n const phase: SpawnHostPhase = aborted ? \"aborted\" : \"timeout\";\n const stopped = await stop();\n throw new SpawnHostError(\n phase === \"aborted\"\n ? `spawnHost: aborted before ph run ${options.host} was ready.`\n : `spawnHost: ph run ${options.host} wrote no run record within ${readyTimeoutMs} ms.`,\n phase,\n tail,\n stopped,\n );\n }\n await Promise.race([sleep(POLL_MS), exited]);\n }\n}\n","import {\n DEFAULT_CONNECT_STUDIO_PORT,\n DEFAULT_SWITCHBOARD_PORT,\n} from \"@powerhousedao/shared/clis/constants\";\nimport {\n compoundStartVerb,\n memberVerbOf,\n prepareMember,\n takesCspRegistrySync,\n type PreparedMember,\n} from \"./compound.js\";\nimport { isBuiltinEnvName, substituteBuiltinEnv } from \"./env-substitution.js\";\nimport { loadHost } from \"./host-loader.js\";\nimport type { CheckStage, HostIssue } from \"./host-issues.js\";\nimport type { ChildWrapper, CompoundWiring } from \"./host-schemas.js\";\nimport {\n checkOutputPaths,\n checkTokenSites,\n envSitesOf,\n outputRefsOf,\n outputSitesOf,\n type OutputRef,\n type OutputsSchemaLookup,\n} from \"./resolve/declared.js\";\nimport {\n loadProducers,\n processResolveEnv,\n producerOutputsSchemas,\n runnerOutputsSchema,\n} from \"./resolve/node.js\";\nimport { memberForRef, planCompound } from \"./resolve/plan.js\";\nimport { findRemovedForms } from \"./resolve/removed-forms.js\";\nimport {\n resolveHostOutputs,\n TokenResolutionError,\n unsetEnvMessage,\n type DeferredToken,\n type OutputSource,\n type SelfMembers,\n} from \"./resolve/resolve.js\";\nimport { isPlainObject } from \"./resolve/walk.js\";\nimport {\n CONNECT_RUNNER,\n getVerb,\n hostSchemaIssues,\n kindShapeIssues,\n ONE_SHOT_VERBS,\n resolveRunnerModule,\n type HostSchemaLike,\n type RunnerIssue,\n type RunnerModule,\n} from \"./runner-resolver.js\";\n\nexport interface CheckHostOptions {\n projectRoot: string;\n /** The environment `ph run` would resolve against; `process.env` is never read. */\n env: Readonly<Record<string, string | undefined>>;\n /** Default `run`, as `ph run <name>`. */\n verb?: string;\n /** Producers' outputs. Absent: `$output` tokens are checked declared-only. */\n outputs?: OutputSource;\n}\n\nexport interface CheckDeferred extends DeferredToken {\n file: string;\n}\n\nexport interface CheckHostResult {\n issues: HostIssue[];\n /** What `ph run` survives but the user should know; never fails a check. */\n warnings: HostIssue[];\n /** `$output` tokens left unresolved because no `outputs` were given. */\n deferred: CheckDeferred[];\n}\n\n/** The `ph run` pipeline up to the verb, collecting every issue; starts nothing. */\nexport async function checkHost(\n name: string,\n options: CheckHostOptions,\n): Promise<CheckHostResult> {\n const result: CheckHostResult = { issues: [], warnings: [], deferred: [] };\n const file = `hosts/${name}/host.js`;\n const issue = issuer(result, file);\n const verb = options.verb ?? \"run\";\n let host: Record<string, unknown> & { runner: { module: string } };\n let runner: RunnerModule;\n try {\n host = (await loadHost(options.projectRoot, name)).host;\n runner = await resolveRunnerModule(options.projectRoot, host.runner.module);\n } catch (error) {\n issue(\"load\", \"\", error);\n return result;\n }\n const specifier = host.runner.module;\n\n if (runner.kind === \"compound\") {\n await checkCompound(result, options, {\n file,\n host,\n runner,\n specifier,\n verb,\n });\n return result;\n }\n\n const refs = outputRefsOf(host);\n const producers = await loadProducers(options.projectRoot, refs);\n await checkSubject(result, options, {\n file,\n host,\n runner,\n specifier,\n verb,\n outputsSchemaOf: producerOutputsSchemas(producers),\n self: \"outputs\",\n });\n return result;\n}\n\ninterface Subject {\n file: string;\n host: Record<string, unknown>;\n runner: RunnerModule;\n specifier: string;\n verb: string;\n}\n\ninterface ReactorSubject extends Subject {\n outputsSchemaOf: (ref: OutputRef) => OutputsSchemaLookup;\n /** Whose `$output` tokens stay in place when no outputs are given. */\n self: SelfMembers | \"outputs\";\n /** A compound member's wiring, applied before resolved validation. */\n patch?: (host: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Declared validation; returns whether its tokens and its shape passed. */\nfunction checkDeclared(\n result: CheckHostResult,\n subject: Subject,\n outputsSchemaOf?: (ref: OutputRef) => OutputsSchemaLookup,\n): { tokens: boolean; shape: boolean } {\n const issue = issuer(result, subject.file);\n const { host, runner, specifier } = subject;\n try {\n getVerb(runner, specifier, subject.verb);\n } catch (error) {\n issue(\"declared\", \"\", error);\n }\n const tokenIssues = [\n ...findRemovedForms(host),\n ...checkTokenSites(host),\n ...(outputsSchemaOf ? checkOutputPaths(host, outputsSchemaOf) : []),\n ];\n for (const i of tokenIssues) issue(\"declared\", i);\n const shapeIssues = runner.declaredHostSchema\n ? schemaIssuesOf(runner, runner.declaredHostSchema, specifier, host, true)\n : kindShapeIssues(runner.kind, specifier, host);\n for (const i of shapeIssues) issue(\"declared\", i);\n return { tokens: tokenIssues.length === 0, shape: shapeIssues.length === 0 };\n}\n\nfunction schemaIssuesOf(\n runner: RunnerModule,\n schema: HostSchemaLike,\n specifier: string,\n host: unknown,\n allowTokens: boolean,\n): RunnerIssue[] {\n const checked = hostSchemaIssues(runner, schema, specifier, host, {\n tokens: allowTokens ? \"allow\" : \"forbid\",\n });\n return [...checked.issues, ...(checked.schemaIssues ?? [])];\n}\n\nasync function checkSubject(\n result: CheckHostResult,\n options: CheckHostOptions,\n subject: ReactorSubject,\n): Promise<void> {\n const issue = issuer(result, subject.file);\n const { runner, specifier, file } = subject;\n const declared = checkDeclared(result, subject, subject.outputsSchemaOf);\n const resolveEnv = processResolveEnv(options.projectRoot, options.env);\n const patch = subject.patch ?? ((host) => host);\n\n // A one-shot verb (build) resolves nothing; its verb gets the declared host.\n if (ONE_SHOT_VERBS.has(subject.verb)) {\n if (!declared.tokens || !declared.shape) return;\n const host = patch(\n substituteBuiltinEnv(subject.host, resolveEnv.builtins ?? {}),\n );\n const schema = runner.declaredHostSchema ?? runner.hostSchema;\n for (const i of schemaIssuesOf(runner, schema, specifier, host, true)) {\n issue(\"resolved\", i);\n }\n return;\n }\n\n const unset = envSitesOf(subject.host).filter(\n (site) =>\n !site.optional &&\n !isBuiltinEnvName(site.name) &&\n options.env[site.name] === undefined,\n );\n for (const site of unset) {\n issue(\"resolve\", { path: site.path, message: unsetEnvMessage(site.name) });\n }\n if (!declared.tokens || unset.length > 0) return;\n\n let resolved: Record<string, unknown>;\n let deferred: DeferredToken[] = [];\n try {\n if (options.outputs) {\n resolved = resolveHostOutputs(subject.host, {\n outputs: options.outputs,\n ...resolveEnv,\n });\n } else {\n const partial = resolveHostOutputs(subject.host, resolveEnv, {\n deferSelf: subject.self,\n });\n resolved = partial.host;\n deferred = partial.deferred;\n }\n } catch (error) {\n if (error instanceof TokenResolutionError && error.detail) {\n issue(\"resolve\", {\n path: error.detail.path,\n message: error.detail.reason,\n });\n } else {\n issue(\"resolve\", \"\", error);\n }\n return;\n }\n result.deferred.push(...deferred.map((d) => ({ ...d, file })));\n if (!declared.shape) return;\n\n const allow = deferred.length > 0;\n const schema = allow\n ? (runner.declaredHostSchema ?? runner.hostSchema)\n : runner.hostSchema;\n const checked = hostSchemaIssues(runner, schema, specifier, patch(resolved), {\n tokens: allow ? \"allow\" : \"forbid\",\n });\n const resolvedIssues = [...checked.issues, ...(checked.schemaIssues ?? [])];\n for (const i of resolvedIssues) issue(\"resolved\", i);\n if (resolvedIssues.length > 0 || !runner.checkBoot) return;\n\n try {\n const boot = await runner.checkBoot(checked.data, {\n projectRoot: options.projectRoot,\n verb: subject.verb,\n env: options.env,\n file,\n });\n for (const i of boot) issue(\"boot\", { ...i, path: i.path ?? \"\" });\n } catch (error) {\n issue(\"boot\", \"\", error);\n }\n}\n\nasync function checkCompound(\n result: CheckHostResult,\n options: CheckHostOptions,\n subject: Subject,\n): Promise<void> {\n const issue = issuer(result, subject.file);\n const { host, runner, specifier } = subject;\n const declared = checkDeclared(result, subject);\n if (!declared.tokens || !declared.shape) return;\n // Without a declared schema, checkDeclared checked the kind shape only.\n if (!runner.declaredHostSchema) {\n const own = schemaIssuesOf(\n runner,\n runner.hostSchema,\n specifier,\n host,\n true,\n );\n for (const i of own) issue(\"resolved\", i);\n if (own.length > 0) return;\n }\n\n const children = (\n isPlainObject(host.children) ? host.children : {}\n ) as Record<string, ChildWrapper>;\n const wiring = (\n isPlainObject(host.config) ? host.config : {}\n ) as CompoundWiring;\n // The generic compound's mapping; a runner with its own (desktop's\n // `serve`) is checked as if it were generic.\n const verb = compoundStartVerb(\n subject.verb,\n host.runner as { defaultVerb?: string },\n );\n\n const prepared: PreparedMember[] = [];\n for (const [key, member] of Object.entries(children)) {\n try {\n prepared.push(await prepareMember(options.projectRoot, key, member));\n } catch (error) {\n issuer(result, `hosts/${member.host}/host.js`)(\"load\", \"\", error);\n }\n }\n const members = Object.entries(children).map(([key, m]) => ({\n key,\n host: m.host,\n }));\n if (prepared.length === members.length) {\n try {\n planCompound(\n prepared.map((m) => ({\n key: m.key,\n host: m.member.host,\n refs: outputSitesOf(m.draft).map(({ ref, path }) => ({\n ref,\n path,\n })),\n })),\n wiring.startOrder,\n );\n } catch (error) {\n issue(\"declared\", \"\", error);\n }\n }\n\n result.warnings.push(...sharedPortWarnings(subject.file, prepared));\n\n const byKey = new Map(prepared.map((m) => [m.key, m]));\n const outputsSchemaOf = (ref: OutputRef): OutputsSchemaLookup => {\n const target = memberForRef(ref, members);\n if (\"error\" in target) return { error: target.error };\n const producer = byKey.get(target.key);\n return producer\n ? runnerOutputsSchema(\n producer.runner,\n producer.specifier,\n `member \"${target.key}\"`,\n )\n : { error: `names member \"${target.key}\", which was not prepared.` };\n };\n for (const m of prepared) {\n const csp = wiring.cspRegistrySync === true && takesCspRegistrySync(m);\n await checkSubject(result, options, {\n file: m.file,\n host: m.draft,\n runner: m.runner,\n specifier: m.specifier,\n verb: memberVerbOf(verb, m.draft.runner),\n outputsSchemaOf,\n self: { members },\n ...(csp\n ? {\n patch: (resolved) => ({\n ...resolved,\n runner: { ...(resolved.runner as object), cspRegistrySync: true },\n }),\n }\n : {}),\n });\n }\n}\n\nconst SWITCHBOARD_RUNNER = \"@powerhousedao/ph-cli/runners/switchboard\";\n\n/** The port a member binds: its own literal, else its ph-cli runner's default. */\nfunction boundPortOf(m: PreparedMember): number | undefined {\n const port = (m.draft.runner as { port?: unknown }).port;\n if (port === undefined) {\n if (m.specifier === CONNECT_RUNNER) return DEFAULT_CONNECT_STUDIO_PORT;\n if (m.specifier === SWITCHBOARD_RUNNER) return DEFAULT_SWITCHBOARD_PORT;\n return undefined;\n }\n return typeof port === \"number\" && Number.isInteger(port) && port > 0\n ? port\n : undefined;\n}\n\n/** Members binding one port: under `ph run` the later one moves or fails. */\nfunction sharedPortWarnings(\n file: string,\n prepared: readonly PreparedMember[],\n): HostIssue[] {\n const owners = new Map<number, PreparedMember>();\n const warnings: HostIssue[] = [];\n for (const m of prepared) {\n const port = boundPortOf(m);\n if (port === undefined) continue;\n const other = owners.get(port);\n if (!other) {\n owners.set(port, m);\n continue;\n }\n const connects =\n m.specifier === CONNECT_RUNNER && other.specifier === CONNECT_RUNNER;\n warnings.push({\n stage: \"declared\",\n file,\n path: `children.${m.key}.runner.port`,\n message: connects\n ? `${other.key} and ${m.key} both use port ${port}. One will move to the next free port and lose its browser data.`\n : `${other.key} and ${m.key} both use port ${port}. One will move to the next free port or fail to start.`,\n });\n }\n return warnings;\n}\n\nfunction issuer(result: CheckHostResult, file: string) {\n return (\n stage: CheckStage,\n found: RunnerIssue | string,\n error?: unknown,\n ): void => {\n if (typeof found !== \"string\") {\n const { path, message, hint } = found;\n result.issues.push({\n stage,\n file,\n path,\n message,\n ...(hint ? { hint } : {}),\n });\n return;\n }\n const text = error instanceof Error ? error.message : String(error);\n const [message, hint] = text.split(\"\\n Hint: \");\n result.issues.push({\n stage,\n file,\n path: found,\n message,\n ...(hint ? { hint } : {}),\n });\n };\n}\n","import { z } from \"zod\";\nimport { declaredHostSchemas, type HostDefinition } from \"./host-schemas.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction childFolders(host: unknown): [key: string, folder: string][] {\n if (!isRecord(host) || !isRecord(host.children)) return [];\n return Object.entries(host.children).flatMap(([key, child]) =>\n isRecord(child) && typeof child.host === \"string\"\n ? [[key, child.host] as [string, string]]\n : [],\n );\n}\n\n// Picked by structure, as the loader does, so issues name the field.\nconst declaredHostSchema = z\n .custom<HostDefinition>()\n .superRefine((host, ctx) => {\n const schema =\n isRecord(host) && \"children\" in host\n ? declaredHostSchemas.compoundHostSchema\n : declaredHostSchemas.reactorHostSchema;\n const result = schema.safeParse(host);\n if (result.success) return;\n for (const issue of result.error.issues) {\n ctx.addIssue({\n code: \"custom\",\n message: issue.message,\n path: issue.path,\n });\n }\n });\n\n/** `ph host export`: a declared host plus its members, keyed by folder. */\nexport const hostExportSchema = z\n .strictObject({\n format: z.literal(\"ph-host-export\"),\n version: z.literal(1),\n project: z.strictObject({\n name: z.string().min(1),\n root: z.string().min(1),\n }),\n name: z.string().min(1),\n host: declaredHostSchema,\n members: z.record(z.string(), declaredHostSchema),\n })\n .superRefine((value, ctx) => {\n const reached = new Set<string>();\n const pending: [at: string[], host: unknown][] = [[[\"host\"], value.host]];\n for (let next = pending.shift(); next; next = pending.shift()) {\n const [at, host] = next;\n for (const [key, folder] of childFolders(host)) {\n if (!(folder in value.members)) {\n ctx.addIssue({\n code: \"custom\",\n path: [...at, \"children\", key, \"host\"],\n message: `Member folder \"${folder}\" is missing from members.`,\n });\n continue;\n }\n if (reached.has(folder)) continue;\n reached.add(folder);\n pending.push([[\"members\", folder], value.members[folder]]);\n }\n }\n for (const folder of Object.keys(value.members)) {\n if (reached.has(folder)) continue;\n ctx.addIssue({\n code: \"custom\",\n path: [\"members\", folder],\n message: `Member \"${folder}\" is not reached from the host's children.`,\n });\n }\n });\n\nexport type HostExport = z.input<typeof hostExportSchema>;\n","import path from \"node:path\";\nimport { z } from \"zod\";\nimport { hostExportSchema, type HostExport } from \"./host-export-schema.js\";\nimport { declaredHostSchemas, type HostDefinition } from \"./host-schemas.js\";\nimport { HostLoadError, loadHost } from \"./host-loader.js\";\nimport { readProjectName } from \"./run-record.js\";\n\nfunction checkHint(name: string): string {\n return `Run \\`ph host check ${name}\\`.`;\n}\n\nfunction childFolders(host: HostDefinition, name: string): string[] {\n if (!(\"children\" in host)) return [];\n const parsed = declaredHostSchemas.childrenSchema.safeParse(host.children);\n if (!parsed.success) {\n throw new HostLoadError(\n `hosts/${name}/host.js: invalid \\`children\\`:\\n${z.prettifyError(parsed.error)}`,\n checkHint(name),\n );\n }\n return Object.values(parsed.data).map((child) => child.host);\n}\n\n/** A host as declared and every member it reaches, raw `loadHost` bodies. */\nexport async function exportHost(\n projectRoot: string,\n name: string,\n): Promise<HostExport> {\n const root = path.resolve(projectRoot);\n const { host } = await loadHost(root, name);\n const members: Record<string, HostDefinition> = {};\n const visit = async (folders: string[]): Promise<void> => {\n for (const folder of folders) {\n if (folder in members) continue;\n const member = (await loadHost(root, folder)).host;\n members[folder] = member;\n await visit(childFolders(member, folder));\n }\n };\n await visit(childFolders(host, name));\n const envelope: HostExport = {\n format: \"ph-host-export\",\n version: 1,\n project: { name: readProjectName(root), root },\n name,\n host,\n members,\n };\n // What a consumer parses: `undefined` keys drop in the JSON round trip.\n const parsed = hostExportSchema.safeParse(\n JSON.parse(JSON.stringify(envelope)),\n );\n if (!parsed.success) {\n throw new HostLoadError(\n `hosts/${name}/host.js: the export is not a valid host export:\\n${z.prettifyError(parsed.error)}`,\n checkHint(name),\n );\n }\n return envelope;\n}\n","import crypto from \"node:crypto\";\nimport {\n DRIVE_ICON_MAX_BYTES,\n resolveImageRef,\n} from \"@powerhousedao/shared/connect/image-ref\";\nimport { projectDriveIdWith, type DriveDeclaration } from \"./drive-schema.js\";\n\n/**\n * R1 — core drive declarations. A reactor without drives is not a running\n * reactor, so declaring + seeding them is HOST RUNTIME work (not a plugin):\n * onReactorReady → idempotent slug-keyed seeding → onDrivesReady. Plugins\n * CONTRIBUTE declarations into the same merged list (Contributions.drives);\n * `--explain drives` prints the merged set with provenance.\n *\n * The declaration schema lives in drive-schema.ts (platform-neutral); this\n * module is the node half: resolution (image refs read files), seeding and\n * the node:crypto-bound project drive id.\n */\n\nexport {\n driveDeclarationSchema,\n drivesSchema,\n type DriveDeclaration,\n} from \"./drive-schema.js\";\n\nconst sha256Hex = (input: string): string =>\n crypto.createHash(\"sha256\").update(input).digest(\"hex\");\n\nexport function projectDriveId(projectRoot: string, slug: string): string {\n return projectDriveIdWith(sha256Hex, projectRoot, slug);\n}\n\nexport interface ResolvedDrive {\n kind: \"local\" | \"remote\";\n id: string;\n slug: string;\n name: string;\n icon?: string;\n preferredEditor?: string;\n sharingType: \"public\" | \"private\" | \"shared\";\n availableOffline: boolean;\n remoteUrl?: string;\n}\n\nexport function resolveDriveDeclaration(\n projectRoot: string,\n decl: DriveDeclaration,\n): ResolvedDrive {\n const id = decl.projectHash\n ? projectDriveId(projectRoot, decl.slug)\n : (decl.id ?? decl.slug);\n // Hash-derived drives serve under the hashed slug too (classic parity:\n // the vetra drive's slug IS its hashed id) — unless only the id is hashed.\n const slug = decl.projectHash === true ? id : decl.slug;\n if (decl.remote) {\n return {\n kind: \"remote\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n remoteUrl: decl.remote.url,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n }\n return {\n kind: \"local\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n // A project path becomes a data URI here (the icon lives in synced drive\n // state, so it is size-capped); URLs and data URIs pass through.\n icon: resolveImageRef(projectRoot, decl.icon, {\n maxBytes: DRIVE_ICON_MAX_BYTES,\n warn: (m) => console.warn(m),\n }),\n preferredEditor: decl.preferredEditor,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n}\n\n/* ------------------------------------------------------------------ seeding */\n\n/** The minimal client surface the seeder needs — runners adapt their reactor\n * clients (IReactorClient, addDefaultDrive-style helpers) onto it. */\nexport interface DriveSeederClient {\n /** Return the existing drive's id for a slug, or undefined. */\n findDriveBySlug(slug: string): Promise<string | undefined>;\n /** Create a local drive; preferredEditor lands on header.meta. */\n createDrive(drive: ResolvedDrive): Promise<void>;\n /** Attach a remote drive by URL (idempotent on the client side). */\n attachRemoteDrive(url: string): Promise<void>;\n}\n\nexport interface SeedResult {\n created: string[];\n existing: string[];\n attached: string[];\n}\n\n/** Idempotent, slug-keyed: an existing slug is left untouched (never\n * recreated, never mutated — preserveStrategy refinements live here later). */\nexport async function seedDrives(\n client: DriveSeederClient,\n drives: readonly ResolvedDrive[],\n): Promise<SeedResult> {\n const result: SeedResult = { created: [], existing: [], attached: [] };\n for (const drive of drives) {\n if (drive.kind === \"remote\") {\n await client.attachRemoteDrive(drive.remoteUrl!);\n result.attached.push(drive.slug);\n continue;\n }\n const existing = await client.findDriveBySlug(drive.slug);\n if (existing !== undefined) {\n result.existing.push(drive.slug);\n continue;\n }\n await client.createDrive(drive);\n result.created.push(drive.slug);\n }\n return result;\n}\n\n/* ------------------------------------------------------------------ explain */\n\nexport interface DrivePlanEntry {\n drive: ResolvedDrive;\n /** \"host\" for host.js declarations; a plugin name for contributions. */\n source: string;\n}\n\n/** Merge host-declared drives with plugin contributions, slug-keyed — the\n * host file wins on conflicts (it is the most explicit source). */\nexport function mergeDrivePlan(\n projectRoot: string,\n hostDeclared: readonly DriveDeclaration[],\n contributed: readonly { declaration: DriveDeclaration; source: string }[],\n): DrivePlanEntry[] {\n const plan = new Map<string, DrivePlanEntry>();\n for (const { declaration, source } of contributed) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source });\n }\n for (const declaration of hostDeclared) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source: \"host\" });\n }\n return [...plan.values()];\n}\n\nexport function explainDrivePlan(plan: readonly DrivePlanEntry[]): string {\n if (plan.length === 0) return \"(no drives declared)\";\n const lines = plan.map(({ drive, source }) => {\n const kind =\n drive.kind === \"remote\" ? `remote ${drive.remoteUrl}` : \"local\";\n const editor = drive.preferredEditor\n ? ` editor=${drive.preferredEditor}`\n : \"\";\n return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;\n });\n return [\"drives:\", ...lines].join(\"\\n\");\n}\n","import type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\n/**\n * Phase 4 (track R): project named host backends onto reactor-monitor's\n * `ReactorDescriptor` shape — the input `provision()` takes. Pure and\n * dependency-free; a type-assignability test pins the output to the real\n * `ReactorDescriptor` so an upstream field rename fails this package's tests\n * instead of silently drifting (D2.b: aligned locally, upstreaming not\n * blocked on).\n */\n\n/** The browser-provisionable storage union — reactor-monitor's\n * `ReactorStorageConfig` shape. `postgres` is the SERVER extension (D2.b): a\n * switchboard backend's storage, never a provisioned browser reactor's. */\nexport type ProjectedStorage =\n | { kind: \"idb\" }\n | { kind: \"memory\" }\n | { kind: \"path\"; dataDir: string };\n\nexport interface ProjectedDescriptor {\n kind: \"in-process\" | \"worker\" | \"remote\";\n name: string;\n storage?: ProjectedStorage;\n packages?: { cdnUrl?: string; specs?: string[]; dynamic?: boolean };\n featureFlags?: {\n documentDecisions?: boolean;\n authEnforcement?: boolean;\n authGroups?: boolean;\n authConditions?: boolean;\n };\n remote?: { url: string };\n}\n\nfunction projectStorage(\n name: string,\n storage: NonNullable<ReactorBackend[\"storage\"]>,\n): ProjectedStorage {\n switch (storage.kind) {\n case \"idb\":\n return { kind: \"idb\" };\n case \"memory\":\n return { kind: \"memory\" };\n case \"path\": {\n if (!storage.dataDir) {\n throw new Error(\n `Backend \"${name}\": storage kind \"path\" requires dataDir.`,\n );\n }\n return { kind: \"path\", dataDir: storage.dataDir };\n }\n case \"postgres\":\n throw new Error(\n `Backend \"${name}\": storage kind \"postgres\" is server-side only — ` +\n `a provisioned (in-process/worker) reactor cannot use it. Point a ` +\n `\"remote\" backend at the switchboard that owns that database instead.`,\n );\n }\n}\n\n/** One backend → one descriptor. The protocol's featureFlags ride every\n * descriptor (they are fleet consensus, not per-backend). A remote backend\n * must carry remote.url — provision() requires it. */\nexport function backendToDescriptor(\n name: string,\n backend: ReactorBackend,\n protocol?: ReactorProtocol,\n): ProjectedDescriptor {\n const descriptor: ProjectedDescriptor = {\n kind: backend.kind,\n name,\n };\n if (descriptor.kind === \"remote\") {\n const url = backend.remote?.url;\n if (!url) {\n throw new Error(\n `Backend \"${name}\" is kind \"remote\" but has no remote.url — ` +\n `a remote descriptor attaches to an already-running reactor by URL.`,\n );\n }\n descriptor.remote = { url };\n // remote attaches; it builds nothing, so local-build fields do not apply\n return descriptor;\n }\n if (backend.storage) {\n descriptor.storage = projectStorage(name, backend.storage);\n }\n if (backend.packages) descriptor.packages = backend.packages;\n if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n return descriptor;\n}\n\n/** All named backends, in placement-primary-first order (the order a\n * createReactorClients step would provision them). */\nexport function backendsToDescriptors(\n reactor: ReactorConfig | undefined,\n): ProjectedDescriptor[] {\n const backends = reactor?.backends;\n if (!backends) return [];\n const names = Object.keys(backends);\n const primary = reactor.placement?.primary;\n const ordered =\n primary && names.includes(primary)\n ? [primary, ...names.filter((n) => n !== primary)]\n : names;\n return ordered.map((name) =>\n backendToDescriptor(name, backends[name], reactor.protocol),\n );\n}\n\nconst LOCAL_KINDS = new Set<ReactorBackendKind>([\"in-process\", \"worker\"]);\n\n/**\n * Structural multi-reactor (phase 4): true when the block names BOTH a local\n * backend (in-process/worker — the tab's own reactor) and a remote one. This\n * is the shape Connect's routing client serves; a lone remote backend is an\n * attach-only host (assistant/agent shape), not a routed tab.\n */\nexport function isStructuralMultiReactor(\n reactor: ReactorConfig | undefined,\n): boolean {\n const backends = reactor?.backends;\n if (!backends) return false;\n const kinds = Object.values(backends).map((b) => b.kind);\n return (\n kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\")\n );\n}\n\n/** The remote backends' drive addresses, placement order. */\nexport function remoteBackendUrls(\n reactor: ReactorConfig | undefined,\n): string[] {\n return backendsToDescriptors(reactor)\n .filter((d) => d.kind === \"remote\")\n .map((d) => d.remote?.url)\n .filter((u): u is string => typeof u === \"string\");\n}\n\n/** A switchboard as Connect's served config names it, with its connection settings. */\nexport type ServedRemoteBackend = { name: string; url: string } & Omit<\n NonNullable<ReactorBackend[\"remote\"]>,\n \"url\"\n>;\n\n/**\n * The remote backends by host key, placement order, each with the\n * connection settings it sets. A url that is not a string yet (an output\n * token, unresolved when a host builds) is skipped, as in remoteBackendUrls.\n */\nexport function remoteBackends(\n reactor: ReactorConfig | undefined,\n): ServedRemoteBackend[] {\n return backendsToDescriptors(reactor).flatMap((d) => {\n const remote = reactor?.backends?.[d.name]?.remote;\n if (d.kind !== \"remote\" || typeof d.remote?.url !== \"string\" || !remote) {\n return [];\n }\n const { requestTimeoutMs, breaker, realtime } = remote;\n return [\n {\n name: d.name,\n url: d.remote.url,\n ...(requestTimeoutMs !== undefined ? { requestTimeoutMs } : {}),\n ...(breaker !== undefined ? { breaker } : {}),\n ...(realtime !== undefined ? { realtime } : {}),\n },\n ];\n });\n}\n","/**\n * The shared `reactor` host-config block and its projections onto the\n * Switchboard config / Connect runtime config. Phase 2 of uniform-runners: makes\n * the reactor block live through the bridge runners, BEFORE track R replaces\n * the projection with reactor-monitor's provision(). The headline is\n * single-sourced `reactor.protocol` — both projections read the same block, so\n * client and server cannot diverge, and a contradicting pre-set env fails boot.\n */\n\nimport {\n remoteBackends,\n type ServedRemoteBackend,\n} from \"./backend-projection.js\";\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\nexport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorPackageConfig,\n ReactorProtocol,\n ReactorRemoteConfig,\n ReactorStorageConfig,\n} from \"./host-schemas.js\";\n\n/** A switchboard host's own store. Prefers placement.primary, else\n * \"main\"/\"local\", else the first. Connect refuses placement.primary: its\n * reactor is {@link browserBackend}. */\nexport function primaryBackend(\n reactor: ReactorConfig | undefined,\n): ReactorBackend | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const names = Object.keys(backends);\n if (names.length === 0) return undefined;\n const pick =\n reactor.placement?.primary ??\n (names.includes(\"main\")\n ? \"main\"\n : names.includes(\"local\")\n ? \"local\"\n : names[0]);\n return backends[pick];\n}\n\nconst FLAG_ENV: Record<\n keyof NonNullable<ReactorProtocol[\"featureFlags\"]>,\n string\n> = {\n documentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n authEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n authGroups: \"REACTOR_AUTH_GROUPS\",\n authConditions: \"REACTOR_AUTH_CONDITIONS\",\n};\n\n/** The env vars a protocol block maps onto, with their string values. Only\n * keys the block actually sets appear. */\nexport function protocolEnv(\n protocol: ReactorProtocol | undefined,\n): Record<string, string> {\n const env: Record<string, string> = {};\n if (!protocol) return env;\n for (const [key, varName] of Object.entries(FLAG_ENV)) {\n const value = protocol.featureFlags?.[key as keyof typeof FLAG_ENV];\n if (value !== undefined) env[varName] = value ? \"true\" : \"false\";\n }\n if (protocol.createSignaturePolicy !== undefined) {\n env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n }\n if (protocol.unsupportedStoredDocuments !== undefined) {\n env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS =\n protocol.unsupportedStoredDocuments;\n }\n return env;\n}\n\n/** The switchboard config layer a reactor block maps to (the shape of\n * `@powerhousedao/switchboard/config`'s input). Only keys the block sets. */\nexport interface SwitchboardReactorLayer {\n storage?: { reactor?: { url: string }; readModel?: { url: string } };\n protocol?: ReactorProtocol;\n packages?: { dynamic: true };\n features?: { workflows: boolean };\n}\n\n/** The reactor block as a switchboard config layer. The reactor store and the\n * read model are separate fields: `readModel.url` never moves the reactor. */\nexport function reactorBlockToSwitchboardConfig(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorLayer {\n const layer: SwitchboardReactorLayer = {};\n const backend = primaryBackend(reactor);\n const storage = backend?.storage;\n const reactorUrl =\n storage?.kind === \"postgres\" ? storage.url : storage?.dataDir;\n const readModelUrl = backend?.readModel?.url;\n if (reactorUrl || readModelUrl) {\n layer.storage = {\n ...(reactorUrl ? { reactor: { url: reactorUrl } } : {}),\n ...(readModelUrl ? { readModel: { url: readModelUrl } } : {}),\n };\n }\n if (reactor?.protocol) layer.protocol = reactor.protocol;\n if (backend?.packages?.dynamic) layer.packages = { dynamic: true };\n if (reactor?.workflows !== undefined) {\n layer.features = { workflows: reactor.workflows };\n }\n return layer;\n}\n\n/** The four reactor-client shapes a Connect host can select (mirrors the\n * shared PHReactorClientMode; kept local to avoid an import cycle). */\nexport type ReactorClientMode = \"in-process\" | \"worker\" | \"remote\" | \"router\";\n\nconst LOCAL_BACKEND_KINDS = new Set<ReactorBackendKind>([\n \"in-process\",\n \"worker\",\n]);\n\n/** Connect's browser reactor: its first in-process or worker backend. */\nexport function browserBackend(\n reactor: ReactorConfig | undefined,\n): (ReactorBackend & { name: string }) | undefined {\n const entry = Object.entries(reactor?.backends ?? {}).find(([, backend]) =>\n LOCAL_BACKEND_KINDS.has(backend.kind),\n );\n return entry ? { ...entry[1], name: entry[0] } : undefined;\n}\n\n/**\n * Which reactor client the backend topology asks for:\n * - local (in-process/worker) AND remote backends -> `router`\n * - remote backend(s) only -> `remote`\n * - a worker backend -> `worker`\n * - anything else local -> `in-process`\n * `undefined` when no backends are declared — the caller then keeps the\n * legacy reactorWorker/multiReactor behaviour untouched.\n */\nexport function reactorClientMode(\n reactor: ReactorConfig | undefined,\n): ReactorClientMode | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const kinds = Object.values(backends).map((b) => b.kind);\n if (kinds.length === 0) return undefined;\n const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));\n const hasRemote = kinds.some((k) => k === \"remote\");\n if (hasLocal && hasRemote) return \"router\";\n if (hasRemote) return \"remote\";\n return browserBackend(reactor)?.kind === \"worker\" ? \"worker\" : \"in-process\";\n}\n\n/** The router settings Connect serves: only the keys the host sets. */\nexport interface ConnectRouterSettings {\n /** A remote backend's host key; absent, the browser reactor (or the only switchboard). */\n newDrives?: string;\n probeTimeoutMs?: number;\n provisionalRouteMs?: number;\n}\n\n/** Served only when `newDrives` names a served remote backend: a local one\n * is the default, and Connect refuses one it has no address for. */\nfunction connectRouterSettings(\n reactor: ReactorConfig | undefined,\n served: readonly ServedRemoteBackend[],\n): ConnectRouterSettings | undefined {\n const newDrives = reactor?.placement?.newDrives;\n const { probeTimeoutMs, provisionalRouteMs } = reactor?.router ?? {};\n const router: ConnectRouterSettings = {\n ...(newDrives !== undefined &&\n served.some((remote) => remote.name === newDrives)\n ? { newDrives }\n : {}),\n ...(probeTimeoutMs !== undefined ? { probeTimeoutMs } : {}),\n ...(provisionalRouteMs !== undefined ? { provisionalRouteMs } : {}),\n };\n return Object.keys(router).length > 0 ? router : undefined;\n}\n\nexport interface ConnectReactorProjection {\n /** Patch merged into the connect runtime config (connect.*). */\n connect: {\n reactor?: ReactorProtocol;\n instance?: {\n reactorWorker?: boolean;\n reactorClient?: ReactorClientMode;\n remoteBackends?: ServedRemoteBackend[];\n router?: ConnectRouterSettings;\n };\n app?: { workflowsEnabled?: boolean };\n };\n}\n\n/** Project the reactor block onto the Connect runtime config: protocol →\n * connect.reactor (same shape), backend topology → instance.reactorWorker\n * (the browser reactor's kind), instance.reactorClient, and with a\n * switchboard instance.remoteBackends and instance.router, workflows →\n * app.workflowsEnabled. */\nexport function projectReactorToConnect(\n reactor: ReactorConfig | undefined,\n): ConnectReactorProjection {\n const connect: ConnectReactorProjection[\"connect\"] = {};\n if (reactor?.protocol) connect.reactor = reactor.protocol;\n const mode = reactorClientMode(reactor);\n if (mode !== undefined) {\n const routed = mode === \"router\" || mode === \"remote\";\n const served = routed ? remoteBackends(reactor) : [];\n const router = routed ? connectRouterSettings(reactor, served) : undefined;\n connect.instance = {\n reactorWorker: browserBackend(reactor)?.kind === \"worker\",\n reactorClient: mode,\n ...(routed ? { remoteBackends: served } : {}),\n ...(router ? { router } : {}),\n };\n }\n if (reactor?.workflows !== undefined) {\n connect.app = { workflowsEnabled: reactor.workflows };\n }\n return { connect };\n}\n\n/** Each pre-set env var that CONTRADICTS the host's protocol block, as a\n * message naming the var, the host value and the env value. An env var that\n * merely matches, or is unset, is fine. */\nexport function protocolConflicts(\n protocol: ReactorProtocol | undefined,\n env: Readonly<Record<string, string | undefined>>,\n hostFile = \"the host file\",\n): string[] {\n if (!protocol) return [];\n return Object.entries(protocolEnv(protocol)).flatMap(\n ([varName, hostValue]) => {\n const envValue = env[varName];\n if (envValue === undefined || envValue === hostValue) return [];\n return [\n `reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment ` +\n `but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — ` +\n `a mismatch would diverge replay. Remove the env override or align the host.`,\n ];\n },\n );\n}\n\n/**\n * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n * the host's protocol block, fail loudly naming the var, the host value, and\n * the env value (phase-2 transition keeps an operator's explicit env as an\n * escape hatch unless it disagrees with the protocol — see the WBS\n * precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n const conflict = protocolConflicts(protocol, env, hostFile).at(0);\n if (conflict) throw new Error(conflict);\n}\n","import type {\n PHConnectCollection,\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n PHConnectRuntimeDefaultDrive,\n} from \"@powerhousedao/shared/clis\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { remoteBackends } from \"./backend-projection.js\";\nimport type { ReactorConfig } from \"./host-schemas.js\";\n\n/**\n * Instance-fact projection for compound hosts: the drives a compound's\n * reactor member created, projected into the Connect member's runtime-config\n * override. Pure functions, moved from ph-cli's vetra service so the generic\n * compound and the classic path share one implementation.\n */\n\nfunction isLocalDrive(\n drive: PHConnectDefaultDrive,\n): drive is Extract<PHConnectDefaultDrive, { local: true }> {\n return \"local\" in drive;\n}\n\n// Identity key for de-duplication: remote entries are keyed by URL; local\n// entries are keyed by `local:<id>` so a local drive id can never collide\n// with a remote URL that happens to be the same string.\nconst driveKey = (drive: PHConnectDefaultDrive): string =>\n isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\n\n/**\n * Concatenate groups of `connect.drives.defaultDrives` in the order given,\n * de-duplicating by drive identity (URL for remote entries, id for local\n * ones). The first occurrence of a drive wins, so earlier groups keep their\n * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first\n * even when the project's `powerhouse.config.json` lists the same drive.\n */\nexport function mergeDefaultDrives(\n ...groups: PHConnectDefaultDrive[][]\n): PHConnectDefaultDrive[] {\n const seen = new Set<string>();\n const out: PHConnectDefaultDrive[] = [];\n for (const group of groups) {\n for (const drive of group) {\n const key = driveKey(drive);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(drive);\n }\n }\n return out;\n}\n\n/**\n * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,\n * swaps the loopback origin for the public base. Browser clients behind a\n * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs\n * (e.g. a remote drive) are already public and pass through unchanged, as do\n * unparseable ones.\n */\nexport function rebaseDriveUrl(driveUrl: string, publicBase: string): string {\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n}\n\nexport interface DriveProjectionInput {\n /** Drive URLs the compound's reactor member created, in display order\n * (e.g. vetra, preview, workflows). Null/undefined entries are skipped. */\n createdDriveUrls: (string | null | undefined)[];\n /** The project's configured `connect.drives.defaultDrives`. */\n configuredDefaultDrives?: PHConnectDefaultDrive[];\n /** `--drives-public-base`: advertise proxy-reachable URLs to the browser. */\n publicBase?: string | null;\n}\n\n/**\n * The compound's drives projection: created drives first (rebased onto the\n * public base when given), then the project's configured drives, de-duplicated\n * — and `preserve-all`, because compound-injected drive lists change per\n * launch context and must never detach drives the user added by hand.\n */\nexport function projectDrivesIntoConnect(\n input: DriveProjectionInput,\n): Pick<PHConnectRuntimeConfig, \"drives\"> {\n const created: PHConnectDefaultDrive[] = input.createdDriveUrls\n .filter((url): url is string => typeof url === \"string\" && url.length > 0)\n .map((url) => ({\n url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n name: null,\n icon: null,\n }));\n return {\n drives: {\n defaultDrives: mergeDefaultDrives(\n created,\n input.configuredDefaultDrives ?? [],\n ),\n preserveStrategy: \"preserve-all\",\n },\n };\n}\n\n/** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */\nfunction servesSlug(declared: string, served: string): boolean {\n return (\n served === declared ||\n (served.startsWith(`${declared}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1)))\n );\n}\n\nexport interface PlacedConnectDrives {\n defaultDrives: PHConnectRuntimeDefaultDrive[];\n collections?: Record<string, PHConnectCollection>;\n}\n\n/** Annotates remote default drives with their backend (`sync: false` when placed on it); other remote placements become collections. */\nexport function placeConnectDrives(\n reactor: ReactorConfig | undefined,\n defaultDrives: readonly PHConnectDefaultDrive[],\n): PlacedConnectDrives {\n const remotes = remoteBackends(reactor).flatMap(({ name, url }) => {\n const at = switchboardOfDrive(url);\n return at ? [{ name, base: at.base }] : [];\n });\n if (remotes.length === 0) return { defaultDrives: [...defaultDrives] };\n const placement = Object.entries(reactor?.placement?.drives ?? {});\n const matched = new Set<string>();\n const placed = defaultDrives.map((drive): PHConnectRuntimeDefaultDrive => {\n if (!(\"url\" in drive)) return drive;\n const at = switchboardOfDrive(drive.url);\n const backend = remotes.find((remote) => remote.base === at?.base)?.name;\n if (!at || !backend) return drive;\n const entry = placement.find(([slug]) => servesSlug(slug, at.slug));\n if (entry) matched.add(entry[0]);\n return entry?.[1] === backend\n ? { ...drive, backend, sync: false }\n : { ...drive, backend };\n });\n const names = new Set(remotes.map((remote) => remote.name));\n const collections = Object.fromEntries(\n placement\n .filter(([slug, backend]) => !matched.has(slug) && names.has(backend))\n .map(([slug, backend]) => [slug, { backend, sync: false }]),\n );\n return Object.keys(collections).length > 0\n ? { defaultDrives: placed, collections }\n : { defaultDrives: placed };\n}\n","import {\n backendToDescriptor,\n isStructuralMultiReactor,\n} from \"./backend-projection.js\";\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorStorageConfig,\n RunnerKind,\n} from \"./host-schemas.js\";\nimport { reactorClientMode, type ReactorClientMode } from \"./reactor-config.js\";\nimport { envSitesOf, outputSitesOf, refKey } from \"./resolve/declared.js\";\nimport type { CompoundPlan } from \"./resolve/plan.js\";\nimport type { OutputPath } from \"./tokens.js\";\n\n/**\n * What a host amounts to once its pipeline has run (typed-host-configs G2,\n * 2.2): the reactor-client shape its backends select, the drives it serves\n * or attaches, the producers whose outputs it consumes and, for a compound,\n * the start order and each member's expectation. Pure and platform-neutral:\n * the caller runs load → declared validation → resolve → resolved\n * validation (and plugin contribution discovery) and hands over the\n * results. The returned value is JSON-only, so it can be pinned in a test\n * table or shipped to another process (a future reactor-monitor).\n */\n\n/** One backend, in placement-primary-first order. */\nexport interface ExpectedBackend {\n name: string;\n kind: ReactorBackendKind;\n storage?: ReactorStorageConfig[\"kind\"];\n /** The RESOLVED storage dir (`\"${userData}\"` sugar and `$env` applied). */\n dataDir?: string;\n /** Why a provisioned reactor (a browser tab, reactor-monitor) cannot be\n * built from this backend (`backendToDescriptor`): e.g. postgres storage\n * is server-side only, a remote backend needs `remote.url`. Absent when\n * it can. A switchboard's own backend may legitimately carry one. */\n provisionError?: string;\n}\n\n/** One drive of the merged plan: plugin contributions first, then the\n * host's own declarations (the host wins a slug). Identity is the DECLARED\n * slug: a `projectHash` drive reports the flag, not a hashed id, so the\n * expectation does not depend on where the project lives. */\nexport interface ExpectedDrive {\n slug: string;\n kind: \"local\" | \"remote\";\n /** \"host\" for `reactor.drives`; the plugin name for a contribution. */\n source: string;\n /** A remote drive's resolved URL. */\n url?: string;\n id?: string;\n projectHash?: boolean | \"id\";\n}\n\n/** One `$output` token in the declared host. */\nexport interface ConsumedOutput {\n /** Host path of the token (`reactor.backends.sb.remote.url`). */\n at: string;\n host: string;\n member?: string;\n path: OutputPath;\n}\n\nexport interface HostExpectation {\n name: string;\n kind: RunnerKind;\n /** The verb this host runs at: `runner.defaultVerb ?? \"run\"` standalone;\n * for a compound member, its own effective verb under the compound's. */\n verb: string;\n /** Reactor hosts with backends: `reactorClientMode`. */\n clientMode?: ReactorClientMode;\n /** Reactor hosts: local AND remote backends (Connect's routing client). */\n multiReactor?: boolean;\n backends?: ExpectedBackend[];\n /** The resolved URLs of the remote backends, placement order. */\n remotes?: string[];\n drives?: ExpectedDrive[];\n /** Producers its own tokens read (`host` or `host#member`), sorted. */\n dependsOn: string[];\n consumes: ConsumedOutput[];\n /** `$env` names its own tokens read, sorted (values are not recorded). */\n env: string[];\n /** Compound: member keys in start order. */\n startOrder?: string[];\n /** Compound: each member's expectation. */\n members?: Record<string, MemberExpectation>;\n}\n\nexport interface MemberExpectation extends Omit<\n HostExpectation,\n \"startOrder\" | \"members\"\n> {\n /** The member's host folder (`children.<key>.host`). */\n host: string;\n /** Member keys this member consumes (it starts after them), sorted. */\n after: string[];\n}\n\n/** A drive a plugin contributes, as plugin contribution discovery reports\n * it (`resolvePluginContributions`). */\nexport interface ContributedDriveInput {\n declaration: Record<string, unknown>;\n source: string;\n}\n\nexport interface ExpectHostInput {\n kind: RunnerKind;\n /** The host as declared (tokens in place); a compound member's draft\n * (its host.js with the wrapper applied). */\n declared: Record<string, unknown>;\n /** The resolved (and parsed) host. Default: `declared`. */\n resolved?: Record<string, unknown>;\n /** Drives the host's plugins contribute at its verb. */\n contributed?: readonly ContributedDriveInput[];\n /** Compound: its members, any order (the plan orders them). */\n members?: readonly MemberInput[];\n /** Compound: the dependency plan (`planCompound`). */\n plan?: CompoundPlan;\n}\n\nexport interface MemberInput extends Omit<ExpectHostInput, \"members\" | \"plan\"> {\n key: string;\n host: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction runnerOf(host: Record<string, unknown>): Record<string, unknown> {\n return isRecord(host.runner) ? host.runner : {};\n}\n\nfunction defaultVerbOf(host: Record<string, unknown>): string | undefined {\n const verb = runnerOf(host).defaultVerb;\n return typeof verb === \"string\" ? verb : undefined;\n}\n\n/** At compound verb \"run\" each member runs its own defaultVerb; any other\n * compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */\nfunction memberVerb(compoundVerb: string, member: Record<string, unknown>) {\n return compoundVerb === \"run\"\n ? (defaultVerbOf(member) ?? \"run\")\n : compoundVerb;\n}\n\n/** Backend names, placement-primary first (`backendsToDescriptors` order). */\nfunction orderedBackends(reactor: ReactorConfig): [string, ReactorBackend][] {\n const backends = Object.entries(reactor.backends ?? {});\n const primary = reactor.placement?.primary;\n const first = backends.filter(([name]) => name === primary);\n return [...first, ...backends.filter(([name]) => name !== primary)];\n}\n\nfunction expectBackend(\n name: string,\n backend: ReactorBackend,\n reactor: ReactorConfig,\n): ExpectedBackend {\n const out: ExpectedBackend = { name, kind: backend.kind };\n if (backend.storage) out.storage = backend.storage.kind;\n if (typeof backend.storage?.dataDir === \"string\") {\n out.dataDir = backend.storage.dataDir;\n }\n try {\n backendToDescriptor(name, backend, reactor.protocol);\n } catch (error) {\n out.provisionError = error instanceof Error ? error.message : String(error);\n }\n return out;\n}\n\nfunction expectDrive(\n declaration: Record<string, unknown>,\n source: string,\n): ExpectedDrive | undefined {\n if (typeof declaration.slug !== \"string\") return undefined;\n const remote = isRecord(declaration.remote) ? declaration.remote : undefined;\n const drive: ExpectedDrive = {\n slug: declaration.slug,\n kind: remote ? \"remote\" : \"local\",\n source,\n };\n if (remote && typeof remote.url === \"string\") drive.url = remote.url;\n if (typeof declaration.id === \"string\") drive.id = declaration.id;\n const projectHash = declaration.projectHash;\n if (typeof projectHash === \"boolean\" || projectHash === \"id\") {\n drive.projectHash = projectHash;\n }\n return drive;\n}\n\n/** The key `mergeDrivePlan` merges on: the SERVED slug, which for\n * `projectHash: true` is the hashed id (never equal to a plain slug). */\nfunction servedSlugKey(drive: ExpectedDrive): string {\n return drive.projectHash === true ? `${drive.slug}\\0hashed` : drive.slug;\n}\n\n/** Contributions first, then host declarations; keyed by served slug, the\n * host wins (and keeps the contribution's position), like `mergeDrivePlan`. */\nfunction drivePlan(\n reactor: ReactorConfig | undefined,\n contributed: readonly ContributedDriveInput[],\n): ExpectedDrive[] {\n const plan = new Map<string, ExpectedDrive>();\n for (const { declaration, source } of contributed) {\n const drive = expectDrive(declaration, source);\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n for (const declaration of reactor?.drives ?? []) {\n const drive = expectDrive(declaration, \"host\");\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n return [...plan.values()];\n}\n\n/** Token facts of the host's OWN fields (a compound's `children` are its\n * members' own). */\nfunction tokenFacts(\n declared: Record<string, unknown>,\n kind: RunnerKind,\n): Pick<HostExpectation, \"dependsOn\" | \"consumes\" | \"env\"> {\n const own =\n kind === \"compound\"\n ? Object.fromEntries(\n Object.entries(declared).filter(([key]) => key !== \"children\"),\n )\n : declared;\n const sites = outputSitesOf(own);\n const consumes = sites.map(({ path, ref, outputPath }): ConsumedOutput => ({\n at: path,\n host: ref.host,\n ...(ref.member !== undefined ? { member: ref.member } : {}),\n path: outputPath,\n }));\n return {\n dependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),\n consumes,\n env: [...new Set(envSitesOf(own).map(({ name }) => name))].sort(),\n };\n}\n\nfunction expectOwn(\n input: Omit<ExpectHostInput, \"members\" | \"plan\">,\n verb: string,\n): HostExpectation {\n const resolved = input.resolved ?? input.declared;\n const expectation: HostExpectation = {\n name: typeof resolved.name === \"string\" ? resolved.name : \"\",\n kind: input.kind,\n verb,\n ...tokenFacts(input.declared, input.kind),\n };\n if (input.kind !== \"reactor\") return expectation;\n\n const reactor = isRecord(resolved.reactor)\n ? (resolved.reactor as ReactorConfig)\n : undefined;\n const mode = reactorClientMode(reactor);\n if (mode !== undefined) expectation.clientMode = mode;\n expectation.multiReactor = isStructuralMultiReactor(reactor);\n const backends = reactor ? orderedBackends(reactor) : [];\n if (reactor && backends.length > 0) {\n expectation.backends = backends.map(([name, backend]) =>\n expectBackend(name, backend, reactor),\n );\n expectation.remotes = backends.flatMap(([, backend]) =>\n backend.kind === \"remote\" && typeof backend.remote?.url === \"string\"\n ? [backend.remote.url]\n : [],\n );\n }\n expectation.drives = drivePlan(reactor, input.contributed ?? []);\n return expectation;\n}\n\n/**\n * The expectation for one host. A reactor host's comes from its resolved\n * reactor block and contributed drives; a compound's lists its members in\n * plan order, each with the verb it runs at under the compound's own verb\n * and the members it starts after.\n */\nexport function expectHost(input: ExpectHostInput): HostExpectation {\n const verb = defaultVerbOf(input.declared) ?? \"run\";\n const expectation = expectOwn(input, verb);\n if (input.kind !== \"compound\" || !input.members) return expectation;\n\n const order = input.plan?.order ?? input.members.map((m) => m.key);\n const edges = input.plan?.edges ?? [];\n const byKey = new Map(input.members.map((m) => [m.key, m]));\n const members: Record<string, MemberExpectation> = {};\n for (const key of order) {\n const member = byKey.get(key);\n if (!member) continue;\n members[key] = {\n host: member.host,\n ...expectOwn(member, memberVerb(verb, member.declared)),\n after: [\n ...new Set(\n edges.filter((e) => e.consumer === key).map((e) => e.producer),\n ),\n ].sort(),\n };\n }\n expectation.startOrder = order.filter((key) => byKey.has(key));\n expectation.members = members;\n return expectation;\n}\n"],"mappings":";;;;;;;;;;;;;AAuDA,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CACA;CACA;CAJX,YACE,SACA,OACA,YACA,MACA;EACA,MACE,aAAa,GAAG,QAAQ,yBAAyB,eAAe,OAClE;EANS,KAAA,QAAA;EACA,KAAA,aAAA;EACA,KAAA,OAAA;EAKT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,UAAU;AAGhB,MAAM,gBAAgB;AAEtB,MAAM,gBAAgB;CAAC;CAAQ;CAAQ;AAAQ;AAC/C,MAAM,iBAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAS,SACP,SACA,MAA8B,CAAC,GACP;CACxB,IAAI,sBAAsB,KACxB,MAAM,IAAI,MACR,uEACF;CAEF,MAAM,OACJ,QAAQ,aAAa,UACjB,CAAC,GAAG,eAAe,GAAG,cAAc,IACpC;CACN,MAAM,OAA+B,CAAC;CACtC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ,QAAQ,IAAI;EAC1B,IAAI,UAAU,KAAA,GAAW,KAAK,OAAO;CACvC;CACA,OAAO;EACL,GAAG;EACH,iCAAiC;EACjC,kBAAkB;EAClB,iBAAiB;EACjB,cAAc;EACd,GAAG;CACL;AACF;AAEA,SAAS,kBAAkB,aAA6B;CAItD,MAAM,UAHW,cACf,cAAc,KAAK,KAAK,aAAa,cAAc,CAAC,CAAC,CAAC,IAEjC,CAAC,CAAC,QAAQ,oCAAoC;CACrE,OAAO,KAAK,KAAK,KAAK,QAAQ,OAAO,GAAG,QAAQ,SAAS;AAC3D;;AAGA,eAAe,mBACb,aACA,MACA,MACe;CACf,IAAI,SAAS,KAAA,KAAa,eAA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M,OAAO,QAAQ,CAAC;GACtD,OAAO,CACL,GAAG,IAAI,IACL,MAAM,QAAQ,MAAM,EAAE,aAAa,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,QAAQ,CAC/D,CACF,CAAC,CAAC,KAAK;EACT;CACF;CACA,YAAY,aAAa,MAAM,QAAQ,QAAQ,MAAM,IAAI,GAAG,CAAC;CAC7D,YAAY,UAAU;CACtB,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { D as declaredGenericCompoundHostSchema } from "./host-schemas-DtKFmLd0.mjs";
1
+ import { k as declaredGenericCompoundHostSchema } from "./host-schemas-CwNCJflE.mjs";
2
2
  import { z } from "zod";
3
3
  //#region src/host-types.d.ts
4
4
  declare global {
@@ -179,4 +179,4 @@ declare function mergeContributions(resolved: readonly {
179
179
  //#endregion
180
180
  export { runObserveHookSequential as C, PHHostOutputs as D, PHHost as E, PluginEntry as O, runObserveHook as S, runTransformHook as T, normalizePluginEntry as _, MergedContribution as a, registerHostType as b, PluginEntryData as c, ResolvedPlugin as d, Transform as f, normalizePluginEntries as g, mergeContributions as h, HostPluginModule as i, PluginError as l, hostTypeSatisfies as m, Contributions as n, NormalizedPluginEntry as o, entryActiveForVerb as p, HostPlugin as r, Observe as s, ContributionSource as t, Provide as u, pluginEntryObjectSchema as v, runProvideHook as w, resolveOrder as x, pluginEntrySchema as y };
181
181
  export {};
182
- //# sourceMappingURL=plugins-C1Rjl-zt.d.mts.map
182
+ //# sourceMappingURL=plugins-DZPDoyBt.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugins-C1Rjl-zt.d.mts","names":[],"sources":["../src/host-types.ts","../src/plugins.ts"],"mappings":";;;QAUQ;;;YAII;;YAGA;;KAMP,wBAAwB;KAExB,wBAAwB;;;;KAKxB,iBAAiB,GAAG,oBAAoB;EAAY,cAAc;IACnE,KAAK;EACH,QAAQ,KAAK;IACX,QAAQ;IACR,UAAU;;;;;KAON,YACT,KAAK,kBAAkB,cAAc;EAAa,Y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Q;iBAWW,iBAAiB,GAAG,GACxC,cACA,kBAAkB,cAClB,KAAK,GACL,MAAM,IACL,QAAQ;;;;iBAYW,yBAAyB,GAC7C,cACA,kBAAkB,cAClB,KAAK,IACJ;iBAOmB,eAAe,GACnC,cACA,kBAAkB,cAClB,KAAK,IACJ;UAWc;EACf;EACA;;UAGe,mBAAmB;EAClC,OAAO;EACP,QAAQ;;;;iBAKM,mBACd;EACE,QAAQ;EACR,YAAY;MAEb,eAAe"}
1
+ {"version":3,"file":"plugins-DZPDoyBt.d.mts","names":[],"sources":["../src/host-types.ts","../src/plugins.ts"],"mappings":";;;QAUQ;;;YAII;;YAGA;;KAMP,wBAAwB;KAExB,wBAAwB;;;;KAKxB,iBAAiB,GAAG,oBAAoB;EAAY,cAAc;IACnE,KAAK;EACH,QAAQ,KAAK;IACX,QAAQ;IACR,UAAU;;;;;KAON,YACT,KAAK,kBAAkB,cAAc;EAAa,YAAY;IAC3D,iBAAiB,GAAG,cAExB;;KAGU,cAAc,UAAU,mBAClC,cAAc;EAAa,eAAe;IAAM;UAExC,kBAAkB,kBAAkB;EAC5C,QAAQ;;EAER;;EAEA;EACA,SAAS;;KAGN,sBACF,KAAK,kBAAkB,IAAI,kBAAkB,GAAG,gBAAgB,OACjE;;;;;;;;;KAUU,cAEV,4BAA4B;QAKtB;YACI;IACR;MACE,MAAM,EAAE,aAAa;MACrB,SAAS;;;;;;;;;;;;;;;;;;;;;;cChEF,oBAAoB;EAC/B,YAAY,iBAAiB;;cAQlB,yBAAuB,EAAA;;;;;GAUlC,EAAA,KAAA;cAEW,mBAAiB,EAAA,mBAAA,EAAA,WAAA,EAAA;;;;;GAG5B,EAAA,KAAA;;;KAIU,kBAAkB,EAAE,aAAa;UAG5B;EACf;EACA;EACA;EACA,QAAQ;;iBAGM,qBACd,OAAO,kBACN;;;iBAca,uBACd,kBAAkB,mBAClB,gBACC;iBAea,mBACd,OAAO,uBACP;iBAsBc,iBAAiB,YAAY;iBAS7B,kBACd,kBACA;;;KAcU,QAAQ,GAAG,MAAM,KAAK,MAAM,IAAI,QAAQ;KACxC,UAAU,GAAG,MAAM,OAAO,GAAG,KAAK,MAAM,IAAI,QAAQ;KACpD,QAAQ,MAAM,KAAK,aAAa;;;;;;;UAQ3B;EACf;EACA;EACA;IAAuB;IAAc;IAAe;;GACnD;;UAGc,WACf,SAAS,yBACT;;EAGA;;;EAGA;;EAEA;;;EAGA;;;EAGA,eAAe,EAAE,QAAQ;EACzB,QAAQ,QAAQ;EAChB,gBAAgB;;;;KAKN,iBACV,SAAS,yBACT,qBAEE,WAAW,QAAQ,aACjB,QAAQ,YAAY,WAAW,QAAQ;UAE5B,eAAe,SAAS;EACvC,OAAO;EACP,QAAQ,WAAW;;EAEnB;;;;iBAOc,aAAa,QAC3B,kBAAkB,WAAW,YAC5B,WAAW;iBA6CQ,eAAe,GAAG,GACtC,cACA,kBAAkB,cAClB,KAAK,IACJ,QAAQ;iBAWW,iBAAiB,GAAG,GACxC,cACA,kBAAkB,cAClB,KAAK,GACL,MAAM,IACL,QAAQ;;;;iBAYW,yBAAyB,GAC7C,cACA,kBAAkB,cAClB,KAAK,IACJ;iBAOmB,eAAe,GACnC,cACA,kBAAkB,cAClB,KAAK,IACJ;UAWc;EACf;EACA;;UAGe,mBAAmB;EAClC,OAAO;EACP,QAAQ;;;;iBAKM,mBACd;EACE,QAAQ;EACR,YAAY;MAEb,eAAe"}
@@ -1,3 +1,3 @@
1
- import { C as runObserveHookSequential, O as PluginEntry, S as runObserveHook, T as runTransformHook, _ as normalizePluginEntry, a as MergedContribution, b as registerHostType, c as PluginEntryData, d as ResolvedPlugin, f as Transform, g as normalizePluginEntries, h as mergeContributions, i as HostPluginModule, l as PluginError, m as hostTypeSatisfies, n as Contributions, o as NormalizedPluginEntry, p as entryActiveForVerb, r as HostPlugin, s as Observe, t as ContributionSource, u as Provide, v as pluginEntryObjectSchema, w as runProvideHook, x as resolveOrder, y as pluginEntrySchema } from "./plugins-C1Rjl-zt.mjs";
1
+ import { C as runObserveHookSequential, O as PluginEntry, S as runObserveHook, T as runTransformHook, _ as normalizePluginEntry, a as MergedContribution, b as registerHostType, c as PluginEntryData, d as ResolvedPlugin, f as Transform, g as normalizePluginEntries, h as mergeContributions, i as HostPluginModule, l as PluginError, m as hostTypeSatisfies, n as Contributions, o as NormalizedPluginEntry, p as entryActiveForVerb, r as HostPlugin, s as Observe, t as ContributionSource, u as Provide, v as pluginEntryObjectSchema, w as runProvideHook, x as resolveOrder, y as pluginEntrySchema } from "./plugins-DZPDoyBt.mjs";
2
2
  export { ContributionSource, Contributions, HostPlugin, HostPluginModule, MergedContribution, NormalizedPluginEntry, Observe, type PluginEntry, PluginEntryData, PluginError, Provide, ResolvedPlugin, Transform, entryActiveForVerb, hostTypeSatisfies, mergeContributions, normalizePluginEntries, normalizePluginEntry, pluginEntryObjectSchema, pluginEntrySchema, registerHostType, resolveOrder, runObserveHook, runObserveHookSequential, runProvideHook, runTransformHook };
3
3
  export {};