@powerhousedao/clint 6.2.3-dev.58 → 6.2.3-dev.59

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 (28) hide show
  1. package/dist/{build-skills-C1Vr_kQh.mjs → build-skills-C8MlDvTC.mjs} +3 -3
  2. package/dist/{build-skills-C1Vr_kQh.mjs.map → build-skills-C8MlDvTC.mjs.map} +1 -1
  3. package/dist/{events-DkzJFZeW.mjs → events-BnwGFTjv.mjs} +2 -2
  4. package/dist/{events-DkzJFZeW.mjs.map → events-BnwGFTjv.mjs.map} +1 -1
  5. package/dist/index.mjs +6 -4
  6. package/dist/{markdown-C1TFXoB6.mjs → markdown-D-sP2zw_.mjs} +2 -2
  7. package/dist/{markdown-C1TFXoB6.mjs.map → markdown-D-sP2zw_.mjs.map} +1 -1
  8. package/dist/proxy-BFR8GScT.mjs +302 -0
  9. package/dist/proxy-BFR8GScT.mjs.map +1 -0
  10. package/dist/proxy-routes-DP3ztsnS.mjs +215 -0
  11. package/dist/proxy-routes-DP3ztsnS.mjs.map +1 -0
  12. package/dist/runners/clint-runner.d.mts +46 -2
  13. package/dist/runners/clint-runner.d.mts.map +1 -1
  14. package/dist/runners/clint-runner.mjs +81 -3
  15. package/dist/runners/clint-runner.mjs.map +1 -1
  16. package/dist/runners/mastra-runner.d.mts +46 -1
  17. package/dist/runners/mastra-runner.d.mts.map +1 -1
  18. package/dist/runners/mastra-runner.mjs +6 -2
  19. package/dist/runners/mastra-runner.mjs.map +1 -1
  20. package/dist/{services-BvLvP5Qh.mjs → services-9E-r0nWl.mjs} +3 -214
  21. package/dist/services-9E-r0nWl.mjs.map +1 -0
  22. package/dist/{src-DRDGtXYJ.mjs → src-v5f_WnlY.mjs} +8 -302
  23. package/dist/src-v5f_WnlY.mjs.map +1 -0
  24. package/dist/{start-CKRhuB1Y.mjs → start-b7Mn2cxB.mjs} +3 -3
  25. package/dist/{start-CKRhuB1Y.mjs.map → start-b7Mn2cxB.mjs.map} +1 -1
  26. package/package.json +14 -14
  27. package/dist/services-BvLvP5Qh.mjs.map +0 -1
  28. package/dist/src-DRDGtXYJ.mjs.map +0 -1
@@ -0,0 +1,302 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
+ import { c as normalizeLoopbackHost, l as prefixMatches, o as deriveBasePath } from "./proxy-routes-DP3ztsnS.mjs";
3
+ import http from "node:http";
4
+ import httpProxy from "http-proxy";
5
+ //#region src/core/proxy.ts
6
+ /**
7
+ * Embedded reverse proxy — exposes all service endpoints through a single port.
8
+ * Uses http-proxy for HTTP + WebSocket forwarding.
9
+ */
10
+ var proxy_exports = /* @__PURE__ */ __exportAll({ createProxyServer: () => createProxyServer });
11
+ /**
12
+ * Compute the X-Forwarded-Prefix value to send upstream. `base` is the
13
+ * mount base path ('' | '/x') prepended so upstreams emitting absolute
14
+ * paths reconstruct the externally-visible prefix.
15
+ */
16
+ function computeForwardedPrefix(route, base) {
17
+ if (!route.upstream) return void 0;
18
+ const strip = (s) => s.replace(/\/$/, "");
19
+ const prefix = strip(route.prefix);
20
+ const upstreamPath = strip(route.upstream.pathname);
21
+ return base + (upstreamPath && prefix.endsWith(upstreamPath) ? prefix.slice(0, -upstreamPath.length) : prefix) || void 0;
22
+ }
23
+ function envMs(name, fallback) {
24
+ const raw = process.env[name];
25
+ if (!raw) return fallback;
26
+ const n = Number(raw);
27
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
28
+ }
29
+ const DEFAULT_UPSTREAM_TIMEOUT_MS = 3e4;
30
+ const DEFAULT_INCOMING_TIMEOUT_MS = 6e4;
31
+ function splitUrl(url) {
32
+ const qIdx = url.indexOf("?");
33
+ return qIdx === -1 ? [url, ""] : [url.slice(0, qIdx), url.slice(qIdx)];
34
+ }
35
+ const DEFAULT_DRAIN_TIMEOUT_MS = 1e4;
36
+ /**
37
+ * Create and start an embedded reverse proxy server.
38
+ */
39
+ async function createProxyServer(options) {
40
+ const { host, logger } = options;
41
+ let routes = [];
42
+ let stopped = false;
43
+ const basePath = deriveBasePath(options.publicUrl);
44
+ function stripBase(pathname) {
45
+ if (!basePath) return pathname;
46
+ if (!prefixMatches(basePath, pathname)) return void 0;
47
+ return pathname === basePath ? "/" : pathname.slice(basePath.length);
48
+ }
49
+ function prefixRedirect(location) {
50
+ if (!basePath) return location;
51
+ if (!location.startsWith("/") || location.startsWith("//")) return location;
52
+ if (prefixMatches(basePath, location)) return location;
53
+ return basePath + location;
54
+ }
55
+ const upstreamAgent = new http.Agent({
56
+ keepAlive: true,
57
+ autoSelectFamily: false
58
+ });
59
+ const proxy = httpProxy.createProxyServer({
60
+ xfwd: true,
61
+ agent: upstreamAgent,
62
+ proxyTimeout: envMs("PH_PROXY_UPSTREAM_TIMEOUT_MS", DEFAULT_UPSTREAM_TIMEOUT_MS),
63
+ timeout: envMs("PH_PROXY_INCOMING_TIMEOUT_MS", DEFAULT_INCOMING_TIMEOUT_MS)
64
+ });
65
+ proxy.on("proxyRes", (proxyRes, _req, res) => {
66
+ if (!String(proxyRes.headers["content-type"] ?? "").toLowerCase().includes("text/event-stream")) return;
67
+ proxyRes.socket?.setTimeout(0);
68
+ res.socket?.setTimeout(0);
69
+ });
70
+ proxy.on("proxyRes", (proxyRes, _req, res) => {
71
+ const serverRes = res;
72
+ proxyRes.on("close", () => {
73
+ if (!proxyRes.readableEnded && !serverRes.writableEnded) serverRes.destroy();
74
+ });
75
+ });
76
+ proxy.on("proxyRes", (proxyRes) => {
77
+ const status = proxyRes.statusCode ?? 0;
78
+ if (status < 300 || status >= 400) return;
79
+ const location = proxyRes.headers.location;
80
+ if (typeof location !== "string") return;
81
+ proxyRes.headers.location = prefixRedirect(location);
82
+ });
83
+ proxy.on("error", (err, req, res) => {
84
+ logger.warn(`Proxy error for ${req.url}: ${err.message}`);
85
+ const code = err.code;
86
+ const status = code === "ETIMEDOUT" || code === "ECONNRESET" ? 504 : 502;
87
+ const message = status === 504 ? "Gateway Timeout" : "Bad Gateway";
88
+ if (res && "writeHead" in res) {
89
+ const serverRes = res;
90
+ if (!serverRes.headersSent && serverRes.writable) {
91
+ serverRes.writeHead(status, { "Content-Type": "application/json" });
92
+ serverRes.end(JSON.stringify({
93
+ error: message,
94
+ message: err.message
95
+ }));
96
+ } else if (!serverRes.writableEnded) serverRes.end();
97
+ } else if (res && "destroy" in res) res.destroy();
98
+ });
99
+ function matchRoute(pathname) {
100
+ for (const route of routes) if (route.exact && pathname === route.prefix) return route;
101
+ for (const route of routes) {
102
+ if (route.exact) continue;
103
+ if (prefixMatches(route.prefix, pathname)) return route;
104
+ }
105
+ }
106
+ function sortRoutes() {
107
+ routes.sort((a, b) => b.prefix.length - a.prefix.length);
108
+ }
109
+ function rewriteTarget(route, upstream, requestPath) {
110
+ const suffix = requestPath.slice(route.prefix.length);
111
+ const upstreamPath = upstream.pathname;
112
+ if (upstreamPath.endsWith("/") && suffix.startsWith("/")) return upstreamPath + suffix.slice(1);
113
+ if (!upstreamPath.endsWith("/") && suffix.length > 0 && !suffix.startsWith("/")) return upstreamPath + "/" + suffix;
114
+ return upstreamPath + suffix;
115
+ }
116
+ const server = http.createServer((req, res) => {
117
+ const [rawPath, query] = splitUrl(req.url ?? "/");
118
+ const stripped = stripBase(rawPath);
119
+ if (stripped === void 0) {
120
+ res.writeHead(404, { "Content-Type": "application/json" });
121
+ res.end(JSON.stringify({
122
+ error: "Not Found",
123
+ path: rawPath
124
+ }));
125
+ return;
126
+ }
127
+ const pathname = stripped;
128
+ if (pathname === "/_proxy/health") {
129
+ res.writeHead(200, { "Content-Type": "application/json" });
130
+ res.end(JSON.stringify({
131
+ ok: true,
132
+ routes: routes.length
133
+ }));
134
+ return;
135
+ }
136
+ if (pathname === "/_proxy/routes") {
137
+ res.writeHead(200, { "Content-Type": "application/json" });
138
+ res.end(JSON.stringify(routes.map((r) => ({
139
+ prefix: r.prefix,
140
+ upstream: r.upstream?.toString(),
141
+ ws: r.ws,
142
+ source: r.source,
143
+ ...r.redirectTo ? { redirectTo: r.redirectTo } : {},
144
+ ...r.exact ? { exact: true } : {}
145
+ }))));
146
+ return;
147
+ }
148
+ const route = matchRoute(pathname);
149
+ if (!route) {
150
+ res.writeHead(404, { "Content-Type": "application/json" });
151
+ res.end(JSON.stringify({
152
+ error: "Not Found",
153
+ path: pathname
154
+ }));
155
+ return;
156
+ }
157
+ if (route.redirectTo) {
158
+ res.writeHead(302, { Location: prefixRedirect(route.redirectTo) + query });
159
+ res.end();
160
+ return;
161
+ }
162
+ if (!route.upstream) {
163
+ res.writeHead(502, { "Content-Type": "application/json" });
164
+ res.end(JSON.stringify({
165
+ error: "Bad Gateway",
166
+ message: "route has no upstream"
167
+ }));
168
+ return;
169
+ }
170
+ const upstream = route.upstream;
171
+ const targetPath = rewriteTarget(route, upstream, pathname);
172
+ const target = `${upstream.protocol}//${normalizeLoopbackHost(upstream.host)}`;
173
+ const forwardedPrefix = computeForwardedPrefix(route, basePath);
174
+ if (forwardedPrefix) req.headers["x-forwarded-prefix"] = forwardedPrefix;
175
+ else delete req.headers["x-forwarded-prefix"];
176
+ req.url = (targetPath || "/") + query;
177
+ proxy.web(req, res, {
178
+ target,
179
+ changeOrigin: true
180
+ });
181
+ });
182
+ server.on("connection", (socket) => {
183
+ socket.on("error", (err) => {
184
+ logger.debug(`Proxy client socket error: ${err.message}`);
185
+ socket.destroy();
186
+ });
187
+ });
188
+ server.on("clientError", (err, socket) => {
189
+ logger.debug(`Proxy client error: ${err.message}`);
190
+ if (err.code !== "ECONNRESET" && socket.writable) {
191
+ socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
192
+ return;
193
+ }
194
+ socket.destroy();
195
+ });
196
+ const upgradeSockets = /* @__PURE__ */ new Set();
197
+ server.on("upgrade", (req, socket, head) => {
198
+ upgradeSockets.add(socket);
199
+ socket.on("close", () => upgradeSockets.delete(socket));
200
+ socket.on("error", (err) => {
201
+ logger.warn(`Proxy WS client socket error for ${req.url}: ${err.message}`);
202
+ socket.destroy();
203
+ });
204
+ const [rawPath, query] = splitUrl(req.url ?? "/");
205
+ const stripped = stripBase(rawPath);
206
+ if (stripped === void 0) {
207
+ socket.destroy();
208
+ return;
209
+ }
210
+ const pathname = stripped;
211
+ const route = matchRoute(pathname);
212
+ if (!route || !route.ws || !route.upstream) {
213
+ socket.destroy();
214
+ return;
215
+ }
216
+ const upstream = route.upstream;
217
+ const targetPath = rewriteTarget(route, upstream, pathname);
218
+ const target = `${upstream.protocol}//${normalizeLoopbackHost(upstream.host)}`;
219
+ const forwardedPrefix = computeForwardedPrefix(route, basePath);
220
+ if (forwardedPrefix) req.headers["x-forwarded-prefix"] = forwardedPrefix;
221
+ else delete req.headers["x-forwarded-prefix"];
222
+ req.url = (targetPath || "/") + query;
223
+ proxy.ws(req, socket, head, {
224
+ target,
225
+ changeOrigin: true
226
+ });
227
+ });
228
+ const assignedPort = await new Promise((resolve, reject) => {
229
+ server.on("error", reject);
230
+ server.listen(options.port, host, () => {
231
+ const addr = server.address();
232
+ resolve(typeof addr === "object" && addr ? addr.port : options.port);
233
+ });
234
+ });
235
+ const url = options.publicUrl?.trim().replace(/\/+$/, "") || `http://${host === "0.0.0.0" ? "localhost" : host}:${assignedPort}`;
236
+ return {
237
+ get port() {
238
+ return assignedPort;
239
+ },
240
+ get host() {
241
+ return host;
242
+ },
243
+ get url() {
244
+ return url;
245
+ },
246
+ addRoute(route) {
247
+ const sameMatch = (r) => r.prefix === route.prefix && !!r.exact === !!route.exact;
248
+ const ownIdx = routes.findIndex((r) => sameMatch(r) && r.source === route.source);
249
+ if (ownIdx !== -1) {
250
+ const prev = routes[ownIdx];
251
+ routes[ownIdx] = route;
252
+ const prevDest = prev.redirectTo ?? prev.upstream?.toString() ?? "(no upstream)";
253
+ const newDest = route.redirectTo ?? route.upstream?.toString() ?? "(no upstream)";
254
+ if (prevDest !== newDest) logger.warn(`Proxy route replaced: '${route.prefix}' (${route.source}) upstream ${prevDest} → ${newDest}`);
255
+ } else {
256
+ const existing = routes.find(sameMatch);
257
+ if (existing) logger.warn(`Proxy route conflict: '${route.prefix}'${route.exact ? " (exact)" : ""} already registered by ${existing.source}; route from ${route.source} will be shadowed`);
258
+ routes.push(route);
259
+ sortRoutes();
260
+ }
261
+ const dest = route.redirectTo ? `redirect → ${route.redirectTo}` : route.upstream?.toString() ?? "(no upstream)";
262
+ logger.debug(`Proxy route added: ${route.prefix} → ${dest} (${route.source})`);
263
+ },
264
+ removeRoutesBySource(source) {
265
+ const before = routes.length;
266
+ routes = routes.filter((r) => r.source !== source);
267
+ const removed = before - routes.length;
268
+ if (removed > 0) logger.debug(`Proxy: removed ${removed} route(s) for source '${source}'`);
269
+ },
270
+ getRoutes() {
271
+ return routes;
272
+ },
273
+ async stop() {
274
+ if (stopped) return;
275
+ stopped = true;
276
+ const drainTimeout = envMs("PH_PROXY_DRAIN_TIMEOUT_MS", DEFAULT_DRAIN_TIMEOUT_MS);
277
+ const drained = new Promise((resolve) => {
278
+ server.close(() => resolve());
279
+ });
280
+ for (const socket of upgradeSockets) socket.destroy();
281
+ upgradeSockets.clear();
282
+ let timer;
283
+ const deadline = new Promise((resolve) => {
284
+ timer = setTimeout(() => {
285
+ logger.warn(`Proxy drain timed out after ${drainTimeout}ms; force-closing connections`);
286
+ server.closeAllConnections?.();
287
+ resolve();
288
+ }, drainTimeout);
289
+ timer.unref?.();
290
+ });
291
+ await Promise.race([drained, deadline]);
292
+ if (timer) clearTimeout(timer);
293
+ proxy.close();
294
+ upstreamAgent.destroy();
295
+ logger.debug("Proxy server stopped");
296
+ }
297
+ };
298
+ }
299
+ //#endregion
300
+ export { proxy_exports as n, createProxyServer as t };
301
+
302
+ //# sourceMappingURL=proxy-BFR8GScT.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy-BFR8GScT.mjs","names":[],"sources":["../src/core/proxy.ts"],"sourcesContent":["/**\n * Embedded reverse proxy — exposes all service endpoints through a single port.\n * Uses http-proxy for HTTP + WebSocket forwarding.\n */\nimport http from \"node:http\";\nimport httpProxy from \"http-proxy\";\nimport type { Logger } from \"./types.js\";\nimport type { ProxyRoute } from \"./proxy-routes.js\";\nimport {\n deriveBasePath,\n normalizeLoopbackHost,\n prefixMatches,\n} from \"./proxy-routes.js\";\n\nexport interface ProxyServerOptions {\n /** Port to listen on (0 = auto-assign). */\n port: number;\n /** Bind address (default '0.0.0.0'). */\n host: string;\n /**\n * Browser-facing base URL when the proxy sits behind an ingress /\n * reverse proxy (e.g. `https://vetra-agent.<tenant>.vetra.io`). When\n * set, `url` returns this instead of the local listen address, so\n * everything composed from it (the ready event's proxied switchboard /\n * drive / mcp URLs) is reachable from outside the pod.\n *\n * A non-root pathname mounts the whole proxy surface under that base\n * path (e.g. `https://host/myagent` → base path `/myagent`): incoming\n * requests carry the prefix, it is stripped before route matching, and\n * redirect Locations are re-prefixed with it.\n */\n publicUrl?: string;\n logger: Logger;\n}\n\nexport interface ProxyServerInstance {\n readonly port: number;\n readonly host: string;\n readonly url: string;\n addRoute(route: ProxyRoute): void;\n removeRoutesBySource(source: string): void;\n getRoutes(): ReadonlyArray<Readonly<ProxyRoute>>;\n stop(): Promise<void>;\n}\n\n/**\n * Compute the X-Forwarded-Prefix value to send upstream. `base` is the\n * mount base path ('' | '/x') prepended so upstreams emitting absolute\n * paths reconstruct the externally-visible prefix.\n */\nfunction computeForwardedPrefix(\n route: ProxyRoute,\n base: string,\n): string | undefined {\n if (!route.upstream) return undefined;\n const strip = (s: string) => s.replace(/\\/$/, \"\");\n const prefix = strip(route.prefix);\n const upstreamPath = strip(route.upstream.pathname);\n const routePrefix =\n upstreamPath && prefix.endsWith(upstreamPath)\n ? prefix.slice(0, -upstreamPath.length)\n : prefix;\n const result = base + routePrefix;\n return result || undefined;\n}\n\n// Upstream/incoming socket timeouts (ms), overridable via env. The proxy\n// fronts only loopback dev services that should answer in well under a second;\n// 30s upstream is generous headroom for a cold start yet fails fast on a dead\n// or silent upstream instead of hanging the client. Incoming client timeout is\n// looser (60s) to reap stuck/half-open clients without cutting slow uploads.\n// WS routes are not bound by proxyTimeout here (long-lived upgrades).\nfunction envMs(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : fallback;\n}\nconst DEFAULT_UPSTREAM_TIMEOUT_MS = 30_000;\nconst DEFAULT_INCOMING_TIMEOUT_MS = 60_000;\n\n// Split a request URL into pathname and query tail ('' or leading-'?').\n// Route matching and base stripping operate on the pathname only; the tail\n// is re-appended to the path forwarded upstream (and to redirect Locations).\nfunction splitUrl(url: string): [pathname: string, query: string] {\n const qIdx = url.indexOf(\"?\");\n return qIdx === -1 ? [url, \"\"] : [url.slice(0, qIdx), url.slice(qIdx)];\n}\n\n// Max time to wait for in-flight requests to finish on shutdown before\n// force-closing remaining sockets. Overridable via PH_PROXY_DRAIN_TIMEOUT_MS.\nconst DEFAULT_DRAIN_TIMEOUT_MS = 10_000;\n\n/**\n * Create and start an embedded reverse proxy server.\n */\nexport async function createProxyServer(\n options: ProxyServerOptions,\n): Promise<ProxyServerInstance> {\n const { host, logger } = options;\n let routes: ProxyRoute[] = [];\n // Idempotent stop: a duplicate signal during teardown must not re-drain.\n let stopped = false;\n\n // Base path the whole proxy surface is mounted under, derived from a\n // non-root pathname on publicUrl. Empty when serving from the origin\n // root. Normalized to a leading-slash, no-trailing-slash form ('' | '/x').\n const basePath = deriveBasePath(options.publicUrl);\n\n // Strip the base path from an incoming request path before route\n // matching. Requests that don't carry the prefix yield undefined so the\n // caller can 404 rather than mismatch a root route.\n function stripBase(pathname: string): string | undefined {\n if (!basePath) return pathname;\n if (!prefixMatches(basePath, pathname)) return undefined;\n return pathname === basePath ? \"/\" : pathname.slice(basePath.length);\n }\n\n // Re-prefix a root-relative redirect Location with the base path so the\n // browser stays under the mount. Absolute URLs and other-prefixed paths\n // pass through untouched.\n function prefixRedirect(location: string): string {\n if (!basePath) return location;\n if (!location.startsWith(\"/\") || location.startsWith(\"//\")) return location;\n if (prefixMatches(basePath, location)) return location;\n return basePath + location;\n }\n\n // Shared keep-alive agent for all upstreams (every target is loopback HTTP).\n // autoSelectFamily:false pins Node to the first resolved address; paired with\n // localhost→127.0.0.1 normalization on the target host so the pinned family\n // is deterministically IPv4 (avoids the Happy-Eyeballs dual-stack stall).\n const upstreamAgent = new http.Agent({\n keepAlive: true,\n autoSelectFamily: false,\n });\n\n const proxy = httpProxy.createProxyServer({\n xfwd: true,\n agent: upstreamAgent,\n proxyTimeout: envMs(\n \"PH_PROXY_UPSTREAM_TIMEOUT_MS\",\n DEFAULT_UPSTREAM_TIMEOUT_MS,\n ),\n timeout: envMs(\"PH_PROXY_INCOMING_TIMEOUT_MS\", DEFAULT_INCOMING_TIMEOUT_MS),\n });\n\n // Event streams legitimately go quiet between events; the fail-fast idle\n // timeouts (proxyTimeout/timeout) must not reap them. Clear both the\n // upstream and client socket idle timers for text/event-stream responses.\n proxy.on(\"proxyRes\", (proxyRes, _req, res) => {\n const contentType = String(\n proxyRes.headers[\"content-type\"] ?? \"\",\n ).toLowerCase();\n if (!contentType.includes(\"text/event-stream\")) return;\n proxyRes.socket?.setTimeout(0);\n (res as http.ServerResponse).socket?.setTimeout(0);\n });\n\n // proxyTimeout fires mid-response as proxyReq.abort(); Node suppresses the\n // request 'error' after an explicit abort, so http-proxy's error handler\n // never runs and the client would hang on a truncated body. If the upstream\n // body closes without ending, tear down the client response (destroy, not\n // end — a clean end would mis-signal a complete chunked body).\n proxy.on(\"proxyRes\", (proxyRes, _req, res) => {\n const serverRes = res as http.ServerResponse;\n proxyRes.on(\"close\", () => {\n if (!proxyRes.readableEnded && !serverRes.writableEnded) {\n serverRes.destroy();\n }\n });\n });\n\n // Upstream 3xx responses pass through verbatim; under a base-path mount a\n // root-relative Location would escape the mount. Re-prefix it the same way\n // built-in redirect routes are (prefixRedirect: no-op at root mount, for\n // absolute/protocol-relative URLs, and for already-prefixed paths).\n // http-proxy emits 'proxyRes' before writing headers in default mode, so\n // mutating proxyRes.headers takes effect.\n proxy.on(\"proxyRes\", (proxyRes) => {\n const status = proxyRes.statusCode ?? 0;\n if (status < 300 || status >= 400) return;\n const location = proxyRes.headers.location;\n if (typeof location !== \"string\") return;\n proxyRes.headers.location = prefixRedirect(location);\n });\n\n proxy.on(\"error\", (err, req, res) => {\n logger.warn(`Proxy error for ${req.url}: ${err.message}`);\n // 504 on an upstream that accepted/connected but stalled past proxyTimeout\n // (http-proxy surfaces this as ECONNRESET/ETIMEDOUT); 502 on a refused or\n // unreachable connect. Default to 502 for anything else.\n const code = (err as NodeJS.ErrnoException).code;\n const status = code === \"ETIMEDOUT\" || code === \"ECONNRESET\" ? 504 : 502;\n const message = status === 504 ? \"Gateway Timeout\" : \"Bad Gateway\";\n // Guard against double-send: the response may be a WS socket, or headers\n // may already be in flight from a partially-streamed response.\n if (res && \"writeHead\" in res) {\n const serverRes = res as http.ServerResponse;\n if (!serverRes.headersSent && serverRes.writable) {\n serverRes.writeHead(status, { \"Content-Type\": \"application/json\" });\n serverRes.end(JSON.stringify({ error: message, message: err.message }));\n } else if (!serverRes.writableEnded) {\n serverRes.end();\n }\n } else if (res && \"destroy\" in res) {\n (res as import(\"node:net\").Socket).destroy();\n }\n });\n\n function matchRoute(pathname: string): ProxyRoute | undefined {\n // Exact routes win first, so a `'/'` exact redirect fires only on the bare\n // root while `/assets/*`, `/d/<id>`, etc. fall through to prefix routes\n // (including a `'/'` catch-all).\n for (const route of routes) {\n if (route.exact && pathname === route.prefix) {\n return route;\n }\n }\n // Routes are kept sorted longest-prefix-first.\n for (const route of routes) {\n if (route.exact) continue;\n if (prefixMatches(route.prefix, pathname)) {\n return route;\n }\n }\n return undefined;\n }\n\n function sortRoutes(): void {\n routes.sort((a, b) => b.prefix.length - a.prefix.length);\n }\n\n function rewriteTarget(\n route: ProxyRoute,\n upstream: URL,\n requestPath: string,\n ): string {\n const suffix = requestPath.slice(route.prefix.length);\n const upstreamPath = upstream.pathname;\n // Avoid double slashes when both upstream ends with / and suffix starts with /\n if (upstreamPath.endsWith(\"/\") && suffix.startsWith(\"/\")) {\n return upstreamPath + suffix.slice(1);\n }\n // Ensure a separator when upstream doesn't end with / and suffix doesn't start with /\n if (\n !upstreamPath.endsWith(\"/\") &&\n suffix.length > 0 &&\n !suffix.startsWith(\"/\")\n ) {\n return upstreamPath + \"/\" + suffix;\n }\n return upstreamPath + suffix;\n }\n\n const server = http.createServer((req, res) => {\n const [rawPath, query] = splitUrl(req.url ?? \"/\");\n const stripped = stripBase(rawPath);\n if (stripped === undefined) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\", path: rawPath }));\n return;\n }\n const pathname = stripped;\n\n // Built-in health endpoint\n if (pathname === \"/_proxy/health\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true, routes: routes.length }));\n return;\n }\n\n // Built-in debug endpoint\n if (pathname === \"/_proxy/routes\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify(\n routes.map((r) => ({\n prefix: r.prefix,\n upstream: r.upstream?.toString(),\n ws: r.ws,\n source: r.source,\n ...(r.redirectTo ? { redirectTo: r.redirectTo } : {}),\n ...(r.exact ? { exact: true } : {}),\n })),\n ),\n );\n return;\n }\n\n const route = matchRoute(pathname);\n if (!route) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\", path: pathname }));\n return;\n }\n\n if (route.redirectTo) {\n res.writeHead(302, {\n Location: prefixRedirect(route.redirectTo) + query,\n });\n res.end();\n return;\n }\n\n if (!route.upstream) {\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: \"Bad Gateway\",\n message: \"route has no upstream\",\n }),\n );\n return;\n }\n\n const upstream = route.upstream;\n const targetPath = rewriteTarget(route, upstream, pathname);\n const target = `${upstream.protocol}//${normalizeLoopbackHost(upstream.host)}`;\n\n const forwardedPrefix = computeForwardedPrefix(route, basePath);\n if (forwardedPrefix) {\n req.headers[\"x-forwarded-prefix\"] = forwardedPrefix;\n } else {\n delete req.headers[\"x-forwarded-prefix\"];\n }\n req.url = (targetPath || \"/\") + query;\n proxy.web(req, res, { target, changeOrigin: true });\n });\n\n // Errors on accepted client sockets (resets, aborts) must surface on the\n // socket, never as an uncaught exception: destroy and move on.\n server.on(\"connection\", (socket) => {\n socket.on(\"error\", (err) => {\n logger.debug(`Proxy client socket error: ${err.message}`);\n socket.destroy();\n });\n });\n\n // Malformed or aborted requests before a response object exists: answer 400\n // when the socket is still usable, otherwise just drop it.\n server.on(\"clientError\", (err, socket) => {\n logger.debug(`Proxy client error: ${err.message}`);\n if (\n (err as NodeJS.ErrnoException).code !== \"ECONNRESET\" &&\n socket.writable\n ) {\n socket.end(\"HTTP/1.1 400 Bad Request\\r\\n\\r\\n\");\n return;\n }\n socket.destroy();\n });\n\n // Tracked upgrade/WS client sockets, closed on drain so a long-lived socket\n // can't block shutdown indefinitely.\n const upgradeSockets = new Set<import(\"node:stream\").Duplex>();\n\n // WebSocket upgrade handling\n server.on(\"upgrade\", (req, socket, head) => {\n upgradeSockets.add(socket);\n socket.on(\"close\", () => upgradeSockets.delete(socket));\n // http-proxy only attaches its client-socket error handler after the\n // upstream upgrade succeeds; a client reset during the handshake would\n // otherwise surface as an unhandled 'error' and crash the process. Attach\n // ours first, before any validation or proxy.ws().\n socket.on(\"error\", (err) => {\n logger.warn(\n `Proxy WS client socket error for ${req.url}: ${err.message}`,\n );\n socket.destroy();\n });\n\n const [rawPath, query] = splitUrl(req.url ?? \"/\");\n const stripped = stripBase(rawPath);\n if (stripped === undefined) {\n socket.destroy();\n return;\n }\n const pathname = stripped;\n const route = matchRoute(pathname);\n\n if (!route || !route.ws || !route.upstream) {\n socket.destroy();\n return;\n }\n\n const upstream = route.upstream;\n const targetPath = rewriteTarget(route, upstream, pathname);\n const target = `${upstream.protocol}//${normalizeLoopbackHost(upstream.host)}`;\n\n const forwardedPrefix = computeForwardedPrefix(route, basePath);\n if (forwardedPrefix) {\n req.headers[\"x-forwarded-prefix\"] = forwardedPrefix;\n } else {\n delete req.headers[\"x-forwarded-prefix\"];\n }\n req.url = (targetPath || \"/\") + query;\n proxy.ws(req, socket, head, { target, changeOrigin: true });\n });\n\n // Start listening\n const assignedPort = await new Promise<number>((resolve, reject) => {\n server.on(\"error\", reject);\n server.listen(options.port, host, () => {\n const addr = server.address();\n const p = typeof addr === \"object\" && addr ? addr.port : options.port;\n resolve(p);\n });\n });\n\n // `url` advertises the browser-facing base, including any base path on\n // publicUrl. `xfwd` relies on the fronting ingress to set\n // X-Forwarded-Proto/Host; the base path is folded into X-Forwarded-Prefix\n // here so upstreams emitting absolute paths reconstruct the full prefix.\n // `|| fallback` (not `??`) so an empty/whitespace-only publicUrl is treated\n // as unset rather than producing an empty `url`. The CLI also validates this\n // as a URL, but createProxyServer is callable directly so we guard here too.\n const url =\n options.publicUrl?.trim().replace(/\\/+$/, \"\") ||\n `http://${host === \"0.0.0.0\" ? \"localhost\" : host}:${assignedPort}`;\n\n const instance: ProxyServerInstance = {\n get port() {\n return assignedPort;\n },\n get host() {\n return host;\n },\n get url() {\n return url;\n },\n\n addRoute(route: ProxyRoute): void {\n // Same prefix only conflicts when both match the same way: an exact\n // route and a prefix route on the same prefix (e.g. a `'/'` redirect vs\n // Connect's `'/'` catch-all) coexist — matchRoute dispatches exact first.\n // Re-adding from the same source replaces the existing route, so\n // repeated registration (boot-adoption + service:ready) is idempotent.\n const sameMatch = (r: ProxyRoute) =>\n r.prefix === route.prefix && !!r.exact === !!route.exact;\n const ownIdx = routes.findIndex(\n (r) => sameMatch(r) && r.source === route.source,\n );\n if (ownIdx !== -1) {\n // Replace in place: equal prefix length means the sorted position is\n // unchanged, and re-sorting must not let a previously-shadowed\n // same-prefix route from another source jump ahead.\n const prev = routes[ownIdx];\n routes[ownIdx] = route;\n const prevDest =\n prev.redirectTo ?? prev.upstream?.toString() ?? \"(no upstream)\";\n const newDest =\n route.redirectTo ?? route.upstream?.toString() ?? \"(no upstream)\";\n if (prevDest !== newDest) {\n logger.warn(\n `Proxy route replaced: '${route.prefix}' (${route.source}) upstream ${prevDest} → ${newDest}`,\n );\n }\n } else {\n const existing = routes.find(sameMatch);\n if (existing) {\n logger.warn(\n `Proxy route conflict: '${route.prefix}'${route.exact ? \" (exact)\" : \"\"} already registered by ${existing.source}; ` +\n `route from ${route.source} will be shadowed`,\n );\n }\n routes.push(route);\n sortRoutes();\n }\n const dest = route.redirectTo\n ? `redirect → ${route.redirectTo}`\n : (route.upstream?.toString() ?? \"(no upstream)\");\n logger.debug(\n `Proxy route added: ${route.prefix} → ${dest} (${route.source})`,\n );\n },\n\n removeRoutesBySource(source: string): void {\n const before = routes.length;\n routes = routes.filter((r) => r.source !== source);\n const removed = before - routes.length;\n if (removed > 0) {\n logger.debug(\n `Proxy: removed ${removed} route(s) for source '${source}'`,\n );\n }\n },\n\n getRoutes(): ReadonlyArray<Readonly<ProxyRoute>> {\n return routes;\n },\n\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n\n const drainTimeout = envMs(\n \"PH_PROXY_DRAIN_TIMEOUT_MS\",\n DEFAULT_DRAIN_TIMEOUT_MS,\n );\n\n // Stop accepting new connections; server.close resolves once all\n // in-flight HTTP requests finish.\n const drained = new Promise<void>((resolve) => {\n server.close(() => resolve());\n });\n\n // Close tracked WS/upgrade sockets so they don't hold the drain open.\n for (const socket of upgradeSockets) socket.destroy();\n upgradeSockets.clear();\n\n // Bound the drain: after the timeout, force-close any sockets still\n // serving in-flight HTTP requests and resolve.\n let timer: NodeJS.Timeout | undefined;\n const deadline = new Promise<void>((resolve) => {\n timer = setTimeout(() => {\n logger.warn(\n `Proxy drain timed out after ${drainTimeout}ms; force-closing connections`,\n );\n server.closeAllConnections?.();\n resolve();\n }, drainTimeout);\n timer.unref?.();\n });\n\n await Promise.race([drained, deadline]);\n if (timer) clearTimeout(timer);\n proxy.close();\n upstreamAgent.destroy();\n logger.debug(\"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eACnB,MAAM,UAAU,SAAS,KAAK;GACnC,OAAO,MACL,sBAAsB,MAAM,OAAO,KAAK,KAAK,IAAI,MAAM,OAAO,EAChE;EACF;EAEA,qBAAqB,QAAsB;GACzC,MAAM,SAAS,OAAO;GACtB,SAAS,OAAO,QAAQ,MAAM,EAAE,WAAW,MAAM;GACjD,MAAM,UAAU,SAAS,OAAO;GAChC,IAAI,UAAU,GACZ,OAAO,MACL,kBAAkB,QAAQ,wBAAwB,OAAO,EAC3D;EAEJ;EAEA,YAAiD;GAC/C,OAAO;EACT;EAEA,MAAM,OAAsB;GAC1B,IAAI,SAAS;GACb,UAAU;GAEV,MAAM,eAAe,MACnB,6BACA,wBACF;GAIA,MAAM,UAAU,IAAI,SAAe,YAAY;IAC7C,OAAO,YAAY,QAAQ,CAAC;GAC9B,CAAC;GAGD,KAAK,MAAM,UAAU,gBAAgB,OAAO,QAAQ;GACpD,eAAe,MAAM;GAIrB,IAAI;GACJ,MAAM,WAAW,IAAI,SAAe,YAAY;IAC9C,QAAQ,iBAAiB;KACvB,OAAO,KACL,+BAA+B,aAAa,8BAC9C;KACA,OAAO,sBAAsB;KAC7B,QAAQ;IACV,GAAG,YAAY;IACf,MAAM,QAAQ;GAChB,CAAC;GAED,MAAM,QAAQ,KAAK,CAAC,SAAS,QAAQ,CAAC;GACtC,IAAI,OAAO,aAAa,KAAK;GAC7B,MAAM,MAAM;GACZ,cAAc,QAAQ;GACtB,OAAO,MAAM,sBAAsB;EACrC;CAGY;AAChB"}
@@ -0,0 +1,215 @@
1
+ //#region src/core/proxy-routes.ts
2
+ /**
3
+ * Match a route prefix against a request pathname on path-segment boundaries:
4
+ * the prefix matches only when the pathname equals it or continues with a `/`.
5
+ * A bare `startsWith` would let `/foobar` match a `/foo` route. The root prefix
6
+ * `/` matches everything. A prefix already carrying a trailing `/`
7
+ * (e.g. `/switchboard/attachments/`) matches `<prefix>` and `<prefix><rest>`
8
+ * without doubling the separator.
9
+ */
10
+ function prefixMatches(prefix, pathname) {
11
+ if (prefix === "/") return true;
12
+ if (prefix.endsWith("/")) return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix);
13
+ return pathname === prefix || pathname.startsWith(prefix + "/");
14
+ }
15
+ /**
16
+ * Derive the mount base path from publicUrl's pathname. Returns '' for an
17
+ * absent/invalid/root pathname, otherwise a leading-slash, no-trailing-slash
18
+ * form ('/myagent'). Mirrors the trailing-slash stripping the proxy's
19
+ * advertised `url` applies, so the base path and `url` stay aligned.
20
+ */
21
+ function deriveBasePath(publicUrl) {
22
+ const trimmed = publicUrl?.trim();
23
+ if (!trimmed) return "";
24
+ try {
25
+ const url = new URL(trimmed);
26
+ if (!/^https?:$/.test(url.protocol)) return "";
27
+ return url.pathname.replace(/\/+$/, "");
28
+ } catch {
29
+ return "";
30
+ }
31
+ }
32
+ /**
33
+ * Resolve the proxy info handed to service command/env builders from the
34
+ * configured publicUrl. Single owner of the publicUrl normalization:
35
+ * `publicUrl` must parse as an http(s) URL and is stripped of trailing
36
+ * slashes, undefined when unset/invalid; `basePath` is the URL's pathname
37
+ * normalized like `deriveBasePath`.
38
+ */
39
+ function resolveServiceProxyContext(publicUrl) {
40
+ const trimmed = publicUrl?.trim();
41
+ if (trimmed) try {
42
+ const url = new URL(trimmed);
43
+ if (/^https?:$/.test(url.protocol)) return {
44
+ publicUrl: trimmed.replace(/\/+$/, ""),
45
+ basePath: url.pathname.replace(/\/+$/, "")
46
+ };
47
+ } catch {}
48
+ return {
49
+ publicUrl: void 0,
50
+ basePath: ""
51
+ };
52
+ }
53
+ /**
54
+ * Rewrite a loopback `localhost` host to `127.0.0.1` so a pinned-family agent
55
+ * (autoSelectFamily:false) connects deterministically over IPv4 instead of
56
+ * racing `::1`/`127.0.0.1` (Happy-Eyeballs). Preserves any `:port`. Non-loopback
57
+ * hosts are returned unchanged.
58
+ */
59
+ function normalizeLoopbackHost(host) {
60
+ const [hostname, ...rest] = host.split(":");
61
+ if (hostname.toLowerCase() === "localhost") return ["127.0.0.1", ...rest].join(":");
62
+ return host;
63
+ }
64
+ /**
65
+ * Endpoint types that imply WebSocket transport. Websites need upgrades
66
+ * forwarded for dev-server HMR sockets (Vite connects on the page's own
67
+ * origin/path).
68
+ */
69
+ function isWsEndpointType(type) {
70
+ return type === "api-mcp" || type === "website";
71
+ }
72
+ /**
73
+ * Relative-prefix route specs for a Powerhouse Switchboard, usable as
74
+ * `ServiceDefinition.proxyRoutes` specs (mounted under `/{serviceId}/`).
75
+ * The MCP route is included only when `mcpUrl` is provided.
76
+ */
77
+ function buildSwitchboardRouteSpecs(switchboardUrl, mcpUrl, basePrefix = "switchboard") {
78
+ const sbBase = new URL(switchboardUrl);
79
+ const specs = [
80
+ {
81
+ prefix: `${basePrefix}/graphql`,
82
+ upstream: new URL("/graphql", sbBase),
83
+ ws: false
84
+ },
85
+ {
86
+ prefix: `${basePrefix}/d/`,
87
+ upstream: new URL("/d/", sbBase),
88
+ ws: false
89
+ },
90
+ {
91
+ prefix: `${basePrefix}/attachments/`,
92
+ upstream: new URL("/attachments/", sbBase),
93
+ ws: false
94
+ }
95
+ ];
96
+ if (mcpUrl) specs.push({
97
+ prefix: `${basePrefix}/mcp`,
98
+ upstream: new URL("/mcp", new URL(mcpUrl)),
99
+ ws: true
100
+ });
101
+ return specs;
102
+ }
103
+ /**
104
+ * Absolute proxy routes for the embedded Switchboard, mounted under
105
+ * `/switchboard` with source `'switchboard'`. The MCP route is included
106
+ * only when `mcpUrl` is provided.
107
+ */
108
+ function buildSwitchboardRoutes(switchboardUrl, mcpUrl) {
109
+ return buildSwitchboardRouteSpecs(switchboardUrl, mcpUrl).map((spec) => ({
110
+ prefix: `/${spec.prefix}`,
111
+ upstream: spec.upstream,
112
+ ws: spec.ws ?? false,
113
+ source: "switchboard"
114
+ }));
115
+ }
116
+ /**
117
+ * Browser-facing switchboard URLs through the proxy. Kept next to
118
+ * `buildSwitchboardRoutes` so the `/switchboard` prefix scheme has a single
119
+ * owner — a prefix change here updates both the routes and the URLs handed
120
+ * out to consumers.
121
+ */
122
+ function buildSwitchboardProxyUrls(proxyUrl, switchboard) {
123
+ return {
124
+ switchboardUrl: `${proxyUrl}/switchboard/graphql`,
125
+ driveUrl: `${proxyUrl}/switchboard${new URL(switchboard.driveUrl).pathname}`,
126
+ mcpUrl: `${proxyUrl}/switchboard/mcp`
127
+ };
128
+ }
129
+ /**
130
+ * Resolve which website capture implicitly owns the proxy root when none
131
+ * sets `proxyRoot` explicitly. Exactly one website capture across all
132
+ * definitions → that capture (preserves single-SPA behavior for CLIs that
133
+ * predate the flag). Zero, several, or any explicit root → undefined.
134
+ */
135
+ function resolveImplicitProxyRoot(defs) {
136
+ let single;
137
+ let count = 0;
138
+ for (const def of defs) for (const [captureName, captureDef] of getCapturesForDef(def)) {
139
+ if (typeof captureDef === "number") continue;
140
+ if (captureDef.type !== "website") continue;
141
+ if (captureDef.proxyRoot) return void 0;
142
+ count++;
143
+ single ??= {
144
+ serviceId: def.id,
145
+ captureName
146
+ };
147
+ }
148
+ return count === 1 ? single : void 0;
149
+ }
150
+ /**
151
+ * Proxy mount prefix for a service route: `/{serviceId}/{name}`. Single
152
+ * owner of the convention used for capture routes and for mounting
153
+ * `ServiceDefinition.proxyRoutes` specs.
154
+ */
155
+ function captureRoutePrefix(serviceId, captureName) {
156
+ return `/${serviceId}/${captureName}`;
157
+ }
158
+ /**
159
+ * Build proxy routes from a service definition's readiness captures and its
160
+ * `proxyRoutes` hook. Only captures with announceable endpoint types produce
161
+ * routes; hook specs are mounted under `/{serviceId}/`.
162
+ */
163
+ function buildServiceRoutes(def, instance, implicitRoot, log) {
164
+ const routes = [];
165
+ const captures = getCapturesForDef(def);
166
+ for (const [captureName, captureDef] of captures) {
167
+ const captureType = typeof captureDef === "number" ? void 0 : captureDef.type;
168
+ if (!captureType) continue;
169
+ const url = instance.endpoints?.[captureName];
170
+ if (!url) continue;
171
+ try {
172
+ const upstream = new URL(url);
173
+ const prefix = captureType === "website" && (typeof captureDef !== "number" && captureDef.proxyRoot === true || implicitRoot?.serviceId === def.id && implicitRoot.captureName === captureName) ? "/" : captureRoutePrefix(def.id, captureName);
174
+ routes.push({
175
+ prefix,
176
+ upstream,
177
+ ws: isWsEndpointType(captureType),
178
+ source: `service:${def.id}`
179
+ });
180
+ } catch {}
181
+ }
182
+ if (def.proxyRoutes) {
183
+ let specs = [];
184
+ try {
185
+ specs = def.proxyRoutes(instance) ?? [];
186
+ } catch (err) {
187
+ log?.warn(`proxyRoutes hook failed for service '${def.id}': ${err instanceof Error ? err.message : String(err)}`);
188
+ }
189
+ for (const spec of specs) try {
190
+ const upstream = spec.upstream instanceof URL ? spec.upstream : new URL(spec.upstream);
191
+ routes.push({
192
+ prefix: captureRoutePrefix(def.id, spec.prefix.replace(/^\/+/, "")),
193
+ upstream,
194
+ ws: spec.ws ?? false,
195
+ source: `service:${def.id}`
196
+ });
197
+ } catch (err) {
198
+ log?.warn(`Invalid proxyRoutes spec '${spec.prefix}' for service '${def.id}': ${err instanceof Error ? err.message : String(err)}`);
199
+ }
200
+ }
201
+ return routes;
202
+ }
203
+ function getCapturesForDef(def) {
204
+ const result = [];
205
+ if (!def.readiness) return result;
206
+ if (def.readiness.captures) for (const [name, capDef] of Object.entries(def.readiness.captures)) result.push([name, capDef]);
207
+ if (def.readiness.patterns) {
208
+ for (const pattern of def.readiness.patterns) if (pattern.captures) for (const [name, capDef] of Object.entries(pattern.captures)) result.push([name, capDef]);
209
+ }
210
+ return result;
211
+ }
212
+ //#endregion
213
+ export { captureRoutePrefix as a, normalizeLoopbackHost as c, resolveServiceProxyContext as d, buildSwitchboardRoutes as i, prefixMatches as l, buildSwitchboardProxyUrls as n, deriveBasePath as o, buildSwitchboardRouteSpecs as r, isWsEndpointType as s, buildServiceRoutes as t, resolveImplicitProxyRoot as u };
214
+
215
+ //# sourceMappingURL=proxy-routes-DP3ztsnS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy-routes-DP3ztsnS.mjs","names":[],"sources":["../src/core/proxy-routes.ts"],"sourcesContent":["/**\n * Pure functions for building proxy routes from service definitions\n * and Switchboard configuration. No side effects — easily unit-testable.\n */\nimport type {\n ServiceDefinition,\n ServiceInstanceStatus,\n ServiceProxyRouteSpec,\n CaptureDefinition,\n EndpointType,\n} from \"./types.js\";\n\nexport interface ProxyRoute {\n /** URL path prefix matched against incoming requests (e.g. '/switchboard/graphql'). */\n prefix: string;\n /**\n * Upstream target URL (e.g. new URL('http://localhost:4001/graphql')).\n * Optional only for pure redirect routes (`redirectTo` set).\n */\n upstream?: URL;\n /** Whether WebSocket upgrade should be forwarded on this route. */\n ws: boolean;\n /** Origin label for route management (e.g. 'switchboard', 'service:my-svc'). */\n source: string;\n /**\n * When set, matching requests get a 302 to this location instead of being\n * proxied. No upstream connection is made.\n */\n redirectTo?: string;\n /**\n * Match the prefix exactly rather than as a `startsWith` prefix. Exact\n * routes are matched before prefix routes so a `'/'` redirect can coexist\n * with a `'/'` catch-all without shadowing longer prefixes.\n */\n exact?: boolean;\n}\n\n/**\n * Match a route prefix against a request pathname on path-segment boundaries:\n * the prefix matches only when the pathname equals it or continues with a `/`.\n * A bare `startsWith` would let `/foobar` match a `/foo` route. The root prefix\n * `/` matches everything. A prefix already carrying a trailing `/`\n * (e.g. `/switchboard/attachments/`) matches `<prefix>` and `<prefix><rest>`\n * without doubling the separator.\n */\nexport function prefixMatches(prefix: string, pathname: string): boolean {\n if (prefix === \"/\") return true;\n if (prefix.endsWith(\"/\")) {\n return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix);\n }\n return pathname === prefix || pathname.startsWith(prefix + \"/\");\n}\n\n/**\n * Derive the mount base path from publicUrl's pathname. Returns '' for an\n * absent/invalid/root pathname, otherwise a leading-slash, no-trailing-slash\n * form ('/myagent'). Mirrors the trailing-slash stripping the proxy's\n * advertised `url` applies, so the base path and `url` stay aligned.\n */\nexport function deriveBasePath(publicUrl: string | undefined): string {\n const trimmed = publicUrl?.trim();\n if (!trimmed) return \"\";\n try {\n const url = new URL(trimmed);\n // `new URL('localhost:8090')` parses with protocol 'localhost:' —\n // anything but http(s) is treated as invalid.\n if (!/^https?:$/.test(url.protocol)) return \"\";\n return url.pathname.replace(/\\/+$/, \"\");\n } catch {\n return \"\";\n }\n}\n\n/**\n * Resolve the proxy info handed to service command/env builders from the\n * configured publicUrl. Single owner of the publicUrl normalization:\n * `publicUrl` must parse as an http(s) URL and is stripped of trailing\n * slashes, undefined when unset/invalid; `basePath` is the URL's pathname\n * normalized like `deriveBasePath`.\n */\nexport function resolveServiceProxyContext(publicUrl: string | undefined): {\n publicUrl?: string;\n basePath: string;\n} {\n const trimmed = publicUrl?.trim();\n if (trimmed) {\n try {\n const url = new URL(trimmed);\n if (/^https?:$/.test(url.protocol)) {\n return {\n publicUrl: trimmed.replace(/\\/+$/, \"\"),\n basePath: url.pathname.replace(/\\/+$/, \"\"),\n };\n }\n } catch {\n // invalid publicUrl — treat as unset\n }\n }\n return { publicUrl: undefined, basePath: \"\" };\n}\n\n/**\n * Rewrite a loopback `localhost` host to `127.0.0.1` so a pinned-family agent\n * (autoSelectFamily:false) connects deterministically over IPv4 instead of\n * racing `::1`/`127.0.0.1` (Happy-Eyeballs). Preserves any `:port`. Non-loopback\n * hosts are returned unchanged.\n */\nexport function normalizeLoopbackHost(host: string): string {\n const [hostname, ...rest] = host.split(\":\");\n if (hostname.toLowerCase() === \"localhost\") {\n return [\"127.0.0.1\", ...rest].join(\":\");\n }\n return host;\n}\n\n/**\n * Endpoint types that imply WebSocket transport. Websites need upgrades\n * forwarded for dev-server HMR sockets (Vite connects on the page's own\n * origin/path).\n */\nexport function isWsEndpointType(type: EndpointType): boolean {\n return type === \"api-mcp\" || type === \"website\";\n}\n\n/**\n * Relative-prefix route specs for a Powerhouse Switchboard, usable as\n * `ServiceDefinition.proxyRoutes` specs (mounted under `/{serviceId}/`).\n * The MCP route is included only when `mcpUrl` is provided.\n */\nexport function buildSwitchboardRouteSpecs(\n switchboardUrl: string,\n mcpUrl?: string,\n basePrefix = \"switchboard\",\n): Array<ServiceProxyRouteSpec & { upstream: URL }> {\n const sbBase = new URL(switchboardUrl);\n\n const specs: Array<ServiceProxyRouteSpec & { upstream: URL }> = [\n {\n prefix: `${basePrefix}/graphql`,\n upstream: new URL(\"/graphql\", sbBase),\n ws: false,\n },\n {\n prefix: `${basePrefix}/d/`,\n upstream: new URL(\"/d/\", sbBase),\n ws: false,\n },\n {\n prefix: `${basePrefix}/attachments/`,\n upstream: new URL(\"/attachments/\", sbBase),\n ws: false,\n },\n ];\n if (mcpUrl) {\n specs.push({\n prefix: `${basePrefix}/mcp`,\n upstream: new URL(\"/mcp\", new URL(mcpUrl)),\n ws: true,\n });\n }\n return specs;\n}\n\n/**\n * Absolute proxy routes for the embedded Switchboard, mounted under\n * `/switchboard` with source `'switchboard'`. The MCP route is included\n * only when `mcpUrl` is provided.\n */\nexport function buildSwitchboardRoutes(\n switchboardUrl: string,\n mcpUrl?: string,\n): Array<ProxyRoute & { upstream: URL }> {\n return buildSwitchboardRouteSpecs(switchboardUrl, mcpUrl).map((spec) => ({\n prefix: `/${spec.prefix}`,\n upstream: spec.upstream,\n ws: spec.ws ?? false,\n source: \"switchboard\",\n }));\n}\n\n/**\n * Browser-facing switchboard URLs through the proxy. Kept next to\n * `buildSwitchboardRoutes` so the `/switchboard` prefix scheme has a single\n * owner — a prefix change here updates both the routes and the URLs handed\n * out to consumers.\n */\nexport function buildSwitchboardProxyUrls(\n proxyUrl: string,\n switchboard: { driveUrl: string },\n): { switchboardUrl: string; driveUrl: string; mcpUrl: string } {\n return {\n switchboardUrl: `${proxyUrl}/switchboard/graphql`,\n driveUrl: `${proxyUrl}/switchboard${new URL(switchboard.driveUrl).pathname}`,\n mcpUrl: `${proxyUrl}/switchboard/mcp`,\n };\n}\n\n/** A (serviceId, captureName) pair identifying the proxy-root website. */\nexport interface ProxyRootCapture {\n serviceId: string;\n captureName: string;\n}\n\n/**\n * Resolve which website capture implicitly owns the proxy root when none\n * sets `proxyRoot` explicitly. Exactly one website capture across all\n * definitions → that capture (preserves single-SPA behavior for CLIs that\n * predate the flag). Zero, several, or any explicit root → undefined.\n */\nexport function resolveImplicitProxyRoot(\n defs: ServiceDefinition[],\n): ProxyRootCapture | undefined {\n let single: ProxyRootCapture | undefined;\n let count = 0;\n for (const def of defs) {\n for (const [captureName, captureDef] of getCapturesForDef(def)) {\n if (typeof captureDef === \"number\") continue;\n if (captureDef.type !== \"website\") continue;\n if (captureDef.proxyRoot) return undefined;\n count++;\n single ??= { serviceId: def.id, captureName };\n }\n }\n return count === 1 ? single : undefined;\n}\n\n/**\n * Proxy mount prefix for a service route: `/{serviceId}/{name}`. Single\n * owner of the convention used for capture routes and for mounting\n * `ServiceDefinition.proxyRoutes` specs.\n */\nexport function captureRoutePrefix(\n serviceId: string,\n captureName: string,\n): string {\n return `/${serviceId}/${captureName}`;\n}\n\n/**\n * Build proxy routes from a service definition's readiness captures and its\n * `proxyRoutes` hook. Only captures with announceable endpoint types produce\n * routes; hook specs are mounted under `/{serviceId}/`.\n */\nexport function buildServiceRoutes(\n def: ServiceDefinition,\n instance: ServiceInstanceStatus,\n implicitRoot?: ProxyRootCapture,\n log?: { warn(msg: string): void },\n): ProxyRoute[] {\n const routes: ProxyRoute[] = [];\n const captures = getCapturesForDef(def);\n\n for (const [captureName, captureDef] of captures) {\n const captureType =\n typeof captureDef === \"number\" ? undefined : captureDef.type;\n if (!captureType) continue;\n\n const url = instance.endpoints?.[captureName];\n if (!url) continue;\n\n try {\n const upstream = new URL(url);\n // Only the proxy-root capture claims the '/' catch-all — the primary\n // SPA whose root-relative asset requests (/assets/*, /icon.ico) must\n // resolve at the proxy root. Either flagged `proxyRoot` explicitly, or\n // the implicit fallback when it is the only website across all\n // services. Every other endpoint, websites included, is routed under\n // its own prefix; prefixed websites must serve themselves under that\n // base path.\n const proxyRoot =\n captureType === \"website\" &&\n ((typeof captureDef !== \"number\" && captureDef.proxyRoot === true) ||\n (implicitRoot?.serviceId === def.id &&\n implicitRoot.captureName === captureName));\n const prefix = proxyRoot ? \"/\" : captureRoutePrefix(def.id, captureName);\n routes.push({\n prefix,\n upstream,\n ws: isWsEndpointType(captureType),\n source: `service:${def.id}`,\n });\n } catch {\n // Skip invalid URLs\n }\n }\n\n if (def.proxyRoutes) {\n let specs: ServiceProxyRouteSpec[] = [];\n try {\n specs = def.proxyRoutes(instance) ?? [];\n } catch (err) {\n // Skip a throwing hook — capture routes still apply\n log?.warn(\n `proxyRoutes hook failed for service '${def.id}': ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n for (const spec of specs) {\n try {\n const upstream =\n spec.upstream instanceof URL ? spec.upstream : new URL(spec.upstream);\n routes.push({\n prefix: captureRoutePrefix(def.id, spec.prefix.replace(/^\\/+/, \"\")),\n upstream,\n ws: spec.ws ?? false,\n source: `service:${def.id}`,\n });\n } catch (err) {\n // Skip invalid upstream URLs — other specs still apply\n log?.warn(\n `Invalid proxyRoutes spec '${spec.prefix}' for service '${def.id}': ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n }\n\n return routes;\n}\n\nfunction getCapturesForDef(\n def: ServiceDefinition,\n): Array<[string, number | CaptureDefinition]> {\n const result: Array<[string, number | CaptureDefinition]> = [];\n if (!def.readiness) return result;\n\n if (def.readiness.captures) {\n for (const [name, capDef] of Object.entries(def.readiness.captures)) {\n result.push([name, capDef]);\n }\n }\n\n if (def.readiness.patterns) {\n for (const pattern of def.readiness.patterns) {\n if (pattern.captures) {\n for (const [name, capDef] of Object.entries(pattern.captures)) {\n result.push([name, capDef]);\n }\n }\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;AA6CA,SAAgB,cAAc,QAAgB,UAA2B;CACvE,IAAI,WAAW,KAAK,OAAO;CAC3B,IAAI,OAAO,SAAS,GAAG,GACrB,OAAO,aAAa,OAAO,MAAM,GAAG,EAAE,KAAK,SAAS,WAAW,MAAM;CAEvE,OAAO,aAAa,UAAU,SAAS,WAAW,SAAS,GAAG;AAChE;;;;;;;AAQA,S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