@powerhousedao/switchboard 6.2.3-dev.78 → 6.2.3-dev.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  2. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  3. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  4. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  5. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  6. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  7. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  8. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  9. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  10. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  11. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  12. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  13. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  14. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  15. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  16. package/CHANGELOG.md +35 -0
  17. package/README.md +9 -5
  18. package/dist/boot.d.mts +8 -0
  19. package/dist/boot.d.mts.map +1 -1
  20. package/dist/boot.mjs +22 -16
  21. package/dist/boot.mjs.map +1 -1
  22. package/dist/config/from-env.d.mts +15 -0
  23. package/dist/config/from-env.d.mts.map +1 -0
  24. package/dist/config/from-env.mjs +4 -0
  25. package/dist/config/schema.d.mts +3 -0
  26. package/dist/config/schema.mjs +4 -0
  27. package/dist/from-env-BO0n9R02.mjs +401 -0
  28. package/dist/from-env-BO0n9R02.mjs.map +1 -0
  29. package/dist/index.mjs +34 -38
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/migrate.mjs +2 -2
  32. package/dist/{plugin-host-BBqojyyY.d.mts → plugin-host-C1sYEm8g.d.mts} +4 -1
  33. package/dist/plugin-host-C1sYEm8g.d.mts.map +1 -0
  34. package/dist/plugins/attachments.d.mts +3 -3
  35. package/dist/plugins/attachments.mjs +3 -3
  36. package/dist/plugins/mcp.d.mts +1 -1
  37. package/dist/plugins/privacy.d.mts +1 -1
  38. package/dist/plugins/privacy.mjs +3 -3
  39. package/dist/plugins/workflows.d.mts +1 -1
  40. package/dist/plugins/workflows.mjs +3 -3
  41. package/dist/privacy-BO8Q25xI.mjs +44 -0
  42. package/dist/privacy-BO8Q25xI.mjs.map +1 -0
  43. package/dist/{privacy-BsFl7GzK.mjs → privacy-DxIJGH4P.mjs} +14 -41
  44. package/dist/privacy-DxIJGH4P.mjs.map +1 -0
  45. package/dist/renown-layers-COZsrGQT.mjs +40 -0
  46. package/dist/renown-layers-COZsrGQT.mjs.map +1 -0
  47. package/dist/schema-0g_QdOWn.mjs +267 -0
  48. package/dist/schema-0g_QdOWn.mjs.map +1 -0
  49. package/dist/schema-ivUWPQOn.d.mts +202 -0
  50. package/dist/schema-ivUWPQOn.d.mts.map +1 -0
  51. package/dist/{server-Bdq8xquD.mjs → server-CtGBZlTg.mjs} +230 -382
  52. package/dist/server-CtGBZlTg.mjs.map +1 -0
  53. package/dist/server.d.mts +46 -11
  54. package/dist/server.d.mts.map +1 -1
  55. package/dist/server.mjs +5 -4
  56. package/dist/{utils-CTtD7Oti.mjs → utils-BbV_nodR.mjs} +23 -20
  57. package/dist/utils-BbV_nodR.mjs.map +1 -0
  58. package/dist/utils.d.mts.map +1 -1
  59. package/dist/utils.mjs +3 -3
  60. package/dist/{reactor-feature-flags-BtWVQDt6.mjs → worker-pool-BWHBLBJd.mjs} +12 -32
  61. package/dist/worker-pool-BWHBLBJd.mjs.map +1 -0
  62. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -1
  63. package/dist/{workflows-fsBcElEi.mjs → workflows-QY9Y2eoD.mjs} +5 -16
  64. package/dist/workflows-QY9Y2eoD.mjs.map +1 -0
  65. package/package.json +29 -19
  66. package/test/attachment-reference-read-model.test.ts +22 -19
  67. package/test/attachments/download-target.test.ts +29 -19
  68. package/test/attachments/service-config.test.ts +28 -16
  69. package/test/boot-auth-config.test.ts +109 -0
  70. package/test/boot-create-signature-policy.test.ts +15 -13
  71. package/test/boot-env-isolation.test.ts +2 -2
  72. package/test/boot-helpers.ts +18 -0
  73. package/test/boot-inspection-enabled.test.ts +16 -13
  74. package/test/boot-mcp-enabled.test.ts +15 -13
  75. package/test/boot-port-zero.test.ts +15 -13
  76. package/test/boot-preconditions.test.ts +51 -0
  77. package/test/boot-privacy.test.ts +12 -10
  78. package/test/boot-unsupported-stored-documents.test.ts +10 -9
  79. package/test/boot-without-renown.test.ts +11 -9
  80. package/test/boot-without-require-signatures.test.ts +12 -10
  81. package/test/boot-worker-trust-policy.test.ts +11 -10
  82. package/test/boot-workflow-singleton-conflict.test.ts +11 -9
  83. package/test/boot-workflow-singleton-retry.test.ts +12 -10
  84. package/test/config-from-env.test.ts +758 -0
  85. package/test/config-merge.test.ts +215 -0
  86. package/test/config-schema.test.ts +128 -0
  87. package/test/default-drive-protocol-versions.test.ts +78 -0
  88. package/test/pglite-storage-dirs.test.ts +24 -14
  89. package/test/pglite-store.test.ts +1 -62
  90. package/test/plugin-presence.test.ts +27 -21
  91. package/test/renown-storage-path.test.ts +9 -8
  92. package/test/shutdown.test.ts +22 -21
  93. package/test/two-switchboards.test.ts +146 -0
  94. package/test/workflow-runtime.test.ts +12 -69
  95. package/tsdown.config.ts +2 -0
  96. package/vitest.config.ts +2 -0
  97. package/.tsbuild/test/inspection-flag.test.d.ts +0 -2
  98. package/.tsbuild/test/inspection-flag.test.d.ts.map +0 -1
  99. package/.tsbuild/test/mcp-flag.test.d.ts +0 -2
  100. package/.tsbuild/test/mcp-flag.test.d.ts.map +0 -1
  101. package/dist/plugin-host-BBqojyyY.d.mts.map +0 -1
  102. package/dist/privacy-BsFl7GzK.mjs.map +0 -1
  103. package/dist/reactor-feature-flags-BtWVQDt6.mjs.map +0 -1
  104. package/dist/server-Bdq8xquD.mjs.map +0 -1
  105. package/dist/utils-CTtD7Oti.mjs.map +0 -1
  106. package/dist/workflows-fsBcElEi.mjs.map +0 -1
  107. package/test/inspection-flag.test.ts +0 -62
  108. package/test/mcp-flag.test.ts +0 -56
@@ -22,7 +22,8 @@ import {
22
22
  type MockInstance,
23
23
  } from "vitest";
24
24
  import { applySwitchboardReactorDefaults } from "../src/builder-defaults.mjs";
25
- import { startSwitchboard } from "../src/server.mjs";
25
+ import type { startSwitchboard } from "../src/server.mjs";
26
+ import { bootSwitchboard } from "./boot-helpers.js";
26
27
 
27
28
  type Switchboard = Awaited<ReturnType<typeof startSwitchboard>>;
28
29
 
@@ -116,16 +117,16 @@ describe("SwitchboardReactor.shutdown", () => {
116
117
  async function start(
117
118
  reactor?: InProcessReactorClientModule,
118
119
  ): Promise<Switchboard> {
119
- switchboard = await startSwitchboard({
120
- reactor,
121
- workflows: { enabled: false },
122
- dbPath: join(tempRoot, "read-model"),
123
- port: 0,
124
- mcp: false,
125
- disableLocalPackages: true,
126
- identity: { keypairPath: join(tempRoot, "identity.json") },
127
- logger: stubLogger(),
128
- });
120
+ switchboard = await bootSwitchboard(
121
+ {
122
+ server: { port: 0 },
123
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
124
+ features: { workflows: false, mcp: false },
125
+ packages: { disableLocal: true },
126
+ identity: { keypairPath: join(tempRoot, "identity.json") },
127
+ },
128
+ { reactor, logger: stubLogger() },
129
+ );
129
130
  return switchboard;
130
131
  }
131
132
 
@@ -216,16 +217,16 @@ describe("SwitchboardReactor.shutdown", () => {
216
217
 
217
218
  try {
218
219
  await expect(
219
- startSwitchboard({
220
- workflows: { enabled: false },
221
- dbPath: join(tempRoot, "read-model"),
222
- port,
223
- strictPort: true,
224
- mcp: false,
225
- disableLocalPackages: true,
226
- identity: { keypairPath: join(tempRoot, "identity.json") },
227
- logger: stubLogger(),
228
- }),
220
+ bootSwitchboard(
221
+ {
222
+ server: { port: port, strictPort: true },
223
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
224
+ features: { workflows: false, mcp: false },
225
+ packages: { disableLocal: true },
226
+ identity: { keypairPath: join(tempRoot, "identity.json") },
227
+ },
228
+ { logger: stubLogger() },
229
+ ),
229
230
  ).rejects.toThrow(/no loaded package serves/);
230
231
  } finally {
231
232
  if (previousSource === undefined) {
@@ -0,0 +1,146 @@
1
+ import { signaturePolicyOf } from "@powerhousedao/shared/document-model";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { ILogger } from "document-model";
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7
+ import type { SwitchboardConfigInput } from "../src/config/schema.js";
8
+ import { startSwitchboard, type SwitchboardReactor } from "../src/server.mjs";
9
+
10
+ type Info = ReturnType<typeof vi.fn>;
11
+
12
+ function stubLogger(): ILogger & { info: Info } {
13
+ const logger = {
14
+ verbose: vi.fn(),
15
+ debug: vi.fn(),
16
+ info: vi.fn(),
17
+ warn: vi.fn(),
18
+ error: vi.fn(),
19
+ child: vi.fn(),
20
+ };
21
+ logger.child.mockReturnValue(logger);
22
+ return logger as unknown as ILogger & { info: Info };
23
+ }
24
+
25
+ function messages(logger: { info: Info }): string[] {
26
+ return logger.info.mock.calls.map(([message]) => String(message));
27
+ }
28
+
29
+ /** The `[policy enforcement, caller identity]` reactor-api logged, if any. */
30
+ function authSetup(logger: { info: Info }): unknown[] | undefined {
31
+ return logger.info.mock.calls
32
+ .find(([message]) =>
33
+ String(message).startsWith("Setting up Auth middleware"),
34
+ )
35
+ ?.slice(1);
36
+ }
37
+
38
+ async function throttled(port: number): Promise<boolean> {
39
+ const response = await fetch(`http://localhost:${port}/graphql/inspection`, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json" },
42
+ body: JSON.stringify({
43
+ query:
44
+ '{ inspection { validateDocument(documentId: "missing") { documentId } } }',
45
+ }),
46
+ });
47
+ const body = (await response.json()) as {
48
+ errors?: { extensions?: { code?: string } }[];
49
+ };
50
+ return (body.errors ?? []).some(
51
+ (error) => error.extensions?.code === "TOO_MANY_REQUESTS",
52
+ );
53
+ }
54
+
55
+ // Env a direct caller does not map: nothing inside the server may read it.
56
+ const STRAY_ENV = { AUTH_ENABLED: "true", ADMINS: "0xenv" };
57
+
58
+ describe("two switchboards in one process", () => {
59
+ let root: string;
60
+ const started: SwitchboardReactor[] = [];
61
+ const previous = new Map<string, string | undefined>();
62
+
63
+ beforeEach(async () => {
64
+ root = await mkdtemp(join(tmpdir(), "switchboard-two-"));
65
+ for (const [name, value] of Object.entries(STRAY_ENV)) {
66
+ previous.set(name, process.env[name]);
67
+ process.env[name] = value;
68
+ }
69
+ });
70
+
71
+ afterEach(async () => {
72
+ for (const handle of started.splice(0)) await handle.shutdown();
73
+ for (const [name, value] of previous) {
74
+ if (value === undefined) delete process.env[name];
75
+ else process.env[name] = value;
76
+ }
77
+ previous.clear();
78
+ await rm(root, { recursive: true, force: true });
79
+ });
80
+
81
+ async function boot(name: string, config: SwitchboardConfigInput) {
82
+ const logger = stubLogger();
83
+ const handle = await startSwitchboard(
84
+ {
85
+ server: { port: 0 },
86
+ storage: { inMemory: true, userDataDir: join(root, name) },
87
+ features: { workflows: false, mcp: false },
88
+ packages: { disableLocal: true },
89
+ identity: { keypairPath: join(root, name, "identity.json") },
90
+ ...config,
91
+ },
92
+ { logger, signalHandlers: false, fatalErrorShutdown: false },
93
+ );
94
+ started.push(handle);
95
+ return { handle, logger };
96
+ }
97
+
98
+ it("runs each on its own config, not on the process env", async () => {
99
+ const a = await boot("a", {
100
+ protocol: {
101
+ featureFlags: { documentDecisions: true },
102
+ createSignaturePolicy: "legacy",
103
+ },
104
+ auth: { resolveIdentity: true },
105
+ inspection: { callsPerMinute: 1 },
106
+ });
107
+ const b = await boot("b", {
108
+ protocol: { featureFlags: { documentDecisions: false } },
109
+ inspection: { callsPerMinute: 3 },
110
+ });
111
+
112
+ expect(a.handle.port).toBeGreaterThan(0);
113
+ expect(b.handle.port).toBeGreaterThan(0);
114
+ expect(a.handle.port).not.toBe(b.handle.port);
115
+
116
+ const flagsOn = "Reactor feature flags enabled: documentDecisions";
117
+ expect(messages(a.logger)).toContain(flagsOn);
118
+ expect(messages(b.logger)).not.toContain(flagsOn);
119
+
120
+ // AUTH_ENABLED in process.env reaches neither.
121
+ expect(authSetup(a.logger)).toEqual([false, true]);
122
+ expect(authSetup(b.logger)).toBeUndefined();
123
+
124
+ const onA = await a.handle.reactor.createEmpty("powerhouse/document-model");
125
+ const onB = await b.handle.reactor.createEmpty("powerhouse/document-model");
126
+ expect(signaturePolicyOf(onA.header)).toBe("legacy");
127
+ expect(signaturePolicyOf(onB.header)).toBe("v2-required");
128
+ const exists = (handle: SwitchboardReactor, id: string) =>
129
+ handle.reactor.get(id).then(
130
+ () => true,
131
+ () => false,
132
+ );
133
+ expect(await exists(a.handle, onA.header.id)).toBe(true);
134
+ expect(await exists(b.handle, onA.header.id)).toBe(false);
135
+ expect(await exists(a.handle, onB.header.id)).toBe(false);
136
+
137
+ expect(a.handle.inspectionEnabled).toBe(true);
138
+ expect(b.handle.inspectionEnabled).toBe(true);
139
+ expect(await throttled(a.handle.port)).toBe(false);
140
+ expect(await throttled(a.handle.port)).toBe(true);
141
+ for (let call = 0; call < 3; call++) {
142
+ expect(await throttled(b.handle.port)).toBe(false);
143
+ }
144
+ expect(await throttled(b.handle.port)).toBe(true);
145
+ }, 120_000);
146
+ });
@@ -30,10 +30,9 @@ import type { ILogger } from "document-model";
30
30
  import { Kysely } from "kysely";
31
31
  import { PGliteDialect } from "kysely-pglite-dialect";
32
32
  import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
33
- import { initFeatureFlags } from "../src/feature-flags.js";
34
- import { startSwitchboard } from "../src/server.mjs";
33
+ import type { startSwitchboard } from "../src/server.mjs";
34
+ import { bootSwitchboard } from "./boot-helpers.js";
35
35
  import {
36
- PH_WORKFLOWS_ENABLED,
37
36
  bindPackagePieces,
38
37
  attachmentReadPolicy,
39
38
  composeWorkflowRuntime,
@@ -43,8 +42,6 @@ import {
43
42
  retryWorkflowSingleton,
44
43
  workflowSingletonLossHandler,
45
44
  reactorAccessOf,
46
- resolveWorkflowsEnabled,
47
- type BooleanFlagSource,
48
45
  type ComposedWorkflowRuntime,
49
46
  } from "../src/workflow-runtime.mjs";
50
47
 
@@ -67,61 +64,6 @@ function stubLogger(): ILogger & {
67
64
  };
68
65
  }
69
66
 
70
- describe("resolveWorkflowsEnabled", () => {
71
- let featureFlags: BooleanFlagSource;
72
-
73
- beforeAll(async () => {
74
- featureFlags = await initFeatureFlags();
75
- });
76
-
77
- afterEach(() => {
78
- delete process.env[PH_WORKFLOWS_ENABLED];
79
- });
80
-
81
- it("defaults to off", async () => {
82
- await expect(resolveWorkflowsEnabled({ featureFlags })).resolves.toBe(
83
- false,
84
- );
85
- });
86
-
87
- it("lets the host's option win over the env var", async () => {
88
- process.env[PH_WORKFLOWS_ENABLED] = "false";
89
-
90
- await expect(
91
- resolveWorkflowsEnabled({ featureFlags, override: true }),
92
- ).resolves.toBe(true);
93
-
94
- process.env[PH_WORKFLOWS_ENABLED] = "true";
95
-
96
- await expect(
97
- resolveWorkflowsEnabled({ featureFlags, override: false }),
98
- ).resolves.toBe(false);
99
- });
100
-
101
- it("reads the env var in every form reactor-api accepted", async () => {
102
- for (const [raw, expected] of [
103
- ["true", true],
104
- ["1", true],
105
- ["false", false],
106
- ["0", false],
107
- ] as const) {
108
- process.env[PH_WORKFLOWS_ENABLED] = raw;
109
- await expect(
110
- resolveWorkflowsEnabled({ featureFlags, configEnabled: !expected }),
111
- ).resolves.toBe(expected);
112
- }
113
- });
114
-
115
- it("falls back to the config file, then off", async () => {
116
- await expect(
117
- resolveWorkflowsEnabled({ featureFlags, configEnabled: true }),
118
- ).resolves.toBe(true);
119
- await expect(
120
- resolveWorkflowsEnabled({ featureFlags, configEnabled: false }),
121
- ).resolves.toBe(false);
122
- });
123
- });
124
-
125
67
  describe("assertWorkflowPackageLoadable", () => {
126
68
  it("passes when the package resolves", async () => {
127
69
  await expect(
@@ -1000,15 +942,16 @@ describe("booting Switchboard with workflows on", () => {
1000
942
  let switchboard: Awaited<ReturnType<typeof startSwitchboard>> | undefined;
1001
943
 
1002
944
  try {
1003
- switchboard = await startSwitchboard({
1004
- workflows: { enabled: true },
1005
- dbPath: join(tempRoot, "read-model"),
1006
- port: 0,
1007
- mcp: false,
1008
- disableLocalPackages: true,
1009
- identity: { keypairPath: join(tempRoot, "identity.json") },
1010
- logger: stubLogger(),
1011
- });
945
+ switchboard = await bootSwitchboard(
946
+ {
947
+ server: { port: 0 },
948
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
949
+ features: { workflows: true, mcp: false },
950
+ packages: { disableLocal: true },
951
+ identity: { keypairPath: join(tempRoot, "identity.json") },
952
+ },
953
+ { logger: stubLogger() },
954
+ );
1012
955
 
1013
956
  expect(switchboard.workflowTriggers).toEqual({ status: "available" });
1014
957
  const { results } = await switchboard.reactor.getDocumentModelModules();
package/tsdown.config.ts CHANGED
@@ -7,6 +7,8 @@ export default defineConfig({
7
7
  "src/server.mts",
8
8
  "src/utils.mts",
9
9
  "src/boot.mts",
10
+ "src/config/schema.ts",
11
+ "src/config/from-env.ts",
10
12
  "src/install-packages.mts",
11
13
  "src/migrate.mts",
12
14
  // R2: the built-in plugins, published as subpaths so host.js runner.plugins
package/vitest.config.ts CHANGED
@@ -59,6 +59,8 @@ export default defineConfig({
59
59
  environment: "node",
60
60
  isolate: true,
61
61
  maxWorkers: 1,
62
+ // Node 24's V8 double-frees tiered wasm wrappers after a PGlite worker exits (nodejs/node#66366).
63
+ execArgv: ["--wasm-wrapper-tiering-budget=1000000000"],
62
64
  include: ["test/**/*.test.ts"],
63
65
  },
64
66
  });
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=inspection-flag.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"inspection-flag.test.d.ts","sourceRoot":"","sources":["../../test/inspection-flag.test.ts"],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=mcp-flag.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mcp-flag.test.d.ts","sourceRoot":"","sources":["../../test/mcp-flag.test.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"plugin-host-BBqojyyY.d.mts","names":[],"sources":["../src/plugin-host.mts"],"mappings":";;;;;;;UAgDiB;;;EAGf;EACA,SAAS;EACT;EACA;;;EAGA;;;EAGA;EACA;;;EAGA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB;EAChB,eAAe,eAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"privacy-BsFl7GzK.mjs","sources":["../src/privacy.mts","../src/plugins/privacy.mts"],"sourcesContent":["import type {\n InProcessReactorModule,\n IReactorClient,\n} from \"@powerhousedao/reactor\";\nimport {\n AuthorizationPolicy,\n PrivacyPermissionAdapter,\n type DocumentPermissionService,\n type GraphQLManager,\n type IAuthorizationService,\n} from \"@powerhousedao/reactor-api\";\nimport {\n createModuleErasure,\n createPrivacySubgraph,\n DisclosureService,\n MIN_DEPLOYMENT_SECRET_BYTES,\n registerSubjectDocumentsReadModel,\n type ErasureScheduler,\n type IErasureService,\n} from \"@powerhousedao/reactor-privacy\";\nimport type { ISigner } from \"@powerhousedao/shared/document-model\";\nimport type { ILogger } from \"document-model\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nexport type PrivacyOptions = {\n /** Wins over PH_PRIVACY_ENABLED. */\n enabled?: boolean;\n /** Wins over PH_PRIVACY_DEPLOYMENT_SECRET. */\n deploymentSecret?: string;\n /** The reactor's signer, for a caller-provided reactor. */\n signer?: ISigner;\n};\n\nexport type ResolvedPrivacy =\n | { enabled: false }\n | {\n enabled: true;\n deploymentSecret: string;\n intervalMs?: number;\n deadlineMs?: number;\n markerGraceMs?: number;\n purgeTimeoutMs?: number;\n };\n\n/** Enabling privacy on a switchboard that cannot run it safely. */\nexport class PrivacyBootError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PrivacyBootError\";\n }\n}\n\nfunction positive(\n env: NodeJS.ProcessEnv,\n name: string,\n unitMs: number,\n): number | undefined {\n const raw = env[name];\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const value = Number(raw);\n if (!Number.isFinite(value) || value <= 0) {\n throw new PrivacyBootError(\n `${name} must be a positive number, got \"${raw}\"`,\n );\n }\n return value * unitMs;\n}\n\nexport function resolvePrivacy(\n options: PrivacyOptions | undefined,\n env: NodeJS.ProcessEnv,\n): ResolvedPrivacy {\n const enabled = options?.enabled ?? env.PH_PRIVACY_ENABLED === \"true\";\n if (!enabled) return { enabled: false };\n const deploymentSecret =\n options?.deploymentSecret ?? env.PH_PRIVACY_DEPLOYMENT_SECRET;\n if (\n !deploymentSecret ||\n Buffer.byteLength(deploymentSecret, \"utf8\") < MIN_DEPLOYMENT_SECRET_BYTES\n ) {\n throw new PrivacyBootError(\n `PH_PRIVACY_ENABLED needs PH_PRIVACY_DEPLOYMENT_SECRET of at least ${MIN_DEPLOYMENT_SECRET_BYTES} bytes`,\n );\n }\n return {\n enabled: true,\n deploymentSecret,\n intervalMs: positive(env, \"PH_PRIVACY_INTERVAL_MS\", 1),\n deadlineMs: positive(env, \"PH_PRIVACY_DEADLINE_DAYS\", DAY_MS),\n markerGraceMs: positive(env, \"PH_PRIVACY_MARKER_GRACE_DAYS\", DAY_MS),\n purgeTimeoutMs: positive(env, \"PH_PRIVACY_PURGE_TIMEOUT_MINUTES\", 60_000),\n };\n}\n\nexport type RunningPrivacy = {\n erasure: IErasureService;\n scheduler: ErasureScheduler;\n stop(): Promise<void>;\n};\n\n/** Subject index, erasure scheduler and admin subgraph on a built reactor. */\nexport async function startPrivacy(deps: {\n config: Extract<ResolvedPrivacy, { enabled: true }>;\n reactorModule: InProcessReactorModule | undefined;\n signer: ISigner | undefined;\n authorizationService: IAuthorizationService;\n documentPermissionService: DocumentPermissionService | undefined;\n graphqlManager: GraphQLManager;\n reactorClient: IReactorClient;\n logger: ILogger;\n}): Promise<RunningPrivacy> {\n const { config, reactorModule, authorizationService } = deps;\n if (authorizationService.config.policy === AuthorizationPolicy.OPEN) {\n throw new PrivacyBootError(\n \"PH_PRIVACY_ENABLED is refused under the OPEN authorization policy: every caller, anonymous included, would administer erasure. Enable authentication (AUTH_ENABLED=true with ADMINS) first.\",\n );\n }\n if (!reactorModule) {\n throw new PrivacyBootError(\n \"PH_PRIVACY_ENABLED needs an in-process reactor module\",\n );\n }\n if (!deps.signer?.app?.key) {\n throw new PrivacyBootError(\n \"PH_PRIVACY_ENABLED needs a reactor signer (a Renown identity): every receiver refuses an unsigned purge marker\",\n );\n }\n\n const permissions = deps.documentPermissionService\n ? new PrivacyPermissionAdapter(deps.documentPermissionService)\n : undefined;\n const { service, scheduler } = createModuleErasure(reactorModule, {\n deploymentSecret: config.deploymentSecret,\n signer: deps.signer,\n permissions,\n intervalMs: config.intervalMs,\n deadlineMs: config.deadlineMs,\n markerGraceMs: config.markerGraceMs,\n purgeTimeoutMs: config.purgeTimeoutMs,\n logger: deps.logger,\n });\n\n const disclosure = new DisclosureService(\n reactorModule.database,\n config.deploymentSecret,\n permissions,\n );\n let subgraph;\n try {\n subgraph = createPrivacySubgraph({\n authorizationService,\n erasure: service,\n disclosure,\n });\n } catch (error) {\n throw new PrivacyBootError(\n error instanceof Error ? error.message : String(error),\n );\n }\n\n await registerSubjectDocumentsReadModel(reactorModule, {\n deploymentSecret: config.deploymentSecret,\n });\n await deps.graphqlManager.registerSubgraphInstance(\n {\n ...subgraph,\n path: deps.graphqlManager.getBasePath(),\n reactorClient: deps.reactorClient,\n relationalDb: undefined as never,\n },\n \"graphql\",\n false,\n );\n\n scheduler.start();\n deps.logger.info(\"Privacy add-on started: subject index, erasure scheduler\");\n return {\n erasure: service,\n scheduler,\n stop: () => scheduler.stop(),\n };\n}\n","import type { IRenown } from \"@renown/sdk\";\nimport type { HostPlugin } from \"@powerhousedao/host-core\";\nimport type { ILogger } from \"document-model\";\nimport {\n resolvePrivacy,\n startPrivacy,\n type PrivacyOptions,\n type ResolvedPrivacy,\n type RunningPrivacy,\n} from \"../privacy.mjs\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\nimport { z } from \"zod\";\n\n/** No entry config: presence is the whole activation. A typo'd config key\n * fails at resolution instead of being silently ignored. */\nexport const privacyPluginConfigSchema = z.strictObject({});\n\nexport type PrivacyPluginConfig = z.input<typeof privacyPluginConfigSchema>;\n\ndeclare global {\n interface PHPluginConfigs {\n \"@powerhousedao/switchboard/plugins/privacy\": PrivacyPluginConfig;\n }\n}\n\n/**\n * R2.4 — the privacy subsystem as a built-in plugin. Presence is activation\n * of the SUBSYSTEM; whether privacy enforcement runs still requires its\n * config (enabled + deploymentSecret — A SECRET, env-only:\n * PH_PRIVACY_DEPLOYMENT_SECRET never enters host files).\n *\n * Timing preserved from the inline path (carve map): config resolves EARLY at\n * transformServerOptions (a bad secret fails the boot before any resource\n * opens — same fail-fast property as the inline line-571 resolve); the mount\n * runs at onSubgraphsRegistering, whose server-side call site carries the\n * inline failure semantics (stop workflows, abortBoot, rethrow); teardown is\n * first in shutdown via onShutdown.\n */\n\ntype PrivacyCapableOptions = Record<string, unknown> & {\n privacy?: PrivacyOptions & { signer?: unknown };\n reactor?: unknown;\n};\n\nexport const privacyPlugin: HostPlugin<{\n transformServerOptions: (\n options: Record<string, unknown>,\n ctx: SwitchboardHostContext,\n ) => Record<string, unknown>;\n onSubgraphsRegistering: (ctx: SwitchboardHostContext) => Promise<void>;\n onShutdown: (ctx: SwitchboardHostContext) => Promise<void>;\n}> = {\n name: \"switchboard-privacy\",\n appliesTo: \"switchboard\",\n configSchema: privacyPluginConfigSchema,\n hooks: {\n transformServerOptions: (options, ctx) => {\n // Fail-fast resolve, before the reactor is built.\n ctx.privacyConfig = resolvePrivacy(\n (options as PrivacyCapableOptions).privacy,\n process.env,\n );\n return options;\n },\n onSubgraphsRegistering: async (ctx) => {\n const config = ctx.privacyConfig as ResolvedPrivacy;\n if (!config.enabled) return;\n const options = ctx.options as PrivacyCapableOptions;\n // The caller's reactor signs with a signer only the caller knows.\n const signer = options.reactor\n ? options.privacy?.signer\n : (options.privacy?.signer ?? (ctx.renown as IRenown | null)?.signer);\n const api = ctx.api as {\n authorizationService: never;\n documentPermissionService: never;\n };\n ctx.privacy = await startPrivacy({\n config,\n reactorModule: (\n ctx.reactorClientModule as { reactorModule?: never } | undefined\n )?.reactorModule,\n signer: signer as never,\n authorizationService: api.authorizationService,\n documentPermissionService: api.documentPermissionService,\n graphqlManager: ctx.graphqlManager as never,\n reactorClient: ctx.client as never,\n logger: (ctx.logger as ILogger).child([\"privacy\"]),\n });\n },\n onShutdown: async (ctx) => {\n await (ctx.privacy as RunningPrivacy | undefined)?.stop();\n },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default privacyPlugin;\n"],"names":[],"mappings":";;;;;;AAuBA,MAAM,SAAS;;AAuBf,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAS,SACP,KACA,MACA,QACoB;CACpB,MAAM,MAAM,IAAI;CAChB,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IAAI,OAAO,KAAA;CACnD,MAAM,QAAQ,OAAO,GAAG;CACxB,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,iBACR,GAAG,KAAK,mCAAmC,IAAI,EACjD;CAEF,OAAO,QAAQ;AACjB;AAEA,SAAgB,eACd,SACA,KACiB;CAEjB,IAAI,EADY,SAAS,WAAW,IAAI,uBAAuB,SACjD,OAAO,EAAE,SAAS,MAAM;CACtC,MAAM,mBACJ,SAAS,oBAAoB,IAAI;CACnC,IACE,CAAC,oB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B,KAAK,OAAO,KAAK,0DAA0D;CAC3E,OAAO;EACL,SAAS;EACT;EACA,YAAY,UAAU,KAAK;CAC7B;AACF;;;;;ACvKA,MAAa,4BAA4B,EAAE,aAAa,CAAC,CAAC;AA6B1D,MAAa,gBAOR;CACH,MAAM;CACN,WAAW;CACX,cAAc;CACd,OAAO;EACL,yBAAyB,SAAS,QAAQ;GAExC,IAAI,gBAAgB,eACjB,QAAkC,SACnC,QAAQ,GACV;GACA,OAAO;EACT;EACA,wBAAwB,OAAO,QAAQ;GACrC,MAAM,SAAS,IAAI;GACnB,IAAI,CAAC,OAAO,SAAS;GACrB,MAAM,UAAU,IAAI;GAEpB,MAAM,SAAS,QAAQ,UACnB,QAAQ,SAAS,SAChB,QAAQ,SAAS,UAAW,IAAI,QAA2B;GAChE,MAAM,MAAM,IAAI;GAIhB,IAAI,UAAU,MAAM,aAAa;IAC/B;IACA,eACE,IAAI,qBACH;IACK;IACR,sBAAsB,IAAI;IAC1B,2BAA2B,IAAI;IAC/B,gBAAgB,IAAI;IACpB,eAAe,IAAI;IACnB,QAAS,IAAI,OAAmB,MAAM,CAAC,SAAS,CAAC;GACnD,CAAC;EACH;EACA,YAAY,OAAO,QAAQ;GACzB,MAAO,IAAI,SAAwC,KAAK;EAC1D;CACF;AACF","debug_id":"04a759c0-bfa6-5b01-a2ad-e0e248168e96"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reactor-feature-flags-BtWVQDt6.mjs","sources":["../src/boot-preconditions.mts","../src/env.mts","../src/projection-worker.mts","../src/worker-pool.mts","../src/reactor-feature-flags.mts"],"sourcesContent":["import { isPostgresUrl } from \"./postgres-url.mjs\";\n\n/** What the server refuses to boot with; it throws the first, `ph host check` reports all. */\nexport interface SwitchboardBootFacts {\n dev: boolean;\n /** Executor pool size; 0 when the pool is off. */\n workers: number;\n projectionWorker: boolean;\n reactorDbUrl: string | undefined;\n authEnforcement: boolean;\n renownSource: \"self\" | \"remote\";\n}\n\n/** The reactor database the server boots with: its `dbPath` option, then the env. */\nexport function reactorDbUrlOf(\n dbPath: string | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n return (\n dbPath ?? env.PH_REACTOR_DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL\n );\n}\n\nexport function workerTrustPolicyIssue(\n facts: Pick<\n SwitchboardBootFacts,\n \"workers\" | \"authEnforcement\" | \"renownSource\"\n >,\n): string | undefined {\n if (\n facts.workers > 0 &&\n facts.authEnforcement &&\n facts.renownSource === \"self\"\n ) {\n return (\n \"The executor worker pool (REACTOR_WORKERS) cannot verify signers when \" +\n \"REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from \" +\n 'this switchboard (\"self\" via auth.renown.source or RENOWN_SOURCE): ' +\n \"pooled workers have no trust policy and would refuse every signed \" +\n \"write. Set RENOWN_SOURCE=remote, or disable the worker pool \" +\n \"(REACTOR_WORKERS=0).\"\n );\n }\n return undefined;\n}\n\n/** In the order the server checks them; empty when the pool is off. */\nexport function workerPoolIssues(facts: SwitchboardBootFacts): string[] {\n if (facts.workers <= 0) return [];\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\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 const trust = workerTrustPolicyIssue(facts);\n if (trust) issues.push(trust);\n if (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\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 return issues;\n}\n\n/** The projection worker's preconditions, assuming it is enabled. */\nexport function projectionWorkerIssues(\n facts: Pick<SwitchboardBootFacts, \"dev\" | \"reactorDbUrl\">,\n): string[] {\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\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 (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\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 return issues;\n}\n\nexport function switchboardBootIssues(facts: SwitchboardBootFacts): string[] {\n return [\n ...workerPoolIssues(facts),\n ...(facts.projectionWorker ? projectionWorkerIssues(facts) : []),\n ];\n}\n","export 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 { projectionWorkerIssues } from \"./boot-preconditions.mjs\";\nimport { parseNonNegativeInt } from \"./env.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 const issue = projectionWorkerIssues(args).at(0);\n if (issue) throw new Error(issue);\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 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, pathToFileURL } from \"node:url\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\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// As the reactor builder tells a module from the rest of a source's exports.\nfunction isModelModule(value: unknown): boolean {\n const candidate = value as {\n reducer?: unknown;\n documentModel?: { global?: { id?: unknown } };\n } | null;\n return (\n typeof candidate?.reducer === \"function\" &&\n typeof candidate.documentModel?.global?.id === \"string\"\n );\n}\n\n// Drops sources that fail to import or export no model. For workflow pieces\n// only: a missing model means \"unavailable to pieces\", not a failed boot.\nexport async function keepImportableSources(\n sources: FileModelSource[],\n logger: ILogger,\n): Promise<FileModelSource[]> {\n const kept: FileModelSource[] = [];\n for (const source of sources) {\n try {\n const exports = (await import(\n pathToFileURL(source.filePath).href\n )) as Record<string, unknown>;\n if (Object.values(exports).some(isModelModule)) kept.push(source);\n } catch (error) {\n logger.warn(\n `Worker model sources: \"${source.filePath}\" does not import, so workflow pieces will not see its models: ${String(error)}`,\n );\n }\n }\n return kept;\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 options: {\n /** Cached file for a package not installed locally, e.g. from a registry. */\n resolveRemote?: (identifier: string) => Promise<string | null>;\n } = {},\n): Promise<FileModelSource[]> {\n const sources: FileModelSource[] = [];\n for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {\n const filePath =\n (await resolveModelModuleFile(identifier)) ??\n (await resolveRemoteSafely(identifier, options.resolveRemote, logger));\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\nasync function resolveRemoteSafely(\n identifier: string,\n resolveRemote: ((identifier: string) => Promise<string | null>) | undefined,\n logger: ILogger,\n): Promise<string | null> {\n if (!resolveRemote) return null;\n try {\n return await resolveRemote(identifier);\n } catch (error) {\n logger.warn(\n `Worker model sources: could not cache \"${identifier}\" from the registry: ${String(error)}`,\n );\n return null;\n }\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","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"],"names":[],"mappings":";;;;;;;;;;AAcA,SAAgB,eACd,QACA,KACoB;CACpB,OACE,UAAU,IAAI,2BAA2B,IAAI;AAEjD;AAEA,SAAgB,uBACd,OAIoB;CACpB,IACE,MAAM,UAAU,KAChB,MAAM,mBACN,MAAM,iBAAiB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