@powerhousedao/switchboard 6.2.3-dev.17 → 6.2.3-dev.18

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ ## 6.2.3-dev.18 (2026-09-21)
2
+
3
+ ### 🚀 Features
4
+
5
+ - **workflow:** read pieces from a Powerhouse registry ([f1467e0b0](https://github.com/powerhouse-inc/powerhouse/commit/f1467e0b0))
6
+
7
+ ### 🩹 Fixes
8
+
9
+ - **switchboard:** load the workflow package like any other package ([7629bf71f](https://github.com/powerhouse-inc/powerhouse/commit/7629bf71f))
10
+
11
+ ### ❤️ Thank You
12
+
13
+ - acaldas
14
+
1
15
  ## 6.2.3-dev.17 (2026-09-21)
2
16
 
3
17
  This was a version bump only for @powerhousedao/switchboard to align it with other projects, there were no code changes.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
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]="c6c10af1-f4cc-56a5-abf6-fa35cf0de956")}catch(e){}}();
4
- import { a as parseForcePgVersion, r as startSwitchboard } from "./server-CS-HdQ55.mjs";
4
+ import { a as parseForcePgVersion, r as startSwitchboard } from "./server-C6VtW18k.mjs";
5
5
  import "./utils-Baw7rThP.mjs";
6
6
  import { metrics } from "@opentelemetry/api";
7
7
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
@@ -1,5 +1,5 @@
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]="ae2b68ff-70be-5a4d-b660-8ec25c22e5cd")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="75db5742-026a-585f-b76c-c4e4981bb421")}catch(e){}}();
3
3
  import { n as addDefaultReactorDrive, r as isPostgresUrl, t as addDefaultDrive } from "./utils-Baw7rThP.mjs";
4
4
  import { register } from "node:module";
5
5
  import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
@@ -1233,9 +1233,9 @@ async function resolveWorkflowsEnabled({ featureFlags, override, configEnabled =
1233
1233
  if (raw === "0") return false;
1234
1234
  return featureFlags.getBooleanValue(PH_WORKFLOWS_ENABLED, configEnabled);
1235
1235
  }
1236
- async function loadWorkflowDocumentModels(load = () => import("@powerhousedao/workflow/document-models")) {
1236
+ async function assertWorkflowPackageLoadable(load = () => import("@powerhousedao/workflow/document-models")) {
1237
1237
  try {
1238
- return Object.values(await load()).filter((module) => typeof module === "object" && module !== null && "documentModel" in module && "reducer" in module);
1238
+ await load();
1239
1239
  } catch (error) {
1240
1240
  throw new Error(`Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`, { cause: error });
1241
1241
  }
@@ -1325,6 +1325,7 @@ async function composeWorkflowRuntime(deps) {
1325
1325
  } catch (error) {
1326
1326
  throw new Error("Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded", { cause: error });
1327
1327
  }
1328
+ engine.setPieceRegistryUrl(deps.pieceRegistryUrl);
1328
1329
  if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);
1329
1330
  const runtime = engine.createWorkflowRuntime({
1330
1331
  relationalDb: deps.relationalDb,
@@ -1723,6 +1724,10 @@ async function initServer(serverPort, options, renown, renownConfig) {
1723
1724
  process.kill(process.pid, "SIGTERM");
1724
1725
  };
1725
1726
  const workflowsEnabled = options.workflows?.enabled === true;
1727
+ if (workflowsEnabled) {
1728
+ await assertWorkflowPackageLoadable();
1729
+ if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
1730
+ }
1726
1731
  let ownedReactorModule;
1727
1732
  const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests }) => {
1728
1733
  if (options.reactor) {
@@ -1754,13 +1759,8 @@ async function initServer(serverPort, options, renown, renownConfig) {
1754
1759
  if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
1755
1760
  const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
1756
1761
  const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
1757
- const workflowDocumentModels = workflowsEnabled ? await loadWorkflowDocumentModels() : [];
1758
1762
  applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
1759
- documentModels: [
1760
- ...documentModels,
1761
- ...vetraDocumentModels,
1762
- ...workflowDocumentModels
1763
- ],
1763
+ documentModels: [...documentModels, ...vetraDocumentModels],
1764
1764
  upgradeManifests,
1765
1765
  executorConfig: hasSkipThreshold || enabledFeatureFlags.length > 0 ? {
1766
1766
  ...hasSkipThreshold ? { maxSkipThreshold } : {},
@@ -1925,6 +1925,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
1925
1925
  webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,
1926
1926
  authorizationService: api.authorizationService,
1927
1927
  pieces: api.packageManager,
1928
+ pieceRegistryUrl: registryUrl,
1928
1929
  logger: logger.child(["workflow-runtime"])
1929
1930
  });
1930
1931
  const WorkflowRuntimeSubgraph = workflows.subgraph;
@@ -2100,5 +2101,5 @@ if (import.meta.main) await startSwitchboard();
2100
2101
  //#endregion
2101
2102
  export { parseForcePgVersion as a, applySwitchboardReactorDefaults as i, isPortAvailable as n, startSwitchboard as r, deriveAttachmentServiceConfig as t };
2102
2103
 
2103
- //# sourceMappingURL=server-CS-HdQ55.mjs.map
2104
- //# debugId=ae2b68ff-70be-5a4d-b660-8ec25c22e5cd
2104
+ //# sourceMappingURL=server-C6VtW18k.mjs.map
2105
+ //# debugId=75db5742-026a-585f-b76c-c4e4981bb421
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-C6VtW18k.mjs","sources":["../src/pglite-version.ts","../src/attachments/auth.ts","../src/attachments/mount-auth.ts","../src/attachments/routes.ts","../src/attachments/index.ts","../src/attachment-reference-read-model.mts","../src/builder-defaults.mts","../src/worker-pool.mts","../src/projection-worker.mts","../src/feature-flags.ts","../src/workflow/resolvers.ts","../src/workflow/schema.ts","../src/workflow/subgraph.ts","../src/workflow-runtime.mts","../src/pglite-dialect.ts","../src/pglite-migration.ts","../src/reactor-feature-flags.mts","../src/renown.ts","../src/server.mts"],"sourcesContent":["import type * as CurrentPGliteModuleNs from \"@electric-sql/pglite\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const CURRENT_PG_MAJOR = 17;\nexport const SUPPORTED_PG_MAJORS = [16, 17] as const;\nexport type SupportedPgMajor = (typeof SUPPORTED_PG_MAJORS)[number];\n\ntype CurrentPGliteModule = typeof CurrentPGliteModuleNs;\n\nexport async function readPgVersionFile(\n dataDir: string,\n): Promise<number | null> {\n try {\n const raw = await fs.readFile(path.join(dataDir, \"PG_VERSION\"), \"utf8\");\n const major = parseInt(raw.trim(), 10);\n return Number.isFinite(major) ? major : null;\n } catch {\n return null;\n }\n}\n\nexport function isSupportedMajor(major: number): major is SupportedPgMajor {\n return (SUPPORTED_PG_MAJORS as readonly number[]).includes(major);\n}\n\n/**\n * Parses the `PH_FORCE_PG_VERSION` env var. Returns the validated major, or\n * `null` when the var is unset/empty. Throws on any value that is not a\n * supported major — invalid configuration must fail before the server starts\n * touching disk.\n */\nexport function parseForcePgVersion(\n raw: string | undefined,\n): SupportedPgMajor | null {\n if (raw === undefined || raw.trim() === \"\") return null;\n const parsed = Number(raw);\n if (Number.isInteger(parsed) && isSupportedMajor(parsed)) return parsed;\n throw new Error(\n `PH_FORCE_PG_VERSION must be one of: ${SUPPORTED_PG_MAJORS.join(\", \")} (got: ${raw})`,\n );\n}\n\nexport async function loadPGliteModule(\n major: SupportedPgMajor,\n): Promise<CurrentPGliteModule> {\n if (major === 16) {\n return (await import(\"pglite-legacy-02\")) as unknown as CurrentPGliteModule;\n }\n return import(\"@electric-sql/pglite\");\n}\n\ntype PgDumpFn = (options: {\n pg: unknown;\n}) => Promise<{ text(): Promise<string> }>;\n\nexport async function loadPgDump(major: SupportedPgMajor): Promise<PgDumpFn> {\n if (major === 16) {\n const mod = (await import(\"pglite-tools-legacy-02/pg_dump\")) as {\n pgDump: PgDumpFn;\n };\n return mod.pgDump;\n }\n const mod = (await import(\"@electric-sql/pglite-tools/pg_dump\")) as {\n pgDump: PgDumpFn;\n };\n return mod.pgDump;\n}\n","import type { AuthContext, AuthService } from \"@powerhousedao/reactor-api\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n/**\n * Verified actor context for authenticated attachment handlers. The user comes\n * exclusively from bearer verification: when auth is disabled (OPEN mode)\n * `user` is undefined and `authEnabled` is false, and handlers must treat the\n * caller as anonymous. Caller-supplied identity headers are never consulted.\n */\nexport type AttachmentActorContext = {\n user: AuthContext[\"user\"];\n authEnabled: boolean;\n};\n\nconst ANONYMOUS_ACTOR: AttachmentActorContext = {\n user: undefined,\n authEnabled: false,\n};\n\nexport type NodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n actor?: AttachmentActorContext,\n) => Promise<void> | void;\n\nexport type RequireAuthOptions = {\n /**\n * Let requests without a bearer identity through as anonymous actors\n * instead of answering 401, so the handler's own document authorization\n * decides. A bearer that IS supplied must still verify — an invalid token\n * is rejected, never downgraded to anonymous.\n */\n allowAnonymous?: boolean;\n};\n\n/**\n * Wrap a Node-style handler so that, when `authService` is provided and auth is\n * enabled, the request must carry a verifiable Bearer token. The handler always\n * receives an actor context: the verified bearer user when auth is enabled, or\n * the anonymous context when it is disabled. With `allowAnonymous`, a missing\n * bearer yields an anonymous actor with `authEnabled: true` instead of a 401.\n */\nexport function requireAuth(\n authService: AuthService | undefined,\n handler: NodeHandler,\n options?: RequireAuthOptions,\n): NodeHandler {\n if (!authService) {\n return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);\n }\n\n return async (req, res, body) => {\n let result;\n try {\n result = await authService.verifyBearer(req.headers.authorization);\n } catch {\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal authentication error\" }));\n return;\n }\n\n if (result instanceof Response) {\n const body = await result.text();\n res.statusCode = result.status;\n const contentType = result.headers.get(\"content-type\");\n if (contentType) res.setHeader(\"Content-Type\", contentType);\n res.end(body);\n return;\n }\n\n if (result.auth_enabled && !result.user && !options?.allowAnonymous) {\n res.statusCode = 401;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Authentication required\" }));\n return;\n }\n\n await handler(req, res, body, {\n user: result.user,\n authEnabled: result.auth_enabled,\n });\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport {\n requireAuth,\n type NodeHandler,\n type RequireAuthOptions,\n} from \"./auth.js\";\n\nexport type HttpMethod = \"DELETE\" | \"GET\" | \"HEAD\" | \"POST\" | \"PUT\";\n\n/**\n * Mount a Node-style attachment route with `requireAuth` applied unconditionally.\n * When `api.authService` is undefined (auth disabled), the handler still runs\n * through `requireAuth` and receives the anonymous actor context — that is the\n * only way to opt out of bearer verification. To register a route without auth\n * wrapping you must call `api.httpAdapter.mountNodeRoute` directly.\n *\n * `allowAnonymous` is reserved for routes whose handlers make a per-document\n * authorization decision themselves; identity-only routes must not use it.\n */\nexport function mountAuthenticatedNodeRoute(\n api: Pick<API, \"httpAdapter\" | \"authService\">,\n method: HttpMethod,\n path: string,\n handler: NodeHandler,\n options?: RequireAuthOptions,\n): void {\n api.httpAdapter.mountNodeRoute(\n method,\n path,\n requireAuth(api.authService, handler, options),\n );\n}\n","import {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n HashMismatch,\n InvalidAttachmentRef,\n ReservationNotFound,\n SizeMismatch,\n UploadTooLarge,\n createRef,\n parseAttachmentDownloadTarget,\n type AttachmentBuildResult,\n type AttachmentDownloadTarget,\n type ReserveAttachmentOptions,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { IAttachmentAccessService } from \"@powerhousedao/reactor-api\";\nimport type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport { childLogger } from \"document-model\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport type { AttachmentActorContext } from \"./auth.js\";\n\nconst logger = childLogger([\"switchboard\", \"attachments\"]);\n\nconst RETRY_AFTER_SECONDS = 5;\n\n// Canonical form is lowercase hex (the SHA-256 hasher emits lowercase), but\n// accept either case from the wire and normalise before lookup. This keeps\n// the API forgiving for hand-typed URLs without changing storage semantics.\nconst HASH_PATTERN = /^[a-f0-9]{64}$/i;\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS = /[\\x00-\\x1f\\x7f]/;\n// RFC 6838 token chars; allows optional `; param=value` pairs (token or quoted-string).\nconst MIME_TYPE_PATTERN =\n /^[!#$%&'*+\\-.^_`|~\\w]+\\/[!#$%&'*+\\-.^_`|~\\w]+(?:\\s*;\\s*[!#$%&'*+\\-.^_`|~\\w]+=(?:[!#$%&'*+\\-.^_`|~\\w]+|\"(?:[^\"\\\\\\r\\n]|\\\\[^\\r\\n])*\"))*$/;\nconst MAX_FILENAME_LEN = 255;\nconst MAX_MIMETYPE_LEN = 255;\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify(body));\n}\n\nfunction sendError(res: ServerResponse, status: number, message: string): void {\n sendJson(res, status, { error: message });\n}\n\nfunction statusForError(err: unknown): number {\n if (err instanceof AttachmentNotFound) return 404;\n if (err instanceof ReservationNotFound) return 404;\n if (err instanceof InvalidAttachmentRef) return 400;\n if (err instanceof UploadTooLarge) return 413;\n return 500;\n}\n\nfunction sendErrorFromException(res: ServerResponse, err: unknown): void {\n const status = statusForError(err);\n if (status >= 500) {\n logger.error(\"Attachment route error: @error\", err);\n sendError(res, status, \"Internal error\");\n return;\n }\n sendError(res, status, err instanceof Error ? err.message : String(err));\n}\n\nasync function readJsonBody(\n req: IncomingMessage,\n body: unknown,\n): Promise<unknown> {\n // The Express body-parser may have already populated `body`. When that\n // happens we trust it; otherwise read the raw stream ourselves so this\n // module is independent of upstream middleware ordering.\n if (body !== undefined && body !== null && typeof body === \"object\") {\n return body;\n }\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(chunk as Buffer);\n }\n if (chunks.length === 0) return undefined;\n const text = Buffer.concat(chunks).toString(\"utf8\");\n if (text.length === 0) return undefined;\n return JSON.parse(text);\n}\n\nexport function parseReserveOptions(\n input: unknown,\n): ReserveAttachmentOptions | null {\n if (input === null || typeof input !== \"object\") return null;\n const obj = input as Record<string, unknown>;\n if (\n typeof obj.mimeType !== \"string\" ||\n obj.mimeType.length === 0 ||\n obj.mimeType.length > MAX_MIMETYPE_LEN ||\n !MIME_TYPE_PATTERN.test(obj.mimeType)\n ) {\n return null;\n }\n if (\n typeof obj.fileName !== \"string\" ||\n obj.fileName.length === 0 ||\n obj.fileName.length > MAX_FILENAME_LEN ||\n CONTROL_CHARS.test(obj.fileName)\n ) {\n return null;\n }\n let extension: string | null = null;\n if (typeof obj.extension === \"string\") {\n if (obj.extension.length === 0 || /[\\\\/]/.test(obj.extension)) return null;\n extension = obj.extension;\n } else if (obj.extension !== undefined && obj.extension !== null) {\n return null;\n }\n\n // Hash-first mode: clientHash triggers this path; sizeBytes is required alongside it.\n // A body with sizeBytes but no clientHash falls through to the legacy path unchanged.\n if (obj.clientHash !== undefined) {\n if (\n typeof obj.clientHash !== \"string\" ||\n !HASH_PATTERN.test(obj.clientHash)\n ) {\n return null;\n }\n if (\n typeof obj.sizeBytes !== \"number\" ||\n !Number.isInteger(obj.sizeBytes) ||\n obj.sizeBytes <= 0 ||\n !Number.isSafeInteger(obj.sizeBytes)\n ) {\n return null;\n }\n return {\n mimeType: obj.mimeType,\n fileName: obj.fileName,\n extension,\n clientHash: obj.clientHash.toLowerCase() as AttachmentHash,\n sizeBytes: obj.sizeBytes,\n };\n }\n\n return {\n mimeType: obj.mimeType,\n fileName: obj.fileName,\n extension,\n };\n}\n\nexport function quoteFilename(name: string): string {\n // RFC 6266: quoted-string with internal \" and \\ escaped.\n return `\"${name.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nexport function buildContentDisposition(fileName: string): string {\n // ASCII fallback: replace any byte outside printable ASCII (0x20-0x7e),\n // plus `\"` and `\\`, with `_`. Browsers fall back to this when they don't\n // grok `filename*=`; the modern parameter carries the real name.\n const ascii = fileName.replace(/[^\\x20-\\x21\\x23-\\x5b\\x5d-\\x7e]/g, \"_\");\n // RFC 5987: percent-encode UTF-8 bytes. encodeURIComponent leaves a few\n // chars that 5987 disallows in token; re-encode them.\n const encoded = encodeURIComponent(fileName).replace(\n /['()*!]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n return `attachment; filename=${quoteFilename(ascii)}; filename*=UTF-8''${encoded}`;\n}\n\nexport function makeReserveHandler(attachments: AttachmentBuildResult) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n ): Promise<void> => {\n let parsed: unknown;\n try {\n parsed = await readJsonBody(req, body);\n } catch {\n sendError(res, 400, \"Invalid JSON body\");\n return;\n }\n const opts = parseReserveOptions(parsed);\n if (!opts) {\n sendError(\n res,\n 400,\n \"Body must be { mimeType: string (type/subtype), fileName: string (no control characters, max 255 chars), extension?: string|null, clientHash?: string (64 hex chars), sizeBytes?: number (required with clientHash) }\",\n );\n return;\n }\n\n let upload;\n try {\n upload = await attachments.service.reserve(opts);\n } catch (err) {\n if (err instanceof AttachmentAlreadyExists) {\n sendJson(res, 409, { error: \"already_exists\", ref: err.ref });\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n sendJson(res, 201, {\n reservationId: upload.reservationId,\n ref: upload.ref,\n expiresAtUtc: upload.expiresAtUtc,\n ...(upload.uploadTarget ? { uploadTarget: upload.uploadTarget } : {}),\n });\n };\n}\n\nexport function makeUploadHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n if (attachments.backend?.kind === \"s3\") {\n sendError(res, 405, \"Use the reservation uploadTarget for S3 uploads\");\n return;\n }\n\n let reservation;\n try {\n reservation = await attachments.reservations.get(reservationId);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n const upload = attachments.uploadFactory.createUpload(reservation);\n\n const webStream = Readable.toWeb(\n req as Readable,\n ) as ReadableStream<Uint8Array>;\n\n try {\n const result = await upload.send(webStream);\n sendJson(res, 200, result);\n } catch (err) {\n if (err instanceof HashMismatch) {\n sendJson(res, 422, {\n error: \"hash_mismatch\",\n claimed: err.claimed,\n actual: err.actual,\n });\n return;\n }\n if (err instanceof SizeMismatch) {\n sendJson(res, 422, {\n error: \"size_mismatch\",\n declared: err.declared,\n actual: err.actual,\n });\n return;\n }\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDownloadHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const controller = new AbortController();\n req.once(\"close\", () => controller.abort());\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n let response;\n try {\n response = await attachments.store.get(canonicalHash, controller.signal);\n } catch (err) {\n if (err instanceof AttachmentPending) {\n res.statusCode = 202;\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n JSON.stringify({\n expiresAtUtc: err.expiresAtUtc,\n ...(err.metadata ?? {}),\n }),\n );\n res.end();\n return;\n }\n sendErrorFromException(res, err);\n return;\n }\n\n const { header, body } = response;\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n\n Readable.fromWeb(body as unknown as NodeReadableStream<Uint8Array>).pipe(\n res,\n );\n };\n}\n\nfunction buildMetadataHeader(header: {\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n extension: string | null;\n createdAtUtc: string;\n lastAccessedAtUtc: string;\n}): string {\n return JSON.stringify({\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n extension: header.extension,\n createdAtUtc: header.createdAtUtc,\n lastAccessedAtUtc: header.lastAccessedAtUtc,\n });\n}\n\nexport function makeStatHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n sendErrorFromException(res, err);\n return;\n }\n\n if (header.status === \"pending\") {\n res.statusCode = 202;\n res.setHeader(\"Retry-After\", String(RETRY_AFTER_SECONDS));\n res.setHeader(\n \"Attachment-Pending\",\n JSON.stringify({\n expiresAtUtc: header.expiresAtUtc,\n mimeType: header.mimeType,\n fileName: header.fileName,\n sizeBytes: header.sizeBytes,\n }),\n );\n res.end();\n return;\n }\n\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", header.mimeType);\n res.setHeader(\"Content-Length\", String(header.sizeBytes));\n res.setHeader(\n \"Content-Disposition\",\n buildContentDisposition(header.fileName),\n );\n res.setHeader(\"Attachment-Metadata\", buildMetadataHeader(header));\n res.end();\n };\n}\n\nexport function makeGetReservationHandler(attachments: AttachmentBuildResult) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n const reservation = await attachments.reservations.get(reservationId);\n sendJson(res, 200, reservation);\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nexport function makeDeleteReservationHandler(\n attachments: AttachmentBuildResult,\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const reservationId = extractParam(req, \"reservationId\");\n if (!reservationId) {\n sendError(res, 400, \"Missing reservationId\");\n return;\n }\n try {\n await attachments.reservations.delete(reservationId);\n res.statusCode = 204;\n res.end();\n } catch (err) {\n sendErrorFromException(res, err);\n }\n };\n}\n\nfunction extractParam(req: IncomingMessage, name: string): string | undefined {\n const expressParams = (\n req as IncomingMessage & {\n params?: Record<string, string>;\n }\n ).params;\n return expressParams?.[name];\n}\n\nconst MAX_DOCUMENT_ID_LEN = 512;\nconst ATTACHMENT_NOT_FOUND_BODY = { error: \"Attachment not found\" };\n// SigV4 presigned URLs cannot outlive 7 days; requests above the cap are\n// clamped rather than rejected so clients need not know the ceiling.\nconst MAX_DOWNLOAD_TARGET_TTL_SECONDS = 7 * 24 * 60 * 60;\n\n/**\n * Returns the single `documentId` query value, or null when it is missing,\n * duplicated, blank, or oversized. Validation happens before authorization so\n * malformed requests never reach the access service.\n */\nfunction extractSingleDocumentId(req: IncomingMessage): string | null {\n if (!req.url) return null;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(\"documentId\");\n if (values.length !== 1) return null;\n const value = values[0];\n if (value.trim().length === 0 || value.length > MAX_DOCUMENT_ID_LEN) {\n return null;\n }\n return value;\n}\n\n/**\n * Returns the requested target TTL in seconds: undefined when absent,\n * \"invalid\" when malformed (duplicated, non-integer, or non-positive), and\n * otherwise the value clamped to the presigning ceiling.\n */\nfunction extractExpiresIn(\n req: IncomingMessage,\n): number | undefined | \"invalid\" {\n if (!req.url) return undefined;\n let url: URL;\n try {\n url = new URL(req.url, \"http://switchboard.invalid\");\n } catch {\n return undefined;\n }\n const values = url.searchParams.getAll(\"expiresIn\");\n if (values.length === 0) return undefined;\n if (values.length > 1) return \"invalid\";\n const parsed = Number(values[0]);\n if (!Number.isInteger(parsed) || parsed <= 0) return \"invalid\";\n return Math.min(parsed, MAX_DOWNLOAD_TARGET_TTL_SECONDS);\n}\n\n/**\n * Base URL of this Switchboard as seen by the caller, used to build\n * filesystem `switchboard` download targets that point back at the existing\n * authenticated byte route.\n */\nfunction requestBaseUrl(req: IncomingMessage): string | null {\n const forwardedProto = req.headers[\"x-forwarded-proto\"];\n const proto =\n (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)\n ?.split(\",\")[0]\n ?.trim() ||\n ((req.socket as { encrypted?: boolean }).encrypted ? \"https\" : \"http\");\n const forwardedHost = req.headers[\"x-forwarded-host\"];\n const host =\n (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ??\n req.headers.host;\n if (!host) return null;\n return `${proto}://${host}`;\n}\n\nexport function makeDownloadTargetHandler(\n attachments: AttachmentBuildResult,\n attachmentAccess: IAttachmentAccessService,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n _body?: unknown,\n actor?: AttachmentActorContext,\n ): Promise<void> => {\n // Target responses carry short-lived URLs and authorization decisions;\n // no intermediary may cache them.\n res.setHeader(\"Cache-Control\", \"no-store\");\n\n const hash = extractParam(req, \"hash\");\n if (!hash || !HASH_PATTERN.test(hash)) {\n sendError(res, 400, \"Invalid attachment hash\");\n return;\n }\n const documentId = extractSingleDocumentId(req);\n if (documentId === null) {\n sendError(\n res,\n 400,\n \"documentId is required exactly once as a non-empty query parameter\",\n );\n return;\n }\n const expiresIn = extractExpiresIn(req);\n if (expiresIn === \"invalid\") {\n sendError(\n res,\n 400,\n \"expiresIn must be a single positive integer number of seconds\",\n );\n return;\n }\n\n const canonicalHash = hash.toLowerCase() as AttachmentHash;\n let decision;\n try {\n decision = await attachmentAccess.canReadAttachment({\n documentId,\n attachmentRef: createRef(canonicalHash),\n userAddress: actor?.user?.address,\n });\n } catch (err) {\n logger.error(\"Attachment access decision failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n\n if (decision.kind === \"projection-unavailable\") {\n sendError(res, 503, \"Attachment downloads are temporarily unavailable\");\n return;\n }\n if (decision.kind === \"denied\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let header;\n try {\n header = await attachments.store.stat(canonicalHash);\n } catch (err) {\n if (err instanceof AttachmentNotFound) {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n logger.error(\"Attachment metadata lookup failed: @error\", err);\n sendError(res, 500, \"Internal error\");\n return;\n }\n if (header.status !== \"available\") {\n sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);\n return;\n }\n\n let target: AttachmentDownloadTarget;\n if (attachments.backend && attachments.backend.kind !== \"filesystem\") {\n try {\n target = await attachments.backend.prepareDownloadTarget(\n canonicalHash,\n expiresIn,\n );\n } catch {\n // Backend errors are sanitized at the backend boundary; no URLs or\n // signatures reach this scope, and none may be logged from here.\n sendError(res, 502, \"Attachment download target unavailable\");\n return;\n }\n } else {\n const base = requestBaseUrl(req);\n if (!base) {\n sendError(res, 500, \"Internal error\");\n return;\n }\n try {\n target = parseAttachmentDownloadTarget({\n kind: \"switchboard\",\n method: \"GET\",\n url: `${base}/attachments/${canonicalHash}`,\n headers: {},\n });\n } catch {\n sendError(res, 500, \"Internal error\");\n return;\n }\n }\n\n sendJson(res, 200, target);\n };\n}\n","import type { API } from \"@powerhousedao/reactor-api\";\nimport { mountAuthenticatedNodeRoute } from \"./mount-auth.js\";\nimport {\n makeDeleteReservationHandler,\n makeDownloadHandler,\n makeDownloadTargetHandler,\n makeGetReservationHandler,\n makeReserveHandler,\n makeStatHandler,\n makeUploadHandler,\n} from \"./routes.js\";\n\nexport function registerAttachmentRoutes(api: API): void {\n const { attachments } = api;\n\n mountAuthenticatedNodeRoute(\n api,\n \"POST\",\n \"/attachments/reservations\",\n makeReserveHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/reservations/:reservationId\",\n makeGetReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"DELETE\",\n \"/attachments/reservations/:reservationId\",\n makeDeleteReservationHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"PUT\",\n \"/attachments/reservations/:reservationId\",\n makeUploadHandler(attachments),\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"HEAD\",\n \"/attachments/:hash\",\n makeStatHandler(attachments),\n );\n\n // Anonymous-capable: authorization is purely the document's — canRead plus\n // the reference index decide, exactly as they do for the document itself.\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash/download-target\",\n makeDownloadTargetHandler(attachments, api.attachmentAccess),\n { allowAnonymous: true },\n );\n\n mountAuthenticatedNodeRoute(\n api,\n \"GET\",\n \"/attachments/:hash\",\n makeDownloadHandler(attachments),\n );\n}\n","import {\n REACTOR_SCHEMA,\n supportsLiveReadModelRegistration,\n type DocumentViewDatabase,\n type InProcessReactorClientModule,\n type ReactorBuilder,\n} from \"@powerhousedao/reactor\";\nimport type { AttachmentReferenceProjectionCapability } from \"@powerhousedao/reactor-api\";\nimport {\n AttachmentReferenceReadModel,\n AttachmentSchemaCompiler,\n type IAttachmentReferenceWriter,\n} from \"@powerhousedao/reactor-attachments\";\nimport type { Kysely } from \"kysely\";\n\nexport type AttachmentReferenceReadModelRegistration = {\n attachmentReferenceWriter: IAttachmentReferenceWriter;\n baseKysely: Kysely<unknown>;\n};\n\nconst attachmentSchemaCompiler = new AttachmentSchemaCompiler();\n\nfunction createAttachmentReferenceReadModel(\n baseKysely: Kysely<unknown>,\n dependencies: {\n operationIndex: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[1];\n writeCache: ConstructorParameters<typeof AttachmentReferenceReadModel>[2];\n processorManagerConsistencyTracker: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[3];\n documentModelRegistry: ConstructorParameters<\n typeof AttachmentReferenceReadModel\n >[4];\n },\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): AttachmentReferenceReadModel {\n return new AttachmentReferenceReadModel(\n baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<DocumentViewDatabase>,\n dependencies.operationIndex,\n dependencies.writeCache,\n dependencies.processorManagerConsistencyTracker,\n dependencies.documentModelRegistry,\n attachmentSchemaCompiler,\n attachmentReferenceWriter,\n );\n}\n\nexport function registerAttachmentReferenceReadModel(\n reactorBuilder: ReactorBuilder,\n registration: AttachmentReferenceReadModelRegistration,\n): void {\n reactorBuilder.withReadModelFactory(\n async ({\n documentModelRegistry,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const readModel = createAttachmentReferenceReadModel(\n registration.baseKysely,\n {\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n documentModelRegistry,\n },\n registration.attachmentReferenceWriter,\n );\n await readModel.init();\n return readModel;\n },\n );\n}\n\nexport async function registerAttachmentReferenceReadModelOnModule(\n clientModule: InProcessReactorClientModule,\n attachmentReferenceWriter: IAttachmentReferenceWriter,\n): Promise<AttachmentReferenceProjectionCapability> {\n const reactorModule = clientModule.reactorModule;\n if (!reactorModule) {\n return {\n status: \"unavailable\",\n reason: \"in-process-reactor-module-unavailable\",\n };\n }\n\n const coordinator = reactorModule.readModelCoordinator;\n if (!supportsLiveReadModelRegistration(coordinator)) {\n return {\n status: \"unavailable\",\n reason: \"live-read-model-registration-unsupported\",\n };\n }\n\n const readModel = createAttachmentReferenceReadModel(\n reactorModule.database as unknown as Kysely<unknown>,\n {\n operationIndex: reactorModule.operationIndex,\n writeCache: reactorModule.writeCache,\n processorManagerConsistencyTracker:\n reactorModule.processorManagerConsistencyTracker,\n documentModelRegistry: reactorModule.documentModelRegistry,\n },\n attachmentReferenceWriter,\n );\n\n await readModel.init();\n coordinator.addReadModel(readModel, \"pre_ready\");\n await readModel.init();\n\n return { status: \"available\" };\n}\n","import type {\n ReactorBuilder,\n ReactorFeatureFlags,\n} from \"@powerhousedao/reactor\";\nimport {\n ChannelScheme,\n type IDocumentModelLoader,\n type ReactorClientBuilder,\n type SignerConfig,\n} from \"@powerhousedao/reactor\";\nimport { reactorDriveDocumentModelModule } from \"@powerhousedao/reactor-drive\";\nimport { ReactorGroupV1 } from \"@powerhousedao/reactor-group\";\nimport { getUniqueDocumentModels } from \"@powerhousedao/reactor-api\";\nimport { driveDocumentModelModule } from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule, type ILogger } from \"document-model\";\n\nexport type SwitchboardReactorDefaultsOptions = {\n // Extra models registered alongside the baseline (document-model, drive,\n // reactor-drive, reactor-group). Pass vetra models here in studio/dev.\n // Deduped by id.\n documentModels?: DocumentModelModule[];\n /** Upgrade manifests for versioned models, one per document type. */\n upgradeManifests?: UpgradeManifest<readonly number[]>[];\n /** Default true. */\n includeBaseModels?: boolean;\n /**\n * Channel scheme. Defaults to `ChannelScheme.SWITCHBOARD`, which populates\n * `reactorModule.syncModule.syncManager` — required by reactor-api. Set\n * to `false` only if the caller will configure a scheme themselves.\n */\n channelScheme?: ChannelScheme | false;\n /** Defaults to true. Set false when the caller owns SIGINT handling. */\n signalHandlers?: boolean;\n /** Executor tuning. Omit to use the reactor's own defaults. */\n executorConfig?: {\n maxSkipThreshold?: number;\n featureFlags?: Partial<ReactorFeatureFlags>;\n };\n /** Wire dynamic document-model loading via HTTP. */\n documentModelLoader?: IDocumentModelLoader;\n logger?: ILogger;\n /**\n * Identity signer (typically from `getRenownSignerConfig`). Applied to the\n * `ReactorClientBuilder`; omit for unsigned operation.\n */\n signer?: SignerConfig;\n};\n\n/**\n * Apply switchboard's standard configuration to a reactor + client builder\n * pair. Each piece is opt-out via the options object; defaults mirror what\n * `startSwitchboard` does when building a reactor itself. Mutates both\n * builders in place.\n *\n * Does NOT touch kysely or read models — callers wire those themselves\n * (see `withKysely` / `withReadModelFactory` on the reactor builder).\n */\n/** The models switchboard always registers alongside package models. */\nexport function switchboardBaseDocumentModels() {\n return [\n documentModelDocumentModelModule,\n driveDocumentModelModule,\n reactorDriveDocumentModelModule,\n ReactorGroupV1 as unknown as DocumentModelModule,\n ];\n}\n\nexport function applySwitchboardReactorDefaults(\n reactorBuilder: ReactorBuilder,\n clientBuilder: ReactorClientBuilder,\n options: SwitchboardReactorDefaultsOptions = {},\n): void {\n const baseModels =\n options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];\n const extra = options.documentModels ?? [];\n if (baseModels.length || extra.length) {\n reactorBuilder.withDocumentModelSources(\n getUniqueDocumentModels(baseModels, extra),\n );\n }\n\n if (options.upgradeManifests?.length) {\n reactorBuilder.withUpgradeManifests(options.upgradeManifests);\n }\n\n const scheme =\n options.channelScheme === undefined\n ? ChannelScheme.SWITCHBOARD\n : options.channelScheme;\n if (scheme !== false) {\n reactorBuilder.withChannelScheme(scheme);\n }\n\n if (options.signalHandlers !== false) {\n reactorBuilder.withSignalHandlers();\n }\n\n if (\n options.executorConfig?.maxSkipThreshold !== undefined ||\n options.executorConfig?.featureFlags !== undefined\n ) {\n reactorBuilder.withExecutorConfig({\n ...(options.executorConfig.maxSkipThreshold !== undefined\n ? { maxSkipThreshold: options.executorConfig.maxSkipThreshold }\n : {}),\n ...(options.executorConfig.featureFlags !== undefined\n ? { featureFlags: options.executorConfig.featureFlags }\n : {}),\n });\n }\n\n if (options.documentModelLoader) {\n reactorBuilder.withDocumentModelLoader(options.documentModelLoader);\n }\n\n if (options.logger) {\n reactorBuilder.withLogger(options.logger);\n }\n\n if (options.signer) {\n clientBuilder.withSigner(options.signer);\n }\n}\n","import type { DbConfig, FileModelSource } from \"@powerhousedao/reactor\";\nimport type { ILogger } from \"document-model\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type WorkerCountInput = number | \"auto\";\n\nexport type SwitchboardWorkerPoolOptions = {\n numWorkers: number;\n /** Whether numWorkers was given explicitly or sized from the core count. */\n mode: \"explicit\" | \"auto\";\n dbPoolSizePerWorker: number;\n acquireTimeoutMs: number;\n};\n\nexport type SwitchboardWorkerPoolInput = {\n numWorkers?: WorkerCountInput;\n dbPoolSizePerWorker?: number;\n acquireTimeoutMs?: number;\n};\n\nconst DEFAULT_DB_POOL_SIZE_PER_WORKER = 2;\nconst DEFAULT_ACQUIRE_TIMEOUT_MS = 5000;\n\n// Host reactor pool. pg-pool's own default is 10, below the bench harness's\n// floor of 16 (bench/host/src/main.ts, REACTOR_DB_POOL_SIZE_HOST). Run 8 of\n// the sweep found throughput flat from 16 to 96 but per-op index p50\n// collapsing 262ms -> 43ms, so this buys latency, not throughput — and only\n// up to whatever the connection budget in front of Postgres allows.\nconst DEFAULT_DB_POOL_SIZE_HOST = 16;\n\n// Auto-sizing: reserve cores for the host event loop (queue, read models,\n// HTTP) and cap at the top of the bench sweep envelope, which also bounds\n// the worker Postgres-connection budget.\nconst AUTO_RESERVED_CORES = 2;\nconst AUTO_WORKER_CAP = 8;\n\n/** Worker count for \"auto\": always at least 1 — auto sizes the pool, it does not turn worker mode off. */\nexport function autoWorkerCount(availableCores: number): number {\n return Math.max(\n 1,\n Math.min(AUTO_WORKER_CAP, availableCores - AUTO_RESERVED_CORES),\n );\n}\n\n/**\n * Effective worker-pool config from programmatic options (which win) and the\n * REACTOR_* env vars; null when disabled (numWorkers 0, the default).\n * `\"auto\"` sizes the pool from the machine's available cores.\n */\nexport function resolveWorkerPoolOptions(\n input: SwitchboardWorkerPoolInput | undefined,\n env: NodeJS.ProcessEnv,\n availableCores: number = os.availableParallelism(),\n): SwitchboardWorkerPoolOptions | null {\n const requested =\n input?.numWorkers ?? parseWorkerCount(env.REACTOR_WORKERS) ?? 0;\n const mode = requested === \"auto\" ? \"auto\" : \"explicit\";\n const numWorkers =\n requested === \"auto\" ? autoWorkerCount(availableCores) : requested;\n if (!Number.isInteger(numWorkers) || numWorkers < 0) {\n throw new Error(\n `workerPool.numWorkers must be \"auto\" or a non-negative integer, got ${numWorkers}`,\n );\n }\n if (numWorkers === 0) {\n return null;\n }\n return {\n numWorkers,\n mode,\n dbPoolSizePerWorker:\n input?.dbPoolSizePerWorker ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_WORKER,\n \"REACTOR_DB_POOL_SIZE_WORKER\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PER_WORKER,\n acquireTimeoutMs:\n input?.acquireTimeoutMs ??\n parseNonNegativeInt(\n env.REACTOR_DB_ACQUIRE_TIMEOUT_MS,\n \"REACTOR_DB_ACQUIRE_TIMEOUT_MS\",\n ) ??\n DEFAULT_ACQUIRE_TIMEOUT_MS,\n };\n}\n\n/**\n * Size of the reactor's own (host) Postgres pool. Unlike the worker pool there\n * is no \"disabled\" state — the host pool is the only Postgres pool in the\n * server path, backing both reactor storage and the read models that reach it\n * via `withSchema` — so 0 is rejected rather than read as \"off\".\n *\n * The acquire timeout is deliberately not configurable here: the host pool\n * waits indefinitely today, and making it finite converts saturation from a\n * latency problem into a thrown error on the read-model path. That is a\n * behavior change worth making separately, once the retry semantics of a\n * rejected `pool.connect()` inside the read-model coordinator are settled.\n */\nexport function resolveHostPoolSize(env: NodeJS.ProcessEnv): number {\n const poolSize =\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_HOST,\n \"REACTOR_DB_POOL_SIZE_HOST\",\n ) ?? DEFAULT_DB_POOL_SIZE_HOST;\n if (poolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_HOST must be at least 1; the host pool cannot be disabled\",\n );\n }\n return poolSize;\n}\n\n/**\n * DbConfig for each worker's own pool, parsed from a postgres:// URL.\n * Explicit host, database, and user are required — no pg-side defaults.\n */\nexport function buildWorkerDbConfig(\n postgresUrl: string,\n options: Pick<\n SwitchboardWorkerPoolOptions,\n \"dbPoolSizePerWorker\" | \"acquireTimeoutMs\"\n >,\n): DbConfig {\n let parsed: URL;\n try {\n parsed = new URL(postgresUrl);\n } catch {\n throw new Error(\n `Worker pool requires a valid postgres:// URL for the reactor database, got \"${postgresUrl}\"`,\n );\n }\n const database = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n if (!parsed.hostname || !database) {\n throw new Error(\n `Worker pool requires a postgres URL with a host and database name, got \"${postgresUrl}\"`,\n );\n }\n if (!parsed.username) {\n throw new Error(\n `Worker pool requires explicit credentials in the postgres URL (workers open their own connections), got \"${postgresUrl}\"`,\n );\n }\n const sslmode = parsed.searchParams.get(\"sslmode\");\n const ssl =\n parsed.searchParams.get(\"ssl\") === \"true\" ||\n (sslmode !== null && sslmode !== \"disable\");\n return {\n host: parsed.hostname,\n port: parsed.port ? Number(parsed.port) : 5432,\n database,\n user: decodeURIComponent(parsed.username),\n password: decodeURIComponent(parsed.password),\n ssl,\n applicationName: \"switchboard-worker\",\n poolSize: options.dbPoolSizePerWorker,\n connectionTimeoutMillis: options.acquireTimeoutMs,\n };\n}\n\n/** Specifiers of the base models switchboard always registers. */\nconst BASE_MODEL_SPECIFIERS = [\n \"document-model\",\n \"@powerhousedao/shared/document-drive\",\n \"@powerhousedao/reactor-drive\",\n \"@powerhousedao/reactor-group/document-models\",\n];\n\n/**\n * Resolves base models and configured package identifiers to `{ filePath }`\n * sources for the reactor builder. Resolution to absolute paths happens here\n * because workers (and the builder) resolve bare specifiers from the reactor\n * package's own dependency context, which cannot see switchboard or project\n * packages. Unresolvable identifiers are skipped with a warning; the builder\n * fails the boot if a registered model ends up without an importable source.\n */\nexport async function resolveWorkerModelSources(\n packages: string[],\n logger: ILogger,\n): Promise<FileModelSource[]> {\n const sources: FileModelSource[] = [];\n for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {\n const filePath = await resolveModelModuleFile(identifier);\n if (!filePath) {\n logger.warn(\n `Worker model sources: no importable document-models entry for \"${identifier}\", skipping`,\n );\n continue;\n }\n sources.push({ filePath });\n }\n return sources;\n}\n\n/**\n * Absolute file path of a source's models barrel. Mirrors reactor-api's\n * import-resolver: import.meta.resolve, then the project's node_modules via\n * the package.json exports map / dist layout.\n */\nasync function resolveModelModuleFile(source: string): Promise<string | null> {\n if (isFsPath(source)) {\n return resolveFromPackageDir(source, \"./document-models\");\n }\n\n const specifier = BASE_MODEL_SPECIFIERS.includes(source)\n ? source\n : `${source}/document-models`;\n\n try {\n const resolved = import.meta.resolve(specifier);\n if (resolved.startsWith(\"file:\")) {\n return fileURLToPath(resolved);\n }\n } catch {\n // fall through to node_modules resolution from the project dir\n }\n\n const { packageName, subpath } = splitSpecifier(specifier);\n const packageDir = path.join(process.cwd(), \"node_modules\", packageName);\n if (!existsSync(packageDir)) {\n return null;\n }\n let realDir: string;\n try {\n realDir = realpathSync(packageDir);\n } catch {\n return null;\n }\n return resolveFromPackageDir(realDir, subpath);\n}\n\nfunction splitSpecifier(specifier: string): {\n packageName: string;\n subpath: string;\n} {\n const parts = specifier.split(\"/\");\n const packageSegments = specifier.startsWith(\"@\") ? 2 : 1;\n const packageName = parts.slice(0, packageSegments).join(\"/\");\n const rest = parts.slice(packageSegments).join(\"/\");\n return { packageName, subpath: rest ? `./${rest}` : \".\" };\n}\n\n/** Exports-map lookup (import condition), then conventional dist paths. */\nasync function resolveFromPackageDir(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n const fromManifest = await resolveViaManifest(packageDir, subpath);\n if (fromManifest) {\n return fromManifest;\n }\n const candidates =\n subpath === \".\"\n ? [path.join(packageDir, \"dist\", \"index.js\")]\n : [\n path.join(packageDir, \"dist\", subpath.slice(2), \"index.js\"),\n path.join(packageDir, \"dist\", `${subpath.slice(2)}.js`),\n path.join(packageDir, subpath.slice(2), \"index.js\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\nasync function resolveViaManifest(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n let raw: string;\n try {\n raw = await readFile(path.join(packageDir, \"package.json\"), \"utf8\");\n } catch {\n return null;\n }\n let manifest: { exports?: unknown; main?: unknown };\n try {\n manifest = JSON.parse(raw) as { exports?: unknown; main?: unknown };\n } catch {\n return null;\n }\n\n let entry: unknown;\n const exportsField = manifest.exports;\n if (\n exportsField !== null &&\n typeof exportsField === \"object\" &&\n !Array.isArray(exportsField)\n ) {\n const map = exportsField as Record<string, unknown>;\n const hasSubpathKeys = Object.keys(map).some((key) => key.startsWith(\".\"));\n entry = hasSubpathKeys ? map[subpath] : subpath === \".\" ? map : undefined;\n } else if (typeof exportsField === \"string\" && subpath === \".\") {\n entry = exportsField;\n }\n\n let target = pickImportTarget(entry);\n if (!target && subpath === \".\" && typeof manifest.main === \"string\") {\n target = manifest.main;\n }\n if (!target) {\n return null;\n }\n const resolved = path.join(packageDir, target);\n return existsSync(resolved) ? resolved : null;\n}\n\nfunction pickImportTarget(entry: unknown): string | null {\n if (typeof entry === \"string\") {\n return entry;\n }\n if (typeof entry !== \"object\" || entry === null) {\n return null;\n }\n const conditions = entry as Record<string, unknown>;\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const value = conditions[condition];\n if (typeof value === \"string\") {\n return value;\n }\n }\n return null;\n}\n\nfunction isFsPath(identifier: string): boolean {\n return (\n path.isAbsolute(identifier) ||\n identifier.startsWith(\"./\") ||\n identifier.startsWith(\"../\")\n );\n}\n\nfunction parseWorkerCount(\n raw: string | undefined,\n): WorkerCountInput | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n if (raw.trim().toLowerCase() === \"auto\") {\n return \"auto\";\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(\n `REACTOR_WORKERS must be \"auto\" or a non-negative integer, got \"${raw}\"`,\n );\n }\n return value;\n}\n\nexport function parseNonNegativeInt(\n raw: string | undefined,\n name: string,\n): number | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(`${name} must be a non-negative integer, got \"${raw}\"`);\n }\n return value;\n}\n","import { isPostgresUrl } from \"./utils.mjs\";\nimport { parseNonNegativeInt } from \"./worker-pool.mjs\";\n\nexport type SwitchboardProjectionWorkerOptions = {\n dbPoolSize: number;\n};\n\nexport type SwitchboardProjectionWorkerInput = {\n enabled?: boolean;\n dbPoolSize?: number;\n};\n\n// Run 11 of the bench sweep saw chain.depth ~6.5 at one shard, so 8 covers the\n// working set; behind a 25-slot transaction pooler a larger pool is not spendable.\nconst DEFAULT_DB_POOL_SIZE_PROJECTION = 8;\n\nconst ON_TOKENS = [\"1\", \"true\", \"on\", \"yes\"];\nconst OFF_TOKENS = [\"0\", \"false\", \"off\", \"no\"];\n\n/**\n * Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or\n * `input.enabled`, which wins when defined; null when off (the default).\n */\nexport function resolveProjectionWorkerOptions(\n input: SwitchboardProjectionWorkerInput | undefined,\n env: NodeJS.ProcessEnv,\n): SwitchboardProjectionWorkerOptions | null {\n const enabled =\n input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false;\n if (!enabled) {\n return null;\n }\n const dbPoolSize =\n input?.dbPoolSize ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_PROJECTION,\n \"REACTOR_DB_POOL_SIZE_PROJECTION\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PROJECTION;\n if (dbPoolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool\",\n );\n }\n return { dbPoolSize };\n}\n\n/** Same preconditions as the executor worker pool; message shape mirrors server.mts. */\nexport function assertProjectionWorkerSupported(args: {\n dev: boolean;\n reactorDbUrl: string | undefined;\n}): void {\n if (args.dev) {\n throw new Error(\n \"The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n if (!args.reactorDbUrl || !isPostgresUrl(args.reactorDbUrl)) {\n throw new Error(\n \"The projection worker (REACTOR_PROJECTION_WORKER) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n}\n\nfunction parseOnOff(raw: string | undefined): boolean | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const token = raw.trim().toLowerCase();\n if (ON_TOKENS.includes(token)) {\n return true;\n }\n if (OFF_TOKENS.includes(token)) {\n return false;\n }\n throw new Error(\n `REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got \"${raw}\"`,\n );\n}\n","import { EnvVarProvider } from \"@openfeature/env-var-provider\";\nimport { OpenFeature } from \"@openfeature/server-sdk\";\n\nexport async function initFeatureFlags() {\n // for now, we're only using env vars for feature flags\n const provider = new EnvVarProvider();\n\n await OpenFeature.setProviderAndWait(provider);\n\n return OpenFeature.getClient();\n}\n","import type {\n Context,\n IAuthorizationService,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n RunRow,\n StepExecutionRow,\n WorkflowRuntimeService,\n} from \"@powerhousedao/reactor-workflow\";\nimport { GraphQLError } from \"graphql\";\n\ninterface FireArgs {\n workflowId: string;\n payload?: unknown;\n}\n\ninterface RunsArgs {\n workflowId?: string;\n driveId?: string;\n limit?: number;\n}\n\n// A secret belongs to the reactor, not to any one document, so writing one is\n// an administrator's call — the gate the package mutations already use.\nfunction requireAdmin(\n authorizationService: IAuthorizationService,\n ctx: Context,\n): void {\n if (!authorizationService.isSupremeAdmin(ctx.user?.address)) {\n throw new GraphQLError(\"Admin access required\");\n }\n}\n\nfunction parseJson(value: string | null): unknown {\n if (value === null) return null;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nfunction toStepRecord(row: StepExecutionRow) {\n return {\n stepId: row.step_id,\n stepKey: row.step_key,\n blockType: row.block_type,\n status: row.status,\n input: parseJson(row.input),\n output: parseJson(row.output),\n port: row.port,\n error: row.error,\n };\n}\n\nfunction toRunRecord(row: RunRow, steps: StepExecutionRow[]) {\n return {\n id: row.id,\n workflowId: row.workflow_id,\n workflowName: row.workflow_name,\n workflowVersion: row.workflow_version,\n triggerKind: row.trigger_kind,\n triggerPayload: parseJson(row.trigger_payload),\n status: row.status,\n error: row.error,\n startedAt: row.started_at,\n endedAt: row.ended_at,\n rerunOf: row.rerun_of,\n steps: steps.map(toStepRecord),\n };\n}\n\nexport const getResolvers = (\n runtime: WorkflowRuntimeService,\n authorizationService: IAuthorizationService,\n): Record<string, unknown> => {\n return {\n Query: {\n workflowRuntime: () => ({}),\n },\n WorkflowRuntimeQueries: {\n health: () => \"ok\",\n blockDescriptor: (_parent: unknown, args: { blockType: string }) =>\n runtime.blockDescriptor(args.blockType),\n blockOptions: (\n _parent: unknown,\n args: {\n blockType: string;\n propName: string;\n input?: unknown;\n connectionId?: string | null;\n },\n ctx: Context,\n ) =>\n runtime.blockOptions(\n args.blockType,\n args.propName,\n args.input,\n args.connectionId ?? undefined,\n ctx,\n ),\n pieceCatalog: () => runtime.pieceCatalog(),\n pieceActions: (_parent: unknown, args: { packageName: string }) =>\n runtime.pieceActions(args.packageName),\n pieceTriggers: (_parent: unknown, args: { packageName: string }) =>\n runtime.pieceTriggers(args.packageName),\n blockOutputTree: (\n _parent: unknown,\n args: { blockType: string; config?: unknown },\n ) => runtime.blockOutputTree(args.blockType, args.config),\n pieceDetail: (_parent: unknown, args: { packageName: string }) =>\n runtime.pieceDetail(args.packageName),\n searchBlocks: (\n _parent: unknown,\n args: { query: string; limit?: number | null },\n ) => runtime.searchBlocks(args.query, args.limit ?? undefined),\n connections: (_parent: unknown, _args: unknown, ctx: Context) =>\n runtime.connections(ctx),\n webhookEndpoint: (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => runtime.webhookEndpoint(args.workflowId, ctx),\n secret: async (_parent: unknown, args: { ref: string }) => {\n try {\n return await (await runtime.secrets()).stat(args.ref);\n } catch {\n // Unknown or malformed ref reads as \"no such secret\".\n return null;\n }\n },\n secrets: async () => (await runtime.secrets()).list(),\n triggerStates: async (_parent: unknown, _args: unknown, ctx: Context) =>\n (await runtime.triggerStates(ctx)).map((row) => ({\n workflowId: row.workflow_id,\n blockType: row.block_type,\n status: row.status,\n intervalMs: row.interval_ms,\n nextPollAt: row.next_poll_at,\n lastPollAt: row.last_poll_at,\n lastError: row.last_error,\n consecutiveFailures: row.consecutive_failures,\n })),\n runs: async (_parent: unknown, args: RunsArgs, ctx: Context) =>\n (await runtime.runs(args, ctx)).map((record) =>\n toRunRecord(record.row, record.steps),\n ),\n run: async (_parent: unknown, args: { id: string }, ctx: Context) => {\n const record = await runtime.run(args.id, ctx);\n return record ? toRunRecord(record.row, record.steps) : null;\n },\n },\n Mutation: {\n workflowRuntime: () => ({}),\n },\n WorkflowRuntimeMutations: {\n fire: (_parent: unknown, args: FireArgs, ctx: Context) =>\n runtime.fire(args.workflowId, args.payload, \"manual\", undefined, ctx),\n testTrigger: (\n _parent: unknown,\n args: { workflowId: string },\n ctx: Context,\n ) => runtime.testTrigger(args.workflowId, ctx),\n rerun: (_parent: unknown, args: { runId: string }, ctx: Context) =>\n runtime.rerun(args.runId, ctx),\n createSecret: async (\n _parent: unknown,\n args: { value: string; label?: string | null },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n return (await runtime.secrets()).create({\n value: args.value,\n label: args.label ?? undefined,\n });\n },\n rotateSecret: async (\n _parent: unknown,\n args: { ref: string; value: string },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n return (await runtime.secrets()).rotate(args.ref, args.value);\n },\n deleteSecret: async (\n _parent: unknown,\n args: { ref: string },\n ctx: Context,\n ) => {\n requireAdmin(authorizationService, ctx);\n await (await runtime.secrets()).delete(args.ref);\n return true;\n },\n checkConnection: (\n _parent: unknown,\n args: { connectionId: string },\n ctx: Context,\n ) => runtime.checkConnection(args.connectionId, ctx),\n },\n };\n};\n","import type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nexport const schema: DocumentNode = gql`\n \"\"\"\n WorkflowRuntime Queries\n \"\"\"\n type WorkflowRuntimeQueries {\n health: String!\n \"\"\"\n Persisted runs, newest first. Scope them to one workflow, or to every\n workflow a drive holds; workflowId wins when both are given.\n \"\"\"\n runs(workflowId: String, driveId: String, limit: Int): [WorkflowRunRecord!]!\n run(id: String!): WorkflowRunRecord\n \"\"\"\n Action descriptor (props, auth) for a piece block type; null for core blocks.\n \"\"\"\n blockDescriptor(blockType: String!): Unknown\n \"\"\"\n Resolves a dynamic prop against the current config values: a DROPDOWN\n yields { options, placeholder, disabled }, a DYNAMIC prop yields the\n resolved sub-property descriptor list.\n \"\"\"\n blockOptions(\n blockType: String!\n propName: String!\n input: Unknown\n connectionId: String\n ): Unknown\n \"\"\"\n All published Activepieces pieces with at least one action.\n \"\"\"\n pieceCatalog: Unknown\n \"\"\"\n A piece's actions, each with a ready-to-use blockType.\n \"\"\"\n pieceActions(packageName: String!): Unknown\n \"\"\"\n A piece's triggers, each with a ready-to-use \"#trigger:\" blockType.\n \"\"\"\n pieceTriggers(packageName: String!): Unknown\n \"\"\"\n Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.\n \"\"\"\n pieceDetail(packageName: String!): Unknown\n \"\"\"\n Action/trigger name search across the catalog. The index builds lazily on\n first use; poll while status is \"indexing\".\n \"\"\"\n searchBlocks(query: String!, limit: Int): BlockSearchResult!\n \"\"\"\n Health of every registered piece trigger (poll schedule, errors).\n \"\"\"\n triggerStates: [TriggerStateRecord!]!\n \"\"\"\n Authored output shape of a block (SDL / outputSchema / sampleData).\n \"\"\"\n blockOutputTree(blockType: String!, config: Unknown): Unknown\n \"\"\"\n Every powerhouse/connection document, for connection pickers.\n \"\"\"\n connections: [ConnectionRecord!]!\n \"\"\"\n The webhook endpoint for a workflow: the URL to hand the provider. Minted\n on first ask, whether or not the workflow is armed — an author needs the\n URL before enabling, and the armed field carries that difference. Null\n only when the host has no webhook service.\n \"\"\"\n webhookEndpoint(workflowId: String!): WebhookEndpointRecord\n \"\"\"\n Secret metadata (label, version, status). Never the value.\n \"\"\"\n secret(ref: String!): SecretRecord\n secrets: [SecretRecord!]!\n }\n\n type BlockSearchHit {\n blockType: String!\n pieceName: String!\n pieceDisplayName: String!\n logoUrl: String!\n displayName: String!\n description: String!\n \"action | trigger\"\n kind: String!\n \"Triggers only: POLLING | WEBHOOK | APP_WEBHOOK\"\n strategy: String\n }\n\n type BlockSearchResult {\n \"ready | indexing | error\"\n status: String!\n hits: [BlockSearchHit!]!\n indexedPieces: Int!\n error: String\n }\n\n type SecretRecord {\n ref: String!\n label: String\n version: Int!\n status: String!\n createdAt: String!\n updatedAt: String!\n }\n\n type ConnectionRecord {\n id: String!\n name: String!\n connectorId: String!\n authType: String!\n status: String!\n accountLabel: String\n }\n\n type ConnectionCheckResult {\n ok: Boolean!\n detail: String\n accountLabel: String\n }\n\n type WebhookEndpointRecord {\n workflowId: String!\n url: String!\n \"\"\"\n False when the reactor does not know its own public origin, so the url\n above is a bare path no provider can call: the author supplies the origin.\n \"\"\"\n absoluteUrl: Boolean!\n \"True while the workflow is ENABLED with a valid webhook trigger\"\n armed: Boolean!\n createdAt: String!\n }\n\n type TriggerStateRecord {\n workflowId: String!\n blockType: String!\n status: String!\n intervalMs: Int!\n nextPollAt: String\n lastPollAt: String\n lastError: String\n consecutiveFailures: Int!\n }\n\n type Query {\n workflowRuntime: WorkflowRuntimeQueries!\n }\n\n type WorkflowStepRunRecord {\n stepId: String!\n stepKey: String!\n blockType: String!\n status: String!\n input: Unknown\n output: Unknown\n port: String\n error: String\n }\n\n type WorkflowRunRecord {\n id: String!\n workflowId: String!\n workflowName: String!\n workflowVersion: Int!\n triggerKind: String!\n triggerPayload: Unknown\n status: String!\n error: String\n startedAt: String!\n endedAt: String\n rerunOf: String\n steps: [WorkflowStepRunRecord!]!\n }\n\n type WorkflowStepRun {\n stepId: String!\n key: String!\n blockType: String!\n status: String!\n input: Unknown\n output: Unknown\n port: String\n error: String\n }\n\n type WorkflowRunPayload {\n runId: String\n status: String!\n error: String\n steps: [WorkflowStepRun!]!\n }\n\n \"\"\"\n WorkflowRuntime Mutations\n \"\"\"\n type WorkflowRuntimeMutations {\n \"\"\"\n Fires a workflow's core#manual trigger and runs it to completion.\n \"\"\"\n fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!\n \"\"\"\n Runs a piece trigger's test hook; sample items, no cursor changes.\n \"\"\"\n testTrigger(workflowId: String!): Unknown\n \"\"\"\n Resumes a FAILED run: succeeded steps replay from the journal,\n execution restarts at the failure. Produces a new run.\n \"\"\"\n rerun(runId: String!): WorkflowRunPayload!\n \"\"\"\n Mints a managed secret and returns its ref; the value is stored\n encrypted and is never readable back over any API.\n \"\"\"\n createSecret(value: String!, label: String): SecretRecord!\n \"\"\"\n Replaces the value behind an existing ref; documents stay untouched.\n \"\"\"\n rotateSecret(ref: String!, value: String!): SecretRecord!\n \"\"\"\n Tombstones a secret; its value becomes unrecoverable.\n \"\"\"\n deleteSecret(ref: String!): Boolean!\n \"\"\"\n Runs the piece's app.checkConnection against the connection's\n credentials and records the outcome on the connection document.\n \"\"\"\n checkConnection(connectionId: String!): ConnectionCheckResult!\n }\n\n type Mutation {\n workflowRuntime: WorkflowRuntimeMutations!\n }\n`;\n","import { BaseSubgraph, type SubgraphClass } from \"@powerhousedao/reactor-api\";\nimport type { WorkflowRuntimeService } from \"@powerhousedao/reactor-workflow\";\nimport type { DocumentNode } from \"graphql\";\nimport { getResolvers } from \"./resolvers.js\";\nimport { schema } from \"./schema.js\";\n\n/** The runtime's read/write surface. The runtime itself is composed by the\n * host, so the subgraph only serves what it is handed. */\nexport function createWorkflowRuntimeSubgraph(\n runtime: WorkflowRuntimeService,\n): SubgraphClass {\n return class WorkflowRuntimeSubgraph extends BaseSubgraph {\n name = \"workflow-runtime\";\n typeDefs: DocumentNode = schema;\n // A field initializer runs after super(), so the authorization service\n // the secret mutations gate on is already in place.\n resolvers = getResolvers(runtime, this.authorizationService);\n additionalContextFields = {};\n };\n}\n","// Switchboard composes the workflow runtime from what it holds (the reactor\n// module) and what startAPI hands back. The intake is a read model.\nimport {\n REACTOR_SCHEMA,\n supportsLiveReadModelRegistration,\n type AttachmentHash,\n type AttachmentRef,\n type DocumentViewDatabase,\n type InProcessReactorClientModule,\n type IReactorClient,\n type IRelationalDb,\n} from \"@powerhousedao/reactor\";\nimport {\n AuthorizationPolicy,\n ForbiddenError,\n createCanonicalDocumentIdResolver,\n type AttachmentReferenceProjectionCapability,\n type CanonicalDocumentId,\n type Context,\n type IAuthorizationService,\n type IPackagePieceSource,\n type PackagePieceEntry,\n type SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport {\n createRef,\n parseRef,\n type IAttachmentReferenceReader,\n} from \"@powerhousedao/reactor-attachments\";\nimport type * as WorkflowEngine from \"@powerhousedao/reactor-workflow\";\nimport type {\n AttachmentClientLike,\n WorkflowCaller,\n WorkflowRuntimeHostDeps,\n} from \"@powerhousedao/reactor-workflow\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { IWebhookScope } from \"@powerhousedao/shared/processors\";\nimport type { ILogger } from \"document-model\";\nimport type { Kysely } from \"kysely\";\nimport { createWorkflowRuntimeSubgraph } from \"./workflow/subgraph.js\";\n\ntype WorkflowEngineModule = typeof WorkflowEngine;\n\n/** The npm name the workflow package owns: its HTTP namespace and its models. */\nexport const WORKFLOW_PACKAGE_NAME = \"@powerhousedao/workflow\";\n\n/** The env var and OpenFeature flag key that turns workflows on. */\nexport const PH_WORKFLOWS_ENABLED = \"PH_WORKFLOWS_ENABLED\";\n\n/** Whether the operation intake is indexing. Same shape as the attachment\n * reference projection, because it is the same limitation. */\nexport type WorkflowTriggersCapability =\n | { status: \"available\" }\n | {\n status: \"unavailable\";\n reason:\n | \"in-process-reactor-module-unavailable\"\n | \"live-read-model-registration-unsupported\";\n };\n\n/** The slice of switchboard's OpenFeature client this needs. */\nexport interface BooleanFlagSource {\n getBooleanValue(flagKey: string, defaultValue: boolean): Promise<boolean>;\n}\n\nexport interface WorkflowsFlagInput {\n featureFlags: BooleanFlagSource;\n /** The host's own answer; wins over everything. */\n override?: boolean;\n /** `workflows.enabled` from the powerhouse config file. */\n configEnabled?: boolean;\n /** Defaults to process.env; the tests pass their own. */\n env?: Record<string, string | undefined>;\n}\n\n/** Precedence, unchanged from the reactor-api resolver this replaces: the\n * host's option, then PH_WORKFLOWS_ENABLED, then the config file, then off. */\nexport async function resolveWorkflowsEnabled({\n featureFlags,\n override,\n configEnabled = false,\n env = process.env,\n}: WorkflowsFlagInput): Promise<boolean> {\n if (override !== undefined) return override;\n\n // The env layer is switchboard's OpenFeature client, which casts only\n // \"true\"/\"false\": the numeric forms reactor-api took are answered here.\n const raw = env[PH_WORKFLOWS_ENABLED]?.trim();\n if (raw === \"1\") return true;\n if (raw === \"0\") return false;\n\n return featureFlags.getBooleanValue(PH_WORKFLOWS_ENABLED, configEnabled);\n}\n\n// The package manager reports an unresolvable package and continues; for one\n// the host added itself that is a misconfigured switchboard, not a degraded\n// one. The manager imports this subpath moments later, so the cache absorbs it.\nexport async function assertWorkflowPackageLoadable(\n load: () => Promise<unknown> = () =>\n import(\"@powerhousedao/workflow/document-models\"),\n): Promise<void> {\n try {\n await load();\n } catch (error) {\n throw new Error(\n `Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`,\n { cause: error },\n );\n }\n}\n\nexport interface ComposeWorkflowRuntimeDeps {\n reactorClient: IReactorClient;\n /** The registry this host installs packages from; pieces come from it too.\n * Absent on a host that installs from none, and only the cloud is read. */\n pieceRegistryUrl?: string;\n /** Where the trigger read model registers; absent leaves the intake\n * unavailable rather than quietly dropping every document trigger. */\n clientModule?: InProcessReactorClientModule;\n relationalDb: IRelationalDb;\n attachments: AttachmentClientLike;\n /** The projected document/ref relationships a step's attachment read is\n * checked against; without them, or without the projection, nothing reads. */\n attachmentReferences?: IAttachmentReferenceReader;\n attachmentReferenceProjection?: AttachmentReferenceProjectionCapability;\n webhooks?: IWebhookScope;\n authorizationService: IAuthorizationService;\n /** Where the pieces installed packages ship come from; absent leaves the\n * runtime with none and only published bundles resolvable. */\n pieces?: IPackagePieceSource;\n logger: ILogger;\n /** Overridden by the tests; production always loads the real engine. */\n load?: () => Promise<WorkflowEngineModule>;\n}\n\nexport interface ComposedWorkflowRuntime {\n subgraph: SubgraphClass;\n /** Whether document operations reach the runtime at all. */\n triggers: WorkflowTriggersCapability;\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\n// The engine's own access check, answered as BaseSubgraph answers it: an admin\n// passes, another policy fails closed, an unresolvable identifier is a denial.\nfunction readAssertion(\n authorizationService: IAuthorizationService,\n reactorClient: IReactorClient,\n): WorkflowRuntimeHostDeps[\"assertCanRead\"] {\n const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);\n return async (identifier: string, caller: WorkflowCaller) => {\n const ctx = caller as Context;\n if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;\n if (\n authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n let documentId: CanonicalDocumentId;\n try {\n documentId = await resolveCanonical(identifier);\n } catch {\n throw new ForbiddenError();\n }\n const canRead = await authorizationService.canRead(\n documentId,\n ctx.user?.address,\n );\n if (!canRead) throw new ForbiddenError(\"to read this document\");\n };\n}\n\n/** The same, for a design-time call that writes what it names. */\nfunction writeAssertion(\n authorizationService: IAuthorizationService,\n reactorClient: IReactorClient,\n): WorkflowRuntimeHostDeps[\"assertCanWrite\"] {\n const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);\n return async (identifier: string, caller: WorkflowCaller) => {\n const ctx = caller as Context;\n if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;\n if (\n authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n let documentId: CanonicalDocumentId;\n try {\n documentId = await resolveCanonical(identifier);\n } catch {\n throw new ForbiddenError();\n }\n const canWrite = await authorizationService.canWrite(\n documentId,\n ctx.user?.address,\n );\n if (!canWrite) throw new ForbiddenError(\"to write this document\");\n };\n}\n\n/** Whether the workflow document really references the attachment. A step\n * carries no caller, so the relationship is the whole check. */\nfunction attachmentRefCheck(\n deps: ComposeWorkflowRuntimeDeps,\n): WorkflowRuntimeHostDeps[\"canReadAttachmentRef\"] {\n const resolveCanonical = createCanonicalDocumentIdResolver(\n deps.reactorClient,\n );\n const references = deps.attachmentReferences;\n const projection = deps.attachmentReferenceProjection;\n return async (documentId: string, ref: string) => {\n // An index nobody maintains is evidence of nothing, so it denies rather\n // than waves the read through.\n if (!references || projection?.status !== \"available\") return false;\n let parsed: { version: number; hash: string };\n try {\n parsed = parseRef(ref as AttachmentRef);\n } catch {\n return false;\n }\n if (parsed.version !== 1) return false;\n const canonicalRef = createRef(parsed.hash.toLowerCase() as AttachmentHash);\n try {\n return await references.hasReference(\n await resolveCanonical(documentId),\n canonicalRef,\n );\n } catch {\n return false;\n }\n };\n}\n\n// Live registration is the capability the attachment reference index needs\n// too, so a coordinator without it reads unavailable for the same reason.\nasync function registerWorkflowTriggersReadModel(\n engine: WorkflowEngineModule,\n runtime: WorkflowEngine.WorkflowRuntimeService,\n clientModule: InProcessReactorClientModule | undefined,\n): Promise<WorkflowTriggersCapability> {\n const reactorModule = clientModule?.reactorModule;\n if (!reactorModule) {\n return {\n status: \"unavailable\",\n reason: \"in-process-reactor-module-unavailable\",\n };\n }\n\n const coordinator = reactorModule.readModelCoordinator;\n if (!supportsLiveReadModelRegistration(coordinator)) {\n return {\n status: \"unavailable\",\n reason: \"live-read-model-registration-unsupported\",\n };\n }\n\n // Schema-qualified: the cursor row lives in the reactor's own ViewState.\n const readModel = new engine.WorkflowTriggersReadModel(\n (reactorModule.database as unknown as Kysely<unknown>).withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<DocumentViewDatabase>,\n reactorModule.operationIndex,\n reactorModule.writeCache,\n reactorModule.processorManagerConsistencyTracker,\n runtime,\n );\n await readModel.init();\n coordinator.addReadModel(\n readModel,\n engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE,\n );\n\n return { status: \"available\" };\n}\n\n// The runtime holds pieces; reactor-api is what resolves them. Rebound on\n// every change, so a package rebuilt while this runs needs no restart.\nexport function bindPackagePieces(\n registry: { setPieces(pieces: readonly PackagePieceEntry[]): void },\n source: IPackagePieceSource,\n): void {\n const apply = (byPackage: Map<string, PackagePieceEntry[]>) => {\n registry.setPieces([...byPackage.values()].flat());\n };\n // The initial load already happened inside startAPI, so what it reported is\n // read here rather than waited for.\n apply(source.getPieces());\n source.onPiecesChange(apply);\n}\n\n// Builds the runtime, registers its intake, and returns its GraphQL face plus\n// the lifecycle the host drives. The engine loads lazily: off means unloaded.\nexport async function composeWorkflowRuntime(\n deps: ComposeWorkflowRuntimeDeps,\n): Promise<ComposedWorkflowRuntime> {\n const load = deps.load ?? (() => import(\"@powerhousedao/reactor-workflow\"));\n\n let engine: WorkflowEngineModule;\n try {\n engine = await load();\n } catch (error) {\n throw new Error(\n \"Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded\",\n { cause: error },\n );\n }\n\n // The same registry the host installs packages from, so a piece it indexes\n // is reachable without a second setting to keep in step.\n engine.setPieceRegistryUrl(deps.pieceRegistryUrl);\n\n // Before the runtime exists: a restored trigger asks for a piece as soon as\n // the supervisor starts, and the catalog is served from the same holder.\n if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);\n\n const runtime = engine.createWorkflowRuntime({\n relationalDb: deps.relationalDb,\n reactorClient: deps.reactorClient,\n assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),\n assertCanWrite: writeAssertion(\n deps.authorizationService,\n deps.reactorClient,\n ),\n webhooks: deps.webhooks,\n attachments: deps.attachments,\n canReadAttachmentRef: attachmentRefCheck(deps),\n logger: deps.logger,\n });\n\n const triggers = await registerWorkflowTriggersReadModel(\n engine,\n runtime,\n deps.clientModule,\n );\n if (triggers.status === \"available\") {\n deps.logger.info(\n `Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`,\n );\n } else {\n // Loudly: the runtime still serves GraphQL and still runs webhook and\n // schedule triggers, so nothing else says the document ones are dead.\n deps.logger.error(\n \"Workflow document triggers are NOT armed (@reason): this reactor's \" +\n \"read-model coordinator takes no live registration, so no document \" +\n \"operation reaches the runtime. Webhook and schedule triggers are \" +\n \"unaffected.\",\n triggers.reason,\n );\n }\n\n let stopped = false;\n\n return {\n subgraph: createWorkflowRuntimeSubgraph(runtime),\n triggers,\n\n async start() {\n // The endpoint family first: a restored webhook trigger asks for its URL\n // as soon as the supervisor starts.\n await runtime.registerWebhookEndpoint();\n runtime.startTriggerSupervisor();\n },\n\n stop() {\n if (stopped) return Promise.resolve();\n stopped = true;\n runtime.shutdown();\n return Promise.resolve();\n },\n };\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport type { Driver } from \"kysely\";\nimport { PGliteDialect } from \"kysely-pglite-dialect\";\n\n// kysely-pglite-dialect's driver.destroy() only nulls its reference to the\n// PGlite client — it never calls pglite.close(). Without close(), WAL is not\n// flushed and the data dir is left in a state that aborts the wasm on the\n// next open. This wrapper closes the dialect's PGlite as part of the\n// reactor's database.destroy() chain.\nexport class ClosablePGliteDialect extends PGliteDialect {\n readonly #pglite: PGlite;\n\n constructor(pglite: PGlite) {\n super(pglite);\n this.#pglite = pglite;\n }\n\n createDriver(): Driver {\n const driver = super.createDriver();\n const pglite = this.#pglite;\n const innerDestroy = driver.destroy.bind(driver);\n driver.destroy = async () => {\n await innerDestroy();\n if (!pglite.closed) {\n await pglite.close();\n }\n };\n return driver;\n }\n}\n","import type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n loadPGliteModule,\n loadPgDump,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\n\ntype PGliteCtor = new (\n dataDir: string,\n options?: Record<string, unknown>,\n) => {\n waitReady: Promise<void>;\n exec: (sql: string) => Promise<unknown>;\n close: () => Promise<void>;\n};\n\nfunction backupPath(dataDir: string, major: number): string {\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${dataDir}.backup-pg${major}-${stamp}`;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction logRestoreFailure(\n dataDir: string,\n sql: string,\n err: unknown,\n logger: ILogger,\n): void {\n const errObj = err as {\n message?: string;\n position?: string | number;\n severity?: string;\n code?: string;\n detail?: string;\n where?: string;\n };\n const position =\n typeof errObj.position === \"string\"\n ? parseInt(errObj.position, 10)\n : typeof errObj.position === \"number\"\n ? errObj.position\n : NaN;\n\n logger.error(\n `[pglite-migration] Restore failed for ${dataDir}: code=${errObj.code ?? \"\"} severity=${errObj.severity ?? \"\"} message=${errObj.message ?? \"\"} sqlLength=${sql.length}`,\n );\n\n if (Number.isFinite(position) && position > 0) {\n const zeroBased = position - 1;\n const start = Math.max(0, zeroBased - 200);\n const end = Math.min(sql.length, zeroBased + 200);\n const before = sql.slice(start, zeroBased);\n const at = sql.slice(zeroBased, zeroBased + 1);\n const after = sql.slice(zeroBased + 1, end);\n logger.error(\n `[pglite-migration] SQL context around position ${position}:\\n${before}»${at}«${after}`,\n );\n } else {\n logger.error(\n `[pglite-migration] No position info. First 2000 chars of dump:\\n${sql.slice(0, 2000)}`,\n );\n }\n}\n\n/**\n * Migrate a filesystem PGLite data directory from a legacy PG major to the\n * current one. Renames the existing dir to a timestamped backup, dumps via the\n * matching legacy `pg_dump`, restores into a fresh current-version PGLite at\n * the original path. On failure, the original dir is restored from the backup.\n *\n * No-op when the dir is missing or already at the current major.\n */\nexport async function migratePgliteDir(\n dataDir: string,\n logger: ILogger,\n): Promise<void> {\n const major = await readPgVersionFile(dataDir);\n if (major === null) {\n logger.info(\n `[pglite-migration] No PG_VERSION at ${dataDir}; skipping migration`,\n );\n return;\n }\n if (major === CURRENT_PG_MAJOR) return;\n\n if (!isSupportedMajor(major)) {\n throw new Error(\n `Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${dataDir}`,\n );\n }\n\n const backupDir = backupPath(dataDir, major);\n logger.info(\n `[pglite-migration] Migrating ${dataDir} from PG${major} to PG${CURRENT_PG_MAJOR}; backup: ${backupDir}`,\n );\n\n await fs.rename(dataDir, backupDir);\n\n let sql: string;\n try {\n const [legacyMod, pgDump] = await Promise.all([\n loadPGliteModule(major as SupportedPgMajor),\n loadPgDump(major as SupportedPgMajor),\n ]);\n const LegacyPGlite = (legacyMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n const pg = new LegacyPGlite(backupDir);\n try {\n await pg.waitReady;\n const file = await pgDump({ pg });\n sql = await file.text();\n } finally {\n await pg.close();\n }\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n try {\n const currentMod = await loadPGliteModule(CURRENT_PG_MAJOR);\n const CurrentPGlite = (currentMod as unknown as { PGlite: PGliteCtor })\n .PGlite;\n const pg = new CurrentPGlite(dataDir, { relaxedDurability: false });\n try {\n await pg.waitReady;\n try {\n await pg.exec(\"SET standard_conforming_strings = off;\");\n } catch (gucErr) {\n logger.warn(\n `[pglite-migration] Could not force standard_conforming_strings=off: ${String(gucErr)}`,\n );\n }\n try {\n await pg.exec(sql);\n } catch (execErr) {\n logRestoreFailure(dataDir, sql, execErr, logger);\n throw execErr;\n }\n } finally {\n await pg.close();\n }\n } catch (err) {\n await rollback(dataDir, backupDir, err, logger);\n throw err;\n }\n\n logger.info(\n `[pglite-migration] Migration of ${dataDir} complete. Backup retained at ${backupDir}; remove it manually once you have verified the upgrade.`,\n );\n}\n\nasync function rollback(\n dataDir: string,\n backupDir: string,\n originalError: unknown,\n logger: ILogger,\n): Promise<void> {\n try {\n if (await pathExists(dataDir)) {\n await fs.rm(dataDir, { recursive: true, force: true });\n }\n if (await pathExists(backupDir)) {\n await fs.rename(backupDir, dataDir);\n }\n } catch (rollbackErr) {\n logger.error(\n `[pglite-migration] Migration AND rollback failed for ${dataDir}. Original error: ${String(originalError)}; rollback error: ${String(rollbackErr)}; backup may still exist at ${backupDir}.`,\n );\n return;\n }\n logger.error(\n `[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`,\n );\n}\n","import type { ReactorFeatureFlags } from \"@powerhousedao/reactor\";\n\nexport type ResolvedReactorFeatureFlags = {\n flags: Partial<ReactorFeatureFlags>;\n /** Names of the flags set to true, in prerequisite order. */\n enabled: string[];\n};\n\n/**\n * Enforcement flags from the REACTOR_* env vars. Each flag requires the ones\n * before it; the reactor rejects an inconsistent set rather than enforcing less\n * than the operator asked for, so this reports what was asked without\n * correcting it.\n */\nexport function resolveReactorFeatureFlags(\n env: NodeJS.ProcessEnv,\n): ResolvedReactorFeatureFlags {\n const flags: Partial<ReactorFeatureFlags> = {\n documentDecisions: env.REACTOR_DOCUMENT_DECISIONS === \"true\",\n authEnforcement: env.REACTOR_AUTH_ENFORCEMENT === \"true\",\n authGroups: env.REACTOR_AUTH_GROUPS === \"true\",\n authConditions: env.REACTOR_AUTH_CONDITIONS === \"true\",\n };\n\n const enabled = Object.entries(flags)\n .filter(([, isEnabled]) => isEnabled)\n .map(([name]) => name);\n\n return { flags, enabled };\n}\n","import type { SignerConfig } from \"@powerhousedao/reactor\";\nimport {\n createSignatureVerifier,\n DEFAULT_RENOWN_URL,\n NodeKeyStorage,\n RenownBuilder,\n RenownCryptoBuilder,\n type IRenown,\n} from \"@renown/sdk/node\";\nimport { childLogger } from \"document-model\";\n\nconst logger = childLogger([\"switchboard\", \"renown\"]);\n\nexport interface RenownOptions {\n /** Path to the keypair file. Defaults to .ph/.keypair.json in cwd */\n keypairPath?: string;\n /** If true, won't generate a new keypair if none exists */\n requireExisting?: boolean;\n /** Base url of the Renown instance to use */\n baseUrl?: string;\n}\n\n/**\n * Initialize Renown for the Switchboard instance.\n * This allows Switchboard to authenticate with remote services\n * using the same identity established during `ph login`.\n */\nexport async function initRenown(\n options: RenownOptions = {},\n): Promise<IRenown | null> {\n const {\n keypairPath,\n requireExisting = false,\n baseUrl = DEFAULT_RENOWN_URL,\n } = options;\n\n const keyStorage = new NodeKeyStorage(keypairPath, {\n logger,\n });\n\n // Check if we have an existing keypair\n const existingKeyPair = await keyStorage.loadKeyPair();\n\n if (!existingKeyPair && requireExisting) {\n throw new Error(\n \"No existing keypair found and requireExisting is true. \" +\n 'Run \"ph login\" to create one.',\n );\n }\n\n if (!existingKeyPair) {\n logger.info(\"No existing keypair found. A new one will be generated.\");\n }\n\n const renownCrypto = await new RenownCryptoBuilder()\n .withKeyPairStorage(keyStorage)\n .build();\n\n const renown = await new RenownBuilder(\"switchboard\", {})\n .withCrypto(renownCrypto)\n .withBaseUrl(baseUrl)\n .build();\n\n logger.info(\"Switchboard identity initialized: @did\", renownCrypto.did);\n\n return renown;\n}\n\n/**\n * Get the signer config for the given renown instance.\n *\n * @param renown - The renown instance\n * @param requireSignature - If true, unsigned actions are rejected\n */\nexport function getRenownSignerConfig(\n renown: IRenown,\n requireSignature?: boolean,\n): SignerConfig {\n return {\n signer: renown.signer,\n verifier: createSignatureVerifier(requireSignature),\n };\n}\n","#!/usr/bin/env node\nimport type { PGlite } from \"@electric-sql/pglite\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport { ReactorInstrumentation } from \"@powerhousedao/opentelemetry-instrumentation-reactor\";\nimport { AtomicNodeFs } from \"@powerhousedao/pglite-fs\";\nimport {\n DriveCollectionId,\n EventBus,\n REACTOR_SCHEMA,\n ReactorBuilder,\n ReactorClientBuilder,\n createHybridProjectionCoordinatorFactory,\n instrumentPgPool,\n parseDriveUrl,\n type Database,\n type InProcessReactorClientModule,\n type JwtHandler,\n type PoolInstrumentation,\n} from \"@powerhousedao/reactor\";\nimport {\n HttpPackageLoader,\n ImportPackageLoader,\n PackageManagementService,\n PackagesSubgraph,\n PGLITE_UTC_PARSERS,\n initializeAndStartAPI,\n resolveRenownConfig,\n type ClientInitializerDependencies,\n type CredentialVerifier,\n type IPackageLoader,\n type ResolvedRenownConfig,\n} from \"@powerhousedao/reactor-api\";\nimport { httpsHooksPath } from \"@powerhousedao/reactor-api/https-hooks\";\nimport type { VitePackageLoader } from \"@powerhousedao/reactor-api/vite\";\nimport { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments\";\nimport { createAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\nimport {\n DriveNodeView,\n NodeProcessor,\n ReactorDriveClient,\n createReactorDriveResolvers,\n reactorDriveSubgraphTypeDefs,\n type ReactorDriveDatabase,\n} from \"@powerhousedao/reactor-drive\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n createLocalCredentialVerifier,\n RENOWN_READ_MODEL_SUBGRAPH,\n type CredentialCheck,\n type IRenown,\n} from \"@renown/sdk/node\";\nimport * as Sentry from \"@sentry/node\";\nimport { childLogger, setLogLevel, type ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\nimport { Kysely, PostgresDialect } from \"kysely\";\nimport { promises as fs } from \"node:fs\";\nimport { register } from \"node:module\";\nimport net from \"node:net\";\nimport path from \"path\";\nimport { Pool } from \"pg\";\nimport type { ViteDevServer } from \"vite\";\nimport { registerAttachmentRoutes } from \"./attachments/index.js\";\nimport {\n registerAttachmentReferenceReadModel,\n registerAttachmentReferenceReadModelOnModule,\n} from \"./attachment-reference-read-model.mjs\";\nimport { applySwitchboardReactorDefaults } from \"./builder-defaults.mjs\";\nimport {\n assertProjectionWorkerSupported,\n resolveProjectionWorkerOptions,\n} from \"./projection-worker.mjs\";\nimport {\n buildWorkerDbConfig,\n resolveHostPoolSize,\n resolveWorkerModelSources,\n resolveWorkerPoolOptions,\n} from \"./worker-pool.mjs\";\nimport { initFeatureFlags } from \"./feature-flags.js\";\nimport {\n WORKFLOW_PACKAGE_NAME,\n composeWorkflowRuntime,\n assertWorkflowPackageLoadable,\n resolveWorkflowsEnabled,\n type ComposedWorkflowRuntime,\n} from \"./workflow-runtime.mjs\";\nimport { ClosablePGliteDialect } from \"./pglite-dialect.js\";\nimport { migratePgliteDir } from \"./pglite-migration.js\";\nimport {\n CURRENT_PG_MAJOR,\n isSupportedMajor,\n loadPGliteModule,\n readPgVersionFile,\n type SupportedPgMajor,\n} from \"./pglite-version.js\";\nimport { resolveReactorFeatureFlags } from \"./reactor-feature-flags.mjs\";\nimport { getRenownSignerConfig, initRenown } from \"./renown.js\";\nimport type { StartServerOptions, SwitchboardReactor } from \"./types.js\";\nimport {\n addDefaultDrive,\n addDefaultReactorDrive,\n isPostgresUrl,\n} from \"./utils.mjs\";\n\nconst defaultLogger = childLogger([\"switchboard\"]);\n\nconst LogLevel = (process.env.LOG_LEVEL as ILogger[\"level\"] | \"\") || \"info\";\nsetLogLevel(LogLevel);\n\ndotenv.config();\n\n// Feature flag constants\nconst DOCUMENT_MODEL_SUBGRAPHS_ENABLED = \"DOCUMENT_MODEL_SUBGRAPHS_ENABLED\";\nconst DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT = true;\nconst REQUIRE_SIGNATURES = \"REQUIRE_SIGNATURES\";\nconst REQUIRE_SIGNATURES_DEFAULT = false;\n\nconst DEFAULT_PORT = process.env.PORT ? Number(process.env.PORT) : 4001;\n\n// How many ports forward from the requested one we will try before giving up.\nconst PORT_FALLBACK_ATTEMPTS = 20;\n\n// AtomicNodeFs needs a flush interval to coalesce writes into a single disk write (only used locally)\nconst PGLITE_FLUSH_INTERVAL_MS = (() => {\n const raw = process.env.PGLITE_FLUSH_INTERVAL_MS;\n if (raw === undefined) return 100;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : 100;\n})();\n\n// When set, runs both reactor and read-model PGLite instances purely in-memory.\nconst PGLITE_IN_MEMORY = process.env.PH_PGLITE_IN_MEMORY === \"1\";\n\n/**\n * Attempt to bind a throwaway TCP server to the given port. Resolves true if\n * the port is free, false if the OS reports it in use. Any other error is\n * surfaced so we don't silently mask real issues (permissions, bad host, …).\n */\nexport function isPortAvailable(port: number): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const tester = net.createServer();\n tester.once(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\" || err.code === \"EACCES\") {\n resolve(false);\n } else {\n reject(err);\n }\n });\n tester.once(\"listening\", () => {\n tester.close(() => resolve(true));\n });\n // Bind on the unspecified IPv6 address so we detect collisions with both\n // IPv6 and IPv4 listeners (Node maps `::` to dual-stack on most systems).\n tester.listen({ port, host: \"::\" });\n });\n}\n\n/** The powerhouse.config.json this run reads, defaulting to the cwd copy. */\nfunction resolveConfigPath(configFile: string | undefined): string {\n return configFile ?? path.join(process.cwd(), \"powerhouse.config.json\");\n}\n\n// An unreadable config file means \"not configured\", not a boot failure:\n// workflows are opt-in.\nfunction readConfigWorkflowsEnabled(configPath: string): boolean {\n try {\n return getConfig(configPath).workflows?.enabled ?? false;\n } catch {\n return false;\n }\n}\n\nasync function resolveServerPort(\n requested: number,\n strictPort: boolean,\n logger: ILogger,\n): Promise<number> {\n if (strictPort) return requested;\n for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {\n const candidate = requested + i;\n if (await isPortAvailable(candidate)) {\n if (candidate !== requested) {\n logger.info(\n `Port ${requested} is in use. Falling back to port ${candidate}.`,\n );\n }\n return candidate;\n }\n }\n // Couldn't find a free port in the window; let the caller surface the\n // original EADDRINUSE when the real bind attempts runs.\n return requested;\n}\n\n/**\n * The reactor's storage handle, plus the pool instrumentation when that\n * storage is Postgres. The PGlite branch has no `pg.Pool` at all, so the\n * instrumentation is absent rather than optional-by-convention.\n */\ntype ReactorStorage = {\n kysely: Kysely<Database>;\n poolInstrumentation: PoolInstrumentation | undefined;\n};\n\nasync function createReactorKysely(opts: {\n reactorDbUrl: string | undefined;\n reactorPgliteDir: string | null;\n reactorPgliteMajor: SupportedPgMajor | null;\n inMemory: boolean;\n flushIntervalMs: number;\n /**\n * Resolved lazily: only the Postgres branch has a host pool, and\n * {@link resolveHostPoolSize} throws on a bad REACTOR_DB_POOL_SIZE_HOST.\n * Called eagerly it would fail a PGlite-backed server over a value that\n * path never reads.\n */\n hostPoolSize: () => number;\n logger: ILogger;\n}): Promise<ReactorStorage> {\n const {\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory,\n flushIntervalMs,\n hostPoolSize,\n logger,\n } = opts;\n\n if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {\n const connectionString = reactorDbUrl.includes(\"?\")\n ? reactorDbUrl\n : `${reactorDbUrl}?sslmode=disable`;\n const poolSize = hostPoolSize();\n const pool = new Pool({ connectionString, max: poolSize });\n // Named to match the reactor's own convention for the pools it opens\n // itself (`reactor-worker-N`, `projection-shard-N`).\n const poolInstrumentation = instrumentPgPool(pool, \"reactor-host\");\n logger.info(\n `Using PostgreSQL for reactor storage (host pool max ${poolSize})`,\n );\n return {\n kysely: new Kysely<Database>({ dialect: new PostgresDialect({ pool }) }),\n poolInstrumentation,\n };\n }\n\n if (!reactorPgliteDir || reactorPgliteMajor === null) {\n throw new Error(\"Reactor PGLite directory not resolved\");\n }\n const { PGlite } = await loadPGliteModule(reactorPgliteMajor);\n const pglite = inMemory\n ? new PGlite()\n : new PGlite({\n fs: new AtomicNodeFs(reactorPgliteDir, { logger, flushIntervalMs }),\n });\n logger.info(\n inMemory\n ? `Using in-memory PGlite (PG${reactorPgliteMajor}) for reactor storage [PH_PGLITE_IN_MEMORY=1]`\n : `Using PGlite (PG${reactorPgliteMajor}) for reactor storage at ${reactorPgliteDir}`,\n );\n return {\n kysely: new Kysely<Database>({\n dialect: new ClosablePGliteDialect(pglite),\n }),\n poolInstrumentation: undefined,\n };\n}\n\n/** Derive the remote attachment service config for switchboard's own `/attachments/*` API. */\nexport function deriveAttachmentServiceConfig(\n options: Pick<StartServerOptions, \"attachmentServiceUrl\" | \"https\">,\n serverPort: number,\n renown: IRenown | null,\n): { remoteUrl: string; jwtHandler: JwtHandler | undefined } {\n const protocol = options.https ? \"https\" : \"http\";\n const remoteUrl =\n options.attachmentServiceUrl ??\n process.env.PH_SWITCHBOARD_PUBLIC_URL ??\n `${protocol}://localhost:${serverPort}`;\n const jwtHandler: JwtHandler | undefined = renown\n ? async (url: string) =>\n renown.user\n ? renown.getBearerToken({ expiresIn: 10, aud: url })\n : undefined\n : undefined;\n return { remoteUrl, jwtHandler };\n}\n\nasync function initServer(\n serverPort: number,\n options: StartServerOptions,\n renown: IRenown | null,\n renownConfig: ResolvedRenownConfig,\n) {\n const {\n dev,\n packages = [],\n remoteDrives = [],\n logger = defaultLogger,\n } = options;\n logger.level = LogLevel;\n const dbPath =\n options.dbPath ??\n process.env.DATABASE_URL ??\n process.env.PH_SWITCHBOARD_DATABASE_URL;\n\n // use postgres url for read model storage if available, otherwise use local PGlite path\n const readModelPath = dbPath || \".ph/read-storage\";\n\n const reactorDbUrl =\n options.dbPath ??\n process.env.PH_REACTOR_DATABASE_URL ??\n process.env.PH_SWITCHBOARD_DATABASE_URL;\n // When the caller passes in a reactor, the reactor-side PGLite dir is\n // unused — the caller owns its own storage. Only the read-model dir is\n // still needed by reactor-api itself.\n const reactorPath = reactorDbUrl || \"./.ph/reactor-storage\";\n const reactorPgliteDir = options.reactor\n ? null\n : !reactorDbUrl || !isPostgresUrl(reactorDbUrl)\n ? reactorPath\n : null;\n const readModelPgliteDir =\n !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;\n\n // PGLite version pre-flight: when PH_FORCE_PG_VERSION is set, wipe local\n // data dirs and re-initdb at the chosen version. Otherwise detect on-disk\n // PG_VERSION and either migrate (when --migrate-pglite is set) or warn and\n // fall through to the matching legacy PGLite at runtime.\n const pgliteDirs = [reactorPgliteDir, readModelPgliteDir].filter(\n (d): d is string => d !== null,\n );\n const detectedMajors = new Map<string, number>();\n\n // delete PGLite's lockfile to recover, in case it didn't have time to close\n for (const dir of pgliteDirs) {\n const lockPath = path.join(dir, \"postmaster.pid\");\n try {\n await fs.unlink(lockPath);\n logger.warn(`Removed stale PGLite lockfile ${lockPath}`);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n if (options.forcePgVersion !== undefined && pgliteDirs.length > 0) {\n if (options.migratePglite) {\n logger.warn(\n \"PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.\",\n );\n }\n logger.warn(\n `PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`,\n );\n for (const dir of pgliteDirs) {\n await fs.rm(dir, { recursive: true, force: true });\n logger.info(`Wiped PGLite data dir ${dir}`);\n }\n } else if (options.forcePgVersion === undefined) {\n for (const dir of pgliteDirs) {\n const major = await readPgVersionFile(dir);\n if (major !== null) detectedMajors.set(dir, major);\n }\n\n if (options.migratePglite) {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n await migratePgliteDir(dir, logger);\n // refresh detected major after a successful migration\n const after = await readPgVersionFile(dir);\n if (after !== null) detectedMajors.set(dir, after);\n }\n } else {\n for (const [dir, major] of detectedMajors) {\n if (major === CURRENT_PG_MAJOR) continue;\n logger.warn(\n `PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG${CURRENT_PG_MAJOR}. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`,\n );\n }\n }\n }\n\n function resolvePgliteMajorForDir(dir: string): SupportedPgMajor {\n if (options.forcePgVersion !== undefined) return options.forcePgVersion;\n const detected = detectedMajors.get(dir);\n if (detected === undefined) return CURRENT_PG_MAJOR;\n if (!isSupportedMajor(detected)) {\n throw new Error(\n `Unsupported PGLite data dir at ${dir}: PG_VERSION=${detected}`,\n );\n }\n return detected;\n }\n\n const reactorPgliteMajor = reactorPgliteDir\n ? resolvePgliteMajorForDir(reactorPgliteDir)\n : null;\n const readModelPgliteMajor = readModelPgliteDir\n ? resolvePgliteMajorForDir(readModelPgliteDir)\n : null;\n\n let workerPool = resolveWorkerPoolOptions(options.workerPool, process.env);\n if (workerPool && options.reactor) {\n logger.warn(\n \"Worker pool configuration ignored: the caller-provided reactor owns its own executor\",\n );\n workerPool = null;\n }\n if (workerPool) {\n if (dev) {\n throw new Error(\n \"The executor worker pool (REACTOR_WORKERS) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n if (!reactorDbUrl || !isPostgresUrl(reactorDbUrl)) {\n throw new Error(\n \"The executor worker pool (REACTOR_WORKERS) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n }\n\n let projectionWorker = resolveProjectionWorkerOptions(\n options.projectionWorker,\n process.env,\n );\n if (projectionWorker && options.reactor) {\n logger.warn(\n \"Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator\",\n );\n projectionWorker = null;\n }\n if (projectionWorker) {\n assertProjectionWorkerSupported({ dev: dev === true, reactorDbUrl });\n }\n\n // The reactor-api owns its own PGlite/HTTP/WS resources but has no shutdown\n // path of its own; we register `api.dispose` as a reactor shutdown hook so\n // those resources drain inside the reactor's SIGINT chain. The reference\n // is forward — `initializeClient` runs (and registers the hook) before\n // `initializeAndStartAPI` returns the api — so the closure reads `apiRef`\n // at hook-fire time, not at registration time.\n const apiRef: { current: { dispose: () => Promise<void> } | undefined } = {\n current: undefined,\n };\n let driveNodeView: DriveNodeView | undefined;\n\n // HTTP registry package loading\n const configPath = resolveConfigPath(options.configFile);\n const config = getConfig(configPath);\n const registryUrl =\n options.registryUrl ??\n process.env.PH_REGISTRY_URL ??\n config.packageRegistryUrl;\n const registryPackages = process.env.PH_REGISTRY_PACKAGES;\n const dynamicModelLoading =\n options.dynamicModelLoading ?? process.env.DYNAMIC_MODEL_LOADING === \"true\";\n let httpLoader: HttpPackageLoader | undefined;\n\n if (registryUrl) {\n // Register HTTP/HTTPS module loader hooks for dynamic package imports\n register(httpsHooksPath, import.meta.url);\n httpLoader = new HttpPackageLoader({ registryUrl });\n registryPackages?.split(\",\").forEach((p) => {\n const name = p.trim();\n if (!packages.includes(name)) {\n packages.push(name);\n }\n });\n }\n\n const reactorLogger = logger.child([\"reactor\"]);\n // Latched: dropWriteReady reports the fatal once per dropped job.\n let projectionWorkerFatalFired = false;\n const onProjectionWorkerFatal = (shardId: string, reason: Error) => {\n if (projectionWorkerFatalFired) {\n return;\n }\n projectionWorkerFatalFired = true;\n reactorLogger.error(\n `Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`,\n reason,\n );\n // SIGTERM takes the builder's withSignalHandlers() path: kill, hooks, db.\n process.kill(process.pid, \"SIGTERM\");\n };\n // Resolved in startSwitchboard, which owns the flag mechanism; initServer\n // only reads the answer.\n const workflowsEnabled = options.workflows?.enabled === true;\n\n // Through the package manager like any other, so one route carries the\n // models, the subgraphs and the piece.\n if (workflowsEnabled) {\n await assertWorkflowPackageLoadable();\n if (!packages.includes(WORKFLOW_PACKAGE_NAME)) {\n packages.push(WORKFLOW_PACKAGE_NAME);\n }\n }\n\n // Set only when we build the reactor ourselves; a caller-provided one keeps\n // its own lifecycle and must not be torn down here.\n let ownedReactorModule: InProcessReactorClientModule | undefined;\n const initializeClient = async (\n documentModels: DocumentModelModule[],\n {\n attachmentReferenceWriter,\n upgradeManifests,\n }: ClientInitializerDependencies,\n ) => {\n // When the caller hands us a pre-built reactor module, reuse it\n // instead of constructing one. The caller owns the reactor lifecycle\n // and must call `switchboard.shutdown()` from their own teardown to\n // drain /graphql, MCP, attachments, etc.\n if (options.reactor) {\n const attachmentReferenceProjection =\n await registerAttachmentReferenceReadModelOnModule(\n options.reactor,\n attachmentReferenceWriter,\n );\n if (options.reactor.reactorModule) {\n const instrumentation = new ReactorInstrumentation(\n options.reactor.reactorModule,\n );\n instrumentation.start();\n reactorLogger.info(\n \"Reactor metrics instrumentation started (using caller-provided reactor)\",\n );\n }\n return {\n module: options.reactor,\n attachmentReferenceProjection,\n };\n }\n\n const { kysely: baseKysely, poolInstrumentation } =\n await createReactorKysely({\n reactorDbUrl,\n reactorPgliteDir,\n reactorPgliteMajor,\n inMemory: PGLITE_IN_MEMORY,\n flushIntervalMs: PGLITE_FLUSH_INTERVAL_MS,\n hostPoolSize: () => resolveHostPoolSize(process.env),\n logger,\n });\n\n const maxSkipThreshold = parseInt(process.env.MAX_SKIP_THRESHOLD ?? \"\", 10);\n const hasSkipThreshold = !isNaN(maxSkipThreshold) && maxSkipThreshold > 0;\n if (hasSkipThreshold) {\n logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);\n }\n\n // Flip these per document-sharing fleet, never per node: replay decisions\n // are consensus outcomes, so nodes that disagree on the flags diverge.\n const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } =\n resolveReactorFeatureFlags(process.env);\n if (enabledFeatureFlags.length > 0) {\n logger.info(\n `Reactor feature flags enabled: ${enabledFeatureFlags.join(\", \")}`,\n );\n }\n\n const reactorBuilder = new ReactorBuilder()\n .withEventBus(new EventBus())\n .withKysely(baseKysely)\n .withFeatures({\n legacyProcessorIds:\n process.env.REACTOR_LEGACY_PROCESSOR_IDS !== \"false\",\n });\n\n // Feeds `module.pools`, which ReactorInstrumentation reads to emit\n // reactor.db.pool.{acquire.wait_duration,size,idle,waiting}. Without this\n // the host pool is the one pool the reactor opens that nobody can see.\n // Note the gauges observe pg-pool only: behind a transaction-mode\n // pgbouncer, `waiting` can read 0 while requests queue in the pooler.\n if (poolInstrumentation) {\n reactorBuilder.withInstrumentedPool(poolInstrumentation);\n }\n\n const clientBuilder = new ReactorClientBuilder().withReactorBuilder(\n reactorBuilder,\n );\n\n // Subpath import keeps vetra's React editors out of the node bundle.\n const vetraDocumentModels: DocumentModelModule[] = dev\n ? (\n Object.values(\n await import(\"@powerhousedao/vetra/document-models\"),\n ) as unknown[]\n ).filter(\n (m): m is DocumentModelModule =>\n typeof m === \"object\" &&\n m !== null &&\n \"documentModel\" in m &&\n \"reducer\" in m,\n )\n : [];\n\n applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {\n documentModels: [...documentModels, ...vetraDocumentModels],\n upgradeManifests,\n executorConfig:\n hasSkipThreshold || enabledFeatureFlags.length > 0\n ? {\n ...(hasSkipThreshold ? { maxSkipThreshold } : {}),\n ...(enabledFeatureFlags.length > 0\n ? { featureFlags: reactorFeatureFlags }\n : {}),\n }\n : undefined,\n documentModelLoader:\n httpLoader && dynamicModelLoading\n ? httpLoader.documentModelLoader\n : undefined,\n logger: reactorLogger,\n signer: renown\n ? getRenownSignerConfig(renown, options.identity?.requireSignatures)\n : undefined,\n });\n\n if (workerPool) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: worker pool enabled without a reactor database URL\",\n );\n }\n // File sources give workers importable paths for the same models the\n // live modules above registered; the builder dedupes and fails the\n // boot if any model lacks an importable source.\n const workerSources = await resolveWorkerModelSources(\n packages,\n reactorLogger,\n );\n reactorBuilder.withDocumentModelSources(workerSources).withWorkerPool({\n numWorkers: workerPool.numWorkers,\n db: buildWorkerDbConfig(reactorDbUrl, workerPool),\n });\n reactorLogger.info(\n `Executor worker pool enabled: ${workerPool.numWorkers} worker threads${\n workerPool.mode === \"auto\" ? \" (auto-sized from cores)\" : \"\"\n }`,\n );\n }\n\n reactorBuilder.withReadModelFactory(\n async ({\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n }) => {\n const nodeProcessor = new NodeProcessor(\n baseKysely as unknown as Kysely<unknown>,\n REACTOR_SCHEMA,\n operationIndex,\n writeCache,\n processorManagerConsistencyTracker,\n );\n await nodeProcessor.init();\n return nodeProcessor;\n },\n );\n\n registerAttachmentReferenceReadModel(reactorBuilder, {\n baseKysely: baseKysely as unknown as Kysely<unknown>,\n attachmentReferenceWriter,\n });\n\n if (projectionWorker) {\n if (!reactorDbUrl) {\n throw new Error(\n \"unreachable: projection worker enabled without a reactor database URL\",\n );\n }\n // The projection worker rebuilds its registry from the same manifest.\n if (!workerPool) {\n const workerSources = await resolveWorkerModelSources(\n packages,\n reactorLogger,\n );\n reactorBuilder.withDocumentModelSources(workerSources);\n }\n const db = {\n ...buildWorkerDbConfig(reactorDbUrl, {\n dbPoolSizePerWorker: projectionWorker.dbPoolSize,\n acquireTimeoutMs: workerPool?.acquireTimeoutMs ?? 5000,\n }),\n applicationName: \"switchboard-projection\",\n };\n reactorBuilder.withReadModelCoordinatorFactory(\n createHybridProjectionCoordinatorFactory({\n shardCount: 1,\n poolSize: projectionWorker.dbPoolSize,\n db,\n onFatal: onProjectionWorkerFatal,\n }),\n );\n reactorLogger.info(\n `Projection worker enabled: 1 worker thread, pool size ${projectionWorker.dbPoolSize}`,\n );\n }\n\n reactorBuilder.withShutdownHook(async () => {\n if (apiRef.current) await apiRef.current.dispose();\n });\n\n const module = await clientBuilder.buildModule();\n\n if (module.reactorModule) {\n const instrumentation = new ReactorInstrumentation(module.reactorModule);\n instrumentation.start();\n reactorLogger.info(\"Reactor metrics instrumentation started\");\n }\n\n const reactorDriveSchemaDb = baseKysely.withSchema(\n REACTOR_SCHEMA,\n ) as unknown as Kysely<ReactorDriveDatabase>;\n driveNodeView = new DriveNodeView(reactorDriveSchemaDb);\n const reactorDriveClient = new ReactorDriveClient({\n reactor: module.client,\n readModel: driveNodeView,\n });\n\n ownedReactorModule = module;\n\n return {\n module,\n reactorDriveClient,\n attachmentReferenceProjection: { status: \"available\" as const },\n };\n };\n\n // Tear down a partially booted stack in the reactor's own order: reactor\n // first, then the api's HTTP/WS/db handles, then the database pool.\n const abortBoot = async (api: { dispose: () => Promise<void> }) => {\n const owned = ownedReactorModule;\n if (owned) {\n try {\n await owned.reactor.kill().completed;\n } catch (error) {\n logger.error(\"Aborting boot: reactor shutdown failed: @error\", error);\n }\n }\n try {\n await api.dispose();\n } catch (error) {\n logger.error(\"Aborting boot: api dispose failed: @error\", error);\n }\n if (owned?.reactorModule) {\n try {\n await owned.reactorModule.database.destroy();\n } catch (error) {\n logger.error(\"Aborting boot: database destroy failed: @error\", error);\n }\n }\n };\n\n // Reading credentials from this switchboard's own reactor needs the GraphQL\n // manager, which only exists once the api is up: bind the check afterwards.\n let localCredentialCheck: CredentialCheck | undefined;\n const verifyCredential: CredentialVerifier | undefined =\n renownConfig.source === \"self\"\n ? (params) =>\n localCredentialCheck\n ? localCredentialCheck(params)\n : Promise.reject(\n new Error(\"The local renown read model is not bound yet\"),\n )\n : undefined;\n\n let defaultDriveUrl: undefined | string = undefined;\n\n // TODO get path from powerhouse config\n const basePath = process.cwd();\n\n // import Vite loader only if dev mode is enabled\n let vite: ViteDevServer | undefined;\n let viteLoader: VitePackageLoader | undefined;\n if (dev) {\n const { VitePackageLoader, createViteLogger, startViteServer } =\n await import(\"@powerhousedao/reactor-api/vite\");\n vite = await startViteServer(process.cwd(), createViteLogger(logger));\n viteLoader = VitePackageLoader.build(vite);\n }\n\n // Vetra is builder-only and bundled (not CDN-loadable); lazy-load its\n // processor only in dev, where builder tooling runs (e.g. `ph vetra`).\n const vetraProcessorFactory = dev\n ? (await import(\"@powerhousedao/vetra/processors\")).processorFactory\n : undefined;\n\n // get paths to local document models\n if (!options.disableLocalPackages) {\n packages.push(basePath);\n }\n\n // create loaders\n const packageLoaders: IPackageLoader[] = [];\n if (viteLoader) {\n packageLoaders.push(viteLoader);\n } else {\n packageLoaders.push(new ImportPackageLoader());\n }\n if (httpLoader) {\n packageLoaders.push(httpLoader);\n registryPackages?.split(\",\").forEach((p) => {\n const name = p.trim();\n if (!packages.includes(name)) {\n packages.push(name);\n }\n });\n }\n\n const apiLogger = logger.child([\"reactor-api\"]);\n // When the read-model store is on disk, hand reactor-api a factory that\n // constructs the matching PGLite (current or legacy) for the detected\n // PG_VERSION. reactor-api calls the factory synchronously, so the legacy\n // module is preloaded above.\n let pgliteFactory:\n | ((connectionString: string | undefined) => PGlite)\n | undefined;\n if (readModelPgliteDir && readModelPgliteMajor !== null) {\n const { PGlite: ReadModelPGlite } =\n await loadPGliteModule(readModelPgliteMajor);\n pgliteFactory = PGLITE_IN_MEMORY\n ? () => new ReadModelPGlite({ parsers: PGLITE_UTC_PARSERS })\n : (connectionString) =>\n new ReadModelPGlite({\n fs: new AtomicNodeFs(\n connectionString ?? (readModelPgliteDir as string),\n { logger, flushIntervalMs: PGLITE_FLUSH_INTERVAL_MS },\n ),\n parsers: PGLITE_UTC_PARSERS,\n });\n }\n\n const api = await initializeAndStartAPI(\n initializeClient,\n {\n port: serverPort,\n dbPath: readModelPath,\n pgliteFactory,\n https: options.https,\n packageLoaders: packageLoaders.length > 0 ? packageLoaders : undefined,\n packages: packages,\n processorConfig: options.processorConfig,\n processors: vetraProcessorFactory\n ? { \"@powerhousedao/vetra\": [vetraProcessorFactory] }\n : {},\n configFile: configPath,\n mcp: options.mcp ?? true,\n logger: apiLogger,\n enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,\n // Already resolved for this reactor's own identity; reuse it so an\n // invalid RENOWN_SOURCE is reported once, not once per resolution.\n renown: renownConfig,\n verifyCredential,\n },\n \"switchboard\",\n );\n apiRef.current = api;\n\n if (renownConfig.source === \"self\") {\n const { graphqlManager: manager } = api;\n // Refuse to serve rather than 401 every request: the read model comes from\n // a loaded package, so a missing one is a deployment mistake.\n if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {\n await abortBoot(api);\n throw new Error(\n 'Renown credential verification is set to \"self\" (auth.renown.source ' +\n `or RENOWN_SOURCE) but no loaded package serves the ` +\n `\"${RENOWN_READ_MODEL_SUBGRAPH}\" subgraph. Install one ` +\n \"(@powerhousedao/renown-package) or set RENOWN_SOURCE=remote.\",\n );\n }\n localCredentialCheck = createLocalCredentialVerifier(\n (query, variables) =>\n manager.executeSubgraphQuery(\n RENOWN_READ_MODEL_SUBGRAPH,\n query,\n variables,\n ),\n {\n onError: (error) =>\n logger.error(\"Renown read model query failed: @error\", error),\n },\n );\n logger.info(\n \"Renown credentials will be verified against this switchboard's own \" +\n \"renown read model\",\n );\n }\n\n registerAttachmentRoutes(api);\n\n const attachmentService = createRemoteAttachmentService(\n deriveAttachmentServiceConfig(options, serverPort, renown),\n );\n\n if (process.env.SENTRY_DSN) {\n // Register Sentry error handler after all routes are established.\n // The adapter calls the framework-specific Sentry setup internally.\n api.httpAdapter.setupSentryErrorHandler(Sentry);\n }\n\n const { client, graphqlManager, documentModelRegistry } = api;\n\n const lateSubgraphs: Promise<unknown>[] = [];\n\n // The workflow runtime is a switchboard component: composed from what the\n // api handed back, registered like any other late subgraph.\n let workflows: ComposedWorkflowRuntime | undefined;\n if (workflowsEnabled) {\n workflows = await composeWorkflowRuntime({\n reactorClient: client,\n clientModule: options.reactor ?? ownedReactorModule,\n relationalDb: api.relationalDb,\n attachments: createAttachmentClient(api.attachments.service),\n // A step reads attachments with no caller behind it, so the projected\n // document/ref relationship is what authorizes the read.\n attachmentReferences: api.attachmentReferenceIndex.store,\n attachmentReferenceProjection: api.attachmentReferenceProjection,\n // The workflow package's own HTTP namespace: its webhook endpoints live\n // under it, not under the reactor's.\n webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,\n authorizationService: api.authorizationService,\n // The manager that already loads this reactor's packages: the project it\n // runs in is one of them, so its own pieces arrive with the rest.\n pieces: api.packageManager,\n pieceRegistryUrl: registryUrl,\n logger: logger.child([\"workflow-runtime\"]),\n });\n\n const WorkflowRuntimeSubgraph = workflows.subgraph;\n const workflowSubgraph = new WorkflowRuntimeSubgraph({\n reactorClient: client,\n http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),\n relationalDb: api.relationalDb,\n analyticsStore: undefined as never,\n graphqlManager,\n syncManager: api.syncManager,\n authorizationService: graphqlManager.getAuthorizationService(),\n path: graphqlManager.getBasePath(),\n });\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(workflowSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n logger.error(\n \"Failed to register workflow-runtime subgraph: @error\",\n error,\n );\n }),\n );\n\n await workflows.start();\n logger.info(\"Workflow runtime started\");\n }\n\n // Ahead of the api: the runtime's store lives in the read-model database\n // that dispose closes, and its children outlive the reactor otherwise.\n const shutdown = async () => {\n await workflows?.stop();\n await api.dispose();\n };\n apiRef.current = { dispose: shutdown };\n\n // Wire up dynamic package management if HTTP loader is configured\n if (httpLoader) {\n const packageManagementService = new PackageManagementService({\n defaultRegistryUrl: registryUrl,\n httpLoader,\n documentModelRegistry,\n packageManager: api.packageManager,\n });\n\n packageManagementService.setOnModelsChanged(() => {\n graphqlManager\n .regenerateDocumentModelSubgraphs()\n .catch((error: unknown) => {\n logger.error(\n \"Failed to regenerate document model subgraphs: @error\",\n error,\n );\n });\n });\n\n const packagesSubgraph = new PackagesSubgraph({\n relationalDb: undefined as never,\n analyticsStore: undefined as never,\n reactorClient: client,\n graphqlManager,\n syncManager: api.syncManager,\n path: graphqlManager.getBasePath(),\n authorizationService: graphqlManager.getAuthorizationService(),\n packageManagementService,\n http: graphqlManager.scopeForPackage(\"@powerhousedao/switchboard\"),\n });\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(packagesSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n logger.error(\"Failed to register packages subgraph: @error\", error);\n }),\n );\n }\n\n if (driveNodeView) {\n graphqlManager.setAdditionalContextFields({\n readModel: driveNodeView,\n });\n\n const reactorDriveSubgraph = {\n name: \"reactor-drive\",\n path: graphqlManager.getBasePath(),\n resolvers: createReactorDriveResolvers(),\n typeDefs: reactorDriveSubgraphTypeDefs,\n reactorClient: client,\n relationalDb: undefined as never,\n };\n\n lateSubgraphs.push(\n graphqlManager\n .registerSubgraphInstance(reactorDriveSubgraph, \"graphql\", false)\n .catch((error: unknown) => {\n logger.error(\n \"Failed to register reactor-drive subgraph: @error\",\n error,\n );\n }),\n );\n }\n\n void (async () => {\n await Promise.all(lateSubgraphs);\n try {\n await graphqlManager.updateRouter(true);\n } catch (error) {\n logger.error(\n \"Final router update before readiness failed: @error\",\n error,\n );\n }\n api.readiness.markReady();\n })();\n\n // Create default drive if provided\n if (options.drive) {\n if (!renown) {\n throw new Error(\"Cannot create default drive without Renown identity\");\n }\n\n const driveType = options.drive.documentType ?? \"powerhouse/document-drive\";\n if (driveType === \"powerhouse/reactor-drive\") {\n defaultDriveUrl = await addDefaultReactorDrive(\n client,\n options.drive,\n serverPort,\n );\n } else {\n defaultDriveUrl = await addDefaultDrive(\n client,\n options.drive,\n serverPort,\n );\n }\n }\n\n // add vite middleware after express app is initialized if applicable\n if (vite) {\n api.httpAdapter.mountRawMiddleware(vite.middlewares);\n }\n\n // Connect to remote drives AFTER packages are loaded\n if (remoteDrives.length > 0) {\n for (const remoteDriveUrl of remoteDrives) {\n let driveId: string | undefined;\n\n try {\n const { syncManager } = api;\n const parsed = parseDriveUrl(remoteDriveUrl);\n driveId = parsed.driveId;\n const remoteName = `remote-drive-${driveId}-${crypto.randomUUID()}`;\n await syncManager.add(remoteName, DriveCollectionId.forDrive(driveId), {\n type: \"gql\",\n parameters: { url: parsed.graphqlEndpoint },\n });\n logger.debug(\"Remote drive @remoteDriveUrl synced\", remoteDriveUrl);\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"already exists\")\n ) {\n logger.debug(\n \"Remote drive already added: @remoteDriveUrl\",\n remoteDriveUrl,\n );\n driveId = remoteDriveUrl.split(\"/\").pop();\n } else {\n logger.error(\n \"Failed to connect to remote drive @remoteDriveUrl: @error\",\n remoteDriveUrl,\n error,\n );\n }\n } finally {\n // Construct local URL once in finally block\n if (!defaultDriveUrl && driveId) {\n const protocol = options.https ? \"https\" : \"http\";\n defaultDriveUrl = `${protocol}://localhost:${serverPort}/d/${driveId}`;\n }\n }\n }\n }\n\n return {\n defaultDriveUrl,\n api,\n reactor: client,\n attachmentService,\n attachmentReferenceProjection: api.attachmentReferenceProjection,\n workflowTriggers: workflows?.triggers,\n renown,\n port: serverPort,\n shutdown,\n };\n}\n\n/**\n * Boot the switchboard HTTP/GraphQL/MCP stack on top of a reactor.\n *\n * If `options.reactor` is provided, the switchboard reuses it instead of\n * building its own — the caller then owns the reactor's lifecycle and is\n * responsible for invoking `SwitchboardReactor.shutdown()` from their own\n * teardown / SIGINT path. The switchboard will not reach into the caller's\n * reactor; killing the reactor alone leaves the api/GraphQL/MCP resources\n * dangling until the process exits.\n *\n * When `options.reactor` is omitted, the switchboard builds and owns the\n * reactor. `shutdown()` on the returned handle only drains the api (HTTP\n * server, GraphQL, MCP, attachments); the reactor itself is torn down by\n * its own signal handlers (`withSignalHandlers`), which call `kill()` and\n * trigger the `withShutdownHook` chain that disposes the api. Programmatic\n * full teardown isn't currently exposed — wire it via SIGINT/SIGTERM.\n */\nexport const startSwitchboard = async (\n options: StartServerOptions = {},\n): Promise<SwitchboardReactor> => {\n const requestedPort = options.port ?? DEFAULT_PORT;\n const logger = options.logger ?? defaultLogger;\n const serverPort = await resolveServerPort(\n requestedPort,\n options.strictPort ?? false,\n logger,\n );\n\n // Initialize feature flags\n const featureFlags = await initFeatureFlags();\n\n const enableDocumentModelSubgraphs = await featureFlags.getBooleanValue(\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED,\n options.enableDocumentModelSubgraphs ??\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED_DEFAULT,\n );\n\n options.enableDocumentModelSubgraphs = enableDocumentModelSubgraphs;\n\n const requireSignatures =\n options.identity?.requireSignatures ??\n (await featureFlags.getBooleanValue(\n REQUIRE_SIGNATURES,\n REQUIRE_SIGNATURES_DEFAULT,\n ));\n\n const configPathForFlags = resolveConfigPath(options.configFile);\n const workflowsEnabled = await resolveWorkflowsEnabled({\n featureFlags,\n override: options.workflows?.enabled,\n configEnabled: readConfigWorkflowsEnabled(configPathForFlags),\n });\n options.workflows = { enabled: workflowsEnabled };\n // This switchboard's own identity authenticates against the same Renown\n // instance it verifies incoming credentials against, unless told otherwise.\n const renownConfig = resolveRenownConfig(\n getConfig(resolveConfigPath(options.configFile)).auth?.renown,\n process.env,\n logger,\n );\n options.identity = {\n ...options.identity,\n requireSignatures,\n baseUrl: options.identity?.baseUrl ?? renownConfig.url,\n };\n\n logger.info(\n \"Feature flags: @flags\",\n JSON.stringify(\n {\n DOCUMENT_MODEL_SUBGRAPHS_ENABLED: enableDocumentModelSubgraphs,\n REQUIRE_SIGNATURES: requireSignatures,\n PH_WORKFLOWS_ENABLED: workflowsEnabled,\n },\n null,\n 2,\n ),\n );\n\n // Initialize Renown if identity options are provided or keypair exists\n let renown: IRenown | null = null;\n try {\n renown = await initRenown(options.identity);\n } catch (e) {\n logger.warn(\"Failed to initialize ConnectCrypto: @error\", e);\n if (options.identity.requireExisting) {\n throw new Error(\n 'Identity required but failed to initialize. Run \"ph login\" first.',\n { cause: e },\n );\n }\n }\n\n try {\n return await initServer(serverPort, options, renown, renownConfig);\n } catch (e) {\n Sentry.captureException(e);\n logger.error(\"App crashed: @error\", e);\n throw e;\n }\n};\n\nexport {\n applySwitchboardReactorDefaults,\n type SwitchboardReactorDefaultsOptions,\n} from \"./builder-defaults.mjs\";\nexport * from \"./types.js\";\n\nif (import.me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AAQ,SAAS,gBACnB,OAAM,IAAI,MACR,uEACA,EAAE,OAAO,GAAG,CACb;;AAIL,KAAI;AACF,SAAO,MAAM,WAAW,YAAY,SAAS,QAAQ,aAAa;UAC3D,GAAG;AACV,SAAO,iBAAiB,EAAE;AAC1B,SAAO,MAAM,uBAAuB,EAAE;AACtC,QAAM;;;AAUV,IAAI,OAAO,KAAK,KACd,OAAM,kBAAkB","debug_id":"75db5742-026a-585f-b76c-c4e4981bb421"}
package/dist/server.d.mts CHANGED
@@ -4,8 +4,8 @@ import { AttachmentReferenceProjectionCapability } from "@powerhousedao/reactor-
4
4
  import { IAttachmentService } from "@powerhousedao/reactor-attachments";
5
5
  import { IRenown } from "@renown/sdk/node";
6
6
  import { DriveInput } from "@powerhousedao/shared/document-drive";
7
- import { DocumentModelModule, UpgradeManifest } from "@powerhousedao/shared/document-model";
8
7
  import { IRenown as IRenown$1 } from "@renown/sdk";
8
+ import { DocumentModelModule, UpgradeManifest } from "@powerhousedao/shared/document-model";
9
9
 
10
10
  //#region src/workflow-runtime.d.mts
11
11
  /** Whether the operation intake is indexing. Same shape as the attachment
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/workflow-runtime.mts","../src/types.ts","../src/builder-defaults.mts","../src/server.mts"],"mappings":";;;;;;;;;;;;KAmDY,0BAAA;EACN,MAAA;AAAA;EAEA,MAAA;EACA,MAAA;AAAA;;;;;;;AAJN;;KCjCY,4BAAA;;KAKA,qBAAA,GAAwB,UAAA;EAClC,YAAA,GAAe,4BAAA;AAAA;AAAA,KAGL,cAAA;EACV,IAAA;EACA,cAAA;EACA,WAAA;AAAA;AAAA,KAGU,eAAA;EAf4B,+DAiBtC,WAAA;EAjBsC;;AAKxC;;EAiBE,eAAA,YAhB2C;EAmB3C,OAAA,WAnBA;EAsBA,iBAAA;AAAA;AAAA,KAGU,kBAAA;EAtBA;;;;;;;;;AAMZ;;;;;;;;;;AAgBA;EAqBE,OAAA,GAAU,4BAAA;;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BAAA,EACf,OAAA,GAAS,iCAAA;;;;;;;;iBC+DK,eAAA,CAAgB,IAAA,WAAe,OAAA;;iBAoI/B,6BAAA,CACd,OAAA,EAAS,IAAA,CAAK,kBAAA,qCACd,UAAA,UACA,MAAA,EAAQ,OAAA;EACL,SAAA;EAAmB,UAAA,EAAY,UAAA;AAAA;;;;;;;;;;AF/PpC;;;;;AAKA;;;cEimCa,gBAAA,GACX,OAAA,GAAS,kBAAA,KACR,OAAA,CAAQ,kBAAA"}
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../src/workflow-runtime.mts","../src/types.ts","../src/builder-defaults.mts","../src/server.mts"],"mappings":";;;;;;;;;;AAmDA;;AAAA,KAAY,0BAAA;EACN,MAAA;AAAA;EAEA,MAAA;EACA,MAAA;AAAA;;;;;;;AAJN;;KCjCY,4BAAA;;KAKA,qBAAA,GAAwB,UAAA;EAClC,YAAA,GAAe,4BAAA;AAAA;AAAA,KAGL,cAAA;EACV,IAAA;EACA,cAAA;EACA,WAAA;AAAA;AAAA,KAGU,eAAA;EAf4B,+DAiBtC,WAAA;EAjBsC;;AAKxC;;EAiBE,eAAA,YAhB2C;EAmB3C,OAAA,WAnBA;EAsBA,iBAAA;AAAA;AAAA,KAGU,kBAAA;EAtBA;;;;;;;;;AAMZ;;;;;;;;;;AAgBA;EAqBE,OAAA,GAAU,4BAAA;;;;;;;EAOV,WAAA;EACA,UAAA;EACA,IAAA;EATU;;;;;EAeV,UAAA;EACA,GAAA;EACA,MAAA;EACA,KAAA,GAAQ,qBAAA;EACR,QAAA;EACA,YAAA;EACA,KAAA;IAEM,OAAA;IACA,QAAA;EAAA;EASK;;;;;EAAX,QAAA,GAAW,eAAA,EASO;EAPlB,oBAAA;EACA,GAAA;EAcA;;EAXA,SAAA;IACE,OAAA;EAAA;EAEF,eAAA,GAAkB,GAAA;EAClB,oBAAA;EACA,4BAAA;EAuCE;;;;;EAjCF,mBAAA;EACA,MAAA,GAAS,OAAA;EAiDmB;;;;;;;;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actorDefaults, n as isPortAvailable, r as startSwitchboard, t as deriveAttachmentServiceConfig } from "./server-CS-HdQ55.mjs";
2
+ import { i as applySwitchboardReactorDefaults, n as isPortAvailable, r as startSwitchboard, t as deriveAttachmentServiceConfig } from "./server-C6VtW18k.mjs";
3
3
  import "./utils-Baw7rThP.mjs";
4
4
  export { applySwitchboardReactorDefaults, deriveAttachmentServiceConfig, isPortAvailable, startSwitchboard };
5
- !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]="0b4dddae-349e-582d-b7f7-8ec45c6f7940")}catch(e){}}();
6
- //# debugId=0b4dddae-349e-582d-b7f7-8ec45c6f7940
5
+ !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]="ae48c0e8-eaf4-5b38-87a4-4ba2a144bdbd")}catch(e){}}();
6
+ //# debugId=ae48c0e8-eaf4-5b38-87a4-4ba2a144bdbd