@powerhousedao/switchboard 6.2.3-dev.8 → 6.2.3-dev.81

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 (272) hide show
  1. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  2. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-env-isolation.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  16. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  29. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  30. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  31. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  32. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  33. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  34. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  35. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  36. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  37. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  38. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  39. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  40. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  41. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  42. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  43. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  44. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  45. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  46. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  47. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  48. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  49. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  50. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  51. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  52. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  53. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  54. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  55. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  56. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  57. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  58. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  59. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  60. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  61. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  62. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  63. package/.tsbuild/test/permissions-backfill.test.d.ts +2 -0
  64. package/.tsbuild/test/permissions-backfill.test.d.ts.map +1 -0
  65. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  66. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  67. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  68. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  69. package/.tsbuild/test/pglite-store.test.d.ts +2 -0
  70. package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
  71. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  72. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  73. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  74. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  75. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  76. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  77. package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
  78. package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
  79. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  80. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  81. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  82. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  83. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  84. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  85. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  86. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  87. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  88. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  89. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  90. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  91. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  92. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  93. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  94. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  95. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  96. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  97. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  98. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  99. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  100. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  101. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  102. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  103. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  104. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  105. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  106. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  107. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  108. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  109. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  110. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  111. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  112. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  113. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  114. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  115. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  116. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  117. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  118. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  119. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  120. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  121. package/.tsbuild/vitest.config.d.ts.map +1 -1
  122. package/Auth.md +144 -2
  123. package/CHANGELOG.md +1074 -0
  124. package/README.md +55 -14
  125. package/dist/boot.d.mts +46 -0
  126. package/dist/boot.d.mts.map +1 -0
  127. package/dist/boot.mjs +67 -0
  128. package/dist/boot.mjs.map +1 -0
  129. package/dist/config/from-env.d.mts +15 -0
  130. package/dist/config/from-env.d.mts.map +1 -0
  131. package/dist/config/from-env.mjs +4 -0
  132. package/dist/config/schema.d.mts +3 -0
  133. package/dist/config/schema.mjs +4 -0
  134. package/dist/from-env-BO0n9R02.mjs +401 -0
  135. package/dist/from-env-BO0n9R02.mjs.map +1 -0
  136. package/dist/index.d.mts +2 -1
  137. package/dist/index.mjs +76 -79
  138. package/dist/index.mjs.map +1 -1
  139. package/dist/install-packages.d.mts +2 -1
  140. package/dist/install-packages.mjs +2 -2
  141. package/dist/install-packages.mjs.map +1 -1
  142. package/dist/mcp-SsBK14Jm.mjs +32 -0
  143. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  144. package/dist/migrate.d.mts +2 -1
  145. package/dist/migrate.mjs +7 -5
  146. package/dist/migrate.mjs.map +1 -1
  147. package/dist/plugin-host-C1sYEm8g.d.mts +46 -0
  148. package/dist/plugin-host-C1sYEm8g.d.mts.map +1 -0
  149. package/dist/plugins/attachments.d.mts +33 -0
  150. package/dist/plugins/attachments.d.mts.map +1 -0
  151. package/dist/plugins/attachments.mjs +4 -0
  152. package/dist/plugins/mcp.d.mts +31 -0
  153. package/dist/plugins/mcp.d.mts.map +1 -0
  154. package/dist/plugins/mcp.mjs +4 -0
  155. package/dist/plugins/privacy.d.mts +22 -0
  156. package/dist/plugins/privacy.d.mts.map +1 -0
  157. package/dist/plugins/privacy.mjs +4 -0
  158. package/dist/plugins/workflows.d.mts +79 -0
  159. package/dist/plugins/workflows.d.mts.map +1 -0
  160. package/dist/plugins/workflows.mjs +4 -0
  161. package/dist/postgres-url-DTDhBjXX.mjs +11 -0
  162. package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
  163. package/dist/privacy-BO8Q25xI.mjs +44 -0
  164. package/dist/privacy-BO8Q25xI.mjs.map +1 -0
  165. package/dist/privacy-DxIJGH4P.mjs +91 -0
  166. package/dist/privacy-DxIJGH4P.mjs.map +1 -0
  167. package/dist/renown-layers-COZsrGQT.mjs +40 -0
  168. package/dist/renown-layers-COZsrGQT.mjs.map +1 -0
  169. package/dist/schema-0g_QdOWn.mjs +267 -0
  170. package/dist/schema-0g_QdOWn.mjs.map +1 -0
  171. package/dist/schema-ivUWPQOn.d.mts +202 -0
  172. package/dist/schema-ivUWPQOn.d.mts.map +1 -0
  173. package/dist/server-cE1BWLQu.mjs +2518 -0
  174. package/dist/server-cE1BWLQu.mjs.map +1 -0
  175. package/dist/server.d.mts +270 -48
  176. package/dist/server.d.mts.map +1 -1
  177. package/dist/server.mjs +5 -5
  178. package/dist/utils-C6AIF38Z.mjs +133 -0
  179. package/dist/utils-C6AIF38Z.mjs.map +1 -0
  180. package/dist/utils.d.mts +12 -5
  181. package/dist/utils.d.mts.map +1 -1
  182. package/dist/utils.mjs +4 -3
  183. package/dist/worker-pool-BWHBLBJd.mjs +304 -0
  184. package/dist/worker-pool-BWHBLBJd.mjs.map +1 -0
  185. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  186. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  187. package/dist/workflows-COM3MKfD.mjs +1437 -0
  188. package/dist/workflows-COM3MKfD.mjs.map +1 -0
  189. package/package.json +68 -23
  190. package/scripts/install-packages.sh +0 -0
  191. package/test/attachment-reference-read-model.test.ts +28 -20
  192. package/test/attachments/auth.test.ts +85 -0
  193. package/test/attachments/byte-grants.test.ts +290 -0
  194. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  195. package/test/attachments/download-target.test.ts +211 -32
  196. package/test/attachments/index.test.ts +47 -4
  197. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  198. package/test/attachments/routes-integration.test.ts +60 -4
  199. package/test/attachments/routes.test.ts +297 -35
  200. package/test/attachments/service-config.test.ts +41 -19
  201. package/test/attachments/url-signer.test.ts +105 -0
  202. package/test/boot-auth-config.test.ts +109 -0
  203. package/test/boot-create-signature-policy.test.ts +110 -0
  204. package/test/boot-env-isolation.test.ts +26 -0
  205. package/test/boot-helpers.ts +19 -0
  206. package/test/boot-inspection-enabled.test.ts +140 -0
  207. package/test/boot-mcp-auth.test.ts +449 -0
  208. package/test/boot-mcp-enabled.test.ts +119 -0
  209. package/test/boot-port-zero.test.ts +101 -0
  210. package/test/boot-preconditions.test.ts +200 -0
  211. package/test/boot-privacy.test.ts +232 -0
  212. package/test/boot-unsupported-stored-documents.test.ts +214 -0
  213. package/test/boot-without-renown.test.ts +83 -0
  214. package/test/boot-without-require-signatures.test.ts +76 -0
  215. package/test/boot-worker-trust-policy.test.ts +91 -0
  216. package/test/boot-workflow-singleton-conflict.test.ts +109 -0
  217. package/test/boot-workflow-singleton-retry.test.ts +122 -0
  218. package/test/builder-defaults.test.ts +80 -0
  219. package/test/config-from-env.test.ts +758 -0
  220. package/test/config-merge.test.ts +215 -0
  221. package/test/config-schema.test.ts +128 -0
  222. package/test/create-signature-policy.test.ts +69 -0
  223. package/test/default-drive-protocol-versions.test.ts +102 -0
  224. package/test/default-drive-slug.test.ts +97 -0
  225. package/test/durable-node-fs-pg16.test.ts +80 -0
  226. package/test/fatal-shutdown.test.ts +165 -0
  227. package/test/goldens/packages.graphql +797 -0
  228. package/test/goldens/privacy.graphql +853 -0
  229. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  230. package/test/goldens/resolvers.json +322 -0
  231. package/test/goldens/supergraph.graphql +5652 -0
  232. package/test/goldens/workflow-runtime.graphql +1419 -0
  233. package/test/inspection-throttle.test.ts +23 -0
  234. package/test/observability-signals.test.ts +131 -0
  235. package/test/permissions-backfill.test.ts +486 -0
  236. package/test/pglite-dialect.test.ts +237 -2
  237. package/test/pglite-preflight.test.ts +313 -0
  238. package/test/pglite-storage-dirs.test.ts +113 -0
  239. package/test/pglite-store.test.ts +264 -0
  240. package/test/pglite-version.test.ts +9 -1
  241. package/test/plugin-config-schemas.test.ts +83 -0
  242. package/test/plugin-presence.test.ts +262 -0
  243. package/test/port-probe.test.ts +45 -0
  244. package/test/renown-storage-path.test.ts +40 -0
  245. package/test/renown-trust-policy.test.ts +313 -0
  246. package/test/served-schemas.test.ts +134 -0
  247. package/test/shutdown.test.ts +278 -0
  248. package/test/snapshot-writer.ts +94 -0
  249. package/test/store-lock.test.ts +65 -0
  250. package/test/two-switchboards.test.ts +146 -0
  251. package/test/unsupported-stored-documents.test.ts +72 -0
  252. package/test/worker-pool.test.ts +27 -1
  253. package/test/workflow/harness.ts +289 -0
  254. package/test/workflow/oauth.test.ts +205 -0
  255. package/test/workflow/resolvers.test.ts +369 -0
  256. package/test/workflow/runtime-host.test.ts +19 -0
  257. package/test/workflow/webhook-dedupe.test.ts +295 -0
  258. package/test/workflow/webhook-signed.test.ts +509 -0
  259. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  260. package/test/workflow/webhook-unsigned.test.ts +345 -0
  261. package/test/workflow-reactor-access.test.ts +384 -0
  262. package/test/workflow-reactor-enforcement.test.ts +808 -0
  263. package/test/workflow-read-gate.test.ts +213 -0
  264. package/test/workflow-runtime.test.ts +1135 -0
  265. package/test/workflows-plugin-config.test.ts +77 -0
  266. package/tsconfig.json +11 -2
  267. package/tsdown.config.ts +12 -1
  268. package/vitest.config.ts +65 -0
  269. package/dist/server-CiKkVE6g.mjs +0 -1555
  270. package/dist/server-CiKkVE6g.mjs.map +0 -1
  271. package/dist/utils-Baw7rThP.mjs +0 -80
  272. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,1437 @@
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]="d8a311a1-42a7-5207-856f-5c3b1614ae75")}catch(e){}}();
3
+ import { REACTOR_SCHEMA, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
4
+ import { AuthorizationPolicy, BaseSubgraph, ForbiddenError, callerSubject, createCanonicalDocumentIdResolver } from "@powerhousedao/reactor-api";
5
+ import { hostname } from "node:os";
6
+ import { z } from "zod";
7
+ import { parseRef } from "@powerhousedao/reactor-attachments";
8
+ import { GraphQLError, Kind } from "graphql";
9
+ import { gql } from "graphql-tag";
10
+ //#region src/fatal-shutdown.mts
11
+ const FORCED_EXIT_MS = 15e3;
12
+ const fatalHandlers = /* @__PURE__ */ new WeakMap();
13
+ /**
14
+ * Sends an uncaught exception or unhandled rejection through the SIGTERM
15
+ * shutdown that `withSignalHandlers()` installs, so the reactor and read-model
16
+ * PGlite stores close with a shutdown checkpoint before the process exits
17
+ * with code 1. Node's default is to exit at once, which leaves both stores
18
+ * to WAL recovery on the next open. A store whose wasm runtime aborted
19
+ * (ENOSPC) rejects its close; the builder logs that and still exits. A
20
+ * shutdown that hangs is cut off after FORCED_EXIT_MS.
21
+ *
22
+ * A rejection is fatal only when this is its sole listener: Node exits on an
23
+ * unhandled rejection only when nothing listens for it, and Sentry's
24
+ * listener deliberately keeps the process running.
25
+ */
26
+ function installFatalErrorShutdown(logger, proc = process) {
27
+ if (fatalHandlers.has(proc)) return;
28
+ const realExit = proc.exit.bind(proc);
29
+ let shuttingDown = false;
30
+ /**
31
+ * Logs without ever throwing. onFatal runs inside the uncaughtException
32
+ * handler, so a logger whose transport is gone (EPIPE on a closed stdout)
33
+ * would otherwise throw from the handler that reports throws, killing the
34
+ * process before the shutdown it is supposed to run. A logging failure is
35
+ * swallowed: there is nowhere left to report it.
36
+ */
37
+ const logFatal = (message, err) => {
38
+ try {
39
+ if (err === void 0) logger.error(message);
40
+ else logger.error(message, err);
41
+ } catch {}
42
+ };
43
+ const onFatal = (kind, err) => {
44
+ logFatal(`${kind}: @error`, err);
45
+ if (shuttingDown) return;
46
+ shuttingDown = true;
47
+ proc.exitCode = 1;
48
+ setTimeout(() => {
49
+ logFatal("Shutdown after fatal error timed out; exiting");
50
+ realExit(1);
51
+ }, FORCED_EXIT_MS).unref();
52
+ proc.kill(proc.pid, "SIGTERM");
53
+ };
54
+ fatalHandlers.set(proc, onFatal);
55
+ proc.on("uncaughtException", (err) => onFatal("Uncaught exception", err));
56
+ proc.on("unhandledRejection", (reason) => {
57
+ if (proc.listenerCount("unhandledRejection") > 1) return;
58
+ onFatal("Unhandled rejection", reason);
59
+ });
60
+ }
61
+ /**
62
+ * Routes a fatal condition the caller detected through the same shutdown as an
63
+ * uncaught error. Returns false, and does nothing, when
64
+ * `installFatalErrorShutdown` has not run for `proc`.
65
+ */
66
+ function triggerFatalShutdown(kind, err, proc = process) {
67
+ const onFatal = fatalHandlers.get(proc);
68
+ if (!onFatal) return false;
69
+ onFatal(kind, err);
70
+ return true;
71
+ }
72
+ //#endregion
73
+ //#region src/workflow/oauth-callback.ts
74
+ const OAUTH_CALLBACK_PATH = "oauth/callback";
75
+ function escapeHtml(text) {
76
+ return text.replace(/[&<>"']/g, (char) => ({
77
+ "&": "&amp;",
78
+ "<": "&lt;",
79
+ ">": "&gt;",
80
+ "\"": "&quot;",
81
+ "'": "&#39;"
82
+ })[char]);
83
+ }
84
+ function resultPage(ok, detail) {
85
+ const title = ok ? "Connected" : "Sign-in failed";
86
+ return `<!doctype html>
87
+ <html><head><meta charset="utf-8"><title>${title}</title>
88
+ <meta name="viewport" content="width=device-width, initial-scale=1">
89
+ <style>body{font:15px system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#222}main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.1rem}</style>
90
+ </head><body><main><h1>${title}</h1><p>${ok ? "You can close this window." : escapeHtml(detail ?? "The sign-in did not finish.")}</p></main>
91
+ ${ok ? "<script>setTimeout(function(){window.close()},600)<\/script>" : ""}
92
+ </body></html>`;
93
+ }
94
+ function registerOAuthCallback(http, runtime) {
95
+ return http.get(OAUTH_CALLBACK_PATH, { auth: "public" }, async (request) => {
96
+ const params = new URL(request.url).searchParams;
97
+ const state = params.get("state");
98
+ const result = state ? await runtime.completeOAuth({
99
+ state,
100
+ code: params.get("code") ?? void 0,
101
+ error: params.get("error") ?? void 0,
102
+ errorDescription: params.get("error_description") ?? void 0
103
+ }) : {
104
+ ok: false,
105
+ detail: "The provider sent no state",
106
+ returnUrl: null
107
+ };
108
+ if (result.returnUrl && state) {
109
+ const back = new URL(result.returnUrl);
110
+ back.searchParams.set("ph_oauth", state);
111
+ return new Response(null, {
112
+ status: 303,
113
+ headers: {
114
+ location: back.href,
115
+ "cache-control": "no-store"
116
+ }
117
+ });
118
+ }
119
+ return new Response(resultPage(result.ok, result.detail), {
120
+ status: result.ok ? 200 : 400,
121
+ headers: {
122
+ "content-type": "text/html; charset=utf-8",
123
+ "cache-control": "no-store",
124
+ "referrer-policy": "no-referrer"
125
+ }
126
+ });
127
+ });
128
+ }
129
+ function callbackUrlOf(http) {
130
+ return `${http.baseUrl.replace(/\/+$/, "")}/${OAUTH_CALLBACK_PATH}`;
131
+ }
132
+ //#endregion
133
+ //#region src/workflow/resolvers.ts
134
+ const PIECE_SOURCES = [
135
+ "local",
136
+ "registry",
137
+ "activepieces"
138
+ ];
139
+ function isPieceSource(value) {
140
+ return PIECE_SOURCES.includes(value);
141
+ }
142
+ function blockRef(input) {
143
+ if (input.kind !== "action" && input.kind !== "trigger") throw new GraphQLError(`A block's kind is "action" or "trigger", got "${input.kind}"`);
144
+ return {
145
+ pieceName: input.pieceName,
146
+ pieceVersion: input.pieceVersion,
147
+ name: input.name,
148
+ kind: input.kind
149
+ };
150
+ }
151
+ async function cursorAware(call) {
152
+ try {
153
+ return await call();
154
+ } catch (error) {
155
+ if (error instanceof Error && error.name === "InvalidRunCursorError") throw new GraphQLError(error.message, { extensions: { code: "BAD_USER_INPUT" } });
156
+ throw error;
157
+ }
158
+ }
159
+ function selectsStepData(selections, path) {
160
+ let level = selections;
161
+ for (const name of [...path, "steps"]) {
162
+ const next = [];
163
+ for (const set of level) for (const selection of set.selections) {
164
+ if (selection.kind !== Kind.FIELD) return true;
165
+ if (selection.name.value === name && selection.selectionSet) next.push(selection.selectionSet);
166
+ }
167
+ if (next.length === 0) return false;
168
+ level = next;
169
+ }
170
+ return level.some((set) => set.selections.some((selection) => selection.kind !== Kind.FIELD || selection.name.value === "input" || selection.name.value === "output"));
171
+ }
172
+ function readsStepData(info, path) {
173
+ if (!info) return true;
174
+ return selectsStepData(info.fieldNodes.flatMap((node) => node.selectionSet ? [node.selectionSet] : []), path);
175
+ }
176
+ async function syncAware(call) {
177
+ try {
178
+ return await call();
179
+ } catch (error) {
180
+ if (error instanceof Error && error.name === "WorkflowSyncingError") throw new GraphQLError(error.message, { extensions: {
181
+ code: "WORKFLOW_SYNCING",
182
+ retryable: true
183
+ } });
184
+ throw error;
185
+ }
186
+ }
187
+ function parseJson(value) {
188
+ if (value === null) return null;
189
+ try {
190
+ return JSON.parse(value);
191
+ } catch {
192
+ return value;
193
+ }
194
+ }
195
+ function toStepRecord(row) {
196
+ return {
197
+ stepId: row.step_id,
198
+ stepKey: row.step_key,
199
+ pieceName: row.piece_name,
200
+ blockName: row.block_name,
201
+ status: row.status,
202
+ input: parseJson(row.input),
203
+ output: parseJson(row.output),
204
+ port: row.port,
205
+ error: row.error,
206
+ errorName: row.error_name,
207
+ startedAt: row.started_at,
208
+ endedAt: row.ended_at,
209
+ pieceVersion: row.piece_version,
210
+ pieceSource: row.piece_source,
211
+ versionMatch: row.version_match,
212
+ versionNote: row.version_note
213
+ };
214
+ }
215
+ function toRunRecord(row, steps) {
216
+ return {
217
+ id: row.id,
218
+ workflowId: row.workflow_id,
219
+ workflowName: row.workflow_name,
220
+ workflowVersion: row.workflow_version,
221
+ triggerKind: row.trigger_kind,
222
+ triggerPayload: parseJson(row.trigger_payload),
223
+ status: row.status,
224
+ error: row.error,
225
+ errorName: row.error_name,
226
+ startedAt: row.started_at,
227
+ endedAt: row.ended_at,
228
+ rerunOf: row.rerun_of,
229
+ warnings: row.warnings,
230
+ warningNotes: parseJson(row.warning_notes) ?? [],
231
+ steps: steps.map(toStepRecord)
232
+ };
233
+ }
234
+ const UNKNOWN_ACCESS = {
235
+ authEnforcement: true,
236
+ authConditions: false,
237
+ identity: null
238
+ };
239
+ function signedIn(ctx) {
240
+ return Boolean(ctx.user?.address);
241
+ }
242
+ function isAbsolute(url) {
243
+ return /^https?:\/\//i.test(url);
244
+ }
245
+ function redirectUriFor(routing, requested) {
246
+ if (!routing) throw new GraphQLError("This host serves no OAuth2 callback");
247
+ if (isAbsolute(routing.callbackUrl)) return routing.callbackUrl;
248
+ if (!requested) throw new GraphQLError("This host does not know its public URL; pass redirectUri");
249
+ let url;
250
+ try {
251
+ url = new URL(requested);
252
+ } catch {
253
+ throw new GraphQLError(`"${requested}" is not a URL`);
254
+ }
255
+ if (url.protocol !== "https:" && url.protocol !== "http:" || url.pathname !== routing.callbackUrl || url.search !== "" || url.hash !== "") throw new GraphQLError(`redirectUri must be this host's ${routing.callbackUrl}`);
256
+ return url.href;
257
+ }
258
+ function returnUrlFor(requested, ctx) {
259
+ if (!requested) return void 0;
260
+ const origin = ctx.headers.origin;
261
+ let url;
262
+ try {
263
+ url = new URL(requested);
264
+ } catch {
265
+ url = void 0;
266
+ }
267
+ if (!url || !origin || url.origin !== origin) throw new GraphQLError("returnUrl must be on the requesting page's origin");
268
+ return url.href;
269
+ }
270
+ const getResolvers = (runtime, oauth, access = UNKNOWN_ACCESS, assertCanRead) => {
271
+ return {
272
+ Query: { workflowRuntime: () => ({}) },
273
+ WorkflowRuntimeQueries: {
274
+ health: () => "ok",
275
+ authEnforcement: () => access.authEnforcement,
276
+ reactorIdentity: (_parent, _args, ctx) => signedIn(ctx) ? access.identity : null,
277
+ authConditions: (_parent, _args, ctx) => signedIn(ctx) ? access.authConditions : null,
278
+ reactorAccessDenial: async (_parent, args, ctx) => {
279
+ if (!assertCanRead) throw new GraphQLError("No read check configured");
280
+ await assertCanRead(args.workflowId, ctx);
281
+ return runtime.reactorAccessDenial(args.workflowId) ?? null;
282
+ },
283
+ blockDescriptor: (_parent, args) => runtime.blockDescriptor(blockRef(args.block)),
284
+ blockOptions: (_parent, args, ctx) => runtime.blockOptions(blockRef(args.block), args.propName, args.input, args.connectionId ?? void 0, ctx, args.searchValue ?? void 0, args.reactorConnectionId ?? void 0),
285
+ pieceCatalog: () => runtime.pieceCatalog(),
286
+ pieceActions: (_parent, args) => runtime.pieceActions(args.packageName, args.version ?? void 0),
287
+ pieceTriggers: (_parent, args) => runtime.pieceTriggers(args.packageName, args.version ?? void 0),
288
+ blockOutputTree: (_parent, args) => runtime.blockOutputTree(blockRef(args.block), args.config),
289
+ stepOutputTree: (_parent, args, ctx) => runtime.stepOutputTree(args.workflowId, args.stepId, ctx),
290
+ blockResolutions: (_parent, args, ctx) => runtime.blockResolutions(args.workflowId, ctx),
291
+ pieceDetail: (_parent, args) => runtime.pieceDetail(args.packageName, args.version ?? void 0),
292
+ searchPieces: (_parent, args) => {
293
+ if (args.kind !== "action" && args.kind !== "trigger") throw new GraphQLError(`A search's kind is "action" or "trigger", got "${args.kind}"`);
294
+ const unknown = (args.sources ?? []).filter((source) => !isPieceSource(source));
295
+ if (unknown.length > 0) throw new GraphQLError(`A search's sources are ${PIECE_SOURCES.join(", ")}, got ${unknown.join(", ")}`);
296
+ return runtime.searchPieces(args.query, {
297
+ kind: args.kind,
298
+ sources: (args.sources ?? []).filter(isPieceSource),
299
+ categories: args.categories ?? void 0,
300
+ limit: args.limit ?? void 0
301
+ });
302
+ },
303
+ connections: (_parent, _args, ctx) => runtime.connections(ctx),
304
+ webhookEndpoint: (_parent, args, ctx) => syncAware(() => runtime.webhookEndpoint(args.workflowId, ctx, { driveId: args.driveId ?? void 0 })),
305
+ secret: (_parent, args, ctx) => runtime.secretStat(args.ref, ctx),
306
+ secrets: (_parent, _args, ctx) => runtime.listSecrets(ctx),
307
+ oauthRedirectUri: () => oauth?.callbackUrl ?? null,
308
+ host: () => ({
309
+ id: `switchboard@${hostname()}`,
310
+ label: hostname()
311
+ }),
312
+ oauthAttempt: (_parent, args, ctx) => runtime.oauthAttempt(args.state, ctx),
313
+ triggerStates: async (_parent, _args, ctx) => (await runtime.triggerStates(ctx)).map((row) => ({
314
+ workflowId: row.workflow_id,
315
+ pieceName: row.piece_name,
316
+ triggerName: row.trigger_name,
317
+ status: row.status,
318
+ intervalMs: row.interval_ms,
319
+ nextPollAt: row.next_poll_at,
320
+ lastPollAt: row.last_poll_at,
321
+ lastError: row.last_error,
322
+ consecutiveFailures: row.consecutive_failures,
323
+ nextRenewAt: row.next_renew_at,
324
+ renewError: row.renew_error,
325
+ renewFailures: row.renew_failures,
326
+ pieceVersion: row.piece_version,
327
+ pieceSource: row.piece_source,
328
+ versionMatch: row.version_match,
329
+ versionNote: row.version_note
330
+ })),
331
+ runs: async (_parent, args, ctx, info) => (await runtime.runs({
332
+ ...args,
333
+ withStepData: readsStepData(info, [])
334
+ }, ctx)).map((record) => toRunRecord(record.row, record.steps)),
335
+ runsPage: async (_parent, args, ctx, info) => {
336
+ const { paging, ...scope } = args;
337
+ const page = await cursorAware(() => runtime.runsPage({
338
+ ...scope,
339
+ limit: paging?.limit ?? void 0,
340
+ cursor: paging?.cursor ?? null,
341
+ withStepData: readsStepData(info, ["items"])
342
+ }, ctx));
343
+ return {
344
+ items: page.records.map((record) => toRunRecord(record.row, record.steps)),
345
+ hasNextPage: page.hasNextPage,
346
+ hasPreviousPage: Boolean(paging?.cursor),
347
+ cursor: page.cursor
348
+ };
349
+ },
350
+ run: async (_parent, args, ctx) => {
351
+ const record = await runtime.run(args.id, ctx);
352
+ return record ? toRunRecord(record.row, record.steps) : null;
353
+ }
354
+ },
355
+ Mutation: { workflowRuntime: () => ({}) },
356
+ WorkflowRuntimeMutations: {
357
+ fire: (_parent, args, ctx) => runtime.fire(args.workflowId, args.payload, "manual", void 0, ctx),
358
+ pollNow: (_parent, args, ctx) => runtime.pollNow(args.workflowId, ctx),
359
+ testTrigger: (_parent, args, ctx) => syncAware(() => runtime.testTrigger(args.workflowId, ctx, {
360
+ ...args.payload !== void 0 ? { payload: args.payload } : {},
361
+ ...typeof args.timeoutSeconds === "number" ? { timeoutMs: args.timeoutSeconds * 1e3 } : {},
362
+ driveId: args.driveId ?? void 0
363
+ })),
364
+ cancelTriggerTest: (_parent, args, ctx) => runtime.cancelTriggerTestFor(args.workflowId, ctx),
365
+ testStep: (_parent, args, ctx) => syncAware(() => runtime.testStep(args.workflowId, args.stepId, ctx, { driveId: args.driveId ?? void 0 })),
366
+ rerun: (_parent, args, ctx) => runtime.rerun(args.runId, ctx),
367
+ createSecret: (_parent, args, ctx) => syncAware(() => runtime.createSecret({
368
+ value: args.value,
369
+ label: args.label ?? void 0,
370
+ ownerId: args.documentId
371
+ }, ctx)),
372
+ rotateSecret: (_parent, args, ctx) => runtime.rotateSecret(args.ref, args.value, ctx),
373
+ deleteSecret: async (_parent, args, ctx) => {
374
+ await runtime.deleteSecret(args.ref, ctx);
375
+ return true;
376
+ },
377
+ checkConnection: (_parent, args, ctx) => runtime.checkConnection(args.connectionId, ctx),
378
+ startOAuth: (_parent, args, ctx) => {
379
+ const returnUrl = returnUrlFor(args.returnUrl, ctx);
380
+ return runtime.startOAuth(args.connectionId, ctx, {
381
+ redirectUri: redirectUriFor(oauth, args.redirectUri),
382
+ ...returnUrl ? { returnUrl } : {}
383
+ });
384
+ }
385
+ },
386
+ SecretRecord: { manageable: (parent, _args, ctx) => runtime.canManageSecret(parent, ctx) }
387
+ };
388
+ };
389
+ //#endregion
390
+ //#region src/workflow/schema.ts
391
+ const schema = gql`
392
+ """
393
+ WorkflowRuntime Queries
394
+ """
395
+ type WorkflowRuntimeQueries {
396
+ health: String!
397
+ """
398
+ Whether this reactor enforces document auth (REACTOR_AUTH_ENFORCEMENT).
399
+ On, a workflow needs a signed publish, and the host grants, to reach
400
+ documents. Answered to any caller.
401
+ """
402
+ authEnforcement: Boolean!
403
+ """
404
+ Who this host signs as: grant it on each document a step writes. Null for
405
+ a caller who is not signed in, or a host with no signer.
406
+ """
407
+ reactorIdentity: ReactorIdentity
408
+ """
409
+ REACTOR_AUTH_CONDITIONS. True: grant the host by key, with
410
+ { match: subject.key == key }; false: by address. Null for a caller who
411
+ is not signed in.
412
+ """
413
+ authConditions: Boolean
414
+ """
415
+ Why the workflow's last publish or enable got no reactor access, naming
416
+ the publisher and the connection; null when the check passed.
417
+ """
418
+ reactorAccessDenial(workflowId: String!): String
419
+ """
420
+ Persisted runs, newest first. Scope them to one workflow, or to every
421
+ workflow a drive holds; workflowId wins when both are given.
422
+ """
423
+ runs(
424
+ workflowId: String
425
+ driveId: String
426
+ limit: Int
427
+ "Trigger kinds to leave out, e.g. test."
428
+ excludeTriggerKinds: [String!]
429
+ ): [WorkflowRunRecord!]!
430
+ """
431
+ The same listing a page at a time, newest journaled first. Pass a page's
432
+ cursor back in paging to read the next; a page is short only when
433
+ hasNextPage is false, or when the caller could read none of a long
434
+ stretch of runs. A run that starts between pages keeps its place.
435
+ """
436
+ runsPage(
437
+ workflowId: String
438
+ driveId: String
439
+ excludeTriggerKinds: [String!]
440
+ paging: WorkflowRunsPagingInput
441
+ ): WorkflowRunResultPage!
442
+ run(id: String!): WorkflowRunRecord
443
+ """
444
+ The descriptor (props, auth, ports) of one action or trigger, as the
445
+ version that runs it describes it; triggers come back under "trigger".
446
+ """
447
+ blockDescriptor(block: BlockInput!): Unknown
448
+ """
449
+ Resolves a dynamic prop against the current config values: a DROPDOWN
450
+ yields { options, placeholder, disabled }, a DYNAMIC prop yields the
451
+ resolved sub-property descriptor list.
452
+ """
453
+ blockOptions(
454
+ block: BlockInput!
455
+ propName: String!
456
+ input: Unknown
457
+ connectionId: String
458
+ "What the author typed, for a DROPDOWN declared with refreshOnSearch."
459
+ searchValue: String
460
+ "The step's reactor connection; its filter narrows what the resolver reads."
461
+ reactorConnectionId: String
462
+ ): Unknown
463
+ """
464
+ Every piece this reactor offers: the core piece, its package pieces, and
465
+ the pieces the registry and Activepieces publish.
466
+ """
467
+ pieceCatalog: Unknown
468
+ """
469
+ A piece's actions at one version; pin a step to that version.
470
+ """
471
+ pieceActions(
472
+ packageName: String!
473
+ "That version; the installed or latest one when omitted."
474
+ version: String
475
+ ): Unknown
476
+ """
477
+ A piece's triggers at one version; pin a trigger to that version.
478
+ """
479
+ pieceTriggers(
480
+ packageName: String!
481
+ "That version; the installed or latest one when omitted."
482
+ version: String
483
+ ): Unknown
484
+ """
485
+ Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.
486
+ """
487
+ pieceDetail(
488
+ packageName: String!
489
+ "That version; the installed or latest one when omitted."
490
+ version: String
491
+ ): Unknown
492
+ """
493
+ Piece and block search across the catalog, grouped by piece. The index
494
+ builds lazily on first use; poll while status is "indexing".
495
+ """
496
+ searchPieces(
497
+ query: String!
498
+ "action | trigger"
499
+ kind: String!
500
+ "local | registry | activepieces; all when omitted."
501
+ sources: [String!]
502
+ "Category ids, any of; all when omitted."
503
+ categories: [String!]
504
+ "Pieces returned."
505
+ limit: Int
506
+ ): PieceSearchResult!
507
+ """
508
+ Health of every registered piece trigger (poll schedule, errors).
509
+ """
510
+ triggerStates: [TriggerStateRecord!]!
511
+ """
512
+ Authored output shape of a block (SDL / outputSchema / sampleData).
513
+ """
514
+ blockOutputTree(block: BlockInput!, config: Unknown): Unknown
515
+ """
516
+ Output shape of a draft step or trigger: its latest test output
517
+ (source "test", with sample and testedAt) when tested, else as blockOutputTree.
518
+ """
519
+ stepOutputTree(workflowId: String!, stepId: String!): Unknown
520
+ """
521
+ Every block of the draft (trigger first) as this reactor resolves it:
522
+ which piece version runs, from where, and how it matches the pin.
523
+ """
524
+ blockResolutions(workflowId: String!): [BlockResolutionRecord!]!
525
+ """
526
+ Every powerhouse/connection document, for connection pickers.
527
+ """
528
+ connections: [ConnectionRecord!]!
529
+ """
530
+ The webhook endpoint for a workflow: the URL to hand the provider. Minted
531
+ on first ask, whether or not the workflow is armed — an author needs the
532
+ URL before enabling, and the armed field carries that difference. Null
533
+ only when the host has no webhook service. With driveId, a workflow not
534
+ synced here yet is waited for briefly, then fails as WORKFLOW_SYNCING.
535
+ """
536
+ webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
537
+ """
538
+ Secret metadata (label, version, status). Never the value. Only secrets
539
+ whose owning document the caller can read.
540
+ """
541
+ secret(ref: String!): SecretRecord
542
+ secrets: [SecretRecord!]!
543
+ """
544
+ The URL an OAuth2 app must register as its redirect. A bare path when
545
+ this host does not know its public origin; resolve it against the URL
546
+ this API is reached at. Null when the host serves no HTTP routes.
547
+ """
548
+ oauthRedirectUri: String
549
+ """
550
+ The switchboard this runtime lives in: what an app records as the runner
551
+ of the workflows and connections it sets up here.
552
+ """
553
+ host: RuntimeHost!
554
+ """
555
+ How an OAuth2 sign-in opened by startOAuth stands; null when unknown.
556
+ """
557
+ oauthAttempt(state: String!): OAuthAttempt
558
+ }
559
+
560
+ type RuntimeHost {
561
+ "switchboard@<machine>: what apps record as the runner"
562
+ id: String!
563
+ "The machine's name, for people: where a sign-in has to happen"
564
+ label: String!
565
+ }
566
+
567
+ type OAuthAttempt {
568
+ connectionId: String!
569
+ "PENDING | EXCHANGING | OK | ERROR"
570
+ status: String!
571
+ error: String
572
+ }
573
+
574
+ type OAuthStart {
575
+ state: String!
576
+ "Where to send the user to sign in."
577
+ authorizationUrl: String!
578
+ redirectUri: String!
579
+ expiresAt: String!
580
+ }
581
+
582
+ """
583
+ One action or trigger of a piece, as a workflow pins it. The engine's own
584
+ blocks are the piece @powerhousedao/piece-core.
585
+ """
586
+ input BlockInput {
587
+ pieceName: String!
588
+ "Exact semver."
589
+ pieceVersion: String!
590
+ "The action or trigger name."
591
+ name: String!
592
+ "action | trigger"
593
+ kind: String!
594
+ }
595
+
596
+ type BlockSearchHit {
597
+ pieceName: String!
598
+ "The version the hit is listed at; pin to it when picking the block."
599
+ pieceVersion: String!
600
+ "The action or trigger name."
601
+ name: String!
602
+ pieceDisplayName: String!
603
+ logoUrl: String!
604
+ displayName: String!
605
+ description: String!
606
+ "action | trigger"
607
+ kind: String!
608
+ "Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL"
609
+ strategy: String
610
+ "Why this block cannot run on this reactor; null when it can."
611
+ unsupported: String
612
+ }
613
+
614
+ type BlockResolutionRecord {
615
+ "The trigger's or step's id."
616
+ stepId: String!
617
+ pieceName: String!
618
+ "The version the block pins."
619
+ pieceVersion: String!
620
+ "The action or trigger name."
621
+ name: String!
622
+ "action | trigger"
623
+ kind: String!
624
+ "The version that runs; null when nothing resolves."
625
+ resolvedVersion: String
626
+ "local | registry | activepieces | npm; null when nothing resolves."
627
+ source: String
628
+ "exact | compatible | fallback | installed | missing"
629
+ match: String!
630
+ "Why the version that runs differs from the pin, or why nothing resolves."
631
+ note: String
632
+ "The newest version any source offers."
633
+ latestVersion: String
634
+ }
635
+
636
+ type PieceSearchMatch {
637
+ pieceName: String!
638
+ pieceVersion: String!
639
+ displayName: String!
640
+ description: String!
641
+ logoUrl: String!
642
+ categories: [String!]!
643
+ "local | registry | activepieces"
644
+ source: String!
645
+ deprecated: Boolean
646
+ "Why no block of the piece can run on this reactor."
647
+ unsupported: String
648
+ "Every query token matched the piece's own name."
649
+ namedPiece: Boolean!
650
+ "Matching blocks of the kind asked for, best first."
651
+ blocks: [BlockSearchHit!]!
652
+ }
653
+
654
+ type PieceSearchResult {
655
+ "ready | indexing | error"
656
+ status: String!
657
+ pieces: [PieceSearchMatch!]!
658
+ indexedPieces: Int!
659
+ error: String
660
+ }
661
+
662
+ type SecretRecord {
663
+ ref: String!
664
+ label: String
665
+ "The document the secret resolves for; null for a host secret (an OAuth app's)."
666
+ ownerId: String
667
+ "Whether the caller may rotate or delete it: its creator, able to write its owner."
668
+ manageable: Boolean!
669
+ version: Int!
670
+ status: String!
671
+ createdAt: String!
672
+ updatedAt: String!
673
+ }
674
+
675
+ type ConnectionRecord {
676
+ id: String!
677
+ name: String!
678
+ connectorId: String!
679
+ authType: String!
680
+ status: String!
681
+ accountLabel: String
682
+ }
683
+
684
+ type ReactorIdentity {
685
+ "The address the host signs as; null without a signed-in identity."
686
+ address: String
687
+ "The did:key that signs the host's operations."
688
+ key: String!
689
+ }
690
+
691
+ type ConnectionCheckResult {
692
+ ok: Boolean!
693
+ detail: String
694
+ """
695
+ From auth.getConnectionIdentifier when the check passes; otherwise the
696
+ label the connection already holds.
697
+ """
698
+ accountLabel: String
699
+ }
700
+
701
+ type WebhookEndpointRecord {
702
+ workflowId: String!
703
+ url: String!
704
+ """
705
+ False when the host gave the webhook service no public origin, so the url
706
+ above is a bare path. Switchboard always gives one, falling back to
707
+ http://localhost:<port> when PUBLIC_URL is unset.
708
+ """
709
+ absoluteUrl: Boolean!
710
+ "True while the workflow is ENABLED with a valid webhook trigger"
711
+ armed: Boolean!
712
+ createdAt: String!
713
+ }
714
+
715
+ type TriggerStateRecord {
716
+ workflowId: String!
717
+ pieceName: String!
718
+ triggerName: String!
719
+ status: String!
720
+ intervalMs: Int!
721
+ nextPollAt: String
722
+ lastPollAt: String
723
+ lastError: String
724
+ consecutiveFailures: Int!
725
+ "When a webhook trigger next renews its subscription; null if it never does."
726
+ nextRenewAt: String
727
+ "The last failed renewal, kept apart from lastError, the poll's."
728
+ renewError: String
729
+ renewFailures: Int!
730
+ "The piece version the trigger armed with; null for a host-fed trigger."
731
+ pieceVersion: String
732
+ pieceSource: String
733
+ versionMatch: String
734
+ versionNote: String
735
+ }
736
+
737
+ type Query {
738
+ workflowRuntime: WorkflowRuntimeQueries!
739
+ }
740
+
741
+ type WorkflowStepRunRecord {
742
+ stepId: String!
743
+ stepKey: String!
744
+ pieceName: String!
745
+ "The action the step ran, or the trigger a trigger test sampled."
746
+ blockName: String!
747
+ status: String!
748
+ input: Unknown
749
+ output: Unknown
750
+ port: String
751
+ error: String
752
+ "The thrown error's name, e.g. ReactorAccessDeniedError."
753
+ errorName: String
754
+ startedAt: String
755
+ endedAt: String
756
+ "The piece version that ran; null for an unresolved block."
757
+ pieceVersion: String
758
+ "local | registry | activepieces | npm"
759
+ pieceSource: String
760
+ "exact | compatible | fallback | installed | missing"
761
+ versionMatch: String
762
+ "Why the version that ran differs from the pin."
763
+ versionNote: String
764
+ }
765
+
766
+ type WorkflowRunRecord {
767
+ id: String!
768
+ workflowId: String!
769
+ workflowName: String!
770
+ workflowVersion: Int!
771
+ triggerKind: String!
772
+ triggerPayload: Unknown
773
+ status: String!
774
+ error: String
775
+ errorName: String
776
+ "When the run began executing; a PENDING run's is when it was journaled."
777
+ startedAt: String!
778
+ endedAt: String
779
+ rerunOf: String
780
+ "How many warningNotes the run has; a run with any is not a plain success."
781
+ warnings: Int!
782
+ "Steps that ran a fallback piece version, edges on ports nothing emits."
783
+ warningNotes: [String!]!
784
+ steps: [WorkflowStepRunRecord!]!
785
+ }
786
+
787
+ input WorkflowRunsPagingInput {
788
+ "Page size; default 25, at most 100."
789
+ limit: Int
790
+ "The cursor of the previous page."
791
+ cursor: String
792
+ }
793
+
794
+ type WorkflowRunResultPage {
795
+ items: [WorkflowRunRecord!]!
796
+ hasNextPage: Boolean!
797
+ "True when the page was read after a cursor."
798
+ hasPreviousPage: Boolean!
799
+ "Resumes after this page's last run; null for an empty page."
800
+ cursor: String
801
+ }
802
+
803
+ type WorkflowStepRun {
804
+ stepId: String!
805
+ key: String!
806
+ pieceName: String!
807
+ blockName: String!
808
+ status: String!
809
+ input: Unknown
810
+ output: Unknown
811
+ port: String
812
+ error: String
813
+ errorName: String
814
+ }
815
+
816
+ type WorkflowRunPayload {
817
+ runId: String
818
+ status: String!
819
+ error: String
820
+ errorName: String
821
+ steps: [WorkflowStepRun!]!
822
+ }
823
+
824
+ type WorkflowStepTestResult {
825
+ "Null when the test never started, e.g. an upstream block is untested."
826
+ runId: String
827
+ """
828
+ SUCCEEDED | FAILED | INDETERMINATE. INDETERMINATE is neither: a host call
829
+ the block made timed out, so a write it asked for may well have landed.
830
+ Show it distinctly - it is not a confirmed pass.
831
+ """
832
+ status: String!
833
+ output: Unknown
834
+ error: String
835
+ errorName: String
836
+ durationMs: Int!
837
+ }
838
+
839
+ """
840
+ WorkflowRuntime Mutations
841
+ """
842
+ type WorkflowRuntimeMutations {
843
+ """
844
+ Fires a workflow's manual trigger (the core piece's) and runs it to completion.
845
+ """
846
+ fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!
847
+ """
848
+ Runs the workflow's trigger now, as its schedule or poll would: a
849
+ schedule fires the workflow, a polling trigger polls its source ("sync
850
+ now"). False when it has no armed trigger (disabled, parked, erroring).
851
+ """
852
+ pollNow(workflowId: String!): Boolean!
853
+ """
854
+ Samples the draft trigger and saves it as the trigger's last test. A piece
855
+ trigger runs its test hook (no cursor changes). Of the core piece's
856
+ triggers, manual takes payload, schedule samples a fire now, and webhook
857
+ waits for the next delivery to the workflow's endpoint, up to
858
+ timeoutSeconds (default and cap 300), and that delivery runs nothing.
859
+ """
860
+ testTrigger(
861
+ workflowId: String!
862
+ payload: Unknown
863
+ timeoutSeconds: Int
864
+ driveId: String
865
+ ): Unknown
866
+ """
867
+ Stops a webhook trigger test that is waiting; false when none was.
868
+ """
869
+ cancelTriggerTest(workflowId: String!): Boolean!
870
+ """
871
+ Runs one draft step against the latest test outputs of the blocks it
872
+ reads, journaled as a "test" run and noted as the step's lastTest.
873
+ driveId waits for an unsynced workflow, as for webhookEndpoint.
874
+ """
875
+ testStep(
876
+ workflowId: String!
877
+ stepId: String!
878
+ driveId: String
879
+ ): WorkflowStepTestResult!
880
+ """
881
+ Resumes a FAILED run: succeeded steps replay from the journal,
882
+ execution restarts at the failure. Produces a new run.
883
+ """
884
+ rerun(runId: String!): WorkflowRunPayload!
885
+ """
886
+ Mints a managed secret for a connection or workflow document and returns
887
+ its ref; only that document resolves it. The value is stored encrypted
888
+ and is never readable back over any API.
889
+ """
890
+ createSecret(
891
+ value: String!
892
+ label: String
893
+ documentId: String!
894
+ ): SecretRecord!
895
+ """
896
+ Replaces the value behind an existing ref; documents stay untouched.
897
+ Only its creator, while able to write its owning document.
898
+ """
899
+ rotateSecret(ref: String!, value: String!): SecretRecord!
900
+ """
901
+ Tombstones a secret; its value becomes unrecoverable. Only its creator,
902
+ while able to write its owning document.
903
+ """
904
+ deleteSecret(ref: String!): Boolean!
905
+ """
906
+ Runs the piece's auth.validate against the connection's credentials,
907
+ then auth.getConnectionIdentifier for the account label, and records the
908
+ outcome on the connection document.
909
+ """
910
+ checkConnection(connectionId: String!): ConnectionCheckResult!
911
+ """
912
+ Opens an OAuth2 sign-in with the connection's own app (client_id in its
913
+ config, client_secret in its secretRefs). redirectUri is needed only when
914
+ oauthRedirectUri is a bare path. With returnUrl, which must be on the
915
+ caller's origin, the callback sends the browser back there with
916
+ ?ph_oauth=<state> instead of closing the window.
917
+ """
918
+ startOAuth(
919
+ connectionId: String!
920
+ redirectUri: String
921
+ returnUrl: String
922
+ ): OAuthStart!
923
+ }
924
+
925
+ type Mutation {
926
+ workflowRuntime: WorkflowRuntimeMutations!
927
+ }
928
+ `;
929
+ //#endregion
930
+ //#region src/workflow/subgraph.ts
931
+ /** The runtime's read/write surface. The runtime itself is composed by the
932
+ * host, so the subgraph only serves what it is handed. */
933
+ function createWorkflowRuntimeSubgraph(runtime, oauth, access) {
934
+ return class WorkflowRuntimeSubgraph extends BaseSubgraph {
935
+ name = "workflow-runtime";
936
+ typeDefs = schema;
937
+ resolvers = getResolvers(runtime, oauth, access, (documentId, ctx) => this.assertCanRead(documentId, ctx));
938
+ additionalContextFields = {};
939
+ };
940
+ }
941
+ //#endregion
942
+ //#region src/workflow-runtime.mts
943
+ /** The npm name the workflow package owns: its HTTP namespace and its models. */
944
+ const WORKFLOW_PACKAGE_NAME = "@powerhousedao/workflow";
945
+ const WORKFLOW_TELEMETRY_SCOPE = "@powerhousedao/reactor-workflow";
946
+ const SINGLETON_LOST = {
947
+ status: "unavailable",
948
+ reason: "workflow-singleton-lost"
949
+ };
950
+ async function assertWorkflowPackageLoadable(load = () => import("@powerhousedao/workflow/document-models")) {
951
+ try {
952
+ await load();
953
+ } catch (error) {
954
+ throw new Error(`Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`, { cause: error });
955
+ }
956
+ }
957
+ /**
958
+ * Whether a composition failure was the workflow singleton refusing this
959
+ * process, rather than something that should take the boot down.
960
+ *
961
+ * Matched by NAME: the engine loads lazily, and importing it here for the
962
+ * constructor would defeat that. The fields the engine's error carries are
963
+ * typed optional for the same reason.
964
+ */
965
+ function isWorkflowSingletonConflict(error) {
966
+ return error instanceof Error && error.name === "WorkflowSingletonConflictError";
967
+ }
968
+ /**
969
+ * Retries the singleton claim for a host that booted without it, and hands
970
+ * the runtime over once a claim succeeds.
971
+ *
972
+ * Without it a rolling deploy whose slots have different owner names ends
973
+ * with nobody running workflows: the new pod is refused while the old one
974
+ * still holds the lease, and nothing retries once the old pod releases it.
975
+ * Only for a host that never composed; one that lost the lease after
976
+ * composing stays without workflows until it restarts.
977
+ */
978
+ function retryWorkflowSingleton(options) {
979
+ const intervalMs = options.intervalMs ?? 2e4;
980
+ let stopped = false;
981
+ let timer;
982
+ let attempt;
983
+ const run = async () => {
984
+ let workflows;
985
+ try {
986
+ workflows = await options.compose();
987
+ } catch (error) {
988
+ if (!isWorkflowSingletonConflict(error)) options.logger.error("Composing the workflow runtime after the singleton came free failed: @error", error);
989
+ schedule();
990
+ return;
991
+ }
992
+ if (stopped) {
993
+ await workflows.stop();
994
+ return;
995
+ }
996
+ options.logger.info("Claimed the workflow singleton after boot; starting the workflow runtime");
997
+ try {
998
+ await options.onComposed(workflows);
999
+ } catch (error) {
1000
+ options.logger.error("Starting the workflow runtime after the singleton came free failed: @error", error);
1001
+ schedule();
1002
+ }
1003
+ };
1004
+ const schedule = () => {
1005
+ if (stopped) return;
1006
+ timer = setTimeout(() => {
1007
+ timer = void 0;
1008
+ attempt = run().finally(() => {
1009
+ attempt = void 0;
1010
+ });
1011
+ }, intervalMs);
1012
+ timer.unref();
1013
+ };
1014
+ schedule();
1015
+ return { async stop() {
1016
+ stopped = true;
1017
+ if (timer) clearTimeout(timer);
1018
+ timer = void 0;
1019
+ await attempt?.catch(() => void 0);
1020
+ } };
1021
+ }
1022
+ /**
1023
+ * What a host does once its composed runtime has shut down for losing the
1024
+ * workflow singleton.
1025
+ *
1026
+ * Taken over by another claim: that process runs workflows now, so this one
1027
+ * stays without them until it restarts. Unrenewable with no takeover seen (a
1028
+ * database blip): nothing else runs them, so the process goes down through
1029
+ * the fatal shutdown and its supervisor restarts it, which re-claims at boot.
1030
+ * A host with no fatal shutdown installed (embedded) stays without workflows
1031
+ * and says a restart is needed.
1032
+ */
1033
+ function workflowSingletonLossHandler(logger, fatal = triggerFatalShutdown) {
1034
+ return (loss) => {
1035
+ if (loss.reason === "taken") {
1036
+ logger.error(`Another process ("${loss.heldBy ?? "unknown"}") took the workflow singleton. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted; everything else serves normally.`);
1037
+ return;
1038
+ }
1039
+ const error = /* @__PURE__ */ new Error(`The workflow singleton lease could not be renewed for ${Math.round(loss.silentMs)}ms; no other process was seen taking it over`);
1040
+ if (fatal("Workflow singleton lease unrenewable", error)) return;
1041
+ logger.error(`${error.message}. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted.`);
1042
+ };
1043
+ }
1044
+ function modelManifestSource(builder) {
1045
+ return {
1046
+ modelManifest: () => builder.getResolvedModelManifest() ?? [],
1047
+ modelEntries: (documentType) => builder.getImportableEntries(documentType)
1048
+ };
1049
+ }
1050
+ function readAssertion(authorizationService, reactorClient) {
1051
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
1052
+ const hostCanRead = async (identifier, ctx) => {
1053
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
1054
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1055
+ let documentId;
1056
+ try {
1057
+ documentId = await resolveCanonical(identifier);
1058
+ } catch {
1059
+ throw new ForbiddenError();
1060
+ }
1061
+ if (!await authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
1062
+ };
1063
+ return async (identifier, caller) => {
1064
+ const ctx = caller;
1065
+ await hostCanRead(identifier, ctx);
1066
+ let served;
1067
+ try {
1068
+ served = await reactorClient.isServed(identifier, { subject: callerSubject(ctx.user) });
1069
+ } catch {
1070
+ throw new ForbiddenError();
1071
+ }
1072
+ if (!served) throw new ForbiddenError("to read this document");
1073
+ };
1074
+ }
1075
+ /** The same, for a design-time call that writes what it names. */
1076
+ function writeAssertion(authorizationService, reactorClient) {
1077
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
1078
+ return async (identifier, caller) => {
1079
+ const ctx = caller;
1080
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
1081
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1082
+ let documentId;
1083
+ try {
1084
+ documentId = await resolveCanonical(identifier);
1085
+ } catch {
1086
+ throw new ForbiddenError();
1087
+ }
1088
+ if (!await authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write this document");
1089
+ };
1090
+ }
1091
+ /** What the reactor enforces and who it signs as; unknown counts as enforced. */
1092
+ function reactorAccessOf(clientModule) {
1093
+ const flags = clientModule?.reactorModule?.featureFlags;
1094
+ const signer = clientModule?.signer;
1095
+ const key = signer?.app?.key;
1096
+ const identity = key ? {
1097
+ address: signer.user?.address ?? null,
1098
+ key
1099
+ } : null;
1100
+ return {
1101
+ authEnforcement: flags ? flags.authEnforcement : true,
1102
+ authConditions: flags?.authConditions === true,
1103
+ identity
1104
+ };
1105
+ }
1106
+ /**
1107
+ * A piece's read of a read-model index, run in process as the run's user
1108
+ * through the same GraphQL manager that serves the index over HTTP. The
1109
+ * request's caller is the run user's address on the host's own network and
1110
+ * chain, what a Renown bearer for that address would carry; the index's
1111
+ * access declarations decide from the address.
1112
+ *
1113
+ * A run with no user (its publish was unsigned or host-signed) is refused
1114
+ * before this under enforcement. With enforcement off the host acts for such
1115
+ * a run already, signing its writes with its own key, so its index reads are
1116
+ * the host's too: the request's caller is the host's signed-in address. A
1117
+ * host with no signed-in identity reads anonymously, which the
1118
+ * authenticated-caller floor refuses as it would an anonymous HTTP request.
1119
+ */
1120
+ function indexQueryFor(manager, clientModule) {
1121
+ const signer = clientModule?.signer;
1122
+ const host = signer?.user;
1123
+ const hostKey = signer?.app?.key ?? "";
1124
+ const chainId = host?.chainId ?? 1;
1125
+ const networkId = host?.networkId ?? "eip155";
1126
+ return async (request, runUser) => {
1127
+ const user = runUser ? {
1128
+ address: runUser.address,
1129
+ chainId,
1130
+ networkId,
1131
+ appKey: runUser.subject.key ?? hostKey
1132
+ } : host?.address ? {
1133
+ address: host.address,
1134
+ chainId,
1135
+ networkId,
1136
+ appKey: hostKey
1137
+ } : void 0;
1138
+ const result = await manager.executeSubgraph(request.subgraph, {
1139
+ query: request.query,
1140
+ variables: request.variables,
1141
+ user
1142
+ });
1143
+ return {
1144
+ data: result.data ?? null,
1145
+ ...result.errors ? { errors: result.errors.map((e) => ({ message: e.message })) } : {}
1146
+ };
1147
+ };
1148
+ }
1149
+ /** Whom a run's created documents also grant: the host, as §8 grants it. */
1150
+ function hostPrincipalOf(access) {
1151
+ const identity = access.identity;
1152
+ if (!identity) return void 0;
1153
+ if (access.authConditions) return { match: { eq: [{ attr: "subject.key" }, { lit: identity.key }] } };
1154
+ return identity.address ? { address: identity.address } : void 0;
1155
+ }
1156
+ /** Who the host signs as, so a publish it signs makes no run user. */
1157
+ function hostIdentityOf(access) {
1158
+ const identity = access.identity;
1159
+ if (!identity) return void 0;
1160
+ return identity.address ? {
1161
+ address: identity.address,
1162
+ key: identity.key
1163
+ } : { key: identity.key };
1164
+ }
1165
+ const REFERENCE_INDEX_RETRIES = 8;
1166
+ const REFERENCE_INDEX_RETRY_MS = 250;
1167
+ /** A step reads an attachment the way the download route serves one: when the
1168
+ * run's user may read a document that references it. The candidates are the
1169
+ * documents the run was handed; the reference index can trail the operation
1170
+ * that fired the trigger, so a denial is retried briefly. */
1171
+ function attachmentReadPolicy(access, retryMs = REFERENCE_INDEX_RETRY_MS) {
1172
+ return async (request) => {
1173
+ try {
1174
+ if (parseRef(request.ref).version !== 1) return false;
1175
+ } catch {
1176
+ return false;
1177
+ }
1178
+ if (!access || request.documentIds.length === 0) return false;
1179
+ const subject = request.runUser?.subject;
1180
+ const caller = {
1181
+ ...subject?.address ? { userAddress: subject.address } : {},
1182
+ ...subject?.key ? { appKey: subject.key } : {}
1183
+ };
1184
+ for (let attempt = 0; attempt <= REFERENCE_INDEX_RETRIES; attempt++) {
1185
+ for (const documentId of request.documentIds) if ((await access.canReadAttachment({
1186
+ documentId,
1187
+ attachmentRef: request.ref,
1188
+ ...caller
1189
+ })).kind === "allowed") return true;
1190
+ if (attempt < REFERENCE_INDEX_RETRIES) await new Promise((resolve) => setTimeout(resolve, retryMs));
1191
+ }
1192
+ return false;
1193
+ };
1194
+ }
1195
+ async function registerWorkflowTriggersReadModel(engine, runtime, clientModule, registration) {
1196
+ const reactorModule = clientModule?.reactorModule;
1197
+ if (!reactorModule) return {
1198
+ status: "unavailable",
1199
+ reason: "in-process-reactor-module-unavailable"
1200
+ };
1201
+ const coordinator = reactorModule.readModelCoordinator;
1202
+ if (!supportsLiveReadModelRegistration(coordinator)) return {
1203
+ status: "unavailable",
1204
+ reason: "live-read-model-registration-unsupported"
1205
+ };
1206
+ const readModel = new engine.WorkflowTriggersReadModel(reactorModule.database.withSchema(REACTOR_SCHEMA), reactorModule.operationIndex, reactorModule.writeCache, reactorModule.processorManagerConsistencyTracker, runtime);
1207
+ await readModel.init();
1208
+ if (registration.tornDown) return SINGLETON_LOST;
1209
+ coordinator.addReadModel(readModel, engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE);
1210
+ registration.detach = () => coordinator.removeReadModel(readModel);
1211
+ return { status: "available" };
1212
+ }
1213
+ function bindPackagePieces(registry, source) {
1214
+ const apply = (byPackage) => {
1215
+ registry.setPieces([...byPackage.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([, pieces]) => pieces));
1216
+ };
1217
+ apply(source.getPieces());
1218
+ source.onPiecesChange(apply);
1219
+ }
1220
+ async function composeWorkflowRuntime(deps) {
1221
+ const load = deps.load ?? (() => import("@powerhousedao/reactor-workflow"));
1222
+ let engine;
1223
+ try {
1224
+ engine = await load();
1225
+ } catch (error) {
1226
+ throw new Error("Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded", { cause: error });
1227
+ }
1228
+ const loss = { lost: false };
1229
+ const lease = deps.singletonLease === false ? void 0 : await engine.acquireWorkflowSingletonLease({
1230
+ relationalDb: deps.relationalDb,
1231
+ logger: deps.logger,
1232
+ ...deps.storageId ? { storageId: deps.storageId } : {},
1233
+ selfFence: deps.exclusiveJournal !== true,
1234
+ onLost: (lost) => {
1235
+ loss.lost = true;
1236
+ if (lost.reason === "taken") loss.heldBy = lost.heldBy;
1237
+ loss.tearDown?.();
1238
+ if (loss.composed) deps.onSingletonLost?.(lost);
1239
+ }
1240
+ });
1241
+ try {
1242
+ const composed = await composeClaimed(engine, deps, lease, loss);
1243
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
1244
+ loss.composed = true;
1245
+ return composed;
1246
+ } catch (error) {
1247
+ loss.tearDown?.();
1248
+ await lease?.release();
1249
+ throw error;
1250
+ }
1251
+ }
1252
+ function singletonLostError(engine, loss, lease) {
1253
+ return new engine.WorkflowSingletonConflictError(loss.heldBy ?? "unknown", "unknown", lease?.owner ?? "unknown");
1254
+ }
1255
+ async function composeClaimed(engine, deps, lease, loss) {
1256
+ engine.setPieceRegistryUrl(deps.pieceRegistryUrl);
1257
+ if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);
1258
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
1259
+ const access = reactorAccessOf(deps.clientModule);
1260
+ const models = deps.models;
1261
+ const runtime = engine.createWorkflowRuntime({
1262
+ relationalDb: deps.relationalDb,
1263
+ secretsKeyFile: deps.secretsKeyFile,
1264
+ ...deps.oauthApps?.length ? { oauthApps: deps.oauthApps } : {},
1265
+ reactorClient: deps.reactorClient,
1266
+ assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),
1267
+ subjectOf: (caller) => callerSubject(caller.user),
1268
+ assertCanWrite: writeAssertion(deps.authorizationService, deps.reactorClient),
1269
+ ...deps.clientModule?.reactorModule ? { authEnforcement: access.authEnforcement } : {},
1270
+ hostPrincipal: hostPrincipalOf(access),
1271
+ hostIdentity: hostIdentityOf(access),
1272
+ ...deps.indexQueries ? { queryIndex: indexQueryFor(deps.indexQueries, deps.clientModule) } : {},
1273
+ ...models ? {
1274
+ modelManifest: () => models.modelManifest(),
1275
+ modelEntries: (documentType) => models.modelEntries(documentType)
1276
+ } : {},
1277
+ webhooks: deps.webhooks,
1278
+ attachments: deps.attachments,
1279
+ canReadAttachmentRef: attachmentReadPolicy(deps.attachmentAccess),
1280
+ logger: deps.logger,
1281
+ ...deps.reactorThreads ? { reactorThreads: deps.reactorThreads } : {},
1282
+ ...deps.telemetry ? { telemetry: deps.telemetry } : {}
1283
+ });
1284
+ const routes = {};
1285
+ const registration = { tornDown: false };
1286
+ const tearDown = () => {
1287
+ if (registration.tornDown) return;
1288
+ registration.tornDown = true;
1289
+ routes.oauthCallback?.dispose();
1290
+ runtime.shutdown();
1291
+ registration.detach?.();
1292
+ };
1293
+ loss.tearDown = tearDown;
1294
+ const triggers = await registerWorkflowTriggersReadModel(engine, runtime, deps.clientModule, registration);
1295
+ if (registration.tornDown) throw singletonLostError(engine, loss, lease);
1296
+ if (triggers.status === "available") deps.logger.info(`Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`);
1297
+ else deps.logger.error("Workflow document triggers are NOT armed (@reason): this reactor's read-model coordinator takes no live registration, so no document operation reaches the runtime. Webhook and schedule triggers are unaffected.", triggers.reason);
1298
+ let stopped = false;
1299
+ if (deps.http) routes.oauthCallback = registerOAuthCallback(deps.http, runtime);
1300
+ return {
1301
+ subgraph: createWorkflowRuntimeSubgraph(runtime, deps.http ? { callbackUrl: callbackUrlOf(deps.http) } : void 0, access),
1302
+ get triggers() {
1303
+ return loss.lost ? SINGLETON_LOST : triggers;
1304
+ },
1305
+ ...lease ? { singletonOwner: lease.owner } : {},
1306
+ async start() {
1307
+ if (registration.tornDown) return;
1308
+ await runtime.registerWebhookEndpoint();
1309
+ if (loss.lost || stopped) return;
1310
+ runtime.startTriggerSupervisor();
1311
+ runtime.warmPieceSearch();
1312
+ },
1313
+ async stop() {
1314
+ if (stopped) return;
1315
+ stopped = true;
1316
+ tearDown();
1317
+ await lease?.release();
1318
+ }
1319
+ };
1320
+ }
1321
+ //#endregion
1322
+ //#region src/plugins/workflows.mts
1323
+ /** The drive app Workflow Studio registers under (packages/workflow). */
1324
+ const WORKFLOW_STUDIO_EDITOR_ID = "workflow-studio";
1325
+ /** The drive the plugin seeds unless the entry says otherwise. */
1326
+ const DEFAULT_WORKFLOWS_DRIVE = {
1327
+ slug: "workflows",
1328
+ name: "Workflows"
1329
+ };
1330
+ const workflowsDriveSchema = z.strictObject({
1331
+ /** The seeding key and the served `/d/<slug>` path (default "workflows"). */
1332
+ slug: z.string().min(1).optional(),
1333
+ /** Display name (default "Workflows"). */
1334
+ name: z.string().min(1).optional(),
1335
+ /** Fixed id; without one the id is project-hashed like classic `ph vetra`
1336
+ * (`workflows-<sha256(projectPath)[0:8]>`, slug unchanged), so existing
1337
+ * stores keep theirs. `projectHash: true` hashes the served slug as well. */
1338
+ id: z.string().min(1).optional(),
1339
+ projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
1340
+ icon: z.string().optional()
1341
+ });
1342
+ const workflowsPluginConfigSchema = z.strictObject({
1343
+ /** The Workflows drive to seed; `false` runs the runtime without one. */
1344
+ drive: z.union([workflowsDriveSchema, z.literal(false)]).optional() });
1345
+ /** The drive declaration the entry config amounts to (host-core's
1346
+ * DriveDeclaration shape; kept structural here to avoid the import cycle the
1347
+ * Contributions type documents). `undefined` when `drive: false`. */
1348
+ function workflowsDriveDeclaration(config) {
1349
+ if (config.drive === false) return void 0;
1350
+ const drive = config.drive ?? {};
1351
+ return {
1352
+ slug: drive.slug ?? DEFAULT_WORKFLOWS_DRIVE.slug,
1353
+ name: drive.name ?? DEFAULT_WORKFLOWS_DRIVE.name,
1354
+ preferredEditor: WORKFLOW_STUDIO_EDITOR_ID,
1355
+ ...drive.id !== void 0 ? { id: drive.id } : { projectHash: drive.projectHash ?? "id" },
1356
+ ...drive.icon !== void 0 ? { icon: drive.icon } : {}
1357
+ };
1358
+ }
1359
+ function createWorkflowsPlugin(rawConfig = {}) {
1360
+ const drive = workflowsDriveDeclaration(workflowsPluginConfigSchema.parse(rawConfig ?? {}));
1361
+ return {
1362
+ name: "switchboard-workflows",
1363
+ appliesTo: "switchboard",
1364
+ configSchema: workflowsPluginConfigSchema,
1365
+ contributions: { drives: drive ? [drive] : [] },
1366
+ hooks: {
1367
+ transformServerOptions: (options) => {
1368
+ const current = options.workflows;
1369
+ if (current?.enabled === false) return options;
1370
+ return {
1371
+ ...options,
1372
+ workflows: {
1373
+ ...current,
1374
+ enabled: true
1375
+ }
1376
+ };
1377
+ },
1378
+ onSubgraphsRegistering: async (ctx) => {
1379
+ const orchestration = ctx.workflowsOrchestration;
1380
+ if (!orchestration?.enabled) return;
1381
+ const logger = ctx.logger;
1382
+ const lateSubgraphs = ctx.lateSubgraphs;
1383
+ let workflows;
1384
+ let workflowsRetry;
1385
+ try {
1386
+ workflows = await orchestration.composeWorkflows();
1387
+ } catch (error) {
1388
+ if (!isWorkflowSingletonConflict(error)) throw error;
1389
+ logger.warn(`Workflows are enabled but another live process ("${error.owner ?? "unknown"}") holds the workflow singleton until ${error.expiresAt ?? "unknown"}. This Switchboard has booted WITHOUT the workflow runtime: no trigger of any kind fires here, and the workflow GraphQL face is absent. Everything else serves normally. Stop the other owner, or set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the slot that owns workflows. This Switchboard retries the claim and starts workflows once the lease comes free.`);
1390
+ workflowsRetry = retryWorkflowSingleton({
1391
+ compose: orchestration.composeWorkflows,
1392
+ onComposed: async (composed) => {
1393
+ try {
1394
+ await composed.start();
1395
+ } catch (error) {
1396
+ try {
1397
+ await composed.stop();
1398
+ } catch (stopError) {
1399
+ logger.error("Stopping the late workflow runtime failed: @error", stopError);
1400
+ }
1401
+ throw error;
1402
+ }
1403
+ logger.info("Workflow runtime started");
1404
+ ctx.workflows = composed;
1405
+ await orchestration.registerWorkflowSubgraph(composed);
1406
+ try {
1407
+ await orchestration.updateRouter();
1408
+ } catch (error) {
1409
+ orchestration.reportMountFailure(error);
1410
+ }
1411
+ },
1412
+ logger
1413
+ });
1414
+ }
1415
+ ctx.workflowsRetry = workflowsRetry;
1416
+ if (workflows) {
1417
+ ctx.workflows = workflows;
1418
+ lateSubgraphs.push(orchestration.registerWorkflowSubgraph(workflows));
1419
+ await workflows.start();
1420
+ logger.info("Workflow runtime started");
1421
+ orchestration.setWorkflowsFact();
1422
+ }
1423
+ },
1424
+ onShutdown: async (ctx) => {
1425
+ await ctx.workflowsRetry?.stop();
1426
+ await ctx.workflows?.stop();
1427
+ }
1428
+ }
1429
+ };
1430
+ }
1431
+ /** The default-config instance: the built-in composition's entry. */
1432
+ const workflowsPlugin = createWorkflowsPlugin({});
1433
+ //#endregion
1434
+ export { workflowsPlugin as a, WORKFLOW_TELEMETRY_SCOPE as c, isWorkflowSingletonConflict as d, modelManifestSource as f, triggerFatalShutdown as g, installFatalErrorShutdown as h, workflowsDriveDeclaration as i, assertWorkflowPackageLoadable as l, workflowSingletonLossHandler as m, WORKFLOW_STUDIO_EDITOR_ID as n, workflowsPluginConfigSchema as o, retryWorkflowSingleton as p, createWorkflowsPlugin as r, WORKFLOW_PACKAGE_NAME as s, DEFAULT_WORKFLOWS_DRIVE as t, composeWorkflowRuntime as u };
1435
+
1436
+ //# sourceMappingURL=workflows-COM3MKfD.mjs.map
1437
+ //# debugId=d8a311a1-42a7-5207-856f-5c3b1614ae75