@powerhousedao/host-core 6.2.3-dev.69 → 6.2.3-dev.71

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.
Files changed (36) hide show
  1. package/dist/compound-B6RZMA0Y.mjs +2804 -0
  2. package/dist/compound-B6RZMA0Y.mjs.map +1 -0
  3. package/dist/compound-PhoVeqe1.d.mts +2401 -0
  4. package/dist/compound-PhoVeqe1.d.mts.map +1 -0
  5. package/dist/env-substitution-C_fVirPh.d.mts +17 -0
  6. package/dist/env-substitution-C_fVirPh.d.mts.map +1 -0
  7. package/dist/env-substitution-Dj3pdsut.mjs +330 -0
  8. package/dist/env-substitution-Dj3pdsut.mjs.map +1 -0
  9. package/dist/host-schemas-mqOYNGot.d.mts +2153 -0
  10. package/dist/host-schemas-mqOYNGot.d.mts.map +1 -0
  11. package/dist/index.d.mts +908 -691
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +335 -109
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/plugins-XL6WsvTL.d.mts +182 -0
  16. package/dist/plugins-XL6WsvTL.d.mts.map +1 -0
  17. package/dist/plugins.d.mts +2 -120
  18. package/dist/plugins.mjs.map +1 -1
  19. package/dist/projection.d.mts +586 -0
  20. package/dist/projection.d.mts.map +1 -0
  21. package/dist/projection.mjs +1505 -0
  22. package/dist/projection.mjs.map +1 -0
  23. package/dist/runners/compound.d.mts +157 -12
  24. package/dist/runners/compound.d.mts.map +1 -1
  25. package/dist/runners/compound.mjs +5 -13
  26. package/dist/runners/compound.mjs.map +1 -1
  27. package/dist/schema.d.mts +105 -0
  28. package/dist/schema.d.mts.map +1 -0
  29. package/dist/schema.mjs +35 -0
  30. package/dist/schema.mjs.map +1 -0
  31. package/package.json +16 -4
  32. package/dist/compound-C8P0kvPJ.d.mts +0 -157
  33. package/dist/compound-C8P0kvPJ.d.mts.map +0 -1
  34. package/dist/host-schemas-CtPNRr5v.mjs +0 -720
  35. package/dist/host-schemas-CtPNRr5v.mjs.map +0 -1
  36. package/dist/plugins.d.mts.map +0 -1
@@ -1,720 +0,0 @@
1
- import { pluginEntrySchema } from "./plugins.mjs";
2
- import { createRequire } from "node:module";
3
- import fs, { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
- import path from "node:path";
5
- import { pathToFileURL } from "node:url";
6
- import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
7
- import { z } from "zod";
8
- import crypto from "node:crypto";
9
- //#region src/connect-projection.ts
10
- /**
11
- * Instance-fact projection for compound hosts: the drives a compound's
12
- * reactor member created, projected into the Connect member's runtime-config
13
- * override. Pure functions, moved from ph-cli's vetra service so the generic
14
- * compound and the classic path share one implementation.
15
- */
16
- function isLocalDrive(drive) {
17
- return "local" in drive;
18
- }
19
- const driveKey = (drive) => isLocalDrive(drive) ? `local:${drive.id}` : drive.url;
20
- /**
21
- * Concatenate groups of `connect.drives.defaultDrives` in the order given,
22
- * de-duplicating by drive identity (URL for remote entries, id for local
23
- * ones). The first occurrence of a drive wins, so earlier groups keep their
24
- * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first
25
- * even when the project's `powerhouse.config.json` lists the same drive.
26
- */
27
- function mergeDefaultDrives(...groups) {
28
- const seen = /* @__PURE__ */ new Set();
29
- const out = [];
30
- for (const group of groups) for (const drive of group) {
31
- const key = driveKey(drive);
32
- if (seen.has(key)) continue;
33
- seen.add(key);
34
- out.push(drive);
35
- }
36
- return out;
37
- }
38
- /**
39
- * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,
40
- * swaps the loopback origin for the public base. Browser clients behind a
41
- * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs
42
- * (e.g. a remote drive) are already public and pass through unchanged, as do
43
- * unparseable ones.
44
- */
45
- function rebaseDriveUrl(driveUrl, publicBase) {
46
- let url;
47
- try {
48
- url = new URL(driveUrl);
49
- } catch {
50
- return driveUrl;
51
- }
52
- if (![
53
- "localhost",
54
- "127.0.0.1",
55
- "[::1]"
56
- ].includes(url.hostname)) return driveUrl;
57
- return `${publicBase.replace(/\/+$/, "")}${url.pathname}`;
58
- }
59
- /**
60
- * The compound's drives projection: created drives first (rebased onto the
61
- * public base when given), then the project's configured drives, de-duplicated
62
- * — and `preserve-all`, because compound-injected drive lists change per
63
- * launch context and must never detach drives the user added by hand.
64
- */
65
- function projectDrivesIntoConnect(input) {
66
- return { drives: {
67
- defaultDrives: mergeDefaultDrives(input.createdDriveUrls.filter((url) => typeof url === "string" && url.length > 0).map((url) => ({
68
- url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,
69
- name: null,
70
- icon: null
71
- })), input.configuredDefaultDrives ?? []),
72
- preserveStrategy: "preserve-all"
73
- } };
74
- }
75
- //#endregion
76
- //#region src/host-loader.ts
77
- /**
78
- * Loads and pre-validates a `hosts/<name>/host.js` definition.
79
- *
80
- * A host file is a static PROJECTION of powerhouse.config.json: plain ESM,
81
- * default-exporting a data object. Three gates run before any runner sees it:
82
- * 1. import lint — the only legal import is the project's
83
- * powerhouse.config.json (host files are data, not programs);
84
- * 2. static check — the exported object must survive a JSON round trip
85
- * (functions, undefined, class instances, Dates etc. are rejected,
86
- * reporting the offending path);
87
- * 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children
88
- * rule. Full validation is the runner's `hostSchema` (phase 2).
89
- *
90
- * This module never exits the process — callers own error presentation.
91
- */
92
- const HOST_FILE = "host.js";
93
- const CONFIG_IMPORT_SUFFIX = "powerhouse.config.json";
94
- var HostLoadError = class extends Error {
95
- constructor(message, hint) {
96
- super(hint ? `${message}\n Hint: ${hint}` : message);
97
- this.name = "HostLoadError";
98
- }
99
- };
100
- /** A `hosts/` folder with no `<name>/host.js` inside is "empty" — the guard
101
- * state: callers warn loudly and fall back to legacy rather than activating
102
- * the new architecture off a stray `mkdir hosts`. */
103
- function probeHostsFolder(projectRoot) {
104
- const dir = path.join(projectRoot, "hosts");
105
- if (!existsSync(dir) || !statSync(dir).isDirectory()) return { kind: "absent" };
106
- const hosts = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, HOST_FILE))).map((entry) => entry.name).sort();
107
- return hosts.length === 0 ? {
108
- kind: "empty",
109
- dir
110
- } : {
111
- kind: "present",
112
- dir,
113
- hosts
114
- };
115
- }
116
- /** Sibling host imports: `../<host>/host.js` — source material for derived
117
- * compositions (full-inclusion wrappers compute over them with plain JS). */
118
- const SIBLING_IMPORT = /^\.\.\/([A-Za-z0-9_-]+)\/host\.js$/;
119
- /** Rejects every import except the project's powerhouse.config.json and
120
- * SIBLING host files (R1: derived compositions), plus any dynamic
121
- * `import(...)` or `require(...)`. Source-level enforcement: the JSON round
122
- * trip below is the hard gate; this one produces the better error. Returns
123
- * the sibling host names the file imports, for cycle detection. */
124
- function lintHostImports(source, file) {
125
- const siblings = [];
126
- for (const match of source.matchAll(/^\s*import\b[^;'"]*?from\s+["']([^"']+)["']/gm)) {
127
- const specifier = match[1];
128
- if (specifier.endsWith(CONFIG_IMPORT_SUFFIX)) continue;
129
- const sibling = SIBLING_IMPORT.exec(specifier);
130
- if (sibling) {
131
- siblings.push(sibling[1]);
132
- continue;
133
- }
134
- throw new HostLoadError(`${file} imports "${specifier}" — a host file may only import the project's powerhouse.config.json or sibling hosts/<name>/host.js files.`, "Host files are static projections; code belongs in plugins or the runner.");
135
- }
136
- if (/^\s*import\s+["']/m.test(source)) throw new HostLoadError(`${file} contains a side-effect import — a host file may only import the project's powerhouse.config.json or sibling host files.`);
137
- if (/\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} uses dynamic import()/require() — host files are static data.`);
138
- return siblings;
139
- }
140
- /** Walks the sibling-import graph from `hostName`, linting every visited file
141
- * and failing on a cycle (an ESM circular would otherwise surface as an
142
- * undefined default export with no useful message). */
143
- function lintHostImportGraph(hostsDir, hostName) {
144
- const state = /* @__PURE__ */ new Map();
145
- const visit = (name, chain) => {
146
- const mark = state.get(name);
147
- if (mark === "done") return;
148
- if (mark === "visiting") throw new HostLoadError(`Host import cycle: ${[...chain, name].map((n) => `hosts/${n}`).join(" -> ")}.`, "Hoist the shared data into one host (or powerhouse.config.json) instead of importing both ways.");
149
- const file = path.join(hostsDir, name, HOST_FILE);
150
- if (!existsSync(file)) throw new HostLoadError(`hosts/${chain[chain.length - 1] ?? name} imports sibling "hosts/${name}/host.js", which does not exist.`);
151
- state.set(name, "visiting");
152
- const siblings = lintHostImports(readFileSync(file, "utf8"), file);
153
- for (const sibling of siblings) visit(sibling, [...chain, name]);
154
- state.set(name, "done");
155
- };
156
- visit(hostName, []);
157
- }
158
- /** Returns the path of the first value that would not survive a JSON round
159
- * trip, or undefined when the object is fully static. */
160
- function findNonStaticValue(value, trail = "") {
161
- if (value === null) return void 0;
162
- const kind = typeof value;
163
- if (kind === "string" || kind === "number" || kind === "boolean") return;
164
- if (kind !== "object") return `${trail || "<root>"} (${kind})`;
165
- if (Array.isArray(value)) {
166
- for (let i = 0; i < value.length; i++) {
167
- const hit = findNonStaticValue(value[i], `${trail}[${i}]`);
168
- if (hit) return hit;
169
- }
170
- return;
171
- }
172
- const proto = Object.getPrototypeOf(value);
173
- if (proto !== Object.prototype && proto !== null) return `${trail || "<root>"} (non-plain object)`;
174
- for (const [key, child] of Object.entries(value)) {
175
- const hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);
176
- if (hit) return hit;
177
- }
178
- }
179
- function assertHostShape(host, file) {
180
- if (typeof host.name !== "string" || host.name.length === 0) throw new HostLoadError(`${file}: \`name\` must be a non-empty string.`);
181
- const runner = host.runner;
182
- if (runner === null || typeof runner !== "object" || typeof runner.module !== "string") throw new HostLoadError(`${file}: \`runner\` must be an object with a \`module\` specifier string.`);
183
- if (host.reactor !== void 0 && host.children !== void 0) throw new HostLoadError(`${file}: \`reactor\` and \`children\` are mutually exclusive — a host is a reactor runner or a compound runner, never both.`);
184
- }
185
- async function loadHost(projectRoot, hostName) {
186
- const probe = probeHostsFolder(projectRoot);
187
- if (probe.kind === "absent") throw new HostLoadError(`No hosts/ folder found in ${projectRoot}.`, "Scaffold one with `ph init --uniform-runners` (or create hosts/<name>/host.js).");
188
- if (probe.kind === "empty") throw new HostLoadError(`hosts/ exists at ${probe.dir} but contains no <name>/host.js.`, "An empty hosts/ folder does not activate the uniform-runners architecture; add a host definition or remove the folder.");
189
- if (!probe.hosts.includes(hostName)) throw new HostLoadError(`Unknown host "${hostName}". Available hosts: ${probe.hosts.join(", ")}.`);
190
- const file = path.join(probe.dir, hostName, HOST_FILE);
191
- lintHostImportGraph(probe.dir, hostName);
192
- const host = (await import(pathToFileURL(file).href)).default;
193
- if (host === null || typeof host !== "object" || Array.isArray(host)) throw new HostLoadError(`${file} must default-export the host object (\`export default { name, runner, ... }\`).`);
194
- const nonStatic = findNonStaticValue(host);
195
- if (nonStatic) throw new HostLoadError(`${file} exports a non-static value at \`${nonStatic}\` — host files must survive a JSON round trip.`, "Runtime behavior belongs in the runner; host files only carry data.");
196
- assertHostShape(host, file);
197
- return {
198
- name: hostName,
199
- dir: path.dirname(file),
200
- file,
201
- host
202
- };
203
- }
204
- //#endregion
205
- //#region src/runner-resolver.ts
206
- /**
207
- * Resolves a host's `runner.module` specifier from the PROJECT's dependency
208
- * tree (not ph-cli's), imports it, and checks the runner-module contract:
209
- * `{ run, hostSchema, kind, ...optionalVerbs }`. Phase-0 home is ph-cli; the
210
- * uniform-runners plan moves this into @powerhousedao/host-core with the
211
- * generic compound (phase 1).
212
- */
213
- var RunnerError = class extends Error {
214
- constructor(message, hint) {
215
- super(hint ? `${message}\n Hint: ${hint}` : message);
216
- this.name = "RunnerError";
217
- }
218
- };
219
- /** Exports that are part of the contract but are not verbs. */
220
- const NON_VERB_EXPORTS = /* @__PURE__ */ new Set([
221
- "hostSchema",
222
- "kind",
223
- "default"
224
- ]);
225
- async function resolveRunnerModule(projectRoot, specifier) {
226
- const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
227
- let resolved;
228
- try {
229
- resolved = projectRequire.resolve(specifier);
230
- } catch {
231
- throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project (install it, then retry).");
232
- }
233
- const module = await import(pathToFileURL(resolved).href);
234
- if (typeof module.run !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`run\` function (required verb).`);
235
- const hostSchema = module.hostSchema;
236
- if (!hostSchema || typeof hostSchema.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`hostSchema\` — runners validate their own host shape.`);
237
- if (typeof module.kind !== "string") throw new RunnerError(`Runner "${specifier}" does not export \`kind\` (e.g. "reactor" | "compound").`);
238
- return module;
239
- }
240
- function listVerbs(runner) {
241
- return Object.entries(runner).filter(([name, value]) => typeof value === "function" && !NON_VERB_EXPORTS.has(name)).map(([name]) => name).sort();
242
- }
243
- function getVerb(runner, specifier, verb) {
244
- const candidate = runner[verb];
245
- if (typeof candidate !== "function" || NON_VERB_EXPORTS.has(verb)) throw new RunnerError(`Runner "${specifier}" does not support the verb "${verb}". Supported verbs: ${listVerbs(runner).join(", ")}.`);
246
- return candidate;
247
- }
248
- function validateHost(runner, specifier, host, file) {
249
- const result = runner.hostSchema.safeParse(host);
250
- if (!result.success) throw new RunnerError(`${file} failed validation against the hostSchema of "${specifier}":\n${(result.error?.issues ?? []).map((issue) => ` - ${issue.path.join(".") || "<root>"}: ${issue.message}`).join("\n") || " (no details reported)"}`);
251
- }
252
- //#endregion
253
- //#region src/run-record.ts
254
- const runDir = (projectDir) => path.join(resolvePhDir(projectDir), "run");
255
- const recordPath = (projectDir, hostName) => path.join(runDir(projectDir), `${hostName}.json`);
256
- function readRunRecord(projectDir, hostName) {
257
- try {
258
- return JSON.parse(fs.readFileSync(recordPath(projectDir, hostName), "utf8"));
259
- } catch {
260
- return;
261
- }
262
- }
263
- function writeRunRecord(projectDir, record) {
264
- const target = recordPath(projectDir, record.hostName);
265
- fs.mkdirSync(path.dirname(target), { recursive: true });
266
- fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\n`);
267
- }
268
- function clearRunRecord(projectDir, hostName) {
269
- try {
270
- fs.rmSync(recordPath(projectDir, hostName));
271
- } catch {}
272
- }
273
- function isPidAlive(pid) {
274
- try {
275
- process.kill(pid, 0);
276
- return true;
277
- } catch (error) {
278
- return error.code === "EPERM";
279
- }
280
- }
281
- /**
282
- * Decide whether the recorded instance is this project's live host.
283
- *
284
- * pid liveness alone proves nothing (pids are reused), and the recorded
285
- * projectName is what separates "my instance" from "a different project that
286
- * happens to hold this storage root" — the confusion the vetra lock exists to
287
- * prevent. A stale record (dead pid) is reported so the caller can clear it; a
288
- * foreign one (live pid, different project) is left alone.
289
- */
290
- function probeRun(projectDir, hostName, projectName) {
291
- const record = readRunRecord(projectDir, hostName);
292
- if (!record) return { status: "none" };
293
- if (!isPidAlive(record.pid)) return {
294
- status: "stale",
295
- record
296
- };
297
- if (record.projectName !== projectName) return {
298
- status: "foreign",
299
- record
300
- };
301
- return {
302
- status: "live",
303
- record
304
- };
305
- }
306
- //#endregion
307
- //#region src/placeholders.ts
308
- /**
309
- * `${userData}` resolution for host files (desktop shape): storage paths in a
310
- * host must not derive from the instance name (renames must stay safe), so
311
- * the host file writes `${userData}/.ph/reactor-storage` and the RUNNER
312
- * resolves it at start. `${userData}` is a PROJECT-SHAPED root: its `.ph`
313
- * subtree carries the same names the classic commands use under
314
- * `<project>/.ph` (see `resolvePhDir`). In the CLI it IS the project root, so
315
- * `ph run desktop` in a project shares the one `.ph` tree `ph vetra` uses;
316
- * a shell (Tauri) points it at the OS profile via PH_USER_DATA_DIR, and the
317
- * whole `.ph` tree — stores, identity, run records — follows.
318
- */
319
- function defaultUserDataDir(projectRoot, env = process.env) {
320
- return env.PH_USER_DATA_DIR ?? path.resolve(projectRoot);
321
- }
322
- const PLACEHOLDER = /\$\{userData\}/g;
323
- /** Deep-substitute `${userData}` in every string of a JSON-shaped value.
324
- * Non-strings pass through; the input is never mutated. */
325
- function resolveUserDataPlaceholders(value, userData) {
326
- if (typeof value === "string") return value.replace(PLACEHOLDER, userData);
327
- if (Array.isArray(value)) return value.map((v) => resolveUserDataPlaceholders(v, userData));
328
- if (value !== null && typeof value === "object") {
329
- const out = {};
330
- for (const [k, v] of Object.entries(value)) out[k] = resolveUserDataPlaceholders(v, userData);
331
- return out;
332
- }
333
- return value;
334
- }
335
- //#endregion
336
- //#region src/compound.ts
337
- function memberEntries(host) {
338
- const children = host.children ?? {};
339
- return Object.entries(children);
340
- }
341
- function orderedMembers(host, wiring) {
342
- const entries = memberEntries(host);
343
- if (!wiring.startOrder) return entries;
344
- const byName = new Map(entries);
345
- const out = [];
346
- for (const name of wiring.startOrder) {
347
- const m = byName.get(name);
348
- if (m) {
349
- out.push([name, m]);
350
- byName.delete(name);
351
- }
352
- }
353
- for (const [name, m] of entries) if (byName.has(name)) out.push([name, m]);
354
- return out;
355
- }
356
- /** Build the member host object the member runner sees: the member's own
357
- * host.js with the wrapper applied. R1 semantics (rewire plan): a wrapper
358
- * SECTION is a FULL STATEMENT — `reactor` and `config`, when present on the
359
- * wrapper, replace the member's wholesale (host files derive keeps explicitly
360
- * by spreading the sibling import: `{ ...switchboard.reactor, drives }`).
361
- * `runner` stays key-merged: wrappers never restate `module`/`defaultVerb`,
362
- * they override individual keys (port, host, plugins — the plugins LIST
363
- * itself is a full statement computed in the file). */
364
- async function resolveMemberHost(projectRoot, member, userData, configPatch) {
365
- const base = (await loadHost(projectRoot, member.host)).host;
366
- return resolveUserDataPlaceholders({
367
- ...base,
368
- runner: {
369
- ...base.runner,
370
- ...member.runner ?? {}
371
- },
372
- config: {
373
- ...member.config !== void 0 ? member.config : base.config ?? {},
374
- ...configPatch ?? {}
375
- },
376
- reactor: member.reactor !== void 0 ? member.reactor : base.reactor
377
- }, userData);
378
- }
379
- function isConnectMember(member) {
380
- return member.host === "connect";
381
- }
382
- function isReactorFactMember(member) {
383
- return member.host === "switchboard";
384
- }
385
- async function runCompound(host, ctx, options) {
386
- const projectRoot = ctx.projectRoot;
387
- const wiring = host.config ?? {};
388
- const verb = ctx.verb;
389
- const probe = probeRun(projectRoot, host.name, options.projectName);
390
- if (probe.status === "live") throw new Error(`${host.name} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`);
391
- if (probe.status === "foreign") throw new Error(`.ph/run/${host.name}.json describes a live "${probe.record.projectName}", but this project is "${options.projectName}". Refusing to start a second instance.`);
392
- const userData = defaultUserDataDir(projectRoot, ctx.env);
393
- const started = [];
394
- const reactorFacts = { driveUrls: [] };
395
- const shutdown = async () => {
396
- for (const m of [...started].reverse()) try {
397
- await m.handle.shutdown?.();
398
- } catch {}
399
- if (wiring.runtimeRecord !== false) clearRunRecord(projectRoot, host.name);
400
- };
401
- for (const [name, member] of orderedMembers(host, wiring)) {
402
- let configPatch;
403
- if (isConnectMember(member) && wiring.projectDrivesIntoConnect && reactorFacts.driveUrls.length > 0) {
404
- const configuredDefaultDrives = (member.config?.drives)?.defaultDrives;
405
- configPatch = projectDrivesIntoConnect({
406
- createdDriveUrls: reactorFacts.driveUrls,
407
- configuredDefaultDrives,
408
- publicBase: wiring.drivesPublicBase
409
- });
410
- }
411
- const memberHost = await resolveMemberHost(projectRoot, member, userData, configPatch);
412
- if (isConnectMember(member) && wiring.cspRegistrySync) memberHost.runner = {
413
- ...memberHost.runner,
414
- cspRegistrySync: true
415
- };
416
- const specifier = memberHost.runner.module;
417
- const runner = await resolveRunnerModule(projectRoot, specifier);
418
- validateHost(runner, specifier, memberHost, `hosts/${member.host}/host.js`);
419
- const handle = await getVerb(runner, specifier, verb === "run" ? memberHost.runner.defaultVerb ?? "run" : verb)(memberHost, ctx) ?? {};
420
- if (handle.ready) await handle.ready;
421
- started.push({
422
- name,
423
- handle
424
- });
425
- if (isReactorFactMember(member) && handle.driveUrls) reactorFacts.driveUrls.push(...handle.driveUrls);
426
- }
427
- if (wiring.runtimeRecord !== false) {
428
- const members = {};
429
- for (const m of started) members[m.name] = {
430
- port: m.handle.port,
431
- url: m.handle.endpoints?.graphql ?? m.handle.endpoints?.connect
432
- };
433
- writeRunRecord(projectRoot, {
434
- pid: process.pid,
435
- hostName: host.name,
436
- projectName: options.projectName,
437
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
438
- members,
439
- extra: options.recordExtra
440
- });
441
- }
442
- if (options.installSignalHandlers !== false) {
443
- const onSignal = (code) => {
444
- shutdown().finally(() => process.exit(code));
445
- };
446
- process.on("exit", () => {
447
- if (wiring.runtimeRecord !== false) clearRunRecord(projectRoot, host.name);
448
- });
449
- process.on("SIGINT", () => onSignal(130));
450
- process.on("SIGTERM", () => onSignal(143));
451
- }
452
- return {
453
- started,
454
- shutdown
455
- };
456
- }
457
- //#endregion
458
- //#region src/drives.ts
459
- /**
460
- * R1 — core drive declarations. A reactor without drives is not a running
461
- * reactor, so declaring + seeding them is HOST RUNTIME work (not a plugin):
462
- * onReactorReady → idempotent slug-keyed seeding → onDrivesReady. Plugins
463
- * CONTRIBUTE declarations into the same merged list (Contributions.drives);
464
- * `--explain drives` prints the merged set with provenance.
465
- *
466
- * Field semantics (union of the three existing creation sites — vetra,
467
- * preview, workflows — plus Connect's PHConnectDefaultDrive):
468
- * - slug: the SEEDING KEY (idempotence); id optional (stable identity),
469
- * projectHash derives both from the project path (generateProjectDriveId
470
- * semantics: `${slug}-${sha256(projectPath).slice(0, 8)}`).
471
- * - preferredEditor: binds the drive to its drive app — stored at
472
- * header.meta.preferredEditor; Connect config's `app` is the legacy alias.
473
- * - remote.url: an attachment to a drive served elsewhere (Connect default
474
- * drives, switchboard remoteDrives); local fields are ignored for remotes.
475
- */
476
- const driveDeclarationSchema = z.strictObject({
477
- slug: z.string().min(1),
478
- id: z.string().min(1).optional(),
479
- /** Derive id (and the served slug) from the project path, like
480
- * generateProjectDriveId — same ids classic `ph vetra` produces. */
481
- projectHash: z.boolean().optional(),
482
- name: z.string().min(1).optional(),
483
- icon: z.string().optional(),
484
- preferredEditor: z.string().optional(),
485
- sharingType: z.enum([
486
- "public",
487
- "private",
488
- "shared"
489
- ]).optional(),
490
- availableOffline: z.boolean().optional(),
491
- remote: z.strictObject({ url: z.string().min(1) }).optional()
492
- });
493
- const drivesSchema = z.array(driveDeclarationSchema);
494
- function projectDriveId(projectRoot, slug) {
495
- return `${slug}-${crypto.createHash("sha256").update(projectRoot).digest("hex").substring(0, 8)}`;
496
- }
497
- function resolveDriveDeclaration(projectRoot, decl) {
498
- const id = decl.projectHash ? projectDriveId(projectRoot, decl.slug) : decl.id ?? decl.slug;
499
- const slug = decl.projectHash ? id : decl.slug;
500
- if (decl.remote) return {
501
- kind: "remote",
502
- id,
503
- slug,
504
- name: decl.name ?? decl.slug,
505
- remoteUrl: decl.remote.url,
506
- sharingType: decl.sharingType ?? "public",
507
- availableOffline: decl.availableOffline ?? true
508
- };
509
- return {
510
- kind: "local",
511
- id,
512
- slug,
513
- name: decl.name ?? decl.slug,
514
- icon: decl.icon,
515
- preferredEditor: decl.preferredEditor,
516
- sharingType: decl.sharingType ?? "public",
517
- availableOffline: decl.availableOffline ?? true
518
- };
519
- }
520
- /** Idempotent, slug-keyed: an existing slug is left untouched (never
521
- * recreated, never mutated — preserveStrategy refinements live here later). */
522
- async function seedDrives(client, drives) {
523
- const result = {
524
- created: [],
525
- existing: [],
526
- attached: []
527
- };
528
- for (const drive of drives) {
529
- if (drive.kind === "remote") {
530
- await client.attachRemoteDrive(drive.remoteUrl);
531
- result.attached.push(drive.slug);
532
- continue;
533
- }
534
- if (await client.findDriveBySlug(drive.slug) !== void 0) {
535
- result.existing.push(drive.slug);
536
- continue;
537
- }
538
- await client.createDrive(drive);
539
- result.created.push(drive.slug);
540
- }
541
- return result;
542
- }
543
- /** Merge host-declared drives with plugin contributions, slug-keyed — the
544
- * host file wins on conflicts (it is the most explicit source). */
545
- function mergeDrivePlan(projectRoot, hostDeclared, contributed) {
546
- const plan = /* @__PURE__ */ new Map();
547
- for (const { declaration, source } of contributed) {
548
- const drive = resolveDriveDeclaration(projectRoot, declaration);
549
- plan.set(drive.slug, {
550
- drive,
551
- source
552
- });
553
- }
554
- for (const declaration of hostDeclared) {
555
- const drive = resolveDriveDeclaration(projectRoot, declaration);
556
- plan.set(drive.slug, {
557
- drive,
558
- source: "host"
559
- });
560
- }
561
- return [...plan.values()];
562
- }
563
- function explainDrivePlan(plan) {
564
- if (plan.length === 0) return "(no drives declared)";
565
- return ["drives:", ...plan.map(({ drive, source }) => {
566
- const kind = drive.kind === "remote" ? `remote ${drive.remoteUrl}` : "local";
567
- const editor = drive.preferredEditor ? ` editor=${drive.preferredEditor}` : "";
568
- return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;
569
- })].join("\n");
570
- }
571
- //#endregion
572
- //#region src/host-schemas.ts
573
- /**
574
- * The shared zod schemas for host.js blocks (D2.a). The `reactor` block
575
- * validates STRICTLY (D2.d — phase 0's tolerated-unknown-keys notice ends
576
- * here): a typo'd protocol key must fail, not silently not-apply, because
577
- * these are fleet-consensus settings. `config` stays loose — it is
578
- * runner-defined by design.
579
- */
580
- const profileSchema = z.strictObject({
581
- appId: z.string().min(1).optional(),
582
- name: z.string().min(1).optional(),
583
- description: z.string().optional(),
584
- icon: z.string().optional()
585
- }).optional();
586
- const reactorProtocolSchema = z.strictObject({
587
- featureFlags: z.strictObject({
588
- documentDecisions: z.boolean().optional(),
589
- authEnforcement: z.boolean().optional(),
590
- authGroups: z.boolean().optional(),
591
- authConditions: z.boolean().optional()
592
- }).optional(),
593
- createSignaturePolicy: z.enum(["legacy", "v2-required"]).optional(),
594
- unsupportedStoredDocuments: z.enum(["refuse", "read-only"]).optional()
595
- });
596
- const samePath = (a, b) => {
597
- const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "");
598
- return norm(a) === norm(b);
599
- };
600
- const reactorBackendSchema = z.strictObject({
601
- kind: z.enum([
602
- "in-process",
603
- "worker",
604
- "remote"
605
- ]).optional(),
606
- storage: z.strictObject({
607
- kind: z.enum([
608
- "idb",
609
- "memory",
610
- "path",
611
- "postgres"
612
- ]),
613
- dataDir: z.string().optional(),
614
- url: z.string().optional()
615
- }).optional(),
616
- readModel: z.strictObject({ url: z.string().optional() }).optional(),
617
- packages: z.strictObject({
618
- cdnUrl: z.string().optional(),
619
- specs: z.array(z.string()).optional(),
620
- dynamic: z.boolean().optional()
621
- }).optional(),
622
- remote: z.strictObject({
623
- host: z.string().optional(),
624
- url: z.string().optional()
625
- }).optional(),
626
- projection: z.strictObject({
627
- enabled: z.boolean().optional(),
628
- dbPoolSize: z.number().int().positive().optional()
629
- }).optional(),
630
- executors: z.strictObject({ numWorkers: z.union([z.number().int().positive(), z.literal("auto")]).optional() }).optional()
631
- }).superRefine((backend, ctx) => {
632
- const store = backend.storage;
633
- const storeDir = store?.kind === "path" ? store.dataDir : void 0;
634
- const readModel = backend.readModel?.url;
635
- if (storeDir && readModel && samePath(storeDir, readModel)) ctx.addIssue({
636
- code: "custom",
637
- path: ["readModel", "url"],
638
- message: `readModel.url must not be the reactor's storage dir (${readModel}): two PGlite instances on one data dir corrupt it. Omit readModel.url to get the classic <root>/.ph/read-storage next to the reactor store.`
639
- });
640
- });
641
- const reactorSchema = z.strictObject({
642
- backends: z.record(z.string(), reactorBackendSchema).optional(),
643
- placement: z.strictObject({
644
- primary: z.string().optional(),
645
- default: z.looseObject({}).optional()
646
- }).optional(),
647
- protocol: reactorProtocolSchema.optional(),
648
- /** DEPRECATED (dies in R2): workflows become a listed plugin — presence is
649
- * activation. Kept parsing until the switchboard rewire lands. */
650
- workflows: z.boolean().optional(),
651
- renown: z.strictObject({
652
- url: z.string().optional(),
653
- networkId: z.string().optional(),
654
- chainId: z.number().int().optional()
655
- }).optional(),
656
- packages: z.strictObject({ registryUrl: z.string().optional() }).optional(),
657
- namespace: z.string().min(1).optional(),
658
- auth: z.strictObject({
659
- enabled: z.boolean().optional(),
660
- admins: z.array(z.string()).optional(),
661
- renown: z.looseObject({}).optional()
662
- }).optional(),
663
- drives: drivesSchema.optional()
664
- });
665
- /** Common runner options every host.runner carries; runner modules extend it
666
- * loosely with their own process options. */
667
- const runnerBaseSchema = z.looseObject({
668
- module: z.string().min(1),
669
- defaultVerb: z.string().optional(),
670
- port: z.number().int().positive().optional(),
671
- /** Bind address; each runner documents its default (0.0.0.0 for servers,
672
- * localhost for vite dev, 127.0.0.1 for serve). */
673
- host: z.string().min(1).optional(),
674
- /** THE COMPOSITION: the plugin entries this host boots with. Presence is
675
- * activation; see plugins.ts for entry semantics. */
676
- plugins: z.array(pluginEntrySchema).optional()
677
- });
678
- /** A compound's children map (mutually exclusive with `reactor` — the XOR is
679
- * structural, enforced by the loader; schemas validate each side's shape). */
680
- const childrenSchema = z.record(z.string(), z.strictObject({
681
- host: z.string().min(1),
682
- runner: z.looseObject({}).optional(),
683
- config: z.looseObject({}).optional(),
684
- reactor: reactorSchema.optional()
685
- }));
686
- /** Composed generic host shapes — the basis for the emitted editor schemas
687
- * (D2.a). Runner packages extend these with their own runner options; `config`
688
- * stays loose by design. */
689
- const reactorHostSchema = z.looseObject({
690
- name: z.string().min(1),
691
- runner: runnerBaseSchema,
692
- config: z.looseObject({}).optional(),
693
- profile: profileSchema,
694
- reactor: reactorSchema.optional()
695
- });
696
- const compoundHostSchema = z.looseObject({
697
- name: z.string().min(1),
698
- runner: runnerBaseSchema,
699
- children: childrenSchema,
700
- config: z.looseObject({}).optional(),
701
- profile: profileSchema
702
- });
703
- const SCHEMA_BASE = "https://powerhouse.inc/schemas";
704
- /** The emitted-schema set, keyed by published filename. Pure — the
705
- * emit-schemas script writes these to disk and the drift test re-derives
706
- * them, per the runtime-config-schema pattern. */
707
- function emittedHostSchemas() {
708
- const emit = (name, schema) => ({
709
- $id: `${SCHEMA_BASE}/${name}.schema.json`,
710
- ...z.toJSONSchema(schema, { io: "input" })
711
- });
712
- return {
713
- "host-reactor.schema.json": emit("host-reactor", reactorHostSchema),
714
- "host-compound.schema.json": emit("host-compound", compoundHostSchema)
715
- };
716
- }
717
- //#endregion
718
- export { HostLoadError as A, readRunRecord as C, listVerbs as D, getVerb as E, mergeDefaultDrives as F, projectDrivesIntoConnect as I, rebaseDriveUrl as L, lintHostImports as M, loadHost as N, resolveRunnerModule as O, probeHostsFolder as P, probeRun as S, RunnerError as T, runCompound as _, reactorBackendSchema as a, clearRunRecord as b, reactorSchema as c, drivesSchema as d, explainDrivePlan as f, seedDrives as g, resolveDriveDeclaration as h, profileSchema as i, findNonStaticValue as j, validateHost as k, runnerBaseSchema as l, projectDriveId as m, compoundHostSchema as n, reactorHostSchema as o, mergeDrivePlan as p, emittedHostSchemas as r, reactorProtocolSchema as s, childrenSchema as t, driveDeclarationSchema as u, defaultUserDataDir as v, writeRunRecord as w, isPidAlive as x, resolveUserDataPlaceholders as y };
719
-
720
- //# sourceMappingURL=host-schemas-CtPNRr5v.mjs.map