@powerhousedao/ph-cli 6.2.3-dev.7 → 6.2.3-dev.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/{auth-AR3VxAIk.mjs → auth-BFUq7CvE.mjs} +3 -3
  2. package/dist/{auth-AR3VxAIk.mjs.map → auth-BFUq7CvE.mjs.map} +1 -1
  3. package/dist/auth-CNhbN5UM.mjs +4 -0
  4. package/dist/build-C78yPntL.mjs +4 -0
  5. package/dist/build-Dj8qfSSe.mjs +349 -0
  6. package/dist/build-Dj8qfSSe.mjs.map +1 -0
  7. package/dist/{cli-connect-override-D3hh4aH_.mjs → cli-connect-override-CEJhQWRX.mjs} +39 -27
  8. package/dist/cli-connect-override-CEJhQWRX.mjs.map +1 -0
  9. package/dist/cli.d.mts +2 -1
  10. package/dist/cli.mjs +31 -1175
  11. package/dist/cli.mjs.map +1 -1
  12. package/dist/compound-B6RZMA0Y-Cv3XMQ3Y.mjs +2459 -0
  13. package/dist/compound-B6RZMA0Y-Cv3XMQ3Y.mjs.map +1 -0
  14. package/dist/connect-build-BfhOGbha.mjs +253 -0
  15. package/dist/connect-build-BfhOGbha.mjs.map +1 -0
  16. package/dist/{connect-config-BWGiW3IB.mjs → connect-config-DblqJgxR.mjs} +19 -12
  17. package/dist/connect-config-DblqJgxR.mjs.map +1 -0
  18. package/dist/connect-plugin-configs-D2fwYpMw.mjs +50 -0
  19. package/dist/connect-plugin-configs-D2fwYpMw.mjs.map +1 -0
  20. package/dist/connect-preview-8-qLgWKt.mjs +215 -0
  21. package/dist/connect-preview-8-qLgWKt.mjs.map +1 -0
  22. package/dist/{connect-studio-D6rfWCNB.mjs → connect-studio-DX7r4iyI.mjs} +18 -11
  23. package/dist/connect-studio-DX7r4iyI.mjs.map +1 -0
  24. package/dist/connect-studio-DmjcV8I2.mjs +4 -0
  25. package/dist/dist-CCLkwpTS.mjs +313 -0
  26. package/dist/dist-CCLkwpTS.mjs.map +1 -0
  27. package/dist/explain-DUXbB9jf.mjs +241 -0
  28. package/dist/explain-DUXbB9jf.mjs.map +1 -0
  29. package/dist/feature-flags-xwqcHEWC.mjs +4 -0
  30. package/dist/{generate-all-DrT4ZxHX.mjs → generate-all-Dgyy_kT-.mjs} +9 -3
  31. package/dist/generate-all-Dgyy_kT-.mjs.map +1 -0
  32. package/dist/{generate-app-DNNqA-H3.mjs → generate-app-BTs1u-9l.mjs} +7 -5
  33. package/dist/{generate-app-DNNqA-H3.mjs.map → generate-app-BTs1u-9l.mjs.map} +1 -1
  34. package/dist/generate-desktop-shell-Bj_3bJDL.mjs +317 -0
  35. package/dist/generate-desktop-shell-Bj_3bJDL.mjs.map +1 -0
  36. package/dist/{generate-document-model-BJXyODfm.mjs → generate-document-model-BfFIQ35q.mjs} +19 -7
  37. package/dist/generate-document-model-BfFIQ35q.mjs.map +1 -0
  38. package/dist/{generate-editor-BejvaVVT.mjs → generate-editor-CW7Do69u.mjs} +7 -5
  39. package/dist/{generate-editor-BejvaVVT.mjs.map → generate-editor-CW7Do69u.mjs.map} +1 -1
  40. package/dist/generate-hosts-BFmPIW2X.mjs +18 -0
  41. package/dist/generate-hosts-BFmPIW2X.mjs.map +1 -0
  42. package/dist/generate-hosts-RWj7WPHZ.mjs +4 -0
  43. package/dist/generate-piece-QTt-ddt2.mjs +65 -0
  44. package/dist/generate-piece-QTt-ddt2.mjs.map +1 -0
  45. package/dist/generate-piece-action-DbxrzfKY.mjs +29 -0
  46. package/dist/generate-piece-action-DbxrzfKY.mjs.map +1 -0
  47. package/dist/generate-piece-trigger-CqVOcL9g.mjs +30 -0
  48. package/dist/generate-piece-trigger-CqVOcL9g.mjs.map +1 -0
  49. package/dist/{generate-processor-_WOx-mMe.mjs → generate-processor-DBtTkgo5.mjs} +15 -8
  50. package/dist/generate-processor-DBtTkgo5.mjs.map +1 -0
  51. package/dist/{generate-subgraph-BsHUstpl.mjs → generate-subgraph-CVlTo7qk.mjs} +12 -6
  52. package/dist/generate-subgraph-CVlTo7qk.mjs.map +1 -0
  53. package/dist/index-BIbx17vt.d.mts +4459 -0
  54. package/dist/index-BIbx17vt.d.mts.map +1 -0
  55. package/dist/{init-BZP6gvYd.mjs → init-ScuT3z7P.mjs} +7 -5
  56. package/dist/init-ScuT3z7P.mjs.map +1 -0
  57. package/dist/{inspect-DXjbQEV_.mjs → inspect-zWJnBDMJ.mjs} +11 -4
  58. package/dist/inspect-zWJnBDMJ.mjs.map +1 -0
  59. package/dist/install-added-dependencies-DVSbzler.mjs +33 -0
  60. package/dist/install-added-dependencies-DVSbzler.mjs.map +1 -0
  61. package/dist/{migrate-jGKfE02L.mjs → migrate-DK4HK7Dn.mjs} +4 -4
  62. package/dist/{migrate-jGKfE02L.mjs.map → migrate-DK4HK7Dn.mjs.map} +1 -1
  63. package/dist/ph-cli-commands-BhzvcuzR.mjs +4 -0
  64. package/dist/ph-cli-commands-pyxDifSE.mjs +1493 -0
  65. package/dist/ph-cli-commands-pyxDifSE.mjs.map +1 -0
  66. package/dist/precompress-P6cJDPVC.mjs +77 -0
  67. package/dist/precompress-P6cJDPVC.mjs.map +1 -0
  68. package/dist/{registry-auth-DxEWCJu2.mjs → registry-auth-Bm5AR-fB.mjs} +4 -4
  69. package/dist/{registry-auth-DxEWCJu2.mjs.map → registry-auth-Bm5AR-fB.mjs.map} +1 -1
  70. package/dist/run-sugar-Ns53R6lU.mjs +39 -0
  71. package/dist/run-sugar-Ns53R6lU.mjs.map +1 -0
  72. package/dist/runners/connect.d.mts +1173 -0
  73. package/dist/runners/connect.d.mts.map +1 -0
  74. package/dist/runners/connect.mjs +270 -0
  75. package/dist/runners/connect.mjs.map +1 -0
  76. package/dist/runners/switchboard.d.mts +340 -0
  77. package/dist/runners/switchboard.d.mts.map +1 -0
  78. package/dist/runners/switchboard.mjs +294 -0
  79. package/dist/runners/switchboard.mjs.map +1 -0
  80. package/dist/schemas-D5N5U_Mf.mjs +5738 -0
  81. package/dist/schemas-D5N5U_Mf.mjs.map +1 -0
  82. package/dist/scripts/emit-runner-schemas.ts +24 -0
  83. package/dist/scripts/generate-commands-docs.ts +8 -0
  84. package/dist/scripts/manage-environment +0 -0
  85. package/dist/scripts/setup.sh +0 -0
  86. package/dist/start-run-BIaYSpHh.mjs +124 -0
  87. package/dist/start-run-BIaYSpHh.mjs.map +1 -0
  88. package/dist/superseded-config-CbSTFun2.mjs +53 -0
  89. package/dist/superseded-config-CbSTFun2.mjs.map +1 -0
  90. package/dist/switchboard-C5zgkRl2.mjs +4 -0
  91. package/dist/switchboard-h4-XgP1h.mjs +129 -0
  92. package/dist/switchboard-h4-XgP1h.mjs.map +1 -0
  93. package/dist/{switchboard-migrate-NQ7LHWSi.mjs → switchboard-migrate-7JQZM7-5.mjs} +5 -4
  94. package/dist/{switchboard-migrate-NQ7LHWSi.mjs.map → switchboard-migrate-7JQZM7-5.mjs.map} +1 -1
  95. package/dist/{switchboard-reset-BcQXlcVf.mjs → switchboard-reset-MtTB_GAI.mjs} +8 -6
  96. package/dist/switchboard-reset-MtTB_GAI.mjs.map +1 -0
  97. package/dist/{utils-C4isxXSO.mjs → utils-9KyRM0mf.mjs} +6 -34
  98. package/dist/{utils-C4isxXSO.mjs.map → utils-9KyRM0mf.mjs.map} +1 -1
  99. package/dist/utils-DAux4Ga7.mjs +4 -0
  100. package/dist/{vetra-DkF6EJMY.mjs → vetra-CnrGDPX0.mjs} +70 -35
  101. package/dist/vetra-CnrGDPX0.mjs.map +1 -0
  102. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs +19 -0
  103. package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +1 -0
  104. package/package.json +39 -18
  105. package/dist/auth-BNkN6kS9.mjs +0 -4
  106. package/dist/build-C-A5-ipO.mjs +0 -4
  107. package/dist/build-uQXq6_HU.mjs +0 -71
  108. package/dist/build-uQXq6_HU.mjs.map +0 -1
  109. package/dist/cli-connect-override-D3hh4aH_.mjs.map +0 -1
  110. package/dist/connect-build-WL4axo4z.mjs +0 -43
  111. package/dist/connect-build-WL4axo4z.mjs.map +0 -1
  112. package/dist/connect-config-BWGiW3IB.mjs.map +0 -1
  113. package/dist/connect-preview-D7ypzFDc.mjs +0 -28
  114. package/dist/connect-preview-D7ypzFDc.mjs.map +0 -1
  115. package/dist/connect-studio-BIQzyq5B.mjs +0 -5
  116. package/dist/connect-studio-D6rfWCNB.mjs.map +0 -1
  117. package/dist/generate-all-DrT4ZxHX.mjs.map +0 -1
  118. package/dist/generate-document-model-BJXyODfm.mjs.map +0 -1
  119. package/dist/generate-processor-_WOx-mMe.mjs.map +0 -1
  120. package/dist/generate-subgraph-BsHUstpl.mjs.map +0 -1
  121. package/dist/init-BZP6gvYd.mjs.map +0 -1
  122. package/dist/inspect-DXjbQEV_.mjs.map +0 -1
  123. package/dist/switchboard-CJMoMzWx.mjs +0 -75
  124. package/dist/switchboard-CJMoMzWx.mjs.map +0 -1
  125. package/dist/switchboard-iRFugh8I.mjs +0 -4
  126. package/dist/switchboard-reset-BcQXlcVf.mjs.map +0 -1
  127. package/dist/utils-BzwczAW-.mjs +0 -4
  128. package/dist/vetra-DkF6EJMY.mjs.map +0 -1
@@ -0,0 +1,215 @@
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]="bccaf695-1303-5b73-91f4-0f1423bc1c73")}catch(e){}}();
3
+ import { t as PRECOMPRESS_EXTENSIONS } from "./precompress-P6cJDPVC.mjs";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { deepMerge, normalizeBasePath } from "@powerhousedao/shared/connect";
7
+ import { preview } from "vite";
8
+ import { getConfig } from "@powerhousedao/config/node";
9
+ import sirv from "sirv";
10
+ //#region src/services/connect-preview.ts
11
+ /**
12
+ * The env contract a supervisor can drive the preview with — the same
13
+ * variables the Docker entrypoint and clint's service manager already speak:
14
+ * PH_CONNECT_DEFAULT_DRIVES_URL (comma-separated drive urls, injected into
15
+ * drives.defaultDrives), PH_CONNECT_DRIVES_PRESERVE_STRATEGY, and
16
+ * PH_CONNECT_PACKAGES_REGISTRY (runtime registry: served config + baked-CSP
17
+ * patch). Lets `ph connect preview` replace hand-rolled static servers
18
+ * (clint's connect-server, the ph-win sidecar) without losing injection.
19
+ */
20
+ function overrideFromEnv(env = process.env) {
21
+ const drivesUrl = env.PH_CONNECT_DEFAULT_DRIVES_URL;
22
+ const registry = env.PH_CONNECT_PACKAGES_REGISTRY;
23
+ if (!drivesUrl && !registry) return void 0;
24
+ const override = {};
25
+ if (drivesUrl) override.connect = { drives: {
26
+ defaultDrives: drivesUrl.split(",").map((s) => s.trim()).filter(Boolean).map((url) => ({
27
+ url,
28
+ name: null,
29
+ icon: null
30
+ })),
31
+ preserveStrategy: env.PH_CONNECT_DRIVES_PRESERVE_STRATEGY ?? "preserve-all"
32
+ } };
33
+ if (registry) {
34
+ override.packageRegistryUrl = registry;
35
+ override.cspRegistrySync = true;
36
+ }
37
+ return override;
38
+ }
39
+ function mergedConfigBody(outDir, override) {
40
+ const file = path.join(outDir, "powerhouse.config.json");
41
+ const baked = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
42
+ const connect = override.connect ? deepMerge(baked.connect ?? {}, override.connect) : baked.connect;
43
+ return JSON.stringify({
44
+ ...baked,
45
+ connect,
46
+ ...override.packageRegistryUrl ? { packageRegistryUrl: override.packageRegistryUrl } : {}
47
+ });
48
+ }
49
+ /**
50
+ * Append the registry origin to the baked CSP's script-src. The attribute
51
+ * value is HTML-escaped (every CSP keyword is `'`-quoted, which contains a
52
+ * semicolon), so decode before touching directives and re-escape after —
53
+ * ported from the ph-win-desktop sidecar, which this path replaces.
54
+ */
55
+ function patchCspScriptSrc(html, registryUrl) {
56
+ return html.replace(/(<meta\s+http-equiv="Content-Security-Policy"\s+content=")([^"]*)(")/i, (_match, open, escaped, close) => {
57
+ const policy = escaped.replace(/&amp;/g, "&").replace(/&#39;/g, "'");
58
+ if (policy.includes(registryUrl)) return open + escaped + close;
59
+ return open + policy.replace(/script-src\s+([^;]*)/i, (_directive, sources) => `script-src ${sources.trim()} ${registryUrl}`).replace(/&/g, "&amp;").replace(/'/g, "&#39;") + close;
60
+ });
61
+ }
62
+ function resolvePreviewBase(argBase, outDirAbs) {
63
+ if (argBase && argBase !== "/") return normalizeBasePath(argBase);
64
+ try {
65
+ const basePath = JSON.parse(readFileSync(path.join(outDirAbs, "powerhouse.config.json"), "utf8")).connect?.app?.basePath;
66
+ if (typeof basePath === "string" && basePath) return normalizeBasePath(basePath);
67
+ } catch {}
68
+ }
69
+ function stripBase(pathname, base) {
70
+ return base !== "/" && pathname.startsWith(base) ? `/${pathname.slice(base.length)}` : pathname;
71
+ }
72
+ const IMMUTABLE = "public, max-age=31536000, immutable";
73
+ const HASHED_DIRS = [
74
+ "/assets/",
75
+ "/fonts/",
76
+ "/__reactor_worker__/assets/"
77
+ ];
78
+ function previewCacheControl(pathname, search) {
79
+ if (HASHED_DIRS.some((dir) => pathname.startsWith(dir))) return IMMUTABLE;
80
+ if (pathname.startsWith("/__vendor__/")) return /\/(shared-deps|import-map)\.js(on)?$/.test(pathname) ? "no-cache" : IMMUTABLE;
81
+ if (pathname.startsWith("/__react__/")) return IMMUTABLE;
82
+ if (pathname.startsWith("/__reactor_worker__/")) return new URLSearchParams(search).has("v") ? IMMUTABLE : "no-cache";
83
+ }
84
+ function previewCacheHeadersPlugin(outDir, base) {
85
+ return {
86
+ name: "ph:preview-cache-headers",
87
+ configurePreviewServer(server) {
88
+ server.middlewares.use((req, res, next) => {
89
+ const [rawPath, search = ""] = (req.url ?? "/").split("?");
90
+ const rel = stripBase(rawPath, base);
91
+ let value = previewCacheControl(rel, search);
92
+ if (value === IMMUTABLE && !existsSync(path.join(outDir, rel))) value = void 0;
93
+ if (value) res.setHeader("Cache-Control", value);
94
+ next();
95
+ });
96
+ }
97
+ };
98
+ }
99
+ /** The dist's shell for the served config: its composition's variant and its app name. */
100
+ async function shellSwapFor(outDir, override, base = "/") {
101
+ const composition = override.connect?.composition;
102
+ const renamed = override.connect?.branding?.appName !== void 0;
103
+ if (!composition && !renamed) return void 0;
104
+ const { APP_SHELLS_FILE, appShellVariant, appShellVariantOf, readShellPluginsIn, swapAppShell, withShellAppName } = await import("@powerhousedao/builder-tools");
105
+ const file = path.join(outDir, APP_SHELLS_FILE);
106
+ const variant = composition && appShellVariant(composition, readShellPluginsIn(outDir));
107
+ const shell = variant && existsSync(file) ? JSON.parse(readFileSync(file, "utf8"))[variant] : void 0;
108
+ const appName = JSON.parse(mergedConfigBody(outDir, override)).connect?.branding?.appName;
109
+ return (html) => shell && appShellVariantOf(html) !== variant ? swapAppShell(html, shell, base, appName) : withShellAppName(html, appName);
110
+ }
111
+ function serveOverridePlugin(outDir, override, base = "/", swapShell) {
112
+ return {
113
+ name: "ph:serve-override",
114
+ configurePreviewServer(server) {
115
+ server.middlewares.use((req, res, next) => {
116
+ const urlPath = stripBase((req.url ?? "/").split("?")[0], base);
117
+ if (urlPath === "/powerhouse.config.json") {
118
+ res.writeHead(200, {
119
+ "content-type": "application/json; charset=utf-8",
120
+ "cache-control": "no-store"
121
+ });
122
+ res.end(mergedConfigBody(outDir, override));
123
+ return;
124
+ }
125
+ const isHtml = urlPath === "/" || urlPath.endsWith("/index.html") || !path.extname(urlPath);
126
+ if ((override.cspRegistrySync || swapShell) && isHtml) {
127
+ const file = path.join(outDir, "index.html");
128
+ if (existsSync(file)) {
129
+ let html = readFileSync(file, "utf8");
130
+ if (override.cspRegistrySync) {
131
+ const registry = JSON.parse(mergedConfigBody(outDir, override)).packageRegistryUrl;
132
+ if (registry) html = patchCspScriptSrc(html, registry);
133
+ }
134
+ if (swapShell) html = swapShell(html);
135
+ res.writeHead(200, {
136
+ "content-type": "text/html; charset=utf-8",
137
+ "cache-control": "no-store"
138
+ });
139
+ res.end(html);
140
+ return;
141
+ }
142
+ }
143
+ next();
144
+ });
145
+ }
146
+ };
147
+ }
148
+ const PRECOMPRESSED_TYPES = {
149
+ ".wasm": "application/wasm",
150
+ ".data": "application/octet-stream"
151
+ };
152
+ function precompressedAssetsPlugin(outDir, base = "/") {
153
+ return {
154
+ name: "ph:precompressed-assets",
155
+ configurePreviewServer(server) {
156
+ const headers = server.config.preview.headers;
157
+ const serve = sirv(outDir, {
158
+ dev: true,
159
+ etag: true,
160
+ gzip: true,
161
+ extensions: [],
162
+ setHeaders(res, pathname) {
163
+ if (headers) for (const k in headers) res.setHeader(k, headers[k]);
164
+ res.setHeader("Content-Type", PRECOMPRESSED_TYPES[path.extname(pathname)]);
165
+ }
166
+ });
167
+ server.middlewares.use((req, res, next) => {
168
+ const url = req.url ?? "/";
169
+ const [rawPath, search] = url.split("?");
170
+ const rel = stripBase(rawPath, base);
171
+ if (!PRECOMPRESS_EXTENSIONS.includes(path.extname(rel)) || req.headers.range || base !== "/" && rel === rawPath) return next();
172
+ req.url = search === void 0 ? rel : `${rel}?${search}`;
173
+ serve(req, res, () => {
174
+ req.url = url;
175
+ next();
176
+ });
177
+ });
178
+ }
179
+ };
180
+ }
181
+ async function runConnectPreview(args, serveOverride, dirname = process.cwd()) {
182
+ serveOverride ??= overrideFromEnv();
183
+ const { outDir, port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } = args;
184
+ const mode = "production";
185
+ const sourceBasePath = getConfig(path.join(dirname, "powerhouse.config.json")).connect?.app?.basePath;
186
+ const outDirAbs = path.resolve(dirname, outDir);
187
+ const base = resolvePreviewBase(args.connectBasePath, outDirAbs) ?? (sourceBasePath ? normalizeBasePath(sourceBasePath) : "/");
188
+ const previewConfig = {
189
+ configFile: false,
190
+ mode,
191
+ base,
192
+ build: { outDir: outDirAbs },
193
+ preview: {
194
+ cors,
195
+ port,
196
+ strictPort,
197
+ host,
198
+ open
199
+ },
200
+ plugins: [
201
+ previewCacheHeadersPlugin(outDirAbs, base),
202
+ precompressedAssetsPlugin(outDirAbs, base),
203
+ ...serveOverride ? [serveOverridePlugin(outDirAbs, serveOverride, base, await shellSwapFor(outDirAbs, serveOverride, base))] : []
204
+ ]
205
+ };
206
+ const server = await preview(previewConfig);
207
+ if (printUrls) server.printUrls();
208
+ if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });
209
+ return server;
210
+ }
211
+ //#endregion
212
+ export { runConnectPreview };
213
+
214
+ //# sourceMappingURL=connect-preview-8-qLgWKt.mjs.map
215
+ //# debugId=bccaf695-1303-5b73-91f4-0f1423bc1c73
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect-preview-8-qLgWKt.mjs","sources":["../src/services/connect-preview.ts"],"sourcesContent":["import { getConfig } from \"@powerhousedao/config/node\";\nimport type { AppShells } 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 sirv from \"sirv\";\nimport type { InlineConfig, Plugin } from \"vite\";\nimport { preview } from \"vite\";\nimport type { ConnectPreviewArgs } from \"../types.js\";\nimport { PRECOMPRESS_EXTENSIONS } from \"../utils/precompress.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\nconst HASHED_DIRS = [\"/assets/\", \"/fonts/\", \"/__reactor_worker__/assets/\"];\n\n// Content-addressed output (hashed names, or a `v` query on the worker's), as in the nginx image.\nexport function previewCacheControl(\n pathname: string,\n search: string,\n): string | undefined {\n if (HASHED_DIRS.some((dir) => pathname.startsWith(dir))) return IMMUTABLE;\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(outDir: string, 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 rel = stripBase(rawPath, base);\n let value = previewCacheControl(rel, search);\n // A cached 404 would outlive the next deploy.\n if (value === IMMUTABLE && !existsSync(path.join(outDir, rel))) {\n value = undefined;\n }\n if (value) res.setHeader(\"Cache-Control\", value);\n next();\n });\n },\n };\n}\n\ntype HtmlTransform = (html: string) => string;\n\n/** The dist's shell for the served config: its composition's variant and its app name. */\nexport async function shellSwapFor(\n outDir: string,\n override: ConnectServeOverride,\n base = \"/\",\n): Promise<HtmlTransform | undefined> {\n const composition = override.connect?.composition;\n const renamed = override.connect?.branding?.appName !== undefined;\n if (!composition && !renamed) return undefined;\n const {\n APP_SHELLS_FILE,\n appShellVariant,\n appShellVariantOf,\n readShellPluginsIn,\n swapAppShell,\n withShellAppName,\n } = await import(\"@powerhousedao/builder-tools\");\n const file = path.join(outDir, APP_SHELLS_FILE);\n // The manifest the build copied from the Connect it used.\n const variant =\n composition && appShellVariant(composition, readShellPluginsIn(outDir));\n const shell =\n variant && existsSync(file)\n ? (JSON.parse(readFileSync(file, \"utf8\")) as AppShells)[variant]\n : undefined;\n // The name the app will title itself with: the served (baked + override) config's.\n const appName = (\n JSON.parse(mergedConfigBody(outDir, override)) as {\n connect?: { branding?: { appName?: string } };\n }\n ).connect?.branding?.appName;\n return (html) =>\n shell && appShellVariantOf(html) !== variant\n ? swapAppShell(html, shell, base, appName)\n : withShellAppName(html, appName);\n}\n\nfunction serveOverridePlugin(\n outDir: string,\n override: ConnectServeOverride,\n base = \"/\",\n swapShell?: HtmlTransform,\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 || swapShell) && isHtml) {\n const file = path.join(outDir, \"index.html\");\n if (existsSync(file)) {\n let html = readFileSync(file, \"utf8\");\n if (override.cspRegistrySync) {\n const merged = JSON.parse(mergedConfigBody(outDir, override)) as {\n packageRegistryUrl?: string;\n };\n const registry = merged.packageRegistryUrl;\n if (registry) html = patchCspScriptSrc(html, registry);\n }\n if (swapShell) html = swapShell(html);\n res.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n res.end(html);\n return;\n }\n }\n next();\n });\n },\n };\n}\n\nconst PRECOMPRESSED_TYPES: Record<string, string> = {\n \".wasm\": \"application/wasm\",\n \".data\": \"application/octet-stream\",\n};\n\n// Serves the build's `.gz` siblings of wasm/data; Vite's sirv ignores them.\nexport function precompressedAssetsPlugin(outDir: string, base = \"/\"): Plugin {\n return {\n name: \"ph:precompressed-assets\",\n configurePreviewServer(server) {\n const headers = server.config.preview.headers;\n const serve = sirv(outDir, {\n dev: true,\n etag: true,\n gzip: true,\n extensions: [],\n setHeaders(res, pathname) {\n if (headers) for (const k in headers) res.setHeader(k, headers[k]!);\n res.setHeader(\n \"Content-Type\",\n PRECOMPRESSED_TYPES[path.extname(pathname)],\n );\n },\n });\n server.middlewares.use((req, res, next) => {\n const url = req.url ?? \"/\";\n const [rawPath, search] = url.split(\"?\");\n const rel = stripBase(rawPath, base);\n // Ranges are byte offsets into the identity body: leave them to Vite.\n if (\n !(PRECOMPRESS_EXTENSIONS as readonly string[]).includes(\n path.extname(rel),\n ) ||\n req.headers.range ||\n (base !== \"/\" && rel === rawPath)\n ) {\n return next();\n }\n req.url = search === undefined ? rel : `${rel}?${search}`;\n serve(req, res, () => {\n req.url = url;\n next();\n });\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 // Serving a dist needs only its base, not the build's plugin stack.\n const sourceBasePath = getConfig(path.join(dirname, \"powerhouse.config.json\"))\n .connect?.app?.basePath;\n const outDirAbs = path.resolve(dirname, outDir);\n const base =\n resolvePreviewBase(args.connectBasePath, outDirAbs) ??\n (sourceBasePath ? normalizeBasePath(sourceBasePath) : \"/\");\n\n const previewConfig: InlineConfig = {\n configFile: false,\n mode,\n base,\n build: {\n outDir: outDirAbs,\n },\n preview: {\n cors,\n port,\n strictPort,\n host,\n open,\n },\n plugins: [\n previewCacheHeadersPlugin(outDirAbs, base),\n precompressedAssetsPlugin(outDirAbs, base),\n ...(serveOverride\n ? [\n serveOverridePlugin(\n outDirAbs,\n serveOverride,\n base,\n await shellSwapFor(outDirAbs, serveOverride, base),\n ),\n ]\n : []),\n ],\n };\n\n const server = await preview(previewConfig);\n\n if (printUrls) server.printUrls();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });\n return server;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAsCA,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,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AK,iBAAiB,SAAS,MACjD,iBAAiB,kBAAkB,cAAc,IAAI;CAExD,MAAM,gBAA8B;EAClC,YAAY;EACZ;EACA;EACA,OAAO,EACL,QAAQ,UACV;EACA,SAAS;GACP;GACA;GACA;GACA;GACA;EACF;EACA,SAAS;GACP,0BAA0B,WAAW,IAAI;GACzC,0BAA0B,WAAW,IAAI;GACzC,GAAI,gBACA,CACE,oBACE,WACA,eACA,MACA,MAAM,aAAa,WAAW,eAAe,IAAI,CACnD,CACF,IACA,CAAC;EACP;CACF;CAEA,MAAM,SAAS,MAAM,QAAQ,aAAa;CAE1C,IAAI,WAAW,OAAO,UAAU;CAChC,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,KAAK,CAAC;CAC7D,OAAO;AACT","debug_id":"bccaf695-1303-5b73-91f4-0f1423bc1c73"}
@@ -1,16 +1,21 @@
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]="1de6dc60-070c-5573-97e3-eb528854853f")}catch(e){}}();
3
- import { r as buildStudioConnectOverride } from "./cli-connect-override-D3hh4aH_.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]="b17d6908-daf0-5322-b9d0-2ac650f7907a")}catch(e){}}();
3
+ import { r as buildStudioConnectOverride } from "./cli-connect-override-CEJhQWRX.mjs";
4
4
  import { getConnectBaseViteConfig } from "@powerhousedao/builder-tools";
5
5
  import { createServer, mergeConfig } from "vite";
6
6
  //#region src/services/connect-studio.ts
7
- async function runConnectStudio(args, customLogger, callerOverride) {
7
+ async function runConnectStudio(args, customLogger, callerOverride, { routes } = {}) {
8
8
  const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } = args;
9
- const server = await createServer(mergeConfig(getConnectBaseViteConfig({
10
- mode: "development",
11
- dirname: process.cwd(),
12
- cliConnectOverride: buildStudioConnectOverride(args, callerOverride)
13
- }), {
9
+ const mode = "development";
10
+ const dirname = process.cwd();
11
+ const cliConnectOverride = buildStudioConnectOverride(args, callerOverride);
12
+ const baseConfig = getConnectBaseViteConfig({
13
+ mode,
14
+ dirname,
15
+ cliConnectOverride,
16
+ routes
17
+ });
18
+ const config = mergeConfig(baseConfig, {
14
19
  server: {
15
20
  port,
16
21
  host,
@@ -19,13 +24,15 @@ async function runConnectStudio(args, customLogger, callerOverride) {
19
24
  strictPort
20
25
  },
21
26
  customLogger
22
- }));
27
+ });
28
+ const server = await createServer(config);
23
29
  await server.listen();
24
30
  if (printUrls) server.printUrls();
25
31
  if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });
32
+ return server;
26
33
  }
27
34
  //#endregion
28
35
  export { runConnectStudio as t };
29
36
 
30
- //# sourceMappingURL=connect-studio-D6rfWCNB.mjs.map
31
- //# debugId=1de6dc60-070c-5573-97e3-eb528854853f
37
+ //# sourceMappingURL=connect-studio-DX7r4iyI.mjs.map
38
+ //# debugId=b17d6908-daf0-5322-b9d0-2ac650f7907a
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect-studio-DX7r4iyI.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type { InlineConfig, Logger } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\n\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?: PHConnectRuntimeConfig,\n { routes }: { routes?: string | false } = {},\n) {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n\n const cliConnectOverride = buildStudioConnectOverride(args, callerOverride);\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride,\n routes,\n });\n\n const devServerConfig: InlineConfig = {\n server: { port, host, open, cors, strictPort },\n customLogger,\n };\n\n const config = mergeConfig(baseConfig, devServerConfig);\n\n const server = await createServer(config);\n\n await server.listen();\n\n if (printUrls) server.printUrls();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });\n return server;\n}\n"],"names":[],"mappings":";;;;;;AAOA,eAAsB,iBACpB,MACA,cACA,gBACA,EAAE,WAAwC,CAAC,GAC3C;CACA,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAE5B,MAAM,qBAAqB,2BAA2B,MAAM,cAAc;CAE1E,MAAM,aAAa,yBAAyB;EAC1C;EACA;EACA;EACA;CACF,CAAC;CAOD,MAAM,SAAS,YAAY,YAAY;EAJrC,QAAQ;GAAE;GAAM;GAAM;GAAM;GAAM;EAAW;EAC7C;CAGmD,CAAC;CAEtD,MAAM,SAAS,MAAM,aAAa,MAAM;CAExC,MAAM,OAAO,OAAO;CAEpB,IAAI,WAAW,OAAO,UAAU;CAChC,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,KAAK,CAAC;CAC7D,OAAO;AACT","debug_id":"b17d6908-daf0-5322-b9d0-2ac650f7907a"}
@@ -0,0 +1,4 @@
1
+ import { t as runConnectStudio } from "./connect-studio-DX7r4iyI.mjs";
2
+ export { runConnectStudio };
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]="ea6224c0-9ba2-5caa-ae9b-88fea686e754")}catch(e){}}();
4
+ //# debugId=ea6224c0-9ba2-5caa-ae9b-88fea686e754
@@ -0,0 +1,313 @@
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]="ed6e9a99-bbeb-54b3-986e-46c7a47cc5bc")}catch(e){}}();
3
+ import { k as projectDriveIdWith } from "./compound-B6RZMA0Y-Cv3XMQ3Y.mjs";
4
+ import { DRIVE_ICON_MAX_BYTES, resolveImageRef } from "@powerhousedao/shared/connect/image-ref";
5
+ import crypto from "node:crypto";
6
+ //#region ../../packages/host-core/dist/index.mjs
7
+ const sha256Hex = (input) => crypto.createHash("sha256").update(input).digest("hex");
8
+ function projectDriveId(projectRoot, slug) {
9
+ return projectDriveIdWith(sha256Hex, projectRoot, slug);
10
+ }
11
+ function resolveDriveDeclaration(projectRoot, decl) {
12
+ const id = decl.projectHash ? projectDriveId(projectRoot, decl.slug) : decl.id ?? decl.slug;
13
+ const slug = decl.projectHash === true ? id : decl.slug;
14
+ if (decl.remote) return {
15
+ kind: "remote",
16
+ id,
17
+ slug,
18
+ name: decl.name ?? decl.slug,
19
+ remoteUrl: decl.remote.url,
20
+ sharingType: decl.sharingType ?? "public",
21
+ availableOffline: decl.availableOffline ?? true
22
+ };
23
+ return {
24
+ kind: "local",
25
+ id,
26
+ slug,
27
+ name: decl.name ?? decl.slug,
28
+ icon: resolveImageRef(projectRoot, decl.icon, {
29
+ maxBytes: DRIVE_ICON_MAX_BYTES,
30
+ warn: (m) => console.warn(m)
31
+ }),
32
+ preferredEditor: decl.preferredEditor,
33
+ sharingType: decl.sharingType ?? "public",
34
+ availableOffline: decl.availableOffline ?? true
35
+ };
36
+ }
37
+ /** Idempotent, slug-keyed: an existing slug is left untouched (never
38
+ * recreated, never mutated — preserveStrategy refinements live here later). */
39
+ async function seedDrives(client, drives) {
40
+ const result = {
41
+ created: [],
42
+ existing: [],
43
+ attached: []
44
+ };
45
+ for (const drive of drives) {
46
+ if (drive.kind === "remote") {
47
+ await client.attachRemoteDrive(drive.remoteUrl);
48
+ result.attached.push(drive.slug);
49
+ continue;
50
+ }
51
+ if (await client.findDriveBySlug(drive.slug) !== void 0) {
52
+ result.existing.push(drive.slug);
53
+ continue;
54
+ }
55
+ await client.createDrive(drive);
56
+ result.created.push(drive.slug);
57
+ }
58
+ return result;
59
+ }
60
+ /** Merge host-declared drives with plugin contributions, slug-keyed — the
61
+ * host file wins on conflicts (it is the most explicit source). */
62
+ function mergeDrivePlan(projectRoot, hostDeclared, contributed) {
63
+ const plan = /* @__PURE__ */ new Map();
64
+ for (const { declaration, source } of contributed) {
65
+ const drive = resolveDriveDeclaration(projectRoot, declaration);
66
+ plan.set(drive.slug, {
67
+ drive,
68
+ source
69
+ });
70
+ }
71
+ for (const declaration of hostDeclared) {
72
+ const drive = resolveDriveDeclaration(projectRoot, declaration);
73
+ plan.set(drive.slug, {
74
+ drive,
75
+ source: "host"
76
+ });
77
+ }
78
+ return [...plan.values()];
79
+ }
80
+ function explainDrivePlan(plan) {
81
+ if (plan.length === 0) return "(no drives declared)";
82
+ return ["drives:", ...plan.map(({ drive, source }) => {
83
+ const kind = drive.kind === "remote" ? `remote ${drive.remoteUrl}` : "local";
84
+ const editor = drive.preferredEditor ? ` editor=${drive.preferredEditor}` : "";
85
+ return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;
86
+ })].join("\n");
87
+ }
88
+ /** The single primary backend for phase-2 projection (multi-backend routing is
89
+ * track R). Prefers placement.primary, else "main"/"local", else the first. */
90
+ function primaryBackend(reactor) {
91
+ const backends = reactor?.backends;
92
+ if (!backends) return void 0;
93
+ const names = Object.keys(backends);
94
+ if (names.length === 0) return void 0;
95
+ return backends[reactor.placement?.primary ?? (names.includes("main") ? "main" : names.includes("local") ? "local" : names[0])];
96
+ }
97
+ const FLAG_ENV = {
98
+ documentDecisions: "REACTOR_DOCUMENT_DECISIONS",
99
+ authEnforcement: "REACTOR_AUTH_ENFORCEMENT",
100
+ authGroups: "REACTOR_AUTH_GROUPS",
101
+ authConditions: "REACTOR_AUTH_CONDITIONS"
102
+ };
103
+ /** The env vars a protocol block maps onto, with their string values. Only
104
+ * keys the block actually sets appear. */
105
+ function protocolEnv(protocol) {
106
+ const env = {};
107
+ if (!protocol) return env;
108
+ for (const [key, varName] of Object.entries(FLAG_ENV)) {
109
+ const value = protocol.featureFlags?.[key];
110
+ if (value !== void 0) env[varName] = value ? "true" : "false";
111
+ }
112
+ if (protocol.createSignaturePolicy !== void 0) env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;
113
+ if (protocol.unsupportedStoredDocuments !== void 0) env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS = protocol.unsupportedStoredDocuments;
114
+ return env;
115
+ }
116
+ /** Project the reactor block onto the switchboard's env + options. */
117
+ function projectReactorToSwitchboard(reactor) {
118
+ const env = protocolEnv(reactor?.protocol);
119
+ const backend = primaryBackend(reactor);
120
+ const options = {};
121
+ if (backend?.storage) {
122
+ const s = backend.storage;
123
+ const dbUrl = s.kind === "postgres" ? s.url : s.dataDir;
124
+ if (dbUrl) env.PH_REACTOR_DATABASE_URL = dbUrl;
125
+ }
126
+ if (backend?.readModel?.url) options.dbPath = backend.readModel.url;
127
+ if (backend?.packages?.dynamic) env.DYNAMIC_MODEL_LOADING = "true";
128
+ if (reactor?.workflows !== void 0) env.PH_WORKFLOWS_ENABLED = reactor.workflows ? "1" : "0";
129
+ return {
130
+ env,
131
+ options
132
+ };
133
+ }
134
+ const LOCAL_BACKEND_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
135
+ /**
136
+ * Which reactor client the backend topology asks for:
137
+ * - local (in-process/worker) AND remote backends -> `router`
138
+ * - remote backend(s) only -> `remote`
139
+ * - a worker backend -> `worker`
140
+ * - anything else local -> `in-process`
141
+ * `undefined` when no backends are declared — the caller then keeps the
142
+ * legacy reactorWorker/multiReactor behaviour untouched.
143
+ */
144
+ function reactorClientMode(reactor) {
145
+ const backends = reactor?.backends;
146
+ if (!backends) return void 0;
147
+ const kinds = Object.values(backends).map((b) => b.kind);
148
+ if (kinds.length === 0) return void 0;
149
+ const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));
150
+ const hasRemote = kinds.some((k) => k === "remote");
151
+ if (hasLocal && hasRemote) return "router";
152
+ if (hasRemote) return "remote";
153
+ return primaryBackend(reactor)?.kind === "worker" ? "worker" : "in-process";
154
+ }
155
+ /** Project the reactor block onto the Connect runtime config: protocol →
156
+ * connect.reactor (same shape), backend topology → instance.reactorWorker
157
+ * (legacy) + instance.reactorClient (the explicit 4-way selector),
158
+ * workflows → app.workflowsEnabled. */
159
+ function projectReactorToConnect(reactor) {
160
+ const connect = {};
161
+ if (reactor?.protocol) connect.reactor = reactor.protocol;
162
+ const backend = primaryBackend(reactor);
163
+ const mode = reactorClientMode(reactor);
164
+ if (backend?.kind !== void 0 || mode !== void 0) connect.instance = {
165
+ ...backend?.kind !== void 0 ? { reactorWorker: backend.kind === "worker" } : {},
166
+ ...mode !== void 0 ? { reactorClient: mode } : {}
167
+ };
168
+ if (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };
169
+ return { connect };
170
+ }
171
+ /**
172
+ * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS
173
+ * the host's protocol block, fail loudly naming the var, the host value, and
174
+ * the env value. An env var that merely matches, or is unset, is fine (phase-2
175
+ * transition keeps an operator's explicit env as an escape hatch unless it
176
+ * disagrees with the protocol — see the WBS precedence note).
177
+ */
178
+ function assertProtocolConsistency(protocol, env, hostFile = "the host file") {
179
+ if (!protocol) return;
180
+ const expected = protocolEnv(protocol);
181
+ for (const [varName, hostValue] of Object.entries(expected)) {
182
+ const envValue = env[varName];
183
+ if (envValue !== void 0 && envValue !== hostValue) throw new Error(`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`);
184
+ }
185
+ }
186
+ function projectStorage(name, storage) {
187
+ switch (storage.kind) {
188
+ case "idb": return { kind: "idb" };
189
+ case "memory": return { kind: "memory" };
190
+ case "path":
191
+ if (!storage.dataDir) throw new Error(`Backend "${name}": storage kind "path" requires dataDir.`);
192
+ return {
193
+ kind: "path",
194
+ dataDir: storage.dataDir
195
+ };
196
+ case "postgres": throw new Error(`Backend "${name}": storage kind "postgres" is server-side only — a provisioned (in-process/worker) reactor cannot use it. Point a "remote" backend at the switchboard that owns that database instead.`);
197
+ }
198
+ }
199
+ /** One backend → one descriptor. The protocol's featureFlags ride every
200
+ * descriptor (they are fleet consensus, not per-backend). A remote backend
201
+ * must carry remote.url — provision() requires it. */
202
+ function backendToDescriptor(name, backend, protocol) {
203
+ const descriptor = {
204
+ kind: backend.kind,
205
+ name
206
+ };
207
+ if (descriptor.kind === "remote") {
208
+ const url = backend.remote?.url;
209
+ if (!url) throw new Error(`Backend "${name}" is kind "remote" but has no remote.url — a remote descriptor attaches to an already-running reactor by URL.`);
210
+ descriptor.remote = { url };
211
+ return descriptor;
212
+ }
213
+ if (backend.storage) descriptor.storage = projectStorage(name, backend.storage);
214
+ if (backend.packages) descriptor.packages = backend.packages;
215
+ if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;
216
+ return descriptor;
217
+ }
218
+ /** All named backends, in placement-primary-first order (the order a
219
+ * createReactorClients step would provision them). */
220
+ function backendsToDescriptors(reactor) {
221
+ const backends = reactor?.backends;
222
+ if (!backends) return [];
223
+ const names = Object.keys(backends);
224
+ const primary = reactor.placement?.primary;
225
+ return (primary && names.includes(primary) ? [primary, ...names.filter((n) => n !== primary)] : names).map((name) => backendToDescriptor(name, backends[name], reactor.protocol));
226
+ }
227
+ const LOCAL_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
228
+ /**
229
+ * Structural multi-reactor (phase 4): true when the block names BOTH a local
230
+ * backend (in-process/worker — the tab's own reactor) and a remote one. This
231
+ * is the shape Connect's routing client serves; a lone remote backend is an
232
+ * attach-only host (assistant/agent shape), not a routed tab.
233
+ */
234
+ function isStructuralMultiReactor(reactor) {
235
+ const backends = reactor?.backends;
236
+ if (!backends) return false;
237
+ const kinds = Object.values(backends).map((b) => b.kind);
238
+ return kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === "remote");
239
+ }
240
+ /** The remote backends' urls, placement order — what the routing client dials. */
241
+ function remoteBackendUrls(reactor) {
242
+ return backendsToDescriptors(reactor).filter((d) => d.kind === "remote").map((d) => d.remote?.url).filter((u) => typeof u === "string");
243
+ }
244
+ /**
245
+ * Instance-fact projection for compound hosts: the drives a compound's
246
+ * reactor member created, projected into the Connect member's runtime-config
247
+ * override. Pure functions, moved from ph-cli's vetra service so the generic
248
+ * compound and the classic path share one implementation.
249
+ */
250
+ function isLocalDrive(drive) {
251
+ return "local" in drive;
252
+ }
253
+ const driveKey = (drive) => isLocalDrive(drive) ? `local:${drive.id}` : drive.url;
254
+ /**
255
+ * Concatenate groups of `connect.drives.defaultDrives` in the order given,
256
+ * de-duplicating by drive identity (URL for remote entries, id for local
257
+ * ones). The first occurrence of a drive wins, so earlier groups keep their
258
+ * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first
259
+ * even when the project's `powerhouse.config.json` lists the same drive.
260
+ */
261
+ function mergeDefaultDrives(...groups) {
262
+ const seen = /* @__PURE__ */ new Set();
263
+ const out = [];
264
+ for (const group of groups) for (const drive of group) {
265
+ const key = driveKey(drive);
266
+ if (seen.has(key)) continue;
267
+ seen.add(key);
268
+ out.push(drive);
269
+ }
270
+ return out;
271
+ }
272
+ /**
273
+ * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,
274
+ * swaps the loopback origin for the public base. Browser clients behind a
275
+ * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs
276
+ * (e.g. a remote drive) are already public and pass through unchanged, as do
277
+ * unparseable ones.
278
+ */
279
+ function rebaseDriveUrl(driveUrl, publicBase) {
280
+ let url;
281
+ try {
282
+ url = new URL(driveUrl);
283
+ } catch {
284
+ return driveUrl;
285
+ }
286
+ if (![
287
+ "localhost",
288
+ "127.0.0.1",
289
+ "[::1]"
290
+ ].includes(url.hostname)) return driveUrl;
291
+ return `${publicBase.replace(/\/+$/, "")}${url.pathname}`;
292
+ }
293
+ /**
294
+ * The compound's drives projection: created drives first (rebased onto the
295
+ * public base when given), then the project's configured drives, de-duplicated
296
+ * — and `preserve-all`, because compound-injected drive lists change per
297
+ * launch context and must never detach drives the user added by hand.
298
+ */
299
+ function projectDrivesIntoConnect(input) {
300
+ return { drives: {
301
+ defaultDrives: mergeDefaultDrives(input.createdDriveUrls.filter((url) => typeof url === "string" && url.length > 0).map((url) => ({
302
+ url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,
303
+ name: null,
304
+ icon: null
305
+ })), input.configuredDefaultDrives ?? []),
306
+ preserveStrategy: "preserve-all"
307
+ } };
308
+ }
309
+ //#endregion
310
+ export { mergeDrivePlan as a, projectReactorToConnect as c, remoteBackendUrls as d, resolveDriveDeclaration as f, mergeDefaultDrives as i, projectReactorToSwitchboard as l, explainDrivePlan as n, primaryBackend as o, seedDrives as p, isStructuralMultiReactor as r, projectDrivesIntoConnect as s, assertProtocolConsistency as t, rebaseDriveUrl as u };
311
+
312
+ //# sourceMappingURL=dist-CCLkwpTS.mjs.map
313
+ //# debugId=ed6e9a99-bbeb-54b3-986e-46c7a47cc5bc