@powerhousedao/ph-cli 6.2.3-dev.62 → 6.2.3-dev.64

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 (61) hide show
  1. package/dist/{cli-connect-override-DP5vRA7N.mjs → cli-connect-override-Cf7WutqU.mjs} +4 -4
  2. package/dist/{cli-connect-override-DP5vRA7N.mjs.map → cli-connect-override-Cf7WutqU.mjs.map} +1 -1
  3. package/dist/cli.mjs +4 -4
  4. package/dist/{connect-build-xRrXk9-p.mjs → connect-build-DO93w0f7.mjs} +9 -4
  5. package/dist/connect-build-DO93w0f7.mjs.map +1 -0
  6. package/dist/{connect-config-BvS0chVq.mjs → connect-config-9EZB_0H_.mjs} +4 -4
  7. package/dist/{connect-config-BvS0chVq.mjs.map → connect-config-9EZB_0H_.mjs.map} +1 -1
  8. package/dist/{connect-preview-BW6XnRtj.mjs → connect-preview-DqWtPruk.mjs} +62 -16
  9. package/dist/connect-preview-DqWtPruk.mjs.map +1 -0
  10. package/dist/{connect-studio-8EyDblpG.mjs → connect-studio-FEEyWfwB.mjs} +4 -4
  11. package/dist/{connect-studio-8EyDblpG.mjs.map → connect-studio-FEEyWfwB.mjs.map} +1 -1
  12. package/dist/{connect-studio-NxCVdXDv.mjs → connect-studio-k5vB41GX.mjs} +3 -3
  13. package/dist/dist-BqeDFgEy.mjs +2 -2
  14. package/dist/dist-BqeDFgEy.mjs.map +1 -1
  15. package/dist/{explain-D6gLYBd0.mjs → explain-BDHmXgw3.mjs} +4 -4
  16. package/dist/{explain-D6gLYBd0.mjs.map → explain-BDHmXgw3.mjs.map} +1 -1
  17. package/dist/{generate-all-CRfVwLJ9.mjs → generate-all-C_sPGBuk.mjs} +5 -5
  18. package/dist/{generate-all-CRfVwLJ9.mjs.map → generate-all-C_sPGBuk.mjs.map} +1 -1
  19. package/dist/{generate-desktop-shell-itIzf77U.mjs → generate-desktop-shell-BBSGpmud.mjs} +4 -4
  20. package/dist/generate-desktop-shell-BBSGpmud.mjs.map +1 -0
  21. package/dist/{generate-document-model-ChkXjM1s.mjs → generate-document-model-BfFIQ35q.mjs} +5 -5
  22. package/dist/{generate-document-model-ChkXjM1s.mjs.map → generate-document-model-BfFIQ35q.mjs.map} +1 -1
  23. package/dist/{generate-subgraph-DmcQWVbd.mjs → generate-subgraph-CVlTo7qk.mjs} +5 -5
  24. package/dist/{generate-subgraph-DmcQWVbd.mjs.map → generate-subgraph-CVlTo7qk.mjs.map} +1 -1
  25. package/dist/{host-schemas-CL_wFpY7-B_pY14Jy.mjs → host-schemas-CtPNRr5v-BQyKKFbS.mjs} +18 -4
  26. package/dist/host-schemas-CtPNRr5v-BQyKKFbS.mjs.map +1 -0
  27. package/dist/{ph-cli-commands-CLJP7yKV.mjs → ph-cli-commands-ifxjNJoa.mjs} +16 -16
  28. package/dist/{ph-cli-commands-CLJP7yKV.mjs.map → ph-cli-commands-ifxjNJoa.mjs.map} +1 -1
  29. package/dist/ph-cli-commands-qdvATJ2S.mjs +4 -0
  30. package/dist/precompress-P6cJDPVC.mjs +77 -0
  31. package/dist/precompress-P6cJDPVC.mjs.map +1 -0
  32. package/dist/{run-sugar-DveBlJqh.mjs → run-sugar-BdjKTPGO.mjs} +4 -4
  33. package/dist/{run-sugar-DveBlJqh.mjs.map → run-sugar-BdjKTPGO.mjs.map} +1 -1
  34. package/dist/runners/compound.mjs +2 -2
  35. package/dist/runners/connect.mjs +4 -4
  36. package/dist/runners/switchboard.d.mts +59 -0
  37. package/dist/runners/switchboard.d.mts.map +1 -1
  38. package/dist/runners/switchboard.mjs +49 -19
  39. package/dist/runners/switchboard.mjs.map +1 -1
  40. package/dist/{start-run-CASbiOWI.mjs → start-run-CmDxyMw0.mjs} +4 -4
  41. package/dist/{start-run-CASbiOWI.mjs.map → start-run-CmDxyMw0.mjs.map} +1 -1
  42. package/dist/switchboard-C5zgkRl2.mjs +4 -0
  43. package/dist/{switchboard-tQS3fhqa.mjs → switchboard-h4-XgP1h.mjs} +3 -6
  44. package/dist/switchboard-h4-XgP1h.mjs.map +1 -0
  45. package/dist/{switchboard-reset-CX_Lzw3O.mjs → switchboard-reset-MtTB_GAI.mjs} +7 -5
  46. package/dist/switchboard-reset-MtTB_GAI.mjs.map +1 -0
  47. package/dist/{vetra-BV5F0YeG.mjs → vetra-DPN1SpOC.mjs} +9 -9
  48. package/dist/vetra-DPN1SpOC.mjs.map +1 -0
  49. package/dist/{warn-subgraph-type-conflicts-Jd6SeN-M.mjs → warn-subgraph-type-conflicts-BOHBmThq.mjs} +5 -5
  50. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +1 -0
  51. package/package.json +15 -14
  52. package/dist/connect-build-xRrXk9-p.mjs.map +0 -1
  53. package/dist/connect-preview-BW6XnRtj.mjs.map +0 -1
  54. package/dist/generate-desktop-shell-itIzf77U.mjs.map +0 -1
  55. package/dist/host-schemas-CL_wFpY7-B_pY14Jy.mjs.map +0 -1
  56. package/dist/ph-cli-commands-NHDoX5i7.mjs +0 -4
  57. package/dist/switchboard-BUMqobK4.mjs +0 -4
  58. package/dist/switchboard-reset-CX_Lzw3O.mjs.map +0 -1
  59. package/dist/switchboard-tQS3fhqa.mjs.map +0 -1
  60. package/dist/vetra-BV5F0YeG.mjs.map +0 -1
  61. package/dist/warn-subgraph-type-conflicts-Jd6SeN-M.mjs.map +0 -1
@@ -1,15 +1,16 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1abb069a-9877-5068-9722-7112655b42d1")}catch(e){}}();
3
- import { a as mergeDefaultDrives, d as rebaseDriveUrl } from "./host-schemas-CL_wFpY7-B_pY14Jy.mjs";
4
- import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-DP5vRA7N.mjs";
5
- import { t as runConnectStudio } from "./connect-studio-8EyDblpG.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4b0fe58d-8fb7-57cc-945f-660a5bebebec")}catch(e){}}();
3
+ import { a as mergeDefaultDrives, d as rebaseDriveUrl } from "./host-schemas-CtPNRr5v-BQyKKFbS.mjs";
4
+ import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed } from "./cli-connect-override-Cf7WutqU.mjs";
5
+ import { t as runConnectStudio } from "./connect-studio-FEEyWfwB.mjs";
6
6
  import { a as generateProjectDriveId } from "./utils-CvmDmCVd.mjs";
7
- import { i as POWERHOUSE_DRIVE_ICON, r as startSwitchboard$1 } from "./switchboard-tQS3fhqa.mjs";
7
+ import { i as POWERHOUSE_DRIVE_ICON, r as startSwitchboard$1 } from "./switchboard-h4-XgP1h.mjs";
8
8
  import fs from "node:fs";
9
9
  import path, { join } from "node:path";
10
10
  import { execSync } from "node:child_process";
11
11
  import { blue, green, red, yellow } from "colorette";
12
12
  import { getConfig } from "@powerhousedao/shared/clis";
13
+ import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
13
14
  import { createLogger } from "vite";
14
15
  import { createVetraDocument, getVetraDocuments, setPackageGithubUrl } from "@powerhousedao/common/utils";
15
16
  import { isPortAvailable } from "@powerhousedao/switchboard/server";
@@ -257,9 +258,8 @@ async function resolveSwitchboardPort(requested) {
257
258
  }
258
259
  //#endregion
259
260
  //#region src/utils/vetra-runtime.ts
260
- const RECORD_REL = path.join(".ph", "vetra-runtime.json");
261
261
  const READY_TIMEOUT_MS = 2e3;
262
- const recordPath = (projectDir) => path.join(projectDir, RECORD_REL);
262
+ const recordPath = (projectDir) => path.join(resolvePhDir(projectDir), "vetra-runtime.json");
263
263
  function readVetraRuntime(projectDir) {
264
264
  try {
265
265
  return JSON.parse(fs.readFileSync(recordPath(projectDir), "utf8"));
@@ -610,5 +610,5 @@ async function startVetra(args) {
610
610
  //#endregion
611
611
  export { seedWorkflowsDrive, startVetra };
612
612
 
613
- //# sourceMappingURL=vetra-BV5F0YeG.mjs.map
614
- //# debugId=1abb069a-9877-5068-9722-7112655b42d1
613
+ //# sourceMappingURL=vetra-DPN1SpOC.mjs.map
614
+ //# debugId=4b0fe58d-8fb7-57cc-945f-660a5bebebec
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vetra-DPN1SpOC.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.ts","../src/utils/vetra-runtime.ts","../src/services/vetra.ts"],"sourcesContent":["import {\n createVetraDocument,\n getVetraDocuments,\n setPackageGithubUrl,\n} from \"@powerhousedao/common/utils\";\nimport { red } from \"colorette\";\nimport { execSync } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\n/**\n * Get git remote URL (origin)\n * @returns Git remote URL or null if not configured\n */\nfunction getGitRemoteUrl(): string | null {\n try {\n const url = execSync(\"git remote get-url origin\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n return url || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Prompt user to enter a custom GitHub URL\n */\nasync function promptForCustomUrl(): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(\"\\nEnter GitHub URL (or press Enter to skip): \");\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const url = answer.trim();\n resolve(url || null);\n });\n });\n}\n\n/**\n * Prompt yes/no question\n */\nasync function promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(`\\n${question} (y/n): `);\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const response = answer.trim().toLowerCase();\n resolve(response === \"y\" || response === \"yes\");\n });\n });\n}\n\n/**\n * Prompt user to select or enter GitHub URL\n * @param gitRemoteUrl - Git remote URL if available\n * @returns Selected URL or null if skipped\n */\nasync function promptForGithubUrl(\n gitRemoteUrl: string | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔍 Vetra Package Configuration\");\n console.log(\"=\".repeat(50));\n console.log(\n \"\\nWe detected a Vetra package document in your remote drive without a GitHub URL configured.\",\n );\n console.log(\"\\nWould you like to configure the GitHub URL now?\");\n\n if (gitRemoteUrl) {\n console.log(`\\nGit remote URL detected: ${gitRemoteUrl}`);\n console.log(\"\\nOptions:\");\n console.log(\"1. Use detected URL\");\n console.log(\"2. Enter a different URL\");\n console.log(\"3. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-3): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n resolve(gitRemoteUrl);\n } else if (choice === \"2\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"3\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-3): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n } else {\n console.log(\"\\nNo git remote URL detected.\");\n console.log(\"\\nOptions:\");\n console.log(\"1. Enter GitHub URL manually\");\n console.log(\"2. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-2): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"2\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-2): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n }\n });\n}\n\n/**\n * Set git remote URL (origin)\n */\nfunction setGitRemoteUrl(url: string): void {\n try {\n execSync(`git remote add origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin set to: ${url}`);\n } catch {\n try {\n execSync(`git remote set-url origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin updated to: ${url}`);\n } catch {\n console.error(red(`❌ Failed to set git remote URL`));\n }\n }\n}\n\n/**\n * Validates documents and returns the target document to use\n * Warns if multiple documents found\n */\nfunction validateAndSelectDocument<T>(documents: T[]): T | null {\n if (documents.length === 0) {\n return null;\n }\n\n if (documents.length > 1) {\n console.warn(\n `⚠️ Warning: Multiple Vetra documents found (${documents.length}). Using first document.`,\n );\n }\n\n return documents[0];\n}\n\nasync function applyGithubUrlConfiguration(\n graphqlEndpoint: string,\n vetraDriveId: string,\n documentId: string,\n selectedUrl: string,\n shouldSetRemote: boolean,\n): Promise<void> {\n // Set package GitHub URL\n await setPackageGithubUrl(\n graphqlEndpoint,\n vetraDriveId,\n documentId,\n selectedUrl,\n );\n\n console.log(`✅ GitHub URL configured: ${selectedUrl}`);\n\n // Set git remote URL if requested\n if (shouldSetRemote) {\n setGitRemoteUrl(selectedUrl);\n }\n}\n\nfunction logVerbose(message: string, verbose?: boolean): void {\n if (verbose) {\n console.log(message);\n }\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Configure GitHub URL for Vetra documents\n * @param switchboardPort - Port where switchboard is running\n * @param vetraDriveUrl - Remote drive URL\n * @param verbose - Enable verbose logging\n */\nexport async function configureVetraGithubUrl(\n switchboardPort: number,\n vetraDriveUrl: string,\n verbose?: boolean,\n): Promise<void> {\n logVerbose(\"Checking GitHub URL configuration...\", verbose);\n\n try {\n const graphqlEndpoint = `http://localhost:${switchboardPort}/graphql`;\n const vetraDriveId = vetraDriveUrl.split(\"/\").pop();\n if (!vetraDriveId) {\n throw new Error(\"Invalid vetraDriveUrl: unable to extract drive ID\");\n }\n\n const documents = await getVetraDocuments(graphqlEndpoint, vetraDriveId);\n\n // Skip if already configured\n if (documents.some((doc) => doc.githubUrl)) {\n logVerbose(\"GitHub URL already configured, skipping setup\", verbose);\n return;\n }\n\n // Get or create target document\n let targetDocumentId: string;\n const targetDocument = validateAndSelectDocument(documents);\n\n // Collect user input\n const gitRemoteUrl = getGitRemoteUrl();\n const selectedUrl = await promptForGithubUrl(gitRemoteUrl);\n\n if (!selectedUrl) {\n logVerbose(\"GitHub URL configuration skipped\", verbose);\n return;\n }\n\n let shouldSetRemote = false;\n if (selectedUrl !== gitRemoteUrl && !gitRemoteUrl) {\n shouldSetRemote = await promptYesNo(\"Set this as your git remote URL?\");\n }\n\n if (!targetDocument) {\n logVerbose(\"No Vetra documents found, creating new document...\", verbose);\n\n targetDocumentId = await createVetraDocument(\n graphqlEndpoint,\n vetraDriveId,\n \"vetra-package\",\n );\n\n logVerbose(`Created new document: ${targetDocumentId}`, verbose);\n } else {\n targetDocumentId = targetDocument.id;\n }\n\n await applyGithubUrlConfiguration(\n graphqlEndpoint,\n vetraDriveId,\n targetDocumentId,\n selectedUrl,\n shouldSetRemote,\n );\n } catch (error) {\n console.error(\n red(\n `⚠️ GitHub URL configuration failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n logVerbose(String(error), verbose);\n }\n}\n","import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport type VetraRuntimeRecord = {\n pid: number;\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n mcpUrl: string;\n startedAt: string;\n};\n\nexport type VetraProbe =\n | { status: \"none\" }\n | { status: \"stale\" }\n | { status: \"live\"; record: VetraRuntimeRecord }\n | { status: \"foreign\"; record: VetraRuntimeRecord };\n\nconst READY_TIMEOUT_MS = 2000;\n\n// Under the project's .ph tree — relocated with it by PH_USER_DATA_DIR.\nconst recordPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-runtime.json\");\n\nexport function readVetraRuntime(\n projectDir: string,\n): VetraRuntimeRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir), \"utf8\"),\n ) as VetraRuntimeRecord;\n } catch {\n // Missing or corrupt: either way there is no usable record.\n return undefined;\n }\n}\n\nexport function writeVetraRuntime(\n projectDir: string,\n record: VetraRuntimeRecord,\n): void {\n const target = recordPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\nexport function clearVetraRuntime(projectDir: string): void {\n try {\n fs.rmSync(recordPath(projectDir));\n } catch {\n // Already gone.\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nasync function isReady(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://localhost:${port}/ready`, {\n signal: AbortSignal.timeout(READY_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Decide whether the recorded instance is actually serving this project.\n *\n * All three checks are load-bearing. A pid can be reused by an unrelated\n * process, so a live pid proves nothing on its own. Another project's\n * switchboard would answer `/ready` on its own port, so a healthy `/ready`\n * proves nothing either. And the recorded `projectName` is what separates\n * \"my instance\" from \"someone else's instance that happens to hold this\n * port\" — which is precisely the confusion that let an agent write document\n * models into a different project's drive.\n *\n * A stale record is deleted so the next start is unblocked. A foreign one is\n * left alone: it describes something that is alive.\n */\nexport async function probeVetraRuntime(\n projectDir: string,\n projectName: string,\n): Promise<VetraProbe> {\n const record = readVetraRuntime(projectDir);\n if (!record) return { status: \"none\" };\n\n if (!isPidAlive(record.pid) || !(await isReady(record.switchboardPort))) {\n clearVetraRuntime(projectDir);\n return { status: \"stale\" };\n }\n\n if (record.projectName !== projectName) {\n return { status: \"foreign\", record };\n }\n return { status: \"live\", record };\n}\n\nconst MCP_FILES = [\".mcp.json\", path.join(\".cursor\", \"mcp.json\")];\n\n/**\n * Point every generated MCP config at `port`, returning the files changed.\n *\n * An MCP client resolves these files at session start and cannot read the\n * project config or `.env`, so when an override moves the port the literal\n * has to be corrected on disk. Rewrites in place rather than regenerating,\n * so any other servers or hand-added keys survive.\n */\nexport function syncMcpPort(projectDir: string, port: number): string[] {\n const changed: string[] = [];\n for (const rel of MCP_FILES) {\n const target = path.join(projectDir, rel);\n if (!fs.existsSync(target)) continue;\n\n let parsed: { mcpServers?: Record<string, { url?: string }> };\n try {\n parsed = JSON.parse(fs.readFileSync(target, \"utf8\")) as typeof parsed;\n } catch {\n // Hand-broken JSON is the author's to fix; don't clobber it.\n continue;\n }\n\n const server = parsed.mcpServers?.[\"reactor-mcp\"];\n if (!server?.url) continue;\n\n const wanted = `http://localhost:${port}/mcp`;\n if (server.url === wanted) continue;\n\n server.url = wanted;\n fs.writeFileSync(target, `${JSON.stringify(parsed, null, 2)}\\n`);\n changed.push(rel);\n }\n return changed;\n}\n","import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { join } from \"node:path\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport { generateProjectDriveId, POWERHOUSE_CONFIG_FILE } from \"../utils.js\";\nimport { wasFlagExplicitlyPassed } from \"../utils/cli-connect-override.js\";\nimport {\n configureVetraGithubUrl,\n sleep,\n} from \"../utils/configure-vetra-github-url.js\";\nimport { POWERHOUSE_DRIVE_ICON } from \"../utils/drive-icons.js\";\nimport { mergeDefaultDrives, rebaseDriveUrl } from \"@powerhousedao/host-core\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport {\n clearVetraRuntime,\n probeVetraRuntime,\n syncMcpPort,\n writeVetraRuntime,\n} from \"../utils/vetra-runtime.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport { startSwitchboard } from \"./switchboard.js\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\nconst getDriveId = (driveUrl: string | undefined): string =>\n driveUrl?.split(\"/\").pop() ?? generateProjectDriveId(VETRA_DRIVE_NAME);\n\n// rebaseDriveUrl moved to @powerhousedao/host-core (uniform-runners P1.4) —\n// one implementation shared by this classic path and the generic compound.\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\nasync function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: POWERHOUSE_DRIVE_ICON,\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, previewDrive, port);\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl;\n}\n\n// Opens in Workflow Studio; only seeded when the switchboard runs workflows.\n// Exported for the switchboard bridge runner: a hosts project with\n// reactor.workflows enabled seeds the SAME project-hashed drive this vetra\n// path does, until drive provisioning becomes a plugin contribution.\nexport async function seedWorkflowsDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string> {\n const workflowsDrive = {\n id: generateProjectDriveId(\"workflows\"),\n slug: \"workflows\",\n global: { name: \"Workflows\" },\n preferredEditor: \"workflow-studio\",\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, workflowsDrive, port);\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Workflows drive: ${driveUrl}`));\n }\n return driveUrl;\n}\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraProcessorConfig: VetraProcessorConfigType = {\n interactive,\n driveUrl: remoteDrive ?? getDefaultVetraUrl(connectPort),\n driveId: getDriveId(remoteDrive),\n };\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n let workflowsDriveUrl: string | null = null;\n if (switchboard.workflowsEnabled) {\n try {\n workflowsDriveUrl = await seedWorkflowsDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Started successfully`));\n if (remoteDrive) {\n console.log(\n blue(`Vetra Switchboard: Syncing with remote drive: ${remoteDrive}`),\n );\n }\n } else {\n console.log();\n console.log(\n blue(\n `Vetra Switchboard: http://localhost:${actualSwitchboardPort}/graphql`,\n ),\n );\n console.log(blue(` ➜ Drive URL: ${switchboard.defaultDriveUrl}`));\n if (previewDriveUrl) {\n console.log(blue(` ➜ Preview Drive URL: ${previewDriveUrl}`));\n }\n if (workflowsDriveUrl) {\n console.log(blue(` ➜ Workflows Drive URL: ${workflowsDriveUrl}`));\n }\n }\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n workflowsDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n // One Vetra per project. Two instances over one working tree would contend\n // for the same `.ph/read-model.db` and `.ph/reactor-storage`, and leave the\n // project with two drives that diverge.\n const projectDir = process.cwd();\n const { readPackageSync } = await import(\"read-pkg\");\n const projectName = readPackageSync({ cwd: projectDir }).name;\n const probe = await probeVetraRuntime(projectDir, projectName);\n\n if (probe.status === \"live\") {\n console.log();\n console.log(green(\"Vetra is already running for this project.\"));\n console.log(\n green(` ➜ Connect: http://localhost:${probe.record.connectPort}`),\n );\n console.log(\n green(\n ` ➜ Switchboard: http://localhost:${probe.record.switchboardPort}/graphql`,\n ),\n );\n console.log(\n `Stop that instance (pid ${probe.record.pid}) if you need to restart it.`,\n );\n return;\n }\n\n if (probe.status === \"foreign\") {\n console.error(\n red(\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`,\n ),\n );\n process.exit(1);\n }\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const workflowsDriveUrl = switchboardResult.workflowsDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Record what we actually bound, so a second `ph vetra` can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n writeVetraRuntime(projectDir, {\n pid: process.pid,\n projectName,\n switchboardPort: actualSwitchboardPort,\n connectPort,\n mcpUrl: `http://localhost:${actualSwitchboardPort}/mcp`,\n startedAt: new Date().toISOString(),\n });\n const releaseRuntimeRecord = () => clearVetraRuntime(projectDir);\n process.on(\"exit\", releaseRuntimeRecord);\n process.on(\"SIGINT\", () => {\n releaseRuntimeRecord();\n process.exit(130);\n });\n process.on(\"SIGTERM\", () => {\n releaseRuntimeRecord();\n process.exit(143);\n });\n\n // An MCP client resolved `.mcp.json` before this process started and\n // cannot re-read it, so a drifted literal means the agent is pointed at\n // the wrong port — possibly another project's reactor. Correct the file\n // and say so plainly; we cannot fix the already-open client ourselves.\n const driftedMcpFiles = syncMcpPort(projectDir, actualSwitchboardPort);\n if (driftedMcpFiles.length > 0) {\n console.log(\n yellow(\n `Updated ${driftedMcpFiles.join(\" and \")} to port ${actualSwitchboardPort}. ` +\n `Reconnect your MCP client (/mcp) to pick it up. ` +\n `This edit is local — do not commit it.`,\n ),\n );\n }\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n // give some time for the drive to process initial strands\n await sleep(3000);\n\n await configureVetraGithubUrl(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n\n // give some time for the user to read log messages\n await sleep(2000);\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const browserWorkflowsDriveUrl =\n workflowsDriveUrl && publicBase\n ? rebaseDriveUrl(workflowsDriveUrl, publicBase)\n : workflowsDriveUrl;\n\n // The resolved default-drive list: vetra's own drives first (the\n // Vetra drive, the preview drive in watch mode, and the Workflows\n // drive when workflows are on), then the\n // project's configured `connect.drives.defaultDrives` from\n // powerhouse.config.json (issue #3023). A drive vetra also starts is\n // listed only once. An explicit `--default-drives-url` is appended on\n // top of this list by buildStudioConnectOverride — it never replaces\n // the vetra drives.\n const vetraDriveEntries = [\n ...(browserDriveUrl\n ? [{ url: browserDriveUrl, name: null, icon: null }]\n : []),\n ...(browserPreviewDriveUrl\n ? [{ url: browserPreviewDriveUrl, name: null, icon: null }]\n : []),\n ...(browserWorkflowsDriveUrl\n ? [{ url: browserWorkflowsDriveUrl, name: null, icon: null }]\n : []),\n ];\n const configuredDefaultDrives =\n getConfig(join(projectDir, POWERHOUSE_CONFIG_FILE)).connect?.drives\n ?.defaultDrives ?? [];\n const resolvedDefaultDrives = mergeDefaultDrives(\n vetraDriveEntries,\n configuredDefaultDrives,\n );\n\n if (verbose) {\n console.log(\"Starting Connect...\");\n // Mirror buildStudioConnectOverride: an explicit\n // --default-drives-url is appended to the resolved list.\n const flagDefaultDrives = wasFlagExplicitlyPassed(\"default-drives-url\")\n ? parseDefaultDrivesUrl(args.defaultDrivesUrl ?? \"\")\n : [];\n const printedDefaultDrives = mergeDefaultDrives(\n resolvedDefaultDrives,\n flagDefaultDrives,\n );\n console.log(\n ` ➜ Connect will use default drives: ${printedDefaultDrives\n .map((d) => (\"url\" in d ? d.url : `local:${d.id}`))\n .join(\", \")}`,\n );\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n const vetraDrivesOverride = {\n drives: {\n defaultDrives: resolvedDefaultDrives,\n preserveStrategy: \"preserve-all\" as const,\n },\n };\n\n await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n );\n }\n } catch (error) {\n console.error(error);\n }\n}\n"],"names":["startSwitchboard"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,kBAAiC;CACxC,IAAI;EAKF,OAJY,SAAS,6BAA6B;GAChD,UAAU;GACV,OAAO;IAAC;IAAQ;IAAQ;GAAM;EAChC,CAAC,CAAC,CAAC,KACM,KAAK;CAChB,QAAQ;EACN,OAAO;CACT;AACF;;;;AAKA,eAAe,qBAA6C;CAC1D,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,KAAK,gBAAgB;GACzB,OAAO,QAAQ;GACf,QAAQ,QAAQ;EAClB,CAAC;EAED,QAAQ,OAAO,MAAM,+CAA+C;EAEpE,GAAG,GAAG,SAAS,WAAmB;GAChC,GAAG,MAAM;GAET,QADY,OAAO,KACT,KAAK,IAAI;EACrB,CAAC;CACH,CAAC;AACH;;;;AAKA,eAAe,YAAY,UAAoC;CAC7D,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,KAAK,gBAAgB;GACzB,OAAO,QAAQ;GACf,QAAQ,QAAQ;EAClB,CAAC;EAED,QAAQ,OAAO,MAAM,KAAK,SAAS,SAAS;EAE5C,GAAG,GAAG,SAAS,WAAmB;GAChC,GAAG,MAAM;GACT,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,YAAY;GAC3C,QAAQ,aAAa,OAAO,aAAa,KAAK;EAChD,CAAC;CACH,CAAC;AACH;;;;;;AAOA,eAAe,mBACb,cACw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B,aACjB,eAAe,mBAAmB,UAAU,IAC5C;GAUN,MAAM,oBAAoB;IACxB,GAAI,kBACA,CAAC;KAAE,KAAK;KAAiB,MAAM;KAAM,MAAM;IAAK,CAAC,IACjD,CAAC;IACL,GAAI,yBACA,CAAC;KAAE,KAAK;KAAwB,MAAM;KAAM,MAAM;IAAK,CAAC,IACxD,CAAC;IACL,GAAI,2BACA,CAAC;KAAE,KAAK;KAA0B,MAAM;KAAM,MAAM;IAAK,CAAC,IAC1D,CAAC;GACP;GACA,MAAM,0BACJ,UAAU,KAAK,YAAA,wBAAkC,CAAC,CAAC,CAAC,SAAS,QACzD,iBAAiB,CAAC;GACxB,MAAM,wBAAwB,mBAC5B,mBACA,uBACF;GAEA,IAAI,SAAS;IACX,QAAQ,IAAI,qBAAqB;IAGjC,MAAM,oBAAoB,wBAAwB,oBAAoB,IAClE,sBAAsB,KAAK,oBAAoB,EAAE,IACjD,CAAC;IACL,MAAM,uBAAuB,mBAC3B,uBACA,iBACF;IACA,QAAQ,IACN,yCAAyC,qBACtC,KAAK,MAAO,SAAS,IAAI,EAAE,MAAM,SAAS,EAAE,IAAK,CAAC,CAClD,KAAK,IAAI,GACd;GACF;GACA,QAAQ,IAAI;GACZ,QAAQ,IAAI,MAAM,mCAAmC,aAAa,CAAC;GAEnE,MAAM,mBAAmB,iBAAiB,KAAK;GAQ/C,MAAM,sBAAsB,EAC1B,QAAQ;IACN,eAAe;IACf,kBAAkB;GACpB,EACF;GAEA,MAAM,iBACJ;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;GAChB,GACA,kBACA,mBACF;EACF;CACF,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AACF","debug_id":"4b0fe58d-8fb7-57cc-945f-660a5bebebec"}
@@ -1,11 +1,11 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2ed24f09-ce4a-5883-ac4b-8933dd549150")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8f90996d-2865-5564-b0aa-35c99867095d")}catch(e){}}();
3
3
  import { lintSubgraphTypes } from "@powerhousedao/vetra/codegen";
4
4
  //#region src/utils/warn-subgraph-type-conflicts.ts
5
- function warnSubgraphTypeConflicts(projectDir) {
5
+ async function warnSubgraphTypeConflicts(projectDir) {
6
6
  let warnings;
7
7
  try {
8
- warnings = lintSubgraphTypes(projectDir);
8
+ warnings = await lintSubgraphTypes(projectDir);
9
9
  } catch (error) {
10
10
  console.warn("⚠ Failed to check subgraph type names:", error);
11
11
  return;
@@ -15,5 +15,5 @@ function warnSubgraphTypeConflicts(projectDir) {
15
15
  //#endregion
16
16
  export { warnSubgraphTypeConflicts as t };
17
17
 
18
- //# sourceMappingURL=warn-subgraph-type-conflicts-Jd6SeN-M.mjs.map
19
- //# debugId=2ed24f09-ce4a-5883-ac4b-8933dd549150
18
+ //# sourceMappingURL=warn-subgraph-type-conflicts-BOHBmThq.mjs.map
19
+ //# debugId=8f90996d-2865-5564-b0aa-35c99867095d
@@ -0,0 +1 @@
1
+ {"version":3,"file":"warn-subgraph-type-conflicts-BOHBmThq.mjs","sources":["../src/utils/warn-subgraph-type-conflicts.ts"],"sourcesContent":["import { lintSubgraphTypes } from \"@powerhousedao/vetra/codegen\";\n\nexport async function warnSubgraphTypeConflicts(\n projectDir: string,\n): Promise<void> {\n let warnings: string[];\n try {\n warnings = await lintSubgraphTypes(projectDir);\n } catch (error) {\n console.warn(\"⚠ Failed to check subgraph type names:\", error);\n return;\n }\n for (const warning of warnings) console.warn(`⚠ ${warning}`);\n}\n"],"names":[],"mappings":";;;;AAEA,eAAsB,0BACpB,YACe;CACf,IAAI;CACJ,IAAI;EACF,WAAW,MAAM,kBAAkB,UAAU;CAC/C,SAAS,OAAO;EACd,QAAQ,KAAK,0CAA0C,KAAK;EAC5D;CACF;CACA,KAAK,MAAM,WAAW,UAAU,QAAQ,KAAK,KAAK,SAAS;AAC7D","debug_id":"8f90996d-2865-5564-b0aa-35c99867095d"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/ph-cli",
3
- "version": "6.2.3-dev.62",
3
+ "version": "6.2.3-dev.64",
4
4
  "description": "",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -44,15 +44,15 @@
44
44
  "keywords": [],
45
45
  "author": "",
46
46
  "dependencies": {
47
- "@powerhousedao/builder-tools": "6.2.3-dev.62",
48
- "@powerhousedao/codegen": "6.2.3-dev.62",
49
- "@powerhousedao/common": "6.2.3-dev.62",
50
- "@powerhousedao/config": "6.2.3-dev.62",
51
- "@powerhousedao/reactor": "6.2.3-dev.62",
52
- "@powerhousedao/shared": "6.2.3-dev.62",
53
- "@powerhousedao/switchboard": "6.2.3-dev.62",
54
- "@powerhousedao/vetra": "6.2.3-dev.62",
55
- "@renown/sdk": "6.2.3-dev.62",
47
+ "@powerhousedao/builder-tools": "6.2.3-dev.64",
48
+ "@powerhousedao/codegen": "6.2.3-dev.64",
49
+ "@powerhousedao/common": "6.2.3-dev.64",
50
+ "@powerhousedao/config": "6.2.3-dev.64",
51
+ "@powerhousedao/reactor": "6.2.3-dev.64",
52
+ "@powerhousedao/shared": "6.2.3-dev.64",
53
+ "@powerhousedao/switchboard": "6.2.3-dev.64",
54
+ "@powerhousedao/vetra": "6.2.3-dev.64",
55
+ "@renown/sdk": "6.2.3-dev.64",
56
56
  "@sentry/node-core": "^10.52.0",
57
57
  "@tsdown/css": "0.23.0",
58
58
  "@vercel/nft": "^1.11.0",
@@ -61,7 +61,7 @@
61
61
  "change-case": "5.4.4",
62
62
  "cmd-ts": "0.15.0",
63
63
  "colorette": "2.0.20",
64
- "document-model": "6.2.3-dev.62",
64
+ "document-model": "6.2.3-dev.64",
65
65
  "enquirer": "2.4.1",
66
66
  "kysely": "0.28.16",
67
67
  "package-manager-detector": "1.6.0",
@@ -70,8 +70,9 @@
70
70
  "remeda": "2.33.7",
71
71
  "rolldown": "1.2.9",
72
72
  "semver": "7.7.4",
73
+ "sirv": "^3.0.2",
73
74
  "tsdown": "0.23.0",
74
- "vite": "8.3.0"
75
+ "vite": "8.3.4"
75
76
  },
76
77
  "devDependencies": {
77
78
  "@types/node": "25.2.3",
@@ -81,8 +82,8 @@
81
82
  "ts-morph": "27.0.2",
82
83
  "write-package": "7.2.0",
83
84
  "zod": "^4.5.4",
84
- "@powerhousedao/desktop": "6.2.3-dev.62",
85
- "@powerhousedao/host-core": "6.2.3-dev.62"
85
+ "@powerhousedao/desktop": "6.2.3-dev.64",
86
+ "@powerhousedao/host-core": "6.2.3-dev.64"
86
87
  },
87
88
  "scripts": {
88
89
  "tsc": "tsc",
@@ -1 +0,0 @@
1
- {"version":3,"file":"connect-build-xRrXk9-p.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\n directoryContentDigest,\n findPackageRoot,\n getConnectBaseViteConfig,\n missingVendorEntries,\n prebuildConnectVendor,\n ownProjectPackage,\n prebuildReactorWorker,\n prebuildWorkerPackages,\n resolveReactorWorkerSource,\n type PrebuiltReactorWorker,\n type PrebuiltVendor,\n} from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n normalizeBasePath,\n SHARED_DEP_SPECIFIERS,\n SHARED_SUBPATHS,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { InlineConfig } from \"vite\";\nimport { build, mergeConfig } from \"vite\";\nimport type { ConnectBuildArgs } from \"../types.js\";\nimport { buildCliConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(args: ConnectBuildArgs) {\n const { outDir, debug, dynamicBase, favicon } = args;\n\n const mode = \"production\";\n const dirname = process.cwd();\n\n // Build has no read mode; a bare positional `<key>` is a user error. The\n // 2-positional `<key> <value>` form is handled inside buildCliConnectOverride\n // so it layers on top of --json + flags like any other override input.\n if (args.keyPositional !== undefined && args.valuePositional === undefined) {\n throw new Error(\n \"ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.\",\n );\n }\n\n // Fail fast if any package marked as provider: \"local\" is missing from\n // node_modules — the Vite plugin that bundles them needs them on disk.\n assertLocalPackagesInstalled(dirname);\n\n // Build the CLI override layers (--json + individual flags + positional)\n // once here so a bad payload fails before we waste a build.\n // `--packages-registry` lands at the top-level `packageRegistryUrl`\n // (mirrors source-config shape); every other flag feeds the connect-block\n // precedence ladder.\n const { connectOverride, packageRegistryUrl } = buildCliConnectOverride(args);\n\n await runBuild({\n outDir: \"dist\",\n debug,\n // Local packages built for Connect share deps with the app vendor, same\n // as a plain `ph build`.\n noSharedDeps: false,\n ignoreTypeErrors: false,\n });\n\n // Production shared-dependency vendor: prebuilt into <outDir>/__vendor__\n // before the app build. On by default; PH_CONNECT_VENDOR=0|false disables\n // it. A failed prebuild fails the build — production must not ship import\n // map entries pointing at a vendor that was never built (the dev server\n // keeps its own soft fallback in the dev plugin).\n const outDirAbs = resolve(dirname, outDir);\n let vendor: PrebuiltVendor | null = null;\n // The deploy base the vendor's import-map addresses are written against.\n // Only meaningful when the vendor is built; \"/\" is the inert default.\n let appBase = \"/\";\n // The prebuild out dirs' parent must exist before the prebuilds: their\n // build locks are siblings of the out dirs, and the package build\n // (runBuild) writes to a different out dir, so nothing else creates it yet.\n mkdirSync(outDirAbs, { recursive: true });\n if (isVendorEnabled()) {\n const errorRef: { message?: string } = {};\n // The same base string the app build uses below: the dynamic-base\n // placeholder, or the normalized deploy base (CLI override wins over the\n // source config). The vendor worker appends its own segment.\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const connectBasePath =\n connectOverride?.app?.basePath ?? phConfig.connect?.app?.basePath;\n appBase = dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : \"/\";\n vendor = await prebuildConnectVendor({\n dirname,\n include: productionVendorInclude(),\n vendorDir: join(outDirAbs, \"__vendor__\"),\n base: appBase,\n nodeEnv: \"production\",\n errorRef,\n ...connectOwnVendorDeps(dirname),\n });\n if (!vendor) {\n console.error(\n `ph connect build: the shared-dependency vendor failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`,\n );\n throw new Error(\"shared-dependency vendor prebuild failed\");\n }\n }\n\n // Reactor SharedWorker bundle: the dist worker is a library artifact whose\n // bare imports no worker can resolve (import maps do not apply to workers),\n // so the deployable form is prebuilt here. With a vendor, its shared deps\n // are externalized onto ../__vendor__/ so page and worker share one cache\n // entry per dep; without one it is fully self-contained.\n const reactorWorker = await prebuildReactorWorkerBundle(\n dirname,\n outDirAbs,\n vendor,\n connectOverride,\n );\n\n // Local project models the worker cannot get from the registry, built into\n // the worker bundle's own directory so they share its vendor.\n if (reactorWorker) {\n await prebuildLocalWorkerPackages(\n dirname,\n outDirAbs,\n vendor,\n reactorWorker.vendorImports,\n );\n }\n\n const keepDirs = [\n ...(vendor ? [\"__vendor__\"] : []),\n ...(reactorWorker ? [\"__reactor_worker__\"] : []),\n ];\n // Stale top-level output goes, the prebuilt dirs stay: the app build below\n // runs with emptyOutDir: false and must not wipe them.\n if (keepDirs.length > 0) {\n cleanDistExcept(outDirAbs, keepDirs);\n }\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n // Vendor import-map entries are relative (leading slash stripped) so\n // they resolve against the page URL under any deploy base — root or\n // subpath, dynamic or concrete.\n vendor: vendor\n ? {\n imports: vendorImportMapEntries(vendor.imports, appBase),\n versions: vendor.versions,\n sharedDeps: vendorImportMapEntries(\n { sharedDeps: vendor.sharedDeps },\n appBase,\n ).sharedDeps,\n }\n : undefined,\n reactorWorkerVersion: reactorWorker\n ? directoryContentDigest(join(outDirAbs, \"__reactor_worker__\"))\n : undefined,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n // The vendor / worker dirs were prebuilt into the out dir above; the\n // build must not empty them.\n ...(keepDirs.length > 0 ? { emptyOutDir: false } : {}),\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n\n // Last word on the shipped artifact: every specifier the page's import map\n // publishes must have a file next to it. The prebuild verifies its own\n // output, but it can return a cache hit it never rebuilt, and both the\n // stale-output clean and the app build run afterwards. An entry with no\n // file behind it ships as a URL that 404s, and a SPA answers that with\n // index.html — so the browser reports only an opaque MIME-type error with\n // no filename. Fail here instead, naming the entries.\n if (vendor) {\n const unbacked = missingVendorEntries(\n join(outDirAbs, \"__vendor__\"),\n vendor.imports,\n );\n if (unbacked.length > 0) {\n throw new Error(\n `ph connect build: the shared-dependency vendor is missing ` +\n `${unbacked.length} of the ${Object.keys(vendor.imports).length} ` +\n `entries its import map publishes:\\n` +\n unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join(\"\\n\"),\n );\n }\n }\n}\n\n/**\n * The specifier set the production vendor bundles: the dev-proven heavy set\n * ∪ the package-shared set — everything the app and loaded packages\n * externalize onto the vendor.\n *\n * Two specifiers are deliberately dropped:\n *\n * - `@powerhousedao/connect`. It is in DEFAULT_VENDOR_INCLUDE because the dev\n * server vendors the app to keep rebuilds cheap, but in a production build\n * the app *is* Connect: `SHARED_DEP_SPECIFIERS` omits it, so the app build\n * never externalizes it and nothing would ever resolve its import-map\n * entry. Vendoring it is not merely dead weight — bundling Connect's dist\n * for the browser pulls in its node-only `@powerhousedao/config/node`\n * import, and so `read-pkg` -> `unicorn-magic`, whose browser entry has no\n * `toPath`. That fails the vendor build, and a failed prebuild fails\n * `ph connect build`.\n * - the bare `@powerhousedao/shared` root, whose barrel likewise reaches\n * node-only modules. Its browser-safe subpaths (SHARED_SUBPATHS) are\n * listed instead; a package importing the bare root bundles its own copy.\n */\nexport function productionVendorInclude(): string[] {\n return [\n ...new Set([\n ...DEFAULT_VENDOR_INCLUDE.filter((s) => s !== \"@powerhousedao/connect\"),\n ...SHARED_DEP_SPECIFIERS.filter((s) => s !== \"@powerhousedao/shared\"),\n ...SHARED_SUBPATHS.map((s) => `@powerhousedao/shared/${s}`),\n // Connect imports these roots too; unvendored, the app re-bundles their shared chunks.\n \"@powerhousedao/design-system\",\n \"@powerhousedao/reactor\",\n ]),\n ];\n}\n\n/** Connect's own deps that vendored packages also bundle; projects don't install them. */\nexport const CONNECT_OWN_VENDOR_DEPS = [\n \"kysely\",\n \"tailwind-merge\",\n \"@renown/sdk\",\n \"@renown/sdk/crypto\",\n \"@renown/sdk/trust\",\n \"@powerhousedao/reactor-attachments/client\",\n];\n\nexport function connectOwnVendorDeps(dirname: string): {\n ownDeps?: { specs: string[]; from: string };\n} {\n const from = findPackageRoot(dirname, \"@powerhousedao/connect\");\n return from ? { ownDeps: { specs: CONNECT_OWN_VENDOR_DEPS, from } } : {};\n}\n\n/**\n * Turn the vendor's base-less URLs (`/__vendor__/x.js`) into the addresses\n * the page's import map ships, by prefixing the deploy base.\n *\n * An import map *address* must be a URL or begin with `/`, `./` or `../`;\n * anything else is a bare specifier, which the browser rejects — it drops the\n * entry, resolves the specifier to null, and every shared import then fails\n * with \"blocked by a null value\". So the base is applied rather than the\n * leading slash stripped: a root-relative address is both valid and correct\n * under a subpath deploy, and a dynamic-base build keeps its placeholder for\n * the serving proxy to substitute (the dynamic-base plugin leaves HTML\n * tokens alone by design).\n */\nexport function vendorImportMapEntries(\n imports: Record<string, string>,\n appBase: string,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(imports).map(([spec, url]) => [\n spec,\n `${appBase}/${url}`.replace(/\\/{2,}/g, \"/\"),\n ]),\n );\n}\n\n/**\n * The production vendor prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_VENDOR=0 or false.\n */\nexport function isVendorEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const raw = env.PH_CONNECT_VENDOR ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * The reactor worker bundle prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_REACTOR_WORKER=0 or false. It is built even when\n * `connect.instance.reactorWorker` is off, because the `?reactorWorker=true`\n * runtime override can enable the feature on a flag-off deployment.\n */\nexport function isReactorWorkerBundleEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_REACTOR_WORKER ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * Prebuild the reactor SharedWorker bundle into `<dist>/__reactor_worker__`.\n * Returns null when the prebuild is disabled, the installed Connect ships no\n * worker entry, or the build fails. A failure only fails `ph connect build`\n * when the project explicitly enables `connect.instance.reactorWorker` —\n * otherwise the feature degrades to unavailable and the build goes on.\n */\nasync function prebuildReactorWorkerBundle(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n connectOverride: PHConnectRuntimeConfig | undefined,\n): Promise<PrebuiltReactorWorker | null> {\n if (!isReactorWorkerBundleEnabled()) return null;\n if (!resolveReactorWorkerSource(dirname)) return null;\n\n const errorRef: { message?: string } = {};\n const bundle = await prebuildReactorWorker({\n dirname,\n outDir: join(outDirAbs, \"__reactor_worker__\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n nodeEnv: \"production\",\n errorRef,\n });\n if (bundle) return bundle;\n\n const message = `ph connect build: the reactor worker bundle failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`;\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const required =\n connectOverride?.instance?.reactorWorker ??\n phConfig.connect?.instance?.reactorWorker ??\n false;\n if (required) {\n throw new Error(message);\n }\n console.warn(\n `${message}\\nThe reactorWorker feature will be unavailable in this build.`,\n );\n return null;\n}\n\n/**\n * Build the project's `provider: \"local\"` packages into worker-loadable model\n * bundles beside the worker. A failure is a warning, not a build failure: the\n * worker still runs, and documents of registry types still work - only the\n * project's own types would be unavailable in worker mode.\n */\nasync function prebuildLocalWorkerPackages(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n safeVendorImports: Record<string, string>,\n): Promise<void> {\n const config = getConfig(join(dirname, \"powerhouse.config.json\"));\n const configured = (config.packages ?? [])\n .filter((p) => p.provider === \"local\")\n .map((p) => p.packageName);\n // The project itself is a local package in all but name: a vetra project\n // declares no entry for itself, and its models are the ones the worker\n // cannot otherwise get.\n const own = ownProjectPackage(dirname);\n const localPackages = [...new Set([...configured, ...(own ? [own] : [])])];\n\n const errorRef: { message?: string } = {};\n const built = await prebuildWorkerPackages({\n dirname,\n packages: localPackages,\n outDir: join(outDirAbs, \"__reactor_worker__\", \"packages\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n safeVendorImports,\n nodeEnv: \"production\",\n errorRef,\n });\n if (!built) {\n console.warn(\n `ph connect build: the reactor worker's local package bundles failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }\\nDocuments of this project's own types will not load in worker mode.`,\n );\n }\n}\n\n/**\n * Remove every top-level entry of `dist` except the kept names. Used between\n * the vendor prebuild and the app build so stale app output goes but the\n * just-built vendor stays (the build then runs with emptyOutDir: false).\n * Returns the number of entries removed.\n */\nexport function cleanDistExcept(dist: string, keep: string[] = []): number {\n if (!existsSync(dist)) return 0;\n let removed = 0;\n for (const entry of readdirSync(dist)) {\n if (keep.includes(entry)) continue;\n rmSync(join(dist, entry), { recursive: true, force: true });\n removed += 1;\n }\n return removed;\n}\n\nfunction assertLocalPackagesInstalled(projectPath: string) {\n const config = getConfig(join(projectPath, \"powerhouse.config.json\"));\n const localPackages = (config.packages ?? []).filter(\n (p) => p.provider === \"local\",\n );\n if (localPackages.length === 0) return;\n\n const missing = localPackages.filter(\n (p) =>\n !existsSync(\n join(projectPath, \"node_modules\", p.packageName, \"package.json\"),\n ),\n );\n if (missing.length === 0) return;\n\n const names = missing.map((p) => p.packageName);\n throw new Error(\n `ph connect build requires these packages to be installed in node_modules (they are declared with provider: \"local\" in powerhouse.config.json):\\n` +\n names.map((n) => ` - ${n}`).join(\"\\n\") +\n `\\n\\nInstall them with:\\n ph install --local ${names.join(\" \")}`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;AA8BA,eAAsB,gBAAgB,MAAwB;CAC5D,MAAM,EAAE,QAAQ,OAAO,aAAa,YAAY;CAEhD,MAAM,OAAO;CACb,MAAM,UAAU,QAAQ,IAAI;CAK5B,IAAI,KAAK,kBAAkB,KAAA,KAAa,KAAK,oBAAoB,KAAA,GAC/D,MAAM,IAAI,MACR,4LACF;CAKF,6BAA6B,OAAO;CAOpC,MAAM,EAAE,iBAAiB,uBAAuB,wBAAwB,IAAI;CAE5E,MAAM,SAAS;EACb,QAAQ;EACR;EAGA,cAAc;EACd,kBAAkB;CACpB,CAAC;CAOD,MAAM,YAAY,QAAQ,SAAS,MAAM;CACzC,IAAI,SAAgC;CAGpC,IAAI,UAAU;CAId,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CACxC,IAAI,gBAAgB,GAAG;EACrB,MAAM,WAAiC,CAAC;EAIxC,MAAM,WAAW,UAAU,KAAK,SAAS,wBAAwB,CAAC;EAClE,MAAM,kBACJ,iBAAiB,KAAK,YAAY,SAAS,SAAS,KAAK;EAC3D,UAAU,cACN,2BACA,kBACE,kBAAkB,eAAe,IACjC;EACN,SAA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AC1B,OAAO,KAAK,MAAM,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EAC1D,WAAW;CACb;CACA,OAAO;AACT;AAEA,SAAS,6BAA6B,aAAqB;CAEzD,MAAM,iBADS,UAAU,KAAK,aAAa,wBAAwB,CACvC,CAAC,CAAC,YAAY,CAAC,EAAA,CAAG,QAC3C,MAAM,EAAE,aAAa,OACxB;CACA,IAAI,cAAc,WAAW,GAAG;CAEhC,MAAM,UAAU,cAAc,QAC3B,MACC,CAAC,WACC,KAAK,aAAa,gBAAgB,EAAE,aAAa,cAAc,CACjE,CACJ;CACA,IAAI,QAAQ,WAAW,GAAG;CAE1B,MAAM,QAAQ,QAAQ,KAAK,MAAM,EAAE,WAAW;CAC9C,MAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,IAAI,IACtC,gDAAgD,MAAM,KAAK,GAAG,GAClE;AACF","debug_id":"f9aa4e87-ba42-5b5e-b2f1-fb0305bdaf57"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"connect-preview-BW6XnRtj.mjs","sources":["../src/services/connect-preview.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { deepMerge, normalizeBasePath } from \"@powerhousedao/shared/connect\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { InlineConfig, Plugin } from \"vite\";\nimport { mergeConfig, preview } from \"vite\";\nimport type { ConnectPreviewArgs } from \"../types.js\";\n\n/**\n * Runtime shaping for a served (built) Connect, desktop shape: the compound\n * projects the live switchboard's drive into the connect member's config, and\n * this override makes the STATIC dist serve it — the built\n * powerhouse.config.json is baked, so without this the drive injection never\n * reaches the SPA. `cspRegistrySync` additionally patches the baked CSP's\n * script-src with the runtime registry (the build bakes the CSP for the\n * registry it was built against; setting the registry at run time breaks that\n * coupling and every package import gets blocked otherwise).\n */\nexport interface ConnectServeOverride {\n connect?: PHConnectRuntimeConfig;\n cspRegistrySync?: boolean;\n /** Overrides the baked top-level packageRegistryUrl in the served config. */\n packageRegistryUrl?: string;\n}\n\n/**\n * The env contract a supervisor can drive the preview with — the same\n * variables the Docker entrypoint and clint's service manager already speak:\n * PH_CONNECT_DEFAULT_DRIVES_URL (comma-separated drive urls, injected into\n * drives.defaultDrives), PH_CONNECT_DRIVES_PRESERVE_STRATEGY, and\n * PH_CONNECT_PACKAGES_REGISTRY (runtime registry: served config + baked-CSP\n * patch). Lets `ph connect preview` replace hand-rolled static servers\n * (clint's connect-server, the ph-win sidecar) without losing injection.\n */\nexport function overrideFromEnv(\n env: Record<string, string | undefined> = process.env,\n): ConnectServeOverride | undefined {\n const drivesUrl = env.PH_CONNECT_DEFAULT_DRIVES_URL;\n const registry = env.PH_CONNECT_PACKAGES_REGISTRY;\n if (!drivesUrl && !registry) return undefined;\n const override: ConnectServeOverride = {};\n if (drivesUrl) {\n override.connect = {\n drives: {\n defaultDrives: drivesUrl\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((url) => ({ url, name: null, icon: null })),\n preserveStrategy:\n env.PH_CONNECT_DRIVES_PRESERVE_STRATEGY ?? \"preserve-all\",\n },\n } as PHConnectRuntimeConfig;\n }\n if (registry) {\n override.packageRegistryUrl = registry;\n override.cspRegistrySync = true;\n }\n return override;\n}\n\nfunction mergedConfigBody(\n outDir: string,\n override: ConnectServeOverride,\n): string {\n const file = path.join(outDir, \"powerhouse.config.json\");\n const baked = existsSync(file)\n ? (JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>)\n : {};\n const connect = override.connect\n ? deepMerge(\n (baked.connect ?? {}) as PHConnectRuntimeConfig,\n override.connect,\n )\n : baked.connect;\n return JSON.stringify({\n ...baked,\n connect,\n ...(override.packageRegistryUrl\n ? { packageRegistryUrl: override.packageRegistryUrl }\n : {}),\n });\n}\n\n/**\n * Append the registry origin to the baked CSP's script-src. The attribute\n * value is HTML-escaped (every CSP keyword is `&#39;`-quoted, which contains a\n * semicolon), so decode before touching directives and re-escape after —\n * ported from the ph-win-desktop sidecar, which this path replaces.\n */\nexport function patchCspScriptSrc(html: string, registryUrl: string): string {\n return html.replace(\n /(<meta\\s+http-equiv=\"Content-Security-Policy\"\\s+content=\")([^\"]*)(\")/i,\n (_match, open: string, escaped: string, close: string) => {\n const policy = escaped.replace(/&amp;/g, \"&\").replace(/&#39;/g, \"'\");\n if (policy.includes(registryUrl)) return open + escaped + close;\n const patched = policy.replace(\n /script-src\\s+([^;]*)/i,\n (_directive, sources: string) =>\n `script-src ${sources.trim()} ${registryUrl}`,\n );\n const reEscaped = patched.replace(/&/g, \"&amp;\").replace(/'/g, \"&#39;\");\n return open + reEscaped + close;\n },\n );\n}\n\n// The serve base: an explicit `--base`, else the basePath the dist was built with.\nexport function resolvePreviewBase(\n argBase: string | undefined,\n outDirAbs: string,\n): string | undefined {\n if (argBase && argBase !== \"/\") return normalizeBasePath(argBase);\n try {\n const built = JSON.parse(\n readFileSync(path.join(outDirAbs, \"powerhouse.config.json\"), \"utf8\"),\n ) as { connect?: { app?: { basePath?: unknown } } };\n const basePath = built.connect?.app?.basePath;\n if (typeof basePath === \"string\" && basePath) {\n return normalizeBasePath(basePath);\n }\n } catch {\n // no readable dist config\n }\n return undefined;\n}\n\n// `pathname` relative to the deploy base (\"/\" + rest), or itself when outside it.\nexport function stripBase(pathname: string, base: string): string {\n return base !== \"/\" && pathname.startsWith(base)\n ? `/${pathname.slice(base.length)}`\n : pathname;\n}\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n// The prebuilt dirs are content-addressed: hashed names, or a `v` query on the worker's.\nexport function previewCacheControl(\n pathname: string,\n search: string,\n): string | undefined {\n if (pathname.startsWith(\"/__vendor__/\")) {\n return /\\/(shared-deps|import-map)\\.js(on)?$/.test(pathname)\n ? \"no-cache\"\n : IMMUTABLE;\n }\n if (pathname.startsWith(\"/__react__/\")) return IMMUTABLE;\n if (pathname.startsWith(\"/__reactor_worker__/\")) {\n return new URLSearchParams(search).has(\"v\") ? IMMUTABLE : \"no-cache\";\n }\n return undefined;\n}\n\nfunction previewCacheHeadersPlugin(base: string): Plugin {\n return {\n name: \"ph:preview-cache-headers\",\n configurePreviewServer(server) {\n server.middlewares.use((req, res, next) => {\n const [rawPath, search = \"\"] = (req.url ?? \"/\").split(\"?\");\n const value = previewCacheControl(stripBase(rawPath, base), search);\n if (value) res.setHeader(\"Cache-Control\", value);\n next();\n });\n },\n };\n}\n\nfunction serveOverridePlugin(\n outDir: string,\n override: ConnectServeOverride,\n base = \"/\",\n): Plugin {\n return {\n name: \"ph:serve-override\",\n configurePreviewServer(server) {\n server.middlewares.use((req, res, next) => {\n const urlPath = stripBase((req.url ?? \"/\").split(\"?\")[0], base);\n if (urlPath === \"/powerhouse.config.json\") {\n res.writeHead(200, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n res.end(mergedConfigBody(outDir, override));\n return;\n }\n // index.html and extensionless SPA routes get the CSP patch.\n const isHtml =\n urlPath === \"/\" ||\n urlPath.endsWith(\"/index.html\") ||\n !path.extname(urlPath);\n if (override.cspRegistrySync && isHtml) {\n const file = path.join(outDir, \"index.html\");\n if (existsSync(file)) {\n const merged = JSON.parse(mergedConfigBody(outDir, override)) as {\n packageRegistryUrl?: string;\n };\n const registry = merged.packageRegistryUrl;\n const html = readFileSync(file, \"utf8\");\n res.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n res.end(registry ? patchCspScriptSrc(html, registry) : html);\n return;\n }\n }\n next();\n });\n },\n };\n}\n\nexport async function runConnectPreview(\n args: ConnectPreviewArgs,\n serveOverride?: ConnectServeOverride,\n dirname = process.cwd(),\n) {\n // A supervisor can drive the preview via env when no explicit override is\n // passed (the classic `ph connect preview` command path).\n serveOverride ??= overrideFromEnv();\n const {\n outDir,\n port,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n } = args;\n\n const mode = \"production\";\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n });\n\n const outDirAbs = path.resolve(dirname, outDir);\n const base =\n resolvePreviewBase(args.connectBasePath, outDirAbs) ??\n baseConfig.base ??\n \"/\";\n\n const previewConfig: InlineConfig = {\n base,\n build: {\n outDir,\n },\n preview: {\n cors,\n port,\n strictPort,\n host,\n open,\n },\n plugins: [\n previewCacheHeadersPlugin(base),\n ...(serveOverride\n ? [serveOverridePlugin(outDirAbs, serveOverride, base)]\n : []),\n ],\n };\n\n const config = mergeConfig(baseConfig, previewConfig);\n\n const server = await preview(config);\n\n if (printUrls) server.printUrls();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });\n return server;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAmCA,SAAgB,gBACd,MAA0C,QAAQ,KAChB;CAClC,MAAM,YAAY,IAAI;CACtB,MAAM,WAAW,IAAI;CACrB,IAAI,CAAC,aAAa,CAAC,UAAU,OAAO,KAAA;CACpC,MAAM,WAAiC,CAAC;CACxC,IAAI,WACF,SAAS,UAAU,EACjB,QAAQ;EACN,eAAe,UACZ,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO,CAAC,CACf,KAAK,SAAS;GAAE;GAAK,MAAM;GAAM,MAAM;EAAK,EAAE;EACjD,kBACE,IAAI,uCAAuC;CAC/C,EACF;CAEF,IAAI,UAAU;EACZ,SAAS,qBAAqB;EAC9B,SAAS,kBAAkB;CAC7B;CACA,OAAO;AACT;AAEA,SAAS,iBACP,QACA,UACQ;CACR,MAAM,OAAO,KAAK,KAAK,QAAQ,wBAAwB;CACvD,MAAM,QAAQ,WAAW,IAAI,IACxB,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC,IACtC,CAAC;CACL,MAAM,UAAU,SAAS,UACrB,UACG,MAAM,WAAW,CAAC,GACnB,S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ClC,MAAM,EACJ,QACA,MACA,MACA,MACA,MACA,YACA,WACA,qBACE;CAIJ,MAAM,aAAa,yBAAyB;EAC1C,MAAA;EACA;CACF,CAAC;CAED,MAAM,YAAY,KAAK,QAAQ,SAAS,MAAM;CAC9C,MAAM,OACJ,mBAAmB,KAAK,iBAAiB,SAAS,KAClD,WAAW,QACX;CAEF,MAAM,gBAA8B;EAClC;EACA,OAAO,EACL,OACF;EACA,SAAS;GACP;GACA;GACA;GACA;GACA;EACF;EACA,SAAS,CACP,0BAA0B,IAAI,GAC9B,GAAI,gBACA,CAAC,oBAAoB,WAAW,eAAe,IAAI,CAAC,IACpD,CAAC,CACP;CACF;CAEA,MAAM,SAAS,YAAY,YAAY,aAAa;CAEpD,MAAM,SAAS,MAAM,QAAQ,MAAM;CAEnC,IAAI,WAAW,OAAO,UAAU;CAChC,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,KAAK,CAAC;CAC7D,OAAO;AACT","debug_id":"1f75ea05-dcf8-565f-8c31-f2612019dbea"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-desktop-shell-itIzf77U.mjs","sources":["../../../packages/desktop/dist/shell-BL61-fyi.mjs","../../../packages/desktop/dist/index.mjs","../src/services/generate-desktop-shell.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { execSync, spawn, spawnSync } from \"node:child_process\";\nimport { pathToFileURL } from \"node:url\";\n//#region src/app-json.ts\n/**\n* `hosts/desktop/app.json` — the builder's desktop identity (phase 7, mode 1:\n* the builder ships under THEIR identity without writing Rust). It is the ONE\n* file a builder edits; `shell-project.ts` projects it into a generated\n* `tauri-shell/` that depends on the published `ph-desktop-shell` crate. Every\n* field validates strictly so a typo fails with the field named, not silently.\n*/\nconst identifierSchema = z.string().min(1).regex(/^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/, \"identifier must be reverse-DNS (e.g. com.acme.app): dot-separated alphanumeric segments\");\nconst windowSchema = z.strictObject({\n\ttitle: z.string().min(1).optional(),\n\twidth: z.number().int().positive().optional(),\n\theight: z.number().int().positive().optional(),\n\tresizable: z.boolean().optional()\n}).optional();\nconst fileAssociationSchema = z.strictObject({\n\t/** Extensions WITHOUT the leading dot (\"phd\", not \".phd\"). */\n\text: z.array(z.string().min(1).regex(/^[^.]/, \"drop the leading dot\")).min(1),\n\tname: z.string().min(1),\n\tdescription: z.string().optional(),\n\tmimeType: z.string().optional()\n});\n/** Where the generated Cargo.toml resolves `ph-desktop-shell` from. Default\n* (omitted) = the published crates.io version. */\nconst shellSourceSchema = z.strictObject({\n\t/** Local checkout for shell development (the lab points here). */\n\tpath: z.string().min(1).optional(),\n\t/** Git source, pinned to a tag/rev, for pre-publication consumption. */\n\tgit: z.string().min(1).optional(),\n\ttag: z.string().min(1).optional(),\n\trev: z.string().min(1).optional(),\n\t/** crates.io version requirement (default DEFAULT_SHELL_CRATE_VERSION). */\n\tversion: z.string().min(1).optional()\n}).refine((s) => !(s.path && s.git), { message: \"shell.source: set path OR git, not both\" }).optional();\nconst appJsonSchema = z.strictObject({\n\tidentifier: identifierSchema,\n\tproductName: z.string().min(1),\n\t/** Single source image (square PNG, 1024×1024 recommended); the icon set\n\t* for every platform is generated from it via `tauri icon`. */\n\ticon: z.string().min(1),\n\twindow: windowSchema,\n\tfileAssociations: z.array(fileAssociationSchema).optional(),\n\tshell: shellSourceSchema\n});\n/** Default crates.io version requirement for the shell crate (D7.b: the flip\n* to crates.io default once published — the crate is live). */\nconst DEFAULT_SHELL_CRATE_VERSION = \"0.1\";\nconst APP_JSON_FILE = \"app.json\";\n/** Read + validate hosts/<host>/app.json. Throws with the field named on a\n* bad value, and a clear message when the file is absent. */\nfunction loadAppJson(hostDir) {\n\tconst file = path.join(hostDir, APP_JSON_FILE);\n\tif (!fs.existsSync(file)) throw new Error(`No ${APP_JSON_FILE} in ${hostDir} — run \\`ph generate desktop-shell\\` to scaffold the builder identity, or set runner.shell.project to a prebuilt shell.`);\n\tlet raw;\n\ttry {\n\t\traw = JSON.parse(fs.readFileSync(file, \"utf8\"));\n\t} catch (error) {\n\t\tthrow new Error(`${file}: not valid JSON — ${String(error)}`, { cause: error });\n\t}\n\tconst result = appJsonSchema.safeParse(raw);\n\tif (!result.success) {\n\t\tconst issues = result.error.issues.map((i) => ` ${i.path.join(\".\") || \"(root)\"}: ${i.message}`).join(\"\\n\");\n\t\tthrow new Error(`${file} is invalid:\\n${issues}`);\n\t}\n\treturn result.data;\n}\n/** A filesystem/crate-safe slug of the product name — the generated binary\n* and Cargo package name. Falls back to the identifier's last segment. */\nfunction appSlug(app) {\n\tconst fromName = app.productName.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n\tif (fromName) return fromName;\n\treturn (app.identifier.split(\".\").pop() ?? \"app\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n}\n//#endregion\n//#region src/bundle-stack.ts\nfunction copyIfExists(from, to) {\n\tif (!fs.existsSync(from)) return false;\n\tfs.cpSync(from, to, { recursive: true });\n\treturn true;\n}\n/**\n* Recursively copy `src` → `dest`, skipping any path in `excludes`. Unlike\n* fs.cpSync this tolerates `dest` living INSIDE `src`: in mode 1 the generated\n* shell (and its `dist-stack`) sits under `hosts/<desktop>/`, so staging the\n* project's `hosts/` straight into the shell would be a copy-into-self that\n* cpSync rejects outright. Excluding the shell subtree both avoids that and\n* keeps the crate + node sidecar out of the shippable stack.\n*/\nfunction copyDirFiltered(src, dest, excludes) {\n\tif (!fs.existsSync(src)) return false;\n\tconst skip = new Set(excludes.map((e) => path.resolve(e)));\n\tconst walk = (s, d) => {\n\t\tif (skip.has(path.resolve(s))) return;\n\t\tif (fs.statSync(s).isDirectory()) {\n\t\t\tfs.mkdirSync(d, { recursive: true });\n\t\t\tfor (const entry of fs.readdirSync(s)) walk(path.join(s, entry), path.join(d, entry));\n\t\t} else fs.copyFileSync(s, d);\n\t};\n\twalk(src, dest);\n\treturn true;\n}\nfunction bundleStack(options) {\n\tconst log = options.logger ?? console.log;\n\tconst stackDir = path.join(options.shellProjectDir, \"dist-stack\");\n\tfor (const entry of [\n\t\t\"hosts\",\n\t\t\"agents\",\n\t\t\"dist\",\n\t\t\"powerhouse.config.json\",\n\t\t\"package.json\"\n\t]) fs.rmSync(path.join(stackDir, entry), {\n\t\trecursive: true,\n\t\tforce: true\n\t});\n\tfs.mkdirSync(stackDir, { recursive: true });\n\tlog(` hosts/ ${copyDirFiltered(path.join(options.projectRoot, \"hosts\"), path.join(stackDir, \"hosts\"), options.excludeDirs ?? []) ? \"staged\" : \"absent — skipped\"}`);\n\tfor (const dir of [\"agents\", \"dist\"]) log(` ${dir}/ ${copyIfExists(path.join(options.projectRoot, dir), path.join(stackDir, dir)) ? \"staged\" : \"absent — skipped\"}`);\n\tconst stagedDesktopHost = path.join(stackDir, \"hosts\", \"desktop\", \"host.js\");\n\tif (fs.existsSync(stagedDesktopHost)) {\n\t\tconst source = fs.readFileSync(stagedDesktopHost, \"utf8\");\n\t\tif (source.includes(\"@powerhousedao/desktop/runner\")) {\n\t\t\tfs.writeFileSync(stagedDesktopHost, \"// STAGED COPY (bundle-stack): runner.module rewritten to the generic\\n// compound — the packaged shell is the window; there is no nested shell.\\n\" + source.replace(/@powerhousedao\\/desktop\\/runner/g, \"@powerhousedao/host-core/runners/compound\"));\n\t\t\tlog(\" hosts/desktop/host.js: runner rewritten to the generic compound (staged copy)\");\n\t\t}\n\t}\n\tcopyIfExists(path.join(options.projectRoot, \"powerhouse.config.json\"), path.join(stackDir, \"powerhouse.config.json\"));\n\tif (typeof options.connectPort === \"number\") {\n\t\tfs.writeFileSync(path.join(stackDir, \"shell.json\"), `${JSON.stringify({ connectPort: options.connectPort }, null, 2)}\\n`);\n\t\tlog(` shell.json: connectPort ${options.connectPort}`);\n\t}\n\tconst sourcePkg = JSON.parse(fs.readFileSync(path.join(options.projectRoot, \"package.json\"), \"utf8\"));\n\tconst version = options.phCliVersion ?? \"dev\";\n\tfs.writeFileSync(path.join(stackDir, \"package.json\"), `${JSON.stringify({\n\t\tname: sourcePkg.name ?? \"powerhouse-desktop-stack\",\n\t\tprivate: true,\n\t\ttype: \"module\",\n\t\tdependencies: { \"@powerhousedao/ph-cli\": version }\n\t}, null, 2)}\\n`);\n\tlet vendored = false;\n\tif (options.vendor !== false) {\n\t\tconst specs = `\"${options.phCliSpec ?? `@powerhousedao/ph-cli@${version}`}\" \"@powerhousedao/host-core@${version}\"`;\n\t\tlog(` vendoring ${specs} (hoisted, real files)…`);\n\t\tconst result = spawnSync(`npm install ${specs} --install-strategy=hoisted --omit=dev --no-audit --no-fund`, {\n\t\t\tcwd: stackDir,\n\t\t\tstdio: \"pipe\",\n\t\t\tshell: true,\n\t\t\twindowsHide: true\n\t\t});\n\t\tif (result.status !== 0) throw new Error(`bundle-stack: vendoring failed (${result.status}):\\n${result.stderr.toString().slice(-800)}`);\n\t\tvendored = true;\n\t} else log(\" vendoring skipped (vendor: false) — existing tree left in place\");\n\treturn {\n\t\tstackDir,\n\t\tvendored\n\t};\n}\n//#endregion\n//#region src/shell-project.ts\n/**\n* P7.3 — project `hosts/desktop/app.json` into a generated `tauri-shell/`:\n* a STANDALONE tauri crate that depends on the published `ph-desktop-shell`\n* library, carries the builder's identity, and is built/run by the desktop\n* runner's dev/build verbs. The builder never writes Rust.\n*\n* Everything here mirrors the known-good reference app\n* (ph-desktop-shell/apps/powerhouse-desktop): the tauri plumbing (main.rs,\n* build.rs, capabilities, the loading page, externalBin + icon mechanics) is\n* copied verbatim; only identity/port fields are projected from app.json. The\n* projection is idempotent and stale-detected — a file is rewritten only when\n* its content changes, so Cargo.lock, the generated icon set, and tauri-build\n* output are never disturbed by a regen with an unchanged app.json.\n*/\nconst SHELL_DIR = \"tauri-shell\";\n/** The icon source the runner feeds to `tauri icon` (copied from app.icon). */\nconst ICON_SOURCE = \"app-icon.png\";\n/** `ph-desktop-shell` dependency line for the generated Cargo.toml, from\n* app.json's shell.source (path > git > crates.io version). */\nfunction shellDependency(source) {\n\tif (source?.path) {\n\t\tconst p = source.path.replace(/\\\\/g, \"/\");\n\t\treturn `ph-desktop-shell = { path = ${JSON.stringify(p)} }`;\n\t}\n\tif (source?.git) {\n\t\tconst parts = [`git = ${JSON.stringify(source.git)}`];\n\t\tif (source.tag) parts.push(`tag = ${JSON.stringify(source.tag)}`);\n\t\tif (source.rev) parts.push(`rev = ${JSON.stringify(source.rev)}`);\n\t\treturn `ph-desktop-shell = { ${parts.join(\", \")} }`;\n\t}\n\tconst version = source?.version ?? \"0.1\";\n\treturn `ph-desktop-shell = ${JSON.stringify(version)}`;\n}\nfunction cargoToml(app, binName) {\n\treturn `# GENERATED from ../app.json by @powerhousedao/desktop — do not edit by\n# hand; edit app.json and re-run \\`ph run desktop dev|build\\`. Cargo.lock is\n# preserved across regens.\n[package]\nname = ${JSON.stringify(binName)}\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[build-dependencies]\ntauri-build = { version = \"2\", features = [] }\n\n[dependencies]\ntauri = { version = \"2\", features = [\"tray-icon\", \"devtools\"] }\n# Plugins must be DIRECT deps of the app crate: tauri-build only sees\n# permission manifests (shell:allow-spawn etc.) from direct dependencies.\ntauri-plugin-shell = \"2\"\ntauri-plugin-single-instance = \"2\"\n${shellDependency(app.shell)}\n\n[[bin]]\nname = ${JSON.stringify(binName)}\npath = \"src/main.rs\"\n\n[profile.release]\ncodegen-units = 1\nlto = true\n`;\n}\nconst MAIN_RS = `// GENERATED — identity bakes from tauri.conf.json via generate_context!;\n// behavior is the shared ph-desktop-shell library. Edit ../app.json, not this.\n#![cfg_attr(not(debug_assertions), windows_subsystem = \"windows\")]\n\nfn main() {\n ph_desktop_shell::run(tauri::generate_context!(), Default::default());\n}\n`;\nconst BUILD_RS = `// GENERATED — mirrors the reference shell. Connect is served over\n// http://127.0.0.1 (a remote origin to Tauri), so the launch-queue commands\n// need an explicit ACL; declaring the command manifest here generates the\n// allow-<command> permissions that capabilities/*.json grant.\nfn main() {\n tauri_build::try_build(tauri_build::Attributes::new().app_manifest(\n tauri_build::AppManifest::new().commands(&[\n \"take_launch_files\",\n \"read_launch_file\",\n \"log_from_webview\",\n ]),\n ))\n .expect(\"failed to run tauri-build\");\n}\n`;\nfunction loadingHtml(productName) {\n\tconst name = productName.replace(/[<&]/g, (c) => c === \"<\" ? \"&lt;\" : \"&amp;\");\n\treturn `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>${name}</title>\n <style>\n :root { color-scheme: light dark; }\n body {\n margin: 0; height: 100vh;\n display: flex; align-items: center; justify-content: center;\n font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif;\n background: #0f1115; color: #e6e8eb;\n }\n .box { text-align: center; }\n .dot {\n width: 10px; height: 10px; border-radius: 50%;\n background: #4ade80; display: inline-block; margin-right: 8px;\n animation: pulse 1.2s ease-in-out infinite;\n }\n @keyframes pulse { 0%,100% { opacity: .35 } 50% { opacity: 1 } }\n </style>\n </head>\n <body>\n <div class=\"box\"><span class=\"dot\"></span>Starting ${name}…</div>\n </body>\n</html>\n`;\n}\nfunction tauriConf(input) {\n\tconst { app } = input;\n\tconst win = app.window ?? {};\n\tconst fileAssociations = app.fileAssociations && app.fileAssociations.length > 0 ? app.fileAssociations.map((fa) => ({\n\t\text: fa.ext,\n\t\tname: fa.name,\n\t\t...fa.description ? { description: fa.description } : {},\n\t\t...fa.mimeType ? { mimeType: fa.mimeType } : {}\n\t})) : void 0;\n\tconst conf = {\n\t\t$schema: \"https://schema.tauri.app/config/2\",\n\t\tproductName: app.productName,\n\t\tversion: \"0.1.0\",\n\t\tidentifier: app.identifier,\n\t\tbuild: { frontendDist: \"./ui\" },\n\t\tapp: {\n\t\t\twindows: [{\n\t\t\t\ttitle: win.title ?? app.productName,\n\t\t\t\twidth: win.width ?? 1440,\n\t\t\t\theight: win.height ?? 900,\n\t\t\t\tresizable: win.resizable ?? true,\n\t\t\t\tvisible: true,\n\t\t\t\tdragDropEnabled: false,\n\t\t\t\tcreate: false\n\t\t\t}],\n\t\t\tsecurity: { csp: null }\n\t\t},\n\t\tbundle: {\n\t\t\tactive: true,\n\t\t\ttargets: [\n\t\t\t\t\"nsis\",\n\t\t\t\t\"app\",\n\t\t\t\t\"dmg\"\n\t\t\t],\n\t\t\ticon: [\n\t\t\t\t\"icons/32x32.png\",\n\t\t\t\t\"icons/128x128.png\",\n\t\t\t\t\"icons/128x128@2x.png\",\n\t\t\t\t\"icons/icon.icns\",\n\t\t\t\t\"icons/icon.ico\"\n\t\t\t],\n\t\t\t...fileAssociations ? { fileAssociations } : {},\n\t\t\texternalBin: [\"binaries/node\"],\n\t\t\tresources: { \"./dist-stack\": \"stack\" }\n\t\t}\n\t};\n\treturn JSON.stringify(conf, null, 2) + \"\\n\";\n}\nfunction defaultCapability() {\n\treturn JSON.stringify({\n\t\t$schema: \"../gen/schemas/desktop-schema.json\",\n\t\tidentifier: \"default\",\n\t\tdescription: \"Lets the shell spawn the bundled node sidecar.\",\n\t\twindows: [\"main\"],\n\t\tpermissions: [\n\t\t\t\"core:default\",\n\t\t\t\"allow-take-launch-files\",\n\t\t\t\"allow-read-launch-file\",\n\t\t\t\"allow-log-from-webview\",\n\t\t\t{\n\t\t\t\tidentifier: \"shell:allow-spawn\",\n\t\t\t\tallow: [{\n\t\t\t\t\tname: \"binaries/node\",\n\t\t\t\t\tsidecar: true,\n\t\t\t\t\targs: true\n\t\t\t\t}]\n\t\t\t},\n\t\t\t{\n\t\t\t\tidentifier: \"shell:allow-execute\",\n\t\t\t\tallow: [{\n\t\t\t\t\tname: \"binaries/node\",\n\t\t\t\t\tsidecar: true,\n\t\t\t\t\targs: true\n\t\t\t\t}]\n\t\t\t}\n\t\t]\n\t}, null, 2) + \"\\n\";\n}\nfunction connectCapability(connectPort) {\n\tconst origin = `http://127.0.0.1:${connectPort}`;\n\treturn JSON.stringify({\n\t\t$schema: \"../gen/schemas/desktop-schema.json\",\n\t\tidentifier: \"connect\",\n\t\tdescription: \"Connect is served over http://127.0.0.1 (a remote origin to Tauri); without this the launch-queue commands are rejected before they run.\",\n\t\twindows: [\"main\"],\n\t\tremote: { urls: [origin, `${origin}/*`] },\n\t\tpermissions: [\n\t\t\t\"allow-take-launch-files\",\n\t\t\t\"allow-read-launch-file\",\n\t\t\t\"allow-log-from-webview\"\n\t\t]\n\t}, null, 2) + \"\\n\";\n}\nconst GITIGNORE = `# Generated tauri shell — only Cargo.lock and app-icon.png are tracked.\n/target\n/gen\n/icons\n/dist-stack\n/binaries\n`;\nconst DIST_STACK_README = `This directory is replaced at \\`ph run desktop build\\` with the shippable\nstack (hosts + powerhouse.config.json + built Connect + vendored ph-cli). It\nis bundled as the app's \\`stack\\` resource so the installed app runs with no\nenvironment. Kept as a placeholder so tauri's resource glob resolves in dev.\n`;\n/** Write a file only when its content differs; returns whether it changed. */\nfunction writeIfChanged(file, content) {\n\tif (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === content) return false;\n\tfs.mkdirSync(path.dirname(file), { recursive: true });\n\tfs.writeFileSync(file, content);\n\treturn true;\n}\n/**\n* Materialize/refresh `<hostDir>/tauri-shell/` from app.json. Idempotent:\n* unchanged app.json rewrites nothing. Does NOT run `tauri icon` or fetch the\n* node binary — those are toolchain steps the runner performs at dev/build.\n*/\nfunction projectShell(input) {\n\tconst { hostDir, app, connectPort } = input;\n\tconst binName = appSlug(app);\n\tconst shellDir = path.join(hostDir, SHELL_DIR);\n\tconst files = [\n\t\t[\"Cargo.toml\", cargoToml(app, binName)],\n\t\t[\"src/main.rs\", MAIN_RS],\n\t\t[\"build.rs\", BUILD_RS],\n\t\t[\"tauri.conf.json\", tauriConf(input)],\n\t\t[\"ui/index.html\", loadingHtml(app.productName)],\n\t\t[\"capabilities/default.json\", defaultCapability()],\n\t\t[\"capabilities/connect.json\", connectCapability(connectPort)],\n\t\t[\".gitignore\", GITIGNORE],\n\t\t[\"dist-stack/README.md\", DIST_STACK_README]\n\t];\n\tlet changed = false;\n\tfor (const [rel, content] of files) if (writeIfChanged(path.join(shellDir, rel), content)) changed = true;\n\tconst iconSrc = path.resolve(hostDir, app.icon);\n\tconst iconDest = path.join(shellDir, ICON_SOURCE);\n\tif (fs.existsSync(iconSrc)) {\n\t\tconst bytes = fs.readFileSync(iconSrc);\n\t\tif (!fs.existsSync(iconDest) || !fs.readFileSync(iconDest).equals(bytes)) {\n\t\t\tfs.mkdirSync(shellDir, { recursive: true });\n\t\t\tfs.writeFileSync(iconDest, bytes);\n\t\t\tchanged = true;\n\t\t}\n\t}\n\treturn {\n\t\tshellDir,\n\t\tbinName,\n\t\tchanged\n\t};\n}\n//#endregion\n//#region src/shell-toolchain.ts\n/** The Node release triple for a build host — the sidecar filename tauri\n* resolves (`node-<triple>`). Pure, so the mapping is unit-tested. */\nfunction nodeSidecarTarget(platform, arch) {\n\tconst target = {\n\t\t\"win32 x64\": {\n\t\t\ttriple: \"x86_64-pc-windows-msvc\",\n\t\t\tdist: \"win-x64\",\n\t\t\tbin: \"node.exe\",\n\t\t\text: \".exe\"\n\t\t},\n\t\t\"darwin arm64\": {\n\t\t\ttriple: \"aarch64-apple-darwin\",\n\t\t\tdist: \"darwin-arm64\",\n\t\t\tbin: \"bin/node\",\n\t\t\text: \"\"\n\t\t},\n\t\t\"darwin x64\": {\n\t\t\ttriple: \"x86_64-apple-darwin\",\n\t\t\tdist: \"darwin-x64\",\n\t\t\tbin: \"bin/node\",\n\t\t\text: \"\"\n\t\t},\n\t\t\"linux x64\": {\n\t\t\ttriple: \"x86_64-unknown-linux-gnu\",\n\t\t\tdist: \"linux-x64\",\n\t\t\tbin: \"bin/node\",\n\t\t\text: \"\"\n\t\t}\n\t}[`${platform} ${arch}`];\n\tif (!target) throw new Error(`No Node sidecar mapping for ${platform} ${arch} — the desktop shell supports win32/x64, darwin/arm64, darwin/x64, linux/x64.`);\n\treturn target;\n}\n/** Fetch the stock Node the shell ships as its sidecar into `<shellDir>/\n* binaries`, named per target triple. No-op when already present. Ported from\n* the reference repo's fetch-node.mjs (the builder has no such script). */\nfunction fetchNodeSidecar(shellDir, version = process.versions.node, platform = process.platform, arch = process.arch) {\n\tconst target = nodeSidecarTarget(platform, arch);\n\tconst binariesDir = path.join(shellDir, \"binaries\");\n\tfs.mkdirSync(binariesDir, { recursive: true });\n\tconst dest = path.join(binariesDir, `node-${target.triple}${target.ext}`);\n\tif (fs.existsSync(dest)) return dest;\n\tif (platform === \"win32\") {\n\t\tconst url = `https://nodejs.org/dist/v${version}/win-x64/node.exe`;\n\t\texecSync(`curl -fsSL -o \"${dest}\" \"${url}\"`, { stdio: \"inherit\" });\n\t} else {\n\t\tconst name = `node-v${version}-${target.dist}`;\n\t\tconst url = `https://nodejs.org/dist/v${version}/${name}.tar.gz`;\n\t\texecSync(`curl -fsSL \"${url}\" | tar -xz -C \"${binariesDir}\" --strip-components=2 ${name}/${target.bin}`, {\n\t\t\tstdio: \"inherit\",\n\t\t\tshell: \"/bin/sh\"\n\t\t});\n\t\tfs.renameSync(path.join(binariesDir, \"node\"), dest);\n\t\tfs.chmodSync(dest, 493);\n\t}\n\treturn dest;\n}\n/** Default bundle targets for the build host (`cargo tauri build --bundles`).\n* macOS gets app+dmg, Windows nsis, Linux deb+appimage — a host only builds\n* installers it can produce. */\nfunction tauriBundlesForHost(platform = process.platform) {\n\tswitch (platform) {\n\t\tcase \"darwin\": return [\"app\", \"dmg\"];\n\t\tcase \"win32\": return [\"nsis\"];\n\t\tdefault: return [\"deb\", \"appimage\"];\n\t}\n}\n/** Spawn parameters that avoid DEP0190 (args array + shell:true): cargo on\n* Windows needs the shell for PATH/.exe + subcommand resolution — pass ONE\n* string, empty args; everything else runs argv directly (shell:false). The\n* joined tokens here are our own constants/paths, never user input. */\nfunction tauriSpawn(tauri, subcommand) {\n\tconst argv = [...tauri.prefix, ...subcommand];\n\tif (tauri.cmd === \"cargo\" && process.platform === \"win32\") return {\n\t\tcommand: [\"cargo\", ...argv].join(\" \"),\n\t\targs: [],\n\t\tshell: true\n\t};\n\treturn {\n\t\tcommand: tauri.cmd,\n\t\targs: argv,\n\t\tshell: false\n\t};\n}\nfunction probe(cmd, args) {\n\tconst onWin = process.platform === \"win32\";\n\ttry {\n\t\treturn spawnSync(onWin ? [cmd, ...args].join(\" \") : cmd, onWin ? [] : args, {\n\t\t\tstdio: \"ignore\",\n\t\t\tshell: onWin\n\t\t}).status === 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Is a Rust `cargo` on PATH? (needed to compile the shell crate). */\nfunction hasCargo() {\n\treturn probe(\"cargo\", [\"--version\"]);\n}\n/** Resolve a Tauri CLI: a global `cargo tauri`, else a `@tauri-apps/cli`\n* resolvable from the project. Returns null when neither is available. */\nfunction resolveTauriCommand(projectRoot) {\n\tif (probe(\"cargo\", [\"tauri\", \"--version\"])) return {\n\t\tcmd: \"cargo\",\n\t\tprefix: [\"tauri\"],\n\t\tvia: \"cargo-tauri\"\n\t};\n\ttry {\n\t\tconst pkgJson = createRequire(pathToFileURL(path.join(projectRoot, \"package.json\")).href).resolve(\"@tauri-apps/cli/package.json\");\n\t\tconst pkgDir = path.dirname(pkgJson);\n\t\tconst bin = JSON.parse(fs.readFileSync(pkgJson, \"utf8\")).bin;\n\t\tconst rel = typeof bin === \"string\" ? bin : bin?.tauri;\n\t\tif (rel) return {\n\t\t\tcmd: process.execPath,\n\t\t\tprefix: [path.join(pkgDir, rel)],\n\t\t\tvia: \"node-cli\"\n\t\t};\n\t} catch {}\n\treturn null;\n}\nfunction detectToolchain(projectRoot) {\n\treturn {\n\t\tcargo: hasCargo(),\n\t\ttauri: resolveTauriCommand(projectRoot)\n\t};\n}\n/** Throw a clear, actionable error when the native toolchain is incomplete —\n* the desktop verbs call this before any cargo work so a missing executable\n* is an instruction, not a stack trace. */\nfunction preflightOrThrow(tc, hostName) {\n\tconst missing = [];\n\tif (!tc.cargo) missing.push(\" • Rust/cargo — install from https://rustup.rs (then restart your shell)\");\n\tif (!tc.tauri) missing.push(\" • Tauri CLI — `cargo install tauri-cli --version \\\"^2\\\"` (or add @tauri-apps/cli@^2 to your project's devDependencies)\");\n\tif (missing.length > 0 || !tc.tauri) throw new Error(`hosts/${hostName}: the desktop shell needs a native toolchain that is not installed:\\n${missing.join(\"\\n\")}\\nInstall the above, then re-run \\`ph run ${hostName} dev\\` / \\`ph run ${hostName} build\\`. (The headless stack — \\`ph run ${hostName}\\` — needs none of this.)`);\n\treturn tc.tauri;\n}\n/** `<tauri> icon <source>` — generates the per-platform icon set (icon.ico +\n* icon.icns + pngs) the bundle references and tauri-build requires. */\nfunction runTauriIcon(tauri, shellDir, iconSource) {\n\tconst { command, args, shell } = tauriSpawn(tauri, [\"icon\", iconSource]);\n\tconst r = spawnSync(command, args, {\n\t\tcwd: shellDir,\n\t\tstdio: \"inherit\",\n\t\tshell\n\t});\n\tif (r.status !== 0) throw new Error(`\\`tauri icon ${iconSource}\\` failed (exit ${r.status ?? \"?\"}) in ${shellDir} — check that app.icon is a square PNG.`);\n}\n//#endregion\n//#region src/shell.ts\nfunction resolveShell(projectRoot, options, env) {\n\tconst configured = options?.project ?? env.PH_DESKTOP_SHELL;\n\tif (!configured) throw new Error(\"No desktop shell configured: set runner.shell.project in the host file (path to a ph-win-desktop checkout) or the PH_DESKTOP_SHELL environment variable. `ph run desktop` (headless stack) needs neither.\");\n\tconst projectDir = path.resolve(projectRoot, configured);\n\tif (!fs.existsSync(path.join(projectDir, \"src-tauri\"))) throw new Error(`Desktop shell not found at ${projectDir} (no src-tauri/) — check runner.shell.project / PH_DESKTOP_SHELL.`);\n\treturn {\n\t\tprojectDir,\n\t\texe: [\n\t\t\tpath.join(projectDir, \"src-tauri\", \"target\", \"debug\", \"ph-win.exe\"),\n\t\t\tpath.join(projectDir, \"src-tauri\", \"target\", \"release\", \"ph-win.exe\"),\n\t\t\tpath.join(projectDir, \"src-tauri\", \"target\", \"debug\", \"ph-win\"),\n\t\t\tpath.join(projectDir, \"src-tauri\", \"target\", \"release\", \"ph-win\")\n\t\t].find((c) => fs.existsSync(c))\n\t};\n}\n/** Resolve the project's ph-cli entry from ITS dependency tree — the same\n* resolution `ph run` itself uses. */\nfunction resolvePhCliEntry(projectRoot) {\n\tconst pkgPath = createRequire(pathToFileURL(path.join(projectRoot, \"package.json\")).href).resolve(\"@powerhousedao/ph-cli/package.json\");\n\treturn path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n/** The env trio (plus flag and userData) the shell's uniform-runners mode\n* reads — wired by the RUNNER so nobody exports variables by hand. */\nfunction shellEnv(projectRoot, connectPort, env) {\n\treturn {\n\t\tFEATURE_UNIFORM_RUNNERS_ENABLED: \"1\",\n\t\tPH_RUN_PROJECT: projectRoot,\n\t\tPH_RUN_CLI: resolvePhCliEntry(projectRoot),\n\t\tPH_WIN_CONNECT_PORT: String(connectPort),\n\t\t...env.PH_USER_DATA_DIR ? { PH_USER_DATA_DIR: env.PH_USER_DATA_DIR } : {}\n\t};\n}\n/** Project host shell options onto a tauri `--config` merge patch (D6.d) —\n* the host file stays the single source for app identity on tauri-cli\n* invocations; a built exe has these baked. */\nfunction tauriConfigPatch(options) {\n\tif (!options) return void 0;\n\tconst patch = {};\n\tif (options.window) patch.app = { windows: [{\n\t\t...options.window.title ? { title: options.window.title } : {},\n\t\t...options.window.width ? { width: options.window.width } : {},\n\t\t...options.window.height ? { height: options.window.height } : {}\n\t}] };\n\tif (options.fileAssociations?.length) patch.bundle = { fileAssociations: [{\n\t\text: options.fileAssociations.map((e) => e.replace(/^\\./, \"\")),\n\t\tname: \"Powerhouse Document\"\n\t}] };\n\treturn Object.keys(patch).length > 0 ? patch : void 0;\n}\nfunction launchShell(shell, envVars, options) {\n\tif (shell.exe) return spawn(shell.exe, [], {\n\t\tcwd: shell.projectDir,\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\t...envVars\n\t\t},\n\t\tstdio: \"inherit\",\n\t\twindowsHide: true\n\t});\n\tconst patch = tauriConfigPatch(options);\n\tconst args = [\"tauri\", \"dev\"];\n\tif (patch) args.push(\"--config\", JSON.stringify(patch));\n\treturn spawn(\"pnpm\", args, {\n\t\tcwd: shell.projectDir,\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\t...envVars\n\t\t},\n\t\tstdio: \"inherit\",\n\t\tshell: true,\n\t\twindowsHide: true\n\t});\n}\n//#endregion\nexport { loadAppJson as S, bundleStack as _, tauriConfigPatch as a, appJsonSchema as b, nodeSidecarTarget as c, runTauriIcon as d, tauriBundlesForHost as f, projectShell as g, SHELL_DIR as h, shellEnv as i, preflightOrThrow as l, ICON_SOURCE as m, resolvePhCliEntry as n, detectToolchain as o, tauriSpawn as p, resolveShell as r, fetchNodeSidecar as s, launchShell as t, resolveTauriCommand as u, APP_JSON_FILE as v, appSlug as x, DEFAULT_SHELL_CRATE_VERSION as y };\n\n//# sourceMappingURL=shell-BL61-fyi.mjs.map","import { S as loadAppJson, _ as bundleStack, a as tauriConfigPatch, b as appJsonSchema, c as nodeSidecarTarget, d as runTauriIcon, f as tauriBundlesForHost, g as projectShell, h as SHELL_DIR, i as shellEnv, l as preflightOrThrow, m as ICON_SOURCE, n as resolvePhCliEntry, o as detectToolchain, r as resolveShell, s as fetchNodeSidecar, t as launchShell, u as resolveTauriCommand, v as APP_JSON_FILE, x as appSlug, y as DEFAULT_SHELL_CRATE_VERSION } from \"./shell-BL61-fyi.mjs\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { deflateSync } from \"node:zlib\";\n//#region src/scaffold.ts\n/** Minimal PNG encoder — a solid square so `tauri icon` always has a valid\n* source. Pure Node (zlib); no binary asset ships in the package. The builder\n* replaces it with their real 1024×1024 artwork. */\nfunction solidPng(size, rgba) {\n\tconst [r, g, b, a] = rgba;\n\tconst row = Buffer.alloc(1 + size * 4);\n\tfor (let x = 0; x < size; x++) {\n\t\tconst o = 1 + x * 4;\n\t\trow[o] = r;\n\t\trow[o + 1] = g;\n\t\trow[o + 2] = b;\n\t\trow[o + 3] = a;\n\t}\n\tconst raw = Buffer.concat(Array.from({ length: size }, () => row));\n\tconst idat = deflateSync(raw);\n\tconst chunk = (type, data) => {\n\t\tconst len = Buffer.alloc(4);\n\t\tlen.writeUInt32BE(data.length, 0);\n\t\tconst typeBuf = Buffer.from(type, \"ascii\");\n\t\tconst body = Buffer.concat([typeBuf, data]);\n\t\tconst crc = Buffer.alloc(4);\n\t\tcrc.writeUInt32BE(crc32(body) >>> 0, 0);\n\t\treturn Buffer.concat([\n\t\t\tlen,\n\t\t\tbody,\n\t\t\tcrc\n\t\t]);\n\t};\n\tconst ihdr = Buffer.alloc(13);\n\tihdr.writeUInt32BE(size, 0);\n\tihdr.writeUInt32BE(size, 4);\n\tihdr[8] = 8;\n\tihdr[9] = 6;\n\tihdr[10] = 0;\n\tihdr[11] = 0;\n\tihdr[12] = 0;\n\treturn Buffer.concat([\n\t\tBuffer.from([\n\t\t\t137,\n\t\t\t80,\n\t\t\t78,\n\t\t\t71,\n\t\t\t13,\n\t\t\t10,\n\t\t\t26,\n\t\t\t10\n\t\t]),\n\t\tchunk(\"IHDR\", ihdr),\n\t\tchunk(\"IDAT\", idat),\n\t\tchunk(\"IEND\", Buffer.alloc(0))\n\t]);\n}\nlet crcTable;\nfunction crc32(buf) {\n\tif (!crcTable) {\n\t\tcrcTable = [];\n\t\tfor (let n = 0; n < 256; n++) {\n\t\t\tlet c = n;\n\t\t\tfor (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;\n\t\t\tcrcTable[n] = c;\n\t\t}\n\t}\n\tlet crc = 4294967295;\n\tfor (let i = 0; i < buf.length; i++) crc = crcTable[(crc ^ buf[i]) & 255] ^ crc >>> 8;\n\treturn crc ^ 4294967295;\n}\nconst GITIGNORE = `# Generated tauri shell — only Cargo.lock and app-icon.png are tracked.\n/tauri-shell/target\n/tauri-shell/gen\n/tauri-shell/icons\n/tauri-shell/dist-stack\n/tauri-shell/binaries\n`;\nfunction scaffoldDesktopShell(hostDir, options) {\n\tconst created = [];\n\tconst skipped = [];\n\tfs.mkdirSync(hostDir, { recursive: true });\n\tconst iconFile = \"icon.png\";\n\tconst app = {\n\t\tidentifier: options.identifier,\n\t\tproductName: options.productName,\n\t\ticon: `./${iconFile}`,\n\t\twindow: {\n\t\t\ttitle: options.productName,\n\t\t\twidth: 1440,\n\t\t\theight: 900\n\t\t},\n\t\tfileAssociations: [{\n\t\t\text: [\"phd\"],\n\t\t\tname: \"Powerhouse Document\",\n\t\t\tmimeType: \"application/vnd.powerhouse.document+zip\"\n\t\t}]\n\t};\n\tappJsonSchema.parse(app);\n\tconst appJsonPath = path.join(hostDir, APP_JSON_FILE);\n\tif (fs.existsSync(appJsonPath) && !options.force) skipped.push(appJsonPath);\n\telse {\n\t\tfs.writeFileSync(appJsonPath, `${JSON.stringify(app, null, 2)}\\n`);\n\t\tcreated.push(appJsonPath);\n\t}\n\tconst iconPath = path.join(hostDir, iconFile);\n\tif (fs.existsSync(iconPath)) skipped.push(iconPath);\n\telse {\n\t\tfs.writeFileSync(iconPath, solidPng(1024, [\n\t\t\t79,\n\t\t\t70,\n\t\t\t229,\n\t\t\t255\n\t\t]));\n\t\tcreated.push(iconPath);\n\t}\n\tconst gitignorePath = path.join(hostDir, \".gitignore\");\n\tif (fs.existsSync(gitignorePath)) skipped.push(gitignorePath);\n\telse {\n\t\tfs.writeFileSync(gitignorePath, GITIGNORE);\n\t\tcreated.push(gitignorePath);\n\t}\n\treturn {\n\t\thostDir,\n\t\tcreated,\n\t\tskipped\n\t};\n}\n//#endregion\nexport { APP_JSON_FILE, DEFAULT_SHELL_CRATE_VERSION, ICON_SOURCE, SHELL_DIR, appJsonSchema, appSlug, bundleStack, detectToolchain, fetchNodeSidecar, launchShell, loadAppJson, nodeSidecarTarget, preflightOrThrow, projectShell, resolvePhCliEntry, resolveShell, resolveTauriCommand, runTauriIcon, scaffoldDesktopShell, shellEnv, solidPng, tauriBundlesForHost, tauriConfigPatch };\n\n//# sourceMappingURL=index.mjs.map","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { scaffoldDesktopShell } from \"@powerhousedao/desktop\";\n\nexport interface GenerateDesktopShellArgs {\n name?: string;\n identifier?: string;\n force?: boolean;\n}\n\n/** A reverse-DNS-safe segment from the project name (drop scope, slugify). */\nfunction projectSlug(pkgName: string | undefined): string {\n const bare = (pkgName ?? \"app\").replace(/^@[^/]+\\//, \"\");\n const seg = bare\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return seg || \"app\";\n}\n\n/** `ph generate desktop-shell`: write hosts/desktop/app.json + a placeholder\n * icon + .gitignore. Defaults product name / identifier from the project. */\nexport function startGenerateDesktopShell(\n args: GenerateDesktopShellArgs,\n cwd: string,\n): void {\n let pkgName: string | undefined;\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(cwd, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n pkgName = pkg.name;\n } catch {\n // no package.json — fall back to defaults below\n }\n const slug = projectSlug(pkgName);\n const productName = args.name ?? pkgName?.replace(/^@[^/]+\\//, \"\") ?? \"App\";\n const identifier = args.identifier ?? `inc.powerhouse.desktop.${slug}`;\n\n const hostDir = path.join(cwd, \"hosts\", \"desktop\");\n const result = scaffoldDesktopShell(hostDir, {\n identifier,\n productName,\n force: args.force,\n });\n\n const rel = (p: string) => path.relative(cwd, p).replace(/\\\\/g, \"/\");\n for (const f of result.created) console.log(` created ${rel(f)}`);\n for (const f of result.skipped) {\n console.log(` skipped ${rel(f)} (exists — pass --force to overwrite)`);\n }\n if (!fs.existsSync(path.join(hostDir, \"host.js\"))) {\n console.log(\n `\\nNote: hosts/desktop/host.js not found. Add a desktop host (see the ` +\n `desktop topology from \\`ph init\\`) so \\`ph run desktop\\` can supervise ` +\n `the stack; app.json then gives it a native window.`,\n );\n }\n console.log(\n `\\nIdentity: ${productName} (${identifier}).\\n` +\n `• Replace hosts/desktop/icon.png with your 1024×1024 icon.\\n` +\n `• \\`ph run desktop dev\\` opens the native window (needs Rust + the Tauri CLI).\\n` +\n `• \\`ph run desktop build\\` produces installers for this OS.`,\n );\n}\n"],"names":["z.string","z.strictObject","z.number","z.boolean","z.array"],"mappings":";;;;;;;;;;;;;;;;;AAcA,MAAM,mBAAmBA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,qCAAqC,yFAAyF;AAC/K,MAAM,eAAeC,aAAe;CACnC,OAAOD,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;CAClC,OAAOE,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAC5C,QAAQA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAC7C,WAAWC,QAAU,CAAC,CAAC,SAAS;AACjC,CAAC,CAAC,CAAC,SAAS;AACZ,MAAM,wBAAwBF,aAAe;;CAE5C,KAAKG,MAAQJ,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,SAAS,sBAAsB,CAAC,CAAC,CAAC,IAAI,CAAC;CAC5E,MAAMA,OAAS,CAAC,CAAC,IAAI,CAAC;CACtB,aAAaA,OAAS,CAAC,CAAC,SAAS;CACjC,UAAUA,OAAS,CAAC,CAAC,SAAS;AAC/B,CAAC;;;AAGD,MAAM,oBAAoBC,aAAe;;CAExC,MAAMD,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;CAEjC,KAAKA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;CAChC,KAAKA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;CAChC,KAAKA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;CAEhC,SAASA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;AACrC,CAAC,CAAC,CAAC,QAAQ,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,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,WAAW,KAAK,KAAK,SAAS,SAAS,CAAC,GAC9C,QAAQ,IACN,4LAGF;CAEF,QAAQ,IACN,eAAe,YAAY,IAAI,WAAW,4MAI5C;AACF","debug_id":"0143deec-f1bb-5f26-a0fa-873d3d704206"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"host-schemas-CL_wFpY7-B_pY14Jy.mjs","sources":["../../../packages/host-core/dist/host-schemas-CL_wFpY7.mjs"],"sourcesContent":["import { pluginEntrySchema } from \"./plugins.mjs\";\nimport { createRequire } from \"node:module\";\nimport fs, { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\nimport crypto from \"node:crypto\";\n//#region src/connect-projection.ts\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*/\nfunction isLocalDrive(drive) {\n\treturn \"local\" in drive;\n}\nconst driveKey = (drive) => isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\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*/\nfunction mergeDefaultDrives(...groups) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst out = [];\n\tfor (const group of groups) for (const drive of group) {\n\t\tconst key = driveKey(drive);\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tout.push(drive);\n\t}\n\treturn out;\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*/\nfunction rebaseDriveUrl(driveUrl, publicBase) {\n\tlet url;\n\ttry {\n\t\turl = new URL(driveUrl);\n\t} catch {\n\t\treturn driveUrl;\n\t}\n\tif (![\n\t\t\"localhost\",\n\t\t\"127.0.0.1\",\n\t\t\"[::1]\"\n\t].includes(url.hostname)) return driveUrl;\n\treturn `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\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*/\nfunction projectDrivesIntoConnect(input) {\n\treturn { drives: {\n\t\tdefaultDrives: mergeDefaultDrives(input.createdDriveUrls.filter((url) => typeof url === \"string\" && url.length > 0).map((url) => ({\n\t\t\turl: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n\t\t\tname: null,\n\t\t\ticon: null\n\t\t})), input.configuredDefaultDrives ?? []),\n\t\tpreserveStrategy: \"preserve-all\"\n\t} };\n}\n//#endregion\n//#region src/host-loader.ts\n/**\n* Loads and pre-validates a `hosts/<name>/host.js` definition.\n*\n* A host file is a static PROJECTION of powerhouse.config.json: plain ESM,\n* default-exporting a data object. Three gates run before any runner sees it:\n* 1. import lint — the only legal import is the project's\n* powerhouse.config.json (host files are data, not programs);\n* 2. static check — the exported object must survive a JSON round trip\n* (functions, undefined, class instances, Dates etc. are rejected,\n* reporting the offending path);\n* 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children\n* rule. Full validation is the runner's `hostSchema` (phase 2).\n*\n* This module never exits the process — callers own error presentation.\n*/\nconst HOST_FILE = \"host.js\";\nconst CONFIG_IMPORT_SUFFIX = \"powerhouse.config.json\";\nvar HostLoadError = class extends Error {\n\tconstructor(message, hint) {\n\t\tsuper(hint ? `${message}\\n Hint: ${hint}` : message);\n\t\tthis.name = \"HostLoadError\";\n\t}\n};\n/** A `hosts/` folder with no `<name>/host.js` inside is \"empty\" — the guard\n* state: callers warn loudly and fall back to legacy rather than activating\n* the new architecture off a stray `mkdir hosts`. */\nfunction probeHostsFolder(projectRoot) {\n\tconst dir = path.join(projectRoot, \"hosts\");\n\tif (!existsSync(dir) || !statSync(dir).isDirectory()) return { kind: \"absent\" };\n\tconst hosts = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, HOST_FILE))).map((entry) => entry.name).sort();\n\treturn hosts.length === 0 ? {\n\t\tkind: \"empty\",\n\t\tdir\n\t} : {\n\t\tkind: \"present\",\n\t\tdir,\n\t\thosts\n\t};\n}\n/** Sibling host imports: `../<host>/host.js` — source material for derived\n* compositions (full-inclusion wrappers compute over them with plain JS). */\nconst SIBLING_IMPORT = /^\\.\\.\\/([A-Za-z0-9_-]+)\\/host\\.js$/;\n/** Rejects every import except the project's powerhouse.config.json and\n* SIBLING host files (R1: derived compositions), plus any dynamic\n* `import(...)` or `require(...)`. Source-level enforcement: the JSON round\n* trip below is the hard gate; this one produces the better error. Returns\n* the sibling host names the file imports, for cycle detection. */\nfunction lintHostImports(source, file) {\n\tconst siblings = [];\n\tfor (const match of source.matchAll(/^\\s*import\\b[^;'\"]*?from\\s+[\"']([^\"']+)[\"']/gm)) {\n\t\tconst specifier = match[1];\n\t\tif (specifier.endsWith(CONFIG_IMPORT_SUFFIX)) continue;\n\t\tconst sibling = SIBLING_IMPORT.exec(specifier);\n\t\tif (sibling) {\n\t\t\tsiblings.push(sibling[1]);\n\t\t\tcontinue;\n\t\t}\n\t\tthrow 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.\");\n\t}\n\tif (/^\\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.`);\n\tif (/\\bimport\\s*\\(/.test(source) || /\\brequire\\s*\\(/.test(source)) throw new HostLoadError(`${file} uses dynamic import()/require() — host files are static data.`);\n\treturn siblings;\n}\n/** Walks the sibling-import graph from `hostName`, linting every visited file\n* and failing on a cycle (an ESM circular would otherwise surface as an\n* undefined default export with no useful message). */\nfunction lintHostImportGraph(hostsDir, hostName) {\n\tconst state = /* @__PURE__ */ new Map();\n\tconst visit = (name, chain) => {\n\t\tconst mark = state.get(name);\n\t\tif (mark === \"done\") return;\n\t\tif (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.\");\n\t\tconst file = path.join(hostsDir, name, HOST_FILE);\n\t\tif (!existsSync(file)) throw new HostLoadError(`hosts/${chain[chain.length - 1] ?? name} imports sibling \"hosts/${name}/host.js\", which does not exist.`);\n\t\tstate.set(name, \"visiting\");\n\t\tconst siblings = lintHostImports(readFileSync(file, \"utf8\"), file);\n\t\tfor (const sibling of siblings) visit(sibling, [...chain, name]);\n\t\tstate.set(name, \"done\");\n\t};\n\tvisit(hostName, []);\n}\n/** Returns the path of the first value that would not survive a JSON round\n* trip, or undefined when the object is fully static. */\nfunction findNonStaticValue(value, trail = \"\") {\n\tif (value === null) return void 0;\n\tconst kind = typeof value;\n\tif (kind === \"string\" || kind === \"number\" || kind === \"boolean\") return;\n\tif (kind !== \"object\") return `${trail || \"<root>\"} (${kind})`;\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst hit = findNonStaticValue(value[i], `${trail}[${i}]`);\n\t\t\tif (hit) return hit;\n\t\t}\n\t\treturn;\n\t}\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return `${trail || \"<root>\"} (non-plain object)`;\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tconst hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);\n\t\tif (hit) return hit;\n\t}\n}\nfunction assertHostShape(host, file) {\n\tif (typeof host.name !== \"string\" || host.name.length === 0) throw new HostLoadError(`${file}: \\`name\\` must be a non-empty string.`);\n\tconst runner = host.runner;\n\tif (runner === null || typeof runner !== \"object\" || typeof runner.module !== \"string\") throw new HostLoadError(`${file}: \\`runner\\` must be an object with a \\`module\\` specifier string.`);\n\tif (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.`);\n}\nasync function loadHost(projectRoot, hostName) {\n\tconst probe = probeHostsFolder(projectRoot);\n\tif (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).\");\n\tif (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.\");\n\tif (!probe.hosts.includes(hostName)) throw new HostLoadError(`Unknown host \"${hostName}\". Available hosts: ${probe.hosts.join(\", \")}.`);\n\tconst file = path.join(probe.dir, hostName, HOST_FILE);\n\tlintHostImportGraph(probe.dir, hostName);\n\tconst host = (await import(pathToFileURL(file).href)).default;\n\tif (host === null || typeof host !== \"object\" || Array.isArray(host)) throw new HostLoadError(`${file} must default-export the host object (\\`export default { name, runner, ... }\\`).`);\n\tconst nonStatic = findNonStaticValue(host);\n\tif (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.\");\n\tassertHostShape(host, file);\n\treturn {\n\t\tname: hostName,\n\t\tdir: path.dirname(file),\n\t\tfile,\n\t\thost\n\t};\n}\n//#endregion\n//#region src/runner-resolver.ts\n/**\n* Resolves a host's `runner.module` specifier from the PROJECT's dependency\n* tree (not ph-cli's), imports it, and checks the runner-module contract:\n* `{ run, hostSchema, kind, ...optionalVerbs }`. Phase-0 home is ph-cli; the\n* uniform-runners plan moves this into @powerhousedao/host-core with the\n* generic compound (phase 1).\n*/\nvar RunnerError = class extends Error {\n\tconstructor(message, hint) {\n\t\tsuper(hint ? `${message}\\n Hint: ${hint}` : message);\n\t\tthis.name = \"RunnerError\";\n\t}\n};\n/** Exports that are part of the contract but are not verbs. */\nconst NON_VERB_EXPORTS = /* @__PURE__ */ new Set([\n\t\"hostSchema\",\n\t\"kind\",\n\t\"default\"\n]);\nasync function resolveRunnerModule(projectRoot, specifier) {\n\tconst projectRequire = createRequire(pathToFileURL(path.join(projectRoot, \"package.json\")).href);\n\tlet resolved;\n\ttry {\n\t\tresolved = projectRequire.resolve(specifier);\n\t} catch {\n\t\tthrow new RunnerError(`Cannot resolve runner module \"${specifier}\" from ${projectRoot}.`, \"The runner must be a dependency of the project (install it, then retry).\");\n\t}\n\tconst module = await import(pathToFileURL(resolved).href);\n\tif (typeof module.run !== \"function\") throw new RunnerError(`Runner \"${specifier}\" does not export a \\`run\\` function (required verb).`);\n\tconst hostSchema = module.hostSchema;\n\tif (!hostSchema || typeof hostSchema.safeParse !== \"function\") throw new RunnerError(`Runner \"${specifier}\" does not export a \\`hostSchema\\` — runners validate their own host shape.`);\n\tif (typeof module.kind !== \"string\") throw new RunnerError(`Runner \"${specifier}\" does not export \\`kind\\` (e.g. \"reactor\" | \"compound\").`);\n\treturn module;\n}\nfunction listVerbs(runner) {\n\treturn Object.entries(runner).filter(([name, value]) => typeof value === \"function\" && !NON_VERB_EXPORTS.has(name)).map(([name]) => name).sort();\n}\nfunction getVerb(runner, specifier, verb) {\n\tconst candidate = runner[verb];\n\tif (typeof candidate !== \"function\" || NON_VERB_EXPORTS.has(verb)) throw new RunnerError(`Runner \"${specifier}\" does not support the verb \"${verb}\". Supported verbs: ${listVerbs(runner).join(\", \")}.`);\n\treturn candidate;\n}\nfunction validateHost(runner, specifier, host, file) {\n\tconst result = runner.hostSchema.safeParse(host);\n\tif (!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)\"}`);\n}\n//#endregion\n//#region src/run-record.ts\nconst runDir = (projectDir) => path.join(projectDir, \".ph\", \"run\");\nconst recordPath = (projectDir, hostName) => path.join(runDir(projectDir), `${hostName}.json`);\nfunction readRunRecord(projectDir, hostName) {\n\ttry {\n\t\treturn JSON.parse(fs.readFileSync(recordPath(projectDir, hostName), \"utf8\"));\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction writeRunRecord(projectDir, record) {\n\tconst target = recordPath(projectDir, record.hostName);\n\tfs.mkdirSync(path.dirname(target), { recursive: true });\n\tfs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\nfunction clearRunRecord(projectDir, hostName) {\n\ttry {\n\t\tfs.rmSync(recordPath(projectDir, hostName));\n\t} catch {}\n}\nfunction isPidAlive(pid) {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn error.code === \"EPERM\";\n\t}\n}\n/**\n* Decide whether the recorded instance is this project's live host.\n*\n* pid liveness alone proves nothing (pids are reused), and the recorded\n* projectName is what separates \"my instance\" from \"a different project that\n* happens to hold this storage root\" — the confusion the vetra lock exists to\n* prevent. A stale record (dead pid) is reported so the caller can clear it; a\n* foreign one (live pid, different project) is left alone.\n*/\nfunction probeRun(projectDir, hostName, projectName) {\n\tconst record = readRunRecord(projectDir, hostName);\n\tif (!record) return { status: \"none\" };\n\tif (!isPidAlive(record.pid)) return {\n\t\tstatus: \"stale\",\n\t\trecord\n\t};\n\tif (record.projectName !== projectName) return {\n\t\tstatus: \"foreign\",\n\t\trecord\n\t};\n\treturn {\n\t\tstatus: \"live\",\n\t\trecord\n\t};\n}\n//#endregion\n//#region src/placeholders.ts\n/**\n* `${userData}` resolution for host files (desktop shape): storage paths in a\n* host must not derive from the instance name (renames must stay safe), so\n* the host file writes `${userData}/pglite` and the RUNNER resolves it at\n* start. In the CLI the default userData is `<projectRoot>/.ph/user-data`;\n* a shell (Tauri) overrides it via PH_USER_DATA_DIR to the OS profile dir.\n*/\nfunction defaultUserDataDir(projectRoot, env = process.env) {\n\treturn env.PH_USER_DATA_DIR ?? path.join(projectRoot, \".ph\", \"user-data\");\n}\nconst PLACEHOLDER = /\\$\\{userData\\}/g;\n/** Deep-substitute `${userData}` in every string of a JSON-shaped value.\n* Non-strings pass through; the input is never mutated. */\nfunction resolveUserDataPlaceholders(value, userData) {\n\tif (typeof value === \"string\") return value.replace(PLACEHOLDER, userData);\n\tif (Array.isArray(value)) return value.map((v) => resolveUserDataPlaceholders(v, userData));\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst out = {};\n\t\tfor (const [k, v] of Object.entries(value)) out[k] = resolveUserDataPlaceholders(v, userData);\n\t\treturn out;\n\t}\n\treturn value;\n}\n//#endregion\n//#region src/compound.ts\nfunction memberEntries(host) {\n\tconst children = host.children ?? {};\n\treturn Object.entries(children);\n}\nfunction orderedMembers(host, wiring) {\n\tconst entries = memberEntries(host);\n\tif (!wiring.startOrder) return entries;\n\tconst byName = new Map(entries);\n\tconst out = [];\n\tfor (const name of wiring.startOrder) {\n\t\tconst m = byName.get(name);\n\t\tif (m) {\n\t\t\tout.push([name, m]);\n\t\t\tbyName.delete(name);\n\t\t}\n\t}\n\tfor (const [name, m] of entries) if (byName.has(name)) out.push([name, m]);\n\treturn out;\n}\n/** Build the member host object the member runner sees: the member's own\n* host.js with the wrapper applied. R1 semantics (rewire plan): a wrapper\n* SECTION is a FULL STATEMENT — `reactor` and `config`, when present on the\n* wrapper, replace the member's wholesale (host files derive keeps explicitly\n* by spreading the sibling import: `{ ...switchboard.reactor, drives }`).\n* `runner` stays key-merged: wrappers never restate `module`/`defaultVerb`,\n* they override individual keys (port, host, plugins — the plugins LIST\n* itself is a full statement computed in the file). */\nasync function resolveMemberHost(projectRoot, member, userData, configPatch) {\n\tconst base = (await loadHost(projectRoot, member.host)).host;\n\treturn resolveUserDataPlaceholders({\n\t\t...base,\n\t\trunner: {\n\t\t\t...base.runner,\n\t\t\t...member.runner ?? {}\n\t\t},\n\t\tconfig: {\n\t\t\t...member.config !== void 0 ? member.config : base.config ?? {},\n\t\t\t...configPatch ?? {}\n\t\t},\n\t\treactor: member.reactor !== void 0 ? member.reactor : base.reactor\n\t}, userData);\n}\nfunction isConnectMember(member) {\n\treturn member.host === \"connect\";\n}\nfunction isReactorFactMember(member) {\n\treturn member.host === \"switchboard\";\n}\nasync function runCompound(host, ctx, options) {\n\tconst projectRoot = ctx.projectRoot;\n\tconst wiring = host.config ?? {};\n\tconst verb = ctx.verb;\n\tconst probe = probeRun(projectRoot, host.name, options.projectName);\n\tif (probe.status === \"live\") throw new Error(`${host.name} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`);\n\tif (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.`);\n\tconst userData = defaultUserDataDir(projectRoot, ctx.env);\n\tconst started = [];\n\tconst reactorFacts = { driveUrls: [] };\n\tconst shutdown = async () => {\n\t\tfor (const m of [...started].reverse()) try {\n\t\t\tawait m.handle.shutdown?.();\n\t\t} catch {}\n\t\tif (wiring.runtimeRecord !== false) clearRunRecord(projectRoot, host.name);\n\t};\n\tfor (const [name, member] of orderedMembers(host, wiring)) {\n\t\tlet configPatch;\n\t\tif (isConnectMember(member) && wiring.projectDrivesIntoConnect && reactorFacts.driveUrls.length > 0) {\n\t\t\tconst configuredDefaultDrives = (member.config?.drives)?.defaultDrives;\n\t\t\tconfigPatch = projectDrivesIntoConnect({\n\t\t\t\tcreatedDriveUrls: reactorFacts.driveUrls,\n\t\t\t\tconfiguredDefaultDrives,\n\t\t\t\tpublicBase: wiring.drivesPublicBase\n\t\t\t});\n\t\t}\n\t\tconst memberHost = await resolveMemberHost(projectRoot, member, userData, configPatch);\n\t\tif (isConnectMember(member) && wiring.cspRegistrySync) memberHost.runner = {\n\t\t\t...memberHost.runner,\n\t\t\tcspRegistrySync: true\n\t\t};\n\t\tconst specifier = memberHost.runner.module;\n\t\tconst runner = await resolveRunnerModule(projectRoot, specifier);\n\t\tvalidateHost(runner, specifier, memberHost, `hosts/${member.host}/host.js`);\n\t\tconst handle = await getVerb(runner, specifier, verb === \"run\" ? memberHost.runner.defaultVerb ?? \"run\" : verb)(memberHost, ctx) ?? {};\n\t\tif (handle.ready) await handle.ready;\n\t\tstarted.push({\n\t\t\tname,\n\t\t\thandle\n\t\t});\n\t\tif (isReactorFactMember(member) && handle.driveUrls) reactorFacts.driveUrls.push(...handle.driveUrls);\n\t}\n\tif (wiring.runtimeRecord !== false) {\n\t\tconst members = {};\n\t\tfor (const m of started) members[m.name] = {\n\t\t\tport: m.handle.port,\n\t\t\turl: m.handle.endpoints?.graphql ?? m.handle.endpoints?.connect\n\t\t};\n\t\twriteRunRecord(projectRoot, {\n\t\t\tpid: process.pid,\n\t\t\thostName: host.name,\n\t\t\tprojectName: options.projectName,\n\t\t\tstartedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\tmembers,\n\t\t\textra: options.recordExtra\n\t\t});\n\t}\n\tif (options.installSignalHandlers !== false) {\n\t\tconst onSignal = (code) => {\n\t\t\tshutdown().finally(() => process.exit(code));\n\t\t};\n\t\tprocess.on(\"exit\", () => {\n\t\t\tif (wiring.runtimeRecord !== false) clearRunRecord(projectRoot, host.name);\n\t\t});\n\t\tprocess.on(\"SIGINT\", () => onSignal(130));\n\t\tprocess.on(\"SIGTERM\", () => onSignal(143));\n\t}\n\treturn {\n\t\tstarted,\n\t\tshutdown\n\t};\n}\n//#endregion\n//#region src/drives.ts\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* Field semantics (union of the three existing creation sites — vetra,\n* preview, workflows — plus Connect's PHConnectDefaultDrive):\n* - slug: the SEEDING KEY (idempotence); id optional (stable identity),\n* projectHash derives both from the project path (generateProjectDriveId\n* semantics: `${slug}-${sha256(projectPath).slice(0, 8)}`).\n* - preferredEditor: binds the drive to its drive app — stored at\n* header.meta.preferredEditor; Connect config's `app` is the legacy alias.\n* - remote.url: an attachment to a drive served elsewhere (Connect default\n* drives, switchboard remoteDrives); local fields are ignored for remotes.\n*/\nconst driveDeclarationSchema = z.strictObject({\n\tslug: z.string().min(1),\n\tid: z.string().min(1).optional(),\n\t/** Derive id (and the served slug) from the project path, like\n\t* generateProjectDriveId — same ids classic `ph vetra` produces. */\n\tprojectHash: z.boolean().optional(),\n\tname: z.string().min(1).optional(),\n\ticon: z.string().optional(),\n\tpreferredEditor: z.string().optional(),\n\tsharingType: z.enum([\n\t\t\"public\",\n\t\t\"private\",\n\t\t\"shared\"\n\t]).optional(),\n\tavailableOffline: z.boolean().optional(),\n\tremote: z.strictObject({ url: z.string().min(1) }).optional()\n});\nconst drivesSchema = z.array(driveDeclarationSchema);\nfunction projectDriveId(projectRoot, slug) {\n\treturn `${slug}-${crypto.createHash(\"sha256\").update(projectRoot).digest(\"hex\").substring(0, 8)}`;\n}\nfunction resolveDriveDeclaration(projectRoot, decl) {\n\tconst id = decl.projectHash ? projectDriveId(projectRoot, decl.slug) : decl.id ?? decl.slug;\n\tconst slug = decl.projectHash ? id : decl.slug;\n\tif (decl.remote) return {\n\t\tkind: \"remote\",\n\t\tid,\n\t\tslug,\n\t\tname: decl.name ?? decl.slug,\n\t\tremoteUrl: decl.remote.url,\n\t\tsharingType: decl.sharingType ?? \"public\",\n\t\tavailableOffline: decl.availableOffline ?? true\n\t};\n\treturn {\n\t\tkind: \"local\",\n\t\tid,\n\t\tslug,\n\t\tname: decl.name ?? decl.slug,\n\t\ticon: decl.icon,\n\t\tpreferredEditor: decl.preferredEditor,\n\t\tsharingType: decl.sharingType ?? \"public\",\n\t\tavailableOffline: decl.availableOffline ?? true\n\t};\n}\n/** Idempotent, slug-keyed: an existing slug is left untouched (never\n* recreated, never mutated — preserveStrategy refinements live here later). */\nasync function seedDrives(client, drives) {\n\tconst result = {\n\t\tcreated: [],\n\t\texisting: [],\n\t\tattached: []\n\t};\n\tfor (const drive of drives) {\n\t\tif (drive.kind === \"remote\") {\n\t\t\tawait client.attachRemoteDrive(drive.remoteUrl);\n\t\t\tresult.attached.push(drive.slug);\n\t\t\tcontinue;\n\t\t}\n\t\tif (await client.findDriveBySlug(drive.slug) !== void 0) {\n\t\t\tresult.existing.push(drive.slug);\n\t\t\tcontinue;\n\t\t}\n\t\tawait client.createDrive(drive);\n\t\tresult.created.push(drive.slug);\n\t}\n\treturn result;\n}\n/** Merge host-declared drives with plugin contributions, slug-keyed — the\n* host file wins on conflicts (it is the most explicit source). */\nfunction mergeDrivePlan(projectRoot, hostDeclared, contributed) {\n\tconst plan = /* @__PURE__ */ new Map();\n\tfor (const { declaration, source } of contributed) {\n\t\tconst drive = resolveDriveDeclaration(projectRoot, declaration);\n\t\tplan.set(drive.slug, {\n\t\t\tdrive,\n\t\t\tsource\n\t\t});\n\t}\n\tfor (const declaration of hostDeclared) {\n\t\tconst drive = resolveDriveDeclaration(projectRoot, declaration);\n\t\tplan.set(drive.slug, {\n\t\t\tdrive,\n\t\t\tsource: \"host\"\n\t\t});\n\t}\n\treturn [...plan.values()];\n}\nfunction explainDrivePlan(plan) {\n\tif (plan.length === 0) return \"(no drives declared)\";\n\treturn [\"drives:\", ...plan.map(({ drive, source }) => {\n\t\tconst kind = drive.kind === \"remote\" ? `remote ${drive.remoteUrl}` : \"local\";\n\t\tconst editor = drive.preferredEditor ? ` editor=${drive.preferredEditor}` : \"\";\n\t\treturn ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;\n\t})].join(\"\\n\");\n}\n//#endregion\n//#region src/host-schemas.ts\n/**\n* The shared zod schemas for host.js blocks (D2.a). The `reactor` block\n* validates STRICTLY (D2.d — phase 0's tolerated-unknown-keys notice ends\n* here): a typo'd protocol key must fail, not silently not-apply, because\n* these are fleet-consensus settings. `config` stays loose — it is\n* runner-defined by design.\n*/\nconst profileSchema = z.strictObject({\n\tappId: z.string().min(1).optional(),\n\tname: z.string().min(1).optional(),\n\tdescription: z.string().optional(),\n\ticon: z.string().optional()\n}).optional();\nconst reactorProtocolSchema = z.strictObject({\n\tfeatureFlags: z.strictObject({\n\t\tdocumentDecisions: z.boolean().optional(),\n\t\tauthEnforcement: z.boolean().optional(),\n\t\tauthGroups: z.boolean().optional(),\n\t\tauthConditions: z.boolean().optional()\n\t}).optional(),\n\tcreateSignaturePolicy: z.enum([\"legacy\", \"v2-required\"]).optional(),\n\tunsupportedStoredDocuments: z.enum([\"refuse\", \"read-only\"]).optional()\n});\nconst reactorBackendSchema = z.strictObject({\n\tkind: z.enum([\n\t\t\"in-process\",\n\t\t\"worker\",\n\t\t\"remote\"\n\t]).optional(),\n\tstorage: z.strictObject({\n\t\tkind: z.enum([\n\t\t\t\"idb\",\n\t\t\t\"memory\",\n\t\t\t\"path\",\n\t\t\t\"postgres\"\n\t\t]),\n\t\tdataDir: z.string().optional(),\n\t\turl: z.string().optional()\n\t}).optional(),\n\treadModel: z.strictObject({ url: z.string().optional() }).optional(),\n\tpackages: z.strictObject({\n\t\tcdnUrl: z.string().optional(),\n\t\tspecs: z.array(z.string()).optional(),\n\t\tdynamic: z.boolean().optional()\n\t}).optional(),\n\tremote: z.strictObject({\n\t\thost: z.string().optional(),\n\t\turl: z.string().optional()\n\t}).optional(),\n\tprojection: z.strictObject({\n\t\tenabled: z.boolean().optional(),\n\t\tdbPoolSize: z.number().int().positive().optional()\n\t}).optional(),\n\texecutors: z.strictObject({ numWorkers: z.union([z.number().int().positive(), z.literal(\"auto\")]).optional() }).optional()\n});\nconst reactorSchema = z.strictObject({\n\tbackends: z.record(z.string(), reactorBackendSchema).optional(),\n\tplacement: z.strictObject({\n\t\tprimary: z.string().optional(),\n\t\tdefault: z.looseObject({}).optional()\n\t}).optional(),\n\tprotocol: reactorProtocolSchema.optional(),\n\t/** DEPRECATED (dies in R2): workflows become a listed plugin — presence is\n\t* activation. Kept parsing until the switchboard rewire lands. */\n\tworkflows: z.boolean().optional(),\n\trenown: z.strictObject({\n\t\turl: z.string().optional(),\n\t\tnetworkId: z.string().optional(),\n\t\tchainId: z.number().int().optional()\n\t}).optional(),\n\tpackages: z.strictObject({ registryUrl: z.string().optional() }).optional(),\n\tnamespace: z.string().min(1).optional(),\n\tauth: z.strictObject({\n\t\tenabled: z.boolean().optional(),\n\t\tadmins: z.array(z.string()).optional(),\n\t\trenown: z.looseObject({}).optional()\n\t}).optional(),\n\tdrives: drivesSchema.optional()\n});\n/** Common runner options every host.runner carries; runner modules extend it\n* loosely with their own process options. */\nconst runnerBaseSchema = z.looseObject({\n\tmodule: z.string().min(1),\n\tdefaultVerb: z.string().optional(),\n\tport: z.number().int().positive().optional(),\n\t/** Bind address; each runner documents its default (0.0.0.0 for servers,\n\t* localhost for vite dev, 127.0.0.1 for serve). */\n\thost: z.string().min(1).optional(),\n\t/** THE COMPOSITION: the plugin entries this host boots with. Presence is\n\t* activation; see plugins.ts for entry semantics. */\n\tplugins: z.array(pluginEntrySchema).optional()\n});\n/** A compound's children map (mutually exclusive with `reactor` — the XOR is\n* structural, enforced by the loader; schemas validate each side's shape). */\nconst childrenSchema = z.record(z.string(), z.strictObject({\n\thost: z.string().min(1),\n\trunner: z.looseObject({}).optional(),\n\tconfig: z.looseObject({}).optional(),\n\treactor: reactorSchema.optional()\n}));\n/** Composed generic host shapes — the basis for the emitted editor schemas\n* (D2.a). Runner packages extend these with their own runner options; `config`\n* stays loose by design. */\nconst reactorHostSchema = z.looseObject({\n\tname: z.string().min(1),\n\trunner: runnerBaseSchema,\n\tconfig: z.looseObject({}).optional(),\n\tprofile: profileSchema,\n\treactor: reactorSchema.optional()\n});\nconst compoundHostSchema = z.looseObject({\n\tname: z.string().min(1),\n\trunner: runnerBaseSchema,\n\tchildren: childrenSchema,\n\tconfig: z.looseObject({}).optional(),\n\tprofile: profileSchema\n});\nconst SCHEMA_BASE = \"https://powerhouse.inc/schemas\";\n/** The emitted-schema set, keyed by published filename. Pure — the\n* emit-schemas script writes these to disk and the drift test re-derives\n* them, per the runtime-config-schema pattern. */\nfunction emittedHostSchemas() {\n\tconst emit = (name, schema) => ({\n\t\t$id: `${SCHEMA_BASE}/${name}.schema.json`,\n\t\t...z.toJSONSchema(schema, { io: \"input\" })\n\t});\n\treturn {\n\t\t\"host-reactor.schema.json\": emit(\"host-reactor\", reactorHostSchema),\n\t\t\"host-compound.schema.json\": emit(\"host-compound\", compoundHostSchema)\n\t};\n}\n//#endregion\nexport { 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 };\n\n//# sourceMappingURL=host-schemas-CL_wFpY7.mjs.map"],"names":["z.strictObject","z.string","z.boolean","z.enum","z.array","z.number","z.union","z.literal","z.record","z.looseObject"],"mappings":";;;;;;;;;;;;;;;;AAcA,SAAS,aAAa,OAAO;CAC5B,OAAO,WAAW;AACnB;AACA,MAAM,YAAY,UAAU,aAAa,KAAK,IAAI,SAAS,MAAM,OAAO,MAAM;;;;;;;;AAQ9E,SAAS,mBAAmB,GAAG,QAAQ;CACtC,MAAM,uBAAuB,IAAI,IAAI;CACrC,MAAM,MAAM,CAAC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BAAmBA,YAAc;CACtC,QAAQR,OAAS,CAAC,CAAC,IAAI,CAAC;CACxB,aAAaA,OAAS,CAAC,CAAC,SAAS;CACjC,MAAMI,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;;;CAG3C,MAAMJ,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;CAGjC,SAASG,MAAQ,iBAAiB,CAAC,CAAC,SAAS;AAC9C,CAAC;;;AAGD,MAAM,iBAAiBI,OAASP,OAAS,GAAGD,aAAe;CAC1D,MAAMC,OAAS,CAAC,CAAC,IAAI,CAAC;CACtB,QAAQQ,YAAc,CAAC,CAAC,CAAC,CAAC,SAAS;CACnC,QAAQA,YAAc,CAAC,CAAC,CAAC,CAAC,SAAS;CACnC,SAAS,cAAc,SAAS;AACjC,CAAC,CAAC;AAIwBA,YAAc;CACvC,MAAMR,OAAS,CAAC,CAAC,IAAI,CAAC;CACtB,QAAQ;CACR,QAAQQ,YAAc,CAAC,CAAC,CAAC,CAAC,SAAS;CACnC,SAAS;CACT,SAAS,cAAc,SAAS;AACjC,CAAC;AAC0BA,YAAc;CACxC,MAAMR,OAAS,CAAC,CAAC,IAAI,CAAC;CACtB,QAAQ;CACR,UAAU;CACV,QAAQQ,YAAc,CAAC,CAAC,CAAC,CAAC,SAAS;CACnC,SAAS;AACV,CAAC","debug_id":"743f1b82-6dd0-55e7-988d-09d953939295"}
@@ -1,4 +0,0 @@
1
- import { n as phCliCommands } from "./ph-cli-commands-CLJP7yKV.mjs";
2
- export { phCliCommands };
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7e26f2e3-6e52-5756-a7a8-11ac6c583b99")}catch(e){}}();
4
- //# debugId=7e26f2e3-6e52-5756-a7a8-11ac6c583b99
@@ -1,4 +0,0 @@
1
- import { r as startSwitchboard } from "./switchboard-tQS3fhqa.mjs";
2
- export { startSwitchboard };
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54e39bab-94e6-5440-9af6-8843b25d4c2b")}catch(e){}}();
4
- //# debugId=54e39bab-94e6-5440-9af6-8843b25d4c2b
@@ -1 +0,0 @@
1
- {"version":3,"file":"switchboard-reset-CX_Lzw3O.mjs","sources":["../src/services/switchboard-reset.ts"],"sourcesContent":["import { yellow, red, green, cyan } from \"colorette\";\nimport { promises as fs } from \"node:fs\";\n\nexport interface ResetSwitchboardOptions {\n dbPath?: string;\n yes?: boolean;\n}\n\nexport interface ResolvedResetPaths {\n reactorDir: string | null;\n readModelDir: string | null;\n postgresUrl: string | null;\n}\n\nconst CONFIRMATION_TOKEN = \"reset\";\n\nexport function isPostgresUrl(url: string): boolean {\n return url.startsWith(\"postgresql://\") || url.startsWith(\"postgres://\");\n}\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\n/**\n * Resolves the on-disk PGlite directories that `--reset` would delete.\n * Mirrors the resolution in apps/switchboard/src/server.mts so we touch the\n * same paths the running switchboard uses. When a Postgres URL is configured\n * the corresponding directory is null and `postgresUrl` is populated so the\n * caller can refuse.\n */\nexport function resolveResetPaths(\n options: ResetSwitchboardOptions,\n env: NodeJS.ProcessEnv = process.env,\n): ResolvedResetPaths {\n const readModelDbPath =\n options.dbPath ?? env.DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL;\n const readModelPath = readModelDbPath || \".ph/read-storage\";\n const reactorDbUrl =\n options.dbPath ??\n env.PH_REACTOR_DATABASE_URL ??\n env.PH_SWITCHBOARD_DATABASE_URL;\n const reactorPath = reactorDbUrl || \"./.ph/reactor-storage\";\n\n const reactorIsPostgres = !!reactorDbUrl && isPostgresUrl(reactorDbUrl);\n const readModelIsPostgres =\n !!readModelDbPath && isPostgresUrl(readModelDbPath);\n\n let postgresUrl: string | null = null;\n if (reactorIsPostgres) postgresUrl = reactorDbUrl as string;\n else if (readModelIsPostgres) postgresUrl = readModelDbPath as string;\n\n return {\n reactorDir: reactorIsPostgres ? null : reactorPath,\n readModelDir: readModelIsPostgres ? null : readModelPath,\n postgresUrl,\n };\n}\n\nasync function promptForConfirmation(): Promise<boolean> {\n const enquirer = await import(\"enquirer\");\n try {\n const answer = await enquirer.default.prompt<{ confirmation: string }>({\n type: \"input\",\n name: \"confirmation\",\n message: `Type \"${CONFIRMATION_TOKEN}\" to confirm wiping the local switchboard databases:`,\n });\n return answer.confirmation.trim() === CONFIRMATION_TOKEN;\n } catch {\n return false;\n }\n}\n\nexport async function resetSwitchboardDatabase(\n options: ResetSwitchboardOptions,\n): Promise<void> {\n const paths = resolveResetPaths(options);\n\n if (paths.postgresUrl) {\n console.error(\n red(\n `Refusing to reset: a PostgreSQL URL is configured (${paths.postgresUrl}).`,\n ),\n );\n console.error(\n yellow(\n \"`ph switchboard --reset` only wipes the local PGlite stores. \" +\n \"To reset a Postgres-backed switchboard, drop/recreate the database manually.\",\n ),\n );\n process.exit(1);\n }\n\n const targets = [paths.reactorDir, paths.readModelDir].filter(\n (d): d is string => d !== null,\n );\n\n if (targets.length === 0) {\n console.error(red(\"No local PGlite directories resolved; nothing to do.\"));\n process.exit(1);\n }\n\n console.log(yellow(\"The following directories will be permanently deleted:\"));\n for (const dir of targets) {\n console.log(` - ${dir}`);\n }\n console.log(\n yellow(\n \"This will wipe all local switchboard state. Migrations will re-run on next `ph switchboard`.\",\n ),\n );\n\n let confirmed = false;\n if (options.yes) {\n confirmed = true;\n } else if (isInteractive()) {\n confirmed = await promptForConfirmation();\n } else {\n console.error(\n red(\n \"Refusing to reset in a non-interactive context without --yes. Re-run with --yes to confirm.\",\n ),\n );\n process.exit(1);\n }\n\n if (!confirmed) {\n console.error(red(\"Aborted: confirmation not provided.\"));\n process.exit(1);\n }\n\n for (const dir of targets) {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(cyan(`Removed ${dir}`));\n }\n\n console.log(\n green(\n \"Switchboard local storage reset. Run `ph switchboard` to re-initialize.\",\n ),\n );\n}\n"],"names":["fs"],"mappings":";;;;;AAcA,MAAM,qBAAqB;AAE3B,SAAgB,cAAc,KAAsB;CAClD,OAAO,IAAI,WAAW,eAAe,KAAK,IAAI,WAAW,aAAa;AACxE;AAEA,SAAS,gBAAyB;CAChC,OAAO,QAAQ,QAAQ,MAAM,KAAK,KAAK,CAAC,QAAQ,IAAI;AACtD;;;;;;;;AASA,SAAgB,kBACd,SACA,MAAyB,QAAQ,KACb;CACpB,MAAM,kBACJ,QAAQ,UAAU,IAAI,gBAAgB,IAAI;CAC5C,MAAM,gBAAgB,mBAAmB;CACzC,MAAM,eACJ,QAAQ,UACR,IAAI,2BACJ,IAAI;CACN,MAAM,cAAc,gBAAgB;CAEpC,MAAM,oBAAoB,CAAC,CAAC,gBAAgB,cAAc,YAAY;CACtE,MAAM,sBACJ,CAAC,CAAC,mBAAmB,cAAc,eAAe;CAEpD,IAAI,cAA6B;CACjC,IAAI,mBAAmB,cAAc;MAChC,IAAI,qBAAqB,cAAc;CAE5C,OAAO;EACL,YAAY,oBAAoB,OAAO;EACvC,cAAc,sBAAsB,OAAO;EAC3C;CACF;AACF;AAEA,eAAe,wBAA0C;CACvD,MAAM,WAAW,MAAM,OAAO;CAC9B,IAAI;EAMF,QAAO,MALc,SAAS,QAAQ,OAAiC;GACrE,MAAM;GACN,MAAM;GACN,SAAS,SAAS,mBAAmB;EACvC,CAAC,EAAA,CACa,aAAa,KAAK,MAAM;CACxC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAsB,yBACpB,SACe;CACf,MAAM,QAAQ,kBAAkB,OAAO;CAEvC,IAAI,MAAM,aAAa;EACrB,QAAQ,MACN,IACE,sDAAsD,MAAM,Y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