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

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