@powerhousedao/reactor-workflow 6.2.3-dev.100

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["logger","up","clientAuth","action","trigger","logger","logger","parseScheduleConfig","parseSharedSchedule","ReactorJobPendingError","otelContext","up","trim","logger","performance","logger","logger","targetOf","parseScheduleConfig","asRecord","logger","connectionActions","ReactorAccessDeniedError","parseScheduleConfig","workflowActions","SUBFLOWS_PIECE","CALL_FLOW_ACTION","workflowUtils","workflowReducer"],"sources":["../src/pieces/activepieces/piece-versions.ts","../src/reactor/attachment-port.ts","../src/reactor/package-name.ts","../src/reactor/id-token.ts","../src/reactor/oauth.ts","../src/reactor/reactor-piece.ts","../src/reactor/output-tree.ts","../src/reactor/unsupported-pieces.ts","../src/reactor/piece-catalog.ts","../src/reactor/local-catalog.ts","../src/reactor/block-search.ts","../src/reactor/block-resolver.ts","../src/reactor/run-scope.ts","../src/reactor/piece-store-port.ts","../src/reactor/connector-id.ts","../src/reactor/runnable.ts","../src/reactor/lib.ts","../src/reactor/schedule.ts","../src/reactor/sync-wait.ts","../src/reactor/reactor-errors.ts","../src/reactor/run-user.ts","../src/reactor/reactor-access.ts","../src/reactor/run-scope-builder.ts","../src/reactor/run-scoped-client.ts","../src/reactor/reactor-session.ts","../src/reactor/core-blocks.ts","../src/reactor/secret-store.ts","../src/reactor/variables.ts","../src/reactor/step-test.ts","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js","../src/reactor/policy.ts","../src/reactor/waitpoint-types.ts","../src/reactor/store.ts","../src/reactor/park-state.ts","../src/reactor/subflows.ts","../src/reactor/run-cursor.ts","../src/reactor/waitpoint-poller.ts","../src/reactor/run-gate.ts","../src/reactor/shutdown.ts","../src/reactor/run-dispatcher.ts","../src/reactor/event-loop.ts","../src/reactor/run-retention.ts","../src/reactor/trigger-binding.ts","../src/reactor/trigger-supervisor.ts","../src/reactor/webhook.ts","../src/reactor/piece-handshake.ts","../src/reactor/trigger-filters.ts","../src/reactor/oauth-apps.ts","../src/reactor/service.ts","../src/reactor/singleton-lease.ts","../src/reactor/workflow-triggers-read-model.ts"],"sourcesContent":["// Which versions of a piece each remote source can serve.\nimport { npmRegistryBaseUrl } from \"./fetch.js\";\nimport { pieceRegistrySource } from \"./registry-source.js\";\n\nexport type VersionListing =\n | { kind: \"listed\"; versions: string[] }\n // The source answered and has no such piece.\n | { kind: \"absent\" }\n | { kind: \"unreachable\"; detail: string };\n\ninterface Cached {\n value: VersionListing;\n expiresAt: number;\n}\n\n// Short: a publish should show up without a restart, and an absent piece is\n// asked for again soon, since a retried trigger may be waiting on its publish\nconst LISTED_TTL_MS = 5 * 60_000;\nconst ABSENT_TTL_MS = 30_000;\nconst DEFAULT_TIMEOUT_MS = 5_000;\n\nconst cache = new Map<string, Cached>();\nconst inFlight = new Map<string, Promise<VersionListing>>();\n\n/** Test seam: forget every listing. */\nexport function clearVersionListings(): void {\n cache.clear();\n}\n\nasync function listing(\n key: string,\n load: () => Promise<VersionListing>,\n fresh: boolean,\n): Promise<VersionListing> {\n const cached = cache.get(key);\n if (!fresh && cached && cached.expiresAt > Date.now()) return cached.value;\n const pending = inFlight.get(key);\n if (pending) return pending;\n const started = load()\n .then((value) => {\n // An unreachable source is no answer, so it is never remembered.\n if (value.kind !== \"unreachable\") {\n const ttl = value.kind === \"listed\" ? LISTED_TTL_MS : ABSENT_TTL_MS;\n cache.set(key, { value, expiresAt: Date.now() + ttl });\n }\n return value;\n })\n .finally(() => inFlight.delete(key));\n inFlight.set(key, started);\n return started;\n}\n\nasync function getJson(\n url: string,\n timeoutMs: number,\n headers?: Record<string, string>,\n): Promise<{ status: number; body: unknown }> {\n const response = await fetch(url, {\n signal: AbortSignal.timeout(timeoutMs),\n ...(headers ? { headers } : {}),\n });\n const body: unknown = await response.json().catch(() => undefined);\n return { status: response.status, body };\n}\n\nfunction unreachable(url: string, error: unknown): VersionListing {\n const reason = error instanceof Error ? error.message : String(error);\n return { kind: \"unreachable\", detail: `${url}: ${reason}` };\n}\n\nexport interface ListingOptions {\n timeoutMs?: number;\n fresh?: boolean;\n}\n\n// GET <registry>/pieces/<name>/versions, newest first. Undefined without a registry.\nexport function registryVersions(\n name: string,\n options: ListingOptions = {},\n): Promise<VersionListing> | undefined {\n const source = pieceRegistrySource();\n if (!source) return undefined;\n const url = `${source.pieceUrl(name)}/versions`;\n return listing(\n `registry\\u0000${url}`,\n async () => {\n try {\n const { status, body } = await getJson(\n url,\n options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n );\n if (status === 404) return { kind: \"absent\" };\n if (status < 200 || status >= 300 || !Array.isArray(body)) {\n return unreachable(url, new Error(`responded ${status}`));\n }\n const versions = (body as { version?: unknown }[])\n .map((entry) => entry.version)\n .filter((version): version is string => typeof version === \"string\");\n return { kind: \"listed\", versions };\n } catch (error) {\n return unreachable(url, error);\n }\n },\n options.fresh === true,\n );\n}\n\n// The versions an npm packument lists, read in its abbreviated form.\nexport function npmVersions(\n name: string,\n options: ListingOptions = {},\n): Promise<VersionListing> {\n const url = `${npmRegistryBaseUrl()}/${name.replace(\"/\", \"%2f\")}`;\n return listing(\n `npm\\u0000${url}`,\n async () => {\n try {\n const { status, body } = await getJson(\n url,\n options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n { accept: \"application/vnd.npm.install-v1+json\" },\n );\n if (status === 404) return { kind: \"absent\" };\n const versions = (body as { versions?: unknown } | undefined)?.versions;\n if (status < 200 || status >= 300 || !versions) {\n return unreachable(url, new Error(`responded ${status}`));\n }\n return {\n kind: \"listed\",\n versions: Object.keys(versions as Record<string, unknown>),\n };\n } catch (error) {\n return unreachable(url, error);\n }\n },\n options.fresh === true,\n );\n}\n","// Adapts the reactor's attachment client to the engine's AttachmentPort: both\n// directions go through the filesystem, so a step's bytes never cross the\n// worker's JSON IPC channel.\nimport type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type { AttachmentPort } from \"../pieces/index.js\";\nimport { FileTooLargeError, maxFileBytes } from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport { openAsBlob } from \"node:fs\";\nimport { open, rm } from \"node:fs/promises\";\n\nconst logger = childLogger([\"workflow\", \"attachments\"]);\n\n// The slice of the attachment client the engine uses, structural so hosts need\n// not install the attachments package; a type test pins it to IAttachmentClient.\nexport interface AttachmentClientLike {\n upload(input: {\n file: Blob;\n fileName?: string;\n mimeType?: string;\n signal?: AbortSignal;\n }): Promise<{ ref: string }>;\n // Streamed rather than materialized: the size limit has to refuse an\n // oversized attachment before its bytes are in this process's memory.\n download(input: {\n documentId: string;\n ref: AttachmentRef;\n signal?: AbortSignal;\n }): Promise<{\n header: { sizeBytes: number; mimeType: string; fileName: string };\n body: ReadableStream<Uint8Array>;\n }>;\n}\n\n// Writes the body out while counting it, so a stream that outgrows the limit\n// is cancelled mid-flight and its partial file removed.\nasync function writeCapped(\n body: ReadableStream<Uint8Array>,\n destPath: string,\n limit: number,\n): Promise<void> {\n const reader = body.getReader();\n const handle = await open(destPath, \"w\");\n let written = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n written += value.byteLength;\n if (written > limit) {\n await reader.cancel();\n throw new FileTooLargeError(written, limit);\n }\n await handle.write(value);\n }\n } catch (error) {\n await handle.close();\n await rm(destPath, { force: true });\n throw error;\n }\n await handle.close();\n}\n\nexport interface AttachmentPortAccess {\n // The workflow document a download is made under.\n documentIdFor: () => string | undefined;\n // Whether the running workflow may read the ref.\n canReadRef: (ref: string) => Promise<boolean>;\n // Told about every ref a step wrote, so the run may read it back.\n onWritten?: (ref: string) => void;\n}\n\nexport function createAttachmentPort(\n client: AttachmentClientLike,\n access: AttachmentPortAccess,\n): AttachmentPort {\n const authorize = async (ref: string): Promise<string> => {\n const documentId = access.documentIdFor();\n if (!documentId) {\n throw new Error(\n `Cannot resolve ${ref}: no workflow document is in scope to authorize the read`,\n );\n }\n if (!(await access.canReadRef(ref))) {\n throw new Error(\n `Cannot resolve ${ref}: workflow \"${documentId}\" may not read it`,\n );\n }\n return documentId;\n };\n return {\n async authorize(ref) {\n await authorize(ref);\n },\n\n async read(ref, destPath, signal) {\n const documentId = await authorize(ref);\n const limit = maxFileBytes();\n const { header, body } = await client.download({\n documentId,\n ref: ref as AttachmentRef,\n ...(signal ? { signal } : {}),\n });\n // The declared size refuses before a byte is read; writeCapped's own\n // count is what catches a header that understated the body.\n if (\n typeof header.sizeBytes === \"number\" &&\n Number.isFinite(header.sizeBytes) &&\n header.sizeBytes > limit\n ) {\n await body.cancel().catch(() => undefined);\n throw new FileTooLargeError(header.sizeBytes, limit);\n }\n await writeCapped(body, destPath, limit);\n const contentType = header.mimeType !== \"\" ? header.mimeType : undefined;\n return { fileName: header.fileName, contentType };\n },\n\n async write(file, signal) {\n // A file-backed Blob: hashed natively and streamed, never held in memory.\n const { ref } = await client.upload({\n file: await openAsBlob(file.path),\n fileName: file.fileName,\n mimeType: file.contentType ?? \"application/octet-stream\",\n ...(signal ? { signal } : {}),\n });\n access.onWritten?.(ref);\n logger.debug(`Ingested ${file.fileName} (${file.size} bytes) as ${ref}`);\n return ref;\n },\n };\n}\n","// The reactor package whose document models the runtime serves, and whose HTTP\n// namespace its webhook endpoints live under.\nexport const WORKFLOW_PACKAGE_NAME = \"@powerhousedao/workflow\";\n","// The account an OAuth2 connection signed in as, from the OpenID Connect ID\n// token in the provider's token response (asked for with the `openid email`\n// scopes). A fallback for pieces whose auth has no getConnectionIdentifier.\n//\n// The signature is not checked: the token came straight from the provider's\n// token endpoint over TLS, in answer to this runtime's own code exchange,\n// which OpenID Connect Core 1.0 §3.1.3.7 allows in place of validating it.\n// It only names the connection for people; nothing is authorised on it.\n\n/** The verified email in a connection auth's `data.id_token`, if there is one. */\nexport function idTokenEmail(auth: unknown): string | undefined {\n const data = (auth as { data?: unknown } | null | undefined)?.data;\n const token = (data as { id_token?: unknown } | null | undefined)?.id_token;\n if (typeof token !== \"string\") return undefined;\n const payload = token.split(\".\")[1];\n if (!payload) return undefined;\n let claims: { email?: unknown; email_verified?: unknown };\n try {\n claims = JSON.parse(\n Buffer.from(payload, \"base64url\").toString(\"utf8\"),\n ) as typeof claims;\n } catch {\n return undefined;\n }\n // Google sends email_verified; a provider that leaves it out is taken at its word.\n if (claims.email_verified === false || claims.email_verified === \"false\") {\n return undefined;\n }\n return typeof claims.email === \"string\" && claims.email !== \"\"\n ? claims.email\n : undefined;\n}\n","// OAuth2 authorization-code sign-in for connections that bring their own app:\n// pending attempts, the code exchange and token refresh.\nimport type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport {\n isPrivateAddress,\n parseAddress,\n type EgressPolicy,\n type OAuth2MethodDescriptor,\n type SecretOwner,\n type SecretStore,\n} from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport dns from \"node:dns\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport net from \"node:net\";\n\n// Names the connection's secretRefs and config use for the OAuth2 parts.\nexport const OAUTH_CLIENT_ID = \"client_id\";\nexport const OAUTH_CLIENT_SECRET = \"client_secret\";\nexport const OAUTH_TOKEN = \"token\";\n\nconst ATTEMPT_TTL_MS = 10 * 60 * 1000;\n// A claimed attempt still exchanges and checks past its expiry.\nconst EXCHANGE_GRACE_MS = 2 * 60 * 1000;\n// Refreshed this long before expiry, as Activepieces does; at most half a\n// short-lived token's lifetime, or it would be due the moment it is issued.\nconst REFRESH_MARGIN_S = 15 * 60;\nconst TOKEN_TIMEOUT_MS = 15_000;\nconst TOKEN_MAX_BYTES = 1024 * 1024;\n\nconst oauthLogger = childLogger([\"workflow\", \"oauth\"]);\n\nexport type OAuthAttemptStatus = \"PENDING\" | \"EXCHANGING\" | \"OK\" | \"ERROR\";\n\nexport interface OAuthAttemptRow {\n state: string;\n connection_id: string;\n client_id: string;\n // Null for a sign-in through a relay: the relay holds the secret.\n client_secret_ref: string | null;\n code_verifier: string | null;\n redirect_uri: string;\n token_url: string;\n authorization_method: string | null;\n return_url: string | null;\n // Lower-cased address of who started it; null when anonymous.\n created_by: string | null;\n status: OAuthAttemptStatus;\n error: string | null;\n created_at: string;\n expires_at: string;\n}\n\ninterface OAuthDB {\n oauth_attempt: OAuthAttemptRow;\n}\n\n// The token set stored as one secret; only the host writes it.\nexport interface OAuthTokenSet {\n access_token: string;\n refresh_token?: string;\n token_type: string;\n expires_in?: number;\n // Unix seconds the token was issued at.\n claimed_at: number;\n scope?: string;\n token_url: string;\n authorization_method?: \"HEADER\" | \"BODY\";\n redirect_url: string;\n // The client that obtained the token, when it came from the host's app\n // registry rather than the connection: a refresh must use the same client.\n client_id?: string;\n client_secret_ref?: string;\n // Obtained through an app's relay: token_url is the relay's, and a refresh\n // sends it client_id and no secret, which only the relay holds.\n relayed?: true;\n // The provider's whole token response; pieces read fields off it.\n data: Record<string, unknown>;\n}\n\nexport class OAuthError extends Error {\n constructor(\n message: string,\n // The provider's own error code (RFC 6749 §5.2), when it answered with one.\n readonly code?: string,\n ) {\n super(message);\n this.name = \"OAuthError\";\n }\n}\n\n// The provider no longer accepts the connection's sign-in: its refresh token\n// is expired or revoked (invalid_grant), or the stored token is unreadable.\n// Only signing in again fixes it, so it is recorded on the connection.\nexport class OAuthSignInRefusedError extends OAuthError {\n constructor(message: string, code?: string) {\n super(message, code);\n this.name = \"OAuthSignInRefused\";\n }\n}\n\n// What a refresh refused this way tells the host, to record on the connection.\nexport type SignInRefusedListener = (\n connectionId: string,\n error: OAuthSignInRefusedError,\n) => Promise<void>;\n\nasync function up(db: IRelationalDb<OAuthDB>): Promise<void> {\n await db.schema\n .createTable(\"oauth_attempt\")\n .addColumn(\"state\", \"text\", (col) => col.primaryKey())\n .addColumn(\"connection_id\", \"text\", (col) => col.notNull())\n .addColumn(\"client_id\", \"text\", (col) => col.notNull())\n .addColumn(\"client_secret_ref\", \"text\")\n .addColumn(\"code_verifier\", \"text\")\n .addColumn(\"redirect_uri\", \"text\", (col) => col.notNull())\n .addColumn(\"token_url\", \"text\", (col) => col.notNull())\n .addColumn(\"authorization_method\", \"text\")\n .addColumn(\"return_url\", \"text\")\n .addColumn(\"created_by\", \"text\")\n .addColumn(\"status\", \"text\", (col) => col.notNull())\n .addColumn(\"error\", \"text\")\n .addColumn(\"created_at\", \"text\", (col) => col.notNull())\n .addColumn(\"expires_at\", \"text\", (col) => col.notNull())\n .ifNotExists()\n .execute();\n // Additive migration for namespaces created before attempts had a caller.\n try {\n await db.schema\n .alterTable(\"oauth_attempt\")\n .addColumn(\"created_by\", \"text\")\n .execute();\n } catch {\n // column already exists\n }\n // Nullable since relayed sign-ins hold no client secret; a no-op on a\n // table created that way.\n await db.schema\n .alterTable(\"oauth_attempt\")\n .alterColumn(\"client_secret_ref\", (col) => col.dropNotNull())\n .execute();\n}\n\n// `{name}` placeholders in a provider URL, filled from the connection's props.\nexport function fillOAuthUrl(\n template: string,\n props: Record<string, unknown>,\n): string {\n const filled = template.replace(/\\{(\\w+)\\}/g, (_match, name: string) => {\n const value = props[name];\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n throw new OAuthError(`Set \"${name}\" before connecting`);\n }\n return encodeURIComponent(String(value));\n });\n let url: URL;\n try {\n url = new URL(filled);\n } catch {\n throw new OAuthError(`\"${filled}\" is not a valid URL`);\n }\n return url.href;\n}\n\nfunction base64url(bytes: Buffer): string {\n return bytes.toString(\"base64url\");\n}\n\nexport interface StartOAuthInput {\n connectionId: string;\n method: OAuth2MethodDescriptor;\n props: Record<string, unknown>;\n clientId: string;\n /** Null when a relay exchanges the code and holds the secret. */\n clientSecretRef: string | null;\n redirectUri: string;\n /** Replaces the piece's token URL: a relay's. */\n tokenUrl?: string;\n returnUrl?: string;\n /** Replaces the piece's scopes: the connection asks for exactly these. */\n scopes?: string[];\n /** Always PKCE, whatever the piece says: a desktop client cannot keep its secret. */\n pkce?: boolean;\n /**\n * Appended to the state after a dot: a relay reads where to forward the\n * provider's answer from it. The whole string stays the attempt's key.\n */\n stateSuffix?: string;\n createdBy?: string | null;\n}\n\nexport interface OAuthStart {\n state: string;\n authorizationUrl: string;\n redirectUri: string;\n expiresAt: string;\n}\n\nexport interface OAuthAttemptView {\n connectionId: string;\n status: OAuthAttemptStatus;\n error: string | null;\n returnUrl: string | null;\n}\n\nexport class OAuthAttemptStore {\n private constructor(private readonly db: IRelationalDb<OAuthDB>) {}\n\n static async create(relationalDb: IRelationalDb): Promise<OAuthAttemptStore> {\n const db = (await relationalDb.createNamespace(\n \"oauth\",\n )) as IRelationalDb<OAuthDB>;\n await up(db);\n return new OAuthAttemptStore(db);\n }\n\n async start(input: StartOAuthInput): Promise<OAuthStart> {\n const now = new Date();\n // Finished and abandoned attempts are kept a day, so a late poll still answers.\n await this.db\n .deleteFrom(\"oauth_attempt\")\n .where(\n \"expires_at\",\n \"<\",\n new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),\n )\n .execute();\n\n const { method } = input;\n const nonce = base64url(randomBytes(32));\n const state = input.stateSuffix ? `${nonce}.${input.stateSuffix}` : nonce;\n const pkce = method.pkce === true || input.pkce === true;\n const verifier = pkce ? base64url(randomBytes(48)) : null;\n const authUrl = new URL(fillOAuthUrl(method.authUrl, input.props));\n const params = authUrl.searchParams;\n params.set(\"response_type\", \"code\");\n params.set(\"client_id\", input.clientId);\n params.set(\"redirect_uri\", input.redirectUri);\n params.set(\"state\", state);\n const scope = input.scopes ?? method.scope;\n if (scope.length > 0) params.set(\"scope\", scope.join(\" \"));\n // Activepieces' defaults: without them Google issues no refresh token.\n params.set(\"access_type\", \"offline\");\n const prompt = method.prompt ?? \"consent\";\n if (prompt !== \"omit\") params.set(\"prompt\", prompt);\n if (verifier) {\n const plain = method.pkceMethod === \"plain\";\n params.set(\n \"code_challenge\",\n plain\n ? verifier\n : base64url(createHash(\"sha256\").update(verifier).digest()),\n );\n params.set(\"code_challenge_method\", plain ? \"plain\" : \"S256\");\n }\n for (const [key, value] of Object.entries(method.extra ?? {})) {\n params.set(key, value);\n }\n\n const expiresAt = new Date(now.getTime() + ATTEMPT_TTL_MS).toISOString();\n await this.db\n .insertInto(\"oauth_attempt\")\n .values({\n state,\n connection_id: input.connectionId,\n client_id: input.clientId,\n client_secret_ref: input.clientSecretRef,\n code_verifier: verifier,\n redirect_uri: input.redirectUri,\n token_url: input.tokenUrl ?? fillOAuthUrl(method.tokenUrl, input.props),\n authorization_method: method.authorizationMethod ?? null,\n return_url: input.returnUrl ?? null,\n created_by: input.createdBy?.toLowerCase() ?? null,\n status: \"PENDING\",\n error: null,\n created_at: now.toISOString(),\n expires_at: expiresAt,\n })\n .execute();\n return {\n state,\n authorizationUrl: authUrl.href,\n redirectUri: input.redirectUri,\n expiresAt,\n };\n }\n\n async view(state: string): Promise<OAuthAttemptView | undefined> {\n const row = await this.db\n .selectFrom(\"oauth_attempt\")\n .selectAll()\n .where(\"state\", \"=\", state)\n .executeTakeFirst();\n if (!row) return undefined;\n // An exchange still EXCHANGING well past expiry died with its process.\n const deadline =\n Date.parse(row.expires_at) +\n (row.status === \"EXCHANGING\" ? EXCHANGE_GRACE_MS : 0);\n const unfinished = row.status === \"PENDING\" || row.status === \"EXCHANGING\";\n const expired = unfinished && deadline < Date.now();\n return {\n connectionId: row.connection_id,\n status: expired ? \"ERROR\" : row.status,\n error: expired ? \"The sign-in expired before it finished\" : row.error,\n returnUrl: row.return_url,\n };\n }\n\n // Takes a pending attempt for its one exchange. Undefined when it is\n // unknown, expired or already taken, so a replayed callback does nothing.\n // RETURNING, not numUpdatedRows: the knex-backed dialect reports no count.\n claim(state: string): Promise<OAuthAttemptRow | undefined> {\n return this.db\n .updateTable(\"oauth_attempt\")\n .set({ status: \"EXCHANGING\" })\n .where(\"state\", \"=\", state)\n .where(\"status\", \"=\", \"PENDING\")\n .where(\"expires_at\", \">\", new Date().toISOString())\n .returningAll()\n .executeTakeFirst();\n }\n\n async finish(state: string, error: string | null): Promise<void> {\n await this.db\n .updateTable(\"oauth_attempt\")\n .set({ status: error === null ? \"OK\" : \"ERROR\", error })\n .where(\"state\", \"=\", state)\n .execute();\n }\n}\n\n// ── token endpoint ─────────────────────────────────────────────────────────\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return net.isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\nfunction allowedAddresses(policy: EgressPolicy | undefined): net.BlockList {\n const list = new net.BlockList();\n for (const spec of policy?.allowAddresses ?? []) {\n const slash = spec.indexOf(\"/\");\n const ip = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!ip) continue;\n const family = familyOf(ip);\n const width = family === \"ipv6\" ? 128 : 32;\n list.addSubnet(\n ip,\n slash === -1 ? width : Number(spec.slice(slash + 1)),\n family,\n );\n }\n return list;\n}\n\n// POSTs a form to a token endpoint. The address is checked at connect time,\n// so a name that resolves to private space is refused as a piece's would be.\nexport async function postTokenForm(\n url: string,\n form: Record<string, string>,\n headers: Record<string, string>,\n egress?: EgressPolicy,\n): Promise<Record<string, unknown>> {\n const target = new URL(url);\n if (target.protocol !== \"https:\" && target.protocol !== \"http:\") {\n throw new OAuthError(`Token URL \"${url}\" is not http(s)`);\n }\n const allowed = allowedAddresses(egress);\n const named = (address: string) => {\n const ip = parseAddress(address);\n return ip !== undefined && allowed.check(ip, familyOf(ip));\n };\n // Plain http only reaches an address the operator named.\n const permitted = (address: string) =>\n named(address) ||\n (target.protocol === \"https:\" &&\n (egress?.allowPrivateAddresses === true || !isPrivateAddress(address)));\n const refused = (hostname: string) =>\n new OAuthError(`Token URL host \"${hostname}\" is not reachable from here`);\n // A literal IP never reaches the lookup below.\n const literal = parseAddress(target.hostname.replace(/^\\[|\\]$/g, \"\"));\n if (literal !== undefined && !permitted(literal)) {\n throw refused(target.hostname);\n }\n // Node asks for every address when it races IPv4 against IPv6.\n const lookup = ((\n hostname: string,\n options: dns.LookupOptions,\n callback: (\n error: Error | null,\n address: string | dns.LookupAddress[],\n family?: number,\n ) => void,\n ) => {\n dns.lookup(hostname, { ...options, all: true }, (error, addresses) => {\n if (error) return callback(error, []);\n const usable = addresses.filter((entry) => permitted(entry.address));\n if (usable.length === 0) return callback(refused(hostname), []);\n if (options.all) return callback(null, usable);\n callback(null, usable[0].address, usable[0].family);\n });\n }) as net.LookupFunction;\n\n const body = new URLSearchParams(form).toString();\n const client = target.protocol === \"https:\" ? https : http;\n const { status, contentType, text } = await new Promise<{\n status: number;\n contentType: string;\n text: string;\n }>((resolve, reject) => {\n const request = client.request(\n target,\n {\n method: \"POST\",\n lookup,\n timeout: TOKEN_TIMEOUT_MS,\n headers: {\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\",\n \"content-length\": Buffer.byteLength(body).toString(),\n ...headers,\n },\n },\n (response) => {\n const chunks: Buffer[] = [];\n let size = 0;\n response.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > TOKEN_MAX_BYTES) {\n request.destroy(new OAuthError(\"Token response is too large\"));\n return;\n }\n chunks.push(chunk);\n });\n response.on(\"end\", () =>\n resolve({\n status: response.statusCode ?? 0,\n contentType: String(response.headers[\"content-type\"] ?? \"\"),\n text: Buffer.concat(chunks).toString(\"utf8\"),\n }),\n );\n response.on(\"error\", reject);\n },\n );\n request.on(\"timeout\", () =>\n request.destroy(new OAuthError(\"Token endpoint timed out\")),\n );\n request.on(\"error\", reject);\n request.end(body);\n });\n\n let parsed: Record<string, unknown>;\n try {\n parsed = contentType.includes(\"application/x-www-form-urlencoded\")\n ? Object.fromEntries(new URLSearchParams(text))\n : (JSON.parse(text) as Record<string, unknown>);\n } catch {\n throw new OAuthError(\n `Token endpoint answered ${status} with a body that is not JSON`,\n );\n }\n // Some providers (Slack) answer 200 with { ok: false, error }.\n const error = parsed.error ?? (parsed.ok === false ? \"error\" : undefined);\n if (status < 200 || status >= 300 || error !== undefined) {\n const description =\n typeof parsed.error_description === \"string\"\n ? `: ${parsed.error_description}`\n : \"\";\n throw new OAuthError(\n `Token endpoint refused (${typeof error === \"string\" ? error : status})${description}`,\n typeof error === \"string\" ? error : undefined,\n );\n }\n if (typeof parsed.access_token !== \"string\") {\n throw new OAuthError(\"Token endpoint answered without an access_token\");\n }\n return parsed;\n}\n\nfunction clientAuth(\n method: \"HEADER\" | \"BODY\" | undefined,\n clientId: string,\n // Null for a relay, which adds the secret itself.\n clientSecret: string | null,\n): { form: Record<string, string>; headers: Record<string, string> } {\n if (clientSecret === null) {\n return { form: { client_id: clientId }, headers: {} };\n }\n if (method === \"HEADER\") {\n const basic = Buffer.from(`${clientId}:${clientSecret}`).toString(\"base64\");\n return { form: {}, headers: { authorization: `Basic ${basic}` } };\n }\n return {\n form: { client_id: clientId, client_secret: clientSecret },\n headers: {},\n };\n}\n\nfunction authorizationMethod(\n value: string | null | undefined,\n): \"HEADER\" | \"BODY\" | undefined {\n return value === \"HEADER\" || value === \"BODY\" ? value : undefined;\n}\n\nfunction tokenSetFrom(\n response: Record<string, unknown>,\n context: Pick<\n OAuthTokenSet,\n | \"token_url\"\n | \"authorization_method\"\n | \"redirect_url\"\n | \"client_id\"\n | \"client_secret_ref\"\n | \"relayed\"\n >,\n previous?: OAuthTokenSet,\n): OAuthTokenSet {\n const expires = Number(response.expires_in);\n const refresh =\n typeof response.refresh_token === \"string\"\n ? response.refresh_token\n : previous?.refresh_token;\n const scope =\n typeof response.scope === \"string\" ? response.scope : previous?.scope;\n return {\n access_token: response.access_token as string,\n ...(refresh ? { refresh_token: refresh } : {}),\n token_type:\n typeof response.token_type === \"string\" ? response.token_type : \"Bearer\",\n ...(Number.isFinite(expires) && expires > 0 ? { expires_in: expires } : {}),\n claimed_at: Math.round(Date.now() / 1000),\n ...(scope ? { scope } : {}),\n token_url: context.token_url,\n ...(context.authorization_method\n ? { authorization_method: context.authorization_method }\n : {}),\n redirect_url: context.redirect_url,\n ...((context.client_id ?? previous?.client_id)\n ? { client_id: context.client_id ?? previous?.client_id }\n : {}),\n ...((context.client_secret_ref ?? previous?.client_secret_ref)\n ? {\n client_secret_ref:\n context.client_secret_ref ?? previous?.client_secret_ref,\n }\n : {}),\n ...((context.relayed ?? previous?.relayed)\n ? { relayed: true as const }\n : {}),\n data: { ...previous?.data, ...response },\n };\n}\n\n// A relay's token URL is the host's configuration (workflows.oauthApps), not a\n// piece's: it may resolve to private space, e.g. a cluster that routes its own\n// domains internally. Still https only; plain http needs a named address.\nexport function relayEgress(egress?: EgressPolicy): EgressPolicy {\n return { ...egress, allowPrivateAddresses: true };\n}\n\n// A null clientSecret exchanges through a relay: client_id and the PKCE\n// verifier, no secret.\nexport async function exchangeCode(\n attempt: OAuthAttemptRow,\n code: string,\n clientSecret: string | null,\n egress?: EgressPolicy,\n fromRegistry = false,\n): Promise<OAuthTokenSet> {\n const method = authorizationMethod(attempt.authorization_method);\n const auth = clientAuth(method, attempt.client_id, clientSecret);\n const response = await postTokenForm(\n attempt.token_url,\n {\n grant_type: \"authorization_code\",\n code,\n redirect_uri: attempt.redirect_uri,\n ...(attempt.code_verifier\n ? { code_verifier: attempt.code_verifier }\n : {}),\n ...auth.form,\n },\n auth.headers,\n clientSecret === null ? relayEgress(egress) : egress,\n );\n return tokenSetFrom(response, {\n token_url: attempt.token_url,\n authorization_method: method,\n redirect_url: attempt.redirect_uri,\n ...(fromRegistry\n ? {\n client_id: attempt.client_id,\n ...(attempt.client_secret_ref\n ? { client_secret_ref: attempt.client_secret_ref }\n : {}),\n }\n : {}),\n ...(clientSecret === null ? { relayed: true as const } : {}),\n });\n}\n\nexport function parseTokenSet(value: string): OAuthTokenSet {\n const parsed = JSON.parse(value) as OAuthTokenSet;\n if (typeof parsed.access_token !== \"string\") {\n throw new OAuthSignInRefusedError(\n \"Stored OAuth2 token is malformed; reconnect\",\n );\n }\n return parsed;\n}\n\nexport function tokenExpired(\n tokens: OAuthTokenSet,\n nowSeconds: number,\n): boolean {\n if (tokens.expires_in === undefined) return false;\n return nowSeconds >= tokens.claimed_at + tokens.expires_in;\n}\n\nexport function tokenDue(tokens: OAuthTokenSet, nowSeconds: number): boolean {\n if (tokens.expires_in === undefined || !tokens.refresh_token) return false;\n const margin = Math.min(REFRESH_MARGIN_S, tokens.expires_in / 2);\n return nowSeconds >= tokens.claimed_at + tokens.expires_in - margin;\n}\n\n// What resolution needs from a connection to refresh its token.\nexport interface OAuthConnectionSource {\n config?: Record<string, unknown>;\n secretRefs?: { name: string; ref: string }[];\n}\n\nexport interface OAuthTokenRefresher {\n // Rotates the token secret in place when it is close to expiring. Secrets\n // are read as connectionId, so refs copied from another connection fail.\n refreshIfDue(\n source: OAuthConnectionSource,\n connectionId: string,\n ): Promise<void>;\n}\n\nexport class StoreTokenRefresher implements OAuthTokenRefresher {\n // One refresh per token in this process; the others wait on it.\n private readonly inFlight = new Map<string, Promise<void>>();\n\n constructor(\n private readonly secrets: () => Promise<SecretStore>,\n private readonly egress?: EgressPolicy,\n // Told when the provider refuses the sign-in itself, to record it.\n private readonly onSignInRefused?: SignInRefusedListener,\n ) {}\n\n refreshIfDue(\n source: OAuthConnectionSource,\n connectionId: string,\n ): Promise<void> {\n const refOf = (name: string) =>\n source.secretRefs?.find((entry) => entry.name === name)?.ref;\n const tokenRef = refOf(OAUTH_TOKEN);\n if (!tokenRef) return Promise.resolve();\n // A connection's own app, or (absent) the registry client the token set names.\n const secretRef = refOf(OAUTH_CLIENT_SECRET);\n const configId = source.config?.[OAUTH_CLIENT_ID];\n const own =\n secretRef && typeof configId === \"string\"\n ? { secretRef, clientId: configId }\n : undefined;\n let pending = this.inFlight.get(tokenRef);\n if (!pending) {\n const owner: SecretOwner = {\n documentId: connectionId,\n kind: \"connection\",\n };\n pending = this.refresh(tokenRef, own, owner).finally(() =>\n this.inFlight.delete(tokenRef),\n );\n this.inFlight.set(tokenRef, pending);\n }\n return pending;\n }\n\n private async refresh(\n tokenRef: string,\n own: { secretRef: string; clientId: string } | undefined,\n owner: SecretOwner,\n ): Promise<void> {\n const store = await this.secrets();\n const read = (ref: string) => store.get(ref, owner);\n let tokens: OAuthTokenSet;\n try {\n tokens = parseTokenSet(await read(tokenRef));\n } catch (error) {\n if (error instanceof OAuthSignInRefusedError) {\n await this.signInRefused(owner.documentId, error);\n }\n throw error;\n }\n if (!tokenDue(tokens, Math.round(Date.now() / 1000))) return;\n let auth: { form: Record<string, string>; headers: Record<string, string> };\n if (tokens.relayed) {\n // Through the relay it was obtained from, which adds the secret: the\n // refresh token belongs to the relay's client, whatever the config says now.\n if (!tokens.client_id) return;\n auth = clientAuth(undefined, tokens.client_id, null);\n } else {\n const clientId = own?.clientId ?? tokens.client_id;\n const secretRef = own?.secretRef ?? tokens.client_secret_ref;\n // No client to refresh with: the token is used until it expires.\n if (!clientId || !secretRef) return;\n auth = clientAuth(\n tokens.authorization_method,\n clientId,\n // A host app's client secret has no owner document.\n own ? await read(secretRef) : await store.get(secretRef, null),\n );\n }\n let response: Record<string, unknown>;\n try {\n response = await postTokenForm(\n tokens.token_url,\n {\n grant_type: \"refresh_token\",\n refresh_token: tokens.refresh_token!,\n ...auth.form,\n },\n auth.headers,\n tokens.relayed ? relayEgress(this.egress) : this.egress,\n );\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n const message = `Refreshing the OAuth2 token failed; reconnect: ${detail}`;\n // The provider refused the refresh token itself: the sign-in is over,\n // even while the stored token still works. A timeout or an outage is\n // not, and a later call retries it.\n const refused =\n error instanceof OAuthError && error.code === \"invalid_grant\"\n ? new OAuthSignInRefusedError(message, error.code)\n : undefined;\n if (refused) await this.signInRefused(owner.documentId, refused);\n // The stored token still works until it expires; a later call retries.\n if (!tokenExpired(tokens, Math.round(Date.now() / 1000))) {\n oauthLogger.warn(\n `Refreshing an OAuth2 token failed; using it until it expires: ${detail}`,\n );\n return;\n }\n throw refused ?? new OAuthError(message);\n }\n // A sign-in that landed meanwhile is newer than this refresh.\n const current = parseTokenSet(await read(tokenRef));\n if (\n current.access_token !== tokens.access_token ||\n current.claimed_at !== tokens.claimed_at\n ) {\n return;\n }\n await store.rotate(\n tokenRef,\n JSON.stringify(tokenSetFrom(response, tokens, tokens)),\n );\n }\n\n // A failure to record it leaves the run's own error to say it.\n private async signInRefused(\n connectionId: string,\n error: OAuthSignInRefusedError,\n ): Promise<void> {\n if (!this.onSignInRefused) return;\n try {\n await this.onSignInRefused(connectionId, error);\n } catch (cause) {\n oauthLogger.warn(\n `Recording the refused OAuth2 sign-in of connection ${connectionId} failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n }\n}\n","// The blocks of the piece this package ships.\n\n// The runtime knows these by name for two reasons only: the document triggers\n// are fired by the host rather than polled, and the output shape of a document\n// block depends on the model an author picked, which static piece metadata\n// cannot express. Everything else about them comes from the piece.\n\nimport { blockKey } from \"@powerhousedao/pieces-framework/block-type\";\n\nexport const REACTOR_PIECE = \"@powerhousedao/piece-reactor\";\n\n// Block keys, never written to a document: compare a block's blockKey().\n\nfunction action(name: string): string {\n return blockKey({ pieceName: REACTOR_PIECE, kind: \"action\", name });\n}\n\nfunction trigger(name: string): string {\n return blockKey({ pieceName: REACTOR_PIECE, kind: \"trigger\", name });\n}\n\nexport const DOCUMENT_CREATE_BLOCK = action(\"document-create\");\nexport const DOCUMENT_DISPATCH_BLOCK = action(\"document-dispatch\");\nexport const DOCUMENT_GET_BLOCK = action(\"document-get\");\nexport const DOCUMENT_FIND_BLOCK = action(\"document-find\");\nexport const DOCUMENT_SCHEMA_BLOCK = action(\"document-schema\");\nexport const DOCUMENT_TYPES_BLOCK = action(\"document-types\");\n\nexport const DOCUMENT_EVENT_BLOCK = trigger(\"document-event\");\nexport const DOCUMENT_CREATED_BLOCK = trigger(\"document-created\");\nexport const DOCUMENT_DELETED_BLOCK = trigger(\"document-deleted\");\n\n// A design-time value that can actually be resolved: an expression cannot, so\n// a tree built from one falls back to the block's static shape.\nexport function staticString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (!trimmed || trimmed.includes(\"{{\")) return undefined;\n return trimmed;\n}\n","// Authored output shapes for the {} expression picker: document-model SDL,\n// piece outputSchema/sampleData, and static shapes for core blocks.\nimport {\n DOCUMENT_REF_KEY,\n isDocumentRefMarker,\n manualInputTypeName,\n type DocumentReference,\n type ManualInput,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n Kind,\n parse,\n type FieldDefinitionNode,\n type InputValueDefinitionNode,\n type TypeNode,\n} from \"graphql\";\n\nexport interface OutputTreeNode {\n name: string;\n // Display type, e.g. \"String!\", \"OID\", \"array\", \"string (sample)\".\n type: string;\n description?: string;\n children?: OutputTreeNode[];\n}\n\nexport interface OutputTree {\n // \"test\": the block's latest test output, the picker's \"from test\" source.\n source: \"schema\" | \"sample\" | \"static\" | \"none\" | \"test\";\n nodes: OutputTreeNode[];\n // \"test\" only: the output itself, and when and in which run it was taken.\n sample?: unknown;\n testedAt?: string;\n runId?: string;\n}\n\nconst MAX_DEPTH = 6;\n\nfunction typeName(node: TypeNode): { name: string; display: string } {\n switch (node.kind) {\n case Kind.NON_NULL_TYPE: {\n const inner = typeName(node.type);\n return { name: inner.name, display: `${inner.display}!` };\n }\n case Kind.LIST_TYPE: {\n const inner = typeName(node.type);\n return { name: inner.name, display: `[${inner.display}]` };\n }\n default:\n return { name: node.name.value, display: node.name.value };\n }\n}\n\ntype FieldNode = FieldDefinitionNode | InputValueDefinitionNode;\n\n// The type a spec names for its root: `<Model>State` for the global state\n// (`<Model>GlobalState` also valid), `<Operation>Input` for an operation.\nexport type SdlRoot = { state: string } | { input: string };\n\n// Case- and separator-insensitive, so SET_URL matches SetUrlInput and SetURLInput.\nconst normalize = (name: string) =>\n name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\nfunction rootCandidates(root: SdlRoot): string[] {\n if (\"input\" in root) return [`${normalize(root.input)}input`];\n const model = normalize(root.state);\n return [`${model}state`, `${model}globalstate`];\n}\n\n// Field tree of the spec's root type (object or input), recursing into types\n// defined in the same SDL; unknown/scalar types are leaves.\nexport function fieldsFromSdl(sdl: string, root: SdlRoot): OutputTreeNode[] {\n let definitions;\n try {\n definitions = parse(sdl).definitions;\n } catch {\n return [];\n }\n const types = new Map<string, readonly FieldNode[]>();\n const byNormalized = new Map<string, string>();\n for (const def of definitions) {\n if (\n def.kind !== Kind.OBJECT_TYPE_DEFINITION &&\n def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION\n ) {\n continue;\n }\n const name = def.name.value;\n types.set(name, def.fields ?? []);\n if (!byNormalized.has(normalize(name))) {\n byNormalized.set(normalize(name), name);\n }\n }\n const rootName = rootCandidates(root)\n .map((candidate) => byNormalized.get(candidate))\n .find((name) => name !== undefined);\n if (!rootName) return [];\n\n const build = (name: string, depth: number): OutputTreeNode[] => {\n const fields = types.get(name);\n if (!fields || depth > MAX_DEPTH) return [];\n return fields.map((field) => {\n const { name: inner, display } = typeName(field.type);\n const children = build(inner, depth + 1);\n return {\n name: field.name.value,\n type: display,\n description: field.description?.value,\n ...(children.length > 0 ? { children } : {}),\n };\n });\n };\n return build(rootName, 0);\n}\n\ninterface ApOutputSchemaField {\n key?: string;\n label?: string;\n // Path into run()'s return value; defaults to key, \"\" means the whole output.\n value?: string;\n format?: string;\n description?: string;\n children?: ApOutputSchemaField[];\n properties?: ApOutputSchemaField[];\n listItems?: ApOutputSchemaField[];\n}\n\n// Nodes from separate fields can share a path prefix (a.b + a.c): merge them.\nfunction mergeNodes(nodes: OutputTreeNode[]): OutputTreeNode[] {\n const byName = new Map<string, OutputTreeNode>();\n for (const node of nodes) {\n const existing = byName.get(node.name);\n if (existing?.children && node.children) {\n existing.children = mergeNodes([...existing.children, ...node.children]);\n } else if (!byName.has(node.name)) {\n byName.set(node.name, node);\n }\n }\n return [...byName.values()];\n}\n\n// Activepieces action/trigger outputSchema → tree. Expression paths follow\n// each field's `value` (the real path into run()'s return), not its key.\nexport function fromOutputSchema(schema: unknown): OutputTreeNode[] {\n const fields = (schema as { fields?: ApOutputSchemaField[] } | null)?.fields;\n if (!Array.isArray(fields)) return [];\n const convert = (field: ApOutputSchemaField): OutputTreeNode[] => {\n const inner = field.children ?? field.properties;\n const items = field.listItems;\n const childNodes = mergeNodes((inner ?? items ?? []).flatMap(convert));\n const path =\n typeof field.value === \"string\" ? field.value : (field.key ?? \"\");\n // Whole-output field: hoist children; a scalar contributes no sub-path.\n if (path === \"\") return childNodes;\n const segments = path.split(\".\");\n let node: OutputTreeNode = {\n name: segments[segments.length - 1],\n type: items\n ? \"array\"\n : (field.format ?? (childNodes.length > 0 ? \"object\" : \"value\")),\n description: field.description,\n ...(childNodes.length > 0 ? { children: childNodes } : {}),\n };\n for (let i = segments.length - 2; i >= 0; i--) {\n node = { name: segments[i], type: \"object\", children: [node] };\n }\n return [node];\n };\n return mergeNodes(fields.flatMap(convert)).filter((node) => node.name);\n}\n\nexport function hasOutputSchemaFields(schema: unknown): boolean {\n const fields = (schema as { fields?: unknown[] } | null)?.fields;\n return Array.isArray(fields) && fields.length > 0;\n}\n\n// Piece-authored sampleData → tree; types inferred from the sample's values.\n// A journaled document reference becomes the nodes `documentNodes` gives.\nexport function fromSample(\n value: unknown,\n depth = 0,\n documentNodes?: (reference: DocumentReference) => OutputTreeNode[],\n): OutputTreeNode[] {\n if (value === null || typeof value !== \"object\" || depth > MAX_DEPTH) {\n return [];\n }\n const marker =\n documentNodes && isDocumentRefMarker(value)\n ? value[DOCUMENT_REF_KEY]\n : undefined;\n const entries = Array.isArray(value)\n ? value.slice(0, 1).map((item) => [\"0\", item] as const)\n : Object.entries(value as Record<string, unknown>).filter(\n ([name]) => !marker || name !== DOCUMENT_REF_KEY,\n );\n const nodes = entries.map(([name, child]) => {\n const kind = Array.isArray(child)\n ? \"array\"\n : child === null\n ? \"null\"\n : typeof child;\n const children = fromSample(child, depth + 1, documentNodes);\n return {\n name,\n type: kind,\n ...(children.length > 0 ? { children } : {}),\n };\n });\n return marker && documentNodes ? [...documentNodes(marker), ...nodes] : nodes;\n}\n\nconst leaf = (name: string, type: string, description?: string) => ({\n name,\n type,\n ...(description ? { description } : {}),\n});\n\nexport const OPERATION_NODE: OutputTreeNode = {\n name: \"operation\",\n type: \"object\",\n children: [leaf(\"index\", \"Int!\"), leaf(\"timestampUtcMs\", \"String!\")],\n};\n\n// A reactor document's header, as document-get and document-find return it.\nexport function documentHeaderNode(): OutputTreeNode {\n return {\n name: \"header\",\n type: \"object\",\n children: [\n leaf(\"id\", \"PHID!\"),\n leaf(\"documentType\", \"String!\"),\n leaf(\"name\", \"String\"),\n leaf(\"slug\", \"String\"),\n leaf(\"branch\", \"String!\"),\n leaf(\"revision\", \"JSONObject!\", \"Operation count per scope\"),\n leaf(\"createdAtUtcIso\", \"DateTime!\"),\n leaf(\"lastModifiedAtUtcIso\", \"DateTime!\"),\n ],\n };\n}\n\n// { header, state }; global state children come from the model's schema.\nexport function documentTree(\n globalChildren: OutputTreeNode[],\n): OutputTreeNode[] {\n return [\n documentHeaderNode(),\n {\n name: \"state\",\n type: \"object\",\n children: [\n {\n name: \"global\",\n type: \"object\",\n description: \"Document global state as read\",\n ...(globalChildren.length > 0 ? { children: globalChildren } : {}),\n },\n ],\n },\n ];\n}\n\n// What document-create and document-dispatch output.\nexport function documentReferenceTree(): OutputTreeNode[] {\n return [\n leaf(\"documentId\", \"PHID!\"),\n leaf(\"documentType\", \"String!\"),\n leaf(\"branch\", \"String!\"),\n leaf(\n \"revision\",\n \"JSONObject!\",\n \"Operation count per scope after the write\",\n ),\n ];\n}\n\nexport function documentFindTree(): OutputTreeNode[] {\n return [\n {\n name: \"results\",\n type: \"array\",\n children: [\n documentHeaderNode(),\n leaf(\"state\", \"JSONObject\", \"With Include state only\"),\n ],\n },\n leaf(\"nextCursor\", \"String\", \"Present while more documents match\"),\n ];\n}\n\n// An output tree as a value, its leaves the declared type names.\nexport function treeValue(nodes: OutputTreeNode[]): Record<string, unknown> {\n return Object.fromEntries(\n nodes.map((node) => [\n node.name,\n node.children ? treeValue(node.children) : node.type,\n ]),\n );\n}\n\nexport function documentTypesTree(): OutputTreeNode[] {\n return [\n leaf(\"count\", \"Int!\"),\n {\n name: \"types\",\n type: \"array\",\n children: [leaf(\"documentType\", \"String!\"), leaf(\"name\", \"String\")],\n },\n ];\n}\n\nexport function documentSchemaTree(): OutputTreeNode[] {\n return [\n leaf(\"documentType\", \"String!\"),\n leaf(\"name\", \"String\"),\n leaf(\"stateSchema\", \"String\", \"SDL of the global state type\"),\n {\n name: \"actions\",\n type: \"array\",\n description: \"Dispatchable actions with their input SDL\",\n children: [\n leaf(\"type\", \"String!\"),\n leaf(\"module\", \"String\"),\n leaf(\"inputSchema\", \"String\"),\n ],\n },\n ];\n}\n\nexport function lifecycleTriggerTree(): OutputTreeNode[] {\n return [\n leaf(\"documentId\", \"PHID!\"),\n leaf(\"documentType\", \"String\"),\n leaf(\"name\", \"String\", \"Set on creation only\"),\n leaf(\"driveId\", \"PHID\", \"Null for a document that belongs to no drive\"),\n leaf(\"parentId\", \"PHID\"),\n OPERATION_NODE,\n ];\n}\n\n// The core schedule trigger's payload; exactly one of cron / everyMs is present.\nexport function scheduleTriggerTree(): OutputTreeNode[] {\n return [\n leaf(\"scheduledFor\", \"DateTime!\", \"The slot that came due (ISO 8601)\"),\n leaf(\"firedAt\", \"DateTime!\", \"When the run actually started\"),\n leaf(\"timezone\", \"String!\"),\n leaf(\"cron\", \"String\", \"Cron mode only\"),\n leaf(\"everyMs\", \"Int\", \"Interval mode only\"),\n ];\n}\n\n// The core webhook trigger's payload: Activepieces' catch-webhook shape. Headers and query\n// are open maps, so they stay leaves the author addresses by name.\nexport function webhookTriggerTree(): OutputTreeNode[] {\n return [\n leaf(\"method\", \"String!\", \"Uppercase HTTP method\"),\n leaf(\"path\", \"String!\"),\n leaf(\"headers\", \"JSONObject!\", \"Lowercased names; credentials redacted\"),\n leaf(\"queryParams\", \"JSONObject!\"),\n leaf(\"body\", \"Unknown\", \"Parsed JSON or form fields; text otherwise\"),\n ];\n}\n\n// The core manual trigger's payload, one leaf per declared input.\nexport function manualTriggerTree(\n inputs: readonly ManualInput[],\n): OutputTreeNode[] {\n return inputs.map((input) =>\n leaf(input.name, manualInputTypeName(input), input.description),\n );\n}\n\nexport function documentEventTree(\n actionInputChildren: OutputTreeNode[],\n): OutputTreeNode[] {\n return [\n leaf(\"documentId\", \"PHID!\"),\n leaf(\"documentType\", \"String!\"),\n leaf(\"branch\", \"String!\"),\n leaf(\"scope\", \"String!\"),\n {\n name: \"action\",\n type: \"object\",\n children: [\n leaf(\"type\", \"String!\"),\n {\n name: \"input\",\n type: \"object\",\n ...(actionInputChildren.length > 0\n ? { children: actionInputChildren }\n : {}),\n },\n ],\n },\n OPERATION_NODE,\n ];\n}\n","// Pieces whose ACTIONS only run inside the Activepieces platform (ctx.server\n// AI proxy, or platform agents/todos/tables APIs). Hidden everywhere.\nexport const SERVER_ONLY_PIECES = new Set<string>([\n // Platform AI proxy (v1/ai-providers): no own auth, keys live server-side.\n \"@activepieces/piece-ai\",\n \"@activepieces/piece-text-ai\",\n \"@activepieces/piece-image-ai\",\n \"@activepieces/piece-utility-ai\",\n // AI proxy + platform agents API (ctx.agent.tools).\n \"@activepieces/piece-agent\",\n // Platform-feature APIs: todos, tables.\n \"@activepieces/piece-todos\",\n \"@activepieces/piece-tables\",\n]);\n","// Piece catalog proxied from the Activepieces public metadata API — the same\n// source their piece selector uses. Bundles themselves load lazily on use.\n\n// A Powerhouse registry, when a deployment allows one, answers the same three\n// endpoints and is read first; see pieces/activepieces/registry-source.ts.\n\nimport type {\n ActionBase,\n PieceMetadataModel,\n TriggerBase,\n} from \"@powerhousedao/pieces-framework\";\nimport type { Page } from \"@powerhousedao/shared/registry\";\nimport { childLogger } from \"document-model\";\nimport type { PieceAuthDescriptor } from \"../pieces/activepieces/descriptor.js\";\nimport { pieceRegistrySource } from \"../pieces/activepieces/registry-source.js\";\nimport {\n unsupportedAuth,\n unsupportedTrigger,\n type UnsupportedFeature,\n} from \"../pieces/activepieces/unsupported.js\";\nimport { SERVER_ONLY_PIECES } from \"./unsupported-pieces.js\";\n\nconst CATALOG_URL = \"https://cloud.activepieces.com/api/v1/pieces\";\n// A publish reaches the catalog within minutes; one exact version never changes\nconst CACHE_TTL_MS = 5 * 60 * 1000;\nconst PINNED_TTL_MS = 60 * 60 * 1000;\n// The registry's largest page; the cap bounds a registry that never ends\nconst REGISTRY_PAGE_SIZE = 50;\nconst REGISTRY_MAX_PAGES = 200;\n\nconst logger = childLogger([\"workflow\", \"piece-catalog\"]);\n\n// Their piece endpoints default to audience=human, which hides actions tagged\n// audience: \"ai\" -- atomics added for agents that would clutter their flow\n// builder (activepieces/activepieces#13960). We want the whole surface, the\n// way their own non-builder callers ask for it.\nexport function aiLast(audience: string | null): number {\n return audience === \"ai\" ? 1 : 0;\n}\n\nfunction pieceUrl(packageName: string, version?: string): string {\n const at = version ? `&version=${encodeURIComponent(version)}` : \"\";\n return `${CATALOG_URL}/${packageName}?audience=all${at}`;\n}\n\nfunction atVersion(url: string, version?: string): string {\n return version ? `${url}?version=${encodeURIComponent(version)}` : url;\n}\n\n// A listing field, set only for a block that cannot run here.\nexport function reasonOf(feature: UnsupportedFeature | undefined): {\n unsupported?: string;\n} {\n return feature ? { unsupported: feature.reason } : {};\n}\n\n// A descriptor's auth as clients read it: each method's refusal as its reason.\nexport function clientAuth(\n auth: PieceAuthDescriptor | PieceAuthDescriptor[] | undefined,\n): unknown {\n if (!auth) return null;\n const one = ({ unsupported, ...method }: PieceAuthDescriptor) => ({\n ...method,\n ...reasonOf(unsupported),\n });\n return Array.isArray(auth) ? auth.map(one) : one(auth);\n}\n\n// Where a listing came from: a reactor package, the Powerhouse registry, or\n// the Activepieces cloud catalog.\nexport type PieceSource = \"local\" | \"registry\" | \"activepieces\";\n\nexport interface PieceSummary {\n name: string;\n displayName: string;\n description: string;\n logoUrl: string;\n version: string;\n actionCount: number;\n triggerCount: number;\n categories: string[];\n source: PieceSource;\n // The piece's PieceAuth descriptor, verbatim; null when authless.\n auth: unknown;\n // Why no block of the piece can run here. Listed, so a\n // search explains the piece rather than silently missing it.\n unsupported?: string;\n // The publisher retired it; listed, but marked, so a search still finds it.\n deprecated?: boolean;\n // A package piece shadowing a published one: the version published.\n publishedVersion?: string;\n}\n\nexport interface PieceActionEntry {\n name: string;\n displayName: string;\n description: string;\n // \"human\" | \"ai\" | \"both\"; absent on most pieces, which means \"both\".\n audience: string | null;\n unsupported?: string;\n}\n\nexport interface PieceActionsResult {\n name: string;\n displayName: string;\n version: string;\n actions: PieceActionEntry[];\n auth: unknown;\n}\n\nexport interface PieceTriggerEntry {\n name: string;\n displayName: string;\n description: string;\n strategy: string;\n unsupported?: string;\n}\n\nexport interface PieceTriggersResult {\n name: string;\n displayName: string;\n version: string;\n triggers: PieceTriggerEntry[];\n auth: unknown;\n}\n\n// An untrusted HTTP response in the shape of their own metadata types, so every\n// field is optional and the closed enums stay widened to string.\ntype CatalogEntry = Partial<\n Pick<\n PieceMetadataModel,\n \"name\" | \"displayName\" | \"description\" | \"logoUrl\" | \"version\"\n >\n> & {\n actions?: number | Record<string, PieceDetailAction>;\n triggers?: number | Record<string, PieceDetailTrigger>;\n categories?: string[];\n auth?: unknown;\n deprecated?: boolean;\n};\n\ntype PieceDetailAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\">\n> & {\n // Their discovery filter: \"ai\" marks agent-targeted atomics.\n audience?: string;\n};\n\ntype PieceDetailTrigger = Partial<\n Pick<TriggerBase, \"name\" | \"displayName\" | \"description\">\n> & {\n // POLLING | WEBHOOK | APP_WEBHOOK | MANUAL; runtime support varies by strategy.\n type?: string;\n renewConfiguration?: unknown;\n};\n\n// List entry with suggestionType=ACTION_AND_TRIGGER: the same list endpoint\n// their selector searches, carrying every action/trigger name inline.\nexport interface CatalogSuggestionEntry {\n name?: string;\n auth?: unknown;\n displayName?: string;\n description?: string;\n categories?: string[];\n deprecated?: boolean;\n // Set by this module, not the listing.\n source?: PieceSource;\n version?: string;\n logoUrl?: string;\n suggestedActions?: PieceDetailAction[];\n suggestedTriggers?: PieceDetailTrigger[];\n}\n\ninterface Cached<T> {\n value: T;\n expiresAt: number;\n}\n\n// Carries the status, so a caller can tell \"this source has no such piece\"\n// from \"this source did not answer\". A transport failure throws something\n// else, which is the same distinction from the other side.\nexport class CatalogStatusError extends Error {\n constructor(\n url: string,\n readonly status: number,\n ) {\n super(`${url} responded ${status}`);\n this.name = \"CatalogStatusError\";\n }\n}\n\nasync function fetchJson(url: string, timeoutMs = 30_000): Promise<unknown> {\n const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });\n if (!response.ok) {\n throw new CatalogStatusError(url, response.status);\n }\n return response.json();\n}\n\n// A registry that ignores page params answers with the whole list, bare.\nasync function fetchRegistryCatalog(\n url: string,\n timeoutMs: number,\n): Promise<unknown[]> {\n const items: unknown[] = [];\n for (let n = 0; n < REGISTRY_MAX_PAGES; n++) {\n const pageUrl = new URL(url);\n pageUrl.searchParams.set(\"limit\", String(REGISTRY_PAGE_SIZE));\n pageUrl.searchParams.set(\"offset\", String(items.length));\n const page = (await fetchJson(\n pageUrl.toString(),\n timeoutMs,\n )) as Page<unknown>;\n if (!Array.isArray(page.items)) {\n throw new Error(`${url} did not answer with a page`);\n }\n items.push(...page.items);\n if (!page.hasMore || page.items.length === 0) return items;\n }\n logger.warn(`${url} still had more pieces after ${REGISTRY_MAX_PAGES} pages`);\n return items;\n}\n\nfunction asList(value: unknown): { name?: unknown }[] {\n return Array.isArray(value) ? (value as { name?: unknown }[]) : [];\n}\n\nfunction asError(reason: unknown): Error {\n return reason instanceof Error ? reason : new Error(String(reason));\n}\n\n// Both published sources at once. A source that fails is a warning while the\n// other answers; every source failing is the read failing.\nasync function publishedLists(\n suggestions: boolean,\n timeoutMs: number,\n): Promise<{ registry: { name?: unknown }[]; cloud: { name?: unknown }[] }> {\n const source = pieceRegistrySource();\n const cloudUrl = suggestions\n ? `${CATALOG_URL}?suggestionType=ACTION_AND_TRIGGER`\n : CATALOG_URL;\n const [fromRegistry, fromCloud] = await Promise.allSettled([\n source\n ? fetchRegistryCatalog(source.catalogUrl(suggestions), timeoutMs)\n : Promise.resolve([]),\n fetchJson(cloudUrl, timeoutMs),\n ]);\n // A registry may index more than this deployment allowed itself to run, so\n // the same names the download source honours are the ones listed.\n const registry =\n fromRegistry.status === \"fulfilled\"\n ? asList(fromRegistry.value).filter(\n (entry) => typeof entry.name === \"string\",\n )\n : [];\n if (fromRegistry.status === \"rejected\") {\n logger.warn(\n \"Piece registry @url did not answer: @error\",\n source?.baseUrl ?? \"?\",\n String(fromRegistry.reason),\n );\n }\n if (fromCloud.status === \"rejected\") {\n if (registry.length === 0) throw asError(fromCloud.reason);\n logger.warn(\n \"Serving registry pieces only: @error\",\n String(fromCloud.reason),\n );\n return { registry, cloud: [] };\n }\n return { registry, cloud: asList(fromCloud.value) };\n}\n\n// The registry's entries win their own names, the way a package piece wins\n// over both: a name is served by whoever is closest to the reactor.\nfunction registryFirst<T extends { name?: unknown }>(\n registry: T[],\n cloud: T[],\n): T[] {\n const claimed = new Set(registry.map((entry) => entry.name));\n return [...registry, ...cloud.filter((entry) => !claimed.has(entry.name))];\n}\n\nfunction tagged<T extends object>(\n entries: T[],\n source: PieceSource,\n): (T & { source: PieceSource })[] {\n return entries.map((entry) => ({ ...entry, source }));\n}\n\n// ~17 MB for the whole cloud catalog; fetched once per index build, never\n// cached here (block-search keeps the compact index instead).\nexport async function fetchCatalogWithSuggestions(): Promise<\n CatalogSuggestionEntry[]\n> {\n const { registry, cloud } = await publishedLists(true, 120_000);\n return registryFirst(\n tagged(registry as CatalogSuggestionEntry[], \"registry\"),\n tagged(cloud as CatalogSuggestionEntry[], \"activepieces\"),\n );\n}\n\nlet catalogCache: Cached<PieceSummary[]> | undefined;\n\n// Test-only: the module caches the catalog for CACHE_TTL_MS.\nexport function __resetCatalogCacheForTests(): void {\n catalogCache = undefined;\n}\n\n// A listing entry is worth showing only if it names a piece with a version\n// and at least one block; the counts are what the list endpoint carries.\nfunction toSummaries(raw: CatalogEntry[], source: PieceSource): PieceSummary[] {\n return raw\n .filter(\n (entry) =>\n typeof entry.name === \"string\" &&\n typeof entry.version === \"string\" &&\n !SERVER_ONLY_PIECES.has(entry.name) &&\n ((typeof entry.actions === \"number\" && entry.actions > 0) ||\n (typeof entry.triggers === \"number\" && entry.triggers > 0)),\n )\n .map((entry) => ({\n name: entry.name!,\n displayName: entry.displayName ?? entry.name!,\n description: entry.description ?? \"\",\n logoUrl: entry.logoUrl ?? \"\",\n version: entry.version!,\n actionCount: typeof entry.actions === \"number\" ? entry.actions : 0,\n triggerCount: typeof entry.triggers === \"number\" ? entry.triggers : 0,\n categories: entry.categories ?? [],\n source,\n auth: entry.auth ?? null,\n ...(entry.deprecated === true ? { deprecated: true } : {}),\n ...reasonOf(unsupportedAuth(entry.auth)),\n }));\n}\n\nexport async function fetchPieceCatalog(): Promise<PieceSummary[]> {\n if (catalogCache && catalogCache.expiresAt > Date.now()) {\n return catalogCache.value;\n }\n const lists = await publishedLists(false, 30_000);\n const published = registryFirst(\n toSummaries(lists.registry as CatalogEntry[], \"registry\"),\n toSummaries(lists.cloud as CatalogEntry[], \"activepieces\"),\n );\n const value = [...published].sort((a, b) =>\n a.displayName.localeCompare(b.displayName),\n );\n catalogCache = { value, expiresAt: Date.now() + CACHE_TTL_MS };\n return value;\n}\n\n// One piece's detail: the registry first, then the cloud. A registry that is\n// down counts as not serving the piece, as it does for the catalog listing.\nasync function fetchPieceJson(\n packageName: string,\n version?: string,\n): Promise<unknown> {\n const source = pieceRegistrySource();\n if (source) {\n try {\n return await fetchJson(atVersion(source.pieceUrl(packageName), version));\n } catch (error) {\n // Passed as values: a scoped name's \"@scope\" would read as a token.\n if (error instanceof CatalogStatusError && error.status === 404) {\n logger.debug(\n \"@registry does not serve @piece\",\n source.baseUrl,\n packageName,\n );\n } else {\n logger.warn(\n \"Piece registry @registry did not answer for @piece: @error\",\n source.baseUrl,\n packageName,\n String(error),\n );\n }\n }\n }\n return fetchJson(pieceUrl(packageName, version));\n}\n\nfunction ttlFor(version: string | undefined): number {\n return version ? PINNED_TTL_MS : CACHE_TTL_MS;\n}\n\nconst detailCache = new Map<string, Cached<unknown>>();\n\n// Full piece detail, verbatim from whichever source answered for it\n// (PieceMetadataModel-shaped).\nexport async function fetchPieceDetail(\n packageName: string,\n version?: string,\n): Promise<unknown> {\n const key = `${packageName}@${version ?? \"\"}`;\n const cached = detailCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.value;\n const value = await fetchPieceJson(packageName, version);\n detailCache.set(key, { value, expiresAt: Date.now() + ttlFor(version) });\n return value;\n}\n\nconst triggersCache = new Map<string, Cached<PieceTriggersResult>>();\n\nexport async function fetchPieceTriggers(\n packageName: string,\n requested?: string,\n): Promise<PieceTriggersResult> {\n const key = `${packageName}@${requested ?? \"\"}`;\n const cached = triggersCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.value;\n const detail = (await fetchPieceJson(packageName, requested)) as CatalogEntry;\n const version = detail.version ?? \"\";\n const pieceUnsupported = unsupportedAuth(detail.auth);\n const triggersRecord =\n detail.triggers && typeof detail.triggers === \"object\"\n ? detail.triggers\n : {};\n const triggers = Object.entries(triggersRecord).map(([name, trigger]) => ({\n name,\n displayName: trigger.displayName ?? name,\n description: trigger.description ?? \"\",\n strategy: trigger.type ?? \"\",\n ...reasonOf(pieceUnsupported ?? unsupportedTrigger(trigger)),\n }));\n const value: PieceTriggersResult = {\n name: packageName,\n displayName: detail.displayName ?? packageName,\n version,\n triggers,\n auth: detail.auth ?? null,\n };\n triggersCache.set(key, {\n value,\n expiresAt: Date.now() + ttlFor(requested),\n });\n return value;\n}\n\nconst actionsCache = new Map<string, Cached<PieceActionsResult>>();\n\nexport async function fetchPieceActions(\n packageName: string,\n requested?: string,\n): Promise<PieceActionsResult> {\n const key = `${packageName}@${requested ?? \"\"}`;\n const cached = actionsCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.value;\n const detail = (await fetchPieceJson(packageName, requested)) as CatalogEntry;\n const version = detail.version ?? \"\";\n const unsupported = reasonOf(unsupportedAuth(detail.auth));\n const actionsRecord =\n detail.actions && typeof detail.actions === \"object\" ? detail.actions : {};\n const actions = Object.entries(actionsRecord)\n .map(([name, action]) => ({\n name,\n displayName: action.displayName ?? name,\n description: action.description ?? \"\",\n audience: action.audience ?? null,\n ...unsupported,\n }))\n // Agent-targeted atomics last, so the actions a person would pick stay at\n // the top. Same predicate their own human view filters on, and an absent\n // audience counts as human-visible.\n .sort((a, b) => aiLast(a.audience) - aiLast(b.audience));\n const value: PieceActionsResult = {\n name: packageName,\n displayName: detail.displayName ?? packageName,\n version,\n actions,\n auth: detail.auth ?? null,\n };\n actionsCache.set(key, {\n value,\n expiresAt: Date.now() + ttlFor(requested),\n });\n return value;\n}\n","// A package piece as the editor's catalog sees it, read from the piece itself.\n\n// A published piece is described by a listing the cloud API serves; one that\n// ships inside a reactor package has no listing, so its descriptor — built in\n// the worker from the piece module — is the listing.\nimport type { PieceDescriptor } from \"../pieces/index.js\";\nimport type {\n BlockSearchHit,\n SearchablePiece,\n SearchPieceMeta,\n} from \"./block-search.js\";\nimport {\n aiLast,\n clientAuth,\n reasonOf,\n type PieceActionsResult,\n type PieceSummary,\n type PieceTriggersResult,\n} from \"./piece-catalog.js\";\n\nexport function catalogEntry(\n descriptor: PieceDescriptor,\n pieceName: string,\n version: string,\n): PieceSummary {\n return {\n name: pieceName,\n displayName: descriptor.displayName || pieceName,\n description: descriptor.description ?? \"\",\n logoUrl: descriptor.logoUrl ?? \"\",\n version,\n actionCount: descriptor.actions.length,\n triggerCount: descriptor.triggers.length,\n categories: descriptor.categories ?? [],\n source: \"local\",\n auth: clientAuth(descriptor.auth),\n ...reasonOf(descriptor.unsupported),\n };\n}\n\nexport function actionsResult(\n descriptor: PieceDescriptor,\n pieceName: string,\n version: string,\n): PieceActionsResult {\n return {\n name: pieceName,\n displayName: descriptor.displayName || pieceName,\n version,\n actions: descriptor.actions\n .map((action) => ({\n name: action.name,\n displayName: action.displayName,\n description: action.description ?? \"\",\n // The cloud's discovery filter. Absent counts as human-visible.\n audience: action.audience ?? null,\n ...reasonOf(descriptor.unsupported),\n }))\n // Agent-targeted atomics last, as the published listing sorts them.\n .sort((a, b) => aiLast(a.audience) - aiLast(b.audience)),\n auth: clientAuth(descriptor.auth),\n };\n}\n\nexport function triggersResult(\n descriptor: PieceDescriptor,\n pieceName: string,\n version: string,\n): PieceTriggersResult {\n return {\n name: pieceName,\n displayName: descriptor.displayName || pieceName,\n version,\n triggers: descriptor.triggers.map((trigger) => ({\n name: trigger.name,\n displayName: trigger.displayName,\n description: trigger.description ?? \"\",\n strategy: trigger.strategy,\n ...reasonOf(descriptor.unsupported ?? trigger.unsupported),\n })),\n auth: clientAuth(descriptor.auth),\n };\n}\n\n// The piece as the search indexes it, so a block the reactor ships is\n// findable whether or not the published catalog answered.\nexport function localSearchPiece(\n descriptor: PieceDescriptor,\n pieceName: string,\n version: string,\n): SearchablePiece {\n const pieceDisplayName = descriptor.displayName || pieceName;\n const logoUrl = descriptor.logoUrl ?? \"\";\n const meta: SearchPieceMeta = {\n pieceName,\n pieceVersion: version,\n displayName: pieceDisplayName,\n description: descriptor.description ?? \"\",\n logoUrl,\n categories: descriptor.categories ?? [],\n source: \"local\",\n ...reasonOf(descriptor.unsupported),\n };\n const blocks: BlockSearchHit[] = [\n ...descriptor.actions.map((action) => ({\n pieceName,\n pieceVersion: version,\n name: action.name,\n pieceDisplayName,\n logoUrl,\n displayName: action.displayName,\n description: action.description ?? \"\",\n kind: \"action\" as const,\n strategy: null,\n ...reasonOf(descriptor.unsupported),\n })),\n ...descriptor.triggers.map((trigger) => ({\n pieceName,\n pieceVersion: version,\n name: trigger.name,\n pieceDisplayName,\n logoUrl,\n displayName: trigger.displayName,\n description: trigger.description ?? \"\",\n kind: \"trigger\" as const,\n strategy: trigger.strategy,\n ...reasonOf(descriptor.unsupported ?? trigger.unsupported),\n })),\n ];\n return { meta, blocks };\n}\n\n// The PieceMetadataModel shape the editor's detail query expects: actions and\n// triggers keyed by name. Output schemas are absent because a descriptor does\n// not carry them — a caller reading one treats that as \"not authored\".\nexport function detailResult(\n descriptor: PieceDescriptor,\n pieceName: string,\n version: string,\n): Record<string, unknown> {\n return {\n name: pieceName,\n displayName: descriptor.displayName || pieceName,\n description: descriptor.description ?? \"\",\n logoUrl: descriptor.logoUrl ?? \"\",\n version,\n categories: descriptor.categories ?? [],\n auth: clientAuth(descriptor.auth),\n actions: Object.fromEntries(\n descriptor.actions.map((action) => [\n action.name,\n {\n name: action.name,\n displayName: action.displayName,\n description: action.description ?? \"\",\n props: action.props,\n requireAuth: action.requireAuth,\n ...(action.requireReactor\n ? { requireReactor: action.requireReactor }\n : {}),\n ...(action.defaultTimeoutSeconds !== undefined\n ? { defaultTimeoutSeconds: action.defaultTimeoutSeconds }\n : {}),\n ...(action.defaultRetry ? { defaultRetry: action.defaultRetry } : {}),\n // What blockOutputTree reads. A published piece's listing carries\n // it; a package piece has only this.\n outputSchema: action.outputSchema,\n audience: action.audience,\n },\n ]),\n ),\n triggers: Object.fromEntries(\n descriptor.triggers.map((trigger) => [\n trigger.name,\n {\n name: trigger.name,\n displayName: trigger.displayName,\n description: trigger.description ?? \"\",\n type: trigger.strategy,\n props: trigger.props,\n requireAuth: trigger.requireAuth,\n ...(trigger.requireReactor\n ? { requireReactor: trigger.requireReactor }\n : {}),\n outputSchema: trigger.outputSchema,\n sampleData: trigger.sampleData,\n testStrategy: trigger.testStrategy,\n // Under the name the published listing uses; the descriptor\n // shortens it.\n handshakeConfiguration: trigger.handshake,\n ...(trigger.renew ? { renewConfiguration: trigger.renew } : {}),\n },\n ]),\n ),\n };\n}\n","// Piece and block search over the whole catalog. The index is built lazily\n// from one list request (suggestionType=ACTION_AND_TRIGGER) and cached.\nimport {\n fetchCatalogWithSuggestions,\n reasonOf,\n type CatalogSuggestionEntry,\n type PieceSource,\n} from \"./piece-catalog.js\";\nimport {\n unsupportedAuth,\n unsupportedTrigger,\n} from \"../pieces/activepieces/unsupported.js\";\nimport { SERVER_ONLY_PIECES } from \"./unsupported-pieces.js\";\n\nexport type BlockSearchKind = \"action\" | \"trigger\";\n\nexport interface BlockSearchHit {\n pieceName: string;\n // The piece version the hit was listed at, to pin when it is picked.\n pieceVersion: string;\n // Action or trigger name within the piece.\n name: string;\n pieceDisplayName: string;\n logoUrl: string;\n displayName: string;\n description: string;\n kind: BlockSearchKind;\n // Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL.\n strategy: string | null;\n // Why the block cannot run here.\n unsupported?: string;\n}\n\nexport interface SearchPieceMeta {\n pieceName: string;\n pieceVersion: string;\n displayName: string;\n description: string;\n logoUrl: string;\n categories: string[];\n source: PieceSource;\n deprecated?: boolean;\n // Why no block of the piece can run here.\n unsupported?: string;\n}\n\n// A piece and its blocks, before indexing.\nexport interface SearchablePiece {\n meta: SearchPieceMeta;\n blocks: BlockSearchHit[];\n}\n\nexport interface PieceSearchMatch extends SearchPieceMeta {\n // Every query token matched the piece's own name.\n namedPiece: boolean;\n // Matching blocks of the kind asked for, best first.\n blocks: BlockSearchHit[];\n}\n\nexport type BlockSearchStatus = \"ready\" | \"indexing\" | \"error\";\n\nexport interface PieceSearchResult {\n status: BlockSearchStatus;\n pieces: PieceSearchMatch[];\n // Number of pieces the index covers; local pieces only while indexing.\n indexedPieces: number;\n error: string | null;\n}\n\nexport interface PieceSearchFilter {\n kind: BlockSearchKind;\n // Any of these; all sources when absent or empty.\n sources?: readonly PieceSource[];\n // Any of these category ids; all pieces when absent or empty.\n categories?: readonly string[];\n // Pieces returned, not blocks.\n limit?: number;\n}\n\ninterface Words {\n words: string[];\n // The words run together, so \"googlesheets\" finds \"Google Sheets\".\n compact: string;\n}\n\ninterface IndexedBlock {\n hit: BlockSearchHit;\n name: Words;\n description: Words;\n}\n\ninterface IndexedPiece {\n meta: SearchPieceMeta;\n name: Words;\n // The display name as a query would spell it, for the exact-name bonus.\n exactName: string;\n // Description and category words.\n about: Words;\n blocks: IndexedBlock[];\n}\n\nexport interface BlockSearchIndex {\n pieces: IndexedPiece[];\n}\n\nconst INDEX_TTL_MS = 60 * 60 * 1000;\nconst DEFAULT_LIMIT = 20;\nconst MAX_LIMIT = 50;\nconst MAX_BLOCKS_PER_PIECE = 50;\n\nexport function tokenize(text: string): string[] {\n return text\n .normalize(\"NFKD\")\n .replace(/\\p{M}/gu, \"\")\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean);\n}\n\nfunction wordsOf(...texts: string[]): Words {\n const words = texts.flatMap(tokenize);\n return { words, compact: words.join(\"\") };\n}\n\n// \"@activepieces/piece-google-sheets\" → \"google-sheets\".\nfunction slugOf(pieceName: string): string {\n return pieceName.replace(/^@[^/]+\\//, \"\").replace(/^piece-/, \"\");\n}\n\nfunction indexPiece(piece: SearchablePiece): IndexedPiece {\n const { meta } = piece;\n return {\n meta,\n name: wordsOf(meta.displayName, slugOf(meta.pieceName)),\n exactName: tokenize(meta.displayName).join(\" \"),\n about: wordsOf(meta.description, ...meta.categories),\n blocks: piece.blocks.map((hit) => ({\n hit,\n name: wordsOf(hit.displayName, hit.name),\n description: wordsOf(hit.description),\n })),\n };\n}\n\nexport function indexPieces(pieces: SearchablePiece[]): BlockSearchIndex {\n return { pieces: pieces.map(indexPiece) };\n}\n\nexport function buildSearchIndex(\n raw: CatalogSuggestionEntry[],\n): BlockSearchIndex {\n const pieces: SearchablePiece[] = [];\n for (const entry of raw) {\n if (\n typeof entry.name !== \"string\" ||\n typeof entry.version !== \"string\" ||\n SERVER_ONLY_PIECES.has(entry.name)\n ) {\n continue;\n }\n const pieceName = entry.name;\n const pieceVersion = entry.version;\n const pieceDisplayName = entry.displayName ?? pieceName;\n const logoUrl = entry.logoUrl ?? \"\";\n const pieceUnsupported = unsupportedAuth(entry.auth);\n const blocks: BlockSearchHit[] = [];\n const push = (\n kind: BlockSearchKind,\n item: {\n name?: string;\n displayName?: string;\n description?: string;\n type?: string;\n renewConfiguration?: unknown;\n },\n ) => {\n if (typeof item.name !== \"string\" || item.name === \"\") return;\n blocks.push({\n pieceName,\n pieceVersion,\n name: item.name,\n pieceDisplayName,\n logoUrl,\n displayName: item.displayName ?? item.name,\n description: item.description ?? \"\",\n kind,\n strategy: kind === \"trigger\" ? (item.type ?? null) : null,\n ...reasonOf(\n pieceUnsupported ??\n (kind === \"trigger\" ? unsupportedTrigger(item) : undefined),\n ),\n });\n };\n for (const action of entry.suggestedActions ?? []) push(\"action\", action);\n for (const trigger of entry.suggestedTriggers ?? [])\n push(\"trigger\", trigger);\n pieces.push({\n meta: {\n pieceName,\n pieceVersion,\n displayName: pieceDisplayName,\n description: entry.description ?? \"\",\n logoUrl,\n categories: Array.isArray(entry.categories) ? entry.categories : [],\n source: entry.source ?? \"activepieces\",\n ...(entry.deprecated === true ? { deprecated: true } : {}),\n ...reasonOf(pieceUnsupported),\n },\n blocks,\n });\n }\n return indexPieces(pieces);\n}\n\n// An installed piece wins its own name, as in the catalog: picking the\n// published listing would bypass the copy that actually runs.\nfunction merge(\n index: BlockSearchIndex | undefined,\n local: BlockSearchIndex | undefined,\n): BlockSearchIndex {\n const localPieces = local?.pieces ?? [];\n const localNames = new Set(localPieces.map((piece) => piece.meta.pieceName));\n return {\n pieces: [\n ...localPieces,\n ...(index?.pieces ?? []).filter(\n (piece) => !localNames.has(piece.meta.pieceName),\n ),\n ],\n };\n}\n\nconst EXACT = 4;\nconst PREFIX = 3;\nconst INNER = 1.5;\nconst FUZZY = 1;\n\n// Field weights: a piece's name says most, its description least.\nconst PIECE_NAME = 3;\nconst BLOCK_NAME = 2;\nconst BLOCK_DESCRIPTION = 1;\nconst PIECE_ABOUT = 0.5;\n\n// Optimal string alignment distance, or max + 1 once it exceeds max.\nfunction editDistance(a: string, b: string, max: number): number {\n if (Math.abs(a.length - b.length) > max) return max + 1;\n let prevPrev: number[] = [];\n let prev = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n const row = [i];\n let rowMin = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n let value = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + cost);\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n value = Math.min(value, prevPrev[j - 2] + 1);\n }\n row.push(value);\n rowMin = Math.min(rowMin, value);\n }\n if (rowMin > max) return max + 1;\n prevPrev = prev;\n prev = row;\n }\n return prev[b.length];\n}\n\n// Whole word, word prefix, inside a word, then (if fuzzy) a word or prefix\n// within one typo, two for long tokens.\nfunction termScore(token: string, field: Words, fuzzy: boolean): number {\n let best = 0;\n for (const word of field.words) {\n if (word === token) return EXACT;\n if (word.startsWith(token)) best = PREFIX;\n else if (best < INNER && token.length >= 3 && word.includes(token)) {\n best = INNER;\n }\n }\n if (best > 0) return best;\n if (token.length >= 3 && field.compact.includes(token)) return INNER;\n if (!fuzzy || token.length < 4) return 0;\n const max = token.length >= 8 ? 2 : 1;\n for (const word of field.words) {\n if (\n editDistance(token, word, max) <= max ||\n (word.length > token.length &&\n editDistance(token, word.slice(0, token.length), max) <= max)\n ) {\n return FUZZY;\n }\n }\n return 0;\n}\n\nfunction allowed(piece: IndexedPiece, filter: PieceSearchFilter): boolean {\n const { sources, categories } = filter;\n if (sources?.length && !sources.includes(piece.meta.source)) return false;\n if (\n categories?.length &&\n !piece.meta.categories.some((category) => categories.includes(category))\n ) {\n return false;\n }\n return true;\n}\n\n// Each token must match the piece or the block. A block scores the sum of its\n// tokens' best weighted matches; a piece scores its best block.\nexport function searchIndex(\n index: BlockSearchIndex,\n query: string,\n filter: PieceSearchFilter,\n): PieceSearchMatch[] {\n const tokens = tokenize(query);\n if (tokens.length === 0) return [];\n const exactName = tokens.join(\" \");\n const matches: { score: number; match: PieceSearchMatch }[] = [];\n for (const piece of index.pieces) {\n // Before the limit, so a narrow filter never loses hits to a wide one.\n if (!allowed(piece, filter)) continue;\n const nameScores = tokens.map((token) =>\n termScore(token, piece.name, true),\n );\n // Each block's own score per token, computed once for both passes.\n const ofKind = piece.blocks\n .filter((block) => block.hit.kind === filter.kind)\n .map((block) => ({\n hit: block.hit,\n scores: tokens.map((token) =>\n Math.max(\n BLOCK_NAME * termScore(token, block.name, true),\n BLOCK_DESCRIPTION * termScore(token, block.description, false),\n ),\n ),\n }));\n const matchBlocks = (pieceScores: number[]) => {\n const found: { score: number; order: number; hit: BlockSearchHit }[] = [];\n ofKind.forEach((block, order) => {\n let score = 0;\n for (let i = 0; i < tokens.length; i++) {\n const best = Math.max(pieceScores[i], block.scores[i]);\n if (best === 0) return;\n score += best;\n }\n found.push({ score, order, hit: block.hit });\n });\n return found;\n };\n let blocks = matchBlocks(nameScores.map((score) => PIECE_NAME * score));\n // The piece's description and categories only when no block matched,\n // or they would pull every block of it into a match.\n if (blocks.length === 0 && ofKind.length > 0) {\n blocks = matchBlocks(\n tokens.map((token, i) =>\n Math.max(\n PIECE_NAME * nameScores[i],\n PIECE_ABOUT * termScore(token, piece.about, false),\n ),\n ),\n );\n }\n if (blocks.length === 0) continue;\n blocks.sort((a, b) => b.score - a.score || a.order - b.order);\n const nameBonus = piece.exactName === exactName ? EXACT : 0;\n matches.push({\n score: blocks[0].score + nameBonus,\n match: {\n ...piece.meta,\n namedPiece: nameScores.every((score) => score > 0),\n blocks: blocks.slice(0, MAX_BLOCKS_PER_PIECE).map(({ hit }) => hit),\n },\n });\n }\n const demoted = (match: PieceSearchMatch) =>\n (match.deprecated ? 2 : 0) + (match.unsupported ? 1 : 0);\n matches.sort(\n (a, b) =>\n b.score - a.score ||\n demoted(a.match) - demoted(b.match) ||\n a.match.displayName.localeCompare(b.match.displayName),\n );\n const limit = Math.min(Math.max(filter.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);\n return matches.slice(0, limit).map(({ match }) => match);\n}\n\ninterface CachedIndex {\n promise: Promise<BlockSearchIndex>;\n value?: BlockSearchIndex;\n error?: string;\n expiresAt: number;\n}\n\nlet cached: CachedIndex | undefined;\n\nfunction ensureIndex(): CachedIndex {\n if (cached && cached.expiresAt > Date.now() && !cached.error) return cached;\n const entry: CachedIndex = {\n promise: fetchCatalogWithSuggestions().then(buildSearchIndex),\n expiresAt: Date.now() + INDEX_TTL_MS,\n };\n entry.promise.then(\n (value) => {\n entry.value = value;\n },\n (error: unknown) => {\n entry.error = error instanceof Error ? error.message : String(error);\n },\n );\n cached = entry;\n return entry;\n}\n\n// Starts the build ahead of the first search. A failure is dropped, so that\n// search retries rather than reports it.\nexport function warmSearchIndex(): void {\n const entry = ensureIndex();\n entry.promise.catch(() => {\n if (cached === entry) cached = undefined;\n });\n}\n\n// Never blocks on the index build: callers poll while status is \"indexing\".\n// Status covers the published half only; local pieces are always searched.\nexport function searchPieces(\n query: string,\n filter: PieceSearchFilter,\n local?: BlockSearchIndex,\n): PieceSearchResult {\n const index = ensureIndex();\n if (index.error) {\n const message = index.error;\n // Drop the failed build so the next call retries.\n cached = undefined;\n return {\n status: \"error\",\n pieces: searchIndex(merge(undefined, local), query, filter),\n indexedPieces: local?.pieces.length ?? 0,\n error: message,\n };\n }\n if (!index.value) {\n return {\n status: \"indexing\",\n pieces: searchIndex(merge(undefined, local), query, filter),\n indexedPieces: local?.pieces.length ?? 0,\n error: null,\n };\n }\n const merged = merge(index.value, local);\n return {\n status: \"ready\",\n pieces: searchIndex(merged, query, filter),\n indexedPieces: merged.pieces.length,\n error: null,\n };\n}\n\n// Test seam.\nexport function resetBlockSearchIndex(): void {\n cached = undefined;\n}\n","// The one policy turning a block into the piece version that runs it.\n// Rules: README, \"Block resolution\".\nimport {\n compareVersions,\n isExactVersion,\n rankClosestVersions,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n isHostBound,\n npmVersions,\n registryVersions,\n unpinnedNote,\n type BlockResolution,\n type LocalPiece,\n type PieceOrigin,\n type VersionListing,\n} from \"../pieces/index.js\";\n\nexport const ACTIVEPIECES_SCOPE = \"@activepieces/\";\n\n// Tie-break order for a version more than one source holds.\nconst PRECEDENCE: PieceOrigin[] = [\"local\", \"registry\", \"activepieces\", \"npm\"];\n\nexport interface PieceCandidates {\n bySource: Map<PieceOrigin, string[]>;\n // Sources that could not be asked, with why.\n unreachable: string[];\n}\n\nexport interface BlockResolverDeps {\n local: (name: string) => LocalPiece | undefined;\n timeoutMs?: number;\n // Whether that version has the block's action or trigger; undefined when it\n // cannot be described (running it then fails with the piece's own error).\n hasBlock?: (\n ref: BlockRef,\n version: string,\n source: PieceOrigin,\n ) => Promise<boolean | undefined>;\n}\n\n// Versions described per resolution before giving up on a block name.\nexport const MAX_BLOCK_LOOKUPS = 5;\n\nconst noBlock = (ref: BlockRef) => `it has no ${ref.kind} \"${ref.name}\"`;\n\nfunction add(\n candidates: PieceCandidates,\n source: PieceOrigin,\n listing: VersionListing | undefined,\n): void {\n if (!listing) return;\n if (listing.kind === \"listed\") {\n candidates.bySource.set(source, listing.versions);\n } else if (listing.kind === \"unreachable\") {\n candidates.unreachable.push(listing.detail);\n }\n}\n\nfunction newest(versions: Iterable<string>): string | undefined {\n let best: string | undefined;\n for (const version of versions) {\n try {\n if (!best || compareVersions(version, best) > 0) best = version;\n } catch {\n // Not semver: never a candidate.\n }\n }\n return best;\n}\n\nexport class BlockResolver {\n constructor(private readonly deps: BlockResolverDeps) {}\n\n // Local, then the registry for names it owns, then Activepieces or npm.\n async candidates(\n piece: string,\n options: { fresh?: boolean } = {},\n ): Promise<PieceCandidates> {\n const candidates: PieceCandidates = {\n bySource: new Map(),\n unreachable: [],\n };\n const local = this.deps.local(piece);\n if (local) candidates.bySource.set(\"local\", [local.version]);\n const listing = { timeoutMs: this.deps.timeoutMs, fresh: options.fresh };\n if (piece.startsWith(ACTIVEPIECES_SCOPE)) {\n add(candidates, \"activepieces\", await npmVersions(piece, listing));\n return candidates;\n }\n const registry = await registryVersions(piece, listing);\n add(candidates, \"registry\", registry);\n // A name the registry holds, or may hold, never comes from npm.\n if (registry === undefined || registry.kind === \"absent\") {\n add(candidates, \"npm\", await npmVersions(piece, listing));\n }\n return candidates;\n }\n\n // Syntax, host binding and version choice; the caller checks the name.\n // `latest` asks every source even when the installed piece is an exact match.\n async resolve(\n ref: BlockRef,\n options: { fresh?: boolean; latest?: boolean } = {},\n ): Promise<BlockResolution> {\n if (!ref.pieceName || !ref.name || !isExactVersion(ref.pieceVersion)) {\n return { requested: ref, match: \"missing\", note: unpinnedNote(ref) };\n }\n if (isHostBound(ref.pieceName)) return this.installed(ref);\n // Exact and local wins every tie, so no other source can change the answer.\n if (\n !options.latest &&\n this.deps.local(ref.pieceName)?.version === ref.pieceVersion &&\n (await this.deps.hasBlock?.(ref, ref.pieceVersion, \"local\")) !== false\n ) {\n return {\n requested: ref,\n resolved: { version: ref.pieceVersion, source: \"local\" },\n match: \"exact\",\n };\n }\n return this.choose(\n ref,\n ref.pieceVersion,\n await this.candidates(ref.pieceName, options),\n );\n }\n\n // For a piece named without a version (a connection check): local, else newest.\n async latest(\n piece: string,\n options: { fresh?: boolean } = {},\n ): Promise<\n | { version: string; source: PieceOrigin }\n | { version?: undefined; unreachable?: string }\n > {\n const local = this.deps.local(piece);\n if (local) return { version: local.version, source: \"local\" };\n const candidates = await this.candidates(piece, options);\n for (const source of PRECEDENCE) {\n const version = newest(candidates.bySource.get(source) ?? []);\n if (version) return { version, source };\n }\n return { unreachable: candidates.unreachable.join(\"; \") || undefined };\n }\n\n // A host-bound piece is the host's own code: always the installed copy.\n private async installed(ref: BlockRef): Promise<BlockResolution> {\n const local = this.deps.local(ref.pieceName);\n if (!local) {\n return {\n requested: ref,\n match: \"missing\",\n note: `${ref.pieceName} runs only as installed, and this reactor has not installed it`,\n };\n }\n if ((await this.deps.hasBlock?.(ref, local.version, \"local\")) === false) {\n return {\n requested: ref,\n match: \"missing\",\n note: `${ref.pieceName}@${local.version} has no ${ref.kind} \"${ref.name}\"`,\n };\n }\n return {\n requested: ref,\n resolved: { version: local.version, source: \"local\" },\n match: \"installed\",\n latestVersion: local.version,\n ...(local.version !== ref.pieceVersion\n ? {\n note: `Runs the installed ${local.version}; the block pins ${ref.pieceVersion}`,\n }\n : {}),\n };\n }\n\n // The closest version holding the block: candidates are described in\n // preference order, at most MAX_BLOCK_LOOKUPS of them.\n private async choose(\n ref: BlockRef,\n requested: string,\n candidates: PieceCandidates,\n ): Promise<BlockResolution> {\n const all = [...candidates.bySource.values()].flat();\n const latestVersion = newest(all);\n const sourceOf = (version: string) =>\n PRECEDENCE.find((source) =>\n candidates.bySource.get(source)?.includes(version),\n )!;\n const ranked = rankClosestVersions(requested, all);\n if (ranked.length === 0) {\n const unreachable = candidates.unreachable.join(\"; \");\n return {\n requested: ref,\n match: \"missing\",\n note: unreachable\n ? `No source could be asked for ${ref.pieceName}: ${unreachable}`\n : `No source has the piece ${ref.pieceName}`,\n ...(unreachable ? { unreachable } : {}),\n };\n }\n const skipped: string[] = [];\n for (const closest of ranked.slice(0, MAX_BLOCK_LOOKUPS)) {\n const source = sourceOf(closest.version);\n if (\n (await this.deps.hasBlock?.(ref, closest.version, source)) === false\n ) {\n skipped.push(`Skipped ${closest.version}: ${noBlock(ref)}`);\n continue;\n }\n const notes = [\n ...(closest.match === \"exact\"\n ? []\n : [\n `Pinned ${requested} is not available; runs ${closest.version} from ${source}`,\n ]),\n ...skipped,\n ];\n return {\n requested: ref,\n resolved: { version: closest.version, source },\n match: closest.match,\n ...(latestVersion ? { latestVersion } : {}),\n ...(notes.length > 0 ? { note: notes.join(\". \") } : {}),\n };\n }\n const checked = ranked.slice(0, MAX_BLOCK_LOOKUPS).map((c) => c.version);\n const unchecked = ranked.length - checked.length;\n return {\n requested: ref,\n match: \"missing\",\n ...(latestVersion ? { latestVersion } : {}),\n note:\n checked.length === 1\n ? `${ref.pieceName}@${checked[0]} has no ${ref.kind} \"${ref.name}\"`\n : `${ref.pieceName} has no ${ref.kind} \"${ref.name}\" in ${checked.join(\", \")}` +\n (unchecked > 0\n ? `; ${unchecked} more versions not checked (limit ${MAX_BLOCK_LOOKUPS})`\n : \"\"),\n };\n }\n}\n","// Which workflow document a step is running for, available to services that\n// sit below the coordinator. Attachment reads are authorized per document, and\n// the block executor is shared across concurrent runs, so the scope travels\n// with the async context rather than on the executor.\nimport type { AuthSubject } from \"@powerhousedao/shared/document-model\";\nimport type {\n FlowsPort,\n IPieceWorker,\n WaitpointPort,\n} from \"../pieces/index.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport interface ReactorConnectionScope {\n access: \"read\" | \"write\";\n}\nexport interface RunScope {\n // null: the snapshot was published by an unsigned operation.\n runUser: { address: string; subject: AuthSubject } | null;\n requireReactor: \"read\" | \"write\";\n connection: ReactorConnectionScope;\n deadline: number; // epoch ms\n journal: {\n recordDocuments(documentIds: string[]): Promise<void>;\n recordJob(jobId: string, documentIds: string[]): Promise<void>;\n };\n}\n\nexport type RunUser = NonNullable<RunScope[\"runUser\"]>;\n\nexport interface ActiveRun {\n workflowId: string;\n runId?: string | null;\n // The connections the definition this run pinned declared; a step resolves\n // nothing outside this set, and an edit mid-run never widens it.\n connections?: ReadonlySet<string>;\n // The worker child this run's piece steps go to, held for the length of the\n // run. Absent outside a pooled run, where the executor falls back to its own.\n pieceWorker?: IPieceWorker;\n // Journals the documents the reactor port hands this run's steps, before\n // they are handed over; absent where there is no journal to gate.\n recordDocuments?: (documentIds: string[]) => Promise<void>;\n // A single-step test: actions run their test method, falling back to run.\n stepTest?: boolean;\n // Who the run acts as; resolved only when the snapshot binds a reactor\n // connection, and null for an unsigned publish.\n runUser?: RunUser | null;\n // Where the run's attachments may come from, for the host's read check.\n attachments?: RunAttachmentOrigins;\n // Absent where the run cannot suspend: no journal, or a single-step test.\n waitpoints?: WaitpointPort;\n // ctx.flows and ctx.server; absent, both throw.\n flows?: FlowsPort;\n}\n\nexport interface RunAttachmentOrigins {\n // The trigger's document and every document handed to a step.\n documentIds: () => string[];\n // Refs this run's steps wrote.\n written: Set<string>;\n}\n\nconst storage = new AsyncLocalStorage<ActiveRun>();\n\nlet scopesOpened = 0;\nlet scopesCollected = 0;\nconst collectedScopes = new FinalizationRegistry<undefined>(() => {\n scopesCollected += 1;\n});\n\nexport function withRunScope<T>(\n scope: ActiveRun,\n fn: () => Promise<T>,\n): Promise<T> {\n scopesOpened += 1;\n collectedScopes.register(scope, undefined);\n return storage.run(scope, fn);\n}\n\n// `held` is the scopes still on the heap: the runs in flight, the finished ones\n// the next major GC will take, and any something keeps. Only the last kind\n// climbs across GCs, and no structure we can count would show it: what keeps a\n// scope is an async context, not a list.\nexport function runScopeStats(): Record<string, number> {\n return {\n opened: scopesOpened,\n collected: scopesCollected,\n held: scopesOpened - scopesCollected,\n };\n}\n\nexport function currentWorkflowId(): string | undefined {\n return storage.getStore()?.workflowId;\n}\n\nexport function currentRunId(): string | undefined {\n return storage.getStore()?.runId ?? undefined;\n}\n\n// Undefined outside a run, which the block executor treats as \"resolve\n// nothing\": only a run establishes a binding.\nexport function currentBoundConnections(): ReadonlySet<string> | undefined {\n return storage.getStore()?.connections;\n}\n\nexport function currentDocumentRecorder():\n | ((documentIds: string[]) => Promise<void>)\n | undefined {\n return storage.getStore()?.recordDocuments;\n}\n\n// The run's own worker, asked for per step rather than held by the executor:\n// the executor is shared, and the child it should use is not.\nexport function currentPieceWorker(): IPieceWorker | undefined {\n return storage.getStore()?.pieceWorker;\n}\n\nexport function currentAttachmentOrigins(): RunAttachmentOrigins | undefined {\n return storage.getStore()?.attachments;\n}\n\nexport function currentStepTest(): boolean {\n return storage.getStore()?.stepTest ?? false;\n}\n\n// Undefined outside a run, or when the run binds no reactor connection.\nexport function currentRunUser(): RunUser | null | undefined {\n return storage.getStore()?.runUser;\n}\n\nexport function currentWaitpoints(): WaitpointPort | undefined {\n return storage.getStore()?.waitpoints;\n}\n\nexport function currentFlows(): FlowsPort | undefined {\n return storage.getStore()?.flows;\n}\n","// Adapts the run journal's `piece_store` table to the engine's PieceStorePort,\n// so an action's `ctx.store` is durable the moment the piece writes it.\n\n// Which workflow a step belongs to travels on the run scope, not the executor,\n// which concurrent runs share.\nimport type { PieceStorePort, StoreScopeName } from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport type { WorkflowRunStore } from \"./store.js\";\n\nconst logger = childLogger([\"workflow\", \"piece-store\"]);\n\n// PROJECT means \"shared by every workflow in the project\", and this reactor is\n// that project: the trigger registry, the run journal and the secret store are\n// all already instance-wide, so nothing new is shared by saying so.\n\n// When a real tenancy model arrives this constant becomes its default project\n// id, and the migration is one UPDATE. See issue #16.\nexport const PROJECT_SCOPE_KEY = \"reactor\";\n\n// Appended to both partition keys for a design-time sample, so a test run\n// cannot alias a live key however the piece happens to name it.\n\n// The supervisor drops these partitions when the sample returns; a key prefix\n// could do neither, since prefixes alias and nothing enumerates them.\nconst TEST_PARTITION_SUFFIX = \"#test\";\n\n// A sample partitions by workflow in *both* scopes, unlike a live run: two\n// samples on one project partition would read and then delete each other's.\nexport function testPartitionKey(\n scope: StoreScopeName,\n workflowId: string,\n): string {\n const base =\n scope === \"PROJECT\" ? `${PROJECT_SCOPE_KEY}#${workflowId}` : workflowId;\n return base + TEST_PARTITION_SUFFIX;\n}\n\n// pollingHelper's cursor. Math.max over one unparseable date yields NaN, which\n// then re-delivers the whole feed forever, or nothing ever again.\nconst CURSOR_KEY = \"lastPoll\";\n\n// A provider's clock can run ahead of ours; beyond a day it is not skew, it is\n// a cursor that would hold the trigger silent until that date passes.\nconst MAX_CURSOR_SKEW_MS = 24 * 60 * 60_000;\n\nfunction isPlausibleCursor(value: unknown, now: number): value is number {\n return (\n typeof value === \"number\" &&\n Number.isFinite(value) &&\n value > 0 &&\n value <= now + MAX_CURSOR_SKEW_MS\n );\n}\n\n// The worker JSON-serialises what it writes, so a NaN or Infinity cursor\n// arrives as null — still ours to reject, just no longer a number.\nfunction isCursorShaped(value: unknown): boolean {\n return value === null || typeof value === \"number\";\n}\n\n// NaN and Infinity both serialise as \"null\", which is the one thing an\n// operator reading the warning must not be told.\nfunction showCursor(value: unknown): string {\n return typeof value === \"number\" ? String(value) : JSON.stringify(value);\n}\n\nfunction isCursorRef(key: string): boolean {\n return key === CURSOR_KEY || key.endsWith(`/${CURSOR_KEY}`);\n}\n\nexport function createPieceStorePort(\n store: WorkflowRunStore,\n workflowIdFor: () => string | undefined,\n sample = false,\n clock: () => number = Date.now,\n): PieceStorePort {\n // A step with no workflow in scope must fail rather than read or write\n // another workflow's keys.\n const flowKey = () => {\n const workflowId = workflowIdFor();\n if (!workflowId) {\n throw new Error(\"ctx.store is unavailable: no workflow is in scope\");\n }\n return workflowId;\n };\n\n const partition = (scope: StoreScopeName): string =>\n sample\n ? testPartitionKey(scope, flowKey())\n : scope === \"PROJECT\"\n ? PROJECT_SCOPE_KEY\n : flowKey();\n\n // Async so that a missing run scope rejects rather than throwing out of a\n // method whose contract is a promise.\n return {\n get: async (key, scope) =>\n store.getPieceStoreValue(scope, partition(scope), key),\n // A durable store means the cursor no longer passes the supervisor on its\n // way to the database, so the guard that policed it lives here instead.\n put: async (key, value, scope) => {\n const now = clock();\n if (!isCursorRef(key) || isPlausibleCursor(value, now)) {\n return store.setPieceStoreValue(scope, partition(scope), key, value);\n }\n const kept = await store.getPieceStoreValue(scope, partition(scope), key);\n // Only our own cursor shape is ours to police: a piece that keeps its\n // own `lastPoll` as a string or an object is left to it.\n if (!isCursorShaped(value) && !isPlausibleCursor(kept, now)) {\n return store.setPieceStoreValue(scope, partition(scope), key, value);\n }\n logger.warn(\n `Rejected @key=@value from workflow ${flowKey()}; keeping @kept`,\n key,\n showCursor(value),\n isPlausibleCursor(kept, now) ? String(kept) : \"no cursor\",\n );\n // With nothing to fall back to the key is dropped, so the next poll\n // fails loudly rather than running on a cursor nobody chose.\n if (!isPlausibleCursor(kept, now)) {\n await store.deletePieceStoreValue(scope, partition(scope), key);\n }\n },\n delete: async (key, scope) =>\n store.deletePieceStoreValue(scope, partition(scope), key),\n };\n}\n","// A connection's connectorId is \"<piece package>#<piece short name>\"; the\n// runtime only ever needs the package half back out of it, never a version.\nexport function packageFromConnectorId(connectorId: string): string {\n const separator = connectorId.lastIndexOf(\"#\");\n if (separator <= 0) return connectorId;\n const spec = connectorId.slice(0, separator);\n const at = spec.indexOf(\"@\", 1);\n return at > 0 ? spec.slice(0, at) : spec;\n}\n","import type {\n PublishedWorkflow,\n WorkflowState,\n} from \"@powerhousedao/workflow/document-models/workflow\";\n\nexport interface RunnableDefinition {\n // The draft version the definition was taken at; a run records it.\n version: number;\n trigger: PublishedWorkflow[\"trigger\"];\n steps: PublishedWorkflow[\"steps\"];\n edges: PublishedWorkflow[\"edges\"];\n variables: PublishedWorkflow[\"variables\"];\n policy: PublishedWorkflow[\"policy\"] | undefined;\n // False for a document never published, which runs its draft.\n published: boolean;\n}\n\n/** What a trigger arms and a run executes: the published snapshot, or the\n * draft of a document that has none. Design-time reads use the draft. */\nexport function runnableDefinition(state: WorkflowState): RunnableDefinition {\n // Older documents carry no `published` field at all.\n const published = state.published as PublishedWorkflow | null | undefined;\n const source = published ?? state;\n return {\n version: source.version,\n trigger: source.trigger ?? null,\n steps: source.steps,\n edges: source.edges,\n variables: source.variables,\n policy: source.policy as PublishedWorkflow[\"policy\"] | undefined,\n published: published !== null && published !== undefined,\n };\n}\n","// Scaffold file meant for customization; delete and re-run codegen to reset.\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport type { WorkflowRuntimeHostDeps } from \"./host.js\";\nimport {\n ActivepiecesBlockExecutor,\n AttachmentCache,\n BoundConnectionResolver,\n CompositeBlockExecutor,\n sourcedResolver,\n shapeConnection,\n type BlockExecutor,\n type ConnectionAuthType,\n type ConnectionRequest,\n type EngineConnectionResolver,\n type AttachmentPort,\n type BlockResolution,\n type PieceResolver,\n type PieceStorePort,\n type ResolvedConnection,\n type EgressPolicy,\n type ActivepiecesBlockExecutorOptions,\n type SecretProvider,\n type WorkflowDefinition,\n} from \"../pieces/index.js\";\nimport type {\n ConnectionDocument,\n ConnectionState,\n} from \"@powerhousedao/workflow/document-models/connection\";\nimport type { WorkflowState } from \"@powerhousedao/workflow/document-models/workflow\";\nimport { childLogger } from \"document-model\";\nimport { readdir, rm, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n currentBoundConnections,\n currentFlows,\n currentPieceWorker,\n currentRunId,\n currentStepTest,\n currentWaitpoints,\n currentWorkflowId,\n} from \"./run-scope.js\";\nimport { PROJECT_SCOPE_KEY } from \"./piece-store-port.js\";\nimport { packagePieces } from \"./piece-registry.js\";\nimport { packageFromConnectorId } from \"./connector-id.js\";\nimport { runnableDefinition, type RunnableDefinition } from \"./runnable.js\";\nimport type { OAuthTokenRefresher } from \"./oauth.js\";\nimport type { WorkflowTelemetry } from \"../telemetry.js\";\n\nconst pieceLogger = childLogger([\"workflow\", \"piece\"]);\n\n/**\n * The ceiling on one line this engine writes to a log.\n *\n * Nothing here is worth more than this to a reader, and an unbounded write is\n * a liability: a piece error carrying an HTML error page, or a piece logging a\n * whole document, becomes a multi-megabyte write to a pipe that may be\n * blocked — and an EPIPE on the fatal path is what produced the boot loop in\n * backlog item 5. Bounding the write is cheaper than handling the throw.\n */\nexport const MAX_LOG_LINE_CHARS = 8_192;\n\nexport function truncateForLog(text: string): string {\n if (text.length <= MAX_LOG_LINE_CHARS) return text;\n return `${text.slice(0, MAX_LOG_LINE_CHARS)}… [truncated, ${text.length} chars]`;\n}\nconst connectionLogger = childLogger([\"workflow\", \"connection\"]);\n\n// A connection is bound to its connector (doc 08 §10): a step of one piece\n// never receives another piece's credentials.\n\n// Absent information refuses. A caller that named no piece, or a connection\n// whose connectorId is blank, leaves nothing to check against.\nfunction assertConnectorMatches(\n state: ConnectionState,\n request: ConnectionRequest | undefined,\n): void {\n const wanted = request?.piecePackage;\n const owner = state.connectorId\n ? packageFromConnectorId(state.connectorId)\n : \"\";\n if (!wanted || !owner || wanted !== owner) {\n throw new ConnectorMismatchError();\n }\n}\n\n// Says only that this connection is not this caller's to use: naming the\n// owning package would tell an author which connector a guessed id belongs to.\nexport class ConnectorMismatchError extends Error {\n constructor() {\n super(\"Connection is not available to this block\");\n this.name = \"ConnectorMismatchError\";\n }\n}\n\n// Resolves a step's connectionId to a powerhouse/connection document and\n// shapes its auth value; secret refs resolve through the managed store.\nexport class DocumentConnectionResolver implements EngineConnectionResolver {\n constructor(\n private readonly host: WorkflowRuntimeHostDeps,\n private readonly secrets: SecretProvider,\n private readonly oauth?: OAuthTokenRefresher,\n ) {}\n\n async resolve(\n connectionId: string,\n request?: ConnectionRequest,\n ): Promise<unknown> {\n return (await this.resolveWithSecrets(connectionId, request)).auth;\n }\n\n // The secret half is what journal redaction matches on, so it is resolved\n // here rather than guessed from the shaped auth value.\n async resolveWithSecrets(\n connectionId: string,\n request?: ConnectionRequest,\n ): Promise<ResolvedConnection> {\n const document =\n await this.host.reactorClient.get<ConnectionDocument>(connectionId);\n return resolveConnectionWithSecrets(\n document,\n this.secrets,\n request,\n this.oauth,\n );\n }\n}\n\n// The one place that decides whether a connection's credentials may be shaped\n// at all. Takes the document so a caller holding one need not fetch it twice.\nexport async function resolveConnectionAuth(\n document: ConnectionDocument,\n secrets: SecretProvider,\n request?: ConnectionRequest,\n oauth?: OAuthTokenRefresher,\n): Promise<unknown> {\n return (await resolveConnectionWithSecrets(document, secrets, request, oauth))\n .auth;\n}\n\n// The same resolution, with the concrete secret strings the journal redacts\n// on. It runs every check above it: getting the secrets is not a way around\n// the question of who is asking.\nexport async function resolveConnectionWithSecrets(\n document: ConnectionDocument,\n secrets: SecretProvider,\n request?: ConnectionRequest,\n oauth?: OAuthTokenRefresher,\n): Promise<ResolvedConnection> {\n // Nothing before the connector check describes what was found: a document\n // of the wrong type answers exactly as a foreign connection does.\n if (document.header.documentType !== \"powerhouse/connection\") {\n throw new ConnectorMismatchError();\n }\n const state: ConnectionState = document.state.global;\n assertConnectorMatches(state, request);\n // Past the check the caller already holds this connection, so the reason it\n // cannot be used is theirs to see.\n if (state.status === \"REVOKED\") {\n throw new Error(\n `Connection \"${state.name || document.header.id}\" is revoked`,\n );\n }\n const source = {\n authType: state.authType as ConnectionAuthType,\n config: (state.config ?? {}) as Record<string, unknown>,\n secretRefs: state.secretRefs,\n };\n if (source.authType === \"OAUTH2\") {\n await oauth?.refreshIfDue(source, document.header.id);\n }\n return shapeConnection(source, secrets, document.header.id);\n}\n\n// Piece code runs under an egress policy that denies private address space —\n// loopback, the RFC1918 ranges, the cloud metadata endpoint — because a piece\n// config is an SSRF surface and a workflow author is not always the operator.\n//\n// A reactor co-hosted with what it integrates has to widen that, or every one\n// of its connections is unreachable: a local demo pointing at\n// http://localhost:18081 fails at the first poll, and so does the dropdown that\n// would have offered it. The widening names addresses rather than switching the\n// guard off, so allowing a demo's loopback services leaves the rest of private\n// space — and the metadata endpoint — denied.\n//\n// PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES=127.0.0.1/32,::1/128\n//\n// Unset, the default policy applies and nothing private is reachable.\nconst EGRESS_ALLOW_ENV = \"PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES\";\n\n// A bare address is one host, not a guess at the network around it.\nfunction asCidr(entry: string): string {\n if (entry.includes(\"/\")) return entry;\n return entry.includes(\":\") ? `${entry}/128` : `${entry}/32`;\n}\n\nexport function configuredEgress(): EgressPolicy | undefined {\n const raw = process.env[EGRESS_ALLOW_ENV];\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const allowAddresses = raw\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\")\n .map(asCidr);\n if (allowAddresses.length === 0) return undefined;\n pieceLogger.info(\n `Egress policy widened by ${EGRESS_ALLOW_ENV}: ${allowAddresses.join(\", \")}`,\n );\n return { allowAddresses };\n}\n\nlet bundleCache = join(resolvePhDir(), \"ap-bundles\");\n\nexport function bundleCacheDir(): string {\n return bundleCache;\n}\n\n// Test seam: a suite keeps its fetched bundles apart from every other suite.\nexport function setBundleCacheDir(dir: string): void {\n bundleCache = dir;\n resolver = undefined;\n}\n\n// Where a piece's ctx.files output and its staged attachment inputs live for\n// the length of one step. Under .ph so a host can sweep it on startup after a\n// crash; the executor removes each step's directory itself.\nexport const ATTACHMENT_STAGING_DIR = join(\n resolvePhDir(),\n \"ap-attachment-staging\",\n);\n\n// Downloaded attachments kept by content, so later steps and runs reuse them.\nexport const ATTACHMENT_CACHE_DIR = join(resolvePhDir(), \"ap-attachment-cache\");\n\nconst DEFAULT_ATTACHMENT_CACHE_BYTES = 1024 * 1024 * 1024;\n\n// PH_WORKFLOWS_ATTACHMENT_CACHE_BYTES; 0 turns the cache off.\nexport function attachmentCacheBytes(): number {\n const raw = process.env.PH_WORKFLOWS_ATTACHMENT_CACHE_BYTES;\n const parsed = raw === undefined ? NaN : Number(raw);\n return Number.isFinite(parsed) && parsed >= 0\n ? Math.floor(parsed)\n : DEFAULT_ATTACHMENT_CACHE_BYTES;\n}\n\n// A step removes its own directory; this clears what a crashed host left.\n// Only entries older than a step could run, so a live step is never swept.\nexport async function sweepAttachmentStaging(\n root: string = ATTACHMENT_STAGING_DIR,\n olderThanMs = 60 * 60 * 1000,\n): Promise<number> {\n const names = await readdir(root).catch(() => [] as string[]);\n let swept = 0;\n for (const name of names) {\n const entry = join(root, name);\n const info = await stat(entry).catch(() => undefined);\n if (!info || Date.now() - info.mtimeMs < olderThanMs) continue;\n await rm(entry, { recursive: true, force: true });\n swept += 1;\n }\n return swept;\n}\n\nlet stagingSwept = false;\n\n// Fetches a piece from the source its resolution chose. One instance: a run\n// and the editor must load the same bytes for the same resolution.\nlet resolver: PieceResolver | undefined;\n\nexport function pieceResolver(): PieceResolver {\n return (resolver ??= sourcedResolver({\n cacheDir: bundleCacheDir(),\n // Asked per call: the host refills the registry as packages change.\n lookup: (name) => packagePieces.lookup(name),\n }));\n}\n\n// The executor is shared by every concurrent run, so the binding travels with\n// the run scope rather than sitting on the resolver.\nexport function boundConnections(\n inner: EngineConnectionResolver,\n): EngineConnectionResolver {\n return new BoundConnectionResolver(\n inner,\n currentBoundConnections,\n (connectionId, request) => {\n // Named apart from a missing connection so an operator can tell a\n // misconfigured step from an attempt to reach a foreign credential.\n connectionLogger.warn(\n `Step \"${request?.stepKey ?? \"?\"}\" of workflow \"${currentWorkflowId() ?? \"?\"}\" asked for connection \"${connectionId}\", which its definition does not declare`,\n );\n },\n );\n}\n\nexport function createBlockExecutor(\n host: WorkflowRuntimeHostDeps,\n secrets: SecretProvider,\n attachments?: AttachmentPort,\n pieceStore?: PieceStorePort,\n // The runtime's resolution policy, shared with triggers and design time.\n resolveBlock?: (block: BlockRef) => Promise<BlockResolution>,\n oauth?: OAuthTokenRefresher,\n reactorAccess?: ActivepiecesBlockExecutorOptions[\"reactorAccess\"],\n telemetry?: WorkflowTelemetry,\n): BlockExecutor {\n if (attachments && !stagingSwept) {\n stagingSwept = true;\n void sweepAttachmentStaging().then(\n (swept) => {\n if (swept > 0) {\n pieceLogger.info(\n `Removed ${swept} leftover attachment staging dir(s)`,\n );\n }\n },\n () => undefined,\n );\n }\n const cacheBytes = attachmentCacheBytes();\n // The document blocks are a piece; they reach the reactor through\n // reactorAccess like any other declaring piece.\n return new CompositeBlockExecutor(\n new ActivepiecesBlockExecutor({\n cacheDir: bundleCacheDir(),\n // Undefined leaves the connectors' default policy in force; a value only\n // ever widens it.\n egress: configuredEgress(),\n // Asked per step, for the same reason the binding is: one executor,\n // many runs, and each run has a child of its own.\n worker: currentPieceWorker,\n stepTest: currentStepTest,\n waitpoints: currentWaitpoints,\n flows: currentFlows,\n // A workflow is a flow; the reactor is the project, as it is for\n // ctx.store's PROJECT scope.\n identity: () => ({\n runId: currentRunId(),\n flowId: currentWorkflowId(),\n projectId: PROJECT_SCOPE_KEY,\n }),\n resolver: pieceResolver(),\n ...(resolveBlock ? { resolveBlock } : {}),\n ...(reactorAccess ? { reactorAccess } : {}),\n ...(telemetry ? { telemetry } : {}),\n connections: boundConnections(\n new DocumentConnectionResolver(host, secrets, oauth),\n ),\n // Without it an action's ctx.store lives only in the worker's heap.\n ...(pieceStore ? { pieceStore } : {}),\n // The worker's stdio is discarded, so a piece's own console output is\n // invisible until it is forwarded here.\n onPieceLog: (entry, execution) => {\n // Truncated HERE as well as in the child. The child caps an entry at\n // 8KB, but a remote transport need not, and an oversized write to a\n // blocked stdout is how the fatal-shutdown EPIPE loop started\n // (backlog item 5): the log line must never be the thing that kills\n // the process.\n const line = truncateForLog(`[${execution.step.key}] ${entry.message}`);\n if (entry.level === \"error\") pieceLogger.error(line);\n else if (entry.level === \"warn\") pieceLogger.warn(line);\n else if (entry.level === \"debug\") pieceLogger.debug(line);\n else pieceLogger.info(line);\n },\n // Without an attachment store a piece's ctx.files still works, but\n // inline as a data URI; with one, bytes go to the store and the output\n // carries a reference.\n ...(attachments\n ? {\n attachments,\n stagingRoot: ATTACHMENT_STAGING_DIR,\n ...(cacheBytes > 0\n ? {\n attachmentCache: new AttachmentCache({\n dir: ATTACHMENT_CACHE_DIR,\n maxBytes: cacheBytes,\n }),\n }\n : {}),\n }\n : {}),\n }),\n );\n}\n\nexport function propertySettings(\n settings:\n | readonly { prop: string; mode: string; schema?: unknown }[]\n | null\n | undefined,\n): WorkflowDefinition[\"steps\"][number][\"propertySettings\"] {\n return settings?.map((setting) => ({\n prop: setting.prop,\n mode: setting.mode,\n schema: setting.schema ?? null,\n }));\n}\n\n// One runnable step in engine shape.\nexport function stepDefinition(\n step: RunnableDefinition[\"steps\"][number],\n): WorkflowDefinition[\"steps\"][number] {\n return {\n id: step.id,\n key: step.key,\n name: step.name,\n pieceName: step.pieceName,\n pieceVersion: step.pieceVersion,\n actionName: step.actionName,\n connectionId: step.connectionId,\n reactorConnectionId: step.reactorConnectionId,\n config: step.config,\n timeoutSeconds: step.timeoutSeconds,\n propertySettings: propertySettings(step.propertySettings),\n skip: step.skip,\n // The author's retry block, which the coordinator resolves against the\n // workflow policy's defaultRetry.\n retry: step.retry,\n };\n}\n\n// The runnable definition (see runnable.ts) in engine shape.\nexport function toWorkflowDefinition(state: WorkflowState): WorkflowDefinition {\n const runnable = runnableDefinition(state);\n if (!runnable.trigger) {\n throw new Error(\"Workflow has no trigger binding\");\n }\n return {\n name: state.name,\n trigger: {\n id: runnable.trigger.id,\n pieceName: runnable.trigger.pieceName,\n pieceVersion: runnable.trigger.pieceVersion,\n triggerName: runnable.trigger.triggerName,\n connectionId: runnable.trigger.connectionId,\n reactorConnectionId: runnable.trigger.reactorConnectionId,\n config: runnable.trigger.config,\n propertySettings: propertySettings(runnable.trigger.propertySettings),\n },\n steps: runnable.steps.map(stepDefinition),\n edges: runnable.edges.map((edge) => ({\n id: edge.id,\n from: edge.from,\n to: edge.to,\n port: edge.port,\n condition: edge.condition,\n })),\n variables: runnable.variables.map((variable) => ({\n key: variable.key,\n value: variable.value,\n })),\n };\n}\n","// Next-fire math for the core schedule trigger. Config parsing is the shared\n// parser's; this adds croner's check that the cron is valid and ever fires.\nimport {\n DEFAULT_TIMEZONE,\n parseScheduleConfig as parseSharedSchedule,\n ScheduleConfigError,\n type ScheduleConfig,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport { Cron } from \"croner\";\n\nexport { DEFAULT_TIMEZONE, type ScheduleConfig };\n\n// The floor the supervisor clamps every poll cadence to, however a workflow\n// asked for it. A schedule's own floor is a minute, its smallest unit.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport function parseScheduleConfig(config: unknown): ScheduleConfig {\n const schedule = parseSharedSchedule(config);\n if (schedule.mode !== \"cron\") return schedule;\n let cronJob: Cron;\n try {\n cronJob = new Cron(schedule.cron, {\n timezone: schedule.timezone,\n legacyMode: false,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ScheduleConfigError(\n `invalid cron \"${schedule.cron}\": ${message}`,\n );\n }\n if (!cronJob.nextRun()) {\n throw new ScheduleConfigError(`cron \"${schedule.cron}\" never fires`);\n }\n return schedule;\n}\n\n// Strictly after `from`. A cron slot erased by a DST jump resolves to the\n// first valid instant after it, so it still fires once.\nexport function nextFireAt(schedule: ScheduleConfig, from: Date): Date {\n if (schedule.mode === \"interval\") {\n return new Date(from.getTime() + schedule.everyMs);\n }\n const next = new Cron(schedule.cron, {\n timezone: schedule.timezone,\n legacyMode: false,\n }).nextRun(from);\n if (!next) {\n throw new Error(`Schedule: cron \"${schedule.cron}\" never fires`);\n }\n return next;\n}\n\n// Interval mode keeps its phase while still ahead of `now` (no tick drift);\n// an overdue slot fires once and rebases on `now` rather than replaying.\nexport function rescheduleAfterFire(\n schedule: ScheduleConfig,\n scheduledFor: Date,\n now: Date,\n): Date {\n if (schedule.mode === \"interval\") {\n const onPhase = new Date(scheduledFor.getTime() + schedule.everyMs);\n return onPhase > now ? onPhase : nextFireAt(schedule, now);\n }\n return nextFireAt(schedule, now);\n}\n\nexport interface SchedulePayload {\n scheduledFor: string;\n firedAt: string;\n timezone: string;\n cron?: string;\n everyMs?: number;\n}\n\nexport function schedulePayload(\n schedule: ScheduleConfig,\n scheduledFor: Date,\n firedAt: Date,\n): SchedulePayload {\n return {\n scheduledFor: scheduledFor.toISOString(),\n firedAt: firedAt.toISOString(),\n timezone: schedule.timezone,\n ...(schedule.mode === \"cron\"\n ? { cron: schedule.cron }\n : { everyMs: schedule.everyMs }),\n };\n}\n\n// Poll cadence implied by a piece's setSchedule cron: the gap between its\n// next two runs, floored. Undefined when it is invalid or never repeats.\nexport function cronIntervalMs(\n cron: string,\n from = new Date(),\n): number | undefined {\n try {\n const job = new Cron(cron.trim(), { timezone: \"UTC\", legacyMode: false });\n const runs = job.nextRuns(2, from);\n if (runs.length < 2) return undefined;\n return Math.max(\n runs[1].getTime() - runs[0].getTime(),\n MIN_SCHEDULE_INTERVAL_MS,\n );\n } catch {\n return undefined;\n }\n}\n","// A workflow created elsewhere can be asked about before it syncs here.\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\n\nexport const SYNC_WAIT_MS = 10_000;\nconst SYNC_POLL_MS = 200;\n\nexport const WORKFLOW_SYNCING_MESSAGE =\n \"Workflow is still syncing; try again in a moment\";\n\n// Retryable: the document has not reached this reactor yet.\nexport class WorkflowSyncingError extends Error {\n readonly code = \"WORKFLOW_SYNCING\";\n readonly retryable = true;\n\n constructor() {\n super(WORKFLOW_SYNCING_MESSAGE);\n this.name = \"WorkflowSyncingError\";\n }\n}\n\nexport interface WorkflowAccessOptions {\n // The drive the caller opened the workflow from; lets a call wait for sync.\n driveId?: string;\n}\n\n// No stream under the id yet. A deleted document keeps its stream, so it\n// never reads as on its way.\nexport async function isNotHereYet(\n client: Pick<IReactorClient, \"isDocumentIdTaken\">,\n documentId: string,\n): Promise<boolean> {\n try {\n return !(await client.isDocumentIdTaken(documentId));\n } catch {\n return false;\n }\n}\n\n// Retries `check` until it passes or `timeoutMs` ends, polling while the\n// document is absent. Throws WorkflowSyncingError if it never arrived.\nexport async function waitForSync(\n client: Pick<IReactorClient, \"isDocumentIdTaken\">,\n documentId: string,\n check: () => Promise<unknown>,\n timeoutMs: number,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n let denied: unknown;\n let arrived = false;\n while (Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, SYNC_POLL_MS));\n if (await isNotHereYet(client, documentId)) continue;\n arrived = true;\n try {\n await check();\n return;\n } catch (error) {\n denied = error;\n }\n }\n if (!arrived) throw new WorkflowSyncingError();\n throw denied;\n}\n","// Reactor errors cross the worker boundary by name; pieces test those names.\nimport {\n DENIED_ACTION_INDEXES,\n ReactorAccessDeniedError,\n type ReactorErrorName,\n} from \"@powerhousedao/pieces-framework\";\n\nexport {\n DocumentModelUnavailableError,\n ReactorAccessDeniedError,\n ReactorActionsFailedError,\n ReactorJobFailedError,\n ReactorJobPendingError,\n ReactorRequestClosedError,\n type ReactorErrorName,\n} from \"@powerhousedao/pieces-framework\";\n\nexport class ReactorError extends Error {\n constructor(\n override readonly name: ReactorErrorName,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport function accessDenied(message: string): ReactorError {\n return new ReactorError(ReactorAccessDeniedError, message);\n}\n\nexport type DeniedAction = { index: number; type: string; reason: string };\n\n// The gate's denial. Only name and message cross the worker boundary, so the\n// message ends with the indexes `deniedActionIndexes` reads.\nexport class ReactorActionsDeniedError extends ReactorError {\n constructor(\n documentId: string,\n readonly denied: DeniedAction[],\n ) {\n super(ReactorAccessDeniedError, deniedMessage(documentId, denied));\n }\n}\n\nfunction deniedMessage(documentId: string, denied: DeniedAction[]): string {\n const actions = denied.map(({ type, reason }) => `${type} (${reason})`);\n const indexes = denied.map(({ index }) => index).join(\",\");\n return `The run user may not apply ${actions.join(\", \")} to document ${documentId}; ${DENIED_ACTION_INDEXES}[${indexes}]`;\n}\n\n// A client method no piece is offered.\nexport function refusedMethod(method: string): ReactorError {\n return accessDenied(`${method} is not available to workflow pieces`);\n}\n\nexport function isReactorError(\n error: unknown,\n name: ReactorErrorName,\n): error is ReactorError {\n return error instanceof Error && error.name === name;\n}\n","// The run user: the signer of the latest publish. Runs execute the published\n// snapshot, so the publisher vouches for what runs (ADR 0005 §6).\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport type {\n ActionSigner,\n Operation,\n} from \"@powerhousedao/shared/document-model\";\nimport type { HostIdentity } from \"./host.js\";\nimport type { RunUser } from \"./run-scope.js\";\n\nexport const PUBLISH_WORKFLOW = \"PUBLISH_WORKFLOW\";\n\n// The subject derives as the reactor's own (authSubjectFromSigner). A signer\n// with no address or no signature is an unsigned publish.\nexport function runUserOfOperation(\n operation: Pick<Operation, \"action\">,\n hostIdentity?: HostIdentity,\n): RunUser | null {\n // Partial: a signer-less client leaves user and app unset.\n const signer = operation.action.context?.signer as\n | Partial<ActionSigner>\n | undefined;\n const address = signer?.user?.address;\n if (!signer || !address || !signer.signatures?.length) return null;\n const key = signer.app?.key;\n // The host signs what a caller sent unsigned, which vouches for nobody.\n if (hostIdentity && key === hostIdentity.key) return null;\n return { address, subject: { address, key } };\n}\n\n// The latest publish that applied; null when it was unsigned, host-signed or\n// there is none.\nexport async function publishRunUser(\n client: Pick<IReactorClient, \"getOperations\">,\n workflowId: string,\n hostIdentity?: HostIdentity,\n signal?: AbortSignal,\n): Promise<RunUser | null> {\n let page = await client.getOperations(\n workflowId,\n { scopes: [\"global\"] },\n { actionTypes: [PUBLISH_WORKFLOW] },\n undefined,\n signal,\n );\n let latest: Operation | undefined;\n for (;;) {\n for (const operation of page.results) {\n if (operation.action.type !== PUBLISH_WORKFLOW) continue;\n if (operation.error !== undefined) continue;\n if (!latest || operation.index > latest.index) latest = operation;\n }\n if (!page.next || page.results.length === 0) break;\n page = await page.next();\n }\n return latest ? runUserOfOperation(latest, hostIdentity) : null;\n}\n","// The read check on a snapshot's reactor connections (ADR 0005 §6), run on\n// publish, on enable and before each run.\nimport type { WorkflowRuntimeHostDeps } from \"./host.js\";\nimport { accessDenied } from \"./reactor-errors.js\";\nimport type { RunUser } from \"./run-scope.js\";\nimport { publishRunUser } from \"./run-user.js\";\n\n// Absent counts as on: a host that doesn't say gets the strict checks.\nexport function authEnforced(\n host: Pick<WorkflowRuntimeHostDeps, \"authEnforcement\">,\n): boolean {\n return host.authEnforcement !== false;\n}\n\nexport const NO_RUN_USER_DENIAL =\n \"The workflow was published unsigned or by the Switchboard itself, so it gets no reactor access while auth enforcement is on; publish it signed in\";\n\n// The reactor's read gate, as the run user, on a reactor connection.\nexport async function assertConnectionReadable(\n host: Pick<WorkflowRuntimeHostDeps, \"reactorClient\">,\n connectionId: string,\n runUser: RunUser,\n): Promise<void> {\n const served = await host.reactorClient\n .isServed(connectionId, { subject: runUser.subject })\n .catch(() => false);\n if (!served) {\n throw accessDenied(\n `${runUser.address} cannot read reactor connection \"${connectionId}\"`,\n );\n }\n}\n\n// Resolves the run user, and throws ReactorAccessDeniedError when it may not\n// read a bound connection. Binding none needs no run user, so none is read.\nexport async function assertReactorConnectionsReadable(\n host: Pick<\n WorkflowRuntimeHostDeps,\n \"reactorClient\" | \"authEnforcement\" | \"hostIdentity\"\n >,\n workflowId: string,\n connectionIds: ReadonlySet<string>,\n // Known already, as when the publish operation is at hand.\n known?: RunUser | null,\n): Promise<RunUser | null | undefined> {\n if (connectionIds.size === 0) return undefined;\n const runUser =\n known !== undefined\n ? known\n : await publishRunUser(host.reactorClient, workflowId, host.hostIdentity);\n if (!runUser) {\n if (authEnforced(host)) throw accessDenied(NO_RUN_USER_DENIAL);\n return null;\n }\n for (const connectionId of connectionIds) {\n await assertConnectionReadable(host, connectionId, runUser);\n }\n return runUser;\n}\n","// Builds the part of a step's RunScope that a reactor connection decides; the\n// caller adds `deadline` and `journal`.\nimport {\n isReactorConnectorId,\n parseReactorConnectionConfig,\n type ConnectionDocument,\n} from \"@powerhousedao/workflow/document-models/connection\";\nimport type { WorkflowRuntimeHostDeps } from \"./host.js\";\nimport { authEnforced, NO_RUN_USER_DENIAL } from \"./reactor-access.js\";\nimport { accessDenied } from \"./reactor-errors.js\";\nimport type { RunScope, RunUser } from \"./run-scope.js\";\n\nexport type ReactorRunScopeBase = Pick<\n RunScope,\n \"runUser\" | \"requireReactor\" | \"connection\"\n>;\n\nexport interface ReactorRunScopeRequest {\n // The step's or trigger's reactorConnectionId, from the pinned snapshot.\n reactorConnectionId: string | null | undefined;\n requireReactor: \"read\" | \"write\";\n // From the run's pre-run check: null for an unsigned publish.\n runUser: RunUser | null;\n}\n\n// Throws ReactorAccessDeniedError when the step cannot have reactor access.\nexport async function buildReactorRunScope(\n host: Pick<WorkflowRuntimeHostDeps, \"reactorClient\" | \"authEnforcement\">,\n request: ReactorRunScopeRequest,\n): Promise<ReactorRunScopeBase> {\n const { reactorConnectionId, requireReactor, runUser } = request;\n if (!reactorConnectionId) {\n throw accessDenied(\n \"This step needs reactor access; bind a reactor connection\",\n );\n }\n if (!runUser && authEnforced(host)) {\n throw accessDenied(NO_RUN_USER_DENIAL);\n }\n let document: ConnectionDocument;\n try {\n document =\n await host.reactorClient.get<ConnectionDocument>(reactorConnectionId);\n } catch {\n throw accessDenied(\n `Reactor connection \"${reactorConnectionId}\" was not found`,\n );\n }\n const state = document.state.global;\n if (\n document.header.documentType !== \"powerhouse/connection\" ||\n state.authType !== \"REACTOR\" ||\n !isReactorConnectorId(state.connectorId)\n ) {\n throw accessDenied(\n `Connection \"${reactorConnectionId}\" is not a reactor connection`,\n );\n }\n if (state.status === \"REVOKED\") {\n throw accessDenied(\n `Reactor connection \"${reactorConnectionId}\" is revoked`,\n );\n }\n const parsed = parseReactorConnectionConfig(state.config);\n if (!parsed.ok) {\n throw accessDenied(\n `Reactor connection \"${reactorConnectionId}\" is invalid: ${parsed.error}`,\n );\n }\n return {\n runUser,\n requireReactor,\n connection: { access: parsed.config.access ?? \"write\" },\n };\n}\n","// The reactor client one piece step gets: the host's client, acting as the\n// run user within the step's declaration, connection and deadline (ADR 0005).\nimport {\n assertActionsApplied,\n type IndexQueryRequest,\n type IndexQueryResult,\n type ReactorClient,\n type ReactorWriteClient,\n} from \"@powerhousedao/pieces-framework\";\nimport {\n createEmptyDocument,\n deleteDocumentAction,\n jobIdsOf,\n JobStatus,\n placeholderJob,\n PropagationMode,\n remoteStagePort,\n WriteHandleFactory,\n type ActionCandidate,\n type ActionEvaluations,\n type ConsistencyToken,\n type DocumentRelationship,\n type HandleReader,\n type IReactorClient,\n type JobInfo,\n type NodeWriteHandle,\n type OperationFilter,\n type PagedResults,\n type PagingOptions,\n type RemoteReads,\n type SearchFilter,\n type ViewFilter,\n type WriteHandle,\n} from \"@powerhousedao/reactor\";\nimport {\n isFolderNode,\n type FolderNode,\n type Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n DOCUMENT_SCOPE_ACTION_TYPES,\n initializeAuth,\n normalizeDocumentModelVersion,\n withSignaturePolicy,\n type Action,\n type AuthSubject,\n type DocumentModelModule,\n type Grant,\n type Operation,\n type PHDocument,\n type Principal,\n} from \"@powerhousedao/shared/document-model\";\nimport type { WorkflowRuntimeHostDeps } from \"./host.js\";\nimport { authEnforced, NO_RUN_USER_DENIAL } from \"./reactor-access.js\";\nimport {\n accessDenied,\n ReactorActionsDeniedError,\n ReactorError,\n ReactorJobFailedError,\n ReactorJobPendingError,\n} from \"./reactor-errors.js\";\nimport type { RunScope } from \"./run-scope.js\";\n\nexport type RunScopedHostDeps = Pick<\n WorkflowRuntimeHostDeps,\n \"authEnforcement\" | \"queryIndex\"\n>;\n\nexport interface RunScopedReactorClientOptions {\n // Largest page a listing serves.\n maxPageLimit?: number;\n // Granted execute, beside the run user, on documents the run creates.\n hostPrincipal?: Principal;\n}\n\nexport const DEFAULT_MAX_PAGE_LIMIT = 100;\n\nconst JOB_NOT_FOUND = \"Job not found\";\n\n// Stop waiting this long before the deadline, to report why.\nconst MIN_DEADLINE_MARGIN_MS = 250;\nconst MAX_DEADLINE_MARGIN_MS = 2_000;\n\nexport function deadlineMargin(budgetMs: number): number {\n return Math.min(\n Math.max(Math.floor(budgetMs / 10), MIN_DEADLINE_MARGIN_MS),\n MAX_DEADLINE_MARGIN_MS,\n );\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction jobPending(jobId: string, status: string): ReactorError {\n return new ReactorError(\n ReactorJobPendingError,\n status === \"UNKNOWN\"\n ? `Reactor job ${jobId} is unknown to the reactor, as after a restart; its actions may or may not have been written`\n : `Reactor job ${jobId} was still ${status} at the step deadline; its actions may yet be written`,\n );\n}\n\n// The reactor's admission refused the host, which signs every write.\nconst AUTHORIZATION_DENIED = \"AuthorizationDeniedError\";\n\nfunction jobFailed(job: JobInfo): ReactorError {\n const error = job.error;\n // The reactor's message names the operation, scope and document.\n if (\n error?.name === AUTHORIZATION_DENIED ||\n error?.message.startsWith(\"Authorization denied\")\n ) {\n return accessDenied(\n `The Switchboard has no grant for this operation: ${error.message}`,\n );\n }\n return new ReactorError(\n ReactorJobFailedError,\n `Reactor job ${job.id} failed: ${job.error?.message ?? \"unknown error\"}`,\n );\n}\n\nconst DOCUMENT_DRIVE = \"powerhouse/document-drive\";\nconst REACTOR_DRIVE = \"powerhouse/reactor-drive\";\n\ntype DriveType = typeof DOCUMENT_DRIVE | typeof REACTOR_DRIVE;\n\ntype DriveTarget = { id: string; documentType: DriveType };\n\nfunction isDriveType(documentType: string): documentType is DriveType {\n return documentType === DOCUMENT_DRIVE || documentType === REACTOR_DRIVE;\n}\n\n// The drive-side action of a file added: a document drive's ADD_FILE, or a\n// reactor drive's child relationship.\nfunction fileCandidate(\n drive: DriveTarget,\n document: PHDocument,\n parentFolder: string | undefined,\n): ActionCandidate {\n const { id, documentType, name } = document.header;\n if (drive.documentType === DOCUMENT_DRIVE) {\n return {\n scope: \"global\",\n type: \"ADD_FILE\",\n input: { id, name: name || id, documentType, parentFolder },\n };\n }\n return {\n scope: \"document\",\n type: \"ADD_RELATIONSHIP\",\n input: {\n sourceId: drive.id,\n targetId: id,\n relationshipType: \"drive/child\",\n metadata: {\n kind: \"file\",\n parentFolderId: parentFolder ?? null,\n documentType,\n },\n },\n };\n}\n\nfunction folderCandidate(\n drive: DriveTarget,\n name: string,\n parentFolder: string | undefined,\n): ActionCandidate {\n return drive.documentType === DOCUMENT_DRIVE\n ? { scope: \"global\", type: \"ADD_FOLDER\", input: { name, parentFolder } }\n : {\n scope: \"document\",\n type: \"ADD_FOLDER\",\n input: { name, parentFolderId: parentFolder ?? null },\n };\n}\n\n// The piece surface; `servedClient` refuses every other method. Reads pass\n// the run user as subject; writes pass `evaluateActions` as the run user.\nexport class RunScopedReactorClient implements ReactorClient {\n private readonly stopAt: number;\n private readonly maxPageLimit: number;\n // Jobs this client submitted, the only ones `read` answers for.\n private readonly jobs = new Set<string>();\n private readonly handles: WriteHandleFactory;\n\n constructor(\n private readonly inner: IReactorClient,\n private readonly scope: RunScope,\n private readonly host: RunScopedHostDeps,\n private readonly options: RunScopedReactorClientOptions = {},\n ) {\n this.stopAt = scope.deadline - deadlineMargin(scope.deadline - Date.now());\n this.maxPageLimit = options.maxPageLimit ?? DEFAULT_MAX_PAGE_LIMIT;\n this.handles = new WriteHandleFactory(remoteStagePort(this.read));\n }\n\n // --- Reads -------------------------------------------------------------\n\n async getDocumentModelModules(\n namespace?: string,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<DocumentModelModule>> {\n this.assertAccess();\n return this.inner.getDocumentModelModules(\n namespace,\n this.paging(paging),\n this.signal(signal),\n );\n }\n\n getDocumentModelModule(\n documentType: string,\n ): Promise<DocumentModelModule<any>> {\n this.assertAccess();\n return this.inner.getDocumentModelModule(documentType);\n }\n\n getDocumentModelModuleForDocument(\n document: PHDocument,\n ): Promise<DocumentModelModule<any>> {\n this.assertAccess();\n return this.inner.getDocumentModelModuleForDocument(document);\n }\n\n async get<TDocument extends PHDocument>(\n identifier: string,\n view?: ViewFilter,\n signal?: AbortSignal,\n consistencyToken?: ConsistencyToken,\n ): Promise<TDocument> {\n const document = await this.inner.get<TDocument>(\n identifier,\n this.readView(view),\n this.signal(signal),\n consistencyToken,\n );\n await this.scope.journal.recordDocuments([document.header.id]);\n return document;\n }\n\n resolveIdOrSlug(\n identifier: string,\n view?: ViewFilter,\n signal?: AbortSignal,\n ): Promise<string> {\n return this.inner.resolveIdOrSlug(\n identifier,\n this.readView(view),\n this.signal(signal),\n );\n }\n\n async getOperations(\n documentIdentifier: string,\n view?: ViewFilter,\n filter?: OperationFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n const readView = this.readView(view);\n const abort = this.signal(signal);\n const id = await this.inner.resolveIdOrSlug(\n documentIdentifier,\n readView,\n abort,\n );\n const page = await this.inner.getOperations(\n id,\n readView,\n filter,\n this.paging(paging),\n abort,\n );\n return this.journaled(page, () => [id]);\n }\n\n async getOutgoingRelationships(\n sourceIdentifier: string,\n relationshipType: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<PHDocument>> {\n return this.documents(\n await this.inner.getOutgoingRelationships(\n sourceIdentifier,\n relationshipType,\n this.readView(view),\n this.paging(paging),\n this.signal(signal),\n ),\n );\n }\n\n async getIncomingRelationships(\n targetIdentifier: string,\n relationshipType: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<PHDocument>> {\n return this.documents(\n await this.inner.getIncomingRelationships(\n targetIdentifier,\n relationshipType,\n this.readView(view),\n this.paging(paging),\n this.signal(signal),\n ),\n );\n }\n\n getOutgoingRelationshipEdges(\n sourceIdentifier: string,\n relationshipType?: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<DocumentRelationship>> {\n return this.inner.getOutgoingRelationshipEdges(\n sourceIdentifier,\n relationshipType,\n this.readView(view),\n this.paging(paging),\n this.signal(signal),\n );\n }\n\n getIncomingRelationshipEdges(\n targetIdentifier: string,\n relationshipType?: string,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<DocumentRelationship>> {\n return this.inner.getIncomingRelationshipEdges(\n targetIdentifier,\n relationshipType,\n this.readView(view),\n this.paging(paging),\n this.signal(signal),\n );\n }\n\n async find(\n search: SearchFilter,\n view?: ViewFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<PHDocument>> {\n return this.documents(\n await this.inner.find(\n search,\n this.readView(view),\n this.paging(paging),\n this.signal(signal),\n ),\n );\n }\n\n // A read-model index, answered by the host as the run user: the index's own\n // access declarations decide, as they would for the same user over HTTP.\n // No run user under enforcement reads nothing, as every other read.\n async query(\n request: IndexQueryRequest,\n signal?: AbortSignal,\n ): Promise<IndexQueryResult> {\n const queryIndex = this.host.queryIndex;\n if (!queryIndex) {\n throw accessDenied(\n \"This host serves no read-model indexes to pieces (reactor.query)\",\n );\n }\n this.assertAccess();\n return queryIndex(request, this.scope.runUser, this.signal(signal));\n }\n\n // --- Writes ------------------------------------------------------------\n\n // The write half: each write answers once its jobs are accepted, with a\n // handle over `read`. A reducer error is on the receipt, not thrown.\n readonly write: ReactorWriteClient = {\n create: (document, parentIdentifier, signal) =>\n this.writeCreate(document, parentIdentifier, signal),\n createEmpty: (documentModelType, options, signal) =>\n this.writeCreateEmpty(\n \"write.createEmpty\",\n documentModelType,\n options,\n this.signal(signal),\n ),\n execute: (documentIdentifier, branch, actions, signal) =>\n this.submitExecute(\n \"write.execute\",\n documentIdentifier,\n branch,\n actions,\n this.signal(signal),\n ),\n deleteDocument: (identifier, propagate, signal) =>\n this.submitDelete(\n \"write.deleteDocument\",\n identifier,\n propagate,\n this.signal(signal),\n ),\n drives: {\n addFile: (driveIdentifier, document, parentFolder, signal) =>\n this.submitAddFile(\n \"write.drives.addFile\",\n driveIdentifier,\n document,\n parentFolder,\n this.signal(signal),\n ),\n addFolder: (driveIdentifier, name, parentFolder, signal) =>\n this.submitAddFolder(\n \"write.drives.addFolder\",\n driveIdentifier,\n name,\n parentFolder,\n this.signal(signal),\n ),\n },\n };\n\n // What a write handle reads through: this client's own jobs, within the\n // deadline, and documents gated as `get` gates them.\n readonly read: RemoteReads = {\n waitForJob: async (jobId, signal) => {\n this.assertOwnJob(jobId);\n return this.settle(jobId, this.signal(signal));\n },\n getJobStatus: async (jobId, signal) => {\n this.assertOwnJob(jobId);\n return this.inner.getJobStatus(jobId, this.signal(signal));\n },\n get: (identifier, view, signal, consistencyToken) =>\n this.get(identifier, view, signal, consistencyToken),\n };\n\n async create<TDocument extends PHDocument = PHDocument>(\n document: PHDocument,\n parentIdentifier?: string,\n signal?: AbortSignal,\n ): Promise<TDocument> {\n this.assertWritable(\"create\");\n const abort = this.signal(signal);\n const parentId = await this.parentOf(parentIdentifier, abort);\n const handle = await this.submitCreate(document, parentId, abort);\n return this.createdBack<TDocument>(handle, abort);\n }\n\n async newDocument<TDocument extends PHDocument = PHDocument>(\n documentModelType: string,\n options?: Parameters<IReactorClient[\"newDocument\"]>[1],\n signal?: AbortSignal,\n ): Promise<TDocument> {\n this.assertWritable(\"newDocument\");\n const abort = this.signal(signal);\n const module = await this.modelModule(\n documentModelType,\n options?.documentModelVersion,\n abort,\n );\n const parentId = await this.parentOf(options?.parentIdentifier, abort);\n const base = await this.inner.getCreateProtocolVersions(\n { documentType: documentModelType, parentIdentifier: parentId },\n abort,\n );\n return createEmptyDocument(\n module,\n options,\n await this.inner.getCreateSignaturePolicy(),\n base,\n ) as TDocument;\n }\n\n async createEmpty<TDocument extends PHDocument>(\n documentModelType: string,\n options?: Parameters<IReactorClient[\"createEmpty\"]>[1],\n signal?: AbortSignal,\n ): Promise<TDocument> {\n const abort = this.signal(signal);\n const handle = await this.writeCreateEmpty(\n \"createEmpty\",\n documentModelType,\n options,\n abort,\n );\n return this.createdBack<TDocument>(handle, abort);\n }\n\n async execute<TDocument extends PHDocument>(\n documentIdentifier: string,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n subject?: AuthSubject,\n ): Promise<TDocument> {\n if (subject !== undefined) {\n throw accessDenied(\"A piece may not choose the subject it reads as\");\n }\n const abort = this.signal(signal);\n const handle = await this.submitExecute(\n \"execute\",\n documentIdentifier,\n branch,\n actions,\n abort,\n );\n await this.landed(handle, abort, actions);\n return this.readBack<TDocument>(handle.documentId, branch, abort);\n }\n\n // As `execute`, and answered at the same point (every action applied, or a\n // throw), but with the settled job and no read of the document.\n async executeAsync(\n documentIdentifier: string,\n branch: string,\n actions: Action[],\n signal?: AbortSignal,\n ): Promise<JobInfo> {\n const abort = this.signal(signal);\n const handle = await this.submitExecute(\n \"executeAsync\",\n documentIdentifier,\n branch,\n actions,\n abort,\n );\n return this.landed(handle, abort, actions);\n }\n\n async deleteDocument(\n identifier: string,\n propagate?: PropagationMode,\n signal?: AbortSignal,\n ): Promise<void> {\n const abort = this.signal(signal);\n const handle = await this.submitDelete(\n \"deleteDocument\",\n identifier,\n propagate,\n abort,\n );\n await this.landed(handle, abort);\n }\n\n private async writeCreate(\n document: PHDocument,\n parentIdentifier: string | undefined,\n signal: AbortSignal | undefined,\n ): Promise<WriteHandle> {\n this.assertWritable(\"write.create\");\n const abort = this.signal(signal);\n const parentId = await this.parentOf(parentIdentifier, abort);\n return this.submitCreate(document, parentId, abort);\n }\n\n private async writeCreateEmpty(\n method: string,\n documentModelType: string,\n options: Parameters<IReactorClient[\"createEmpty\"]>[1],\n abort: AbortSignal,\n ): Promise<WriteHandle> {\n this.assertWritable(method);\n const document = await this.newDocument(documentModelType, options, abort);\n const parentId = await this.parentOf(options?.parentIdentifier, abort);\n return this.submitCreate(document, parentId, abort);\n }\n\n // The checks and the gate, then the job.\n private async submitExecute(\n method: string,\n documentIdentifier: string,\n branch: string,\n actions: Action[],\n abort: AbortSignal,\n ): Promise<WriteHandle> {\n this.assertWritable(method);\n for (const action of actions) {\n if (action.context?.signer) {\n throw accessDenied(\n `Action ${action.type} carries a signer; the host signs every action`,\n );\n }\n // Pieces change documents through model operations only.\n if (DOCUMENT_SCOPE_ACTION_TYPES.has(action.type)) {\n throw accessDenied(\n `${action.type} is a document lifecycle action, which pieces may not execute`,\n );\n }\n }\n const id = await this.resolveReference(documentIdentifier, branch, abort);\n await this.gate(id, branch, actions, abort);\n return this.submit(id, branch, actions, abort);\n }\n\n // The run user's DELETE_DOCUMENT passes the gate; the client's parent edge\n // removals ride on the Switchboard's grant.\n private async submitDelete(\n method: string,\n identifier: string,\n propagate: PropagationMode | undefined,\n abort: AbortSignal,\n ): Promise<WriteHandle> {\n this.assertWritable(method);\n if (propagate === PropagationMode.Cascade) {\n throw accessDenied(\"Cascade delete is not offered to pieces\");\n }\n const id = await this.resolveReference(identifier, \"main\", abort);\n await this.gate(id, \"main\", [deleteDocumentAction(id)], abort);\n this.assertTimeLeft(\"a delete\");\n await this.scope.journal.recordDocuments([id]);\n const submitted = await this.inner.write.deleteDocument(\n id,\n undefined,\n abort,\n );\n return this.handle(submitted, await this.track(submitted, () => [id]));\n }\n\n // --- Drives ------------------------------------------------------------\n\n // Checked before the inner client signs as the host: the drive is read and\n // the drive-side action gated as the run user; a new file gets its grant.\n readonly drives: ReactorClient[\"drives\"] = {\n getNode: (driveIdentifier, nodeId, signal) =>\n this.getNode(driveIdentifier, nodeId, signal),\n listNodes: (driveIdentifier, parentFolder, paging, signal) =>\n this.listNodes(driveIdentifier, parentFolder, paging, signal),\n addFile: (driveIdentifier, document, parentFolder, signal) =>\n this.addFile(driveIdentifier, document, parentFolder, signal),\n addFolder: (driveIdentifier, name, parentFolder, signal) =>\n this.addFolder(driveIdentifier, name, parentFolder, signal),\n };\n\n private async getNode(\n driveIdentifier: string,\n nodeId: string,\n signal?: AbortSignal,\n ): Promise<Node> {\n const abort = this.signal(signal);\n const drive = await this.readDrive(driveIdentifier, abort);\n return this.inner.drives.getNode(drive.id, nodeId, abort);\n }\n\n private async listNodes(\n driveIdentifier: string,\n parentFolder?: string | null,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Node>> {\n const abort = this.signal(signal);\n const drive = await this.readDrive(driveIdentifier, abort);\n return this.inner.drives.listNodes(\n drive.id,\n parentFolder,\n this.paging(paging),\n abort,\n );\n }\n\n private async addFile<TDocument extends PHDocument = PHDocument>(\n driveIdentifier: string,\n document: PHDocument,\n parentFolder?: string,\n signal?: AbortSignal,\n ): Promise<TDocument> {\n const abort = this.signal(signal);\n const handle = await this.submitAddFile(\n \"drives.addFile\",\n driveIdentifier,\n document,\n parentFolder,\n abort,\n );\n return this.createdBack<TDocument>(handle, abort, true);\n }\n\n private async addFolder(\n driveIdentifier: string,\n name: string,\n parentFolder?: string,\n signal?: AbortSignal,\n ): Promise<FolderNode> {\n const abort = this.signal(signal);\n const handle = await this.submitAddFolder(\n \"drives.addFolder\",\n driveIdentifier,\n name,\n parentFolder,\n abort,\n );\n await this.landed(handle, abort);\n const node = await this.inner.drives.getNode(\n handle.documentId,\n handle.nodeId,\n abort,\n );\n if (!isFolderNode(node)) throw new Error(\"Folder creation failed\");\n return node;\n }\n\n // The document batch has completed when the inner write answers.\n private async submitAddFile(\n method: string,\n driveIdentifier: string,\n document: PHDocument,\n parentFolder: string | undefined,\n abort: AbortSignal,\n ): Promise<WriteHandle> {\n this.assertWritable(method);\n const drive = await this.readDrive(driveIdentifier, abort);\n const prepared = withSignaturePolicy(\n document,\n await this.inner.getCreateSignaturePolicy(),\n );\n const documentId = prepared.header.id;\n await this.gateCandidates(\n drive.id,\n \"main\",\n [fileCandidate(drive, prepared, parentFolder)],\n abort,\n );\n this.assertTimeLeft(`a ${prepared.header.documentType} document`);\n await this.scope.journal.recordDocuments([drive.id, documentId]);\n const submitted = await this.inner.write.drives.addFile(\n drive.id,\n prepared,\n parentFolder,\n abort,\n );\n const jobIds = await this.track(submitted, () => [drive.id, documentId]);\n return this.withGrant(submitted, jobIds, abort, true);\n }\n\n private async submitAddFolder(\n method: string,\n driveIdentifier: string,\n name: string,\n parentFolder: string | undefined,\n abort: AbortSignal,\n ): Promise<NodeWriteHandle> {\n this.assertWritable(method);\n const drive = await this.readDrive(driveIdentifier, abort);\n await this.gateCandidates(\n drive.id,\n \"main\",\n [folderCandidate(drive, name, parentFolder)],\n abort,\n );\n this.assertTimeLeft(\"a folder\");\n await this.scope.journal.recordDocuments([drive.id]);\n const submitted = await this.inner.write.drives.addFolder(\n drive.id,\n name,\n parentFolder,\n abort,\n );\n const jobIds = await this.track(submitted, () => [drive.id]);\n return Object.assign(this.handle(submitted, jobIds), {\n nodeId: submitted.nodeId,\n });\n }\n\n // The drive's header, read as the run user; a type with no known node\n // write is refused before anything is submitted.\n private async readDrive(\n driveIdentifier: string,\n signal: AbortSignal,\n ): Promise<DriveTarget> {\n const drive = await this.inner.get(\n driveIdentifier,\n this.readView({ scopes: [\"document\"] }),\n signal,\n );\n const { id, documentType } = drive.header;\n if (!isDriveType(documentType)) {\n throw accessDenied(`Document ${id} is a ${documentType}, not a drive`);\n }\n await this.scope.journal.recordDocuments([id]);\n return { id, documentType };\n }\n\n // --- Access ------------------------------------------------------------\n\n private get subject(): AuthSubject | undefined {\n return this.scope.runUser?.subject;\n }\n\n private assertAccess(): void {\n if (this.scope.runUser === null && authEnforced(this.host)) {\n throw accessDenied(NO_RUN_USER_DENIAL);\n }\n }\n\n // The declaration and the connection's access, for a write method.\n private assertWritable(method: string): void {\n this.assertAccess();\n if (this.scope.requireReactor !== \"write\") {\n throw accessDenied(\n `${method} writes, and this step declares read access only`,\n );\n }\n if (this.scope.connection.access !== \"write\") {\n throw accessDenied(\n `${method} writes, and the reactor connection grants read access only`,\n );\n }\n }\n\n private readView(view?: ViewFilter): ViewFilter {\n this.assertAccess();\n if (view?.subject !== undefined) {\n throw accessDenied(\"A piece may not choose the subject it reads as\");\n }\n return { ...view, subject: this.subject };\n }\n\n private signal(signal?: AbortSignal): AbortSignal {\n const deadline = AbortSignal.timeout(\n Math.max(0, this.scope.deadline - Date.now()),\n );\n return signal ? AbortSignal.any([signal, deadline]) : deadline;\n }\n\n private paging(paging?: PagingOptions): PagingOptions {\n return {\n cursor: paging?.cursor ?? \"\",\n limit: Math.min(paging?.limit ?? this.maxPageLimit, this.maxPageLimit),\n };\n }\n\n // What admission would decide for the run user.\n private async gate(\n documentId: string,\n branch: string,\n actions: readonly Action[],\n signal: AbortSignal,\n ): Promise<void> {\n await this.gateCandidates(\n documentId,\n branch,\n actions.map((action) => ({\n scope: action.scope,\n type: action.type,\n input: action.input,\n })),\n signal,\n );\n }\n\n private async gateCandidates(\n documentId: string,\n branch: string,\n candidates: ActionCandidate[],\n signal: AbortSignal,\n ): Promise<void> {\n if (!authEnforced(this.host) || candidates.length === 0) return;\n let answer: ActionEvaluations;\n try {\n answer = await this.inner.evaluateActions(\n documentId,\n branch,\n candidates,\n this.subject,\n signal,\n );\n } catch (error) {\n throw accessDenied(\n `Could not check the run user's access to document ${documentId}: ${messageOf(error)}`,\n );\n }\n const denied = answer.evaluations.flatMap((evaluation, index) =>\n evaluation.decision === \"deny\"\n ? [{ index, type: candidates[index].type, reason: evaluation.reason }]\n : [],\n );\n if (denied.length > 0) {\n throw new ReactorActionsDeniedError(documentId, denied);\n }\n }\n\n // --- Write path ----------------------------------------------------------\n\n private async submit(\n documentId: string,\n branch: string,\n actions: Action[],\n signal: AbortSignal,\n ): Promise<WriteHandle> {\n this.assertTimeLeft(`${actions.length} action(s)`);\n const submitted = await this.inner.write.execute(\n documentId,\n branch,\n actions,\n signal,\n );\n return this.handle(\n submitted,\n await this.track(submitted, () => [documentId]),\n );\n }\n\n // Submits actions; throws unless every action applied. Answers the job.\n private async run(\n documentId: string,\n branch: string,\n actions: Action[],\n signal: AbortSignal,\n ): Promise<JobInfo> {\n const handle = await this.submit(documentId, branch, actions, signal);\n return this.landed(handle, signal, actions);\n }\n\n // Journals a write's jobs at submit and opens them to `read`, own job first.\n private async track(\n submitted: WriteHandle,\n documentsOf: (jobId: string) => string[],\n ): Promise<string[]> {\n const jobIds = [\n submitted.jobId,\n ...jobIdsOf(submitted).filter((jobId) => jobId !== submitted.jobId),\n ].filter((jobId) => jobId !== \"\");\n for (const jobId of jobIds) {\n this.jobs.add(jobId);\n await this.scope.journal.recordJob(jobId, documentsOf(jobId));\n }\n return jobIds;\n }\n\n // The handle a piece rebuilds: these jobs, read back through `read`.\n private handle(submitted: WriteHandle, jobIds: string[]): WriteHandle {\n const { documentId, branch } = submitted;\n const reader: HandleReader = (receipt, view, signal) =>\n this.get(\n documentId,\n { ...view, branch: receipt.branch },\n signal,\n receipt.token,\n );\n return jobIds.length === 0\n ? this.handles.settled(documentId, branch, reader)\n : this.handles.forJobs(\n submitted.jobId,\n jobIds.map((jobId) => placeholderJob(jobId, documentId)),\n documentId,\n branch,\n undefined,\n reader,\n );\n }\n\n // The facade's wait: every job of the write settled and applied, or a\n // throw. Answers the write's own job.\n private async landed(\n handle: WriteHandle,\n signal: AbortSignal,\n actions?: readonly Action[],\n onLanded?: (jobId: string) => void,\n ): Promise<JobInfo> {\n let own: JobInfo | undefined;\n for (const jobId of jobIdsOf(handle)) {\n const job = await this.settle(jobId, signal);\n if (job.status === JobStatus.FAILED) throw jobFailed(job);\n assertActionsApplied(job, jobId === handle.jobId ? actions : undefined);\n if (jobId === handle.jobId) own = job;\n onLanded?.(jobId);\n }\n return own ?? (await handle.readable).job;\n }\n\n // The facade's read-back of a document a write created; once it exists, a\n // later failure says so.\n private async createdBack<TDocument extends PHDocument = PHDocument>(\n handle: WriteHandle,\n signal: AbortSignal,\n created = false,\n ): Promise<TDocument> {\n try {\n await this.landed(handle, signal, undefined, (jobId) => {\n if (jobId === handle.jobId) created = true;\n });\n return await this.readBack<TDocument>(\n handle.documentId,\n handle.branch,\n signal,\n );\n } catch (error) {\n if (created && error instanceof Error) {\n error.message = `Document ${handle.documentId} was created, but: ${error.message}`;\n }\n throw error;\n }\n }\n\n private assertTimeLeft(what: string): void {\n if (Date.now() >= this.stopAt) {\n throw new Error(\n `No time was left before the step deadline to submit ${what}; nothing was submitted`,\n );\n }\n }\n\n private assertOwnJob(jobId: string): void {\n if (!this.jobs.has(jobId)) {\n throw accessDenied(`Job ${String(jobId)} was not submitted by this step`);\n }\n }\n\n // Answers a job READ_READY or FAILED, or throws it pending at the deadline.\n private async settle(jobId: string, signal: AbortSignal): Promise<JobInfo> {\n let status: string = JobStatus.PENDING;\n for (;;) {\n const remaining = this.stopAt - Date.now();\n if (remaining <= 0) throw jobPending(jobId, status);\n const wait = AbortSignal.any([signal, AbortSignal.timeout(remaining)]);\n let job: JobInfo;\n try {\n job = await this.inner.waitForJob(jobId, wait);\n } catch (error) {\n // The caller's abort is its own; only the deadline reports pending.\n if (!wait.aborted || signal.aborted) throw error;\n job = await this.inner.getJobStatus(jobId).catch(() => {\n throw jobPending(jobId, status);\n });\n if (\n job.status !== JobStatus.READ_READY &&\n job.status !== JobStatus.FAILED\n ) {\n throw jobPending(jobId, job.status);\n }\n }\n if (job.status === JobStatus.FAILED) {\n if (job.error?.message === JOB_NOT_FOUND) {\n throw jobPending(jobId, \"UNKNOWN\");\n }\n return job;\n }\n if (job.status === JobStatus.READ_READY) return job;\n status = job.status;\n }\n }\n\n private async readBack<TDocument extends PHDocument = PHDocument>(\n documentId: string,\n branch: string,\n signal: AbortSignal,\n ): Promise<TDocument> {\n const document = await this.inner.get<TDocument>(\n documentId,\n { branch, subject: this.subject },\n signal,\n );\n await this.scope.journal.recordDocuments([documentId]);\n return document;\n }\n\n // Submits a create. With a run user, waits for it to land and grants the run\n // user; the grant's job joins the handle.\n private async submitCreate(\n document: PHDocument,\n parentId: string | undefined,\n signal: AbortSignal,\n ): Promise<WriteHandle> {\n // New documents get the host's create signature policy.\n const prepared = withSignaturePolicy(\n document,\n await this.inner.getCreateSignaturePolicy(),\n );\n const documentId = prepared.header.id;\n this.assertTimeLeft(`a ${prepared.header.documentType} document`);\n const submitted = await this.inner.write.create(prepared, parentId, signal);\n const jobIds = await this.track(submitted, (jobId) =>\n jobId === submitted.jobId || parentId === undefined\n ? [documentId]\n : [parentId, documentId],\n );\n return this.withGrant(submitted, jobIds, signal);\n }\n\n // Once every job has settled; a failed one is left for the handle to report.\n private async withGrant(\n submitted: WriteHandle,\n jobIds: string[],\n signal: AbortSignal,\n created = false,\n ): Promise<WriteHandle> {\n if (!this.scope.runUser) return this.handle(submitted, jobIds);\n try {\n for (const jobId of jobIds) {\n const job = await this.settle(jobId, signal);\n if (job.status === JobStatus.FAILED) {\n return this.handle(submitted, jobIds);\n }\n created = true;\n }\n const grant = await this.grantRunUser(submitted.documentId, signal);\n return this.handle(submitted, grant ? [...jobIds, grant.id] : jobIds);\n } catch (error) {\n if (created && error instanceof Error) {\n error.message = `Document ${submitted.documentId} was created, but: ${error.message}`;\n }\n throw error;\n }\n }\n\n // A document the run creates starts with a grant for its user.\n private async grantRunUser(\n documentId: string,\n signal: AbortSignal,\n ): Promise<JobInfo | undefined> {\n const runUser = this.scope.runUser;\n if (!runUser) return undefined;\n const created = await this.inner.get(documentId, undefined, signal);\n if (created.state.auth.version !== 0) return undefined;\n const grants: Grant[] = [\n {\n id: \"run-user\",\n description: \"The user whose workflow run created this document\",\n effect: \"allow\",\n principal: { address: runUser.address },\n capability: { can: \"execute\" },\n },\n ];\n if (this.options.hostPrincipal) {\n grants.push({\n id: \"run-host\",\n description: \"The host that runs the workflow\",\n effect: \"allow\",\n principal: this.options.hostPrincipal,\n capability: { can: \"execute\" },\n });\n }\n return this.run(\n documentId,\n \"main\",\n [initializeAuth({ version: 1, grants })],\n signal,\n );\n }\n\n // --- Helpers -------------------------------------------------------------\n\n private parentOf(\n identifier: string | undefined,\n signal: AbortSignal,\n ): Promise<string | undefined> {\n return identifier === undefined\n ? Promise.resolve(undefined)\n : this.resolveReference(identifier, \"main\", signal);\n }\n\n // An id no document has is taken as given, as the client does.\n private async resolveReference(\n identifier: string,\n branch: string,\n signal: AbortSignal,\n ): Promise<string> {\n try {\n return await this.inner.resolveIdOrSlug(identifier, { branch }, signal);\n } catch {\n return identifier;\n }\n }\n\n private async modelModule(\n documentType: string,\n version: number | undefined,\n signal: AbortSignal,\n ): Promise<DocumentModelModule> {\n if (version === undefined) {\n return this.inner.getDocumentModelModule(documentType);\n }\n const requested = normalizeDocumentModelVersion(version);\n let page = await this.inner.getDocumentModelModules(\n undefined,\n undefined,\n signal,\n );\n for (;;) {\n const module = page.results.find(\n (m) =>\n m.documentModel.global.id === documentType &&\n normalizeDocumentModelVersion(m.version) === requested,\n );\n if (module) return module;\n if (!page.next) break;\n page = await page.next();\n }\n throw new Error(\n `Document model not found for type: ${documentType} with version: ${version}`,\n );\n }\n\n private documents(\n page: PagedResults<PHDocument>,\n ): Promise<PagedResults<PHDocument>> {\n return this.journaled(page, (documents) =>\n documents.map((document) => document.header.id),\n );\n }\n\n // Journals each page's documents, later pages included.\n private async journaled<T>(\n page: PagedResults<T>,\n idsOf: (results: T[]) => string[],\n ): Promise<PagedResults<T>> {\n await this.scope.journal.recordDocuments(idsOf(page.results));\n const next = page.next;\n return {\n ...page,\n next: next ? async () => this.journaled(await next(), idsOf) : undefined,\n };\n }\n}\n","// ctx.reactor on the host: one ReactorHostServer per piece request, serving a\n// RunScopedReactorClient over the request's IPC transport (ADR 0005 §3).\nimport type {\n DriveReadMethods,\n DriveWriteHalfMethods,\n DriveWriteMethods,\n IndexQueryMethods,\n ReactorClient,\n ReadMethods,\n RefusedDriveMethods,\n RefusedMethods,\n RefusedWriteHalfMethods,\n WriteHalfMethods,\n WriteMethods,\n} from \"@powerhousedao/pieces-framework\";\nimport type { IReactorClient, RemoteReads } from \"@powerhousedao/reactor\";\nimport {\n ReactorHostServer,\n type IRpcTransport,\n} from \"@powerhousedao/reactor/rpc\";\nimport { context as otelContext } from \"@opentelemetry/api\";\nimport type { ReactorTap } from \"../pieces/index.js\";\nimport { tracedMethods, type WorkflowTelemetry } from \"../telemetry.js\";\nimport type { WorkflowRuntimeHostDeps } from \"./host.js\";\nimport { accessDenied, refusedMethod } from \"./reactor-errors.js\";\nimport type { ReactorRunScopeBase } from \"./run-scope-builder.js\";\nimport { currentDocumentRecorder, type RunScope } from \"./run-scope.js\";\nimport {\n RunScopedReactorClient,\n type RunScopedHostDeps,\n type RunScopedReactorClientOptions,\n} from \"./run-scoped-client.js\";\n\n// Answered by the worker's own registry: modules hold functions, which IPC cannot carry.\ntype WorkerMethods =\n | \"getDocumentModelModules\"\n | \"getDocumentModelModule\"\n | \"getDocumentModelModuleForDocument\";\n\n// A key per method, so a list change fails to compile. `query` is the\n// read-model index read the framework adds beside the client's own methods.\nconst SERVED: Record<\n Exclude<ReadMethods | WriteMethods, WorkerMethods> | keyof IndexQueryMethods,\n true\n> = {\n get: true,\n resolveIdOrSlug: true,\n find: true,\n query: true,\n getOperations: true,\n getOutgoingRelationships: true,\n getIncomingRelationships: true,\n getOutgoingRelationshipEdges: true,\n getIncomingRelationshipEdges: true,\n newDocument: true,\n create: true,\n createEmpty: true,\n execute: true,\n executeAsync: true,\n deleteDocument: true,\n};\n\nconst SERVED_DRIVES: Record<DriveReadMethods | DriveWriteMethods, true> = {\n getNode: true,\n listNodes: true,\n addFile: true,\n addFolder: true,\n};\n\nconst REFUSED_DRIVES: Record<RefusedDriveMethods, true> = {\n create: true,\n removeNode: true,\n renameNode: true,\n moveNode: true,\n copyNode: true,\n setPreferredEditorOnNode: true,\n};\n\nconst SERVED_WRITE: Record<WriteHalfMethods, true> = {\n create: true,\n createEmpty: true,\n execute: true,\n deleteDocument: true,\n};\n\nconst SERVED_DRIVE_WRITES: Record<DriveWriteHalfMethods, true> = {\n addFile: true,\n addFolder: true,\n};\n\nconst REFUSED_WRITE: Record<RefusedWriteHalfMethods, true> = {\n isDocumentIdTaken: true,\n describe: true,\n evaluateActions: true,\n upgradeDocument: true,\n executeBatch: true,\n rename: true,\n setPreferredEditor: true,\n addRelationship: true,\n updateRelationship: true,\n removeRelationship: true,\n moveRelationship: true,\n deleteDocuments: true,\n loadBatch: true,\n undo: true,\n redo: true,\n undoRedoTargets: true,\n undoRedoAvailability: true,\n};\n\n// What the piece's write handles call; the client admits only its own jobs.\nconst SERVED_READ: Record<keyof RemoteReads, true> = {\n waitForJob: true,\n getJobStatus: true,\n get: true,\n};\n\n// Refused by name, so a piece learns why. `read` serves only its handles.\nconst REFUSED: Record<Exclude<RefusedMethods, \"read\">, true> = {\n getMany: true,\n createDocumentInDrive: true,\n executeBatch: true,\n rename: true,\n setPreferredEditor: true,\n addRelationship: true,\n updateRelationship: true,\n removeRelationship: true,\n moveRelationship: true,\n upgradeDocument: true,\n deleteDocuments: true,\n createAsync: true,\n createEmptyAsync: true,\n getJobStatus: true,\n waitForJob: true,\n subscribe: true,\n loadBatch: true,\n evaluateActions: true,\n isDocumentIdTaken: true,\n isServed: true,\n getCreateSignaturePolicy: true,\n getCreateProtocolVersions: true,\n undo: true,\n redo: true,\n undoRedoTargets: true,\n undoRedoAvailability: true,\n};\n\ntype AnyMethod = (...args: unknown[]) => unknown;\n\n// The server calls any method of the client it holds, so it holds only these:\n// no prototype, and none of the wrapper's internals.\nexport function servedClient(\n client: ReactorClient & { read?: RemoteReads },\n): IReactorClient & IndexQueryMethods {\n const facade = served(\n client as unknown as Record<string, AnyMethod>,\n SERVED,\n REFUSED,\n \"\",\n ) as Record<string, unknown>;\n facade.drives = served(\n client.drives as unknown as Record<string, AnyMethod>,\n SERVED_DRIVES,\n REFUSED_DRIVES,\n \"drives.\",\n );\n const write = served(\n client.write as unknown as Record<string, AnyMethod>,\n SERVED_WRITE,\n REFUSED_WRITE,\n \"write.\",\n ) as Record<string, unknown>;\n write.drives = served(\n client.write.drives as unknown as Record<string, AnyMethod>,\n SERVED_DRIVE_WRITES,\n REFUSED_DRIVES,\n \"write.drives.\",\n );\n facade.write = write;\n if (client.read) {\n facade.read = served(\n client.read as unknown as Record<string, AnyMethod>,\n SERVED_READ,\n {},\n \"read.\",\n );\n }\n return facade as unknown as IReactorClient & IndexQueryMethods;\n}\n\nfunction served(\n methods: Record<string, AnyMethod>,\n serve: Record<string, true>,\n refuse: Record<string, true>,\n prefix: string,\n): Record<string, AnyMethod> {\n const facade = Object.create(null) as Record<string, AnyMethod>;\n for (const name of Object.keys(serve)) {\n facade[name] = (...args: unknown[]) => methods[name](...args);\n }\n for (const name of Object.keys(refuse)) {\n facade[name] = () => {\n throw refusedMethod(prefix + name);\n };\n }\n return facade;\n}\n\n// The run's journal: documents a step reads or writes, and a write's\n// documents at submit, go to the run's run_document rows.\nexport function runJournal(): RunScope[\"journal\"] {\n const record = currentDocumentRecorder();\n return {\n recordDocuments: (documentIds) =>\n record ? record(documentIds) : Promise.resolve(),\n recordJob: (_jobId, documentIds) =>\n record ? record(documentIds) : Promise.resolve(),\n };\n}\n\nexport const NO_JOURNAL: RunScope[\"journal\"] = {\n recordDocuments: () => Promise.resolve(),\n recordJob: () => Promise.resolve(),\n};\n\nexport type ReactorSessionHost = RunScopedHostDeps &\n Pick<WorkflowRuntimeHostDeps, \"reactorClient\" | \"hostPrincipal\">;\n\n// Serves one request: the deadline is the request's, the rest decided before.\nexport function reactorTap(\n host: ReactorSessionHost,\n base: ReactorRunScopeBase,\n journal: RunScope[\"journal\"],\n options: RunScopedReactorClientOptions = {},\n telemetry?: WorkflowTelemetry,\n): ReactorTap {\n // Documents a run creates also grant the host, so it can keep writing them.\n const clientOptions: RunScopedReactorClientOptions = {\n ...(host.hostPrincipal ? { hostPrincipal: host.hostPrincipal } : {}),\n ...options,\n };\n return {\n requireReactor: base.requireReactor,\n open(transport, { deadline }) {\n const client = new RunScopedReactorClient(\n host.reactorClient,\n { ...base, deadline, journal },\n host,\n clientOptions,\n );\n const served = servedClient(client);\n // RPC calls arrive as IPC events, outside the step's async context.\n const parent = otelContext.active();\n const server = new ReactorHostServer(\n telemetry\n ? tracedMethods(served, telemetry, \"reactor\", parent, [\n \"drives\",\n \"write\",\n \"read\",\n ])\n : served,\n transport as unknown as IRpcTransport,\n );\n server.start();\n return () => server.stop();\n },\n };\n}\n\n// A design-time resolver reads as the caller, and never writes.\nexport function designTimeScope(\n runUser: ReactorRunScopeBase[\"runUser\"],\n): ReactorRunScopeBase {\n return { runUser, requireReactor: \"read\", connection: { access: \"read\" } };\n}\n\nexport function unboundReactorConnection(reactorConnectionId: string): Error {\n return accessDenied(\n `Reactor connection \"${reactorConnectionId}\" must name a connection, not an expression`,\n );\n}\n","// The core piece's blocks the host serves itself, as keys to compare a block's\n// blockKey with. The piece declares them; schedule.ts and webhook.ts feed them.\nimport {\n blockKey,\n type BlockIdentity,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport { CORE_PIECE_NAME, CORE_PIECE_VERSION } from \"../pieces/index.js\";\n\nconst trigger = (name: string) =>\n blockKey({ pieceName: CORE_PIECE_NAME, kind: \"trigger\", name });\n\nconst action = (name: string) =>\n blockKey({ pieceName: CORE_PIECE_NAME, kind: \"action\", name });\n\nexport const MANUAL_BLOCK = trigger(\"manual\");\nexport const SCHEDULE_BLOCK = trigger(\"schedule\");\nexport const WEBHOOK_BLOCK = trigger(\"webhook\");\nexport const BRANCH_BLOCK = action(\"branch\");\nexport const ROUTER_BLOCK = action(\"router\");\nexport const LOOP_BLOCK = action(\"loop\");\nexport const ASSERT_BLOCK = action(\"assert\");\nexport const DELAY_BLOCK = action(\"delay\");\nexport const APPROVAL_BLOCK = action(\"approval\");\nexport const STOP_BLOCK = action(\"stop\");\nexport const WAIT_FOR_WEBHOOK_BLOCK = action(\"waitForWebhook\");\n\nexport function isCoreBlock(block: BlockIdentity): boolean {\n return block.pieceName === CORE_PIECE_NAME;\n}\n\n// A core trigger pinned to the installed core piece.\nexport function coreTrigger(name: string): BlockRef {\n return {\n pieceName: CORE_PIECE_NAME,\n pieceVersion: CORE_PIECE_VERSION,\n kind: \"trigger\",\n name,\n };\n}\n","// Managed secrets in the relational \"secrets\" namespace, AES-256-GCM at rest;\n// master key from PH_WORKFLOWS_SECRETS_MASTER_KEY or a generated key file.\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport {\n parseSecretRef,\n secretRefFromId,\n SecretDeletedError,\n SecretNotFoundError,\n SecretOwnerMismatchError,\n type SecretOwner,\n type SecretStat,\n type SecretStore,\n} from \"../pieces/index.js\";\nimport {\n createCipheriv,\n createDecipheriv,\n createHmac,\n randomBytes,\n} from \"node:crypto\";\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst KEY_BYTES = 32;\nconst MASTER_KEY_ENV = \"PH_WORKFLOWS_SECRETS_MASTER_KEY\";\nconst LEGACY_MASTER_KEY_ENV = \"PH_SECRETS_MASTER_KEY\";\nconst KEY_CHECK_ID = \"master\";\nconst KEY_CHECK_LABEL = \"reactor-workflow/secrets/key-check/v1\";\n\nexport interface SecretRow {\n id: string;\n label: string | null;\n // The document the secret was minted for; null on pre-ownership rows.\n owner_id: string | null;\n // Lower-cased address of the user who saved it; null when anonymous.\n created_by: string | null;\n version: number;\n // base64(iv || tag || ciphertext); null once deleted.\n enc: string | null;\n status: string; // ACTIVE | DELETED\n created_at: string;\n updated_at: string;\n}\n\n// Fingerprint of the key the namespace's secrets are encrypted with.\ninterface KeyCheckRow {\n id: string;\n fingerprint: string;\n created_at: string;\n}\n\ninterface SecretsDB {\n secret: SecretRow;\n secret_key_check: KeyCheckRow;\n}\n\nasync function up(db: IRelationalDb<SecretsDB>): Promise<void> {\n await db.schema\n .createTable(\"secret\")\n .addColumn(\"id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"label\", \"text\")\n .addColumn(\"owner_id\", \"text\")\n .addColumn(\"created_by\", \"text\")\n .addColumn(\"version\", \"integer\", (col) => col.notNull())\n .addColumn(\"enc\", \"text\")\n .addColumn(\"status\", \"text\", (col) => col.notNull())\n .addColumn(\"created_at\", \"text\", (col) => col.notNull())\n .addColumn(\"updated_at\", \"text\", (col) => col.notNull())\n .ifNotExists()\n .execute();\n // Additive migration for namespaces created before secrets had owners.\n for (const column of [\"owner_id\", \"created_by\"]) {\n try {\n await db.schema.alterTable(\"secret\").addColumn(column, \"text\").execute();\n } catch {\n // column already exists\n }\n }\n await db.schema\n .createTable(\"secret_key_check\")\n .addColumn(\"id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"fingerprint\", \"text\", (col) => col.notNull())\n .addColumn(\"created_at\", \"text\", (col) => col.notNull())\n .ifNotExists()\n .execute();\n}\n\nexport interface LocalSecretStoreOptions {\n // 64 hex chars (32 bytes); defaults to PH_WORKFLOWS_SECRETS_MASTER_KEY.\n masterKeyHex?: string;\n // Where a key is generated when none is set; false requires one instead.\n keyFile?: string | false;\n}\n\nfunction legacyKeyHint(): string {\n return process.env[LEGACY_MASTER_KEY_ENV] !== undefined\n ? ` ${LEGACY_MASTER_KEY_ENV} is set but no longer read; rename it to ${MASTER_KEY_ENV}.`\n : \"\";\n}\n\nexport class MasterKeyRequiredError extends Error {\n constructor() {\n super(\n `${MASTER_KEY_ENV} must be set: this host's secrets outlive its working directory, so a generated key would be lost on restart.${legacyKeyHint()}`,\n );\n this.name = \"MasterKeyRequiredError\";\n }\n}\n\nexport class MasterKeyMismatchError extends Error {\n constructor() {\n super(\n `The secrets master key is not the one this database's secrets were stored with. Set ${MASTER_KEY_ENV} to that key; if it is lost, the stored secrets cannot be recovered.${legacyKeyHint()}`,\n );\n this.name = \"MasterKeyMismatchError\";\n }\n}\n\nfunction readKeyFile(file: string): Buffer | undefined {\n try {\n const key = Buffer.from(readFileSync(file, \"utf8\").trim(), \"hex\");\n if (key.length !== KEY_BYTES) {\n throw new Error(`Key file \"${file}\" is not 32 bytes of hex`);\n }\n return key;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n return undefined;\n }\n}\n\nfunction loadKey(options: LocalSecretStoreOptions): Buffer {\n const hex = options.masterKeyHex ?? process.env[MASTER_KEY_ENV];\n if (hex !== undefined) {\n if (!/^[0-9a-f]{64}$/i.test(hex)) {\n throw new Error(\"Secrets master key must be 64 hex chars (32 bytes)\");\n }\n return Buffer.from(hex, \"hex\");\n }\n if (options.keyFile === false) throw new MasterKeyRequiredError();\n const file = options.keyFile ?? join(resolvePhDir(), \"secrets.key\");\n const kept = readKeyFile(file);\n if (kept) return kept;\n // A shell's stores from before this followed PH_USER_DATA_DIR are encrypted\n // with the key left in the working directory, so a relocated tree takes a\n // copy of it. The original stays: every other identity needs it too.\n const left =\n options.keyFile === undefined\n ? readKeyFile(join(resolvePhDir(process.cwd(), {}), \"secrets.key\"))\n : undefined;\n const key = left ?? randomBytes(KEY_BYTES);\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, key.toString(\"hex\") + \"\\n\", { mode: 0o600 });\n return key;\n}\n\nfunction encrypt(key: Buffer, value: string): string {\n const iv = randomBytes(IV_BYTES);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const ciphertext = Buffer.concat([\n cipher.update(value, \"utf8\"),\n cipher.final(),\n ]);\n return Buffer.concat([iv, cipher.getAuthTag(), ciphertext]).toString(\n \"base64\",\n );\n}\n\nfunction decrypt(key: Buffer, enc: string): string {\n const raw = Buffer.from(enc, \"base64\");\n const iv = raw.subarray(0, IV_BYTES);\n const tag = raw.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);\n const decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n decipher.setAuthTag(tag);\n return Buffer.concat([\n decipher.update(raw.subarray(IV_BYTES + TAG_BYTES)),\n decipher.final(),\n ]).toString(\"utf8\");\n}\n\nfunction decrypts(key: Buffer, enc: string): boolean {\n try {\n decrypt(key, enc);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function storedFingerprint(\n db: IRelationalDb<SecretsDB>,\n): Promise<string | undefined> {\n const row = await db\n .selectFrom(\"secret_key_check\")\n .select(\"fingerprint\")\n .where(\"id\", \"=\", KEY_CHECK_ID)\n .executeTakeFirst();\n return row?.fingerprint;\n}\n\n// Refuses a key other than the one the namespace was first used with. A\n// namespace from before the check is judged by its newest secret.\nasync function verifyKey(\n db: IRelationalDb<SecretsDB>,\n key: Buffer,\n): Promise<void> {\n const fingerprint = createHmac(\"sha256\", key)\n .update(KEY_CHECK_LABEL)\n .digest(\"hex\");\n let stored = await storedFingerprint(db);\n if (stored === undefined) {\n const newest = await db\n .selectFrom(\"secret\")\n .select(\"enc\")\n .where(\"enc\", \"is not\", null)\n .orderBy(\"updated_at\", \"desc\")\n .limit(1)\n .executeTakeFirst();\n if (newest?.enc && !decrypts(key, newest.enc)) {\n throw new MasterKeyMismatchError();\n }\n await db\n .insertInto(\"secret_key_check\")\n .values({\n id: KEY_CHECK_ID,\n fingerprint,\n created_at: new Date().toISOString(),\n })\n .onConflict((oc) => oc.column(\"id\").doNothing())\n .execute();\n // A concurrent first start may have written its own.\n stored = await storedFingerprint(db);\n }\n if (stored !== fingerprint) throw new MasterKeyMismatchError();\n}\n\nexport class LocalEncryptedSecretStore implements SecretStore {\n private constructor(\n private readonly db: IRelationalDb<SecretsDB>,\n private readonly key: Buffer,\n ) {}\n\n static async create(\n relationalDb: IRelationalDb,\n options: LocalSecretStoreOptions = {},\n ): Promise<LocalEncryptedSecretStore> {\n const db = (await relationalDb.createNamespace(\n \"secrets\",\n )) as IRelationalDb<SecretsDB>;\n await up(db);\n const key = loadKey(options);\n await verifyKey(db, key);\n return new LocalEncryptedSecretStore(db, key);\n }\n\n private encrypt(value: string): string {\n return encrypt(this.key, value);\n }\n\n private decrypt(enc: string): string {\n return decrypt(this.key, enc);\n }\n\n private async row(ref: string): Promise<SecretRow> {\n const id = parseSecretRef(ref);\n const row = await this.db\n .selectFrom(\"secret\")\n .selectAll()\n .where(\"id\", \"=\", id)\n .executeTakeFirst();\n if (!row) throw new SecretNotFoundError(ref);\n return row;\n }\n\n private toStat(row: SecretRow): SecretStat {\n return {\n ref: secretRefFromId(row.id),\n label: row.label,\n ownerId: row.owner_id,\n createdBy: row.created_by,\n version: row.version,\n status: row.status as SecretStat[\"status\"],\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n }\n\n async create(input: {\n value: string;\n label?: string;\n ownerId: string | null;\n createdBy?: string | null;\n }): Promise<SecretStat> {\n if (input.ownerId === \"\")\n throw new Error(\"A secret needs an owning document\");\n const now = new Date().toISOString();\n const row: SecretRow = {\n id: randomBytes(16).toString(\"hex\"),\n label: input.label ?? null,\n owner_id: input.ownerId,\n created_by: input.createdBy?.toLowerCase() ?? null,\n version: 1,\n enc: this.encrypt(input.value),\n status: \"ACTIVE\",\n created_at: now,\n updated_at: now,\n };\n await this.db.insertInto(\"secret\").values(row).execute();\n return this.toStat(row);\n }\n\n async rotate(ref: string, value: string): Promise<SecretStat> {\n const row = await this.row(ref);\n if (row.status !== \"ACTIVE\") throw new SecretDeletedError(ref);\n const updated: SecretRow = {\n ...row,\n version: row.version + 1,\n enc: this.encrypt(value),\n updated_at: new Date().toISOString(),\n };\n await this.db\n .updateTable(\"secret\")\n .set({\n version: updated.version,\n enc: updated.enc,\n updated_at: updated.updated_at,\n })\n .where(\"id\", \"=\", row.id)\n .execute();\n return this.toStat(updated);\n }\n\n // Ownership is checked before the value is decrypted; unowned never resolves.\n // `null` reads a host secret (an OAuth app's), which no document owns.\n async get(ref: string, owner: SecretOwner | null): Promise<string> {\n const row = await this.row(ref);\n if (owner === null) {\n if (row.owner_id !== null) throw new SecretOwnerMismatchError(\"host\");\n } else if (row.owner_id === null || row.owner_id !== owner.documentId) {\n throw new SecretOwnerMismatchError(owner.kind);\n }\n if (row.status !== \"ACTIVE\" || row.enc === null) {\n throw new SecretDeletedError(ref);\n }\n return this.decrypt(row.enc);\n }\n\n async stat(ref: string): Promise<SecretStat> {\n return this.toStat(await this.row(ref));\n }\n\n async list(): Promise<SecretStat[]> {\n const rows = await this.db\n .selectFrom(\"secret\")\n .selectAll()\n .where(\"status\", \"=\", \"ACTIVE\")\n .orderBy(\"created_at\", \"desc\")\n .execute();\n return rows.map((row) => this.toStat(row));\n }\n\n // Tombstone: the ciphertext is dropped so the value is unrecoverable, but\n // the row survives so dangling refs error as \"deleted\", not \"not found\".\n async delete(ref: string): Promise<void> {\n const row = await this.row(ref);\n await this.db\n .updateTable(\"secret\")\n .set({\n status: \"DELETED\",\n enc: null,\n updated_at: new Date().toISOString(),\n })\n .where(\"id\", \"=\", row.id)\n .execute();\n }\n}\n","// Typed workflow variables, coerced when a run starts. An untyped variable\n// passes through as authored.\nimport type { WorkflowVariable } from \"@powerhousedao/workflow/document-models/workflow\";\nimport type { SecretProvider, WorkflowVariableDef } from \"../pieces/index.js\";\n\nexport class VariableTypeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VariableTypeError\";\n }\n}\n\nexport interface ResolvedVariables {\n variables: WorkflowVariableDef[];\n // Plaintext of every SECRET variable, for the run's redaction pass.\n secretValues: string[];\n}\n\ntype TypedVariable = Pick<WorkflowVariable, \"key\" | \"value\"> & {\n type?: WorkflowVariable[\"type\"];\n};\n\nfunction isUnset(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n}\n\nfunction coerce(variable: TypedVariable): unknown {\n const { key, value, type } = variable;\n switch (type) {\n case \"TEXT\":\n if (value === undefined || value === null) return null;\n return typeof value === \"object\"\n ? JSON.stringify(value)\n : String(value as string | number | boolean);\n case \"NUMBER\": {\n if (isUnset(value)) return null;\n const number =\n typeof value === \"string\" ? Number(value.trim()) : Number(value);\n if (Number.isNaN(number)) {\n throw new VariableTypeError(\n `Variable \"${key}\" is a NUMBER, but its value ${JSON.stringify(value)} is not a number`,\n );\n }\n return number;\n }\n case \"BOOLEAN\": {\n if (isUnset(value)) return null;\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return value !== 0;\n const text = typeof value === \"string\" ? value.trim().toLowerCase() : \"\";\n if (text === \"true\" || text === \"1\") return true;\n if (text === \"false\" || text === \"0\") return false;\n throw new VariableTypeError(\n `Variable \"${key}\" is a BOOLEAN, but its value ${JSON.stringify(value)} is not true or false`,\n );\n }\n case \"JSON\":\n if (typeof value !== \"string\") return value ?? null;\n if (value.trim() === \"\") return null;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n throw new VariableTypeError(\n `Variable \"${key}\" is JSON, but its value does not parse`,\n );\n }\n default:\n return value ?? null;\n }\n}\n\n/** Coerces typed variables and resolves SECRET ones through the secret store.\n * A SECRET resolves only as the workflow it was minted for. The error for a\n * SECRET names its ref, never a value. */\nexport async function resolveVariables(\n variables: readonly TypedVariable[],\n secrets: SecretProvider,\n workflowId: string,\n): Promise<ResolvedVariables> {\n const secretValues: string[] = [];\n const resolved: WorkflowVariableDef[] = [];\n for (const variable of variables) {\n if (variable.type !== \"SECRET\") {\n resolved.push({ key: variable.key, value: coerce(variable) });\n continue;\n }\n if (isUnset(variable.value)) {\n resolved.push({ key: variable.key, value: null });\n continue;\n }\n if (typeof variable.value !== \"string\") {\n throw new VariableTypeError(\n `Variable \"${variable.key}\" is a SECRET, but its value is not a secret reference`,\n );\n }\n let value: string;\n try {\n value = await secrets.get(variable.value, {\n documentId: workflowId,\n kind: \"workflow\",\n });\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new VariableTypeError(\n `Secret variable \"${variable.key}\" could not be resolved: ${detail}`,\n );\n }\n secretValues.push(value);\n resolved.push({ key: variable.key, value });\n }\n return { variables: resolved, secretValues };\n}\n","// Single-step testing: which parts of the run scope a step's config reads, and\n// the draft step in engine shape.\nimport type { WorkflowState } from \"@powerhousedao/workflow/document-models/workflow\";\nimport {\n expressionsIn,\n type Expression,\n type StepExecutionStatus,\n type WorkflowStepDef,\n} from \"../pieces/index.js\";\nimport { propertySettings } from \"./lib.js\";\n\nexport interface StepTestResult {\n // Null when the test never started: an upstream sample was missing.\n runId: string | null;\n // INDETERMINATE is its own answer, not a shade of either other one: a host\n // call the block made timed out, so a write it asked for may well have\n // landed. See \"Indeterminate steps\" in README.md.\n status: \"SUCCEEDED\" | \"FAILED\" | \"INDETERMINATE\";\n output?: unknown;\n error?: string;\n errorName?: string;\n durationMs: number;\n}\n\n/**\n * A step record's status as a test reports it.\n *\n * Collapsing this to `FAILED : SUCCEEDED` is how an INDETERMINATE test came\n * to read green — the one status that must never be mistaken for a confirmed\n * one, since the whole point of it is that nobody knows whether the write\n * landed.\n */\nexport function testStatusOf(\n status: StepExecutionStatus,\n): StepTestResult[\"status\"] {\n if (status === \"FAILED\") return \"FAILED\";\n if (status === \"INDETERMINATE\") return \"INDETERMINATE\";\n return \"SUCCEEDED\";\n}\n\n// What a single-step test reads a tested block's sample from. \"truncated\"\n// means the journal capped the last test's output to a marker (store.ts,\n// STEP_PAYLOAD_MAX_BYTES): there is a test on record, but no data to serve.\n// \"indeterminate\" means the test neither succeeded nor failed, so it has no\n// output a downstream draft step may stand on.\nexport type TestSample =\n | { kind: \"untested\" | \"stale\" | \"hidden\" | \"truncated\" | \"indeterminate\" }\n | { kind: \"failed\"; runId: string; testedAt: string; error: string }\n | { kind: \"succeeded\"; runId: string; testedAt: string; output: unknown };\n\nexport interface ScopeReferences {\n trigger: boolean;\n // A bare {{steps}} reads every upstream step.\n allSteps: boolean;\n // Step key → fields read (\"output\", \"error\", or \"*\" for the whole entry).\n steps: Map<string, Set<string>>;\n}\n\nfunction collectStrings(value: unknown, into: string[]): void {\n if (typeof value === \"string\") into.push(value);\n else if (Array.isArray(value))\n for (const item of value) collectStrings(item, into);\n else if (value !== null && typeof value === \"object\") {\n for (const entry of Object.values(value)) collectStrings(entry, into);\n }\n}\n\n/** The trigger and step entries a config's strings read. */\nexport function scopeReferences(config: unknown): ScopeReferences {\n const refs: ScopeReferences = {\n trigger: false,\n allSteps: false,\n steps: new Map(),\n };\n const strings: string[] = [];\n collectStrings(config, strings);\n for (const text of strings) {\n let expressions: Expression[];\n try {\n expressions = expressionsIn(text);\n } catch {\n // A malformed expression fails the test run itself, with its own message.\n continue;\n }\n for (const term of expressions.flatMap((expression) => expression.terms)) {\n if (term.kind !== \"path\") continue;\n const [root, key, field] = term.segments;\n if (root === \"trigger\") refs.trigger = true;\n if (root !== \"steps\") continue;\n if (term.segments.length < 2) {\n refs.allSteps = true;\n continue;\n }\n const fields = refs.steps.get(String(key)) ?? new Set<string>();\n fields.add(term.segments.length > 2 ? String(field) : \"*\");\n refs.steps.set(String(key), fields);\n }\n }\n return refs;\n}\n\n/** Steps with a path to `stepId` along the draft's edges. */\nexport function upstreamStepIds(\n state: Pick<WorkflowState, \"edges\">,\n stepId: string,\n): Set<string> {\n const incoming = new Map<string, string[]>();\n for (const edge of state.edges) {\n incoming.set(edge.to, [...(incoming.get(edge.to) ?? []), edge.from]);\n }\n const upstream = new Set<string>();\n const queue = [stepId];\n while (queue.length > 0) {\n for (const from of incoming.get(queue.pop()!) ?? []) {\n if (!upstream.has(from)) {\n upstream.add(from);\n queue.push(from);\n }\n }\n }\n return upstream;\n}\n\n/** A draft step in engine shape; a test runs it even when it is skipped. */\nexport function draftStepDef(\n step: WorkflowState[\"steps\"][number],\n): WorkflowStepDef {\n return {\n id: step.id,\n key: step.key,\n name: step.name,\n pieceName: step.pieceName,\n pieceVersion: step.pieceVersion,\n actionName: step.actionName,\n connectionId: step.connectionId,\n reactorConnectionId: step.reactorConnectionId,\n config: step.config,\n timeoutSeconds: step.timeoutSeconds,\n propertySettings: propertySettings(step.propertySettings),\n skip: false,\n };\n}\n\n/** A run's payload is one trigger item; a trigger test returns the list. */\nexport function triggerSamplePayload(output: unknown): {\n payload?: unknown;\n empty: boolean;\n} {\n if (!Array.isArray(output)) return { payload: output, empty: false };\n return output.length > 0\n ? { payload: output[0] as unknown, empty: false }\n : { empty: true };\n}\n\nexport function untestedError(label: string, sample: TestSample): string {\n switch (sample.kind) {\n case \"stale\":\n return `Test ${label} first: it changed since its last test`;\n case \"hidden\":\n return `Test ${label} first: its last test is not visible to you`;\n case \"failed\":\n return `Test ${label} first: its last test failed`;\n case \"truncated\":\n return `Test ${label} again: the journal kept only a truncated copy of its last output`;\n case \"indeterminate\":\n return `Test ${label} again: its last test is INDETERMINATE, so it has no confirmed output`;\n default:\n return `Test ${label} first`;\n }\n}\n","/// <reference types=\"./object-utils.d.ts\" />\nexport function isEmpty(obj) {\n if (Array.isArray(obj) || isString(obj) || isBuffer(obj)) {\n return obj.length === 0;\n }\n else if (obj) {\n return Object.keys(obj).length === 0;\n }\n return false;\n}\nexport function isUndefined(obj) {\n return typeof obj === 'undefined' || obj === undefined;\n}\nexport function isString(obj) {\n return typeof obj === 'string';\n}\nexport function isNumber(obj) {\n return typeof obj === 'number';\n}\nexport function isBoolean(obj) {\n return typeof obj === 'boolean';\n}\nexport function isNull(obj) {\n return obj === null;\n}\nexport function isDate(obj) {\n return obj instanceof Date;\n}\nexport function isBigInt(obj) {\n return typeof obj === 'bigint';\n}\n// Don't change the returnd type to `obj is Buffer` to not create a\n// hard dependency to node.\nexport function isBuffer(obj) {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(obj);\n}\nexport function isFunction(obj) {\n return typeof obj === 'function';\n}\nexport function isObject(obj) {\n return typeof obj === 'object' && obj !== null;\n}\nexport function isArrayBufferOrView(obj) {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\nexport function isPlainObject(obj) {\n if (!isObject(obj) || getTag(obj) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(obj) === null) {\n return true;\n }\n let proto = obj;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(obj) === proto;\n}\nexport function getLast(arr) {\n return arr[arr.length - 1];\n}\nexport function freeze(obj) {\n return Object.freeze(obj);\n}\nexport function asArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return [arg];\n }\n}\nexport function asReadonlyArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return freeze([arg]);\n }\n}\nexport function isReadonlyArray(arg) {\n return Array.isArray(arg);\n}\nexport function noop(obj) {\n return obj;\n}\nexport function compare(obj1, obj2) {\n if (isReadonlyArray(obj1) && isReadonlyArray(obj2)) {\n return compareArrays(obj1, obj2);\n }\n else if (isObject(obj1) && isObject(obj2)) {\n return compareObjects(obj1, obj2);\n }\n return obj1 === obj2;\n}\nfunction compareArrays(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0; i < arr1.length; ++i) {\n if (!compare(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nfunction compareObjects(obj1, obj2) {\n if (isBuffer(obj1) && isBuffer(obj2)) {\n return compareBuffers(obj1, obj2);\n }\n else if (isDate(obj1) && isDate(obj2)) {\n return compareDates(obj1, obj2);\n }\n return compareGenericObjects(obj1, obj2);\n}\nfunction compareBuffers(buf1, buf2) {\n return Buffer.compare(buf1, buf2) === 0;\n}\nfunction compareDates(date1, date2) {\n return date1.getTime() === date2.getTime();\n}\nfunction compareGenericObjects(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) {\n return false;\n }\n for (const key of keys1) {\n if (!compare(obj1[key], obj2[key])) {\n return false;\n }\n }\n return true;\n}\nconst toString = Object.prototype.toString;\nfunction getTag(value) {\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n return toString.call(value);\n}\n","/// <reference types=\"./identifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const IdentifierNode = freeze({\n is(node) {\n return node.kind === 'IdentifierNode';\n },\n create(name) {\n return freeze({\n kind: 'IdentifierNode',\n name,\n });\n },\n});\n","/// <reference types=\"./schemable-identifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const SchemableIdentifierNode = freeze({\n is(node) {\n return node.kind === 'SchemableIdentifierNode';\n },\n create(identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n identifier: IdentifierNode.create(identifier),\n });\n },\n createWithSchema(schema, identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n schema: IdentifierNode.create(schema),\n identifier: IdentifierNode.create(identifier),\n });\n },\n});\n","/// <reference types=\"./alias-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AliasNode = freeze({\n is(node) {\n return node.kind === 'AliasNode';\n },\n create(node, alias) {\n return freeze({\n kind: 'AliasNode',\n node,\n alias,\n });\n },\n});\n","/// <reference types=\"./table-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const TableNode = freeze({\n is(node) {\n return node.kind === 'TableNode';\n },\n create(table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.create(table),\n });\n },\n createWithSchema(schema, table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.createWithSchema(schema, table),\n });\n },\n});\n","/// <reference types=\"./operation-node-source.d.ts\" />\nimport { isFunction, isObject } from '../util/object-utils.js';\nexport function isOperationNodeSource(obj) {\n return isObject(obj) && isFunction(obj.toOperationNode);\n}\n","/// <reference types=\"./expression.d.ts\" />\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport function isExpression(obj) {\n return isObject(obj) && 'expressionType' in obj && isOperationNodeSource(obj);\n}\nexport function isAliasedExpression(obj) {\n return (isObject(obj) &&\n 'expression' in obj &&\n isString(obj.alias) &&\n isOperationNodeSource(obj));\n}\n","/// <reference types=\"./select-modifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectModifierNode = freeze({\n is(node) {\n return node.kind === 'SelectModifierNode';\n },\n create(modifier, of) {\n return freeze({\n kind: 'SelectModifierNode',\n modifier,\n of,\n });\n },\n createWithExpression(modifier) {\n return freeze({\n kind: 'SelectModifierNode',\n rawModifier: modifier,\n });\n },\n});\n","/// <reference types=\"./and-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AndNode = freeze({\n is(node) {\n return node.kind === 'AndNode';\n },\n create(left, right) {\n return freeze({\n kind: 'AndNode',\n left,\n right,\n });\n },\n});\n","/// <reference types=\"./or-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrNode = freeze({\n is(node) {\n return node.kind === 'OrNode';\n },\n create(left, right) {\n return freeze({\n kind: 'OrNode',\n left,\n right,\n });\n },\n});\n","/// <reference types=\"./on-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const OnNode = freeze({\n is(node) {\n return node.kind === 'OnNode';\n },\n create(filter) {\n return freeze({\n kind: 'OnNode',\n on: filter,\n });\n },\n cloneWithOperation(onNode, operator, operation) {\n return freeze({\n ...onNode,\n on: operator === 'And'\n ? AndNode.create(onNode.on, operation)\n : OrNode.create(onNode.on, operation),\n });\n },\n});\n","/// <reference types=\"./join-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { OnNode } from './on-node.js';\n/**\n * @internal\n */\nexport const JoinNode = freeze({\n is(node) {\n return node.kind === 'JoinNode';\n },\n create(joinType, table) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: undefined,\n });\n },\n createWithOn(joinType, table, on) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: OnNode.create(on),\n });\n },\n cloneWithOn(joinNode, operation) {\n return freeze({\n ...joinNode,\n on: joinNode.on\n ? OnNode.cloneWithOperation(joinNode.on, 'And', operation)\n : OnNode.create(operation),\n });\n },\n});\n","/// <reference types=\"./binary-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const BinaryOperationNode = freeze({\n is(node) {\n return node.kind === 'BinaryOperationNode';\n },\n create(leftOperand, operator, rightOperand) {\n return freeze({\n kind: 'BinaryOperationNode',\n leftOperand,\n operator,\n rightOperand,\n });\n },\n});\n","/// <reference types=\"./operator-node.d.ts\" />\nimport { freeze, isString } from '../util/object-utils.js';\nexport const COMPARISON_OPERATORS = [\n '=',\n '==',\n '!=',\n '<>',\n '>',\n '>=',\n '<',\n '<=',\n 'in',\n 'not in',\n 'is',\n 'is not',\n 'like',\n 'not like',\n 'match',\n 'ilike',\n 'not ilike',\n '@>',\n '<@',\n '^@',\n '&&',\n '?',\n '?&',\n '?|',\n '!<',\n '!>',\n '<=>',\n '!~',\n '~',\n '~*',\n '!~*',\n '@@',\n '@@@',\n '!!',\n '<->',\n 'regexp',\n 'is distinct from',\n 'is not distinct from',\n];\nexport const ARITHMETIC_OPERATORS = [\n '+',\n '-',\n '*',\n '/',\n '%',\n '^',\n '&',\n '|',\n '#',\n '<<',\n '>>',\n];\nexport const JSON_OPERATORS = ['->', '->>'];\nexport const BINARY_OPERATORS = [\n ...COMPARISON_OPERATORS,\n ...ARITHMETIC_OPERATORS,\n '&&',\n '||',\n];\nexport const UNARY_FILTER_OPERATORS = ['exists', 'not exists'];\nexport const UNARY_OPERATORS = ['not', '-', ...UNARY_FILTER_OPERATORS];\nexport const OPERATORS = [\n ...BINARY_OPERATORS,\n ...JSON_OPERATORS,\n ...UNARY_OPERATORS,\n 'between',\n 'between symmetric',\n];\n/**\n * @internal\n */\nexport const OperatorNode = freeze({\n is(node) {\n return node.kind === 'OperatorNode';\n },\n create(operator) {\n return freeze({\n kind: 'OperatorNode',\n operator,\n });\n },\n});\nexport function isOperator(op) {\n return isString(op) && OPERATORS.includes(op);\n}\nexport function isBinaryOperator(op) {\n return isString(op) && BINARY_OPERATORS.includes(op);\n}\nexport function isComparisonOperator(op) {\n return isString(op) && COMPARISON_OPERATORS.includes(op);\n}\nexport function isArithmeticOperator(op) {\n return isString(op) && ARITHMETIC_OPERATORS.includes(op);\n}\nexport function isJSONOperator(op) {\n return isString(op) && JSON_OPERATORS.includes(op);\n}\n","/// <reference types=\"./column-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const ColumnNode = freeze({\n is(node) {\n return node.kind === 'ColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'ColumnNode',\n column: IdentifierNode.create(column),\n });\n },\n});\n","/// <reference types=\"./select-all-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectAllNode = freeze({\n is(node) {\n return node.kind === 'SelectAllNode';\n },\n create() {\n return freeze({\n kind: 'SelectAllNode',\n });\n },\n});\n","/// <reference types=\"./reference-node.d.ts\" />\nimport { SelectAllNode } from './select-all-node.js';\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReferenceNode = freeze({\n is(node) {\n return node.kind === 'ReferenceNode';\n },\n create(column, table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column,\n });\n },\n createSelectAll(table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column: SelectAllNode.create(),\n });\n },\n});\n","/// <reference types=\"./dynamic-reference-builder.d.ts\" />\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseSimpleReferenceExpression } from '../parser/reference-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicReferenceBuilder {\n #dynamicReference;\n get dynamicReference() {\n return this.#dynamicReference;\n }\n /**\n * @private\n *\n * This needs to be here just so that the typings work. Without this\n * the generated .d.ts file contains no reference to the type param R\n * which causes this type to be equal to DynamicReferenceBuilder with\n * any R.\n */\n get refType() {\n return undefined;\n }\n constructor(reference) {\n this.#dynamicReference = reference;\n }\n toOperationNode() {\n return parseSimpleReferenceExpression(this.#dynamicReference);\n }\n}\nexport function isDynamicReferenceBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.dynamicReference));\n}\n","/// <reference types=\"./order-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByItemNode = freeze({\n is(node) {\n return node.kind === 'OrderByItemNode';\n },\n create(orderBy, direction) {\n return freeze({\n kind: 'OrderByItemNode',\n orderBy,\n direction,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n","/// <reference types=\"./raw-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const RawNode = freeze({\n is(node) {\n return node.kind === 'RawNode';\n },\n create(sqlFragments, parameters) {\n return freeze({\n kind: 'RawNode',\n sqlFragments: freeze(sqlFragments),\n parameters: freeze(parameters),\n });\n },\n createWithSql(sql) {\n return RawNode.create([sql], []);\n },\n createWithChild(child) {\n return RawNode.create(['', ''], [child]);\n },\n createWithChildren(children) {\n return RawNode.create(new Array(children.length + 1).fill(''), children);\n },\n});\n","/// <reference types=\"./collate-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CollateNode = freeze({\n is(node) {\n return node.kind === 'CollateNode';\n },\n create(collation) {\n return freeze({\n kind: 'CollateNode',\n collation: IdentifierNode.create(collation),\n });\n },\n});\n","/// <reference types=\"./order-by-item-builder.d.ts\" />\nimport { CollateNode } from '../operation-node/collate-node.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OrderByItemBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds `desc` to the `order by` item.\n *\n * See {@link asc} for the opposite.\n */\n desc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('desc'),\n }),\n });\n }\n /**\n * Adds `asc` to the `order by` item.\n *\n * See {@link desc} for the opposite.\n */\n asc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('asc'),\n }),\n });\n }\n /**\n * Adds `nulls last` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsFirst} for the opposite.\n */\n nullsLast() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'last' }),\n });\n }\n /**\n * Adds `nulls first` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsLast} for the opposite.\n */\n nullsFirst() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'first' }),\n });\n }\n /**\n * Adds `collate <collationName>` to the `order by` item.\n */\n collate(collation) {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n collation: CollateNode.create(collation),\n }),\n });\n }\n toOperationNode() {\n return this.#props.node;\n }\n}\n","/// <reference types=\"./log-once.d.ts\" />\nconst LOGGED_MESSAGES = new Set();\n/**\n * Use for system-level logging, such as deprecation messages.\n * Logs a message and ensures it won't be logged again.\n */\nexport function logOnce(message) {\n if (LOGGED_MESSAGES.has(message)) {\n return;\n }\n LOGGED_MESSAGES.add(message);\n console.log(message);\n}\n","/// <reference types=\"./order-by-parser.d.ts\" />\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { isExpression } from '../expression/expression.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { OrderByItemBuilder } from '../query-builder/order-by-item-builder.js';\nimport { logOnce } from '../util/log-once.js';\nimport { isExpressionOrFactory, parseExpression, } from './expression-parser.js';\nimport { parseStringReference, } from './reference-parser.js';\nexport function isOrderByDirection(thing) {\n return thing === 'asc' || thing === 'desc';\n}\nexport function parseOrderBy(args) {\n if (args.length === 2) {\n return [parseOrderByItem(args[0], args[1])];\n }\n if (args.length === 1) {\n const [orderBy] = args;\n if (Array.isArray(orderBy)) {\n logOnce('orderBy(array) is deprecated, use multiple orderBy calls instead.');\n return orderBy.map((item) => parseOrderByItem(item));\n }\n return [parseOrderByItem(orderBy)];\n }\n throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`);\n}\nexport function parseOrderByItem(expr, modifiers) {\n const parsedRef = parseOrderByExpression(expr);\n if (OrderByItemNode.is(parsedRef)) {\n if (modifiers) {\n throw new Error('Cannot specify direction twice!');\n }\n return parsedRef;\n }\n return parseOrderByWithModifiers(parsedRef, modifiers);\n}\nfunction parseOrderByExpression(expr) {\n if (isExpressionOrFactory(expr)) {\n return parseExpression(expr);\n }\n if (isDynamicReferenceBuilder(expr)) {\n return expr.toOperationNode();\n }\n const [ref, direction] = expr.split(' ');\n if (direction) {\n logOnce(\"`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead.\");\n return parseOrderByWithModifiers(parseStringReference(ref), direction);\n }\n return parseStringReference(expr);\n}\nfunction parseOrderByWithModifiers(expr, modifiers) {\n if (typeof modifiers === 'string') {\n if (!isOrderByDirection(modifiers)) {\n throw new Error(`Invalid order by direction: ${modifiers}`);\n }\n return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers));\n }\n if (isExpression(modifiers)) {\n logOnce(\"`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead.\");\n return OrderByItemNode.create(expr, modifiers.toOperationNode());\n }\n const node = OrderByItemNode.create(expr);\n if (!modifiers) {\n return node;\n }\n return modifiers(new OrderByItemBuilder({ node })).toOperationNode();\n}\n","/// <reference types=\"./json-reference-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONReferenceNode = freeze({\n is(node) {\n return node.kind === 'JSONReferenceNode';\n },\n create(reference, traversal) {\n return freeze({\n kind: 'JSONReferenceNode',\n reference,\n traversal,\n });\n },\n cloneWithTraversal(node, traversal) {\n return freeze({\n ...node,\n traversal,\n });\n },\n});\n","/// <reference types=\"./json-operator-chain-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONOperatorChainNode = freeze({\n is(node) {\n return node.kind === 'JSONOperatorChainNode';\n },\n create(operator) {\n return freeze({\n kind: 'JSONOperatorChainNode',\n operator,\n values: freeze([]),\n });\n },\n cloneWithValue(node, value) {\n return freeze({\n ...node,\n values: freeze([...node.values, value]),\n });\n },\n});\n","/// <reference types=\"./json-path-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathNode = freeze({\n is(node) {\n return node.kind === 'JSONPathNode';\n },\n create(inOperator) {\n return freeze({\n kind: 'JSONPathNode',\n inOperator,\n pathLegs: freeze([]),\n });\n },\n cloneWithLeg(jsonPathNode, pathLeg) {\n return freeze({\n ...jsonPathNode,\n pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg]),\n });\n },\n});\n","/// <reference types=\"./reference-parser.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ReferenceNode } from '../operation-node/reference-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOrderByDirection, parseOrderBy, } from './order-by-parser.js';\nimport { OperatorNode, isJSONOperator, } from '../operation-node/operator-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nexport function parseSimpleReferenceExpression(exp) {\n if (isString(exp)) {\n return parseStringReference(exp);\n }\n return exp.toOperationNode();\n}\nexport function parseReferenceExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return arg.map((it) => parseReferenceExpression(it));\n }\n else {\n return [parseReferenceExpression(arg)];\n }\n}\nexport function parseReferenceExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return parseSimpleReferenceExpression(exp);\n}\nexport function parseJSONReference(ref, op) {\n const referenceNode = parseStringReference(ref);\n if (isJSONOperator(op)) {\n return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op)));\n }\n const opWithoutLastChar = op.slice(0, -1);\n if (isJSONOperator(opWithoutLastChar)) {\n return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar)));\n }\n throw new Error(`Invalid JSON operator: ${op}`);\n}\nexport function parseStringReference(ref) {\n const COLUMN_SEPARATOR = '.';\n if (!ref.includes(COLUMN_SEPARATOR)) {\n return ReferenceNode.create(ColumnNode.create(ref));\n }\n const parts = ref.split(COLUMN_SEPARATOR).map(trim);\n if (parts.length === 3) {\n return parseStringReferenceWithTableAndSchema(parts);\n }\n if (parts.length === 2) {\n return parseStringReferenceWithTable(parts);\n }\n throw new Error(`invalid column reference ${ref}`);\n}\nexport function parseAliasedStringReference(ref) {\n const ALIAS_SEPARATOR = ' as ';\n if (ref.includes(ALIAS_SEPARATOR)) {\n const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias));\n }\n else {\n return parseStringReference(ref);\n }\n}\nexport function parseColumnName(column) {\n return ColumnNode.create(column);\n}\nexport function parseOrderedColumnName(column) {\n const ORDER_SEPARATOR = ' ';\n if (column.includes(ORDER_SEPARATOR)) {\n const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim);\n if (!isOrderByDirection(order)) {\n throw new Error(`invalid order direction \"${order}\" next to \"${columnName}\"`);\n }\n return parseOrderBy([columnName, order])[0];\n }\n else {\n return parseColumnName(column);\n }\n}\nfunction parseStringReferenceWithTableAndSchema(parts) {\n const [schema, table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema, table));\n}\nfunction parseStringReferenceWithTable(parts) {\n const [table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table));\n}\nfunction trim(str) {\n return str.trim();\n}\n","/// <reference types=\"./primitive-value-list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PrimitiveValueListNode = freeze({\n is(node) {\n return node.kind === 'PrimitiveValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'PrimitiveValueListNode',\n values: freeze([...values]),\n });\n },\n});\n","/// <reference types=\"./value-list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueListNode = freeze({\n is(node) {\n return node.kind === 'ValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'ValueListNode',\n values: freeze(values),\n });\n },\n});\n","/// <reference types=\"./value-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueNode = freeze({\n is(node) {\n return node.kind === 'ValueNode';\n },\n create(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n });\n },\n createImmediate(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n immediate: true,\n });\n },\n});\n","/// <reference types=\"./value-parser.d.ts\" />\nimport { PrimitiveValueListNode } from '../operation-node/primitive-value-list-node.js';\nimport { ValueListNode } from '../operation-node/value-list-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { isBoolean, isNull, isNumber, isReadonlyArray, } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nexport function parseValueExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return parseValueExpressionList(arg);\n }\n return parseValueExpression(arg);\n}\nexport function parseValueExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return ValueNode.create(exp);\n}\nexport function isSafeImmediateValue(value) {\n return isNumber(value) || isBoolean(value) || isNull(value);\n}\nexport function parseSafeImmediateValue(value) {\n if (!isSafeImmediateValue(value)) {\n throw new Error(`unsafe immediate value ${JSON.stringify(value)}`);\n }\n return ValueNode.createImmediate(value);\n}\nfunction parseValueExpressionList(arg) {\n if (arg.some(isExpressionOrFactory)) {\n return ValueListNode.create(arg.map((it) => parseValueExpression(it)));\n }\n return PrimitiveValueListNode.create(arg);\n}\n","/// <reference types=\"./parens-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ParensNode = freeze({\n is(node) {\n return node.kind === 'ParensNode';\n },\n create(node) {\n return freeze({\n kind: 'ParensNode',\n node,\n });\n },\n});\n","/// <reference types=\"./binary-operation-parser.d.ts\" />\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { isBoolean, isNull, isString, isUndefined, } from '../util/object-utils.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { OperatorNode, OPERATORS, } from '../operation-node/operator-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nimport { parseValueExpression, parseValueExpressionOrList, } from './value-parser.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { OrNode } from '../operation-node/or-node.js';\nexport function parseValueBinaryOperationOrExpression(args) {\n if (args.length === 3) {\n return parseValueBinaryOperation(args[0], args[1], args[2]);\n }\n else if (args.length === 1) {\n return parseValueExpression(args[0]);\n }\n throw new Error(`invalid arguments: ${JSON.stringify(args)}`);\n}\nexport function parseValueBinaryOperation(left, operator, right) {\n if (isIsOperator(operator) && needsIsOperator(right)) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right));\n }\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right));\n}\nexport function parseReferentialBinaryOperation(left, operator, right) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right));\n}\nexport function parseFilterObject(obj, combinator) {\n return parseFilterList(Object.entries(obj)\n .filter(([, v]) => !isUndefined(v))\n .map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? 'is' : '=', v)), combinator);\n}\nexport function parseFilterList(list, combinator, withParens = true) {\n const combine = combinator === 'and' ? AndNode.create : OrNode.create;\n if (list.length === 0) {\n return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create('='), ValueNode.createImmediate(combinator === 'and' ? 1 : 0));\n }\n let node = toOperationNode(list[0]);\n for (let i = 1; i < list.length; ++i) {\n node = combine(node, toOperationNode(list[i]));\n }\n if (list.length > 1 && withParens) {\n return ParensNode.create(node);\n }\n return node;\n}\nfunction isIsOperator(operator) {\n return operator === 'is' || operator === 'is not';\n}\nfunction needsIsOperator(value) {\n return isNull(value) || isBoolean(value);\n}\nfunction parseOperator(operator) {\n if (isString(operator) && OPERATORS.includes(operator)) {\n return OperatorNode.create(operator);\n }\n if (isOperationNodeSource(operator)) {\n return operator.toOperationNode();\n }\n throw new Error(`invalid operator ${JSON.stringify(operator)}`);\n}\nfunction toOperationNode(nodeOrSource) {\n return isOperationNodeSource(nodeOrSource)\n ? nodeOrSource.toOperationNode()\n : nodeOrSource;\n}\n","/// <reference types=\"./order-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByNode = freeze({\n is(node) {\n return node.kind === 'OrderByNode';\n },\n create(items) {\n return freeze({\n kind: 'OrderByNode',\n items: freeze([...items]),\n });\n },\n cloneWithItems(orderBy, items) {\n return freeze({\n ...orderBy,\n items: freeze([...orderBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./partition-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByNode = freeze({\n is(node) {\n return node.kind === 'PartitionByNode';\n },\n create(items) {\n return freeze({\n kind: 'PartitionByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(partitionBy, items) {\n return freeze({\n ...partitionBy,\n items: freeze([...partitionBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./over-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { OrderByNode } from './order-by-node.js';\nimport { PartitionByNode } from './partition-by-node.js';\n/**\n * @internal\n */\nexport const OverNode = freeze({\n is(node) {\n return node.kind === 'OverNode';\n },\n create() {\n return freeze({\n kind: 'OverNode',\n });\n },\n cloneWithOrderByItems(overNode, items) {\n return freeze({\n ...overNode,\n orderBy: overNode.orderBy\n ? OrderByNode.cloneWithItems(overNode.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithPartitionByItems(overNode, items) {\n return freeze({\n ...overNode,\n partitionBy: overNode.partitionBy\n ? PartitionByNode.cloneWithItems(overNode.partitionBy, items)\n : PartitionByNode.create(items),\n });\n },\n});\n","/// <reference types=\"./from-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FromNode = freeze({\n is(node) {\n return node.kind === 'FromNode';\n },\n create(froms) {\n return freeze({\n kind: 'FromNode',\n froms: freeze(froms),\n });\n },\n cloneWithFroms(from, froms) {\n return freeze({\n ...from,\n froms: freeze([...from.froms, ...froms]),\n });\n },\n});\n","/// <reference types=\"./group-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByNode = freeze({\n is(node) {\n return node.kind === 'GroupByNode';\n },\n create(items) {\n return freeze({\n kind: 'GroupByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(groupBy, items) {\n return freeze({\n ...groupBy,\n items: freeze([...groupBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./having-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const HavingNode = freeze({\n is(node) {\n return node.kind === 'HavingNode';\n },\n create(filter) {\n return freeze({\n kind: 'HavingNode',\n having: filter,\n });\n },\n cloneWithOperation(havingNode, operator, operation) {\n return freeze({\n ...havingNode,\n having: operator === 'And'\n ? AndNode.create(havingNode.having, operation)\n : OrNode.create(havingNode.having, operation),\n });\n },\n});\n","/// <reference types=\"./insert-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const InsertQueryNode = freeze({\n is(node) {\n return node.kind === 'InsertQueryNode';\n },\n create(into, withNode, replace) {\n return freeze({\n kind: 'InsertQueryNode',\n into,\n ...(withNode && { with: withNode }),\n replace,\n });\n },\n createWithoutInto() {\n return freeze({\n kind: 'InsertQueryNode',\n });\n },\n cloneWith(insertQuery, props) {\n return freeze({\n ...insertQuery,\n ...props,\n });\n },\n});\n","/// <reference types=\"./list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ListNode = freeze({\n is(node) {\n return node.kind === 'ListNode';\n },\n create(items) {\n return freeze({\n kind: 'ListNode',\n items: freeze(items),\n });\n },\n});\n","/// <reference types=\"./update-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { ListNode } from './list-node.js';\n/**\n * @internal\n */\nexport const UpdateQueryNode = freeze({\n is(node) {\n return node.kind === 'UpdateQueryNode';\n },\n create(tables, withNode) {\n return freeze({\n kind: 'UpdateQueryNode',\n // For backwards compatibility, use the raw table node when there's only one table\n // and don't rename the property to something like `tables`.\n table: tables.length === 1 ? tables[0] : ListNode.create(tables),\n ...(withNode && { with: withNode }),\n });\n },\n createWithoutTable() {\n return freeze({\n kind: 'UpdateQueryNode',\n });\n },\n cloneWithFromItems(updateQuery, fromItems) {\n return freeze({\n ...updateQuery,\n from: updateQuery.from\n ? FromNode.cloneWithFroms(updateQuery.from, fromItems)\n : FromNode.create(fromItems),\n });\n },\n cloneWithUpdates(updateQuery, updates) {\n return freeze({\n ...updateQuery,\n updates: updateQuery.updates\n ? freeze([...updateQuery.updates, ...updates])\n : updates,\n });\n },\n cloneWithLimit(updateQuery, limit) {\n return freeze({\n ...updateQuery,\n limit,\n });\n },\n});\n","/// <reference types=\"./using-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UsingNode = freeze({\n is(node) {\n return node.kind === 'UsingNode';\n },\n create(tables) {\n return freeze({\n kind: 'UsingNode',\n tables: freeze(tables),\n });\n },\n cloneWithTables(using, tables) {\n return freeze({\n ...using,\n tables: freeze([...using.tables, ...tables]),\n });\n },\n});\n","/// <reference types=\"./delete-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { UsingNode } from './using-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const DeleteQueryNode = freeze({\n is(node) {\n return node.kind === 'DeleteQueryNode';\n },\n create(fromItems, withNode) {\n return freeze({\n kind: 'DeleteQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithLimit(deleteNode, limit) {\n return freeze({\n ...deleteNode,\n limit,\n });\n },\n cloneWithoutLimit(deleteNode) {\n return freeze({\n ...deleteNode,\n limit: undefined,\n });\n },\n cloneWithUsing(deleteNode, tables) {\n return freeze({\n ...deleteNode,\n using: deleteNode.using !== undefined\n ? UsingNode.cloneWithTables(deleteNode.using, tables)\n : UsingNode.create(tables),\n });\n },\n});\n","/// <reference types=\"./where-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const WhereNode = freeze({\n is(node) {\n return node.kind === 'WhereNode';\n },\n create(filter) {\n return freeze({\n kind: 'WhereNode',\n where: filter,\n });\n },\n cloneWithOperation(whereNode, operator, operation) {\n return freeze({\n ...whereNode,\n where: operator === 'And'\n ? AndNode.create(whereNode.where, operation)\n : OrNode.create(whereNode.where, operation),\n });\n },\n});\n","/// <reference types=\"./returning-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReturningNode = freeze({\n is(node) {\n return node.kind === 'ReturningNode';\n },\n create(selections) {\n return freeze({\n kind: 'ReturningNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(returning, selections) {\n return freeze({\n ...returning,\n selections: returning.selections\n ? freeze([...returning.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n","/// <reference types=\"./explain-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ExplainNode = freeze({\n is(node) {\n return node.kind === 'ExplainNode';\n },\n create(format, options) {\n return freeze({\n kind: 'ExplainNode',\n format,\n options,\n });\n },\n});\n","/// <reference types=\"./when-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const WhenNode = freeze({\n is(node) {\n return node.kind === 'WhenNode';\n },\n create(condition) {\n return freeze({\n kind: 'WhenNode',\n condition,\n });\n },\n cloneWithResult(whenNode, result) {\n return freeze({\n ...whenNode,\n result,\n });\n },\n});\n","/// <reference types=\"./merge-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const MergeQueryNode = freeze({\n is(node) {\n return node.kind === 'MergeQueryNode';\n },\n create(into, withNode) {\n return freeze({\n kind: 'MergeQueryNode',\n into,\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithUsing(mergeNode, using) {\n return freeze({\n ...mergeNode,\n using,\n });\n },\n cloneWithWhen(mergeNode, when) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([...mergeNode.whens, when])\n : freeze([when]),\n });\n },\n cloneWithThen(mergeNode, then) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([\n ...mergeNode.whens.slice(0, -1),\n WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then),\n ])\n : undefined,\n });\n },\n});\n","/// <reference types=\"./output-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OutputNode = freeze({\n is(node) {\n return node.kind === 'OutputNode';\n },\n create(selections) {\n return freeze({\n kind: 'OutputNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(output, selections) {\n return freeze({\n ...output,\n selections: output.selections\n ? freeze([...output.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n","/// <reference types=\"./query-node.d.ts\" />\nimport { InsertQueryNode } from './insert-query-node.js';\nimport { SelectQueryNode } from './select-query-node.js';\nimport { UpdateQueryNode } from './update-query-node.js';\nimport { DeleteQueryNode } from './delete-query-node.js';\nimport { WhereNode } from './where-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { ReturningNode } from './returning-node.js';\nimport { ExplainNode } from './explain-node.js';\nimport { MergeQueryNode } from './merge-query-node.js';\nimport { OutputNode } from './output-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const QueryNode = freeze({\n is(node) {\n return (SelectQueryNode.is(node) ||\n InsertQueryNode.is(node) ||\n UpdateQueryNode.is(node) ||\n DeleteQueryNode.is(node) ||\n MergeQueryNode.is(node));\n },\n cloneWithEndModifier(node, modifier) {\n return freeze({\n ...node,\n endModifiers: node.endModifiers\n ? freeze([...node.endModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWithWhere(node, operation) {\n return freeze({\n ...node,\n where: node.where\n ? WhereNode.cloneWithOperation(node.where, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithJoin(node, join) {\n return freeze({\n ...node,\n joins: node.joins ? freeze([...node.joins, join]) : freeze([join]),\n });\n },\n cloneWithReturning(node, selections) {\n return freeze({\n ...node,\n returning: node.returning\n ? ReturningNode.cloneWithSelections(node.returning, selections)\n : ReturningNode.create(selections),\n });\n },\n cloneWithoutReturning(node) {\n return freeze({\n ...node,\n returning: undefined,\n });\n },\n cloneWithoutWhere(node) {\n return freeze({\n ...node,\n where: undefined,\n });\n },\n cloneWithExplain(node, format, options) {\n return freeze({\n ...node,\n explain: ExplainNode.create(format, options?.toOperationNode()),\n });\n },\n cloneWithTop(node, top) {\n return freeze({\n ...node,\n top,\n });\n },\n cloneWithOutput(node, selections) {\n return freeze({\n ...node,\n output: node.output\n ? OutputNode.cloneWithSelections(node.output, selections)\n : OutputNode.create(selections),\n });\n },\n cloneWithOrderByItems(node, items) {\n return freeze({\n ...node,\n orderBy: node.orderBy\n ? OrderByNode.cloneWithItems(node.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithoutOrderBy(node) {\n return freeze({\n ...node,\n orderBy: undefined,\n });\n },\n});\n","/// <reference types=\"./select-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { GroupByNode } from './group-by-node.js';\nimport { HavingNode } from './having-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const SelectQueryNode = freeze({\n is(node) {\n return node.kind === 'SelectQueryNode';\n },\n create(withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n ...(withNode && { with: withNode }),\n });\n },\n createFrom(fromItems, withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithSelections(select, selections) {\n return freeze({\n ...select,\n selections: select.selections\n ? freeze([...select.selections, ...selections])\n : freeze(selections),\n });\n },\n cloneWithDistinctOn(select, expressions) {\n return freeze({\n ...select,\n distinctOn: select.distinctOn\n ? freeze([...select.distinctOn, ...expressions])\n : freeze(expressions),\n });\n },\n cloneWithFrontModifier(select, modifier) {\n return freeze({\n ...select,\n frontModifiers: select.frontModifiers\n ? freeze([...select.frontModifiers, modifier])\n : freeze([modifier]),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n cloneWithGroupByItems(selectNode, items) {\n return freeze({\n ...selectNode,\n groupBy: selectNode.groupBy\n ? GroupByNode.cloneWithItems(selectNode.groupBy, items)\n : GroupByNode.create(items),\n });\n },\n cloneWithLimit(selectNode, limit) {\n return freeze({\n ...selectNode,\n limit,\n });\n },\n cloneWithOffset(selectNode, offset) {\n return freeze({\n ...selectNode,\n offset,\n });\n },\n cloneWithFetch(selectNode, fetch) {\n return freeze({\n ...selectNode,\n fetch,\n });\n },\n cloneWithHaving(selectNode, operation) {\n return freeze({\n ...selectNode,\n having: selectNode.having\n ? HavingNode.cloneWithOperation(selectNode.having, 'And', operation)\n : HavingNode.create(operation),\n });\n },\n cloneWithSetOperations(selectNode, setOperations) {\n return freeze({\n ...selectNode,\n setOperations: selectNode.setOperations\n ? freeze([...selectNode.setOperations, ...setOperations])\n : freeze([...setOperations]),\n });\n },\n cloneWithoutSelections(select) {\n return freeze({\n ...select,\n selections: [],\n });\n },\n cloneWithoutLimit(select) {\n return freeze({\n ...select,\n limit: undefined,\n });\n },\n cloneWithoutOffset(select) {\n return freeze({\n ...select,\n offset: undefined,\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithoutGroupBy(select) {\n return freeze({\n ...select,\n groupBy: undefined,\n });\n },\n});\n","/// <reference types=\"./join-builder.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class JoinBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n on(...args) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Just like {@link WhereInterface.whereRef} but adds an item to the join's\n * `on` clause instead.\n *\n * See {@link WhereInterface.whereRef} for documentation and examples.\n */\n onRef(lhs, op, rhs) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds `on true`.\n */\n onTrue() {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql('true')),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.joinNode;\n }\n}\n","/// <reference types=\"./partition-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByItemNode = freeze({\n is(node) {\n return node.kind === 'PartitionByItemNode';\n },\n create(partitionBy) {\n return freeze({\n kind: 'PartitionByItemNode',\n partitionBy,\n });\n },\n});\n","/// <reference types=\"./partition-by-parser.d.ts\" />\nimport { PartitionByItemNode } from '../operation-node/partition-by-item-node.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parsePartitionBy(partitionBy) {\n return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create);\n}\n","/// <reference types=\"./over-builder.d.ts\" />\nimport { OverNode } from '../operation-node/over-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { parsePartitionBy, } from '../parser/partition-by-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OverBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n orderBy(...args) {\n return new OverBuilder({\n overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new OverBuilder({\n overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode),\n });\n }\n partitionBy(partitionBy) {\n return new OverBuilder({\n overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.overNode;\n }\n}\n","/// <reference types=\"./selection-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { ReferenceNode } from './reference-node.js';\nimport { SelectAllNode } from './select-all-node.js';\n/**\n * @internal\n */\nexport const SelectionNode = freeze({\n is(node) {\n return node.kind === 'SelectionNode';\n },\n create(selection) {\n return freeze({\n kind: 'SelectionNode',\n selection: selection,\n });\n },\n createSelectAll() {\n return freeze({\n kind: 'SelectionNode',\n selection: SelectAllNode.create(),\n });\n },\n createSelectAllFromTable(table) {\n return freeze({\n kind: 'SelectionNode',\n selection: ReferenceNode.createSelectAll(table),\n });\n },\n});\n","/// <reference types=\"./select-parser.d.ts\" />\nimport { isFunction, isReadonlyArray, isString } from '../util/object-utils.js';\nimport { SelectionNode } from '../operation-node/selection-node.js';\nimport { parseAliasedStringReference } from './reference-parser.js';\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { parseTable } from './table-parser.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nexport function parseSelectArg(selection) {\n if (isFunction(selection)) {\n return parseSelectArg(selection(expressionBuilder()));\n }\n else if (isReadonlyArray(selection)) {\n return selection.map((it) => parseSelectExpression(it));\n }\n else {\n return [parseSelectExpression(selection)];\n }\n}\nfunction parseSelectExpression(selection) {\n if (isString(selection)) {\n return SelectionNode.create(parseAliasedStringReference(selection));\n }\n else if (isDynamicReferenceBuilder(selection)) {\n return SelectionNode.create(selection.toOperationNode());\n }\n else {\n return SelectionNode.create(parseAliasedExpression(selection));\n }\n}\nexport function parseSelectAll(table) {\n if (!table) {\n return [SelectionNode.createSelectAll()];\n }\n else if (Array.isArray(table)) {\n return table.map(parseSelectAllArg);\n }\n else {\n return [parseSelectAllArg(table)];\n }\n}\nfunction parseSelectAllArg(table) {\n if (isString(table)) {\n return SelectionNode.createSelectAllFromTable(parseTable(table));\n }\n throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`);\n}\n","/// <reference types=\"./no-result-error.d.ts\" />\nexport class NoResultError extends Error {\n /**\n * The operation node tree of the query that was executed.\n */\n node;\n constructor(node) {\n super('no result');\n this.node = node;\n }\n}\nexport function isNoResultErrorConstructor(fn) {\n return Object.prototype.hasOwnProperty.call(fn, 'prototype');\n}\n","/// <reference types=\"./top-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TopNode = freeze({\n is(node) {\n return node.kind === 'TopNode';\n },\n create(expression, modifiers) {\n return freeze({\n kind: 'TopNode',\n expression,\n modifiers,\n });\n },\n});\n","/// <reference types=\"./top-parser.d.ts\" />\nimport { TopNode } from '../operation-node/top-node.js';\nimport { isBigInt, isNumber, isUndefined } from '../util/object-utils.js';\nexport function parseTop(expression, modifiers) {\n if (!isNumber(expression) && !isBigInt(expression)) {\n throw new Error(`Invalid top expression: ${expression}`);\n }\n if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) {\n throw new Error(`Invalid top modifiers: ${modifiers}`);\n }\n return TopNode.create(expression, modifiers);\n}\nfunction isTopModifiers(modifiers) {\n return (modifiers === 'percent' ||\n modifiers === 'with ties' ||\n modifiers === 'percent with ties');\n}\n","/// <reference types=\"./limit-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const LimitNode = freeze({\n is(node) {\n return node.kind === 'LimitNode';\n },\n create(limit) {\n return freeze({\n kind: 'LimitNode',\n limit,\n });\n },\n});\n","/// <reference types=\"./random-string.d.ts\" />\nconst CHARS = [\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n 'l',\n 'm',\n 'n',\n 'o',\n 'p',\n 'q',\n 'r',\n 's',\n 't',\n 'u',\n 'v',\n 'w',\n 'x',\n 'y',\n 'z',\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n];\nexport function randomString(length) {\n let chars = '';\n for (let i = 0; i < length; ++i) {\n chars += randomChar();\n }\n return chars;\n}\nfunction randomChar() {\n return CHARS[~~(Math.random() * CHARS.length)];\n}\n","/// <reference types=\"./query-id.d.ts\" />\nimport { randomString } from './random-string.js';\nexport function createQueryId() {\n return new LazyQueryId();\n}\nclass LazyQueryId {\n #queryId;\n get queryId() {\n if (this.#queryId === undefined) {\n this.#queryId = randomString(8);\n }\n return this.#queryId;\n }\n}\n","/// <reference types=\"./require-all-props.d.ts\" />\n/**\n * Helper function to check listed properties according to given type. Check if all properties has been used when object is initialised.\n *\n * Example use:\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n *\n * // propB has to be mentioned even it is optional. It still should be initialized with undefined.\n * const a: SomeType = requireAllProps<SomeType>({ propA: \"value A\", propB: undefined });\n *\n * // checked type is implicit for variable.\n * const b = requireAllProps<SomeType>({ propA: \"value A\", propB: undefined });\n * ```\n *\n * Wrong use of this helper:\n *\n * 1. Omit checked type - all checked properties will be expect as of type never\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * // const z: SomeType = requireAllProps({ propC: \"no type will work\" }); // Property 'propA' is missing in type '{ propC: string; }' but required in type 'SomeType'.\n * ```\n *\n * 2. Apply to spreaded object - there is no way how to check in compile time if spreaded object contains all properties\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * const y: SomeType = { propA: \"\" }; // valid object according to SomeType declaration\n * // const x = requireAllProps<SomeType>({ ...y }); // Argument of type '{ propA: string; propB?: number; }' is not assignable to parameter of type 'AllProps<SomeType>'.\n * ```\n *\n * @param obj object to check if all properties has been used\n * @returns untouched obj parameter is returned\n */\nexport function requireAllProps(obj) {\n return obj;\n}\n","/// <reference types=\"./operation-node-transformer.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { requireAllProps } from '../util/require-all-props.js';\n/**\n * Transforms an operation node tree into another one.\n *\n * Kysely queries are expressed internally as a tree of objects (operation nodes).\n * `OperationNodeTransformer` takes such a tree as its input and returns a\n * transformed deep copy of it. By default the `OperationNodeTransformer`\n * does nothing. You need to override one or more methods to make it do\n * something.\n *\n * There's a method for each node type. For example if you'd like to convert\n * each identifier (table name, column name, alias etc.) from camelCase to\n * snake_case, you'd do something like this:\n *\n * ```ts\n * import { type IdentifierNode, OperationNodeTransformer } from 'kysely'\n * import snakeCase from 'lodash/snakeCase'\n *\n * class CamelCaseTransformer extends OperationNodeTransformer {\n * override transformIdentifier(node: IdentifierNode): IdentifierNode {\n * node = super.transformIdentifier(node)\n *\n * return {\n * ...node,\n * name: snakeCase(node.name),\n * }\n * }\n * }\n *\n * const transformer = new CamelCaseTransformer()\n *\n * const query = db.selectFrom('person').select(['first_name', 'last_name'])\n *\n * const tree = transformer.transformNode(query.toOperationNode())\n * ```\n */\nexport class OperationNodeTransformer {\n nodeStack = [];\n #transformers = freeze({\n AliasNode: this.transformAlias.bind(this),\n ColumnNode: this.transformColumn.bind(this),\n IdentifierNode: this.transformIdentifier.bind(this),\n SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this),\n RawNode: this.transformRaw.bind(this),\n ReferenceNode: this.transformReference.bind(this),\n SelectQueryNode: this.transformSelectQuery.bind(this),\n SelectionNode: this.transformSelection.bind(this),\n TableNode: this.transformTable.bind(this),\n FromNode: this.transformFrom.bind(this),\n SelectAllNode: this.transformSelectAll.bind(this),\n AndNode: this.transformAnd.bind(this),\n OrNode: this.transformOr.bind(this),\n ValueNode: this.transformValue.bind(this),\n ValueListNode: this.transformValueList.bind(this),\n PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this),\n ParensNode: this.transformParens.bind(this),\n JoinNode: this.transformJoin.bind(this),\n OperatorNode: this.transformOperator.bind(this),\n WhereNode: this.transformWhere.bind(this),\n InsertQueryNode: this.transformInsertQuery.bind(this),\n DeleteQueryNode: this.transformDeleteQuery.bind(this),\n ReturningNode: this.transformReturning.bind(this),\n CreateTableNode: this.transformCreateTable.bind(this),\n AddColumnNode: this.transformAddColumn.bind(this),\n ColumnDefinitionNode: this.transformColumnDefinition.bind(this),\n DropTableNode: this.transformDropTable.bind(this),\n DataTypeNode: this.transformDataType.bind(this),\n OrderByNode: this.transformOrderBy.bind(this),\n OrderByItemNode: this.transformOrderByItem.bind(this),\n GroupByNode: this.transformGroupBy.bind(this),\n GroupByItemNode: this.transformGroupByItem.bind(this),\n UpdateQueryNode: this.transformUpdateQuery.bind(this),\n ColumnUpdateNode: this.transformColumnUpdate.bind(this),\n LimitNode: this.transformLimit.bind(this),\n OffsetNode: this.transformOffset.bind(this),\n OnConflictNode: this.transformOnConflict.bind(this),\n OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this),\n CreateIndexNode: this.transformCreateIndex.bind(this),\n DropIndexNode: this.transformDropIndex.bind(this),\n ListNode: this.transformList.bind(this),\n PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this),\n UniqueConstraintNode: this.transformUniqueConstraint.bind(this),\n ReferencesNode: this.transformReferences.bind(this),\n CheckConstraintNode: this.transformCheckConstraint.bind(this),\n WithNode: this.transformWith.bind(this),\n CommonTableExpressionNode: this.transformCommonTableExpression.bind(this),\n CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this),\n HavingNode: this.transformHaving.bind(this),\n CreateSchemaNode: this.transformCreateSchema.bind(this),\n DropSchemaNode: this.transformDropSchema.bind(this),\n AlterTableNode: this.transformAlterTable.bind(this),\n DropColumnNode: this.transformDropColumn.bind(this),\n RenameColumnNode: this.transformRenameColumn.bind(this),\n AlterColumnNode: this.transformAlterColumn.bind(this),\n ModifyColumnNode: this.transformModifyColumn.bind(this),\n AddConstraintNode: this.transformAddConstraint.bind(this),\n DropConstraintNode: this.transformDropConstraint.bind(this),\n RenameConstraintNode: this.transformRenameConstraint.bind(this),\n ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this),\n CreateViewNode: this.transformCreateView.bind(this),\n RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this),\n DropViewNode: this.transformDropView.bind(this),\n GeneratedNode: this.transformGenerated.bind(this),\n DefaultValueNode: this.transformDefaultValue.bind(this),\n OnNode: this.transformOn.bind(this),\n ValuesNode: this.transformValues.bind(this),\n SelectModifierNode: this.transformSelectModifier.bind(this),\n CreateTypeNode: this.transformCreateType.bind(this),\n DropTypeNode: this.transformDropType.bind(this),\n ExplainNode: this.transformExplain.bind(this),\n DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this),\n AggregateFunctionNode: this.transformAggregateFunction.bind(this),\n OverNode: this.transformOver.bind(this),\n PartitionByNode: this.transformPartitionBy.bind(this),\n PartitionByItemNode: this.transformPartitionByItem.bind(this),\n SetOperationNode: this.transformSetOperation.bind(this),\n BinaryOperationNode: this.transformBinaryOperation.bind(this),\n UnaryOperationNode: this.transformUnaryOperation.bind(this),\n UsingNode: this.transformUsing.bind(this),\n FunctionNode: this.transformFunction.bind(this),\n CaseNode: this.transformCase.bind(this),\n WhenNode: this.transformWhen.bind(this),\n JSONReferenceNode: this.transformJSONReference.bind(this),\n JSONPathNode: this.transformJSONPath.bind(this),\n JSONPathLegNode: this.transformJSONPathLeg.bind(this),\n JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this),\n TupleNode: this.transformTuple.bind(this),\n MergeQueryNode: this.transformMergeQuery.bind(this),\n MatchedNode: this.transformMatched.bind(this),\n AddIndexNode: this.transformAddIndex.bind(this),\n CastNode: this.transformCast.bind(this),\n FetchNode: this.transformFetch.bind(this),\n TopNode: this.transformTop.bind(this),\n OutputNode: this.transformOutput.bind(this),\n OrActionNode: this.transformOrAction.bind(this),\n CollateNode: this.transformCollate.bind(this),\n });\n transformNode(node, queryId) {\n if (!node) {\n return node;\n }\n this.nodeStack.push(node);\n const out = this.transformNodeImpl(node, queryId);\n this.nodeStack.pop();\n return freeze(out);\n }\n transformNodeImpl(node, queryId) {\n return this.#transformers[node.kind](node, queryId);\n }\n transformNodeList(list, queryId) {\n if (!list) {\n return list;\n }\n return freeze(list.map((node) => this.transformNode(node, queryId)));\n }\n transformSelectQuery(node, queryId) {\n return requireAllProps({\n kind: 'SelectQueryNode',\n from: this.transformNode(node.from, queryId),\n selections: this.transformNodeList(node.selections, queryId),\n distinctOn: this.transformNodeList(node.distinctOn, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n groupBy: this.transformNode(node.groupBy, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n where: this.transformNode(node.where, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n limit: this.transformNode(node.limit, queryId),\n offset: this.transformNode(node.offset, queryId),\n with: this.transformNode(node.with, queryId),\n having: this.transformNode(node.having, queryId),\n explain: this.transformNode(node.explain, queryId),\n setOperations: this.transformNodeList(node.setOperations, queryId),\n fetch: this.transformNode(node.fetch, queryId),\n top: this.transformNode(node.top, queryId),\n });\n }\n transformSelection(node, queryId) {\n return requireAllProps({\n kind: 'SelectionNode',\n selection: this.transformNode(node.selection, queryId),\n });\n }\n transformColumn(node, queryId) {\n return requireAllProps({\n kind: 'ColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAlias(node, queryId) {\n return requireAllProps({\n kind: 'AliasNode',\n node: this.transformNode(node.node, queryId),\n alias: this.transformNode(node.alias, queryId),\n });\n }\n transformTable(node, queryId) {\n return requireAllProps({\n kind: 'TableNode',\n table: this.transformNode(node.table, queryId),\n });\n }\n transformFrom(node, queryId) {\n return requireAllProps({\n kind: 'FromNode',\n froms: this.transformNodeList(node.froms, queryId),\n });\n }\n transformReference(node, queryId) {\n return requireAllProps({\n kind: 'ReferenceNode',\n column: this.transformNode(node.column, queryId),\n table: this.transformNode(node.table, queryId),\n });\n }\n transformAnd(node, queryId) {\n return requireAllProps({\n kind: 'AndNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformOr(node, queryId) {\n return requireAllProps({\n kind: 'OrNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformValueList(node, queryId) {\n return requireAllProps({\n kind: 'ValueListNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformParens(node, queryId) {\n return requireAllProps({\n kind: 'ParensNode',\n node: this.transformNode(node.node, queryId),\n });\n }\n transformJoin(node, queryId) {\n return requireAllProps({\n kind: 'JoinNode',\n joinType: node.joinType,\n table: this.transformNode(node.table, queryId),\n on: this.transformNode(node.on, queryId),\n });\n }\n transformRaw(node, queryId) {\n return requireAllProps({\n kind: 'RawNode',\n sqlFragments: freeze([...node.sqlFragments]),\n parameters: this.transformNodeList(node.parameters, queryId),\n });\n }\n transformWhere(node, queryId) {\n return requireAllProps({\n kind: 'WhereNode',\n where: this.transformNode(node.where, queryId),\n });\n }\n transformInsertQuery(node, queryId) {\n return requireAllProps({\n kind: 'InsertQueryNode',\n into: this.transformNode(node.into, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n values: this.transformNode(node.values, queryId),\n returning: this.transformNode(node.returning, queryId),\n onConflict: this.transformNode(node.onConflict, queryId),\n onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n ignore: node.ignore,\n orAction: this.transformNode(node.orAction, queryId),\n replace: node.replace,\n explain: this.transformNode(node.explain, queryId),\n defaultValues: node.defaultValues,\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformValues(node, queryId) {\n return requireAllProps({\n kind: 'ValuesNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformDeleteQuery(node, queryId) {\n return requireAllProps({\n kind: 'DeleteQueryNode',\n from: this.transformNode(node.from, queryId),\n using: this.transformNode(node.using, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n limit: this.transformNode(node.limit, queryId),\n explain: this.transformNode(node.explain, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformReturning(node, queryId) {\n return requireAllProps({\n kind: 'ReturningNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformCreateTable(node, queryId) {\n return requireAllProps({\n kind: 'CreateTableNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n constraints: this.transformNodeList(node.constraints, queryId),\n temporary: node.temporary,\n ifNotExists: node.ifNotExists,\n onCommit: node.onCommit,\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n selectQuery: this.transformNode(node.selectQuery, queryId),\n });\n }\n transformColumnDefinition(node, queryId) {\n return requireAllProps({\n kind: 'ColumnDefinitionNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n references: this.transformNode(node.references, queryId),\n primaryKey: node.primaryKey,\n autoIncrement: node.autoIncrement,\n unique: node.unique,\n notNull: node.notNull,\n unsigned: node.unsigned,\n defaultTo: this.transformNode(node.defaultTo, queryId),\n check: this.transformNode(node.check, queryId),\n generated: this.transformNode(node.generated, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n identity: node.identity,\n ifNotExists: node.ifNotExists,\n });\n }\n transformAddColumn(node, queryId) {\n return requireAllProps({\n kind: 'AddColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformDropTable(node, queryId) {\n return requireAllProps({\n kind: 'DropTableNode',\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformOrderBy(node, queryId) {\n return requireAllProps({\n kind: 'OrderByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformOrderByItem(node, queryId) {\n return requireAllProps({\n kind: 'OrderByItemNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n direction: this.transformNode(node.direction, queryId),\n collation: this.transformNode(node.collation, queryId),\n nulls: node.nulls,\n });\n }\n transformGroupBy(node, queryId) {\n return requireAllProps({\n kind: 'GroupByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformGroupByItem(node, queryId) {\n return requireAllProps({\n kind: 'GroupByItemNode',\n groupBy: this.transformNode(node.groupBy, queryId),\n });\n }\n transformUpdateQuery(node, queryId) {\n return requireAllProps({\n kind: 'UpdateQueryNode',\n table: this.transformNode(node.table, queryId),\n from: this.transformNode(node.from, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n explain: this.transformNode(node.explain, queryId),\n limit: this.transformNode(node.limit, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n });\n }\n transformColumnUpdate(node, queryId) {\n return requireAllProps({\n kind: 'ColumnUpdateNode',\n column: this.transformNode(node.column, queryId),\n value: this.transformNode(node.value, queryId),\n });\n }\n transformLimit(node, queryId) {\n return requireAllProps({\n kind: 'LimitNode',\n limit: this.transformNode(node.limit, queryId),\n });\n }\n transformOffset(node, queryId) {\n return requireAllProps({\n kind: 'OffsetNode',\n offset: this.transformNode(node.offset, queryId),\n });\n }\n transformOnConflict(node, queryId) {\n return requireAllProps({\n kind: 'OnConflictNode',\n columns: this.transformNodeList(node.columns, queryId),\n constraint: this.transformNode(node.constraint, queryId),\n indexExpression: this.transformNode(node.indexExpression, queryId),\n indexWhere: this.transformNode(node.indexWhere, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n updateWhere: this.transformNode(node.updateWhere, queryId),\n doNothing: node.doNothing,\n });\n }\n transformOnDuplicateKey(node, queryId) {\n return requireAllProps({\n kind: 'OnDuplicateKeyNode',\n updates: this.transformNodeList(node.updates, queryId),\n });\n }\n transformCreateIndex(node, queryId) {\n return requireAllProps({\n kind: 'CreateIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n where: this.transformNode(node.where, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n });\n }\n transformList(node, queryId) {\n return requireAllProps({\n kind: 'ListNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformDropIndex(node, queryId) {\n return requireAllProps({\n kind: 'DropIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformPrimaryKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'PrimaryKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformUniqueConstraint(node, queryId) {\n return requireAllProps({\n kind: 'UniqueConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformForeignKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'ForeignKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n references: this.transformNode(node.references, queryId),\n name: this.transformNode(node.name, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformSetOperation(node, queryId) {\n return requireAllProps({\n kind: 'SetOperationNode',\n operator: node.operator,\n expression: this.transformNode(node.expression, queryId),\n all: node.all,\n });\n }\n transformReferences(node, queryId) {\n return requireAllProps({\n kind: 'ReferencesNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n });\n }\n transformCheckConstraint(node, queryId) {\n return requireAllProps({\n kind: 'CheckConstraintNode',\n expression: this.transformNode(node.expression, queryId),\n name: this.transformNode(node.name, queryId),\n });\n }\n transformWith(node, queryId) {\n return requireAllProps({\n kind: 'WithNode',\n expressions: this.transformNodeList(node.expressions, queryId),\n recursive: node.recursive,\n });\n }\n transformCommonTableExpression(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNode',\n name: this.transformNode(node.name, queryId),\n materialized: node.materialized,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformCommonTableExpressionName(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNameNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n });\n }\n transformHaving(node, queryId) {\n return requireAllProps({\n kind: 'HavingNode',\n having: this.transformNode(node.having, queryId),\n });\n }\n transformCreateSchema(node, queryId) {\n return requireAllProps({\n kind: 'CreateSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformDropSchema(node, queryId) {\n return requireAllProps({\n kind: 'DropSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformAlterTable(node, queryId) {\n return requireAllProps({\n kind: 'AlterTableNode',\n table: this.transformNode(node.table, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n setSchema: this.transformNode(node.setSchema, queryId),\n columnAlterations: this.transformNodeList(node.columnAlterations, queryId),\n addConstraint: this.transformNode(node.addConstraint, queryId),\n dropConstraint: this.transformNode(node.dropConstraint, queryId),\n renameConstraint: this.transformNode(node.renameConstraint, queryId),\n addIndex: this.transformNode(node.addIndex, queryId),\n dropIndex: this.transformNode(node.dropIndex, queryId),\n });\n }\n transformDropColumn(node, queryId) {\n return requireAllProps({\n kind: 'DropColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformRenameColumn(node, queryId) {\n return requireAllProps({\n kind: 'RenameColumnNode',\n column: this.transformNode(node.column, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n });\n }\n transformAlterColumn(node, queryId) {\n return requireAllProps({\n kind: 'AlterColumnNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId),\n setDefault: this.transformNode(node.setDefault, queryId),\n dropDefault: node.dropDefault,\n setNotNull: node.setNotNull,\n dropNotNull: node.dropNotNull,\n });\n }\n transformModifyColumn(node, queryId) {\n return requireAllProps({\n kind: 'ModifyColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAddConstraint(node, queryId) {\n return requireAllProps({\n kind: 'AddConstraintNode',\n constraint: this.transformNode(node.constraint, queryId),\n });\n }\n transformDropConstraint(node, queryId) {\n return requireAllProps({\n kind: 'DropConstraintNode',\n constraintName: this.transformNode(node.constraintName, queryId),\n ifExists: node.ifExists,\n modifier: node.modifier,\n });\n }\n transformRenameConstraint(node, queryId) {\n return requireAllProps({\n kind: 'RenameConstraintNode',\n oldName: this.transformNode(node.oldName, queryId),\n newName: this.transformNode(node.newName, queryId),\n });\n }\n transformCreateView(node, queryId) {\n return requireAllProps({\n kind: 'CreateViewNode',\n name: this.transformNode(node.name, queryId),\n temporary: node.temporary,\n orReplace: node.orReplace,\n ifNotExists: node.ifNotExists,\n materialized: node.materialized,\n columns: this.transformNodeList(node.columns, queryId),\n as: this.transformNode(node.as, queryId),\n });\n }\n transformRefreshMaterializedView(node, queryId) {\n return requireAllProps({\n kind: 'RefreshMaterializedViewNode',\n name: this.transformNode(node.name, queryId),\n concurrently: node.concurrently,\n withNoData: node.withNoData,\n });\n }\n transformDropView(node, queryId) {\n return requireAllProps({\n kind: 'DropViewNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n materialized: node.materialized,\n cascade: node.cascade,\n });\n }\n transformGenerated(node, queryId) {\n return requireAllProps({\n kind: 'GeneratedNode',\n byDefault: node.byDefault,\n always: node.always,\n identity: node.identity,\n stored: node.stored,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformDefaultValue(node, queryId) {\n return requireAllProps({\n kind: 'DefaultValueNode',\n defaultValue: this.transformNode(node.defaultValue, queryId),\n });\n }\n transformOn(node, queryId) {\n return requireAllProps({\n kind: 'OnNode',\n on: this.transformNode(node.on, queryId),\n });\n }\n transformSelectModifier(node, queryId) {\n return requireAllProps({\n kind: 'SelectModifierNode',\n modifier: node.modifier,\n rawModifier: this.transformNode(node.rawModifier, queryId),\n of: this.transformNodeList(node.of, queryId),\n });\n }\n transformCreateType(node, queryId) {\n return requireAllProps({\n kind: 'CreateTypeNode',\n name: this.transformNode(node.name, queryId),\n enum: this.transformNode(node.enum, queryId),\n });\n }\n transformDropType(node, queryId) {\n return requireAllProps({\n kind: 'DropTypeNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n });\n }\n transformExplain(node, queryId) {\n return requireAllProps({\n kind: 'ExplainNode',\n format: node.format,\n options: this.transformNode(node.options, queryId),\n });\n }\n transformSchemableIdentifier(node, queryId) {\n return requireAllProps({\n kind: 'SchemableIdentifierNode',\n schema: this.transformNode(node.schema, queryId),\n identifier: this.transformNode(node.identifier, queryId),\n });\n }\n transformAggregateFunction(node, queryId) {\n return requireAllProps({\n kind: 'AggregateFunctionNode',\n func: node.func,\n aggregated: this.transformNodeList(node.aggregated, queryId),\n distinct: node.distinct,\n orderBy: this.transformNode(node.orderBy, queryId),\n withinGroup: this.transformNode(node.withinGroup, queryId),\n filter: this.transformNode(node.filter, queryId),\n over: this.transformNode(node.over, queryId),\n });\n }\n transformOver(node, queryId) {\n return requireAllProps({\n kind: 'OverNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformPartitionBy(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformPartitionByItem(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByItemNode',\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformBinaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'BinaryOperationNode',\n leftOperand: this.transformNode(node.leftOperand, queryId),\n operator: this.transformNode(node.operator, queryId),\n rightOperand: this.transformNode(node.rightOperand, queryId),\n });\n }\n transformUnaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'UnaryOperationNode',\n operator: this.transformNode(node.operator, queryId),\n operand: this.transformNode(node.operand, queryId),\n });\n }\n transformUsing(node, queryId) {\n return requireAllProps({\n kind: 'UsingNode',\n tables: this.transformNodeList(node.tables, queryId),\n });\n }\n transformFunction(node, queryId) {\n return requireAllProps({\n kind: 'FunctionNode',\n func: node.func,\n arguments: this.transformNodeList(node.arguments, queryId),\n });\n }\n transformCase(node, queryId) {\n return requireAllProps({\n kind: 'CaseNode',\n value: this.transformNode(node.value, queryId),\n when: this.transformNodeList(node.when, queryId),\n else: this.transformNode(node.else, queryId),\n isStatement: node.isStatement,\n });\n }\n transformWhen(node, queryId) {\n return requireAllProps({\n kind: 'WhenNode',\n condition: this.transformNode(node.condition, queryId),\n result: this.transformNode(node.result, queryId),\n });\n }\n transformJSONReference(node, queryId) {\n return requireAllProps({\n kind: 'JSONReferenceNode',\n reference: this.transformNode(node.reference, queryId),\n traversal: this.transformNode(node.traversal, queryId),\n });\n }\n transformJSONPath(node, queryId) {\n return requireAllProps({\n kind: 'JSONPathNode',\n inOperator: this.transformNode(node.inOperator, queryId),\n pathLegs: this.transformNodeList(node.pathLegs, queryId),\n });\n }\n transformJSONPathLeg(node, _queryId) {\n return requireAllProps({\n kind: 'JSONPathLegNode',\n type: node.type,\n value: node.value,\n });\n }\n transformJSONOperatorChain(node, queryId) {\n return requireAllProps({\n kind: 'JSONOperatorChainNode',\n operator: this.transformNode(node.operator, queryId),\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformTuple(node, queryId) {\n return requireAllProps({\n kind: 'TupleNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformMergeQuery(node, queryId) {\n return requireAllProps({\n kind: 'MergeQueryNode',\n into: this.transformNode(node.into, queryId),\n using: this.transformNode(node.using, queryId),\n whens: this.transformNodeList(node.whens, queryId),\n with: this.transformNode(node.with, queryId),\n top: this.transformNode(node.top, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n output: this.transformNode(node.output, queryId),\n returning: this.transformNode(node.returning, queryId),\n });\n }\n transformMatched(node, _queryId) {\n return requireAllProps({\n kind: 'MatchedNode',\n not: node.not,\n bySource: node.bySource,\n });\n }\n transformAddIndex(node, queryId) {\n return requireAllProps({\n kind: 'AddIndexNode',\n name: this.transformNode(node.name, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformCast(node, queryId) {\n return requireAllProps({\n kind: 'CastNode',\n expression: this.transformNode(node.expression, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n });\n }\n transformFetch(node, queryId) {\n return requireAllProps({\n kind: 'FetchNode',\n rowCount: this.transformNode(node.rowCount, queryId),\n modifier: node.modifier,\n });\n }\n transformTop(node, _queryId) {\n return requireAllProps({\n kind: 'TopNode',\n expression: node.expression,\n modifiers: node.modifiers,\n });\n }\n transformOutput(node, queryId) {\n return requireAllProps({\n kind: 'OutputNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformDataType(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformSelectAll(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformIdentifier(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformPrimitiveValueList(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOperator(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformDefaultInsertValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOrAction(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformCollate(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n}\n","/// <reference types=\"./with-schema-transformer.d.ts\" />\nimport { AliasNode } from '../../operation-node/alias-node.js';\nimport { IdentifierNode } from '../../operation-node/identifier-node.js';\nimport { JoinNode } from '../../operation-node/join-node.js';\nimport { ListNode } from '../../operation-node/list-node.js';\nimport { OperationNodeTransformer } from '../../operation-node/operation-node-transformer.js';\nimport { SchemableIdentifierNode } from '../../operation-node/schemable-identifier-node.js';\nimport { TableNode } from '../../operation-node/table-node.js';\nimport { UsingNode } from '../../operation-node/using-node.js';\nimport { freeze } from '../../util/object-utils.js';\n// This object exist only so that we get a type error when a new RootOperationNode\n// is added. If you get a type error here, make sure to add the new root node and\n// handle it correctly in the transformer.\n//\n// DO NOT REFACTOR THIS EVEN IF IT SEEMS USELESS TO YOU!\nconst ROOT_OPERATION_NODES = freeze({\n AlterTableNode: true,\n CreateIndexNode: true,\n CreateSchemaNode: true,\n CreateTableNode: true,\n CreateTypeNode: true,\n CreateViewNode: true,\n RefreshMaterializedViewNode: true,\n DeleteQueryNode: true,\n DropIndexNode: true,\n DropSchemaNode: true,\n DropTableNode: true,\n DropTypeNode: true,\n DropViewNode: true,\n InsertQueryNode: true,\n RawNode: true,\n SelectQueryNode: true,\n UpdateQueryNode: true,\n MergeQueryNode: true,\n});\nconst SCHEMALESS_FUNCTIONS = {\n json_agg: true,\n to_json: true,\n};\nexport class WithSchemaTransformer extends OperationNodeTransformer {\n #schema;\n #schemableIds = new Set();\n #ctes = new Set();\n constructor(schema) {\n super();\n this.#schema = schema;\n }\n transformNodeImpl(node, queryId) {\n if (!this.#isRootOperationNode(node)) {\n return super.transformNodeImpl(node, queryId);\n }\n const ctes = this.#collectCTEs(node);\n for (const cte of ctes) {\n this.#ctes.add(cte);\n }\n const tables = this.#collectSchemableIds(node);\n for (const table of tables) {\n this.#schemableIds.add(table);\n }\n const transformed = super.transformNodeImpl(node, queryId);\n for (const table of tables) {\n this.#schemableIds.delete(table);\n }\n for (const cte of ctes) {\n this.#ctes.delete(cte);\n }\n return transformed;\n }\n transformSchemableIdentifier(node, queryId) {\n const transformed = super.transformSchemableIdentifier(node, queryId);\n if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) {\n return transformed;\n }\n return {\n ...transformed,\n schema: IdentifierNode.create(this.#schema),\n };\n }\n transformReferences(node, queryId) {\n const transformed = super.transformReferences(node, queryId);\n if (transformed.table.table.schema) {\n return transformed;\n }\n return {\n ...transformed,\n table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name),\n };\n }\n transformAggregateFunction(node, queryId) {\n return {\n ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId),\n aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, 'aggregated'),\n };\n }\n transformFunction(node, queryId) {\n return {\n ...super.transformFunction({ ...node, arguments: [] }, queryId),\n arguments: this.#transformTableArgsWithoutSchemas(node, queryId, 'arguments'),\n };\n }\n transformSelectModifier(node, queryId) {\n return {\n ...super.transformSelectModifier({ ...node, of: undefined }, queryId),\n of: node.of?.map((item) => TableNode.is(item) && !item.table.schema\n ? {\n ...item,\n table: this.transformIdentifier(item.table.identifier, queryId),\n }\n : this.transformNode(item, queryId)),\n };\n }\n #transformTableArgsWithoutSchemas(node, queryId, argsKey) {\n return SCHEMALESS_FUNCTIONS[node.func]\n ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema\n ? this.transformNode(arg, queryId)\n : {\n ...arg,\n table: this.transformIdentifier(arg.table.identifier, queryId),\n })\n : this.transformNodeList(node[argsKey], queryId);\n }\n #isRootOperationNode(node) {\n return node.kind in ROOT_OPERATION_NODES;\n }\n #collectSchemableIds(node) {\n const schemableIds = new Set();\n if ('name' in node && node.name && SchemableIdentifierNode.is(node.name)) {\n this.#collectSchemableId(node.name, schemableIds);\n }\n if ('from' in node && node.from) {\n for (const from of node.from.froms) {\n this.#collectSchemableIdsFromTableExpr(from, schemableIds);\n }\n }\n if ('into' in node && node.into) {\n this.#collectSchemableIdsFromTableExpr(node.into, schemableIds);\n }\n if ('table' in node && node.table) {\n this.#collectSchemableIdsFromTableExpr(node.table, schemableIds);\n }\n if ('joins' in node && node.joins) {\n for (const join of node.joins) {\n this.#collectSchemableIdsFromTableExpr(join.table, schemableIds);\n }\n }\n if ('using' in node && node.using) {\n if (JoinNode.is(node.using)) {\n this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds);\n }\n else {\n this.#collectSchemableIdsFromTableExpr(node.using, schemableIds);\n }\n }\n return schemableIds;\n }\n #collectCTEs(node) {\n const ctes = new Set();\n if ('with' in node && node.with) {\n this.#collectCTEIds(node.with, ctes);\n }\n return ctes;\n }\n #collectSchemableIdsFromTableExpr(node, schemableIds) {\n if (TableNode.is(node)) {\n return this.#collectSchemableId(node.table, schemableIds);\n }\n if (AliasNode.is(node) && TableNode.is(node.node)) {\n return this.#collectSchemableId(node.node.table, schemableIds);\n }\n if (ListNode.is(node)) {\n for (const table of node.items) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n if (UsingNode.is(node)) {\n for (const table of node.tables) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n }\n #collectSchemableId(node, schemableIds) {\n const id = node.identifier.name;\n if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) {\n schemableIds.add(id);\n }\n }\n #collectCTEIds(node, ctes) {\n for (const expr of node.expressions) {\n const cteId = expr.name.table.table.identifier.name;\n if (!this.#ctes.has(cteId)) {\n ctes.add(cteId);\n }\n }\n }\n}\n","/// <reference types=\"./with-schema-plugin.d.ts\" />\nimport { WithSchemaTransformer } from './with-schema-transformer.js';\nexport class WithSchemaPlugin {\n #transformer;\n constructor(schema) {\n this.#transformer = new WithSchemaTransformer(schema);\n }\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n return args.result;\n }\n}\n","/// <reference types=\"./deferred.d.ts\" />\nexport class Deferred {\n #promise;\n #resolve;\n #reject;\n constructor() {\n this.#promise = new Promise((resolve, reject) => {\n this.#reject = reject;\n this.#resolve = resolve;\n });\n }\n get promise() {\n return this.#promise;\n }\n resolve = (value) => {\n if (this.#resolve) {\n this.#resolve(value);\n }\n };\n reject = (reason) => {\n if (this.#reject) {\n this.#reject(reason);\n }\n };\n}\n","/// <reference types=\"./provide-controlled-connection.d.ts\" />\nimport { Deferred } from './deferred.js';\nimport { freeze } from './object-utils.js';\nexport async function provideControlledConnection(connectionProvider) {\n const connectionDefer = new Deferred();\n const connectionReleaseDefer = new Deferred();\n connectionProvider\n .provideConnection(async (connection) => {\n connectionDefer.resolve(connection);\n return await connectionReleaseDefer.promise;\n })\n .catch((ex) => connectionDefer.reject(ex));\n // Create composite of the connection and the release method instead of\n // modifying the connection or creating a new nesting `DatabaseConnection`.\n // This way we don't accidentally override any methods of 3rd party\n // connections and don't return wrapped connections to drivers that\n // expect a certain specific connection class.\n return freeze({\n connection: await connectionDefer.promise,\n release: connectionReleaseDefer.resolve,\n });\n}\n","/// <reference types=\"./query-executor-base.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { provideControlledConnection } from '../util/provide-controlled-connection.js';\nimport { logOnce } from '../util/log-once.js';\nconst NO_PLUGINS = freeze([]);\nexport class QueryExecutorBase {\n #plugins;\n constructor(plugins = NO_PLUGINS) {\n this.#plugins = plugins;\n }\n get plugins() {\n return this.#plugins;\n }\n transformQuery(node, queryId) {\n for (const plugin of this.#plugins) {\n const transformedNode = plugin.transformQuery({ node, queryId });\n // We need to do a runtime check here. There is no good way\n // to write types that enforce this constraint.\n if (transformedNode.kind === node.kind) {\n node = transformedNode;\n }\n else {\n throw new Error([\n `KyselyPlugin.transformQuery must return a node`,\n `of the same kind that was given to it.`,\n `The plugin was given a ${node.kind}`,\n `but it returned a ${transformedNode.kind}`,\n ].join(' '));\n }\n }\n return node;\n }\n async executeQuery(compiledQuery) {\n return await this.provideConnection(async (connection) => {\n const result = await connection.executeQuery(compiledQuery);\n if ('numUpdatedOrDeletedRows' in result) {\n logOnce('kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.');\n }\n return await this.#transformResult(result, compiledQuery.queryId);\n });\n }\n async *stream(compiledQuery, chunkSize) {\n const { connection, release } = await provideControlledConnection(this);\n try {\n for await (const result of connection.streamQuery(compiledQuery, chunkSize)) {\n yield await this.#transformResult(result, compiledQuery.queryId);\n }\n }\n finally {\n release();\n }\n }\n async #transformResult(result, queryId) {\n for (const plugin of this.#plugins) {\n result = await plugin.transformResult({ result, queryId });\n }\n return result;\n }\n}\n","/// <reference types=\"./noop-query-executor.d.ts\" />\nimport { QueryExecutorBase } from './query-executor-base.js';\n/**\n * A {@link QueryExecutor} subclass that can be used when you don't\n * have a {@link QueryCompiler}, {@link ConnectionProvider} or any\n * other needed things to actually execute queries.\n */\nexport class NoopQueryExecutor extends QueryExecutorBase {\n get adapter() {\n throw new Error('this query cannot be compiled to SQL');\n }\n compileQuery() {\n throw new Error('this query cannot be compiled to SQL');\n }\n provideConnection() {\n throw new Error('this query cannot be executed');\n }\n withConnectionProvider() {\n throw new Error('this query cannot have a connection provider');\n }\n withPlugin(plugin) {\n return new NoopQueryExecutor([...this.plugins, plugin]);\n }\n withPlugins(plugins) {\n return new NoopQueryExecutor([...this.plugins, ...plugins]);\n }\n withPluginAtFront(plugin) {\n return new NoopQueryExecutor([plugin, ...this.plugins]);\n }\n withoutPlugins() {\n return new NoopQueryExecutor([]);\n }\n}\nexport const NOOP_QUERY_EXECUTOR = new NoopQueryExecutor();\n","/// <reference types=\"./parse-utils.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { OverNode } from '../operation-node/over-node.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { JoinBuilder } from '../query-builder/join-builder.js';\nimport { OverBuilder } from '../query-builder/over-builder.js';\nimport { createSelectQueryBuilder as newSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { QueryCreator } from '../query-creator.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { parseTableExpression, parseTableExpressionOrList, } from './table-parser.js';\nexport function createSelectQueryBuilder() {\n return newSelectQueryBuilder({\n queryId: createQueryId(),\n executor: NOOP_QUERY_EXECUTOR,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList([])),\n });\n}\nexport function createQueryCreator() {\n return new QueryCreator({\n executor: NOOP_QUERY_EXECUTOR,\n });\n}\nexport function createJoinBuilder(joinType, table) {\n return new JoinBuilder({\n joinNode: JoinNode.create(joinType, parseTableExpression(table)),\n });\n}\nexport function createOverBuilder() {\n return new OverBuilder({\n overNode: OverNode.create(),\n });\n}\n","/// <reference types=\"./join-parser.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { parseReferentialBinaryOperation } from './binary-operation-parser.js';\nimport { createJoinBuilder } from './parse-utils.js';\nimport { parseTableExpression, } from './table-parser.js';\nexport function parseJoin(joinType, args) {\n if (args.length === 3) {\n return parseSingleOnJoin(joinType, args[0], args[1], args[2]);\n }\n else if (args.length === 2) {\n return parseCallbackJoin(joinType, args[0], args[1]);\n }\n else if (args.length === 1) {\n return parseOnlessJoin(joinType, args[0]);\n }\n else {\n throw new Error('not implemented');\n }\n}\nfunction parseCallbackJoin(joinType, from, callback) {\n return callback(createJoinBuilder(joinType, from)).toOperationNode();\n}\nfunction parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) {\n return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, '=', rhsColumn));\n}\nfunction parseOnlessJoin(joinType, from) {\n return JoinNode.create(joinType, parseTableExpression(from));\n}\n","/// <reference types=\"./offset-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OffsetNode = freeze({\n is(node) {\n return node.kind === 'OffsetNode';\n },\n create(offset) {\n return freeze({\n kind: 'OffsetNode',\n offset,\n });\n },\n});\n","/// <reference types=\"./group-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByItemNode = freeze({\n is(node) {\n return node.kind === 'GroupByItemNode';\n },\n create(groupBy) {\n return freeze({\n kind: 'GroupByItemNode',\n groupBy,\n });\n },\n});\n","/// <reference types=\"./group-by-parser.d.ts\" />\nimport { GroupByItemNode } from '../operation-node/group-by-item-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parseGroupBy(groupBy) {\n groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy;\n return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create);\n}\n","/// <reference types=\"./set-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SetOperationNode = freeze({\n is(node) {\n return node.kind === 'SetOperationNode';\n },\n create(operator, expression, all) {\n return freeze({\n kind: 'SetOperationNode',\n operator,\n expression,\n all,\n });\n },\n});\n","/// <reference types=\"./set-operation-parser.d.ts\" />\nimport { createExpressionBuilder, } from '../expression/expression-builder.js';\nimport { SetOperationNode, } from '../operation-node/set-operation-node.js';\nimport { isFunction, isReadonlyArray } from '../util/object-utils.js';\nimport { parseExpression } from './expression-parser.js';\nexport function parseSetOperations(operator, expression, all) {\n if (isFunction(expression)) {\n expression = expression(createExpressionBuilder());\n }\n if (!isReadonlyArray(expression)) {\n expression = [expression];\n }\n return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all));\n}\n","/// <reference types=\"./expression-wrapper.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { OrNode } from '../operation-node/or-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nexport class ExpressionWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `ExpressionWrapper` with a new output type.\n */\n $castTo() {\n return new ExpressionWrapper(this.#node);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new ExpressionWrapper(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedExpressionWrapper {\n #expr;\n #alias;\n constructor(expr, alias) {\n this.#expr = expr;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#expr;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\nexport class OrWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `OrWrapper` with a new output type.\n */\n $castTo() {\n return new OrWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\nexport class AndWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AndWrapper` with a new output type.\n */\n $castTo() {\n return new AndWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\n","/// <reference types=\"./fetch-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { ValueNode } from './value-node.js';\n/**\n * @internal\n */\nexport const FetchNode = freeze({\n is(node) {\n return node.kind === 'FetchNode';\n },\n create(rowCount, modifier) {\n return {\n kind: 'FetchNode',\n rowCount: ValueNode.create(rowCount),\n modifier,\n };\n },\n});\n","/// <reference types=\"./fetch-parser.d.ts\" />\nimport { FetchNode } from '../operation-node/fetch-node.js';\nimport { isBigInt, isNumber } from '../util/object-utils.js';\nexport function parseFetch(rowCount, modifier) {\n if (!isNumber(rowCount) && !isBigInt(rowCount)) {\n throw new Error(`Invalid fetch row count: ${rowCount}`);\n }\n if (!isFetchModifier(modifier)) {\n throw new Error(`Invalid fetch modifier: ${modifier}`);\n }\n return FetchNode.create(rowCount, modifier);\n}\nfunction isFetchModifier(value) {\n return value === 'only' || value === 'with ties';\n}\n","/// <reference types=\"./select-query-builder.d.ts\" />\nvar _a;\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { SelectModifierNode } from '../operation-node/select-modifier-node.js';\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { OffsetNode } from '../operation-node/offset-node.js';\nimport { asArray, freeze } from '../util/object-utils.js';\nimport { parseGroupBy } from '../parser/group-by-parser.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { parseSetOperations, } from '../parser/set-operation-parser.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { parseFetch } from '../parser/fetch-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nclass SelectQueryBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isSelectQueryBuilder() {\n return true;\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n having(...args) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n havingRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n select(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n distinctOn(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection)),\n });\n }\n modifyFront(modifier) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n distinct() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create('Distinct')),\n });\n }\n forUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forKeyShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForKeyShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forNoKeyUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForNoKeyUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n skipLocked() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('SkipLocked')),\n });\n }\n noWait() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('NoWait')),\n });\n }\n selectAll(table) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n crossJoin(...args) {\n return this.#join('CrossJoin', args);\n }\n innerJoinLateral(...args) {\n return this.#join('LateralInnerJoin', args);\n }\n leftJoinLateral(...args) {\n return this.#join('LateralLeftJoin', args);\n }\n crossJoinLateral(...args) {\n return this.#join('LateralCrossJoin', args);\n }\n crossApply(...args) {\n return this.#join('CrossApply', args);\n }\n outerApply(...args) {\n return this.#join('OuterApply', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n groupBy(groupBy) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy)),\n });\n }\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n offset(offset) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset))),\n });\n }\n fetch(rowCount, modifier = 'only') {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier)),\n });\n }\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n union(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, false)),\n });\n }\n unionAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, true)),\n });\n }\n intersect(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, false)),\n });\n }\n intersectAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, true)),\n });\n }\n except(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, false)),\n });\n }\n exceptAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, true)),\n });\n }\n as(alias) {\n return new AliasedSelectQueryBuilderImpl(this, alias);\n }\n clearSelect() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n clearLimit() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode),\n });\n }\n clearOffset() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n clearGroupBy() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode),\n });\n }\n $call(func) {\n return func(this);\n }\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n $castTo() {\n return new _a(this.#props);\n }\n $narrowType() {\n return new _a(this.#props);\n }\n $assertType() {\n return new _a(this.#props);\n }\n $asTuple() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n $asScalar() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n return result.rows;\n }\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = SelectQueryBuilderImpl;\nexport function createSelectQueryBuilder(props) {\n return new SelectQueryBuilderImpl(props);\n}\n/**\n * {@link SelectQueryBuilder} with an alias. The result of calling {@link SelectQueryBuilder.as}.\n */\nclass AliasedSelectQueryBuilderImpl {\n #queryBuilder;\n #alias;\n constructor(queryBuilder, alias) {\n this.#queryBuilder = queryBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#queryBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get isAliasedSelectQueryBuilder() {\n return true;\n }\n toOperationNode() {\n return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./aggregate-function-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhereNode } from './where-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const AggregateFunctionNode = freeze({\n is(node) {\n return node.kind === 'AggregateFunctionNode';\n },\n create(aggregateFunction, aggregated = []) {\n return freeze({\n kind: 'AggregateFunctionNode',\n func: aggregateFunction,\n aggregated,\n });\n },\n cloneWithDistinct(aggregateFunctionNode) {\n return freeze({\n ...aggregateFunctionNode,\n distinct: true,\n });\n },\n cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) {\n const prop = withinGroup ? 'withinGroup' : 'orderBy';\n return freeze({\n ...aggregateFunctionNode,\n [prop]: aggregateFunctionNode[prop]\n ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems)\n : OrderByNode.create(orderItems),\n });\n },\n cloneWithFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'And', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOrFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'Or', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOver(aggregateFunctionNode, over) {\n return freeze({\n ...aggregateFunctionNode,\n over,\n });\n },\n});\n","/// <reference types=\"./function-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FunctionNode = freeze({\n is(node) {\n return node.kind === 'FunctionNode';\n },\n create(func, args) {\n return freeze({\n kind: 'FunctionNode',\n func,\n arguments: args,\n });\n },\n});\n","/// <reference types=\"./aggregate-function-builder.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { createOverBuilder } from '../parser/parse-utils.js';\nimport { parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nexport class AggregateFunctionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n /**\n * Returns an aliased version of the function.\n *\n * In addition to slapping `as \"the_alias\"` to the end of the SQL,\n * this method also provides strict typing:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.count<number>('id').as('person_count')\n * )\n * .executeTakeFirstOrThrow()\n *\n * // `person_count: number` field exists in the result type.\n * console.log(result.person_count)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(\"id\") as \"person_count\"\n * from \"person\"\n * ```\n */\n as(alias) {\n return new AliasedAggregateFunctionBuilder(this, alias);\n }\n /**\n * Adds a `distinct` clause inside the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) =>\n * eb.fn.count<number>('first_name').distinct().as('first_name_count')\n * )\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(distinct \"first_name\") as \"first_name_count\"\n * from \"person\"\n * ```\n */\n distinct() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode),\n });\n }\n orderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode),\n });\n }\n withinGroupOrderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true),\n });\n }\n filterWhere(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Adds a `filter` clause with a nested `where` clause after the function, where\n * both sides of the operator are references to columns.\n *\n * Similar to {@link WhereInterface}'s `whereRef` method.\n *\n * ### Examples\n *\n * Count people with same first and last names versus general public:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) => [\n * eb.fn\n * .count<number>('id')\n * .filterWhereRef('first_name', '=', 'last_name')\n * .as('repeat_name_count'),\n * eb.fn.count<number>('id').as('total_count'),\n * ])\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select\n * count(\"id\") filter(where \"first_name\" = \"last_name\") as \"repeat_name_count\",\n * count(\"id\") as \"total_count\"\n * from \"person\"\n * ```\n */\n filterWhereRef(lhs, op, rhs) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds an `over` clause (window functions) after the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg<number>('age').over().as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over() as \"average_age\"\n * from \"person\"\n * ```\n *\n * Also supports passing a callback that returns an over builder,\n * allowing to add partition by and sort by clauses inside over.\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg<number>('age').over(\n * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc')\n * ).as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over(partition by \"last_name\" order by \"first_name\" asc) as \"average_age\"\n * from \"person\"\n * ```\n */\n over(over) {\n const builder = createOverBuilder();\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n /**\n * Casts the expression to the given type.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AggregateFunctionBuilder` with a new output type.\n */\n $castTo() {\n return new AggregateFunctionBuilder(this.#props);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new AggregateFunctionBuilder(this.#props);\n }\n toOperationNode() {\n return this.#props.aggregateFunctionNode;\n }\n}\n/**\n * {@link AggregateFunctionBuilder} with an alias. The result of calling {@link AggregateFunctionBuilder.as}.\n */\nexport class AliasedAggregateFunctionBuilder {\n #aggregateFunctionBuilder;\n #alias;\n constructor(aggregateFunctionBuilder, alias) {\n this.#aggregateFunctionBuilder = aggregateFunctionBuilder;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#aggregateFunctionBuilder;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./function-module.d.ts\" />\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { FunctionNode } from '../operation-node/function-node.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { parseSelectAll } from '../parser/select-parser.js';\nimport { AggregateFunctionBuilder } from './aggregate-function-builder.js';\nimport { isString } from '../util/object-utils.js';\nimport { parseTable } from '../parser/table-parser.js';\nexport function createFunctionModule() {\n const fn = (name, args) => {\n return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? [])));\n };\n const agg = (name, args) => {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : undefined),\n });\n };\n return Object.assign(fn, {\n agg,\n avg(column) {\n return agg('avg', [column]);\n },\n coalesce(...values) {\n return fn('coalesce', values);\n },\n count(column) {\n return agg('count', [column]);\n },\n countAll(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('count', parseSelectAll(table)),\n });\n },\n max(column) {\n return agg('max', [column]);\n },\n min(column) {\n return agg('min', [column]);\n },\n sum(column) {\n return agg('sum', [column]);\n },\n any(column) {\n return fn('any', [column]);\n },\n jsonAgg(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('json_agg', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]),\n });\n },\n toJson(table) {\n return new ExpressionWrapper(FunctionNode.create('to_json', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]));\n },\n });\n}\n","/// <reference types=\"./unary-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UnaryOperationNode = freeze({\n is(node) {\n return node.kind === 'UnaryOperationNode';\n },\n create(operator, operand) {\n return freeze({\n kind: 'UnaryOperationNode',\n operator,\n operand,\n });\n },\n});\n","/// <reference types=\"./unary-operation-parser.d.ts\" />\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { UnaryOperationNode } from '../operation-node/unary-operation-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nexport function parseExists(operand) {\n return parseUnaryOperation('exists', operand);\n}\nexport function parseNotExists(operand) {\n return parseUnaryOperation('not exists', operand);\n}\nexport function parseUnaryOperation(operator, operand) {\n return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand));\n}\n","/// <reference types=\"./case-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const CaseNode = freeze({\n is(node) {\n return node.kind === 'CaseNode';\n },\n create(value) {\n return freeze({\n kind: 'CaseNode',\n value,\n });\n },\n cloneWithWhen(caseNode, when) {\n return freeze({\n ...caseNode,\n when: freeze(caseNode.when ? [...caseNode.when, when] : [when]),\n });\n },\n cloneWithThen(caseNode, then) {\n return freeze({\n ...caseNode,\n when: caseNode.when\n ? freeze([\n ...caseNode.when.slice(0, -1),\n WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then),\n ])\n : undefined,\n });\n },\n cloneWith(caseNode, props) {\n return freeze({\n ...caseNode,\n ...props,\n });\n },\n});\n","/// <reference types=\"./case-builder.d.ts\" />\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { freeze } from '../util/object-utils.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { isSafeImmediateValue, parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nexport class CaseBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n}\nexport class CaseThenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n then(valueExpression) {\n return new CaseWhenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression)),\n });\n }\n}\nexport class CaseWhenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n else(valueExpression) {\n return new CaseEndBuilder({\n ...this.#props,\n node: CaseNode.cloneWith(this.#props.node, {\n else: isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression),\n }),\n });\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\nexport class CaseEndBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\n","/// <reference types=\"./json-path-leg-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathLegNode = freeze({\n is(node) {\n return node.kind === 'JSONPathLegNode';\n },\n create(type, value) {\n return freeze({\n kind: 'JSONPathLegNode',\n type,\n value,\n });\n },\n});\n","/// <reference types=\"./json-path-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathLegNode, } from '../operation-node/json-path-leg-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nexport class JSONPathBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Access an element of a JSON array in a specific location.\n *\n * Since there's no guarantee an element exists in the given array location, the\n * resulting type is always nullable. If you're sure the element exists, you\n * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely.\n *\n * See also {@link key} to access properties of JSON objects.\n *\n * ### Examples\n *\n * ```ts\n * await db.selectFrom('person')\n * .select(eb =>\n * eb.ref('nicknames', '->').at(0).as('primary_nickname')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"nicknames\"->0 as \"primary_nickname\" from \"person\"\n *```\n *\n * Combined with {@link key}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('experience', '->').at(0).key('role').as('first_role')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"experience\"->0->'role' as \"first_role\" from \"person\"\n * ```\n *\n * You can use `'last'` to access the last element of the array in MySQL:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->$').at('last').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `nicknames`->'$[last]' as `last_nickname` from `person`\n * ```\n *\n * Or `'#-1'` in SQLite:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select \"nicknames\"->>'$[#-1]' as `last_nickname` from `person`\n * ```\n */\n at(index) {\n return this.#createBuilderWithPathLeg('ArrayLocation', index);\n }\n /**\n * Access a property of a JSON object.\n *\n * If a field is optional, the resulting type will be nullable.\n *\n * See also {@link at} to access elements of JSON arrays.\n *\n * ### Examples\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('address', '->').key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"address\"->'city' as \"city\" from \"person\"\n * ```\n *\n * Going deeper:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->$').key('website').key('url').as('website_url')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `profile`->'$.website.url' as `website_url` from `person`\n * ```\n *\n * Combined with {@link at}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"profile\"->'addresses'->0->'city' as \"city\" from \"person\"\n * ```\n */\n key(key) {\n return this.#createBuilderWithPathLeg('Member', key);\n }\n #createBuilderWithPathLeg(legType, value) {\n if (JSONReferenceNode.is(this.#node)) {\n return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal)\n ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value))\n : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value))));\n }\n return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value)));\n }\n}\nexport class TraversedJSONPathBuilder extends JSONPathBuilder {\n #node;\n constructor(node) {\n super(node);\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedJSONPathBuilder(this, alias);\n }\n /**\n * Change the output type of the json path.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `JSONPathBuilder` with a new output type.\n */\n $castTo() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n $notNull() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedJSONPathBuilder {\n #jsonPath;\n #alias;\n constructor(jsonPath, alias) {\n this.#jsonPath = jsonPath;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#jsonPath;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./tuple-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TupleNode = freeze({\n is(node) {\n return node.kind === 'TupleNode';\n },\n create(values) {\n return freeze({\n kind: 'TupleNode',\n values: freeze(values),\n });\n },\n});\n","/// <reference types=\"./data-type-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nconst SIMPLE_COLUMN_DATA_TYPES = [\n 'varchar',\n 'char',\n 'text',\n 'integer',\n 'int2',\n 'int4',\n 'int8',\n 'smallint',\n 'bigint',\n 'boolean',\n 'real',\n 'double precision',\n 'float4',\n 'float8',\n 'decimal',\n 'numeric',\n 'binary',\n 'bytea',\n 'date',\n 'datetime',\n 'time',\n 'timetz',\n 'timestamp',\n 'timestamptz',\n 'serial',\n 'bigserial',\n 'uuid',\n 'json',\n 'jsonb',\n 'blob',\n 'varbinary',\n 'int4range',\n 'int4multirange',\n 'int8range',\n 'int8multirange',\n 'numrange',\n 'nummultirange',\n 'tsrange',\n 'tsmultirange',\n 'tstzrange',\n 'tstzmultirange',\n 'daterange',\n 'datemultirange',\n];\nconst COLUMN_DATA_TYPE_REGEX = [\n /^varchar\\(\\d+\\)$/,\n /^char\\(\\d+\\)$/,\n /^decimal\\(\\d+, \\d+\\)$/,\n /^numeric\\(\\d+, \\d+\\)$/,\n /^binary\\(\\d+\\)$/,\n /^datetime\\(\\d+\\)$/,\n /^time\\(\\d+\\)$/,\n /^timetz\\(\\d+\\)$/,\n /^timestamp\\(\\d+\\)$/,\n /^timestamptz\\(\\d+\\)$/,\n /^varbinary\\(\\d+\\)$/,\n];\n/**\n * @internal\n */\nexport const DataTypeNode = freeze({\n is(node) {\n return node.kind === 'DataTypeNode';\n },\n create(dataType) {\n return freeze({\n kind: 'DataTypeNode',\n dataType,\n });\n },\n});\nexport function isColumnDataType(dataType) {\n if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) {\n return true;\n }\n if (COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType))) {\n return true;\n }\n return false;\n}\n","/// <reference types=\"./data-type-parser.d.ts\" />\nimport { DataTypeNode, isColumnDataType, } from '../operation-node/data-type-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nexport function parseDataTypeExpression(dataType) {\n if (isOperationNodeSource(dataType)) {\n return dataType.toOperationNode();\n }\n if (isColumnDataType(dataType)) {\n return DataTypeNode.create(dataType);\n }\n throw new Error(`invalid column data type ${JSON.stringify(dataType)}`);\n}\n","/// <reference types=\"./cast-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const CastNode = freeze({\n is(node) {\n return node.kind === 'CastNode';\n },\n create(expression, dataType) {\n return freeze({\n kind: 'CastNode',\n expression,\n dataType,\n });\n },\n});\n","/// <reference types=\"./expression-builder.d.ts\" />\nimport { createSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { parseTableExpressionOrList, parseTable, } from '../parser/table-parser.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createFunctionModule, } from '../query-builder/function-module.js';\nimport { parseJSONReference, parseReferenceExpression, parseStringReference, } from '../parser/reference-parser.js';\nimport { parseFilterList, parseFilterObject, parseValueBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { ExpressionWrapper } from './expression-wrapper.js';\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { parseUnaryOperation } from '../parser/unary-operation-parser.js';\nimport { parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { CaseBuilder } from '../query-builder/case-builder.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { isReadonlyArray, isUndefined } from '../util/object-utils.js';\nimport { JSONPathBuilder } from '../query-builder/json-path-builder.js';\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { TupleNode } from '../operation-node/tuple-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { CastNode } from '../operation-node/cast-node.js';\nexport function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) {\n function binary(lhs, op, rhs) {\n return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs));\n }\n function unary(op, expr) {\n return new ExpressionWrapper(parseUnaryOperation(op, expr));\n }\n const eb = Object.assign(binary, {\n fn: undefined,\n eb: undefined,\n selectFrom(table) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)),\n });\n },\n case(reference) {\n return new CaseBuilder({\n node: CaseNode.create(isUndefined(reference)\n ? undefined\n : parseReferenceExpression(reference)),\n });\n },\n ref(reference, op) {\n if (isUndefined(op)) {\n return new ExpressionWrapper(parseStringReference(reference));\n }\n return new JSONPathBuilder(parseJSONReference(reference, op));\n },\n jsonPath() {\n return new JSONPathBuilder(JSONPathNode.create());\n },\n table(table) {\n return new ExpressionWrapper(parseTable(table));\n },\n val(value) {\n return new ExpressionWrapper(parseValueExpression(value));\n },\n refTuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression)));\n },\n tuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression)));\n },\n lit(value) {\n return new ExpressionWrapper(parseSafeImmediateValue(value));\n },\n unary,\n not(expr) {\n return unary('not', expr);\n },\n exists(expr) {\n return unary('exists', expr);\n },\n neg(expr) {\n return unary('-', expr);\n },\n between(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n betweenSymmetric(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between symmetric'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n and(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'and'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'and'));\n },\n or(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'or'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'or'));\n },\n parens(...args) {\n const node = parseValueBinaryOperationOrExpression(args);\n if (ParensNode.is(node)) {\n // No double wrapping.\n return new ExpressionWrapper(node);\n }\n else {\n return new ExpressionWrapper(ParensNode.create(node));\n }\n },\n cast(expr, dataType) {\n return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType)));\n },\n withSchema(schema) {\n return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema)));\n },\n });\n eb.fn = createFunctionModule();\n eb.eb = eb;\n return eb;\n}\nexport function expressionBuilder(_) {\n return createExpressionBuilder();\n}\n","/// <reference types=\"./expression-parser.d.ts\" />\nimport { isAliasedExpression, isExpression, } from '../expression/expression.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nexport function parseExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid expression: ${JSON.stringify(exp)}`);\n}\nexport function parseAliasedExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`);\n}\nexport function isExpressionOrFactory(obj) {\n return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj);\n}\n","/// <reference types=\"./dynamic-table-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicTableBuilder {\n #table;\n get table() {\n return this.#table;\n }\n constructor(table) {\n this.#table = table;\n }\n as(alias) {\n return new AliasedDynamicTableBuilder(this.#table, alias);\n }\n}\nexport class AliasedDynamicTableBuilder {\n #table;\n #alias;\n get table() {\n return this.#table;\n }\n get alias() {\n return this.#alias;\n }\n constructor(table, alias) {\n this.#table = table;\n this.#alias = alias;\n }\n toOperationNode() {\n return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias));\n }\n}\nexport function isAliasedDynamicTableBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.table) &&\n isString(obj.alias));\n}\n","/// <reference types=\"./table-parser.d.ts\" />\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isAliasedDynamicTableBuilder, } from '../dynamic/dynamic-table-builder.js';\nexport function parseTableExpressionOrList(table) {\n if (isReadonlyArray(table)) {\n return table.map((it) => parseTableExpression(it));\n }\n else {\n return [parseTableExpression(table)];\n }\n}\nexport function parseTableExpression(table) {\n if (isString(table)) {\n return parseAliasedTable(table);\n }\n else if (isAliasedDynamicTableBuilder(table)) {\n return table.toOperationNode();\n }\n else {\n return parseAliasedExpression(table);\n }\n}\nexport function parseAliasedTable(from) {\n const ALIAS_SEPARATOR = ' as ';\n if (from.includes(ALIAS_SEPARATOR)) {\n const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseTable(table), IdentifierNode.create(alias));\n }\n else {\n return parseTable(from);\n }\n}\nexport function parseTable(from) {\n const SCHEMA_SEPARATOR = '.';\n if (from.includes(SCHEMA_SEPARATOR)) {\n const [schema, table] = from.split(SCHEMA_SEPARATOR).map(trim);\n return TableNode.createWithSchema(schema, table);\n }\n else {\n return TableNode.create(from);\n }\n}\nfunction trim(str) {\n return str.trim();\n}\n","/// <reference types=\"./raw-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nclass RawBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isRawBuilder() {\n return true;\n }\n as(alias) {\n return new AliasedRawBuilderImpl(this, alias);\n }\n $castTo() {\n return new RawBuilderImpl({ ...this.#props });\n }\n $notNull() {\n return new RawBuilderImpl(this.#props);\n }\n withPlugin(plugin) {\n return new RawBuilderImpl({\n ...this.#props,\n plugins: this.#props.plugins !== undefined\n ? freeze([...this.#props.plugins, plugin])\n : freeze([plugin]),\n });\n }\n toOperationNode() {\n return this.#toOperationNode(this.#getExecutor());\n }\n compile(executorProvider) {\n return this.#compile(this.#getExecutor(executorProvider));\n }\n async execute(executorProvider) {\n const executor = this.#getExecutor(executorProvider);\n return executor.executeQuery(this.#compile(executor));\n }\n #getExecutor(executorProvider) {\n const executor = executorProvider !== undefined\n ? executorProvider.getExecutor()\n : NOOP_QUERY_EXECUTOR;\n return this.#props.plugins !== undefined\n ? executor.withPlugins(this.#props.plugins)\n : executor;\n }\n #toOperationNode(executor) {\n return executor.transformQuery(this.#props.rawNode, this.#props.queryId);\n }\n #compile(executor) {\n return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);\n }\n}\nexport function createRawBuilder(props) {\n return new RawBuilderImpl(props);\n}\nclass AliasedRawBuilderImpl {\n #rawBuilder;\n #alias;\n constructor(rawBuilder, alias) {\n this.#rawBuilder = rawBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#rawBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get rawBuilder() {\n return this.#rawBuilder;\n }\n toOperationNode() {\n return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./sql.d.ts\" />\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { parseStringReference } from '../parser/reference-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseValueExpression } from '../parser/value-parser.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createRawBuilder } from './raw-builder.js';\nexport const sql = Object.assign((sqlFragments, ...parameters) => {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []),\n });\n}, {\n ref(columnReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseStringReference(columnReference)),\n });\n },\n val(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseValueExpression(value)),\n });\n },\n value(value) {\n return this.val(value);\n },\n table(tableReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseTable(tableReference)),\n });\n },\n id(...ids) {\n const fragments = new Array(ids.length + 1).fill('.');\n fragments[0] = '';\n fragments[fragments.length - 1] = '';\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)),\n });\n },\n lit(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)),\n });\n },\n literal(value) {\n return this.lit(value);\n },\n raw(sql) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithSql(sql),\n });\n },\n join(array, separator = sql `, `) {\n const nodes = new Array(Math.max(2 * array.length - 1, 0));\n const sep = separator.toOperationNode();\n for (let i = 0; i < array.length; ++i) {\n nodes[2 * i] = parseParameter(array[i]);\n if (i !== array.length - 1) {\n nodes[2 * i + 1] = sep;\n }\n }\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChildren(nodes),\n });\n },\n});\nfunction parseParameter(param) {\n if (isOperationNodeSource(param)) {\n return param.toOperationNode();\n }\n return parseValueExpression(param);\n}\n","// The workflow document's `policy` block, as the runtime reads it.\n//\n// Every field here was schema-and-editor only until W3.3: the document model\n// has carried `concurrency`, `runTimeoutSeconds`, `defaultRetry` and\n// `onFailure` since its first version and nothing ever read them, so an author\n// who set them got no behaviour and no warning. The ones this module resolves\n// are now enforced; the ones it does not are marked \"not yet enforced\" in the\n// document model's own SDL, because a knob that lies is worse than one that is\n// absent.\n//\n// A definition with NO policy at all enforces nothing; only hand-built\n// definitions lack one. Every workflow document carries a policy: the field\n// is non-null in the model since v1, initialised to QUEUE, PARK and a 3600s\n// run timeout. Enforcing it therefore changes every deployed workflow; the\n// README lists how.\nimport {\n effectiveRetryPolicy,\n type EffectiveRetryPolicy,\n} from \"../pieces/index.js\";\nimport type { RunnableDefinition } from \"./runnable.js\";\n\nexport type ConcurrencyMode = \"SINGLETON\" | \"QUEUE\" | \"PARALLEL\";\nexport type FailureMode = \"PARK\" | \"NOTIFY\" | \"IGNORE\";\n\n/** What the runtime enforces for one run. */\nexport interface EffectiveRunPolicy {\n concurrency: ConcurrencyMode;\n /** Runs of THIS workflow that may execute at once under PARALLEL; null is\n * unbounded. The serialising modes carry 1 in {@link concurrencyLimit}. */\n maxParallelRuns: number | null;\n /** Null when the author set no bound. */\n runTimeoutSeconds: number | null;\n onFailure: FailureMode;\n /** The fallback for a step with no `retry` of its own. */\n defaultRetry: EffectiveRetryPolicy | null;\n}\n\n/** The pre-enforcement behaviour, for a definition that declares no policy. */\nexport const UNENFORCED_POLICY: EffectiveRunPolicy = Object.freeze({\n concurrency: \"PARALLEL\",\n maxParallelRuns: null,\n runTimeoutSeconds: null,\n onFailure: \"IGNORE\",\n defaultRetry: null,\n});\n\nconst CONCURRENCY_MODES: readonly string[] = [\"SINGLETON\", \"QUEUE\", \"PARALLEL\"];\nconst FAILURE_MODES: readonly string[] = [\"PARK\", \"NOTIFY\", \"IGNORE\"];\n\nfunction positive(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0\n ? value\n : null;\n}\n\n/** What the runtime enforces for a run of this definition. */\nexport function effectiveRunPolicy(\n runnable: Pick<RunnableDefinition, \"policy\">,\n): EffectiveRunPolicy {\n const policy = runnable.policy as Record<string, unknown> | undefined | null;\n if (!policy) return UNENFORCED_POLICY;\n // An unknown mode reads as the unenforced one rather than as the strictest:\n // a reactor on an older build must not start serialising or parking because\n // a newer schema added a value it cannot interpret.\n const concurrency = CONCURRENCY_MODES.includes(policy.concurrency as string)\n ? (policy.concurrency as ConcurrencyMode)\n : \"PARALLEL\";\n return {\n concurrency,\n maxParallelRuns:\n concurrency === \"PARALLEL\" ? positive(policy.maxParallelRuns) : null,\n runTimeoutSeconds: positive(policy.runTimeoutSeconds),\n onFailure: FAILURE_MODES.includes(policy.onFailure as string)\n ? (policy.onFailure as FailureMode)\n : \"IGNORE\",\n defaultRetry: effectiveRetryPolicy(policy.defaultRetry),\n };\n}\n\n/** How many runs of one workflow may execute at once; 1 for both serialising\n * modes, so the gate holds one number rather than three branches. Null is\n * unbounded, i.e. no gate at all. */\nexport function concurrencyLimit(policy: EffectiveRunPolicy): number | null {\n if (policy.concurrency === \"PARALLEL\") return policy.maxParallelRuns;\n return 1;\n}\n\n/** The trigger status PARK leaves on a supervised trigger's row. Not ENABLED,\n * so the supervisor's due-trigger query does not return it and the schedule\n * stops refiring; a re-publish or re-enable arms it again. The park itself, for\n * every trigger kind, is the store's `workflow_park` row. */\nexport const PARKED_TRIGGER_STATUS = \"PARKED\";\n\n/** The run status a firing skipped by SINGLETON is journaled under, and the\n * one a run that passed `runTimeoutSeconds` ends in. Both are \"this run did\n * not finish and nothing is wrong with the workflow\", which is what the\n * document model's RunStatus.CANCELLED means. */\nexport const CANCELLED_RUN_STATUS = \"CANCELLED\";\n\n/** How long a run may stay suspended; null when the policy sets no bound. */\nexport function maxSuspensionMs(\n runnable: Pick<RunnableDefinition, \"policy\">,\n): number | null {\n const policy = runnable.policy as Record<string, unknown> | undefined | null;\n const days = positive(policy?.maxSuspensionDays);\n return days === null ? null : days * 86_400_000;\n}\n","// Shared shapes for suspended runs: the engine writes them, the HTTP resume\n// route and the subgraph read them.\n\nexport type WaitpointType = \"DELAY\" | \"WEBHOOK\";\n\n// PENDING: waiting. COMPLETED: resume payload stored, run not yet re-entered.\n// CONSUMED: the run resumed. EXPIRED / CANCELLED: the run ended without resuming.\nexport type WaitpointStatus =\n | \"PENDING\"\n | \"COMPLETED\"\n | \"CONSUMED\"\n | \"EXPIRED\"\n | \"CANCELLED\";\n\n// Who may resolve a WEBHOOK waitpoint from the editor, and how it renders there.\nexport type WaitpointKind = \"approval\" | \"webhook\" | \"delay\";\n\nexport type ReasonRequiredOn = \"none\" | \"reject\" | \"both\";\n\n// Set by the core \"Request approval\" block; null for Activepieces pieces.\nexport interface ApprovalRequest {\n title: string;\n // Markdown, rendered once when the run paused.\n body: string | null;\n approveLabel: string;\n rejectLabel: string;\n reasonRequiredOn: ReasonRequiredOn;\n // DIDs allowed to decide; empty means anyone with write access.\n approvers: string[];\n}\n\n// Matches Activepieces' ResumePayload, so a piece reads the same shape\n// whichever route resumed it.\nexport interface WaitpointResumePayload {\n body?: unknown;\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n}\n\n// A resume link's confirm page: only what anyone holding the link may see.\nexport interface WaitpointDescription {\n workflowName: string;\n stepName: string;\n status: WaitpointStatus;\n workflowDescription?: string;\n // The action's display name, e.g. \"Create Approval Links\".\n actionName?: string;\n waitingSince: string;\n expiresAt?: string;\n startedAt?: string;\n triggerName?: string;\n}\n\nexport interface WaitpointRecord {\n id: string;\n runId: string;\n workflowId: string;\n stepId: string;\n stepKey: string;\n // Full step path, e.g. \"loop_1:0/step_2\"; the step id outside loops.\n stepPath: string;\n pieceName: string;\n blockName: string;\n type: WaitpointType;\n kind: WaitpointKind;\n status: WaitpointStatus;\n createdAt: string;\n // DELAY only.\n resumeAt: string | null;\n // From policy.maxSuspensionDays or the block's own expiry.\n expiresAt: string | null;\n resolvedAt: string | null;\n // The resolver's DID when resolved from the editor.\n decidedBy: string | null;\n approval: ApprovalRequest | null;\n}\n\nexport interface ResolveWaitpointInput {\n approved: boolean;\n reason?: string;\n}\n\nexport interface WaitingRunsArgs {\n driveId?: string;\n workflowId?: string;\n first?: number;\n}\n\n// A waiting run ended because its wait expired.\nexport const WAITPOINT_EXPIRED_ERROR_NAME = \"WaitpointExpired\";\n// A step that waited without a live waitpoint of its own.\nexport const WAITPOINT_NOT_LIVE_ERROR_NAME = \"WaitpointNotLive\";\n","// Persisted run journal in the relational \"workflow_runtime\" namespace.\n// Dates are ISO text columns: PGlite parses `timestamp` as local time.\nimport type { BlockIdentity } from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n DOCUMENT_REF_KEY,\n isDocumentRefMarker,\n referenceDocuments,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport {\n containsRedactedMarker,\n redact,\n redactMessage,\n type StepExecutionRecord,\n type WorkflowRunResult,\n} from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport {\n sql,\n type ColumnType,\n type Expression,\n type ExpressionBuilder,\n type Kysely,\n type SqlBool,\n} from \"kysely\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { CORE_PIECE_NAME } from \"../pieces/index.js\";\nimport { PROJECT_SCOPE_KEY } from \"./piece-store-port.js\";\nimport { PARKED_TRIGGER_STATUS } from \"./policy.js\";\nimport {\n WAITPOINT_EXPIRED_ERROR_NAME,\n WAITPOINT_NOT_LIVE_ERROR_NAME,\n} from \"./waitpoint-types.js\";\n\nexport interface RunRow {\n id: string;\n workflow_id: string;\n workflow_name: string;\n workflow_version: number;\n trigger_kind: string;\n trigger_payload: string | null;\n status: string;\n error: string | null;\n // The thrown error's name, e.g. ReactorAccessDeniedError.\n error_name: string | null;\n // When the run was journaled; the listing's stable key, unlike started_at.\n enqueued_at: string;\n // When it began executing; a PENDING run holds its enqueue time here.\n started_at: string;\n ended_at: string | null;\n // Failed run this one resumes; null for first-hand runs.\n rerun_of: string | null;\n // How many warning_notes there are.\n warnings: number;\n // JSON list: fallback piece versions, edges on ports nothing emits.\n warning_notes: string | null;\n}\n\nexport interface StepExecutionRow {\n id: string;\n run_id: string;\n // Execution order; runs journaled before per-step journaling landed hold\n // the definition index. Both are per-run, and nothing compares across runs.\n ordinal: number;\n step_id: string;\n // The step id, or \"<loop>[<i>]/<step>\" for one iteration of a loop body.\n step_path: string;\n step_key: string;\n piece_name: string;\n // The action a step ran, or the trigger a trigger test sampled.\n block_name: string;\n status: string;\n input: string | null;\n output: string | null;\n port: string | null;\n error: string | null;\n error_name: string | null;\n started_at: string | null;\n ended_at: string | null;\n // The piece version that ran and how it matched the pin; null when unresolved.\n piece_version: string | null;\n piece_source: string | null;\n version_match: string | null;\n version_note: string | null;\n // Hash of the step definition it ran from; rerun replays only on a match.\n config_hash: string | null;\n // How many times the block ran, when its retry policy let it run more than\n // once. Null for a single attempt, which is what every row written before\n // retry was enforced holds.\n attempts: number | null;\n}\n\n// A document a run's steps were handed through the reactor port.\nexport interface RunDocumentRow {\n run_id: string;\n document_id: string;\n}\n\nexport interface TriggerStateRow {\n workflow_id: string;\n piece_name: string;\n trigger_name: string;\n config_hash: string;\n // ENABLED | DISABLED | ERROR | PARKED. PARKED is terminal: it is a runtime\n // override of the document's enabled-ness, and only a re-publish that\n // changes the trigger or a disable/re-enable clears it — never a restart.\n status: string;\n // Vestigial: hook state lives in piece_store now, and this is written \"{}\"\n // and never read. Rolling back past the migration re-delivers; see up().\n store_state: string;\n interval_ms: number;\n next_poll_at: string | null;\n last_poll_at: string | null;\n last_error: string | null;\n consecutive_failures: number;\n // Always null and never read: kept so the schema matches main's and a\n // rollback finds the columns it writes. Placement is singleton-lease.ts.\n lease_owner: string | null;\n lease_expires_at: string | null;\n updated_at: string;\n // The piece version the trigger armed with; null for a host-fed trigger.\n piece_version: string | null;\n piece_source: string | null;\n version_match: string | null;\n version_note: string | null;\n // When onRenew is next due; null for a trigger that never renews.\n next_renew_at: string | null;\n // The last onRenew failure and its streak, apart from the poll's.\n renew_error: string | null;\n renew_failures: number;\n}\n\ntype DefaultedTriggerColumn =\n | \"piece_version\"\n | \"piece_source\"\n | \"version_match\"\n | \"version_note\"\n | \"next_renew_at\"\n | \"renew_error\"\n | \"renew_failures\";\n\n// A trigger row as written; the piece and renew columns default to null.\nexport type TriggerStateInput = Omit<TriggerStateRow, DefaultedTriggerColumn> &\n Partial<Pick<TriggerStateRow, DefaultedTriggerColumn>>;\n\n// The trigger a row was written for, and the columns that name it.\nexport function triggerRowBlock(row: TriggerStateRow): BlockIdentity {\n return { pieceName: row.piece_name, kind: \"trigger\", name: row.trigger_name };\n}\n\nexport function triggerBlockColumns(\n block: BlockIdentity,\n): Pick<TriggerStateRow, \"piece_name\" | \"trigger_name\"> {\n return { piece_name: block.pieceName, trigger_name: block.name };\n}\n\nexport interface TriggerDedupeRow {\n workflow_id: string;\n dedupe_key: string;\n run_id: string | null;\n created_at: string;\n // How many times this operation has been DELIVERED. Counted before the run\n // is journaled, so a fire that takes the process down before the write\n // lands is still countable on the next boot — which is what bounds the\n // crash-replay loop (see claimAndEnqueueRun). Null on rows written before\n // the budget existed.\n attempts: number | null;\n}\n\n/**\n * How many times one operation may be re-delivered without ever having\n * journaled a run before it is abandoned.\n *\n * Three, not one: a delivery can fail to journal for reasons that are nothing\n * to do with the fire — a store mid-recreate, a transient database error — and\n * losing a legitimate trigger to the first hiccup would be worse than the loop\n * this bounds. Three deliveries of the same operation that never once reach a\n * run row is not a hiccup.\n */\nexport const FIRE_CRASH_BUDGET = 3;\n\n// A dedupe row's run_id for a fire with no run linked: run unjournaled, run\n// erased, or written before claims. NULL is reserved for \"not yet claimed\".\nexport const FIRED_WITHOUT_RUN_ID = \"fired-without-run\";\n\nconst DEDUPE_CLAIM_MIGRATION = \"trigger_dedupe.run_id-null-is-unclaimed\";\n// step_execution is unique per (run_id, step_path), not per step id.\nconst STEP_PATH_MIGRATION = \"step_execution.step_path\";\n\nexport function abandonedAdmissionError(attempts: number): string {\n return (\n `This run was admitted at ${attempts} boots and the reactor stopped ` +\n \"each time before it started, so it is no longer admitted on boot. Fix \" +\n \"the cause, then rerun it to fire the workflow with the same payload.\"\n );\n}\n\nexport function abandonedFireError(attempts: number): string {\n return (\n `This operation was delivered ${attempts} times and never once got as ` +\n \"far as journaling a run, so the reactor was taken down before the \" +\n \"write landed each time. It is abandoned rather than replayed on every \" +\n \"boot. Fix the cause, then rerun this run to fire the workflow with the \" +\n \"same payload.\"\n );\n}\n\n/** What a fire claim resolved to; see {@link WorkflowRunStore.claimAndEnqueueRun}. */\nexport type FireClaim =\n | { outcome: \"claimed\"; runId: string }\n | { outcome: \"duplicate\" }\n | { outcome: \"abandoned\"; attempts: number };\n\n// One key a piece wrote through `ctx.store`, from an action or a trigger hook\n// alike — the same table for both, as Activepieces has.\n\n// `scope` mirrors their StoreScope: FLOW partitions by workflow, PROJECT by\n// the reactor, which is the only project identity we have. See issue #16.\nexport interface PieceStoreRow {\n scope: string; // FLOW | PROJECT\n scope_key: string;\n key: string;\n value: string; // JSON\n updated_at: string;\n}\n\n// A workflow PARK took out of service, whatever its trigger kind.\nexport interface WorkflowParkRow {\n workflow_id: string;\n // The published version that failed.\n published_version: number;\n reason: string;\n parked_at: string;\n}\n\nexport function workflowParkRow(\n workflowId: string,\n publishedVersion: number,\n reason: string,\n): WorkflowParkRow {\n return {\n workflow_id: workflowId,\n published_version: publishedVersion,\n reason: redactMessage(reason),\n parked_at: new Date().toISOString(),\n };\n}\n\n// What a suspended run executes on resume: written when it first waits.\nexport interface RunPinRow {\n // Our hash of the runnable definition the run started from.\n definition_hash: string | null;\n // The workflow document's global revision, and its state hash, at that read.\n definition_op_index: number | null;\n definition_scope_hash: string | null;\n}\n\ntype NullableColumn<T> = ColumnType<T | null, T | null | undefined, T | null>;\n\nexport interface WaitpointRow {\n id: string;\n run_id: string;\n workflow_id: string;\n step_id: string;\n step_key: string;\n // Full step path; the step id outside loops.\n step_path: string;\n piece_name: string;\n block_name: string;\n type: string; // DELAY | WEBHOOK\n kind: string; // approval | webhook | delay\n status: string; // see WaitpointStatus\n // sha256 hex of the resume URL's token; null for a DELAY.\n token_hash: string | null;\n created_at: string;\n resume_at: string | null;\n expires_at: string | null;\n resolved_at: string | null;\n decided_by: string | null;\n // JSON: ApprovalRequest, WaitpointResumePayload, the sync response.\n approval: string | null;\n resume_payload: string | null;\n response_to_send: string | null;\n}\n\nexport const WAITING_RUN_STATUS = \"WAITING\";\n\nexport interface WorkflowRuntimeDB {\n // admit_attempts: boots that admitted this PENDING run without it starting.\n run: RunRow & {\n admit_attempts: ColumnType<number, number | undefined, number>;\n definition_hash: NullableColumn<string>;\n definition_op_index: NullableColumn<number>;\n definition_scope_hash: NullableColumn<string>;\n // The waitpoint a WAITING run waits on.\n waiting_on: NullableColumn<string>;\n // The run that called this one (Call Flow), and the caller's waitpoint to\n // fail when this run fails; null when the caller asked for neither.\n parent_run_id: NullableColumn<string>;\n parent_waitpoint_id: NullableColumn<string>;\n };\n waitpoint: WaitpointRow;\n step_execution: StepExecutionRow;\n run_document: RunDocumentRow;\n trigger_state: TriggerStateRow;\n trigger_dedupe: TriggerDedupeRow;\n piece_store: PieceStoreRow;\n workflow_park: WorkflowParkRow;\n migration_mark: { name: string; applied_at: string };\n}\n\nconst logger = childLogger([\"workflow\", \"runtime\", \"store\"]);\n\n// Recorded as the run's error when the reactor died mid-run, so the cause is\n// legible in the UI rather than the run just stopping.\nexport const ORPHANED_RUN_ERROR =\n \"Reactor stopped before the run finished; steps completed before then were journaled\";\n\n// A matched fire, durable before the operation batch that matched it returns.\n// Nothing executes it yet: fire() adopts the row and turns it RUNNING.\nexport const PENDING_RUN_STATUS = \"PENDING\";\n\n// A run that has not ended; only these may end, wait or resume.\nconst LIVE_RUN_STATUSES = [PENDING_RUN_STATUS, \"RUNNING\", WAITING_RUN_STATUS];\n// A waitpoint that may still resume its run.\nconst LIVE_WAITPOINT_STATUSES = [\"PENDING\", \"COMPLETED\"];\n\n// A run's live waitpoints, now closed; the ids it closed.\nasync function closeLiveWaitpoints(\n db: Kysely<WorkflowRuntimeDB>,\n runIds: string[],\n status: \"EXPIRED\" | \"CANCELLED\",\n resolvedAt: string,\n keep?: (\n eb: ExpressionBuilder<WorkflowRuntimeDB, \"waitpoint\">,\n ) => Expression<SqlBool>,\n): Promise<string[]> {\n if (runIds.length === 0) return [];\n const closed = await db\n .updateTable(\"waitpoint\")\n .set({ status, resolved_at: resolvedAt })\n .where(\"run_id\", \"in\", runIds)\n .where(\"status\", \"in\", LIVE_WAITPOINT_STATUSES)\n .$if(keep !== undefined, (qb) => qb.where((eb) => eb.not(keep!(eb))))\n .returning(\"id\")\n .execute();\n return closed.map((row) => row.id);\n}\n\n// The step a run waited on, once the run ended without resuming it.\nasync function failWaitingSteps(\n db: Kysely<WorkflowRuntimeDB>,\n runIds: string[],\n reason: string,\n errorName: string | null,\n endedAt: string,\n): Promise<void> {\n if (runIds.length === 0) return;\n await db\n .updateTable(\"step_execution\")\n .set({\n status: \"FAILED\",\n error: redactMessage(reason),\n error_name: errorName,\n ended_at: endedAt,\n })\n .where(\"run_id\", \"in\", runIds)\n .where(\"status\", \"=\", WAITING_RUN_STATUS)\n .execute();\n}\n\n// Why the poller ended a WAITING run on its waitpoint's expiry.\nexport function waitpointExpiryReason(waitpoint: WaitpointRow): string {\n const what = waitpoint.kind === \"approval\" ? \"approval\" : \"wait for a resume\";\n return (\n `The ${what} at step \"${waitpoint.step_key}\" expired at ` +\n `${waitpoint.expires_at} without being resolved`\n );\n}\n\n// A WAITING run whose waitpoint is no longer live and holds no delivered resume.\nfunction strandedWait(\n eb: ExpressionBuilder<WorkflowRuntimeDB, \"run\">,\n): Expression<SqlBool> {\n const live = eb\n .selectFrom(\"waitpoint\")\n .select(\"waitpoint.id\")\n .where(\"waitpoint.status\", \"in\", LIVE_WAITPOINT_STATUSES);\n return eb.and([\n eb.not(eb.exists(completedOf(eb))),\n eb.or([\n eb.and([\n eb(\"run.waiting_on\", \"is not\", null),\n eb.not(eb.exists(live.whereRef(\"waitpoint.id\", \"=\", \"run.waiting_on\"))),\n ]),\n eb.and([\n eb(\"run.waiting_on\", \"is\", null),\n eb.not(eb.exists(live.whereRef(\"waitpoint.run_id\", \"=\", \"run.id\"))),\n ]),\n ]),\n ]);\n}\n\n// A run's COMPLETED waitpoints: a resume was delivered and wins over an end.\nfunction completedOf(eb: ExpressionBuilder<WorkflowRuntimeDB, \"run\">) {\n return eb\n .selectFrom(\"waitpoint\")\n .select(\"waitpoint.id\")\n .whereRef(\"waitpoint.run_id\", \"=\", \"run.id\")\n .where(\"waitpoint.status\", \"=\", \"COMPLETED\");\n}\n\n// Ends a WAITING run CANCELLED: on the expiry of the waitpoint it waits on,\n// or, without one, when its wait is stranded. Undefined when it did not end.\nasync function endWaitingRun(\n db: Kysely<WorkflowRuntimeDB>,\n runId: string,\n end: {\n reason: string;\n errorName: string;\n endedAt: string;\n waitpointId?: string;\n },\n): Promise<EndedWait | undefined> {\n const { waitpointId } = end;\n const rows = await db\n .updateTable(\"run\")\n .set({\n status: \"CANCELLED\",\n error: redactMessage(end.reason),\n error_name: end.errorName,\n ended_at: end.endedAt,\n })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"=\", WAITING_RUN_STATUS)\n .where((eb) =>\n waitpointId === undefined\n ? strandedWait(eb)\n : eb.and([\n eb.or([\n eb(\"run.waiting_on\", \"=\", waitpointId),\n eb(\"run.waiting_on\", \"is\", null),\n ]),\n eb.not(eb.exists(completedOf(eb))),\n ]),\n )\n .returning(\"id\")\n .execute();\n if (rows.length === 0) return undefined;\n await failWaitingSteps(db, [runId], end.reason, end.errorName, end.endedAt);\n const closed = await closeLiveWaitpoints(db, [runId], \"EXPIRED\", end.endedAt);\n return { runId, reason: end.reason, closed };\n}\n\nfunction priorNotes(text: string | null): string[] {\n if (!text) return [];\n try {\n const notes = JSON.parse(text) as unknown;\n return Array.isArray(notes)\n ? notes.filter((note): note is string => typeof note === \"string\")\n : [];\n } catch {\n return [];\n }\n}\n\nexport const STRANDED_WAIT_REASON =\n \"The run waited on a waitpoint that is no longer live\";\n\n// A WAITING run the poller ended, and the waitpoints that closed with it.\nexport interface EndedWait {\n runId: string;\n reason: string;\n closed: string[];\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// Postgres 42P07: the constraint's backing index is already there, which is\n// what a re-run migration looks like. Bad data raises 23505 instead.\nfunction isDuplicateObject(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n return (error as { code?: unknown }).code === \"42P07\";\n}\n\n// A trigger with nothing to renew, and no renewal failure left on it.\nconst RENEW_CLEARED = {\n next_renew_at: null,\n renew_error: null,\n renew_failures: 0,\n} as const;\n\nasync function up(db: IRelationalDb<WorkflowRuntimeDB>): Promise<Set<string>> {\n await db.schema\n .createTable(\"run\")\n .addColumn(\"id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"workflow_id\", \"text\", (col) => col.notNull())\n .addColumn(\"workflow_name\", \"text\", (col) => col.notNull())\n .addColumn(\"workflow_version\", \"integer\", (col) => col.notNull())\n .addColumn(\"trigger_kind\", \"text\", (col) => col.notNull())\n .addColumn(\"trigger_payload\", \"text\")\n .addColumn(\"status\", \"text\", (col) => col.notNull())\n .addColumn(\"error\", \"text\")\n .addColumn(\"started_at\", \"text\", (col) => col.notNull())\n .addColumn(\"ended_at\", \"text\")\n .addColumn(\"rerun_of\", \"text\")\n .ifNotExists()\n .execute();\n\n // Additive migration for journals created before rerun support.\n try {\n await db.schema.alterTable(\"run\").addColumn(\"rerun_of\", \"text\").execute();\n } catch {\n // column already exists\n }\n\n await db.schema\n .createTable(\"trigger_state\")\n .addColumn(\"workflow_id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"piece_name\", \"text\", (col) => col.notNull())\n .addColumn(\"trigger_name\", \"text\", (col) => col.notNull())\n .addColumn(\"config_hash\", \"text\", (col) => col.notNull())\n .addColumn(\"status\", \"text\", (col) => col.notNull())\n .addColumn(\"store_state\", \"text\", (col) => col.notNull())\n .addColumn(\"interval_ms\", \"integer\", (col) => col.notNull())\n .addColumn(\"next_poll_at\", \"text\")\n .addColumn(\"last_poll_at\", \"text\")\n .addColumn(\"last_error\", \"text\")\n .addColumn(\"consecutive_failures\", \"integer\", (col) => col.notNull())\n .addColumn(\"lease_owner\", \"text\")\n .addColumn(\"lease_expires_at\", \"text\")\n .addColumn(\"updated_at\", \"text\", (col) => col.notNull())\n .ifNotExists()\n .execute();\n\n await db.schema\n .createTable(\"trigger_dedupe\")\n .addColumn(\"workflow_id\", \"text\", (col) => col.notNull())\n .addColumn(\"dedupe_key\", \"text\", (col) => col.notNull())\n .addColumn(\"run_id\", \"text\")\n .addColumn(\"created_at\", \"text\", (col) => col.notNull())\n .addPrimaryKeyConstraint(\"trigger_dedupe_pk\", [\"workflow_id\", \"dedupe_key\"])\n .ifNotExists()\n .execute();\n\n await db.schema\n .createTable(\"workflow_park\")\n .addColumn(\"workflow_id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"published_version\", \"integer\", (col) => col.notNull())\n .addColumn(\"reason\", \"text\", (col) => col.notNull())\n .addColumn(\"parked_at\", \"text\", (col) => col.notNull())\n .ifNotExists()\n .execute();\n\n await db.schema\n .createTable(\"step_execution\")\n .addColumn(\"id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"run_id\", \"text\", (col) => col.notNull())\n .addColumn(\"ordinal\", \"integer\", (col) => col.notNull())\n .addColumn(\"step_id\", \"text\", (col) => col.notNull())\n .addColumn(\"step_key\", \"text\", (col) => col.notNull())\n .addColumn(\"piece_name\", \"text\", (col) => col.notNull())\n .addColumn(\"block_name\", \"text\", (col) => col.notNull())\n .addColumn(\"status\", \"text\", (col) => col.notNull())\n .addColumn(\"input\", \"text\")\n .addColumn(\"output\", \"text\")\n .addColumn(\"port\", \"text\")\n .addColumn(\"error\", \"text\")\n .addColumn(\"started_at\", \"text\")\n .addColumn(\"ended_at\", \"text\")\n .addUniqueConstraint(\"step_execution_run_step\", [\"run_id\", \"step_id\"])\n .ifNotExists()\n .execute();\n\n // Additive migration for journals created before step timings.\n for (const column of [\"started_at\", \"ended_at\"]) {\n try {\n await db.schema\n .alterTable(\"step_execution\")\n .addColumn(column, \"text\")\n .execute();\n } catch {\n // column already exists\n }\n }\n\n await db.schema\n .createTable(\"migration_mark\")\n .addColumn(\"name\", \"text\", (col) => col.primaryKey())\n .addColumn(\"applied_at\", \"text\", (col) => col.notNull())\n .ifNotExists()\n .execute();\n const stepPathMigrated = await db\n .selectFrom(\"migration_mark\")\n .select(\"name\")\n .where(\"name\", \"=\", STEP_PATH_MIGRATION)\n .executeTakeFirst();\n\n // Additive migration for journals created before per-step journaling: the\n // upsert in recordStep/finishRun needs this constraint to conflict on.\n // Superseded by (run_id, step_path) below.\n if (!stepPathMigrated) {\n try {\n await db.schema\n .alterTable(\"step_execution\")\n .addUniqueConstraint(\"step_execution_run_step\", [\"run_id\", \"step_id\"])\n .execute();\n } catch (error) {\n // Only \"already there\" is benign. Swallowing anything else would leave\n // every later upsert failing on a missing ON CONFLICT target.\n if (!isDuplicateObject(error)) {\n throw new Error(\n `Could not add the step_execution (run_id, step_id) unique constraint, ` +\n `which per-step journaling upserts against: ${errorMessage(error)}`,\n { cause: error },\n );\n }\n }\n }\n\n // Additive migration for block versioning: what each step and trigger ran.\n for (const table of [\"step_execution\", \"trigger_state\"] as const) {\n for (const column of [\n \"piece_version\",\n \"piece_source\",\n \"version_match\",\n \"version_note\",\n ...(table === \"step_execution\" ? [\"config_hash\"] : []),\n ]) {\n try {\n await db.schema.alterTable(table).addColumn(column, \"text\").execute();\n } catch {\n // column already exists\n }\n }\n }\n // Additive migration for the crash-replay budget: how many times one\n // operation has been delivered. Defaulted, so a row written before this\n // counts as its first delivery rather than as none.\n try {\n await db.schema\n .alterTable(\"trigger_dedupe\")\n .addColumn(\"attempts\", \"integer\", (col) => col.notNull().defaultTo(1))\n .execute();\n } catch {\n // column already exists\n }\n // Before claims, a NULL run_id meant \"fired\"; it now means \"not claimed\".\n // Keyed on its own mark, committed with it, so an interrupted upgrade\n // converts on the next open rather than never.\n if (!stepPathMigrated) await migrateStepPath(db);\n await db.transaction().execute(async (trx) => {\n const done = await trx\n .selectFrom(\"migration_mark\")\n .select(\"name\")\n .where(\"name\", \"=\", DEDUPE_CLAIM_MIGRATION)\n .executeTakeFirst();\n if (done) return;\n await trx\n .updateTable(\"trigger_dedupe\")\n .set({ run_id: FIRED_WITHOUT_RUN_ID })\n .where(\"run_id\", \"is\", null)\n .execute();\n await trx\n .insertInto(\"migration_mark\")\n .values({\n name: DEDUPE_CLAIM_MIGRATION,\n applied_at: new Date().toISOString(),\n })\n .onConflict((oc) => oc.column(\"name\").doNothing())\n .execute();\n });\n\n // Additive migration for enforced step retry: how many times a step ran.\n try {\n await db.schema\n .alterTable(\"step_execution\")\n .addColumn(\"attempts\", \"integer\")\n .execute();\n } catch {\n // column already exists\n }\n try {\n await db.schema\n .alterTable(\"trigger_state\")\n .addColumn(\"next_renew_at\", \"text\")\n .execute();\n } catch {\n // column already exists\n }\n try {\n await db.schema\n .alterTable(\"trigger_state\")\n .addColumn(\"renew_error\", \"text\")\n .execute();\n } catch {\n // column already exists\n }\n try {\n await db.schema\n .alterTable(\"trigger_state\")\n .addColumn(\"renew_failures\", \"integer\", (col) =>\n col.notNull().defaultTo(0),\n )\n .execute();\n } catch {\n // column already exists\n }\n await db.schema\n .createIndex(\"trigger_state_renew_due\")\n .ifNotExists()\n .on(\"trigger_state\")\n .columns([\"status\", \"next_renew_at\"])\n .execute();\n try {\n await db.schema\n .alterTable(\"run\")\n .addColumn(\"warnings\", \"integer\", (col) => col.notNull().defaultTo(0))\n .execute();\n } catch {\n // column already exists\n }\n try {\n await db.schema\n .alterTable(\"run\")\n .addColumn(\"warning_notes\", \"text\")\n .execute();\n } catch {\n // column already exists\n }\n for (const table of [\"run\", \"step_execution\"] as const) {\n try {\n await db.schema\n .alterTable(table)\n .addColumn(\"error_name\", \"text\")\n .execute();\n } catch {\n // column already exists\n }\n }\n\n await db.schema\n .createTable(\"run_document\")\n .addColumn(\"run_id\", \"text\", (col) => col.notNull())\n .addColumn(\"document_id\", \"text\", (col) => col.notNull())\n .addPrimaryKeyConstraint(\"run_document_pk\", [\"run_id\", \"document_id\"])\n .ifNotExists()\n .execute();\n\n await db.schema\n .createTable(\"piece_store\")\n .addColumn(\"scope\", \"text\", (col) => col.notNull())\n .addColumn(\"scope_key\", \"text\", (col) => col.notNull())\n .addColumn(\"key\", \"text\", (col) => col.notNull())\n .addColumn(\"value\", \"text\", (col) => col.notNull())\n .addColumn(\"updated_at\", \"text\", (col) => col.notNull())\n .addPrimaryKeyConstraint(\"piece_store_pk\", [\"scope\", \"scope_key\", \"key\"])\n .ifNotExists()\n .execute();\n\n // Additive migration: rows journaled before enqueued_at list by their start.\n try {\n await db.schema\n .alterTable(\"run\")\n .addColumn(\"enqueued_at\", \"text\")\n .execute();\n } catch {\n // column already exists\n }\n await db\n .updateTable(\"run\")\n .set({ enqueued_at: sql.ref(\"started_at\") })\n .where(\"enqueued_at\", \"is\", null)\n .execute();\n\n // Additive migration: boot admission's crash budget.\n try {\n await db.schema\n .alterTable(\"run\")\n .addColumn(\"admit_attempts\", \"integer\", (col) =>\n col.notNull().defaultTo(0),\n )\n .execute();\n } catch {\n // column already exists\n }\n\n // Run listings, scoped and unscoped, page newest first on (enqueued_at, id).\n await db.schema.dropIndex(\"run_workflow_started\").ifExists().execute();\n await db.schema.dropIndex(\"run_started\").ifExists().execute();\n await db.schema\n .createIndex(\"run_workflow_enqueued\")\n .ifNotExists()\n .on(\"run\")\n .columns([\"workflow_id\", \"enqueued_at desc\", \"id desc\"])\n .execute();\n await db.schema\n .createIndex(\"run_enqueued\")\n .ifNotExists()\n .on(\"run\")\n .columns([\"enqueued_at desc\", \"id desc\"])\n .execute();\n // claimDedupe prunes one workflow's expired keys on every claim.\n await db.schema\n .createIndex(\"trigger_dedupe_workflow_created\")\n .ifNotExists()\n .on(\"trigger_dedupe\")\n .columns([\"workflow_id\", \"created_at\"])\n .execute();\n // The retention sweep: finished runs by age, and dedupe keys past every TTL.\n await db.schema\n .createIndex(\"run_ended\")\n .ifNotExists()\n .on(\"run\")\n .column(\"ended_at\")\n .execute();\n await db.schema\n .createIndex(\"trigger_dedupe_created\")\n .ifNotExists()\n .on(\"trigger_dedupe\")\n .column(\"created_at\")\n .execute();\n // The PENDING sweep, every minute: only the rows still waiting to start.\n await db.schema\n .createIndex(\"run_pending\")\n .ifNotExists()\n .on(\"run\")\n .columns([\"enqueued_at\", \"id\"])\n .where(sql.ref(\"status\"), \"=\", PENDING_RUN_STATUS)\n .execute();\n // The supervisor's due-trigger query on every tick.\n await db.schema\n .createIndex(\"trigger_state_due\")\n .ifNotExists()\n .on(\"trigger_state\")\n .column(\"next_poll_at\")\n .where(sql.ref(\"status\"), \"=\", \"ENABLED\")\n .execute();\n\n // The reactor's webhook service owns tokens now, in its own namespace, so\n // the local table is dead weight wherever the GraphQL ingress once ran.\n\n // Nothing is migrated: those tokens addressed a mutation that no longer\n // exists, so a trigger re-enables onto a freshly minted endpoint.\n try {\n await db.schema.dropTable(\"webhook_endpoint\").ifExists().execute();\n } catch {\n // Never blocks the journal: a leftover table costs nothing.\n }\n\n // Additive migration for suspended runs: the definition a run pins, and\n // the waitpoints it waits on.\n for (const [column, type] of [\n [\"definition_hash\", \"text\"],\n [\"definition_op_index\", \"integer\"],\n [\"definition_scope_hash\", \"text\"],\n [\"waiting_on\", \"text\"],\n [\"parent_run_id\", \"text\"],\n [\"parent_waitpoint_id\", \"text\"],\n ] as const) {\n try {\n await db.schema.alterTable(\"run\").addColumn(column, type).execute();\n } catch {\n // column already exists\n }\n }\n await db.schema\n .createTable(\"waitpoint\")\n .addColumn(\"id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"run_id\", \"text\", (col) => col.notNull())\n .addColumn(\"workflow_id\", \"text\", (col) => col.notNull())\n .addColumn(\"step_id\", \"text\", (col) => col.notNull())\n .addColumn(\"step_key\", \"text\", (col) => col.notNull())\n .addColumn(\"step_path\", \"text\", (col) => col.notNull())\n .addColumn(\"piece_name\", \"text\", (col) => col.notNull())\n .addColumn(\"block_name\", \"text\", (col) => col.notNull())\n .addColumn(\"type\", \"text\", (col) => col.notNull())\n .addColumn(\"kind\", \"text\", (col) => col.notNull())\n .addColumn(\"status\", \"text\", (col) => col.notNull())\n .addColumn(\"token_hash\", \"text\")\n .addColumn(\"created_at\", \"text\", (col) => col.notNull())\n .addColumn(\"resume_at\", \"text\")\n .addColumn(\"expires_at\", \"text\")\n .addColumn(\"resolved_at\", \"text\")\n .addColumn(\"decided_by\", \"text\")\n .addColumn(\"approval\", \"text\")\n .addColumn(\"resume_payload\", \"text\")\n .addColumn(\"response_to_send\", \"text\")\n .ifNotExists()\n .execute();\n await db.schema\n .createIndex(\"waitpoint_token\")\n .ifNotExists()\n .unique()\n .on(\"waitpoint\")\n .column(\"token_hash\")\n .execute();\n // The DELAY poller's due scan, and expiry.\n await db.schema\n .createIndex(\"waitpoint_status_resume\")\n .ifNotExists()\n .on(\"waitpoint\")\n .columns([\"status\", \"resume_at\"])\n .execute();\n // The poller's expiry scan.\n await db.schema\n .createIndex(\"waitpoint_status_expires\")\n .ifNotExists()\n .on(\"waitpoint\")\n .columns([\"status\", \"expires_at\"])\n .execute();\n await db.schema\n .createIndex(\"waitpoint_run\")\n .ifNotExists()\n .on(\"waitpoint\")\n .column(\"run_id\")\n .execute();\n // One live waitpoint per step, as upstream's (flowRunId, stepName).\n const liveStep = db.schema\n .createIndex(\"waitpoint_live_step\")\n .ifNotExists()\n .unique()\n .on(\"waitpoint\")\n .columns([\"run_id\", \"step_path\"])\n .where(sql.ref(\"status\"), \"in\", LIVE_WAITPOINT_STATUSES);\n try {\n await liveStep.execute();\n } catch {\n // Rows from before the index: a step keeps only the one its run waits on.\n await db\n .updateTable(\"waitpoint\")\n .set({ status: \"CANCELLED\", resolved_at: new Date().toISOString() })\n .where(\"status\", \"in\", LIVE_WAITPOINT_STATUSES)\n .where((eb) =>\n eb.and([\n eb.not(\n eb.exists(\n eb\n .selectFrom(\"run\")\n .select(\"run.id\")\n .whereRef(\"run.waiting_on\", \"=\", \"waitpoint.id\"),\n ),\n ),\n eb.exists(\n eb\n .selectFrom(\"waitpoint as sibling\")\n .select(\"sibling.id\")\n .whereRef(\"sibling.run_id\", \"=\", \"waitpoint.run_id\")\n .whereRef(\"sibling.step_path\", \"=\", \"waitpoint.step_path\")\n .whereRef(\"sibling.id\", \"!=\", \"waitpoint.id\")\n .where(\"sibling.status\", \"in\", LIVE_WAITPOINT_STATUSES),\n ),\n ]),\n )\n .execute();\n await liveStep.execute();\n }\n await db.schema\n .createIndex(\"waitpoint_workflow_status\")\n .ifNotExists()\n .on(\"waitpoint\")\n .columns([\"workflow_id\", \"status\"])\n .execute();\n // Waiting-runs listings.\n await db.schema\n .createIndex(\"run_waiting\")\n .ifNotExists()\n .on(\"run\")\n .columns([\"workflow_id\", \"enqueued_at\"])\n .where(sql.ref(\"status\"), \"=\", WAITING_RUN_STATUS)\n .execute();\n\n await migrateBlockType(db, \"trigger_state\", \"trigger_name\");\n await migrateBlockType(db, \"step_execution\", \"block_name\");\n\n return migrateTriggerStoreState(db);\n}\n\n// Journals from before block identities named a block by one packed string,\n// block_type: \"<pkg>[@<version>]#<action>\" or \"<pkg>[@<version>]#trigger:<name>\".\ntype LegacyBlockTable = \"trigger_state\" | \"step_execution\";\n\ninterface LegacyBlockTypeDB {\n trigger_state: LegacyBlockTypeRow;\n step_execution: LegacyBlockTypeRow;\n}\n\ninterface LegacyBlockTypeRow {\n workflow_id: string;\n id: string;\n block_type: string | null;\n piece_name: string | null;\n trigger_name: string | null;\n block_name: string | null;\n}\n\n// The pre-rename core piece.\nconst LEGACY_CORE_PIECE = \"core\";\n\nfunction legacyBlockIdentity(blockType: string): {\n pieceName: string;\n name: string;\n} {\n const separator = blockType.lastIndexOf(\"#\");\n if (separator <= 0) return { pieceName: blockType, name: \"\" };\n const spec = blockType.slice(0, separator);\n const fragment = blockType.slice(separator + 1);\n const name = fragment.startsWith(\"trigger:\")\n ? fragment.slice(\"trigger:\".length)\n : fragment;\n const versionAt = spec.indexOf(\"@\", 1);\n const pieceName = versionAt > 0 ? spec.slice(0, versionAt) : spec;\n return {\n pieceName: pieceName === LEGACY_CORE_PIECE ? CORE_PIECE_NAME : pieceName,\n name,\n };\n}\n\n// Iteration steps get their own path; others keep their id. Idempotent, as two\n// runtimes may open one journal at once; the mark lands last.\nasync function migrateStepPath(\n db: IRelationalDb<WorkflowRuntimeDB>,\n): Promise<void> {\n await db.schema\n .alterTable(\"step_execution\")\n .addColumn(\"step_path\", \"text\", (col) => col.ifNotExists())\n .execute();\n await db\n .updateTable(\"step_execution\")\n .set({ step_path: sql.ref(\"step_id\") })\n .where(\"step_path\", \"is\", null)\n .execute();\n await db.schema\n .alterTable(\"step_execution\")\n .alterColumn(\"step_path\", (col) => col.setNotNull())\n .execute();\n try {\n await db.schema\n .alterTable(\"step_execution\")\n .addUniqueConstraint(\"step_execution_run_path\", [\"run_id\", \"step_path\"])\n .execute();\n } catch (error) {\n if (!isDuplicateObject(error)) throw error;\n }\n await db.schema\n .alterTable(\"step_execution\")\n .dropConstraint(\"step_execution_run_step\")\n .ifExists()\n .execute();\n await db\n .insertInto(\"migration_mark\")\n .values({\n name: STEP_PATH_MIGRATION,\n applied_at: new Date().toISOString(),\n })\n .onConflict((oc) => oc.column(\"name\").doNothing())\n .execute();\n}\n\n// Adds the identity columns to a table created with block_type and fills them\n// from it. block_type stays, nullable, since nothing writes it any more.\nasync function migrateBlockType(\n db: IRelationalDb<WorkflowRuntimeDB>,\n table: LegacyBlockTable,\n nameColumn: \"trigger_name\" | \"block_name\",\n): Promise<void> {\n const legacy = db as unknown as IRelationalDb<LegacyBlockTypeDB>;\n try {\n await legacy.schema\n .alterTable(table)\n .alterColumn(\"block_type\", (col) => col.dropNotNull())\n .execute();\n } catch {\n // no block_type: created with the identity columns\n return;\n }\n for (const column of [\"piece_name\", nameColumn]) {\n try {\n await legacy.schema.alterTable(table).addColumn(column, \"text\").execute();\n } catch {\n // column already exists\n }\n }\n const key = table === \"trigger_state\" ? \"workflow_id\" : \"id\";\n const rows = await legacy\n .selectFrom(table)\n .select([key, \"block_type\"])\n .where((eb) =>\n eb.or([eb(\"piece_name\", \"is\", null), eb(nameColumn, \"is\", null)]),\n )\n .execute();\n for (const row of rows) {\n const { pieceName, name } = legacyBlockIdentity(row.block_type ?? \"\");\n await legacy\n .updateTable(table)\n .set({ piece_name: pieceName, [nameColumn]: name })\n .where(key, \"=\", row[key])\n .execute();\n }\n}\n\n// MIGRATION: trigger store state used to round-trip through\n// trigger_state.store_state as one JSON blob; it lives in piece_store now.\n\n// Stranding it would strand a WEBHOOK trigger's registered endpoint id, and\n// then onDisable can never delete that endpoint: it leaks at the provider.\n\n// ONE-WAY DOOR: the blob is blanked once moved and never written again, so a\n// reactor rolled back past this point reads an empty cursor and re-delivers.\ninterface LegacyStoreStateRow {\n workflow_id: string;\n store_state: string;\n}\n\ninterface LegacyEntry {\n scope: \"FLOW\" | \"PROJECT\";\n scopeKey: string;\n key: string;\n value: unknown;\n}\n\ninterface PendingMigration {\n workflowId: string;\n entries: LegacyEntry[];\n}\n\n// Returns the workflows whose blob did not move: nothing reads store_state any\n// more, so their hooks would run against an empty piece_store.\nasync function migrateTriggerStoreState(\n db: IRelationalDb<WorkflowRuntimeDB>,\n): Promise<Set<string>> {\n const unmigrated = new Set<string>();\n let rows: LegacyStoreStateRow[];\n try {\n // Oldest first, so a later row's project key overwrites an earlier one;\n // workflow_id settles a tie rather than leaving it to row order.\n rows = await db\n .selectFrom(\"trigger_state\")\n .select([\"workflow_id\", \"store_state\"])\n .orderBy(\"updated_at\", \"asc\")\n .orderBy(\"workflow_id\", \"asc\")\n .execute();\n } catch (error) {\n // Never blocks the journal: a store that fails to open is returned as\n // `undefined` forever, which silently stops every trigger in the process.\n logger.error(\"Could not read trigger_state to migrate it: @error\", error);\n return unmigrated;\n }\n const pending: PendingMigration[] = [];\n for (const row of rows) {\n const entries = parseLegacyBlob(row, unmigrated);\n if (entries) pending.push({ workflowId: row.workflow_id, entries });\n }\n const projectWinner = resolveProjectCollisions(pending);\n for (const row of pending) {\n try {\n await migrateOneRow(db, row, projectWinner);\n } catch (error) {\n // Per row, for the same reason. The blob is only blanked on success, so\n // a row that failed here is retried on the next startup.\n unmigrated.add(row.workflowId);\n logger.error(\n `Could not migrate trigger store state for ${row.workflowId}`,\n error,\n );\n }\n }\n return unmigrated;\n}\n\n// A blob that cannot be read is left exactly as it is, and its workflow is\n// reported unmigrated: guessing at it would lose the state for good.\nfunction parseLegacyBlob(\n row: LegacyStoreStateRow,\n unmigrated: Set<string>,\n): LegacyEntry[] | null {\n if (!row.store_state || row.store_state === \"{}\") return null;\n let state: unknown;\n try {\n state = JSON.parse(row.store_state);\n } catch {\n logger.warn(\n `Leaving unparseable store_state for ${row.workflow_id} in place`,\n );\n unmigrated.add(row.workflow_id);\n return null;\n }\n if (typeof state !== \"object\" || state === null) {\n unmigrated.add(row.workflow_id);\n return null;\n }\n const entries: LegacyEntry[] = [];\n for (const [key, value] of Object.entries(state)) {\n // Only the unambiguous shape a test hook wrote is dropped. A bare \"test…\"\n // key may be a piece's own (\"testimonials\"), so it migrates instead.\n if (/^testflow_.+\\//.test(key)) continue;\n const flow = /^flow_(.+?)\\/(.+)$/.exec(key);\n if (flow) {\n entries.push({\n scope: \"FLOW\",\n scopeKey: flow[1],\n key: flow[2],\n value,\n });\n continue;\n }\n if (key.startsWith(\"test\")) {\n logger.info(\n `Migrating \"${key}\" for ${row.workflow_id} as a project key; it may be a test leftover`,\n );\n }\n entries.push({\n scope: \"PROJECT\",\n scopeKey: PROJECT_SCOPE_KEY,\n key,\n value,\n });\n }\n return entries;\n}\n\n// A bare project key lived inside each workflow's own row, so two workflows\n// can hold different values for one key and only one can survive the move.\n\n// Last write wins, over the whole set rather than whichever row the database\n// returned first, and every discarded value is named so an operator sees it.\nfunction resolveProjectCollisions(\n pending: PendingMigration[],\n): Map<string, string> {\n const winner = new Map<string, string>();\n const contested = new Map<string, string[]>();\n for (const row of pending) {\n for (const entry of row.entries) {\n if (entry.scope !== \"PROJECT\") continue;\n const previous = winner.get(entry.key);\n if (previous !== undefined) {\n const seen = contested.get(entry.key) ?? [previous];\n contested.set(entry.key, [...seen, row.workflowId]);\n }\n winner.set(entry.key, row.workflowId);\n }\n }\n for (const [key, workflows] of contested) {\n logger.warn(\n `Project store key \"@key\" was written by ${workflows.join(\", \")}; keeping the value last updated, from ${winner.get(key)}, and discarding the rest`,\n key,\n );\n }\n return winner;\n}\n\nasync function migrateOneRow(\n db: IRelationalDb<WorkflowRuntimeDB>,\n row: PendingMigration,\n projectWinner: Map<string, string>,\n): Promise<void> {\n for (const entry of row.entries) {\n // Another workflow updated its row later, so its copy of this project key\n // is the surviving one.\n if (\n entry.scope === \"PROJECT\" &&\n projectWinner.get(entry.key) !== row.workflowId\n ) {\n continue;\n }\n await insertPieceStoreIfAbsent(\n db,\n entry.scope,\n entry.scopeKey,\n entry.key,\n entry.value,\n );\n }\n // Blanked once moved, so a later startup cannot replay a stale blob over\n // what the trigger has written since.\n await db\n .updateTable(\"trigger_state\")\n .set({ store_state: \"{}\" })\n .where(\"workflow_id\", \"=\", row.workflowId)\n .execute();\n}\n\n// A key the piece has already rewritten under the new layout wins: the blob is\n// the older copy by construction.\nasync function insertPieceStoreIfAbsent(\n db: IRelationalDb<WorkflowRuntimeDB>,\n scope: string,\n scopeKey: string,\n key: string,\n value: unknown,\n): Promise<void> {\n const encoded = jsonOrNull(value);\n if (encoded === null) return;\n // The blob had no ceilings; piece_store inherits the action ones. A value\n // over them still migrates, but every later put on it will throw.\n warnIfOverPieceStoreLimits(scope, scopeKey, key, encoded);\n const existing = await db\n .selectFrom(\"piece_store\")\n .select(\"key\")\n .where(\"scope\", \"=\", scope)\n .where(\"scope_key\", \"=\", scopeKey)\n .where(\"key\", \"=\", key)\n .executeTakeFirst();\n if (existing) return;\n // doNothing, not a bare insert: two reactors starting against one journal\n // both see no row, and a PK violation here would reject up() and the store.\n await db\n .insertInto(\"piece_store\")\n .values({\n scope,\n scope_key: scopeKey,\n key,\n value: encoded,\n updated_at: new Date().toISOString(),\n })\n .onConflict((oc) => oc.columns([\"scope\", \"scope_key\", \"key\"]).doNothing())\n .execute();\n}\n\n// Loud rather than fatal: a trigger whose accumulated state is already over\n// the ceiling would otherwise start failing on its next put with no clue why.\nfunction warnIfOverPieceStoreLimits(\n scope: string,\n scopeKey: string,\n key: string,\n encoded: string,\n): void {\n const at = `${scope}/${scopeKey}/${key}`;\n if (key.length > PIECE_STORE_MAX_KEY_LENGTH) {\n logger.warn(\n `Migrated store key ${at} is ${key.length} chars, over the ${PIECE_STORE_MAX_KEY_LENGTH} limit; writes to it will fail`,\n );\n }\n const size = Buffer.byteLength(encoded, \"utf8\");\n if (size > PIECE_STORE_MAX_VALUE_BYTES) {\n logger.warn(\n `Migrated store value ${at} is ${size} bytes, over the ${PIECE_STORE_MAX_VALUE_BYTES} limit; writes to it will fail`,\n );\n }\n}\n\n// Their own ceilings (STORE_KEY_MAX_LENGTH, STORE_VALUE_MAX_SIZE), so a piece\n// that behaves on Activepieces behaves here. Enforced on the host, not the child.\nexport const PIECE_STORE_MAX_KEY_LENGTH = 128;\nexport const PIECE_STORE_MAX_VALUE_BYTES = 512 * 1024;\n\nexport class PieceStoreLimitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PieceStoreLimitError\";\n }\n}\n\nfunction assertPieceStoreEntry(key: string, value: unknown): void {\n if (key.length === 0 || key.length > PIECE_STORE_MAX_KEY_LENGTH) {\n throw new PieceStoreLimitError(\n `Store key must be 1-${PIECE_STORE_MAX_KEY_LENGTH} characters, got ${key.length}`,\n );\n }\n // stringify yields undefined for functions/symbols despite its typing.\n const encoded = JSON.stringify(value) as string | undefined;\n if (encoded === undefined) {\n throw new PieceStoreLimitError(`Store value for \"${key}\" is not JSON`);\n }\n const size = Buffer.byteLength(encoded, \"utf8\");\n if (size > PIECE_STORE_MAX_VALUE_BYTES) {\n throw new PieceStoreLimitError(\n `Store value for \"${key}\" is ${size} bytes, over the ${PIECE_STORE_MAX_VALUE_BYTES} byte limit`,\n );\n }\n}\n\n// The journal's ceiling per payload: a step's input and output, and a run's\n// trigger payload, are each capped at serialization time. Over the cap, the\n// row keeps a marker — the original byte count and a prefix of the\n// serialized JSON — rather than refusing the write, because the journal is\n// diagnostic and a refused write loses the evidence. Half the piece-store ceiling: the piece store holds working state\n// a trigger needs back intact, while the journal only needs enough of a\n// payload to diagnose a run (the case that forced the cap was document-get\n// journaling whole multi-megabyte documents, where the first kilobytes carry\n// everything a reader uses).\n//\n// This bounds row width only. Row COUNT is bounded by the retention sweep\n// (run-retention.ts), which defaults to 30 days — change either bound with the\n// other in view.\nexport const STEP_PAYLOAD_MAX_BYTES = 256 * 1024;\n\n// What survives of an over-cap payload: the head of its serialized JSON.\nexport const STEP_PAYLOAD_PREFIX_CHARS = 32 * 1024;\n\n/**\n * The reserved key a truncation marker is recognised by, and its value.\n *\n * A marker has to be distinguishable from a legitimate payload that merely\n * LOOKS like one, because a run whose output is mistaken for a marker is a\n * step that silently re-executes on rerun. The original predicate duck-typed\n * `{truncated: true, bytes: number, prefix: string}` (review backlog item 15),\n * which any piece returning a truncation report of its own would match — and\n * \"did we truncate this?\" is exactly the shape such a report takes.\n *\n * So the marker is keyed on a namespaced sentinel whose VALUE is a versioned\n * magic string. A piece would have to emit that exact pair to collide, which\n * is not something a payload produces by accident.\n */\nexport const TRUNCATED_PAYLOAD_KEY =\n \"@powerhousedao/reactor-workflow:runJournal\";\nexport const TRUNCATED_PAYLOAD_SENTINEL = \"truncated-payload/v1\";\n\n// The shape journaled in place of an over-cap payload.\nexport interface TruncatedStepPayload {\n [TRUNCATED_PAYLOAD_KEY]: typeof TRUNCATED_PAYLOAD_SENTINEL;\n // Byte length of the serialized payload the prefix was cut from.\n bytes: number;\n prefix: string;\n // The payload's own top-level ids, carried past the cap: erasure\n // (journaledPayloadNames) and run serving (triggerDocumentIds) both read\n // them off the journaled row, and would otherwise lose the row the moment\n // it is capped. Ids, not bulk.\n documentId?: string;\n driveId?: string;\n}\n\n// Every key a legacy marker could carry, and no others.\nconst LEGACY_MARKER_KEYS: readonly string[] = [\n \"truncated\",\n \"bytes\",\n \"prefix\",\n \"documentId\",\n \"driveId\",\n];\n\n/**\n * True for a journaled value this store truncated.\n *\n * Two shapes are accepted and only one is written. New rows carry the reserved\n * key, which a payload cannot produce by accident. Rows journaled before it\n * carry the old `{truncated: true, bytes, prefix}`, and those still have to be\n * recognised: reading one as data would re-run the side-effectful step that\n * produced it, which is the whole bug.\n *\n * So the legacy branch is matched by its EXACT key set, not by duck-typing.\n * `{truncated, bytes, prefix, source}` — a truncation report a piece might\n * legitimately return, and the collision the review found — is no longer a\n * marker. A payload whose keys are exactly the legacy marker's is still\n * ambiguous, and nothing can resolve that for a row already written; the\n * window is as narrow as the stored data allows.\n */\nfunction unreplayablePayload(\n payload: unknown,\n): \"truncated\" | \"redacted\" | undefined {\n if (isTruncatedStepPayload(payload)) return \"truncated\";\n if (containsRedactedMarker(payload)) return \"redacted\";\n return undefined;\n}\n\nexport function isTruncatedStepPayload(\n value: unknown,\n): value is TruncatedStepPayload {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const record = value as Record<string, unknown>;\n if (record[TRUNCATED_PAYLOAD_KEY] === TRUNCATED_PAYLOAD_SENTINEL) return true;\n // LEGACY, read-only.\n return (\n record.truncated === true &&\n typeof record.bytes === \"number\" &&\n typeof record.prefix === \"string\" &&\n Object.keys(record).every((key) => LEGACY_MARKER_KEYS.includes(key))\n );\n}\n\n// The two top-level ids a journaled payload is matched by after the fact.\n// Top level only, and strings only: a list sample carries its ids per item,\n// and collecting those would grow with the payload — the one thing the cap\n// exists to prevent (store.erase-runs.test.ts pins that accepted gap).\nfunction topLevelDocumentIds(\n value: unknown,\n): Pick<TruncatedStepPayload, \"documentId\" | \"driveId\"> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n const { documentId, driveId } = value as Record<string, unknown>;\n return {\n ...(typeof documentId === \"string\" ? { documentId } : {}),\n ...(typeof driveId === \"string\" ? { driveId } : {}),\n };\n}\n\n// Takes the already-redacted payload value, not its JSON: the marker keeps\n// the value's top-level document ids, which a serialized string cannot give\n// back without a second parse.\nfunction cappedPayload(value: unknown): string | null {\n const json = jsonOrNull(value);\n if (json === null) return null;\n const bytes = Buffer.byteLength(json, \"utf8\");\n if (bytes <= STEP_PAYLOAD_MAX_BYTES) return json;\n let prefix = json.slice(0, STEP_PAYLOAD_PREFIX_CHARS);\n // Never cut through a surrogate pair; the prefix must stay serializable.\n const last = prefix.charCodeAt(prefix.length - 1);\n if (last >= 0xd800 && last <= 0xdbff) prefix = prefix.slice(0, -1);\n const marker: TruncatedStepPayload = {\n [TRUNCATED_PAYLOAD_KEY]: TRUNCATED_PAYLOAD_SENTINEL,\n bytes,\n prefix,\n ...topLevelDocumentIds(value),\n };\n return JSON.stringify(marker);\n}\n\n// Every column of a step_execution row but its surrogate id, shared by the\n// per-step write and the closing sweep so the two cannot drift.\n\n// It is also the last gate before a credential becomes a database row, which\n// is why the redaction sits here rather than at each writer.\n\n// Only the key-based pass runs here; the run's own secret values are the\n// engine's to match, and the store never sees them.\n\n// A document in an output is journaled as a reference marker, before\n// redaction and the cap: whoever needs its state reads the document.\n// What the closing sweep compares, kept instead of the row's payloads.\nfunction rowHash(values: ReturnType<typeof stepValues>): string {\n return createHash(\"sha1\").update(JSON.stringify(values)).digest(\"base64\");\n}\n\nfunction stepValues(runId: string, ordinal: number, step: StepExecutionRecord) {\n return {\n run_id: runId,\n ordinal,\n step_id: step.stepId,\n step_path: step.path ?? step.stepId,\n step_key: step.key,\n piece_name: step.pieceName,\n block_name: step.blockName,\n status: step.status,\n input: cappedPayload(redact(step.input)),\n // `journaledOutput` wins where it is set: the record has no output to give\n // a caller, but the row still has to carry what the journal holds — the\n // truncation marker of a REPLAYED step, so a second rerun can read it.\n output: cappedPayload(\n redact(\n referenceDocuments(\n step.journaledOutput !== undefined\n ? step.journaledOutput\n : step.output,\n ),\n ),\n ),\n port: step.port ?? null,\n error: step.error ? redactMessage(step.error) : null,\n error_name: step.errorName ?? null,\n started_at: step.startedAt ?? null,\n ended_at: step.endedAt ?? null,\n piece_version: step.piece?.version ?? null,\n piece_source: step.piece?.source ?? null,\n version_match: step.piece?.match ?? null,\n version_note: step.piece?.note ?? null,\n config_hash: step.configHash ?? null,\n attempts: step.attempts ?? null,\n };\n}\n\n// What a run should not be read as a plain success for.\nexport function runWarningNotes(result: WorkflowRunResult): string[] {\n const fallbacks = result.steps\n .filter((step) => step.piece?.match === \"fallback\")\n .map(\n (step) =>\n `Step \"${step.key}\" ran ${step.piece!.version}, a fallback for the version it pins`,\n );\n return [...fallbacks, ...(result.warnings ?? [])];\n}\n\nexport function runWarnings(result: WorkflowRunResult): number {\n return runWarningNotes(result).length;\n}\n\nfunction jsonOrNull(value: unknown): string | null {\n if (value === undefined) return null;\n try {\n // stringify yields undefined for functions/symbols despite its typing.\n const text = JSON.stringify(value) as string | undefined;\n return text ?? null;\n } catch {\n return null;\n }\n}\n\n// The documents a trigger names: the one whose operation fired, and its drive.\nexport function triggerDocumentIds(payload: unknown): string[] {\n if (payload === null || typeof payload !== \"object\") return [];\n const record = payload as Record<string, unknown>;\n return [\n ...new Set(\n [record.documentId, record.driveId].filter(\n (id): id is string => typeof id === \"string\" && id !== \"\",\n ),\n ),\n ];\n}\n\nexport function journaledTriggerDocumentIds(payload: string | null): string[] {\n if (payload === null) return [];\n try {\n return triggerDocumentIds(JSON.parse(payload));\n } catch {\n return [];\n }\n}\n\n// The trigger kind a design-time test journals its one-step run under.\nexport const TEST_TRIGGER_KIND = \"test\";\n\n// A payload, or a sample's list of them, naming an id where erasure looks.\nfunction journaledPayloadNames(\n json: string | null,\n ids: readonly string[],\n): boolean {\n if (json === null) return false;\n let value: unknown;\n try {\n value = JSON.parse(json);\n } catch {\n return false;\n }\n return (Array.isArray(value) ? value : [value]).some((item) => {\n if (item === null || typeof item !== \"object\") return false;\n const record = item as Record<string, unknown>;\n const referenced = isDocumentRefMarker(record)\n ? record[DOCUMENT_REF_KEY].documentId\n : undefined;\n return [\n record.documentId,\n record.driveId,\n record.parentId,\n referenced,\n ].some((id) => typeof id === \"string\" && ids.includes(id));\n });\n}\n\n// Runs erased mid-flight; process-wide, as a run keeps its store across reloads.\nconst erasedRuns = new Set<string>();\n\n// What eraseRunsForDocuments removed, by table.\nexport interface ErasedRuns {\n runs: number;\n steps: number;\n documents: number;\n dedupeKeysUnlinked: number;\n}\n\nexport interface AdmittedRun {\n runId: string;\n workflowId: string;\n triggerKind: string;\n triggerPayload: unknown;\n}\n\nexport interface PollSuccess {\n workflowId: string;\n storeState: string;\n nextPollAtIso: string | null;\n}\n\nasync function pollSucceededIn(\n db: Kysely<WorkflowRuntimeDB>,\n workflowId: string,\n storeState: string,\n nowIso: string,\n nextPollAtIso: string | null,\n): Promise<void> {\n await db\n .updateTable(\"trigger_state\")\n .set({\n store_state: storeState,\n last_poll_at: nowIso,\n next_poll_at: nextPollAtIso,\n last_error: null,\n consecutive_failures: 0,\n updated_at: nowIso,\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n}\n\n// The insert's own conflict outcome is the claim; a prior select can't be trusted.\nasync function claimDedupeIn(\n db: Kysely<WorkflowRuntimeDB>,\n workflowId: string,\n dedupeKey: string,\n ttlMs: number,\n nowIso: string,\n runId = FIRED_WITHOUT_RUN_ID,\n): Promise<boolean> {\n const cutoff = new Date(Date.parse(nowIso) - ttlMs).toISOString();\n await db\n .deleteFrom(\"trigger_dedupe\")\n .where(\"workflow_id\", \"=\", workflowId)\n .where(\"created_at\", \"<\", cutoff)\n .execute();\n const inserted = await db\n .insertInto(\"trigger_dedupe\")\n .values({\n workflow_id: workflowId,\n dedupe_key: dedupeKey,\n run_id: runId,\n created_at: nowIso,\n attempts: 1,\n })\n // A row left unclaimed by a claim whose run never landed is taken too.\n .onConflict((oc) =>\n oc\n .columns([\"workflow_id\", \"dedupe_key\"])\n .doUpdateSet({ run_id: runId })\n .where(\"trigger_dedupe.run_id\", \"is\", null),\n )\n .returning(\"dedupe_key\")\n .executeTakeFirst();\n return inserted !== undefined;\n}\n\nconst STEP_COLUMNS_WITHOUT_DATA = [\n \"id\",\n \"run_id\",\n \"ordinal\",\n \"step_id\",\n \"step_path\",\n \"step_key\",\n \"piece_name\",\n \"block_name\",\n \"status\",\n \"port\",\n \"error\",\n \"error_name\",\n \"started_at\",\n \"ended_at\",\n \"piece_version\",\n \"piece_source\",\n \"version_match\",\n \"version_note\",\n \"config_hash\",\n \"attempts\",\n] as const satisfies readonly Exclude<\n keyof StepExecutionRow,\n \"input\" | \"output\"\n>[];\n\n// A run's position in the newest-first listing; fixed once journaled.\nexport interface RunKey {\n enqueuedAt: string;\n id: string;\n}\n\nexport interface ListRunsOptions {\n after?: RunKey;\n excludeTriggerKinds?: string[];\n}\n\nexport const MAX_LIST_RUNS = 100;\n\nconst PRUNE_BATCH_SIZE = 500;\n\nexport interface EnqueueRunOptions {\n workflowId: string;\n triggerKind: string;\n triggerPayload?: unknown;\n parent?: RunParent;\n}\n\n// A sub-flow's caller: its run, and the waitpoint failed when this run fails.\nexport interface RunParent {\n runId: string;\n waitpointId: string | null;\n}\n\nexport interface StartRunOptions {\n workflowId: string;\n workflowName: string;\n workflowVersion: number;\n triggerKind: string;\n triggerPayload?: unknown;\n rerunOf?: string;\n}\n\n// Runs this process started and has not closed out. A run outlives its store:\n// configure() opens a new one on each hot reload, mid-flight runs and all.\n\nexport class WorkflowRunStore {\n // Runtime-local on purpose. A second reactor over the same journal would\n // need a lease, and one that can block startup costs more than a sweep.\n private readonly runsInFlight = new Set<string>();\n // Runs the last recoverOrphanedRuns failed, for the host to close out.\n orphanedRunIds: string[] = [];\n // Rows this process wrote for each run it began, so finishRun can skip a\n // closing sweep that would rewrite them unchanged.\n private readonly journaledSteps = new Map<\n string,\n Map<string, { ordinal: number; hash: string }>\n >();\n // Runs whose current leg made a waitpoint, and legs this process resumed:\n // only their close-out reads prior notes and closes waitpoints.\n private readonly pausingRuns = new Set<string>();\n private readonly resumedLegs = new Set<string>();\n\n private constructor(\n private readonly db: IRelationalDb<WorkflowRuntimeDB>,\n private readonly unmigrated: Set<string>,\n ) {}\n\n static async create(relationalDb: IRelationalDb): Promise<WorkflowRunStore> {\n const db = (await relationalDb.createNamespace(\n \"workflow_runtime\",\n )) as IRelationalDb<WorkflowRuntimeDB>;\n const unmigrated = await up(db);\n const store = new WorkflowRunStore(db, unmigrated);\n await store.recoverOrphanedRuns();\n return store;\n }\n\n // Its legacy store_state never reached piece_store, so the hook would run\n // against an empty one, unable to name the endpoint onDisable has to free.\n hasUnmigratedTriggerState(workflowId: string): boolean {\n return this.unmigrated.has(workflowId);\n }\n\n // The trigger no longer depends on the blob — it was re-enabled from\n // scratch — so it may be scheduled again without waiting for a restart.\n clearUnmigratedTriggerState(workflowId: string): void {\n this.unmigrated.delete(workflowId);\n }\n\n // A run still RUNNING when the journal opens, and not one of ours, belongs\n // to a process that is gone: close it out as FAILED.\n\n // Without this the steps journaled before the crash are unreachable, since\n // rerun() only accepts a FAILED run.\n async recoverOrphanedRuns(): Promise<number> {\n const endedAt = new Date().toISOString();\n const inFlight = [...this.runsInFlight];\n const recovered = await this.db.transaction().execute(async (trx) => {\n let query = trx\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: ORPHANED_RUN_ERROR,\n ended_at: endedAt,\n })\n .where(\"status\", \"=\", \"RUNNING\");\n // Failing a run this process is still executing would hand rerun() a\n // live run, and its side effects would happen twice.\n if (inFlight.length > 0) {\n query = query.where(\"id\", \"not in\", inFlight);\n }\n // Counted off RETURNING: the knex-backed dialect reports no row count.\n const ids = (await query.returning(\"id\").execute()).map((row) => row.id);\n // A run that crashed after it resumed still has its waiting step.\n await failWaitingSteps(trx, ids, ORPHANED_RUN_ERROR, null, endedAt);\n await closeLiveWaitpoints(trx, ids, \"CANCELLED\", endedAt);\n return ids;\n });\n this.orphanedRunIds = recovered;\n if (recovered.length > 0) {\n logger.warn(\n `Recovered ${recovered.length} workflow run(s) left RUNNING by a stopped reactor; they are now FAILED and rerunnable`,\n );\n }\n return recovered.length;\n }\n\n // PENDING runs a stopped process journaled, oldest first, each counted as\n // one more admission. The host starts them; RUNNING ones are failed instead.\n\n // Past the crash budget a run is failed: a fire that takes the reactor down\n // before it starts is not replayed on every boot.\n async admitAbandonedRuns(\n options: { enqueuedBefore?: Date } = {},\n ): Promise<AdmittedRun[]> {\n const admitted = await this.db.transaction().execute(async (trx) => {\n let query = trx\n .selectFrom(\"run\")\n .select([\n \"id\",\n \"workflow_id\",\n \"trigger_kind\",\n \"trigger_payload\",\n \"admit_attempts\",\n ])\n .where(\"status\", \"=\", PENDING_RUN_STATUS)\n .orderBy(\"enqueued_at\", \"asc\")\n .orderBy(\"id\", \"asc\");\n if (this.runsInFlight.size > 0) {\n query = query.where(\"id\", \"not in\", [...this.runsInFlight]);\n }\n if (options.enqueuedBefore) {\n query = query.where(\n \"enqueued_at\",\n \"<\",\n options.enqueuedBefore.toISOString(),\n );\n }\n const rows = await query.execute();\n const runs: AdmittedRun[] = [];\n const now = new Date().toISOString();\n for (const row of rows) {\n if (row.admit_attempts >= FIRE_CRASH_BUDGET) {\n await trx\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: abandonedAdmissionError(row.admit_attempts),\n ended_at: now,\n })\n .where(\"id\", \"=\", row.id)\n .execute();\n continue;\n }\n const triggerPayload =\n row.trigger_payload === null\n ? undefined\n : (JSON.parse(row.trigger_payload) as unknown);\n // The journal keeps a capped, redacted copy: running it would feed the\n // workflow markers. Failed as rerun() refuses the same payloads.\n const unreplayable = unreplayablePayload(triggerPayload);\n if (unreplayable) {\n await trx\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: `The trigger payload was ${unreplayable} by the journal and cannot be run after a restart; fire the workflow again`,\n ended_at: now,\n })\n .where(\"id\", \"=\", row.id)\n .execute();\n continue;\n }\n await trx\n .updateTable(\"run\")\n .set({ admit_attempts: row.admit_attempts + 1 })\n .where(\"id\", \"=\", row.id)\n .execute();\n runs.push({\n runId: row.id,\n workflowId: row.workflow_id,\n triggerKind: row.trigger_kind,\n triggerPayload,\n });\n }\n return runs;\n });\n for (const run of admitted) this.runsInFlight.add(run.runId);\n if (admitted.length > 0) {\n logger.info(\n `Admitting ${admitted.length} workflow run(s) journaled by a stopped reactor`,\n );\n }\n return admitted;\n }\n\n // A graceful shutdown refused this PENDING run before it started: the boot\n // that admitted it did not crash, so its attempt is given back.\n async releaseAdmission(runId: string): Promise<void> {\n this.runsInFlight.delete(runId);\n await this.db\n .updateTable(\"run\")\n .set({ admit_attempts: sql<number>`greatest(admit_attempts - 1, 0)` })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"=\", PENDING_RUN_STATUS)\n .execute();\n }\n\n /**\n * Closes a run out as CANCELLED, with the reason as its error.\n *\n * Two callers, one meaning — \"this run did not finish, and the workflow is\n * not at fault\": a firing SINGLETON concurrency refused, and a run that\n * passed its `runTimeoutSeconds`. Separate from `failRun` because a\n * CANCELLED run is not rerunnable and must not read as a workflow defect.\n */\n // A run that already ended keeps its status. Returns the waitpoints closed.\n async cancelRun(runId: string, reason: string): Promise<string[]> {\n return this.endLiveRun(runId, \"CANCELLED\", reason, null);\n }\n\n // Ends a run that has not ended, its waiting step FAILED and its\n // waitpoints CANCELLED; the ids of the waitpoints it closed.\n private async endLiveRun(\n runId: string,\n status: \"CANCELLED\" | \"FAILED\",\n reason: string,\n errorName: string | null,\n ): Promise<string[]> {\n this.runsInFlight.delete(runId);\n this.journaledSteps.delete(runId);\n this.pausingRuns.delete(runId);\n this.resumedLegs.delete(runId);\n if (erasedRuns.delete(runId)) return [];\n const endedAt = new Date().toISOString();\n return this.db.transaction().execute(async (trx) => {\n const ended = await trx\n .updateTable(\"run\")\n .set({\n status,\n error: redactMessage(reason),\n error_name: errorName,\n ended_at: endedAt,\n })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"in\", LIVE_RUN_STATUSES)\n .returning(\"id\")\n .execute();\n if (ended.length === 0) return [];\n await failWaitingSteps(trx, [runId], reason, errorName, endedAt);\n return closeLiveWaitpoints(trx, [runId], \"CANCELLED\", endedAt);\n });\n }\n\n // The durable record of a matched trigger, written before the operation\n // batch that matched it is acknowledged. The workflow's name and version are\n // only known once fire() reads the document, so beginRun fills them in.\n async enqueueRun(options: EnqueueRunOptions): Promise<string> {\n const id = randomUUID();\n await this.unmarkOnFailure([id], () =>\n this.insertPendingRun(this.db, id, options),\n );\n return id;\n }\n\n // A row insertPendingRun marked but whose write never landed is no run.\n private async unmarkOnFailure<T>(\n ids: string[],\n write: () => Promise<T>,\n ): Promise<T> {\n try {\n return await write();\n } catch (error) {\n for (const id of ids) {\n this.runsInFlight.delete(id);\n this.journaledSteps.delete(id);\n }\n throw error;\n }\n }\n\n /**\n * Claims the dedupe key and journals the PENDING run, bounding crash replays.\n *\n * Three outcomes, as {@link FireClaim}:\n *\n * - **`\"claimed\"`** with a run id: this fire is ours to run.\n * - **`\"duplicate\"`**: an earlier delivery of this operation already\n * fired: it journaled a run, or ran without one\n * ({@link FIRED_WITHOUT_RUN_ID}).\n * - **`\"abandoned\"`**: the operation has been delivered\n * {@link FIRE_CRASH_BUDGET} times and has never once got as far as\n * journaling a run — i.e. it is taking the process down before the write\n * lands, and the read-model cursor replays it on every boot. That is the\n * EPIPE boot loop (backlog item 5), and a budget is what turns it from an\n * unbootable reactor into one FAILED run naming the loop.\n *\n * Two writes, and which one is which matters:\n *\n * - The **attempt count** is bumped in its own committed transaction,\n * BEFORE the risky work. That is the only way a delivery that leaves no\n * run behind can be counted at all, which is what the budget needs. The\n * counter is never a claim signal — it only decides the budget.\n * - The **claim** is `run_id`, and it is set in the SAME transaction as the\n * run row, under a `WHERE run_id IS NULL` guard. The guard takes the\n * row's lock, so of two concurrent deliveries of one operation the second\n * blocks until the first commits and then matches no row: exactly one\n * delivery wins, and the run it journaled is committed with the claim. A\n * crash in between rolls BOTH back, so a claim that holds a run id always\n * holds a run — and a claim without one is retried, up to the budget.\n *\n * Counting and claiming are deliberately not the same write: if the bump\n * rode along inside the claim transaction, a run insert that takes the\n * process down would roll the count back with it and the budget could never\n * reach its limit — the boot loop it exists to bound.\n */\n async claimAndEnqueueRun(\n dedupeKey: string,\n ttlMs: number,\n nowIso: string,\n options: EnqueueRunOptions,\n ): Promise<FireClaim> {\n const attempt = await this.recordFireAttempt(\n options.workflowId,\n dedupeKey,\n ttlMs,\n nowIso,\n );\n if (attempt.runId !== null) return { outcome: \"duplicate\" };\n if (attempt.attempts > FIRE_CRASH_BUDGET) {\n return { outcome: \"abandoned\", attempts: attempt.attempts };\n }\n\n const id = randomUUID();\n const claimed = await this.unmarkOnFailure([id], () =>\n this.db.transaction().execute(async (trx) => {\n // RETURNING, not a row count: the knex-backed dialect reports none.\n const won = await trx\n .updateTable(\"trigger_dedupe\")\n .set({ run_id: id })\n .where(\"workflow_id\", \"=\", options.workflowId)\n .where(\"dedupe_key\", \"=\", dedupeKey)\n .where(\"run_id\", \"is\", null)\n .returning(\"dedupe_key\")\n .executeTakeFirst();\n if (won === undefined) return false;\n await this.insertPendingRun(trx, id, options);\n return true;\n }),\n );\n // The read this lost to is committed, so it holds the winner's run.\n if (!claimed) return { outcome: \"duplicate\" };\n return { outcome: \"claimed\", runId: id };\n }\n\n // A trigger batch's claims and PENDING runs, in one write; undefined where already claimed.\n // With `success`, the poll's success lands with its rows, or neither does:\n // a crash between them would advance next_poll_at past items never journaled.\n async journalTriggerItems(\n items: { dedupeKey?: string; options: EnqueueRunOptions }[],\n ttlMs: number,\n nowIso: string,\n success?: PollSuccess,\n ): Promise<(string | undefined)[]> {\n const marked: string[] = [];\n return this.unmarkOnFailure(marked, () =>\n this.db.transaction().execute(async (trx) => {\n if (success) {\n await pollSucceededIn(\n trx,\n success.workflowId,\n success.storeState,\n nowIso,\n success.nextPollAtIso,\n );\n }\n const journaled: (string | undefined)[] = [];\n for (const { dedupeKey, options } of items) {\n const id = randomUUID();\n const won =\n dedupeKey === undefined ||\n (await claimDedupeIn(\n trx,\n options.workflowId,\n dedupeKey,\n ttlMs,\n nowIso,\n id,\n ));\n if (won) {\n marked.push(id);\n await this.insertPendingRun(trx, id, options);\n }\n journaled.push(won ? id : undefined);\n }\n return journaled;\n }),\n );\n }\n\n // A schedule slot is consumed and its firing journaled together, or neither.\n async recordScheduleFire(\n nowIso: string,\n nextPollAtIso: string,\n options: EnqueueRunOptions,\n ): Promise<string> {\n const id = randomUUID();\n await this.unmarkOnFailure([id], () =>\n this.db.transaction().execute(async (trx) => {\n await pollSucceededIn(\n trx,\n options.workflowId,\n \"{}\",\n nowIso,\n nextPollAtIso,\n );\n await this.insertPendingRun(trx, id, options);\n }),\n );\n return id;\n }\n\n /**\n * Puts a piece_store partition back to `entries` and, in the same write,\n * cancels the runs the restored cursor delivers again and releases their\n * claims, so no reader sees the old cursor while the claims still hold.\n */\n async rewindPieceStore(\n scope: string,\n scopeKey: string,\n entries: Record<string, unknown>,\n redelivered: { runIds: string[]; reason: string } = {\n runIds: [],\n reason: \"\",\n },\n ): Promise<void> {\n const live = redelivered.runIds.filter((runId) => !erasedRuns.has(runId));\n const nowIso = new Date().toISOString();\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom(\"piece_store\")\n .where(\"scope\", \"=\", scope)\n .where(\"scope_key\", \"=\", scopeKey)\n .execute();\n for (const [key, value] of Object.entries(entries)) {\n assertPieceStoreEntry(key, value);\n await trx\n .insertInto(\"piece_store\")\n .values({\n scope,\n scope_key: scopeKey,\n key,\n value: JSON.stringify(value),\n updated_at: nowIso,\n })\n .execute();\n }\n if (live.length === 0) return;\n await trx\n .updateTable(\"run\")\n .set({\n status: \"CANCELLED\",\n error: redactMessage(redelivered.reason),\n ended_at: nowIso,\n })\n .where(\"id\", \"in\", live)\n .execute();\n await trx\n .deleteFrom(\"trigger_dedupe\")\n .where(\"run_id\", \"in\", live)\n .execute();\n });\n for (const runId of redelivered.runIds) {\n this.runsInFlight.delete(runId);\n this.journaledSteps.delete(runId);\n erasedRuns.delete(runId);\n }\n }\n\n /**\n * Counts one delivery of an operation, and reports whether a run was ever\n * journaled for it.\n *\n * Committed on its own: the point is to leave a trace even when whatever\n * comes next takes the process down. It is NOT a claim — the row it writes\n * holds no run id, and {@link claimAndEnqueueRun} is what decides, under a\n * lock, which delivery gets to fill it in.\n */\n async recordFireAttempt(\n workflowId: string,\n dedupeKey: string,\n ttlMs: number,\n nowIso: string,\n ): Promise<{ attempts: number; runId: string | null }> {\n const cutoff = new Date(Date.parse(nowIso) - ttlMs).toISOString();\n await this.db\n .deleteFrom(\"trigger_dedupe\")\n .where(\"workflow_id\", \"=\", workflowId)\n .where(\"created_at\", \"<\", cutoff)\n .execute();\n const row = await this.db\n .insertInto(\"trigger_dedupe\")\n .values({\n workflow_id: workflowId,\n dedupe_key: dedupeKey,\n run_id: null,\n created_at: nowIso,\n attempts: 1,\n })\n .onConflict((oc) =>\n oc.columns([\"workflow_id\", \"dedupe_key\"]).doUpdateSet({\n attempts: sql`${sql.table(\"trigger_dedupe\")}.attempts + 1`,\n }),\n )\n .returning([\"attempts\", \"run_id\"])\n .executeTakeFirstOrThrow();\n return { attempts: row.attempts ?? 1, runId: row.run_id };\n }\n\n /**\n * The abandonment of an over-budget fire, as a visible FAILED run, linked to\n * its dedupe key so a later delivery is a duplicate rather than another one.\n */\n async journalAbandonedFire(\n dedupeKey: string,\n options: EnqueueRunOptions & { attempts: number },\n ): Promise<string> {\n const id = randomUUID();\n const now = new Date().toISOString();\n await this.db.transaction().execute(async (trx) => {\n await trx\n .insertInto(\"run\")\n .values({\n id,\n workflow_id: options.workflowId,\n workflow_name: \"\",\n workflow_version: 0,\n trigger_kind: options.triggerKind,\n trigger_payload: cappedPayload(redact(options.triggerPayload)),\n status: \"FAILED\",\n error: redactMessage(abandonedFireError(options.attempts)),\n enqueued_at: now,\n started_at: now,\n ended_at: now,\n rerun_of: null,\n warnings: 0,\n warning_notes: null,\n })\n .execute();\n await trx\n .updateTable(\"trigger_dedupe\")\n .set({ run_id: id })\n .where(\"workflow_id\", \"=\", options.workflowId)\n .where(\"dedupe_key\", \"=\", dedupeKey)\n .where(\"run_id\", \"is\", null)\n .execute();\n });\n return id;\n }\n\n // In flight before the row commits: boot admission must never see a row\n // this process is about to start as one a stopped process left behind.\n private async insertPendingRun(\n db: Kysely<WorkflowRuntimeDB>,\n id: string,\n options: EnqueueRunOptions,\n ): Promise<void> {\n this.runsInFlight.add(id);\n const now = new Date().toISOString();\n await db\n .insertInto(\"run\")\n .values({\n id,\n workflow_id: options.workflowId,\n workflow_name: \"\",\n workflow_version: 0,\n trigger_kind: options.triggerKind,\n trigger_payload: cappedPayload(redact(options.triggerPayload)),\n status: PENDING_RUN_STATUS,\n error: null,\n enqueued_at: now,\n started_at: now,\n ended_at: null,\n rerun_of: null,\n warnings: 0,\n warning_notes: null,\n ...(options.parent\n ? {\n parent_run_id: options.parent.runId,\n parent_waitpoint_id: options.parent.waitpointId,\n }\n : {}),\n })\n .execute();\n }\n\n async getRunParent(runId: string): Promise<RunParent | undefined> {\n const row = await this.db\n .selectFrom(\"run\")\n .select([\"parent_run_id\", \"parent_waitpoint_id\"])\n .where(\"id\", \"=\", runId)\n .executeTakeFirst();\n if (!row?.parent_run_id) return undefined;\n return {\n runId: row.parent_run_id,\n waitpointId: row.parent_waitpoint_id ?? null,\n };\n }\n\n // Adopts an enqueued row: the run starts now, with the definition fire() read.\n // False when the row is no longer PENDING: cancelled while it queued.\n async beginRun(\n runId: string,\n details: { workflowName: string; workflowVersion: number },\n ): Promise<boolean> {\n this.runsInFlight.add(runId);\n this.journaledSteps.set(runId, new Map());\n const adopted = await this.db\n .updateTable(\"run\")\n .set({\n status: \"RUNNING\",\n workflow_name: details.workflowName,\n workflow_version: details.workflowVersion,\n // The wait between enqueue and start is queueing, not run time;\n // enqueued_at keeps the run's place in the listing.\n started_at: new Date().toISOString(),\n })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"=\", PENDING_RUN_STATUS)\n .returning(\"id\")\n .execute();\n if (adopted.length > 0) return true;\n this.runsInFlight.delete(runId);\n this.journaledSteps.delete(runId);\n return false;\n }\n\n async startRun(options: StartRunOptions): Promise<string> {\n const id = randomUUID();\n const now = new Date().toISOString();\n await this.db\n .insertInto(\"run\")\n .values({\n id,\n workflow_id: options.workflowId,\n workflow_name: options.workflowName,\n workflow_version: options.workflowVersion,\n trigger_kind: options.triggerKind,\n trigger_payload: cappedPayload(redact(options.triggerPayload)),\n status: \"RUNNING\",\n error: null,\n enqueued_at: now,\n started_at: now,\n ended_at: null,\n rerun_of: options.rerunOf ?? null,\n warnings: 0,\n warning_notes: null,\n })\n .execute();\n this.runsInFlight.add(id);\n this.journaledSteps.set(id, new Map());\n return id;\n }\n\n // One step's terminal state, written the moment it reaches it, so a\n // reactor killed mid-run leaves the work it finished behind.\n\n // Keyed by (run_id, step_path): a re-executed step corrects its row.\n async recordStep(\n runId: string,\n ordinal: number,\n step: StepExecutionRecord,\n ): Promise<void> {\n if (erasedRuns.has(runId)) return;\n const values = stepValues(runId, ordinal, step);\n const {\n run_id: _run,\n step_id: _step,\n step_path: _path,\n ...mutable\n } = values;\n const written = await this.withRunRow(runId, (trx) =>\n trx\n .insertInto(\"step_execution\")\n .values({ id: randomUUID(), ...values })\n .onConflict((oc) =>\n oc.columns([\"run_id\", \"step_path\"]).doUpdateSet(mutable),\n )\n .execute(),\n );\n if (!written) return;\n this.journaledSteps\n .get(runId)\n ?.set(values.step_path, { ordinal, hash: rowHash(values) });\n }\n\n // True when every step already has the row the sweep would write.\n private sweepIsNoop(runId: string, result: WorkflowRunResult): boolean {\n const journaled = this.journaledSteps.get(runId);\n if (!journaled) return false;\n return result.steps.every((step) => {\n const row = journaled.get(step.stepId);\n if (row === undefined) return false;\n return row.hash === rowHash(stepValues(runId, row.ordinal, step));\n });\n }\n\n // Closes the run out. `executionOrder` maps step id to the ordinal the step\n // ran with, which a lost row cannot otherwise be given back.\n // A WAITING result stays open with its pin; `held` false, leaving the run\n // RUNNING, when no live waitpoint of its step holds it.\n async finishRun(\n runId: string,\n result: WorkflowRunResult,\n executionOrder?: ReadonlyMap<string, number>,\n pin?: RunPinRow,\n ): Promise<{ held: boolean; closed: string[] }> {\n // Terminal from here whatever the writes below do: if we leave the run\n // RUNNING, a later sweep should be free to reach it.\n this.runsInFlight.delete(runId);\n const resumed = this.resumedLegs.delete(runId);\n const paused = this.pausingRuns.delete(runId) || resumed;\n // A carried step's row is the earlier leg's, already written.\n const own = result.steps.some((step) => step.carried)\n ? { ...result, steps: result.steps.filter((step) => !step.carried) }\n : result;\n const sweep = !this.sweepIsNoop(runId, own);\n this.journaledSteps.delete(runId);\n if (erasedRuns.delete(runId)) return { held: true, closed: [] };\n if (sweep && own.steps.length > 0) {\n try {\n await this.sweepSteps(runId, own, executionOrder);\n } catch (error) {\n // The work is done and the caller is owed its result: a journal that\n // cannot record the steps must not also cost the run its status.\n logger.warn(\n `Run ${runId}: writing the closing step journal failed; the run is closed out without it`,\n error,\n );\n }\n }\n const waiting = result.status === WAITING_RUN_STATUS;\n const on = result.waiting;\n const now = new Date().toISOString();\n // A leg that made no waitpoint and resumed none closes in one statement.\n const close = async (trx: Kysely<WorkflowRuntimeDB>) => {\n // Earlier legs' notes stay; this leg adds its own steps' notes.\n const prior = resumed\n ? await trx\n .selectFrom(\"run\")\n .select(\"warning_notes\")\n .where(\"id\", \"=\", runId)\n .executeTakeFirst()\n : undefined;\n const notes = [\n ...new Set([\n ...priorNotes(prior?.warning_notes ?? null),\n ...runWarningNotes(own),\n ]),\n ];\n const written = await trx\n .updateTable(\"run\")\n .set({\n status: result.status,\n error: result.error ? redactMessage(result.error) : null,\n error_name: result.errorName ?? null,\n ended_at: waiting ? null : now,\n warnings: notes.length,\n warning_notes: notes.length > 0 ? JSON.stringify(notes) : null,\n waiting_on: waiting ? (on?.waitpointId ?? null) : null,\n ...(pin ?? {}),\n })\n .where(\"id\", \"=\", runId)\n // In one statement, so an expiry cannot land between check and write.\n .$if(waiting, (qb) =>\n qb.where((eb) =>\n eb.exists(\n eb\n .selectFrom(\"waitpoint\")\n .select(\"waitpoint.id\")\n .where(\"waitpoint.id\", \"=\", on?.waitpointId ?? \"\")\n .where(\"waitpoint.run_id\", \"=\", runId)\n .where(\"waitpoint.step_id\", \"=\", on?.stepId ?? \"\")\n .where(\"waitpoint.status\", \"in\", LIVE_WAITPOINT_STATUSES),\n ),\n ),\n )\n .returning(\"id\")\n .execute();\n if (!waiting) {\n return {\n held: true,\n closed: paused\n ? await closeLiveWaitpoints(trx, [runId], \"EXPIRED\", now)\n : [],\n };\n }\n if (written.length === 0) return { held: false, closed: [] };\n // Only the waitpoint it waits on, and links a succeeded step made, resume it.\n // A link already resolved cannot resume an approval or a delay.\n const awaited = await trx\n .selectFrom(\"waitpoint\")\n .select(\"kind\")\n .where(\"id\", \"=\", on!.waitpointId)\n .executeTakeFirst();\n const linkStatuses =\n awaited?.kind === \"webhook\" ? LIVE_WAITPOINT_STATUSES : [\"PENDING\"];\n const closed = await closeLiveWaitpoints(\n trx,\n [runId],\n \"CANCELLED\",\n now,\n (eb) =>\n eb.or([\n eb(\"waitpoint.id\", \"=\", on!.waitpointId),\n eb.and([\n eb(\"waitpoint.type\", \"=\", \"WEBHOOK\"),\n eb(\"waitpoint.kind\", \"=\", \"webhook\"),\n eb(\"waitpoint.status\", \"in\", linkStatuses),\n eb.exists(\n eb\n .selectFrom(\"step_execution\")\n .select(\"step_execution.id\")\n .whereRef(\"step_execution.run_id\", \"=\", \"waitpoint.run_id\")\n .whereRef(\"step_execution.step_id\", \"=\", \"waitpoint.step_id\")\n .where(\"step_execution.status\", \"=\", \"SUCCEEDED\"),\n ),\n ]),\n ]),\n );\n return { held: true, closed };\n };\n return waiting || paused\n ? this.db.transaction().execute(close)\n : close(this.db);\n }\n\n // Upserts the whole step set: fills in the SKIPPED sweep per-step journaling\n // omits, and repairs the rows a failed journal write left behind.\n private async sweepSteps(\n runId: string,\n result: WorkflowRunResult,\n executionOrder?: ReadonlyMap<string, number>,\n ): Promise<void> {\n const journaled = await this.db\n .selectFrom(\"step_execution\")\n .select([\"step_id\", \"ordinal\"])\n .where(\"run_id\", \"=\", runId)\n .whereRef(\"step_path\", \"=\", \"step_id\")\n .execute();\n // A journaled step keeps the ordinal it ran with; the sweep lands after\n // the highest of them.\n const ordinals = new Map(\n journaled.map((row) => [row.step_id, row.ordinal]),\n );\n let nextOrdinal = journaled.reduce(\n (max, row) => Math.max(max, row.ordinal + 1),\n 0,\n );\n for (const step of result.steps) {\n const ran = executionOrder?.get(step.stepId);\n // A step that ran but lost its write goes back where it ran, not where\n // the definition happens to list it.\n if (ran === undefined || ordinals.has(step.stepId)) continue;\n ordinals.set(step.stepId, ran);\n nextOrdinal = Math.max(nextOrdinal, ran + 1);\n }\n // Skips never ran and never journaled an ordinal, so they trail everything\n // that did, in definition order.\n const ordinalFor = (step: StepExecutionRecord) =>\n ordinals.get(step.stepId) ?? nextOrdinal++;\n await this.withRunRow(runId, (trx) =>\n trx\n .insertInto(\"step_execution\")\n .values(\n result.steps.map((step) => ({\n id: randomUUID(),\n ...stepValues(runId, ordinalFor(step), step),\n })),\n )\n .onConflict((oc) =>\n oc.columns([\"run_id\", \"step_path\"]).doUpdateSet((eb) => ({\n ordinal: eb.ref(\"excluded.ordinal\"),\n step_key: eb.ref(\"excluded.step_key\"),\n piece_name: eb.ref(\"excluded.piece_name\"),\n block_name: eb.ref(\"excluded.block_name\"),\n status: eb.ref(\"excluded.status\"),\n input: eb.ref(\"excluded.input\"),\n output: eb.ref(\"excluded.output\"),\n port: eb.ref(\"excluded.port\"),\n error: eb.ref(\"excluded.error\"),\n error_name: eb.ref(\"excluded.error_name\"),\n started_at: eb.ref(\"excluded.started_at\"),\n ended_at: eb.ref(\"excluded.ended_at\"),\n piece_version: eb.ref(\"excluded.piece_version\"),\n piece_source: eb.ref(\"excluded.piece_source\"),\n version_match: eb.ref(\"excluded.version_match\"),\n version_note: eb.ref(\"excluded.version_note\"),\n config_hash: eb.ref(\"excluded.config_hash\"),\n })),\n )\n .execute(),\n );\n }\n\n // `fn` under a key-share lock on the run row, so an erase cannot interleave;\n // undefined, writing nothing, once the row is gone.\n private async withRunRow<T>(\n runId: string,\n fn: (trx: Kysely<WorkflowRuntimeDB>) => Promise<T>,\n ): Promise<T | undefined> {\n return this.db.transaction().execute(async (trx) => {\n const run = await trx\n .selectFrom(\"run\")\n .select(\"id\")\n .where(\"id\", \"=\", runId)\n .forKeyShare()\n .executeTakeFirst();\n return run ? fn(trx) : undefined;\n });\n }\n\n // A run that already ended keeps its status. Returns the waitpoints closed.\n async failRun(\n runId: string,\n error: string,\n errorName?: string,\n ): Promise<string[]> {\n return this.endLiveRun(runId, \"FAILED\", error, errorName ?? null);\n }\n\n // Scope is one workflow id, or a set of them (a drive's workflows). An\n // empty set matches nothing, which is not the same as an unscoped listing.\n\n // Newest first on (enqueued_at, id); `after` resumes past a row keyset-style.\n async listRuns(\n workflowId?: string | string[],\n limit = 25,\n options: ListRunsOptions = {},\n ): Promise<RunRow[]> {\n if (Array.isArray(workflowId) && workflowId.length === 0) return [];\n let query = this.db\n .selectFrom(\"run\")\n .selectAll()\n .orderBy(\"enqueued_at\", \"desc\")\n .orderBy(\"id\", \"desc\")\n .limit(Math.min(Math.max(limit, 1), MAX_LIST_RUNS));\n if (Array.isArray(workflowId)) {\n query = query.where(\"workflow_id\", \"in\", workflowId);\n } else if (workflowId) {\n query = query.where(\"workflow_id\", \"=\", workflowId);\n }\n const { after, excludeTriggerKinds } = options;\n if (after) {\n query = query.where((eb) =>\n eb(\n eb.refTuple(\"enqueued_at\", \"id\"),\n \"<\",\n eb.tuple(after.enqueuedAt, after.id),\n ),\n );\n }\n if (excludeTriggerKinds && excludeTriggerKinds.length > 0) {\n query = query.where(\"trigger_kind\", \"not in\", excludeTriggerKinds);\n }\n return query.execute();\n }\n\n async getRun(id: string): Promise<RunRow | undefined> {\n return this.db\n .selectFrom(\"run\")\n .selectAll()\n .where(\"id\", \"=\", id)\n .executeTakeFirst();\n }\n\n // A run's steps in execution order; a loop's iteration rows only with\n // `withIterations`, the first `iterationLimit` of them when set.\n async getSteps(\n runId: string,\n options: { withIterations?: boolean; iterationLimit?: number } = {},\n ): Promise<StepExecutionRow[]> {\n const base = this.db\n .selectFrom(\"step_execution\")\n .selectAll()\n .where(\"run_id\", \"=\", runId)\n .orderBy(\"ordinal\", \"asc\");\n const own = base.whereRef(\"step_path\", \"=\", \"step_id\");\n if (!options.withIterations) return own.execute();\n if (options.iterationLimit === undefined) return base.execute();\n const [steps, iterations] = await Promise.all([\n own.execute(),\n base\n .whereRef(\"step_path\", \"!=\", \"step_id\")\n .limit(options.iterationLimit)\n .execute(),\n ]);\n return [...steps, ...iterations].sort((a, b) => a.ordinal - b.ordinal);\n }\n\n // How many loop iteration rows a run journaled.\n async countIterations(runId: string): Promise<number> {\n const row = await this.db\n .selectFrom(\"step_execution\")\n .select((eb) => eb.fn.countAll<number>().as(\"count\"))\n .where(\"run_id\", \"=\", runId)\n .whereRef(\"step_path\", \"!=\", \"step_id\")\n .executeTakeFirst();\n return Number(row?.count ?? 0);\n }\n\n // Each run's own step rows in one query, in execution order; loop iteration\n // rows are left out. Without `withData` the blobs read as null.\n async getStepsForRuns(\n runIds: string[],\n options: { withData?: boolean } = {},\n ): Promise<Map<string, StepExecutionRow[]>> {\n const byRun = new Map<string, StepExecutionRow[]>(\n runIds.map((id) => [id, []]),\n );\n if (runIds.length === 0) return byRun;\n const base = this.db\n .selectFrom(\"step_execution\")\n .where(\"run_id\", \"in\", [...new Set(runIds)])\n .whereRef(\"step_path\", \"=\", \"step_id\")\n .orderBy(\"run_id\")\n .orderBy(\"ordinal\", \"asc\");\n const rows: StepExecutionRow[] =\n options.withData === false\n ? (await base.select(STEP_COLUMNS_WITHOUT_DATA).execute()).map(\n (row) => ({ ...row, input: null, output: null }),\n )\n : await base.selectAll().execute();\n for (const row of rows) byRun.get(row.run_id)?.push(row);\n return byRun;\n }\n\n async recordRunDocuments(\n runId: string,\n documentIds: string[],\n ): Promise<void> {\n if (documentIds.length === 0 || erasedRuns.has(runId)) return;\n await this.withRunRow(runId, (trx) =>\n trx\n .insertInto(\"run_document\")\n .values(\n [...new Set(documentIds)].map((documentId) => ({\n run_id: runId,\n document_id: documentId,\n })),\n )\n .onConflict((oc) => oc.columns([\"run_id\", \"document_id\"]).doNothing())\n .execute(),\n );\n }\n\n async getRunDocuments(runId: string): Promise<string[]> {\n const rows = await this.db\n .selectFrom(\"run_document\")\n .select(\"document_id\")\n .where(\"run_id\", \"=\", runId)\n .execute();\n return rows.map((row) => row.document_id);\n }\n\n async getRunDocumentsForRuns(\n runIds: string[],\n ): Promise<Map<string, string[]>> {\n const byRun = new Map<string, string[]>(runIds.map((id) => [id, []]));\n if (runIds.length === 0) return byRun;\n const rows = await this.db\n .selectFrom(\"run_document\")\n .select([\"run_id\", \"document_id\"])\n .where(\"run_id\", \"in\", [...new Set(runIds)])\n .execute();\n for (const row of rows) byRun.get(row.run_id)?.push(row.document_id);\n return byRun;\n }\n\n /**\n * Parks a workflow: its park row, and an ENABLED trigger_state row turned\n * PARKED, in one transaction. True when a trigger_state row was parked.\n */\n async parkWorkflow(\n workflowId: string,\n publishedVersion: number,\n reason: string,\n ): Promise<boolean> {\n const { workflow_id: _, ...row } = workflowParkRow(\n workflowId,\n publishedVersion,\n reason,\n );\n const now = row.parked_at;\n return this.db.transaction().execute(async (trx) => {\n await trx\n .insertInto(\"workflow_park\")\n .values({ workflow_id: workflowId, ...row })\n .onConflict((oc) => oc.column(\"workflow_id\").doUpdateSet(row))\n .execute();\n const parked = await trx\n .updateTable(\"trigger_state\")\n .set({\n status: PARKED_TRIGGER_STATUS,\n last_error: row.reason,\n // Kept for a lift: renewal selects only ENABLED rows.\n updated_at: now,\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .where(\"status\", \"=\", \"ENABLED\")\n .returning(\"workflow_id\")\n .execute();\n return parked.length > 0;\n });\n }\n\n /** A disable clears a park: the park row, and a PARKED trigger row turned\n * DISABLED, so re-enabling arms it whether or not the supervisor held it. */\n async clearParkOnDisable(workflowId: string): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom(\"workflow_park\")\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n await trx\n .updateTable(\"trigger_state\")\n .set({\n status: \"DISABLED\",\n ...RENEW_CLEARED,\n updated_at: new Date().toISOString(),\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .where(\"status\", \"=\", PARKED_TRIGGER_STATUS)\n .execute();\n });\n }\n\n /** Undoes {@link parkWorkflow}; `trigger` says whether it parked a row. */\n async liftPark(workflowId: string, trigger: boolean): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom(\"workflow_park\")\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n if (!trigger) return;\n await trx\n .updateTable(\"trigger_state\")\n .set({\n status: \"ENABLED\",\n last_error: null,\n updated_at: new Date().toISOString(),\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .where(\"status\", \"=\", PARKED_TRIGGER_STATUS)\n .execute();\n });\n }\n\n async getWorkflowPark(\n workflowId: string,\n ): Promise<WorkflowParkRow | undefined> {\n return this.db\n .selectFrom(\"workflow_park\")\n .selectAll()\n .where(\"workflow_id\", \"=\", workflowId)\n .executeTakeFirst();\n }\n\n async listWorkflowParks(): Promise<WorkflowParkRow[]> {\n return this.db.selectFrom(\"workflow_park\").selectAll().execute();\n }\n\n async clearWorkflowPark(workflowId: string): Promise<void> {\n await this.db\n .deleteFrom(\"workflow_park\")\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n }\n\n async getTriggerState(\n workflowId: string,\n ): Promise<TriggerStateRow | undefined> {\n return this.db\n .selectFrom(\"trigger_state\")\n .selectAll()\n .where(\"workflow_id\", \"=\", workflowId)\n .executeTakeFirst();\n }\n\n // last_error is whatever a piece's onEnable or a schedule parse threw, so it\n // goes through the same gate a poll failure does.\n async upsertTriggerState(row: TriggerStateInput): Promise<void> {\n const values: TriggerStateRow = {\n piece_version: null,\n piece_source: null,\n version_match: null,\n version_note: null,\n next_renew_at: null,\n renew_failures: 0,\n ...row,\n last_error: row.last_error ? redactMessage(row.last_error) : null,\n renew_error: row.renew_error ? redactMessage(row.renew_error) : null,\n };\n await this.db\n .insertInto(\"trigger_state\")\n .values(values)\n .onConflict((oc) => {\n const { workflow_id: _, ...rest } = values;\n return oc.column(\"workflow_id\").doUpdateSet(rest);\n })\n .execute();\n }\n\n async setTriggerStatus(\n workflowId: string,\n status: string,\n error?: string,\n ): Promise<void> {\n await this.db\n .updateTable(\"trigger_state\")\n .set({\n status,\n last_error: error ? redactMessage(error) : null,\n // Only an ENABLED trigger holds a subscription to renew.\n ...(status === \"ENABLED\" ? {} : RENEW_CLEARED),\n updated_at: new Date().toISOString(),\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n }\n\n async listDueTriggerStates(nowIso: string): Promise<TriggerStateRow[]> {\n const rows = await this.db\n .selectFrom(\"trigger_state\")\n .selectAll()\n .where(\"status\", \"=\", \"ENABLED\")\n .where(\"next_poll_at\", \"<=\", nowIso)\n .execute();\n // A row whose state is still trapped in the blob is not runnable: polling\n // it would advance an empty cursor and re-deliver everything it ever saw.\n return rows.filter((row) => !this.unmigrated.has(row.workflow_id));\n }\n\n async listDueTriggerRenewals(nowIso: string): Promise<TriggerStateRow[]> {\n const rows = await this.db\n .selectFrom(\"trigger_state\")\n .selectAll()\n .where(\"status\", \"=\", \"ENABLED\")\n .where(\"next_renew_at\", \"<=\", nowIso)\n .execute();\n return rows.filter((row) => !this.unmigrated.has(row.workflow_id));\n }\n\n async setTriggerRenewAt(\n workflowId: string,\n nextRenewAtIso: string | null,\n ): Promise<void> {\n await this.db\n .updateTable(\"trigger_state\")\n .set(\n nextRenewAtIso === null\n ? RENEW_CLEARED\n : { next_renew_at: nextRenewAtIso },\n )\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n }\n\n async recordRenewSuccess(\n workflowId: string,\n nowIso: string,\n nextRenewAtIso: string,\n ): Promise<void> {\n await this.db\n .updateTable(\"trigger_state\")\n .set({\n next_renew_at: nextRenewAtIso,\n renew_error: null,\n renew_failures: 0,\n updated_at: nowIso,\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n }\n\n async recordRenewFailure(\n workflowId: string,\n error: string,\n nowIso: string,\n nextRenewAtIso: string,\n renewFailures: number,\n ): Promise<void> {\n await this.db\n .updateTable(\"trigger_state\")\n .set({\n next_renew_at: nextRenewAtIso,\n renew_error: redactMessage(error),\n renew_failures: renewFailures,\n updated_at: nowIso,\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n }\n\n // A deleted workflow's row, with the FLOW partition its trigger wrote.\n async deleteTriggerState(workflowId: string): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom(\"trigger_state\")\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n await trx\n .deleteFrom(\"piece_store\")\n .where(\"scope\", \"=\", \"FLOW\")\n .where(\"scope_key\", \"=\", workflowId)\n .execute();\n });\n this.unmigrated.delete(workflowId);\n }\n\n async listTriggerStates(): Promise<TriggerStateRow[]> {\n return this.db\n .selectFrom(\"trigger_state\")\n .selectAll()\n .orderBy(\"workflow_id\", \"asc\")\n .execute();\n }\n\n // A null next_poll_at leaves the trigger unscheduled, which is what a\n // webhook delivery wants: it recorded a success without becoming a poll.\n async recordPollSuccess(\n workflowId: string,\n storeState: string,\n nowIso: string,\n nextPollAtIso: string | null,\n ): Promise<void> {\n await pollSucceededIn(\n this.db,\n workflowId,\n storeState,\n nowIso,\n nextPollAtIso,\n );\n }\n\n async recordPollFailure(\n workflowId: string,\n error: string,\n nowIso: string,\n nextPollAtIso: string,\n consecutiveFailures: number,\n ): Promise<void> {\n await this.db\n .updateTable(\"trigger_state\")\n .set({\n last_poll_at: nowIso,\n next_poll_at: nextPollAtIso,\n last_error: redactMessage(error),\n consecutive_failures: consecutiveFailures,\n updated_at: nowIso,\n })\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n }\n\n // Claim-with-status dedupe: true when the key was free (caller fires).\n async claimDedupe(\n workflowId: string,\n dedupeKey: string,\n ttlMs: number,\n nowIso: string,\n ): Promise<boolean> {\n return claimDedupeIn(this.db, workflowId, dedupeKey, ttlMs, nowIso);\n }\n\n // A removed workflow's keys would otherwise wait for a claim that never comes.\n async deleteDedupe(workflowId: string): Promise<void> {\n await this.db\n .deleteFrom(\"trigger_dedupe\")\n .where(\"workflow_id\", \"=\", workflowId)\n .execute();\n }\n\n // ── suspended runs ──────────────────────────────────────────────────────\n\n // Inserts the step's waitpoint, or returns the live one it already has, as\n // upstream's createForPause: a repeat create or a retry gets the same row.\n async createWaitpoint(\n row: WaitpointRow,\n ): Promise<{ waitpoint: WaitpointRow; created: boolean }> {\n if (this.runsInFlight.has(row.run_id)) this.pausingRuns.add(row.run_id);\n for (let attempt = 1; ; attempt++) {\n const inserted = await this.withRunRow(row.run_id, (trx) =>\n trx\n .insertInto(\"waitpoint\")\n .values(row)\n .onConflict((oc) => oc.doNothing())\n .returningAll()\n .executeTakeFirst()\n .then((waitpoint) => ({ waitpoint })),\n );\n if (!inserted) throw new Error(`Run \"${row.run_id}\" no longer exists`);\n if (inserted.waitpoint) {\n return { waitpoint: inserted.waitpoint, created: true };\n }\n const live = await this.db\n .selectFrom(\"waitpoint\")\n .selectAll()\n .where(\"run_id\", \"=\", row.run_id)\n .where(\"step_path\", \"=\", row.step_path)\n .where(\"status\", \"in\", LIVE_WAITPOINT_STATUSES)\n .executeTakeFirst();\n if (live) return { waitpoint: live, created: false };\n // It closed between the two statements; the step gets a new one.\n if (attempt >= 3) {\n throw new Error(\n `Could not create a waitpoint for step \"${row.step_key}\"`,\n );\n }\n }\n }\n\n async getWaitpoint(id: string): Promise<WaitpointRow | undefined> {\n return this.db\n .selectFrom(\"waitpoint\")\n .selectAll()\n .where(\"id\", \"=\", id)\n .executeTakeFirst();\n }\n\n async getWaitpointByTokenHash(\n tokenHash: string,\n ): Promise<WaitpointRow | undefined> {\n return this.db\n .selectFrom(\"waitpoint\")\n .selectAll()\n .where(\"token_hash\", \"=\", tokenHash)\n .executeTakeFirst();\n }\n\n // PENDING → COMPLETED, once, while unexpired and its run RUNNING or WAITING.\n // Never a link while its run waits on an approval or a delay.\n async completeWaitpoint(\n id: string,\n resolution: {\n payload: unknown;\n decidedBy?: string | null;\n resolvedAt?: string;\n },\n ): Promise<WaitpointRow | undefined> {\n const now = new Date().toISOString();\n const rows = await this.db\n .updateTable(\"waitpoint\")\n .set({\n status: \"COMPLETED\",\n resume_payload: JSON.stringify(resolution.payload ?? {}),\n resolved_at: resolution.resolvedAt ?? now,\n decided_by: resolution.decidedBy ?? null,\n })\n .where(\"id\", \"=\", id)\n .where(\"status\", \"=\", \"PENDING\")\n .where((eb) =>\n eb.or([eb(\"expires_at\", \"is\", null), eb(\"expires_at\", \">\", now)]),\n )\n .where((eb) =>\n eb.not(\n eb.exists(\n eb\n .selectFrom(\"run\")\n .innerJoin(\"waitpoint as awaited\", \"awaited.id\", \"run.waiting_on\")\n .select(\"run.id\")\n .whereRef(\"run.id\", \"=\", \"waitpoint.run_id\")\n .whereRef(\"awaited.id\", \"!=\", \"waitpoint.id\")\n .where(\"awaited.kind\", \"!=\", \"webhook\")\n .where(\"awaited.status\", \"in\", LIVE_WAITPOINT_STATUSES),\n ),\n ),\n )\n .where((eb) =>\n eb.exists(\n eb\n .selectFrom(\"run\")\n .select(\"run.id\")\n .whereRef(\"run.id\", \"=\", \"waitpoint.run_id\")\n .where(\"run.status\", \"in\", [\"RUNNING\", WAITING_RUN_STATUS]),\n ),\n )\n .returningAll()\n .execute();\n return rows[0];\n }\n\n // Due DELAY waitpoints, claimed PENDING → COMPLETED in one batch.\n async claimDueDelayWaitpoints(\n nowIso: string,\n limit: number,\n ): Promise<WaitpointRow[]> {\n return this.db\n .updateTable(\"waitpoint\")\n .set({ status: \"COMPLETED\", resolved_at: nowIso, resume_payload: \"{}\" })\n .where(\"id\", \"in\", (eb) =>\n eb\n .selectFrom(\"waitpoint\")\n .select(\"id\")\n .where(\"status\", \"=\", \"PENDING\")\n .where(\"type\", \"=\", \"DELAY\")\n .where(\"resume_at\", \"<=\", nowIso)\n .orderBy(\"resume_at\")\n .limit(limit),\n )\n .where(\"status\", \"=\", \"PENDING\")\n .returningAll()\n .execute();\n }\n\n // PENDING waitpoints past their expiry, claimed PENDING → EXPIRED in one\n // batch; the WAITING runs that waited on them end CANCELLED in the same transaction.\n async expireDueWaitpoints(\n nowIso: string,\n limit: number,\n ): Promise<{ expired: WaitpointRow[]; ended: EndedWait[] }> {\n return this.db.transaction().execute(async (trx) => {\n const expired = await trx\n .updateTable(\"waitpoint\")\n .set({ status: \"EXPIRED\", resolved_at: nowIso })\n .where(\"id\", \"in\", (eb) =>\n eb\n .selectFrom(\"waitpoint\")\n .select(\"id\")\n .where(\"status\", \"=\", \"PENDING\")\n .where(\"expires_at\", \"<=\", nowIso)\n .orderBy(\"expires_at\")\n .limit(limit),\n )\n .where(\"status\", \"=\", \"PENDING\")\n .returningAll()\n .execute();\n const ended: EndedWait[] = [];\n for (const waitpoint of expired) {\n const end = await endWaitingRun(trx, waitpoint.run_id, {\n reason: waitpointExpiryReason(waitpoint),\n errorName: WAITPOINT_EXPIRED_ERROR_NAME,\n endedAt: nowIso,\n waitpointId: waitpoint.id,\n });\n if (end) ended.push(end);\n }\n return { expired, ended };\n });\n }\n\n // WAITING runs whose waitpoint is no longer live, with no resume delivered:\n // nothing would ever end them, so they end CANCELLED.\n async endStrandedWaits(limit: number): Promise<EndedWait[]> {\n const runs = await this.db\n .selectFrom(\"run\")\n .select(\"id\")\n .where(\"status\", \"=\", WAITING_RUN_STATUS)\n .where((eb) => strandedWait(eb))\n .limit(limit)\n .execute();\n const ended: EndedWait[] = [];\n for (const run of runs) {\n const end = await this.db.transaction().execute((trx) =>\n endWaitingRun(trx, run.id, {\n reason: STRANDED_WAIT_REASON,\n errorName: WAITPOINT_NOT_LIVE_ERROR_NAME,\n endedAt: new Date().toISOString(),\n }),\n );\n if (end) ended.push(end);\n }\n return ended;\n }\n\n // The next PENDING expiry, for the same timer as DELAY.\n async nextExpiry(): Promise<string | undefined> {\n const row = await this.db\n .selectFrom(\"waitpoint\")\n .select(\"expires_at\")\n .where(\"status\", \"=\", \"PENDING\")\n .where(\"expires_at\", \"is not\", null)\n .orderBy(\"expires_at\")\n .limit(1)\n .executeTakeFirst();\n return row?.expires_at ?? undefined;\n }\n\n async countWaitingRuns(): Promise<number> {\n const row = await this.db\n .selectFrom(\"run\")\n .select((eb) => eb.fn.countAll<number>().as(\"count\"))\n .where(\"status\", \"=\", WAITING_RUN_STATUS)\n .executeTakeFirst();\n return Number(row?.count ?? 0);\n }\n\n // The next DELAY due time, for a single timer.\n async nextDelayDue(): Promise<string | undefined> {\n const row = await this.db\n .selectFrom(\"waitpoint\")\n .select(\"resume_at\")\n .where(\"status\", \"=\", \"PENDING\")\n .where(\"type\", \"=\", \"DELAY\")\n .where(\"resume_at\", \"is not\", null)\n .orderBy(\"resume_at\")\n .limit(1)\n .executeTakeFirst();\n return row?.resume_at ?? undefined;\n }\n\n async hasCompletedWaitpoint(runId: string): Promise<boolean> {\n const row = await this.db\n .selectFrom(\"waitpoint\")\n .select(\"id\")\n .where(\"run_id\", \"=\", runId)\n .where(\"status\", \"=\", \"COMPLETED\")\n .limit(1)\n .executeTakeFirst();\n return row !== undefined;\n }\n\n // WAITING runs a resume was delivered to but which never re-entered.\n async heldRunIds(): Promise<string[]> {\n const rows = await this.db\n .selectFrom(\"waitpoint\")\n .innerJoin(\"run\", \"run.id\", \"waitpoint.run_id\")\n .select(\"waitpoint.run_id\")\n .distinct()\n .where(\"waitpoint.status\", \"=\", \"COMPLETED\")\n .where(\"run.status\", \"=\", WAITING_RUN_STATUS)\n .execute();\n return rows.map((row) => row.run_id);\n }\n\n // Whether this process is executing the run.\n isRunInFlight(runId: string): boolean {\n return this.runsInFlight.has(runId);\n }\n\n // WAITING → RUNNING, once; false when it was not WAITING.\n async claimWaitingRun(runId: string): Promise<boolean> {\n const claimed = await this.db\n .updateTable(\"run\")\n .set({ status: \"RUNNING\" })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"=\", WAITING_RUN_STATUS)\n .returning(\"id\")\n .execute();\n if (claimed.length === 0) return false;\n this.runsInFlight.add(runId);\n this.resumedLegs.add(runId);\n this.journaledSteps.set(runId, new Map());\n return true;\n }\n\n // A claimed run with nothing to resume on goes back to waiting.\n async returnToWaiting(runId: string): Promise<void> {\n this.runsInFlight.delete(runId);\n this.resumedLegs.delete(runId);\n this.journaledSteps.delete(runId);\n await this.db\n .updateTable(\"run\")\n .set({ status: WAITING_RUN_STATUS })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"=\", \"RUNNING\")\n .execute();\n }\n\n // The run's COMPLETED waitpoint, now CONSUMED: the one it waits on, else,\n // for a webhook wait, the oldest link resolved, which closes the one it waits on.\n async consumeCompletedWaitpoint(\n runId: string,\n ): Promise<{ waitpoint: WaitpointRow; closed: string[] } | undefined> {\n return this.db.transaction().execute(async (trx) => {\n const run = await trx\n .selectFrom(\"run\")\n .select(\"waiting_on\")\n .where(\"id\", \"=\", runId)\n .executeTakeFirst();\n const waitingOn = run?.waiting_on ?? null;\n const candidates = await trx\n .selectFrom(\"waitpoint\")\n .selectAll()\n .where(\"run_id\", \"=\", runId)\n .where(\"status\", \"=\", \"COMPLETED\")\n .orderBy(\"resolved_at\")\n .execute();\n const awaited = waitingOn\n ? await trx\n .selectFrom(\"waitpoint\")\n .select(\"kind\")\n .where(\"id\", \"=\", waitingOn)\n .executeTakeFirst()\n : undefined;\n // An approval or a delay is resumed only by its own waitpoint.\n const linksResume = !awaited || awaited.kind === \"webhook\";\n const chosen =\n candidates.find((row) => row.id === waitingOn) ??\n (linksResume ? candidates[0] : undefined);\n if (!chosen) return undefined;\n const rows = await trx\n .updateTable(\"waitpoint\")\n .set({ status: \"CONSUMED\" })\n .where(\"id\", \"=\", chosen.id)\n .where(\"status\", \"=\", \"COMPLETED\")\n .returningAll()\n .execute();\n const waitpoint = rows[0];\n if (!waitpoint) return undefined;\n // So the waiting step, run again, can wait anew.\n const closed =\n waitingOn && waitingOn !== waitpoint.id\n ? await closeLiveWaitpoints(\n trx,\n [runId],\n \"CANCELLED\",\n new Date().toISOString(),\n (eb) => eb(\"waitpoint.id\", \"!=\", waitingOn),\n )\n : [];\n return { waitpoint, closed };\n });\n }\n\n async getRunPin(runId: string): Promise<RunPinRow | undefined> {\n return this.db\n .selectFrom(\"run\")\n .select([\n \"definition_hash\",\n \"definition_op_index\",\n \"definition_scope_hash\",\n ])\n .where(\"id\", \"=\", runId)\n .executeTakeFirst();\n }\n\n // Closes out a run that is not executing: WAITING, or PENDING in a queue.\n async cancelIdleRun(\n runId: string,\n reason: string,\n ): Promise<string | undefined> {\n const endedAt = new Date().toISOString();\n const ended = await this.db.transaction().execute(async (trx) => {\n const rows = await trx\n .updateTable(\"run\")\n .set({\n status: \"CANCELLED\",\n error: redactMessage(reason),\n ended_at: endedAt,\n })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"in\", [WAITING_RUN_STATUS, PENDING_RUN_STATUS])\n .returning(\"id\")\n .execute();\n if (rows.length === 0) return false;\n await failWaitingSteps(trx, [runId], reason, null, endedAt);\n await closeLiveWaitpoints(trx, [runId], \"CANCELLED\", endedAt);\n return true;\n });\n if (!ended) return undefined;\n this.runsInFlight.delete(runId);\n return runId;\n }\n\n // Ends a RUNNING run whose wait cannot go on, its waiting step FAILED.\n async endWait(\n runId: string,\n end: {\n status: \"CANCELLED\" | \"FAILED\";\n reason: string;\n errorName: string;\n waitpoints: \"EXPIRED\" | \"CANCELLED\";\n },\n ): Promise<string[]> {\n this.runsInFlight.delete(runId);\n this.journaledSteps.delete(runId);\n this.pausingRuns.delete(runId);\n this.resumedLegs.delete(runId);\n const endedAt = new Date().toISOString();\n return this.db.transaction().execute(async (trx) => {\n const rows = await trx\n .updateTable(\"run\")\n .set({\n status: end.status,\n error: redactMessage(end.reason),\n error_name: end.errorName,\n ended_at: endedAt,\n })\n .where(\"id\", \"=\", runId)\n .where(\"status\", \"=\", \"RUNNING\")\n .returning(\"id\")\n .execute();\n if (rows.length === 0) return [];\n await failWaitingSteps(trx, [runId], end.reason, end.errorName, endedAt);\n return closeLiveWaitpoints(trx, [runId], end.waitpoints, endedAt);\n });\n }\n\n async listWaitpointsForRuns(\n runIds: string[],\n ): Promise<Map<string, WaitpointRow[]>> {\n const byRun = new Map<string, WaitpointRow[]>(runIds.map((id) => [id, []]));\n if (runIds.length === 0) return byRun;\n const rows = await this.db\n .selectFrom(\"waitpoint\")\n .selectAll()\n .where(\"run_id\", \"in\", [...new Set(runIds)])\n .orderBy(\"created_at\")\n .execute();\n for (const row of rows) byRun.get(row.run_id)?.push(row);\n return byRun;\n }\n\n // WAITING runs, oldest first; an empty scope matches nothing.\n async listWaitingRuns(\n workflowId: string | string[] | undefined,\n limit: number,\n ): Promise<RunRow[]> {\n if (Array.isArray(workflowId) && workflowId.length === 0) return [];\n let query = this.db\n .selectFrom(\"run\")\n .selectAll()\n .where(\"status\", \"=\", WAITING_RUN_STATUS)\n .orderBy(\"enqueued_at\", \"asc\")\n .orderBy(\"id\", \"asc\")\n .limit(Math.min(Math.max(limit, 1), MAX_LIST_RUNS));\n if (Array.isArray(workflowId)) {\n query = query.where(\"workflow_id\", \"in\", workflowId);\n } else if (workflowId) {\n query = query.where(\"workflow_id\", \"=\", workflowId);\n }\n return query.execute();\n }\n\n // Deletes runs that finished before `cutoffIso`, with their steps and\n // documents, a batch per transaction. Returns how many runs went.\n async pruneFinishedRuns(\n cutoffIso: string,\n batchSize = PRUNE_BATCH_SIZE,\n ): Promise<number> {\n let pruned = 0;\n for (;;) {\n const deleted = await this.db.transaction().execute(async (trx) => {\n const ids = (\n await trx\n .selectFrom(\"run\")\n .select(\"id\")\n .where(\"ended_at\", \"is not\", null)\n .where(\"ended_at\", \"<\", cutoffIso)\n .limit(batchSize)\n .execute()\n ).map((row) => row.id);\n if (ids.length === 0) return 0;\n await trx\n .deleteFrom(\"step_execution\")\n .where(\"run_id\", \"in\", ids)\n .execute();\n await trx.deleteFrom(\"waitpoint\").where(\"run_id\", \"in\", ids).execute();\n await trx\n .deleteFrom(\"run_document\")\n .where(\"run_id\", \"in\", ids)\n .execute();\n await trx.deleteFrom(\"run\").where(\"id\", \"in\", ids).execute();\n return ids.length;\n });\n pruned += deleted;\n if (deleted < batchSize) return pruned;\n }\n }\n\n // Runs that carried a document, or a purged workflow's runs, go with their\n // reruns; dedupe keys stay, unlinked.\n async eraseRunsForDocuments(documentIds: string[]): Promise<ErasedRuns> {\n const ids = [...new Set(documentIds)];\n const erased: ErasedRuns = {\n runs: 0,\n steps: 0,\n documents: 0,\n dedupeKeysUnlinked: 0,\n };\n if (ids.length === 0) return erased;\n return this.db.transaction().execute(async (trx) => {\n const runIds = new Set(\n (\n await trx\n .selectFrom(\"run_document\")\n .select(\"run_id\")\n .where(\"document_id\", \"in\", ids)\n .execute()\n ).map((row) => row.run_id),\n );\n // A purged workflow's own runs, test runs included.\n const own = await trx\n .selectFrom(\"run\")\n .select(\"id\")\n .where(\"workflow_id\", \"in\", ids)\n .execute();\n for (const row of own) runIds.add(row.id);\n const named = await trx\n .selectFrom(\"run\")\n .select([\"id\", \"trigger_payload\"])\n .where((eb) =>\n eb.or(\n ids.map((id) => eb(sql`strpos(trigger_payload, ${id})`, \">\", 0)),\n ),\n )\n .execute();\n for (const row of named) {\n if (journaledPayloadNames(row.trigger_payload, ids)) runIds.add(row.id);\n }\n // A trigger test journals its sample as the step's output.\n const sampled = await trx\n .selectFrom(\"step_execution\")\n .innerJoin(\"run\", \"run.id\", \"step_execution.run_id\")\n .select([\"step_execution.run_id as runId\", \"step_execution.output\"])\n .where(\"run.trigger_kind\", \"=\", TEST_TRIGGER_KIND)\n .where((eb) =>\n eb.or(\n ids.map((id) =>\n eb(sql`strpos(step_execution.output, ${id})`, \">\", 0),\n ),\n ),\n )\n .execute();\n for (const row of sampled) {\n if (journaledPayloadNames(row.output, ids)) runIds.add(row.runId);\n }\n // A rerun replays its original's step outputs.\n let frontier = [...runIds];\n while (frontier.length > 0) {\n const reruns = await trx\n .selectFrom(\"run\")\n .select(\"id\")\n .where(\"rerun_of\", \"in\", frontier)\n .execute();\n frontier = reruns.map((row) => row.id).filter((id) => !runIds.has(id));\n for (const id of frontier) runIds.add(id);\n }\n if (runIds.size === 0) return erased;\n\n const all = [...runIds].sort();\n // Locked first: a claim or admission waits for the erase and then finds\n // no row, and one that committed already is read here as live.\n const locked = await trx\n .selectFrom(\"run\")\n .select([\"id\", \"status\"])\n .where(\"id\", \"in\", all)\n .orderBy(\"id\")\n .forUpdate()\n .execute();\n // Before the deletes, so a step journaled meanwhile is dropped too.\n for (const row of locked) {\n if (row.status === \"RUNNING\" || row.status === PENDING_RUN_STATUS) {\n erasedRuns.add(row.id);\n }\n }\n erased.steps = (\n await trx\n .deleteFrom(\"step_execution\")\n .where(\"run_id\", \"in\", all)\n .returning(\"id\")\n .execute()\n ).length;\n await trx.deleteFrom(\"waitpoint\").where(\"run_id\", \"in\", all).execute();\n erased.documents = (\n await trx\n .deleteFrom(\"run_document\")\n .where(\"run_id\", \"in\", all)\n .returning(\"run_id\")\n .execute()\n ).length;\n erased.dedupeKeysUnlinked = (\n await trx\n .updateTable(\"trigger_dedupe\")\n .set({ run_id: FIRED_WITHOUT_RUN_ID })\n .where(\"run_id\", \"in\", all)\n .returning(\"dedupe_key\")\n .execute()\n ).length;\n erased.runs = (\n await trx\n .deleteFrom(\"run\")\n .where(\"id\", \"in\", all)\n .returning(\"id\")\n .execute()\n ).length;\n return erased;\n });\n }\n\n // Keys older than the longest dedupe TTL can no longer suppress anything.\n async pruneDedupe(cutoffIso: string): Promise<number> {\n const deleted = await this.db\n .deleteFrom(\"trigger_dedupe\")\n .where(\"created_at\", \"<\", cutoffIso)\n .returning(\"dedupe_key\")\n .execute();\n return deleted.length;\n }\n\n async getPieceStoreValue(\n scope: string,\n scopeKey: string,\n key: string,\n ): Promise<unknown> {\n const row = await this.db\n .selectFrom(\"piece_store\")\n .select(\"value\")\n .where(\"scope\", \"=\", scope)\n .where(\"scope_key\", \"=\", scopeKey)\n .where(\"key\", \"=\", key)\n .executeTakeFirst();\n if (!row) return null;\n try {\n return JSON.parse(row.value);\n } catch {\n // A row we cannot parse is a row we cannot honour; the piece sees the\n // key as absent and the next write replaces it.\n return null;\n }\n }\n\n async setPieceStoreValue(\n scope: string,\n scopeKey: string,\n key: string,\n value: unknown,\n ): Promise<void> {\n assertPieceStoreEntry(key, value);\n const encoded = JSON.stringify(value);\n const nowIso = new Date().toISOString();\n // One upsert, not select-then-branch: concurrent writers can share a scope\n // (PROJECT scope_key is one row for every workflow) and would otherwise race.\n await this.db\n .insertInto(\"piece_store\")\n .values({\n scope,\n scope_key: scopeKey,\n key,\n value: encoded,\n updated_at: nowIso,\n })\n .onConflict((oc) =>\n oc\n .columns([\"scope\", \"scope_key\", \"key\"])\n .doUpdateSet({ value: encoded, updated_at: nowIso }),\n )\n .execute();\n }\n\n async deletePieceStoreValue(\n scope: string,\n scopeKey: string,\n key: string,\n ): Promise<void> {\n await this.db\n .deleteFrom(\"piece_store\")\n .where(\"scope\", \"=\", scope)\n .where(\"scope_key\", \"=\", scopeKey)\n .where(\"key\", \"=\", key)\n .execute();\n }\n\n // Every key one scope holds; for inspection and for tearing a workflow down.\n async listPieceStore(\n scope: string,\n scopeKey: string,\n ): Promise<Record<string, unknown>> {\n const rows = await this.db\n .selectFrom(\"piece_store\")\n .selectAll()\n .where(\"scope\", \"=\", scope)\n .where(\"scope_key\", \"=\", scopeKey)\n .execute();\n const out: Record<string, unknown> = {};\n for (const row of rows) {\n try {\n out[row.key] = JSON.parse(row.value);\n } catch {\n // Same reasoning as the single-key read above.\n }\n }\n return out;\n }\n\n async deletePieceStore(scope: string, scopeKey: string): Promise<void> {\n await this.db\n .deleteFrom(\"piece_store\")\n .where(\"scope\", \"=\", scope)\n .where(\"scope_key\", \"=\", scopeKey)\n .execute();\n }\n}\n","import type { WorkflowParkRow } from \"./store.js\";\n\n// Each park as the trigger lane leaves it once its queued tasks have run.\nexport class ParkState {\n private readonly parks = new Map<string, WorkflowParkRow>();\n // Written before the seed landed: the seed must not overwrite these.\n private readonly written = new Set<string>();\n private seeded = false;\n private seeding?: Promise<void>;\n\n constructor(\n private readonly load: () => Promise<\n readonly WorkflowParkRow[] | undefined\n >,\n ) {}\n\n async get(workflowId: string): Promise<WorkflowParkRow | undefined> {\n if (!this.seeded) {\n this.seeding ??= this.seed().finally(() => {\n this.seeding = undefined;\n });\n await this.seeding;\n }\n return this.parks.get(workflowId);\n }\n\n // Undefined while the seed has not covered this workflow.\n known(workflowId: string): { park?: WorkflowParkRow } | undefined {\n if (!this.seeded && !this.written.has(workflowId)) return undefined;\n return { park: this.parks.get(workflowId) };\n }\n\n set(park: WorkflowParkRow): void {\n this.parks.set(park.workflow_id, park);\n if (!this.seeded) this.written.add(park.workflow_id);\n }\n\n delete(workflowId: string): void {\n this.parks.delete(workflowId);\n if (!this.seeded) this.written.add(workflowId);\n }\n\n private async seed(): Promise<void> {\n const rows = await this.load();\n if (!rows) return;\n for (const row of rows) {\n if (!this.written.has(row.workflow_id)) {\n this.parks.set(row.workflow_id, row);\n }\n }\n this.written.clear();\n this.seeded = true;\n }\n}\n","// Sub-flows: Activepieces' Call Flow, Callable Flow and Return Response, served\n// in process. A piece's fetch to ctx.server.apiUrl arrives here as a host call.\nimport type { WorkflowState } from \"@powerhousedao/workflow/document-models/workflow\";\nimport {\n HOST_ORIGIN,\n type HostHttpRequest,\n type HostHttpResponse,\n} from \"../pieces/index.js\";\nimport { runnableDefinition } from \"./runnable.js\";\n\nexport {\n CALL_FLOW_ACTION,\n CALLABLE_FLOW_TRIGGER,\n isCallableFlow,\n SUBFLOWS_PIECE,\n} from \"@powerhousedao/pieces-framework/workflow\";\n\n// Activepieces' own header names (PARENT_RUN_ID_HEADER and its sibling).\nexport const PARENT_RUN_HEADER = \"ap-parent-run-id\";\nexport const FAIL_PARENT_HEADER = \"ap-fail-parent-on-failure\";\n\nconst WAITPOINTS_PATH = \"/v1/waitpoints/\";\n\n// Where Call Flow's resume URLs live: the host origin, served in process.\nexport const HOST_WAITPOINTS_URL = `${HOST_ORIGIN}/v1/waitpoints`;\n\n// Activepieces' PopulatedFlow, the shape `ctx.flows.list` answers with.\nexport interface PopulatedFlow {\n id: string;\n externalId: string;\n status: \"ENABLED\" | \"DISABLED\";\n version: {\n id: string;\n displayName: string;\n trigger: {\n type: \"PIECE_TRIGGER\" | \"EMPTY\";\n settings: {\n pieceName?: string;\n pieceVersion?: string;\n triggerName?: string;\n input: Record<string, unknown>;\n };\n };\n };\n}\n\nexport type HostRoute =\n | { kind: \"webhook\"; workflowId: string }\n | { kind: \"callback\"; token: string };\n\n// POST /v1/webhooks/:workflowId and POST /v1/waitpoints/:token.\nexport function hostRoute(request: HostHttpRequest): HostRoute | undefined {\n if (request.method.toUpperCase() !== \"POST\") return undefined;\n const { pathname } = new URL(request.path, HOST_ORIGIN);\n const [version, kind, id, ...rest] = pathname\n .split(\"/\")\n .filter(Boolean)\n .map(decodeURIComponent);\n if (version !== \"v1\" || !id || rest.length > 0) return undefined;\n if (kind === \"webhooks\") return { kind: \"webhook\", workflowId: id };\n if (kind === \"waitpoints\") return { kind: \"callback\", token: id };\n return undefined;\n}\n\nexport function hostBody(request: HostHttpRequest): unknown {\n if (request.body === undefined || request.body === \"\") return undefined;\n const type = request.headers[\"content-type\"] ?? \"\";\n if (!type.includes(\"json\")) return request.body;\n try {\n return JSON.parse(request.body) as unknown;\n } catch {\n return request.body;\n }\n}\n\nexport function jsonReply(status: number, body: unknown): HostHttpResponse {\n return {\n status,\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n };\n}\n\n// A resume URL this host minted, as the host origin serves it to a piece:\n// the callee's Return Response then resumes the caller in process.\nexport function localCallback(\n callbackUrl: string,\n resumeBaseUrl: string | undefined,\n): { url: string; token: string } | undefined {\n const fromHost = callbackUrl.startsWith(`${HOST_ORIGIN}${WAITPOINTS_PATH}`);\n const base = fromHost\n ? `${HOST_ORIGIN}${WAITPOINTS_PATH}`\n : resumeBaseUrl\n ? `${resumeBaseUrl.replace(/\\/+$/, \"\")}/`\n : undefined;\n if (!base || !callbackUrl.startsWith(base)) return undefined;\n const token = callbackUrl.slice(base.length).split(/[/?#]/)[0];\n if (!token) return undefined;\n return { url: `${HOST_ORIGIN}${WAITPOINTS_PATH}${token}`, token };\n}\n\nexport function populatedFlow(\n workflowId: string,\n state: WorkflowState,\n documentName: string | undefined,\n): PopulatedFlow {\n const runnable = runnableDefinition(state);\n const trigger = runnable.trigger;\n const config = trigger?.config;\n return {\n id: workflowId,\n externalId: workflowId,\n status:\n state.status === \"ENABLED\" && runnable.published ? \"ENABLED\" : \"DISABLED\",\n version: {\n id: `${workflowId}@${runnable.version}`,\n displayName: state.name || documentName || workflowId,\n trigger: trigger\n ? {\n type: \"PIECE_TRIGGER\",\n settings: {\n pieceName: trigger.pieceName,\n pieceVersion: trigger.pieceVersion,\n triggerName: trigger.triggerName,\n input:\n config && typeof config === \"object\" && !Array.isArray(config)\n ? (config as Record<string, unknown>)\n : {},\n },\n }\n : { type: \"EMPTY\", settings: { input: {} } },\n },\n };\n}\n","// Opaque keyset cursor over the run listing: base64url of [enqueued_at, id].\nimport type { RunKey } from \"./store.js\";\n\nexport class InvalidRunCursorError extends Error {\n constructor() {\n super(\"Invalid runs cursor\");\n this.name = \"InvalidRunCursorError\";\n }\n}\n\nexport function encodeRunCursor(key: RunKey): string {\n return Buffer.from(JSON.stringify([key.enqueuedAt, key.id])).toString(\n \"base64url\",\n );\n}\n\nexport function decodeRunCursor(cursor: string): RunKey {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf8\"));\n } catch {\n throw new InvalidRunCursorError();\n }\n if (\n !Array.isArray(parsed) ||\n parsed.length !== 2 ||\n typeof parsed[0] !== \"string\" ||\n typeof parsed[1] !== \"string\"\n ) {\n throw new InvalidRunCursorError();\n }\n return { enqueuedAt: parsed[0], id: parsed[1] };\n}\n","// One poller per owning runtime: wakes due DELAY waitpoints and expires\n// overdue ones in batches, on a single timer armed for the next due time.\nimport type { ILogger } from \"document-model\";\nimport type { EndedWait, WorkflowRunStore } from \"./store.js\";\n\nexport const WAITPOINT_BATCH = 100;\n// The timer never sleeps longer, so a missed nudge costs at most this.\nexport const WAITPOINT_POLL_MAX_MS = 5 * 60_000;\nconst WAITPOINT_RETRY_MS = 30_000;\n// How stale the suspended-runs gauge may read before a scrape recounts.\nconst SUSPENDED_COUNT_MS = 30_000;\n\nexport interface WaitpointPollerDeps {\n store: () => Promise<WorkflowRunStore | undefined>;\n // Re-enters a run holding a COMPLETED waitpoint, through admission.\n resume: (runId: string) => Promise<void>;\n // Told of a WAITING run the store ended: its wait expired or is stranded.\n ended: (end: EndedWait) => Promise<void>;\n logger: Pick<ILogger, \"warn\">;\n // Rows per claim; WAITPOINT_BATCH by default.\n batch?: number;\n}\n\nexport class WaitpointPoller {\n private running = false;\n private polling = false;\n private again = false;\n private timer?: ReturnType<typeof setTimeout>;\n private timerAt?: number;\n // A nudge that landed while a poll ran; the poll's own arm honours it.\n private nudged?: number;\n private suspended = 0;\n private suspendedAt = 0;\n private counting = false;\n\n constructor(private readonly deps: WaitpointPollerDeps) {}\n\n get active(): boolean {\n return this.running;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n void this.poll();\n }\n\n stop(): void {\n this.running = false;\n clearTimeout(this.timer);\n this.timer = undefined;\n this.timerAt = undefined;\n this.nudged = undefined;\n }\n\n // A waitpoint due sooner than the armed timer pulls it in.\n nudge(dueIso: string): void {\n if (!this.running) return;\n const due = Date.parse(dueIso);\n if (Number.isNaN(due)) return;\n if (this.polling) {\n this.nudged = Math.min(this.nudged ?? Infinity, due);\n return;\n }\n if (this.timerAt !== undefined && due >= this.timerAt) return;\n this.arm(due);\n }\n\n // WAITING runs as last counted; a stale count refreshes in the background.\n suspendedRuns(): number {\n if (Date.now() - this.suspendedAt > SUSPENDED_COUNT_MS) {\n void this.count();\n }\n return this.suspended;\n }\n\n async count(store?: WorkflowRunStore): Promise<number> {\n if (this.counting) return this.suspended;\n this.counting = true;\n try {\n const journal = store ?? (await this.deps.store());\n if (journal) {\n this.suspended = await journal.countWaitingRuns();\n this.suspendedAt = Date.now();\n }\n } catch (error) {\n this.deps.logger.warn(\"Counting suspended runs failed: @error\", error);\n } finally {\n this.counting = false;\n }\n return this.suspended;\n }\n\n /** One pass: due delays and held resumes deliver, overdue waits expire, the\n * timer re-arms. */\n async poll(): Promise<void> {\n if (!this.running) return;\n if (this.polling) {\n this.again = true;\n return;\n }\n this.polling = true;\n let next = Date.now() + WAITPOINT_RETRY_MS;\n try {\n const store = await this.deps.store();\n if (!store) return;\n const batch = this.deps.batch ?? WAITPOINT_BATCH;\n do {\n this.again = false;\n const now = new Date().toISOString();\n const due = await store.claimDueDelayWaitpoints(now, batch);\n for (const runId of new Set(due.map((row) => row.run_id))) {\n await this.deps.resume(runId);\n }\n const { expired, ended } = await store.expireDueWaitpoints(now, batch);\n // A run whose wait closed without ending it, e.g. after a crash.\n const stranded = await store.endStrandedWaits(batch);\n for (const end of [...ended, ...stranded]) await this.deps.ended(end);\n if (\n due.length === batch ||\n expired.length === batch ||\n stranded.length === batch\n ) {\n this.again = true;\n }\n } while (this.again && this.active);\n // Redelivers a resume whose first delivery was skipped or failed; one\n // already in flight is a no-op, as the claim admits only one leg.\n for (const runId of await store.heldRunIds()) {\n await this.deps.resume(runId);\n }\n await this.count(store);\n const [delay, expiry] = await Promise.all([\n store.nextDelayDue(),\n store.nextExpiry(),\n ]);\n next = Math.min(\n delay ? Date.parse(delay) : Infinity,\n expiry ? Date.parse(expiry) : Infinity,\n );\n } catch (error) {\n this.deps.logger.warn(\"Waitpoint poll failed: @error\", error);\n } finally {\n this.polling = false;\n if (this.nudged !== undefined) next = Math.min(next, this.nudged);\n this.nudged = undefined;\n if (this.active) this.arm(next);\n }\n }\n\n private arm(due: number): void {\n clearTimeout(this.timer);\n const delay = Math.min(\n Math.max(Number.isFinite(due) ? due - Date.now() : Infinity, 0),\n WAITPOINT_POLL_MAX_MS,\n );\n this.timerAt = Date.now() + delay;\n this.timer = setTimeout(() => {\n this.timer = undefined;\n this.timerAt = undefined;\n void this.poll();\n }, delay);\n this.timer.unref();\n }\n}\n","// `policy.concurrency`, enforced: how many runs of ONE workflow may execute\n// at once, and what happens to a firing that arrives while the limit is full.\n//\n// Process-local, and correctly so: workflow execution is a singleton pinned to\n// one reactor (see singleton-lease.ts), so this process IS the deployment's\n// run set. A gate in the database would be a second claim on the same fact.\nimport type { EffectiveRunPolicy } from \"./policy.js\";\nimport { concurrencyLimit } from \"./policy.js\";\n\ninterface Lane {\n active: number;\n // Resolved true with the slot handed over, false when the gate closed.\n waiting: ((admitted: boolean) => void)[];\n}\n\nconst CLOSED_REASON =\n \"Skipped: the workflow runtime shut down while this firing waited\";\n\n/** What a firing may do. */\nexport type GateAdmission =\n // `waited`: it queued, so what it read before admission may be stale.\n | { admitted: true; waited: boolean; release: () => void }\n // SINGLETON, and a run is already going: this firing is dropped, not queued.\n // Or the queue is full: see MAX_QUEUED_FIRINGS. Or the runtime shut down.\n | {\n admitted: false;\n reason: string;\n refusal: \"singleton\" | \"queue-full\" | \"closed\";\n };\n\nexport const QUEUE_DEPTH_ENV = \"PH_WORKFLOWS_MAX_QUEUED_FIRINGS\";\n\n/**\n * How many firings of ONE workflow may wait for a slot.\n *\n * QUEUE means latency, not failure — but an unbounded queue means neither. A\n * document-event trigger on a busy type can enqueue faster than the workflow\n * runs for as long as the reactor is up, and every waiter holds its trigger\n * payload, its promise and (once admitted) a worker slot. The lane grows\n * without bound until the process dies, and nothing in the journal says why:\n * each waiting firing is a PENDING run row nobody is executing.\n *\n * So the queue has a depth, and a firing that overflows it is journaled\n * CANCELLED exactly as a SINGLETON refusal is — visible, rather than the\n * process-killing backlog it was.\n */\nexport const DEFAULT_MAX_QUEUED_FIRINGS = 100;\n\nexport function maxQueuedFirings(env: NodeJS.ProcessEnv = process.env): number {\n const raw = Number(env[QUEUE_DEPTH_ENV]);\n return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_MAX_QUEUED_FIRINGS;\n}\n\nexport class WorkflowRunGate {\n private readonly lanes = new Map<string, Lane>();\n private closed = false;\n\n // Read once per gate: an operator sets it at boot, and a lane that changed\n // its bound mid-flight would admit and refuse on different rules.\n private readonly maxQueued: number;\n\n constructor(options: { maxQueued?: number } = {}) {\n this.maxQueued = options.maxQueued ?? maxQueuedFirings();\n }\n\n /** Runs of this workflow executing right now. */\n active(workflowId: string): number {\n return this.lanes.get(workflowId)?.active ?? 0;\n }\n\n /** Firings of this workflow waiting for a slot. */\n waiting(workflowId: string): number {\n return this.lanes.get(workflowId)?.waiting.length ?? 0;\n }\n\n /**\n * Takes a slot for one run.\n *\n * - **PARALLEL** with no `maxParallelRuns`, or no policy at all: no gate,\n * so an unbounded workflow's hot path costs nothing. Not the default: a\n * workflow document starts as QUEUE.\n * - **PARALLEL** with a bound, and **QUEUE**: waits, first come first\n * served. Latency, not failure — which is what QUEUE means, up to\n * {@link DEFAULT_MAX_QUEUED_FIRINGS} waiters. Past that the queue is full\n * and the firing is refused, so the caller journals it CANCELLED rather\n * than growing a backlog nothing bounds.\n * - **SINGLETON**: refused outright while a run is active. The caller\n * journals the refusal rather than dropping it silently, because a firing\n * that vanished is indistinguishable from a trigger that never fired.\n *\n * A `resume` is a waiting run's next leg, not a new firing: it queues for\n * the slot under every policy, past the queue depth too.\n */\n async admit(\n workflowId: string,\n policy: EffectiveRunPolicy,\n onQueue?: () => void,\n options: { resume?: boolean } = {},\n ): Promise<GateAdmission> {\n if (this.closed)\n return { admitted: false, reason: CLOSED_REASON, refusal: \"closed\" };\n const limit = concurrencyLimit(policy);\n if (limit === null) {\n return { admitted: true, waited: false, release: () => undefined };\n }\n\n const lane = this.lanes.get(workflowId) ?? { active: 0, waiting: [] };\n this.lanes.set(workflowId, lane);\n let waited = false;\n\n if (lane.active >= limit) {\n if (policy.concurrency === \"SINGLETON\" && !options.resume) {\n this.forgetIfIdle(workflowId, lane);\n return {\n admitted: false,\n refusal: \"singleton\",\n reason:\n \"Skipped: this workflow's concurrency is SINGLETON and a run was \" +\n \"already executing\",\n };\n }\n if (!options.resume && lane.waiting.length >= this.maxQueued) {\n return {\n admitted: false,\n refusal: \"queue-full\",\n reason:\n `Skipped: ${lane.waiting.length} firings of this workflow are ` +\n `already waiting for a slot, which is its queue depth ` +\n `(${this.maxQueued}; raise ${QUEUE_DEPTH_ENV} to allow more)`,\n };\n }\n onQueue?.();\n // The release that wakes this counts the run in on its behalf, so the\n // slot is reserved across the await and a later arrival cannot take it.\n const handed = await new Promise<boolean>((resolve) =>\n lane.waiting.push(resolve),\n );\n if (!handed)\n return { admitted: false, reason: CLOSED_REASON, refusal: \"closed\" };\n waited = true;\n } else {\n lane.active += 1;\n }\n\n let released = false;\n return {\n admitted: true,\n waited,\n release: () => {\n if (released) return;\n released = true;\n lane.active -= 1;\n // Handed straight to the next waiter rather than counted down and up\n // again, so a slot freed with someone waiting cannot be taken by a\n // later arrival.\n const next = lane.waiting.shift();\n if (next) {\n lane.active += 1;\n next(true);\n return;\n }\n this.forgetIfIdle(workflowId, lane);\n },\n };\n }\n\n /** Refuses every waiting and later firing: a shut-down runtime runs none. */\n close(): void {\n this.closed = true;\n for (const lane of this.lanes.values()) {\n for (const waiter of lane.waiting.splice(0)) waiter(false);\n }\n }\n\n private forgetIfIdle(workflowId: string, lane: Lane): void {\n if (lane.active === 0 && lane.waiting.length === 0) {\n this.lanes.delete(workflowId);\n }\n }\n}\n","import { PieceWorkerDisposedError } from \"../pieces/index.js\";\n\n/** A firing refused because this runtime has shut down: retryable elsewhere. */\nexport class WorkflowRuntimeClosedError extends Error {\n constructor(readonly workflowId: string) {\n super(\n `Workflow ${workflowId} was not run: this workflow runtime has shut down`,\n );\n this.name = \"WorkflowRuntimeClosedError\";\n }\n}\n\n// `cause` is what the stop cut short, a hook it killed in flight included.\nexport class TriggerSupervisorStoppedError extends Error {\n constructor(options?: { cause?: unknown }) {\n super(\"The trigger supervisor has stopped\", options);\n this.name = \"TriggerSupervisorStoppedError\";\n }\n}\n\n// Not PieceWorkerExitError: a hook killed in flight may have checkpointed.\nexport function isShutdownRefusal(error: unknown): boolean {\n return (\n error instanceof TriggerSupervisorStoppedError ||\n error instanceof WorkflowRuntimeClosedError ||\n error instanceof PieceWorkerDisposedError\n );\n}\n","// Admits runs across all workflows, after each workflow's own run gate (ADR\n// 0007 §5): a cap on runs in flight, and a hold while the main thread is busy.\nimport type { EventLoopReading } from \"./event-loop.js\";\nimport { WorkflowRuntimeClosedError } from \"./shutdown.js\";\n\nexport const DEFAULT_ADMIT_MAX_ELU = 0.8;\n\nexport interface RunDispatcherOptions {\n maxInFlight: number;\n // Event-loop utilization above which no new run is admitted.\n maxElu?: number;\n loop: EventLoopReading;\n}\n\nexport interface RunDispatcherStats {\n inFlight: number;\n waiting: number;\n}\n\ninterface Waiter {\n workflowId: string;\n resolve: (release: () => void) => void;\n reject: (error: unknown) => void;\n}\n\nexport class RunDispatcher {\n private readonly maxInFlight: number;\n private readonly maxElu: number;\n private readonly loop: EventLoopReading;\n private readonly waiters: Waiter[] = [];\n private inFlight = 0;\n private closed = false;\n private readonly unsubscribe: () => void;\n\n constructor(options: RunDispatcherOptions) {\n this.maxInFlight = Math.max(1, Math.trunc(options.maxInFlight));\n this.maxElu = options.maxElu ?? DEFAULT_ADMIT_MAX_ELU;\n this.loop = options.loop;\n // A busy loop that eases admits whoever waited on it.\n this.unsubscribe = this.loop.onSample(() => this.drain());\n }\n\n // Resolves with the release once the run may start, in arrival order.\n // `onQueue` runs synchronously when the run has to wait.\n admit(workflowId: string, onQueue?: () => void): Promise<() => void> {\n if (this.closed) {\n return Promise.reject(new WorkflowRuntimeClosedError(workflowId));\n }\n if (this.waiters.length === 0 && this.room()) {\n return Promise.resolve(this.take());\n }\n onQueue?.();\n return new Promise((resolve, reject) => {\n this.waiters.push({ workflowId, resolve, reject });\n });\n }\n\n stats(): RunDispatcherStats {\n return { inFlight: this.inFlight, waiting: this.waiters.length };\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n this.unsubscribe();\n for (const waiter of this.waiters.splice(0)) {\n waiter.reject(new WorkflowRuntimeClosedError(waiter.workflowId));\n }\n }\n\n // A run always gets in when none is running, so a loop that never eases\n // (PGlite flushing on it) still makes progress.\n private room(): boolean {\n if (this.inFlight === 0) return true;\n return (\n this.inFlight < this.maxInFlight && this.loop.utilization() <= this.maxElu\n );\n }\n\n private take(): () => void {\n this.inFlight++;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.inFlight--;\n this.drain();\n };\n }\n\n private drain(): void {\n while (this.waiters.length > 0 && !this.closed && this.room()) {\n this.waiters.shift()!.resolve(this.take());\n }\n }\n}\n","// The host main thread's event-loop utilization, sampled each second. It is\n// what bounds throughput (ADR 0007), so the run dispatcher admits against it.\nimport { performance } from \"node:perf_hooks\";\n\nconst SAMPLE_MS = 1_000;\n\nexport interface EventLoopReading {\n // Share of the last sample the loop was busy, 0 to 1.\n utilization(): number;\n // Called after each sample; returns the unsubscribe.\n onSample(listener: () => void): () => void;\n}\n\nexport class EventLoopMonitor implements EventLoopReading {\n private last = performance.eventLoopUtilization();\n private current = 0;\n private timer: NodeJS.Timeout | undefined;\n private readonly listeners = new Set<() => void>();\n\n start(): void {\n if (this.timer) return;\n this.last = performance.eventLoopUtilization();\n this.timer = setInterval(() => this.sample(), SAMPLE_MS);\n this.timer.unref();\n }\n\n stop(): void {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n\n utilization(): number {\n return this.current;\n }\n\n onSample(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private sample(): void {\n const now = performance.eventLoopUtilization();\n this.current = performance.eventLoopUtilization(now, this.last).utilization;\n this.last = now;\n for (const listener of this.listeners) listener();\n }\n}\n","// Pruning of the run journal. ON by default: finished runs older than the\n// window go with their step executions and run documents.\n//\n// It used to be opt-in, which meant unbounded growth for every host that did\n// not know to set the variable — measured at 743MB in three days on distyra\n// (multi-reactor plan, backlog item 7). A journal is diagnostic, so a default\n// window is the honest setting and \"keep everything\" is the choice an operator\n// makes deliberately. `STEP_PAYLOAD_MAX_BYTES` bounds row WIDTH; this bounds\n// row COUNT, and the two belong together.\nimport type { WorkflowRunStore } from \"./store.js\";\n\nexport const RUN_RETENTION_ENV = \"PH_WORKFLOWS_RUN_RETENTION_DAYS\";\nexport const RETENTION_SWEEP_INTERVAL_MS = 60 * 60_000;\nconst DAY_MS = 24 * 60 * 60_000;\n\n/** How long a finished run is kept when nothing says otherwise. */\nexport const DEFAULT_RUN_RETENTION_DAYS = 30;\n\n/** The spellings that turn retention OFF, compared case-insensitively after\n * trimming. Wider than `0` because \"off\" and \"never\" are what an operator\n * reaches for, and a variable that silently keeps pruning because they wrote\n * one of those is the worst outcome available. */\nexport const RETENTION_OFF_SPELLINGS: readonly string[] = [\n \"0\",\n \"off\",\n \"never\",\n \"false\",\n \"none\",\n];\n\n/**\n * The retention window, or undefined when an operator turned it off.\n *\n * Unset means the default. An unparseable value also means the default rather\n * than silently disabling: the variable's purpose is a bound, and a typo must\n * not remove one.\n */\nexport function runRetentionMs(\n env: Record<string, string | undefined> = process.env,\n): number | undefined {\n const raw = env[RUN_RETENTION_ENV]?.trim();\n if (\n raw !== undefined &&\n RETENTION_OFF_SPELLINGS.includes(raw.toLowerCase())\n ) {\n return undefined;\n }\n const days = Number(raw);\n return (days > 0 ? days : DEFAULT_RUN_RETENTION_DAYS) * DAY_MS;\n}\n\nexport interface RetentionSweep {\n runs: number;\n dedupeKeys: number;\n}\n\n// `dedupeTtlMs` is the longest TTL any claim uses; older keys are inert.\nexport async function sweepRetention(\n store: WorkflowRunStore,\n options: { retentionMs: number; dedupeTtlMs: number; now?: Date },\n): Promise<RetentionSweep> {\n const now = (options.now ?? new Date()).getTime();\n const runs = await store.pruneFinishedRuns(\n new Date(now - options.retentionMs).toISOString(),\n );\n const dedupeKeys = await store.pruneDedupe(\n new Date(now - options.dedupeTtlMs).toISOString(),\n );\n return { runs, dedupeKeys };\n}\n","// What the runtime hands the supervisor for one workflow, plus the pure\n// helpers over it. Split out so drivers need not import the supervisor.\nimport {\n blockKey,\n type BlockIdentity,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport { blockLabel, type RecordedSchedule } from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport { createHash } from \"node:crypto\";\nimport { cronIntervalMs, MIN_SCHEDULE_INTERVAL_MS } from \"./schedule.js\";\nimport type { TriggerStateRow } from \"./store.js\";\n\nconst logger = childLogger([\"workflow\", \"trigger-binding\"]);\n\nexport const MIN_INTERVAL_MS = MIN_SCHEDULE_INTERVAL_MS;\n\nexport interface PieceTriggerBinding {\n kind?: \"piece\";\n workflowId: string;\n // The trigger as the workflow pins it.\n block: BlockRef;\n packageName: string;\n version: string;\n triggerName: string;\n config: Record<string, unknown>;\n connectionId?: string | null;\n reactorConnectionId?: string | null;\n // Author's poll cadence, from the trigger's pollEverySeconds. Overrides both\n // the piece's own setSchedule and the runtime default; the 60s floor holds.\n pollIntervalMs?: number;\n // How the piece expects to be fed. WEBHOOK-strategy triggers are never\n // polled: their run hook needs the request, and polling would call it blind.\n delivery?: \"poll\" | \"webhook\";\n}\n\n// The core schedule trigger: no piece hooks; next_poll_at is the next fire time.\nexport interface ScheduleTriggerBinding {\n kind: \"schedule\";\n workflowId: string;\n block: BlockRef;\n config: Record<string, unknown>;\n}\n\nexport type TriggerBinding = PieceTriggerBinding | ScheduleTriggerBinding;\n\nexport const SCHEDULE_TRIGGER_KIND = \"schedule\";\n\n// Which driver owns a binding: the one place the union is discriminated.\nexport type TriggerDeliveryKind = \"schedule\" | \"piece-poll\" | \"piece-webhook\";\n\nexport function deliveryKindFor(binding: TriggerBinding): TriggerDeliveryKind {\n if (binding.kind === \"schedule\") return \"schedule\";\n return binding.delivery === \"webhook\" ? \"piece-webhook\" : \"piece-poll\";\n}\n\n// Narrowing assertions stating each driver's precondition. Reaching one means\n// the binding was routed to the wrong driver, which is a bug, not input.\nexport function asPiece(binding: TriggerBinding): PieceTriggerBinding {\n if (binding.kind === \"schedule\") {\n throw new Error(\n `Expected a piece binding, got ${blockLabel(binding.block)}`,\n );\n }\n return binding;\n}\n\nexport function asSchedule(binding: TriggerBinding): ScheduleTriggerBinding {\n if (binding.kind !== \"schedule\") {\n throw new Error(\n `Expected a schedule binding, got ${blockLabel(binding.block)}`,\n );\n }\n return binding;\n}\n\nexport function configHash(block: BlockIdentity, config: unknown): string {\n return createHash(\"sha256\")\n .update(blockKey(block))\n .update(JSON.stringify(config ?? {}))\n .digest(\"hex\")\n .slice(0, 16);\n}\n\n// A run's trigger kind for a piece trigger: \"piece:<pieceName>:<triggerName>\".\n// A package name never holds a colon, so the first one splits it.\nexport function pieceTriggerKind(block: BlockIdentity): string {\n return `piece:${block.pieceName}:${block.name}`;\n}\n\n// The poll cadence setSchedule asked for: the named interval, or the gap between\n// the cron's next two runs (60s floor); an unparseable cron uses the default.\nexport function intervalFromSchedules(\n schedules: RecordedSchedule[] | undefined,\n defaultMs: number,\n): number {\n const schedule = schedules?.at(-1);\n if (!schedule) return Math.max(defaultMs, MIN_INTERVAL_MS);\n if (\"intervalMs\" in schedule) {\n return Math.max(schedule.intervalMs, MIN_INTERVAL_MS);\n }\n const cron = schedule.cronExpression;\n const intervalMs = cronIntervalMs(cron);\n if (intervalMs === undefined) {\n logger.warn(\n 'Unsupported setSchedule cron \"@cron\"; using the default',\n cron,\n );\n return Math.max(defaultMs, MIN_INTERVAL_MS);\n }\n return intervalMs;\n}\n\n// The cadence to poll a piece trigger at: the author's override when set,\n// else what the piece asked for, else the runtime default. Never below the floor.\nexport function pollIntervalFor(\n binding: PieceTriggerBinding,\n schedules: RecordedSchedule[] | undefined,\n defaultMs: number,\n): number {\n if (binding.pollIntervalMs !== undefined) {\n return Math.max(binding.pollIntervalMs, MIN_INTERVAL_MS);\n }\n return intervalFromSchedules(schedules, defaultMs);\n}\n\n// STALE: store_state is vestigial — the migration in store.ts blanks it and\n// the supervisor only ever writes \"{}\". This always returns {} on a live row.\n\n// Only trigger-drivers.ts calls it, and only tests call that. Wiring that path\n// into service.ts without converting it to piece_store restarts every cursor.\nexport function parseStoreState(row: TriggerStateRow): Record<string, unknown> {\n try {\n return JSON.parse(row.store_state) as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n","// Timer-driven trigger supervisor: owns piece-trigger lifecycle (enable/\n// disable, poll cursors) and the core schedule trigger's fires.\n\n// Scheduling state lives in trigger_state; whatever a hook writes through\n// ctx.store lives in piece_store, beside what actions write.\nimport {\n blockKey,\n type BlockIdentity,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n checkTriggerStrategy,\n type TriggerDelivery,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport { isCallableFlow } from \"./subflows.js\";\nimport {\n blockLabel,\n bundleResolver,\n canonicalJson,\n checkDynamicProperties,\n DEFAULT_EGRESS_POLICY,\n hashOf,\n DynamicPropertiesError,\n extractDedupeKey,\n flowsHandlers,\n pieceModuleRef,\n PieceWorker,\n type IPieceWorker,\n PieceWorkerError,\n secretsFor,\n storeHandlers,\n type BlockMatch,\n type ConnectionRequest,\n type PieceDescriptor,\n type PieceOrigin,\n type PieceTarget,\n type EgressPolicy,\n type FlowsPort,\n type PieceResolver,\n type PieceWorkerResult,\n type ModelManifestSource,\n type PropertySettingDef,\n type ReactorTap,\n type RecordedSchedule,\n type TriggerHookRequest,\n type TriggerRenew,\n} from \"../pieces/index.js\";\nimport type { WorkflowTelemetry } from \"../telemetry.js\";\nimport type { RunUser } from \"./run-scope.js\";\nimport { childLogger } from \"document-model\";\nimport {\n cronIntervalMs,\n DEFAULT_TIMEZONE,\n MIN_SCHEDULE_INTERVAL_MS,\n nextFireAt,\n parseScheduleConfig,\n rescheduleAfterFire,\n schedulePayload,\n} from \"./schedule.js\";\nimport { SCHEDULE_BLOCK } from \"./core-blocks.js\";\nimport { ParkState } from \"./park-state.js\";\nimport {\n isShutdownRefusal,\n TriggerSupervisorStoppedError,\n} from \"./shutdown.js\";\nimport { PARKED_TRIGGER_STATUS } from \"./policy.js\";\nimport { pieceTriggerKind } from \"./trigger-binding.js\";\nimport {\n createPieceStorePort,\n PROJECT_SCOPE_KEY,\n testPartitionKey,\n} from \"./piece-store-port.js\";\nimport {\n triggerBlockColumns,\n triggerRowBlock,\n type PollSuccess,\n type RunParent,\n type TriggerStateRow,\n workflowParkRow,\n type WorkflowParkRow,\n type WorkflowRunStore,\n} from \"./store.js\";\n\nconst logger = childLogger([\"workflow\", \"trigger-supervisor\"]);\n\nexport interface PieceTriggerBinding {\n kind?: \"piece\";\n workflowId: string;\n // The trigger as the workflow pins it.\n block: BlockRef;\n packageName: string;\n version: string;\n triggerName: string;\n config: Record<string, unknown>;\n connectionId?: string | null;\n // A REACTOR connection, for a trigger that declares requireReactor.\n reactorConnectionId?: string | null;\n // Author's poll cadence, from the trigger's pollEverySeconds. Overrides both\n // the piece's own setSchedule and the runtime default; the 60s floor holds.\n pollIntervalMs?: number;\n // DYNAMIC props' resolved children, checked before any hook but onDisable.\n propertySettings?: PropertySettingDef[];\n // Where `version` comes from and how it matched the pin.\n source?: PieceOrigin;\n match?: BlockMatch;\n note?: string;\n}\n\nfunction targetOf(binding: PieceTriggerBinding): PieceTarget {\n return {\n name: binding.packageName,\n version: binding.version,\n ...(binding.source ? { source: binding.source } : {}),\n };\n}\n\nfunction pieceColumns(\n binding?: PieceTriggerBinding,\n): Pick<\n TriggerStateRow,\n \"piece_version\" | \"piece_source\" | \"version_match\" | \"version_note\"\n> {\n return {\n piece_version: binding?.version ?? null,\n piece_source: binding?.source ?? null,\n version_match: binding?.match ?? null,\n version_note: binding?.note ?? null,\n };\n}\n\n// The core schedule trigger: no piece hooks; next_poll_at is the next fire time.\nexport interface ScheduleTriggerBinding {\n kind: \"schedule\";\n workflowId: string;\n block: BlockRef;\n config: Record<string, unknown>;\n}\n\nexport type TriggerBinding = PieceTriggerBinding | ScheduleTriggerBinding;\n\nexport const SCHEDULE_TRIGGER_KIND = \"schedule\";\n\nexport interface TriggerSupervisorOptions {\n store: () => Promise<WorkflowRunStore | undefined>;\n // Hooks a tick runs at once (polls, renewals, enable retries); the trigger\n // children that serve them. Defaults to 1.\n hookConcurrency?: number;\n // Shared with the host, which reads parks off the lane.\n parks?: ParkState;\n resolveAuth: (\n connectionId: string | null | undefined,\n request?: ConnectionRequest,\n ) => Promise<unknown>;\n // Every lane firing is journaled first; `runId` is its PENDING run, to adopt.\n fire: (\n workflowId: string,\n payload: unknown,\n kind: string,\n runId: string,\n ) => void;\n // True while a workflow cannot start another run (its serialised slots are\n // taken by firings that have not settled). Its due poll then stays due and\n // is looked at again next tick, rather than handing out work that could\n // only wait in the queue. Unset: every due poll runs.\n pollHeld?: (workflowId: string) => boolean;\n cacheDir: string;\n // Where a trigger's piece comes from. Defaults to fetching into cacheDir,\n // so a host that ships pieces in a package passes its own.\n resolver?: PieceResolver;\n worker?: IPieceWorker;\n // Sent to the supervisor's own worker; a supplied worker brings its own.\n models?: ModelManifestSource;\n // Traces the supervisor's own worker, as models above.\n telemetry?: WorkflowTelemetry;\n // ctx.reactor for a trigger that declares requireReactor. `runUser` is set\n // for a design-time test, which acts as the caller.\n reactorAccess?: (\n binding: PieceTriggerBinding,\n requireReactor: \"read\" | \"write\",\n runUser: RunUser | null | undefined,\n ) => Promise<ReactorTap>;\n // Where a trigger's piece may connect to. Left unset it is the default\n // policy, which refuses private address space; `null` lifts it entirely.\n egress?: EgressPolicy | null;\n tickMs?: number;\n defaultIntervalMs?: number;\n hookTimeoutMs?: number;\n // The endpoint a WEBHOOK-strategy piece registers with its provider, minted\n // per workflow by the reactor's webhook service. Without one, such a trigger\n // refuses to enable rather than registering a URL nothing can reach.\n webhookUrlFor?: (workflowId: string) => Promise<string | undefined>;\n // ctx.flows and ctx.server for a hook; absent, both throw.\n flowsFor?: (workflowId: string, runId?: string) => FlowsPort | undefined;\n // How often a webhook trigger reconciles by polling anyway. A provider that\n // drops a delivery — paperless never retries a transport error — would\n // otherwise lose the event for good.\n reconcileIntervalMs?: number;\n // Clock override for tests; defaults to the wall clock.\n now?: () => Date;\n}\n\nconst MIN_INTERVAL_MS = MIN_SCHEDULE_INTERVAL_MS;\n// What a trigger polls at when neither the workflow nor the piece says.\nexport const DEFAULT_POLL_INTERVAL_MS = 60_000;\nconst MAX_BACKOFF_MS = 30 * 60_000;\nconst DEDUPE_TTL_MS = 30_000;\nconst REDELIVERED_REASON =\n \"Redelivered: the trigger stopped before firing this item and put its cursor back, so the next poll delivers it again\";\n// Memoized: the first call's runs are cancelled in the cursor's own write.\ntype Rewind = (redelivered?: string[]) => Promise<boolean>;\nconst DEFAULT_RECONCILE_INTERVAL_MS = 15 * 60_000;\n// What a failed onRenew backs off from; the next cron slot caps the wait.\nconst RENEW_RETRY_BASE_MS = 60_000;\n\nfunction isSchedule(\n binding: TriggerBinding,\n): binding is ScheduleTriggerBinding {\n return binding.kind === \"schedule\";\n}\n\n// Keyed on the version-free block and canonical config: re-pinning or a\n// reordered config is the same trigger, and keeps its cursor.\nexport function configHash(block: BlockIdentity, config: unknown): string {\n return hashOf(blockKey(block), canonicalJson(config ?? {}));\n}\n\n// The poll cadence setSchedule asked for: the named interval, or the gap between\n// the cron's next two runs (60s floor); an unparseable cron uses the default.\nexport function intervalFromSchedules(\n schedules: RecordedSchedule[] | undefined,\n defaultMs: number,\n): number {\n const schedule = schedules?.at(-1);\n if (!schedule) return Math.max(defaultMs, MIN_INTERVAL_MS);\n if (\"intervalMs\" in schedule) {\n return Math.max(schedule.intervalMs, MIN_INTERVAL_MS);\n }\n const cron = schedule.cronExpression;\n const intervalMs = cronIntervalMs(cron);\n if (intervalMs === undefined) {\n logger.warn(\n 'Unsupported setSchedule cron \"@cron\"; using the default',\n cron,\n );\n return Math.max(defaultMs, MIN_INTERVAL_MS);\n }\n return intervalMs;\n}\n\n// The cadence to poll a piece trigger at: the author's override when set,\n// else what the piece asked for, else the runtime default. Never below the floor.\nexport function pollIntervalFor(\n binding: PieceTriggerBinding,\n schedules: RecordedSchedule[] | undefined,\n defaultMs: number,\n): number {\n if (binding.pollIntervalMs !== undefined) {\n return Math.max(binding.pollIntervalMs, MIN_INTERVAL_MS);\n }\n return intervalFromSchedules(schedules, defaultMs);\n}\n\n// Trigger store state lives in piece_store now, beside the actions'. The\n// column is written but never read: see MIGRATION in store.ts on rollback.\nconst VESTIGIAL_STORE_STATE = \"{}\";\n\n// Raised where the journal is first found missing, rather than deeper: every\n// caller logs it, and a silent return here reads to them as success.\nexport class MissingJournalError extends Error {\n constructor(what: string) {\n super(`${what} needs a run journal, and none is configured`);\n this.name = \"MissingJournalError\";\n }\n}\n\n// A failure the operator has to fix: retrying it only burns cycles and buries\n// the real error under a growing failure count.\nexport class TriggerConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TriggerConfigError\";\n }\n}\n\nexport { isShutdownRefusal, TriggerSupervisorStoppedError };\n\n// Everything a piece throws looks alike once it crosses the worker boundary —\n// an expired token and a timeout are both name/message.\n\n// So only failures we can name structurally park; the rest retry.\nfunction isPermanentFailure(error: unknown): boolean {\n if (error instanceof TriggerConfigError) return true;\n if (error instanceof DynamicPropertiesError) return true;\n return (\n error instanceof PieceWorkerError &&\n (error.serialized.unsupportedMember !== undefined ||\n error.serialized.unsupportedFeature !== undefined ||\n error.serialized.invalidProps !== undefined)\n );\n}\n\ninterface EnableRetry {\n // Epoch ms of the next attempt.\n at: number;\n failures: number;\n // The last attempt reached onEnable, so the provider may be holding a\n // registration the next attempt has to release before making another.\n release: boolean;\n}\n\n// Same shape the poll path backs off with, so a trigger that cannot enable and\n// one that cannot poll retreat at the same rate and to the same ceiling.\nfunction backoffMs(intervalMs: number, failures: number): number {\n return Math.min(intervalMs * 2 ** failures, MAX_BACKOFF_MS);\n}\n\n// Renewal crons run in UTC, as upstream schedules them.\nfunction nextRenewAt(renew: TriggerRenew, from: Date): Date {\n return nextFireAt(\n { mode: \"cron\", cron: renew.cronExpression, timezone: DEFAULT_TIMEZONE },\n from,\n );\n}\n\ninterface TriggerRuntime {\n delivery: TriggerDelivery;\n // Set for a WEBHOOK trigger whose subscription the provider expires.\n renew?: TriggerRenew;\n}\n\nexport class TriggerSupervisor {\n private readonly bindings = new Map<string, TriggerBinding>();\n private readonly worker: IPieceWorker;\n private readonly tickMs: number;\n private readonly defaultIntervalMs: number;\n private readonly hookTimeoutMs: number;\n private readonly now: () => Date;\n private readonly egress: EgressPolicy | undefined;\n private readonly parks: ParkState;\n private timer?: NodeJS.Timeout;\n // One lane per workflow: its enable, disable, park, hooks and polls never\n // interleave, and a slow hook delays only its own workflow (ADR 0007 §6).\n private readonly lanes = new Map<string, Promise<unknown>>();\n // Workflows with tick work in flight, skipped by the next tick until it ends.\n private readonly ticked = new Set<string>();\n // Hooks the tick runs at once: one per trigger child.\n private readonly hookSlots: Slots;\n private ticking = false;\n private warnedMissingJournal = false;\n private stopped = false;\n\n constructor(private readonly options: TriggerSupervisorOptions) {\n this.worker =\n options.worker ??\n new PieceWorker({ models: options.models, telemetry: options.telemetry });\n this.tickMs = options.tickMs ?? 15_000;\n this.defaultIntervalMs =\n options.defaultIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.hookTimeoutMs = options.hookTimeoutMs ?? 60_000;\n this.hookSlots = new Slots(options.hookConcurrency ?? 1);\n this.now = options.now ?? (() => new Date());\n this.egress =\n options.egress === undefined\n ? DEFAULT_EGRESS_POLICY\n : (options.egress ?? undefined);\n this.parks =\n options.parks ??\n new ParkState(async () => (await options.store())?.listWorkflowParks());\n }\n\n start(): void {\n if (this.timer || this.stopped) return;\n this.timer = setInterval(() => {\n this.tick().catch((error: unknown) => {\n if (isShutdownRefusal(error)) {\n logger.debug(\"Trigger tick stopped: @error\", error);\n return;\n }\n logger.error(\"Trigger tick failed: @error\", error);\n });\n }, this.tickMs);\n this.timer.unref();\n logger.info(`Trigger supervisor started (tick ${this.tickMs}ms)`);\n }\n\n stop(): void {\n if (this.stopped) return;\n this.stopped = true;\n if (this.timer) clearInterval(this.timer);\n this.timer = undefined;\n if (!this.options.worker) this.worker.dispose();\n logger.info(\"Trigger supervisor stopped\");\n }\n\n // Serialized per workflow; other workflows' lanes run alongside.\n private enqueue<T>(workflowId: string, task: () => Promise<T>): Promise<T> {\n const previous = this.lanes.get(workflowId) ?? Promise.resolve();\n const run = previous.then(async () => {\n this.throwIfStopped();\n try {\n return await task();\n } catch (error) {\n // Keyed on state: a killed hook throws the worker's exit error.\n if (this.stopped && !(error instanceof TriggerSupervisorStoppedError)) {\n throw new TriggerSupervisorStoppedError({ cause: error });\n }\n throw error;\n }\n });\n const settled = run.catch(() => undefined);\n this.lanes.set(workflowId, settled);\n void settled.then(() => {\n if (this.lanes.get(workflowId) === settled) this.lanes.delete(workflowId);\n });\n return run;\n }\n\n private throwIfStopped(): void {\n if (this.stopped) throw new TriggerSupervisorStoppedError();\n }\n\n // The lane's only way into the journal: once stopped, every call refuses,\n // so work still in flight writes nothing the next owner holds.\n private async store(): Promise<WorkflowRunStore | undefined> {\n this.throwIfStopped();\n const store = await this.options.store();\n if (!store) return undefined;\n return new Proxy(store, {\n get: (target, property) => {\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n return (...args: unknown[]) => {\n this.throwIfStopped();\n return (value as (...a: unknown[]) => unknown).apply(target, args);\n };\n },\n });\n }\n\n private fire(\n workflowId: string,\n payload: unknown,\n kind: string,\n runId: string,\n ): void {\n this.throwIfStopped();\n this.options.fire(workflowId, payload, kind, runId);\n }\n\n // Successfully enabled workflows; identical re-registrations are no-ops.\n private readonly enabledOk = new Set<string>();\n\n // Piece descriptors by package@version, for the trigger strategy lookup.\n private readonly descriptors = new Map<string, PieceDescriptor>();\n\n private own: PieceResolver | undefined;\n\n // The host's resolver when it supplied one — the runtime passes its\n // local-first one — else a fetch into the cache directory this supervisor\n // was configured with, which a direct caller may have warmed itself.\n private resolver(): PieceResolver {\n return (\n this.options.resolver ??\n (this.own ??= bundleResolver({ cacheDir: this.options.cacheDir }))\n );\n }\n\n // Workflows whose onEnable failed and when to try again. The ERROR row keeps\n // the same time so a restart resumes the backoff instead of restarting it.\n private readonly enableRetries = new Map<string, EnableRetry>();\n\n // The published version each binding was registered for; a park blocks\n // only versions up to the one that failed.\n private readonly versions = new Map<string, number>();\n\n upsert(binding: TriggerBinding, publishedVersion?: number): Promise<void> {\n if (publishedVersion !== undefined) {\n this.versions.set(binding.workflowId, publishedVersion);\n }\n const previous = this.bindings.get(binding.workflowId);\n if (\n previous &&\n this.enabledOk.has(binding.workflowId) &&\n JSON.stringify(previous) === JSON.stringify(binding)\n ) {\n return Promise.resolve();\n }\n this.bindings.set(binding.workflowId, binding);\n // The enable lifts a park this version outlived.\n const park = this.parks.known(binding.workflowId)?.park;\n if (\n park &&\n publishedVersion !== undefined &&\n publishedVersion > park.published_version\n ) {\n this.parks.delete(binding.workflowId);\n }\n // The binding it replaces is the only thing that can still name the old\n // registration: the row holds neither the config nor the connection.\n return this.enqueue(binding.workflowId, () =>\n this.enable(binding, previous),\n );\n }\n\n // Park writes ride this lane, the one enable, disable and upsert use, so a\n // park can never land between an enable's park check and its ENABLED write.\n // Each also updates `parks` as it is queued, for readers off the lane.\n\n /** Parks a workflow; true when a trigger row was parked with it. */\n park(\n workflowId: string,\n publishedVersion: number,\n reason: string,\n ): Promise<boolean> {\n this.parks.set(workflowParkRow(workflowId, publishedVersion, reason));\n return this.enqueue(workflowId, async () => {\n const store = await this.store();\n if (!store) return false;\n return store.parkWorkflow(workflowId, publishedVersion, reason);\n });\n }\n\n /** Undoes {@link park} for that version only: a later park stands. */\n liftPark(\n workflowId: string,\n publishedVersion: number,\n trigger: boolean,\n ): Promise<void> {\n if (\n this.parks.known(workflowId)?.park?.published_version === publishedVersion\n ) {\n this.parks.delete(workflowId);\n }\n return this.enqueue(workflowId, async () => {\n const store = await this.store();\n if (!store) return;\n const park = await store.getWorkflowPark(workflowId);\n if (park?.published_version !== publishedVersion) return;\n await store.liftPark(workflowId, trigger);\n });\n }\n\n /** A disable clears the park. With no binding in memory to release a PARKED\n * row through onDisable (a boot), the row is turned DISABLED here. */\n releasePark(workflowId: string, flipRow: boolean): Promise<void> {\n this.parks.delete(workflowId);\n return this.enqueue(workflowId, async () => {\n const store = await this.store();\n if (!store) return;\n if (flipRow) await store.clearParkOnDisable(workflowId);\n else await store.clearWorkflowPark(workflowId);\n });\n }\n\n /**\n * Makes an armed trigger due now and runs the due check at once, so a\n * schedule fires and a poll polls without waiting for its interval (\"sync\n * now\"). The next one follows the interval from there. False when the\n * workflow has no armed trigger (disabled, parked, erroring, unknown).\n */\n async pollNow(workflowId: string): Promise<boolean> {\n if (this.stopped) return false;\n const store = await this.store();\n if (!store) return false;\n const row = await store.getTriggerState(workflowId);\n if (!row || row.status !== \"ENABLED\") return false;\n const binding = this.bindings.get(workflowId);\n if (binding && !isSchedule(binding) && isCallableFlow(binding)) {\n return false;\n }\n await store.upsertTriggerState({\n ...row,\n next_poll_at: this.now().toISOString(),\n });\n this.tick().catch((error: unknown) => {\n if (isShutdownRefusal(error)) return;\n logger.error(\"Trigger tick after poll-now failed: @error\", error);\n });\n return true;\n }\n\n /** A re-publish past the parked version: on this lane, a park older than\n * `publishedVersion` goes and a row it parked is ENABLED again, as it was\n * before (only an ENABLED row is ever parked); a park as new stands. The\n * next upsert of the same binding then arms rather than skipping as\n * unchanged, and a retry held back by the park is due now. */\n unpark(workflowId: string, publishedVersion: number): Promise<void> {\n this.enabledOk.delete(workflowId);\n const retry = this.enableRetries.get(workflowId);\n if (retry) retry.at = 0;\n const park = this.parks.known(workflowId)?.park;\n if (park && park.published_version < publishedVersion) {\n this.parks.delete(workflowId);\n }\n return this.enqueue(workflowId, async () => {\n const store = await this.store();\n if (!store) return;\n const park = await store.getWorkflowPark(workflowId);\n if (!park || park.published_version >= publishedVersion) return;\n await store.liftPark(workflowId, true);\n });\n }\n\n remove(workflowId: string): Promise<void> {\n const binding = this.unbind(workflowId);\n return this.enqueue(workflowId, () => this.disable(workflowId, binding));\n }\n\n // A deleted workflow: disabled as remove() does, then its row, FLOW store\n // and park go too, so nothing is left to poll, renew or re-arm.\n forget(workflowId: string): Promise<void> {\n const binding = this.unbind(workflowId);\n this.parks.delete(workflowId);\n return this.enqueue(workflowId, async () => {\n const store = await this.store();\n if (!store) return;\n await this.disable(workflowId, binding);\n await store.deleteTriggerState(workflowId);\n await store.clearWorkflowPark(workflowId);\n });\n }\n\n private unbind(workflowId: string): TriggerBinding | undefined {\n const binding = this.bindings.get(workflowId);\n this.bindings.delete(workflowId);\n this.versions.delete(workflowId);\n this.enabledOk.delete(workflowId);\n this.enableRetries.delete(workflowId);\n return binding;\n }\n\n // A trigger the runtime could not turn into a binding at all: an unknown\n // block type, a piece nothing can resolve.\n\n // It never reaches enable(), so this is the only thing that writes a row for\n // it, and without one the workflow reads as absent rather than as broken.\n reject(\n workflowId: string,\n block: BlockIdentity,\n config: unknown,\n message: string,\n retryAt?: Date,\n ): Promise<void> {\n this.unbind(workflowId);\n return this.enqueue(workflowId, () =>\n this.recordRejection(workflowId, block, config, message, retryAt),\n );\n }\n\n private async recordRejection(\n workflowId: string,\n block: BlockIdentity,\n config: unknown,\n message: string,\n retryAt?: Date,\n ): Promise<void> {\n const store = await this.store();\n if (!store) return;\n const hash = configHash(block, config);\n const existing = await store.getTriggerState(workflowId);\n // An ENABLED row for this very config is a registration a previous process\n // made and this one cannot see: the binding it would take to call\n // onDisable is the thing that could not be resolved.\n\n // Turning it ERROR would strand it. enable() reads a non-ENABLED row as\n // \"not a republish\", wipes the piece store with it -- the _webhook_id\n // included -- and the next onEnable subscribes a second time at the\n // provider while the first goes on delivering to nobody.\n if (existing?.status === \"ENABLED\" && existing.config_hash === hash) {\n logger.warn(\n `Workflow ${workflowId} could not be resolved, and its trigger row is left as it stands: a registration from before this reactor started is presumed live, and releasing it needs the binding that would not resolve. @error`,\n message,\n );\n return;\n }\n // A PARKED row is left as it stands too: turning it ERROR would clear the\n // park, and the ERROR row's own retry would arm the parked trigger the\n // moment the piece resolves again. Parked is already not-firing.\n if (\n existing?.status === PARKED_TRIGGER_STATUS &&\n existing.config_hash === hash\n ) {\n logger.warn(\n `Workflow ${workflowId} is PARKED and could not be resolved; the park stands. @error`,\n message,\n );\n return;\n }\n await store.upsertTriggerState({\n workflow_id: workflowId,\n ...triggerBlockColumns(block),\n config_hash: hash,\n status: \"ERROR\",\n store_state: VESTIGIAL_STORE_STATE,\n // What it would poll at, once it resolves to something that can.\n interval_ms: this.defaultIntervalMs,\n // Set only when somebody is coming back for it: an absent piece changes\n // nothing on its own, and installing it re-registers rather than waiting.\n next_poll_at: retryAt?.toISOString() ?? null,\n last_poll_at: existing?.last_poll_at ?? null,\n last_error: message,\n consecutive_failures: (existing?.consecutive_failures ?? 0) + 1,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: this.now().toISOString(),\n ...pieceColumns(),\n });\n }\n\n // Design-time sample, run against its own partitions so no key it writes can\n // alias a live one, and dropped afterwards so none of it outlives the sample.\n test(\n binding: PieceTriggerBinding,\n options: { runUser?: RunUser | null } = {},\n ): Promise<unknown> {\n return this.enqueue(binding.workflowId, async () => {\n const store = await this.store();\n try {\n const result = await this.hook(binding, \"test\", {\n ...(options.runUser !== undefined\n ? { runUser: options.runUser }\n : {}),\n });\n return result.output;\n } finally {\n await this.dropTestPartitions(store, binding.workflowId);\n }\n });\n }\n\n // Best-effort: a sample that leaves rows behind is untidy, but failing the\n // sample over it would be worse, and the next one overwrites them anyway.\n private async dropTestPartitions(\n store: WorkflowRunStore | undefined,\n workflowId: string,\n ): Promise<void> {\n if (!store) return;\n try {\n await store.deletePieceStore(\n \"FLOW\",\n testPartitionKey(\"FLOW\", workflowId),\n );\n await store.deletePieceStore(\n \"PROJECT\",\n testPartitionKey(\"PROJECT\", workflowId),\n );\n } catch (error) {\n logger.warn(`Could not clear test store for ${workflowId}`, error);\n }\n }\n\n // The sender's probe, answered by the piece rather than by us: only its own\n // code knows what the sender wants echoed back. Serialised with\n // enable/disable like a delivery, so a probe arriving during a\n // re-registration cannot read a half-written store.\n handshake(\n binding: PieceTriggerBinding,\n payload: unknown,\n ): Promise<PieceWorkerResult> {\n return this.enqueue(binding.workflowId, () =>\n this.hook(binding, \"onHandshake\", { payload }),\n );\n }\n\n // Ingress path: a verified delivery runs the trigger's `run` hook with the\n // payload, then goes through the same dedupe and fire path a poll does. The\n // resolver never waits for this — providers time out fast (paperless allows\n // five seconds) and a slow run would look like a failed delivery.\n // Resolves to the runs it journaled; `parent` is a sub-flow's caller.\n deliverWebhook(\n workflowId: string,\n payload: unknown,\n parent?: RunParent,\n ): Promise<string[]> {\n return this.enqueue(workflowId, async () => {\n const binding = this.bindings.get(workflowId);\n if (!binding || isSchedule(binding)) {\n logger.warn(`Webhook delivery for unknown workflow ${workflowId}`);\n return [];\n }\n const store = await this.store();\n // Rejecting is what stops the resolver logging \"Webhook delivered\" for a\n // delivery that was dropped on the floor.\n if (!store) throw new MissingJournalError(\"Webhook delivery\");\n const row = await store.getTriggerState(workflowId);\n const now = this.now();\n // A dropped delivery is the provider's to retry, and paperless never\n // does — but a rewound cursor lets the reconcile poll find it again.\n const rewind = await this.cursorRewind(store, workflowId);\n let refused = false;\n try {\n const result = await this.hook(binding, \"run\", { payload }).catch(\n (error: unknown) => {\n // Refused before the piece ran, so nothing it would checkpoint moved.\n refused = isShutdownRefusal(error);\n throw error;\n },\n );\n // Checked before the checkpoint, as a poll does: coercing a scalar to\n // no items leaves nothing to rewind, and the delivery is lost for good.\n if (!Array.isArray(result.output)) {\n throw new Error(\n `Trigger run returned ${typeof result.output}, expected an array`,\n );\n }\n // A delivery to a trigger that never enabled still fires, but it must\n // not clear the enable error or reset the backoff by recording a\n // success.\n const success =\n row?.status === \"ENABLED\"\n ? {\n workflowId,\n storeState: VESTIGIAL_STORE_STATE,\n nextPollAtIso: new Date(\n now.getTime() + row.interval_ms,\n ).toISOString(),\n }\n : undefined;\n return await this.fireItems(\n store,\n binding,\n result.output,\n now,\n rewind,\n success,\n parent,\n );\n } catch (error) {\n if (!refused) await rewind();\n throw error;\n }\n });\n }\n\n pieceBinding(workflowId: string): PieceTriggerBinding | undefined {\n const binding = this.bindings.get(workflowId);\n return binding && !isSchedule(binding) ? binding : undefined;\n }\n\n // Once per run, before its first step: the trigger's own setup for it.\n onStart(\n binding: PieceTriggerBinding,\n runId: string,\n payload: unknown,\n ): Promise<PieceWorkerResult> {\n return this.hook(binding, \"onStart\", { payload, runId });\n }\n\n // Trigger delivery is at-least-once, and a durable store puts that at risk:\n // pollingHelper advances its cursor *inside* the hook.\n\n // A failure after that checkpoint would skip items the hook read but never\n // delivered, so a delivery attempt first takes the FLOW partition as it was.\n\n // Putting it back on any failure through the fire means the next read\n // re-delivers, and the dedupe table absorbs the repeats.\n private async cursorRewind(\n store: WorkflowRunStore,\n workflowId: string,\n ): Promise<Rewind> {\n const before = await store.listPieceStore(\"FLOW\", workflowId);\n let rewound: Promise<boolean> | undefined;\n // Past stop() too: a hook that ran may have checkpointed past items it\n // never delivered, and putting the cursor back keeps them deliverable.\n const rewind = async (redelivered: string[]) => {\n try {\n const raw = await this.options.store();\n if (!raw) return false;\n await raw.rewindPieceStore(\"FLOW\", workflowId, before, {\n runIds: redelivered,\n reason: REDELIVERED_REASON,\n });\n return true;\n } catch (error) {\n // The poll already failed; losing the rewind too costs at-most-once\n // for this cursor, which still beats failing the supervisor's lane.\n logger.warn(`Could not rewind the cursor for ${workflowId}`, error);\n return false;\n }\n };\n return (redelivered = []) => (rewound ??= rewind(redelivered));\n }\n\n // The hook's `ctx.store` is the journal's piece_store, served call by call,\n // so a registration id is durable the instant the piece writes it.\n private async hook(\n binding: PieceTriggerBinding,\n hook: TriggerHookRequest[\"hook\"],\n options: {\n isRepublish?: boolean;\n payload?: unknown;\n webhookUrl?: string;\n runUser?: RunUser | null;\n runId?: string;\n } = {},\n ): Promise<PieceWorkerResult> {\n // onDisable still has to release what an earlier enable registered.\n if (hook !== \"onDisable\") {\n checkDynamicProperties(binding.config, binding.propertySettings);\n }\n const store = await this.store();\n // A cursor on the heap resets on restart and re-delivers everything the\n // trigger ever saw, so only a design-time sample may run without a journal.\n if (!store && hook !== \"test\") {\n throw new MissingJournalError(`Trigger hook \"${hook}\"`);\n }\n const pieceStore = store\n ? createPieceStorePort(store, () => binding.workflowId, hook === \"test\")\n : undefined;\n const piece = await this.resolver().resolve(targetOf(binding));\n // A trigger's connection is the workflow's own, declared beside it, so it\n // needs no run binding — but it is still bound to its connector.\n const auth = await this.options.resolveAuth(binding.connectionId, {\n piecePackage: binding.packageName,\n });\n // Redacted in the child, so a hook's error crosses back without the\n // credential the connection resolved to.\n const redactValues = secretsFor(auth);\n const reactor = await this.reactorFor(binding, hook, options.runUser);\n const flows =\n hook === \"test\" || hook === \"onDisable\"\n ? undefined\n : this.options.flowsFor?.(binding.workflowId, options.runId);\n const hostCalls =\n pieceStore || flows\n ? {\n ...(pieceStore ? storeHandlers(pieceStore) : {}),\n ...(flows ? flowsHandlers(flows) : {}),\n }\n : undefined;\n this.throwIfStopped();\n return this.worker.runTriggerHook(\n {\n ...pieceModuleRef(piece),\n triggerName: binding.triggerName,\n hook,\n propsValue: binding.config,\n auth,\n ...(redactValues.length > 0 ? { redactValues } : {}),\n ...(pieceStore ? { durableStore: true } : {}),\n identity: {\n flowId: binding.workflowId,\n projectId: PROJECT_SCOPE_KEY,\n ...(options.runId ? { runId: options.runId } : {}),\n },\n isRepublish: options.isRepublish,\n payload: options.payload,\n // A poll binding gets an unroutable URL on purpose: a live one would\n // let a piece register an endpoint that nothing ever delivers to.\n webhookUrl:\n options.webhookUrl ??\n `http://localhost:0/v1/webhooks/${binding.workflowId}`,\n ...(this.egress ? { egress: this.egress } : {}),\n ...(flows\n ? { flows: flows.publicUrl ? { publicUrl: flows.publicUrl } : {} }\n : {}),\n },\n {\n timeoutMs: this.hookTimeoutMs,\n ...(hostCalls ? { hostCalls } : {}),\n ...(reactor ? { reactor } : {}),\n },\n );\n }\n\n // ctx.reactor for a declaring trigger. onDisable runs without it rather than\n // not at all, so a revoked connection still releases what onEnable registered.\n private async reactorFor(\n binding: PieceTriggerBinding,\n hook: TriggerHookRequest[\"hook\"],\n runUser: RunUser | null | undefined,\n ): Promise<ReactorTap | undefined> {\n const access = this.options.reactorAccess;\n if (!access) return undefined;\n const declared = (await this.triggerDescriptor(binding))?.requireReactor;\n if (!declared) return undefined;\n try {\n return await access(binding, declared, runUser);\n } catch (error) {\n if (hook === \"onDisable\") return undefined;\n throw error;\n }\n }\n\n // Cached per version.\n private async pieceDescriptor(\n binding: PieceTriggerBinding,\n ): Promise<PieceDescriptor> {\n const key = `${binding.source ?? \"\"}:${binding.packageName}@${binding.version}`;\n let descriptor = this.descriptors.get(key);\n if (!descriptor) {\n const piece = await this.resolver().resolve(targetOf(binding));\n const result = await this.worker.describePiece(\n {\n ...pieceModuleRef(piece),\n packageName: binding.packageName,\n version: binding.version,\n ...(this.egress ? { egress: this.egress } : {}),\n },\n { timeoutMs: this.hookTimeoutMs },\n );\n descriptor = result.output as PieceDescriptor;\n this.descriptors.set(key, descriptor);\n }\n return descriptor;\n }\n\n private async triggerDescriptor(\n binding: PieceTriggerBinding,\n ): Promise<PieceDescriptor[\"triggers\"][number] | undefined> {\n const descriptor = await this.pieceDescriptor(binding);\n return descriptor.triggers.find(\n (candidate) => candidate.name === binding.triggerName,\n );\n }\n\n // A trigger's strategy, and whether the engine can run it, live in the piece\n // descriptor. Enables are rare and the descriptor is cached per version.\n private async deliveryFor(\n binding: PieceTriggerBinding,\n ): Promise<TriggerRuntime> {\n const descriptor = await this.pieceDescriptor(binding);\n const trigger = descriptor.triggers.find(\n (candidate) => candidate.name === binding.triggerName,\n );\n const subject = `Trigger \"${binding.triggerName}\" of \"${binding.packageName}\"`;\n if (!trigger) {\n throw new TriggerConfigError(`${subject}: not in ${binding.version}`);\n }\n // Parked, not retried: no attempt can make the feature run.\n const unsupported = descriptor.unsupported ?? trigger.unsupported;\n if (unsupported) {\n throw new TriggerConfigError(`${subject}: ${unsupported.reason}`);\n }\n const check = checkTriggerStrategy(trigger.strategy);\n if (\"issue\" in check) {\n throw new TriggerConfigError(`${subject}: ${check.issue}`);\n }\n return {\n delivery: check.delivery,\n ...(check.delivery === \"webhook\" && trigger.renew\n ? { renew: trigger.renew }\n : {}),\n };\n }\n\n private async enable(\n binding: TriggerBinding,\n superseded?: TriggerBinding,\n ): Promise<void> {\n const store = await this.store();\n // enableSupervised logs this; returning quietly would leave a workflow\n // that looks registered and never fires.\n if (!store) throw new MissingJournalError(\"Enabling a trigger\");\n const hash = configHash(binding.block, binding.config);\n const now = this.now();\n const park = await store.getWorkflowPark(binding.workflowId);\n if (park && (await this.blockingPark(store, binding.workflowId))) {\n this.holdParked(binding, superseded, park);\n return;\n }\n // A newer version outlived the park: it goes, and a row it parked is the\n // live registration this enable releases or republishes onto.\n if (park) await store.liftPark(binding.workflowId, true);\n const existing = await store.getTriggerState(binding.workflowId);\n // Only a completed enable is a republish: a retry after a failed one must\n // register again, or a piece that skips registration never delivers.\n\n // A republish also keeps the cursor and the _webhook_id the hook wrote\n // before, which is exactly what a blob that never migrated no longer holds.\n const isRepublish =\n existing?.config_hash === hash &&\n existing.status === \"ENABLED\" &&\n !store.hasUnmigratedTriggerState(binding.workflowId);\n if (existing && !isRepublish && existing.status === \"ENABLED\") {\n // The trigger changed: release the old registration first.\n await this.disableRow(binding.workflowId, existing, superseded);\n }\n const pending = this.enableRetries.get(binding.workflowId);\n if (isSchedule(binding)) {\n // A piece trigger replaced by the schedule trigger takes its retry with it;\n // left behind, the entry wins a slot on every tick and never resolves.\n this.enableRetries.delete(binding.workflowId);\n if (\n pending?.release &&\n existing &&\n superseded &&\n !isSchedule(superseded)\n ) {\n await this.releaseRegistration(superseded);\n }\n await this.enableSchedule(store, binding, hash, existing);\n return;\n }\n if (this.deferToStoredRetry(binding, hash, existing, now)) return;\n if (pending?.release && existing) {\n // The failed attempt may have subscribed at the provider already, and\n // only one subscription is ever released; drop it before making another.\n await this.releaseRegistration(binding);\n }\n // A changed config is a different trigger: carrying the old cursor and,\n // worse, the old _webhook_id would point it at a dead registration.\n if (!isRepublish) {\n await store.deletePieceStore(\"FLOW\", binding.workflowId);\n }\n let reachedProvider = false;\n try {\n const runtime = await this.deliveryFor(binding);\n // Callable Flow is called by this reactor's runs: no public URL, no polling.\n const inProcess = isCallableFlow(binding);\n const webhook = runtime.delivery === \"webhook\" && !inProcess;\n // The reactor's webhook service owns the token and the URL it lives in,\n // so the piece is handed an address rather than a credential to place.\n const webhookUrl = webhook\n ? await this.webhookUrlOrThrow(binding.workflowId)\n : undefined;\n if (webhook && !webhookUrl) {\n throw new Error(\n \"This trigger delivers by webhook, but no public webhook endpoint is configured for the reactor\",\n );\n }\n reachedProvider = true;\n const result = await this.hook(binding, \"onEnable\", {\n isRepublish,\n webhookUrl,\n });\n // A webhook trigger still polls, just slowly: the poll is the\n // reconciliation sweep that recovers deliveries the provider dropped.\n const intervalMs = webhook\n ? (this.options.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS)\n : pollIntervalFor(binding, result.schedules, this.defaultIntervalMs);\n const renewAt = runtime.renew\n ? this.renewAtAfterEnable(runtime.renew, existing, isRepublish, now)\n : null;\n // A republish keeps a failing renewal's streak, so its backoff holds.\n const renewCarried = renewAt !== null && isRepublish && existing;\n await store.upsertTriggerState({\n workflow_id: binding.workflowId,\n ...triggerBlockColumns(binding.block),\n config_hash: hash,\n status: await this.armedStatus(store, binding.workflowId),\n store_state: VESTIGIAL_STORE_STATE,\n interval_ms: intervalMs,\n next_poll_at: inProcess\n ? null\n : new Date(now.getTime() + intervalMs).toISOString(),\n last_poll_at: null,\n last_error: null,\n consecutive_failures: 0,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: now.toISOString(),\n ...pieceColumns(binding),\n next_renew_at: renewAt?.toISOString() ?? null,\n renew_error: renewCarried ? existing.renew_error : null,\n renew_failures: renewCarried ? existing.renew_failures : 0,\n });\n this.enabledOk.add(binding.workflowId);\n this.enableRetries.delete(binding.workflowId);\n store.clearUnmigratedTriggerState(binding.workflowId);\n logger.info(\n `Enabled @block for workflow ${binding.workflowId} (every ${intervalMs}ms)`,\n blockLabel(binding.block),\n );\n } catch (error) {\n // Refused, not failed: nothing to back off or record.\n if (this.stopped) throw error;\n this.enabledOk.delete(binding.workflowId);\n const message = error instanceof Error ? error.message : String(error);\n const failures = (existing?.consecutive_failures ?? 0) + 1;\n const intervalMs = pollIntervalFor(\n binding,\n undefined,\n this.defaultIntervalMs,\n );\n // A third-party API down for a minute must not park the trigger for good,\n // so onEnable retries on the tick loop; the row stays ERROR until it takes.\n const retryAt = isPermanentFailure(error)\n ? undefined\n : new Date(now.getTime() + backoffMs(intervalMs, failures));\n if (retryAt) {\n this.enableRetries.set(binding.workflowId, {\n at: retryAt.getTime(),\n failures,\n release: reachedProvider,\n });\n } else this.enableRetries.delete(binding.workflowId);\n await store.upsertTriggerState({\n workflow_id: binding.workflowId,\n ...triggerBlockColumns(binding.block),\n config_hash: hash,\n status: \"ERROR\",\n store_state: VESTIGIAL_STORE_STATE,\n interval_ms: intervalMs,\n next_poll_at: retryAt?.toISOString() ?? null,\n last_poll_at: null,\n last_error: message,\n consecutive_failures: failures,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: now.toISOString(),\n ...pieceColumns(binding),\n });\n logger.error(\n `onEnable failed for workflow ${binding.workflowId} (${failures}x): @error` +\n (retryAt\n ? `; retrying at ${retryAt.toISOString()}`\n : \"; not retrying\"),\n message,\n );\n }\n }\n\n // A republish keeps an earlier pending renewal: a piece that skips\n // re-registering on one still holds the old, expiring subscription.\n private renewAtAfterEnable(\n renew: TriggerRenew,\n existing: TriggerStateRow | undefined,\n isRepublish: boolean,\n now: Date,\n ): Date {\n const next = nextRenewAt(renew, now);\n const carried =\n isRepublish && existing?.next_renew_at\n ? Date.parse(existing.next_renew_at)\n : NaN;\n return Number.isFinite(carried) && carried < next.getTime()\n ? new Date(carried)\n : next;\n }\n\n // A reactor with no webhook service will never mint a URL; one that has not\n // finished starting has simply not minted this workflow's yet.\n private async webhookUrlOrThrow(workflowId: string): Promise<string> {\n const mint = this.options.webhookUrlFor;\n if (!mint) {\n throw new TriggerConfigError(\n \"This trigger delivers by webhook, but no public webhook endpoint is configured for the reactor\",\n );\n }\n const url = await mint(workflowId);\n if (!url) {\n throw new Error(\n \"The reactor's webhook endpoint is not available yet for this workflow\",\n );\n }\n return url;\n }\n\n /**\n * The park, when it holds this registration back.\n *\n * `policy.onFailure = PARK` is a **runtime override of the document's\n * enabled-ness**: the document still says ENABLED, and re-arming from it is\n * what a restart does for every workflow it finds. So the park row is the\n * authority, read on this lane, and it blocks every registration of the\n * version that failed or an older one — a boot re-arm, an ERROR row's\n * retry. A newer version is what a re-publish is: it is never blocked, and\n * {@link enable} lifts the park it outlived. A re-enable lifts it through\n * the disable before it.\n */\n private async blockingPark(\n store: WorkflowRunStore,\n workflowId: string,\n ): Promise<WorkflowParkRow | undefined> {\n const park = await store.getWorkflowPark(workflowId);\n if (!park) return undefined;\n const version = this.versions.get(workflowId);\n return version === undefined || version <= park.published_version\n ? park\n : undefined;\n }\n\n /**\n * An enable a park held back. The row is left as it stands, and a pending\n * retry keeps its release flag, so the enable after the park lifts releases\n * a failed attempt and arms afresh; the retry is only pushed back, so it\n * does not take every tick's slot. A binding this replaced is restored, so\n * nothing is released later with one that was never armed.\n */\n private holdParked(\n binding: TriggerBinding,\n superseded: TriggerBinding | undefined,\n park: WorkflowParkRow,\n ): void {\n const { workflowId } = binding;\n const retry = this.enableRetries.get(workflowId);\n if (retry) retry.at = this.now().getTime() + this.defaultIntervalMs;\n if (superseded && this.bindings.get(workflowId) === binding) {\n this.bindings.set(workflowId, superseded);\n }\n logger.warn(\n `Workflow ${workflowId} is PARKED at version ${park.published_version}; its trigger is not armed until the workflow is re-published or re-enabled. @error`,\n park.reason,\n );\n }\n\n /** The status an enable that succeeded writes: never ENABLED while a park\n * stands, whatever ran meanwhile. The registration stays recorded. */\n private async armedStatus(\n store: WorkflowRunStore,\n workflowId: string,\n ): Promise<string> {\n return (await this.blockingPark(store, workflowId))\n ? PARKED_TRIGGER_STATUS\n : \"ENABLED\";\n }\n\n // Backoff that only lives in memory is no backoff at all against a crash\n // loop, so a restart picks the retry time back up off the row.\n\n // A re-registration of the same config waits its turn too; only a changed\n // config is an operator saying \"try this one now\".\n private deferToStoredRetry(\n binding: PieceTriggerBinding,\n hash: string,\n existing: TriggerStateRow | undefined,\n now: Date,\n ): boolean {\n if (existing?.status !== \"ERROR\" || existing.config_hash !== hash) {\n return false;\n }\n const pending = this.enableRetries.get(binding.workflowId);\n const stored = existing.next_poll_at\n ? Date.parse(existing.next_poll_at)\n : NaN;\n const at = pending?.at ?? (Number.isFinite(stored) ? stored : undefined);\n if (at === undefined || at <= now.getTime()) return false;\n if (!pending) {\n this.enableRetries.set(binding.workflowId, {\n at,\n failures: existing.consecutive_failures,\n // Nothing in memory says how far the pre-restart attempt got, and a\n // stale subscription costs more than a redundant onDisable.\n release: true,\n });\n logger.info(\n `Enable for workflow ${binding.workflowId} still backing off until ${existing.next_poll_at}`,\n );\n }\n return true;\n }\n\n // Best effort: the ids a piece unsubscribes with reach us only when onEnable\n // returns, so a timed-out first attempt has nothing here to release with.\n\n // Closing that gap needs the worker to report store writes as they happen.\n private async releaseRegistration(\n binding: PieceTriggerBinding,\n ): Promise<void> {\n try {\n await this.hook(binding, \"onDisable\");\n } catch (error) {\n logger.warn(\n `onDisable before retrying workflow ${binding.workflowId} failed`,\n error,\n );\n }\n }\n\n // An unchanged, still-ENABLED row keeps its next fire time: that is what\n // carries a schedule across a restart. Anything else rebases on now.\n private async enableSchedule(\n store: WorkflowRunStore,\n binding: ScheduleTriggerBinding,\n hash: string,\n existing: TriggerStateRow | undefined,\n ): Promise<void> {\n const now = this.now();\n const base = {\n workflow_id: binding.workflowId,\n ...triggerBlockColumns(binding.block),\n config_hash: hash,\n store_state: VESTIGIAL_STORE_STATE,\n last_poll_at: existing?.last_poll_at ?? null,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: now.toISOString(),\n ...pieceColumns(),\n };\n try {\n const schedule = parseScheduleConfig(binding.config);\n const carried =\n existing?.status === \"ENABLED\" && existing.config_hash === hash\n ? existing.next_poll_at\n : null;\n const nextAt = carried ? new Date(carried) : nextFireAt(schedule, now);\n await store.upsertTriggerState({\n ...base,\n status: await this.armedStatus(store, binding.workflowId),\n interval_ms:\n schedule.mode === \"interval\"\n ? schedule.everyMs\n : MIN_SCHEDULE_INTERVAL_MS,\n next_poll_at: nextAt.toISOString(),\n last_error: null,\n consecutive_failures: 0,\n });\n this.enabledOk.add(binding.workflowId);\n logger.info(\n `Scheduled workflow ${binding.workflowId}: next fire ${nextAt.toISOString()}` +\n (carried ? \" (carried over)\" : \"\"),\n );\n } catch (error) {\n this.enabledOk.delete(binding.workflowId);\n const message = error instanceof Error ? error.message : String(error);\n await store.upsertTriggerState({\n ...base,\n status: \"ERROR\",\n interval_ms: MIN_SCHEDULE_INTERVAL_MS,\n next_poll_at: null,\n last_error: message,\n consecutive_failures: (existing?.consecutive_failures ?? 0) + 1,\n });\n logger.error(\n `Invalid schedule for workflow ${binding.workflowId}: @error`,\n message,\n );\n }\n }\n\n private async disable(\n workflowId: string,\n binding?: TriggerBinding,\n ): Promise<void> {\n const store = await this.store();\n if (!store) throw new MissingJournalError(\"Disabling a trigger\");\n const row = await store.getTriggerState(workflowId);\n if (!row || row.status === \"DISABLED\") return;\n await this.disableRow(workflowId, row, binding);\n }\n\n // The piece_store rows are kept: an unchanged re-enable republishes onto the\n // cursor, and onDisable is the only thing that can release a registration.\n private async disableRow(\n workflowId: string,\n row: TriggerStateRow,\n binding?: TriggerBinding,\n ): Promise<void> {\n const store = await this.store();\n if (!store) return;\n const target = binding ?? this.bindingFromRow(row);\n if (\n target &&\n !isSchedule(target) &&\n blockKey(triggerRowBlock(row)) !== SCHEDULE_BLOCK\n ) {\n try {\n await this.hook(target, \"onDisable\");\n } catch (error) {\n logger.warn(`onDisable failed for workflow ${workflowId}`, error);\n }\n }\n await store.setTriggerStatus(workflowId, \"DISABLED\");\n }\n\n private bindingFromRow(row: TriggerStateRow): TriggerBinding | undefined {\n return this.bindings.get(row.workflow_id);\n }\n\n // Lists what is due and starts it, each on its workflow's lane. Resolves when\n // that work settles; the timer's next tick does not wait for it.\n async tick(): Promise<void> {\n if (this.ticking || this.stopped) return;\n this.ticking = true;\n // Held here, so work started before a stop lands mid-listing still settles.\n const started: (Promise<void> | undefined)[] = [];\n let listing: unknown;\n try {\n await this.startDue(started);\n } catch (error) {\n listing = error;\n } finally {\n this.ticking = false;\n }\n const outcomes = await Promise.allSettled(\n started.filter((run) => run !== undefined),\n );\n if (listing !== undefined) {\n throw listing instanceof Error ? listing : new Error(String(listing));\n }\n const failed = outcomes.find((outcome) => outcome.status === \"rejected\");\n if (failed) throw failed.reason;\n }\n\n // One piece of tick work for a workflow, unless one is still in flight.\n private startOnLane(\n workflowId: string,\n task: () => Promise<void>,\n hook: boolean,\n ): Promise<void> | undefined {\n if (this.ticked.has(workflowId)) return undefined;\n this.ticked.add(workflowId);\n // The slot first, off the lane: waiting for one must not hold up this\n // workflow's webhooks and edits. Nothing on a lane waits for a slot.\n const run = hook\n ? this.hookSlots.run(() => this.enqueue(workflowId, task))\n : this.enqueue(workflowId, task);\n return run.finally(() => this.ticked.delete(workflowId));\n }\n\n // An ERROR row is never due for a poll, so the enable retry rides the same\n // tick rather than a timer of its own.\n\n // One per tick, and after the due rows: an enable hook can burn the whole\n // hook timeout, and a queue of them must not push schedule fires late.\n private startOneEnableRetry(): Promise<void> | undefined {\n const now = this.now().getTime();\n const next = [...this.enableRetries]\n .filter(([id, retry]) => retry.at <= now && !this.ticked.has(id))\n .sort((a, b) => a[1].at - b[1].at)\n .at(0);\n if (!next) return undefined;\n const [workflowId, retry] = next;\n const binding = this.bindings.get(workflowId);\n if (!binding) {\n this.enableRetries.delete(workflowId);\n return undefined;\n }\n return this.startOnLane(\n workflowId,\n () => this.retryEnable(workflowId, retry, binding, now),\n true,\n );\n }\n\n private async retryEnable(\n workflowId: string,\n retry: EnableRetry,\n binding: TriggerBinding,\n now: number,\n ): Promise<void> {\n // The entry is only dropped by an attempt that got as far as writing its\n // own outcome; anything else keeps it, backed off, rather than parking.\n try {\n await this.enable(binding);\n } catch (error) {\n if (this.stopped) throw error;\n const failures = retry.failures + 1;\n // The same cadence the attempt itself would have backed off on: a store\n // that just failed is the last thing to poll faster than configured.\n const intervalMs = isSchedule(binding)\n ? MIN_INTERVAL_MS\n : pollIntervalFor(binding, undefined, this.defaultIntervalMs);\n this.enableRetries.set(workflowId, {\n at: now + backoffMs(intervalMs, failures),\n failures,\n release: retry.release,\n });\n logger.error(`Enable retry for workflow ${workflowId} threw`, error);\n }\n }\n\n private async startDue(\n started: (Promise<void> | undefined)[],\n ): Promise<void> {\n const store = await this.store();\n // Once, not on every tick: the tick repeats forever and the condition\n // never changes without a restart.\n if (!store) {\n if (!this.warnedMissingJournal) {\n this.warnedMissingJournal = true;\n logger.error(\n \"Trigger polling is off: @error\",\n new MissingJournalError(\"Polling\"),\n );\n }\n return;\n }\n const due = await store.listDueTriggerStates(this.now().toISOString());\n // Schedules first: they only write rows, so no hook is ahead of them.\n const ordered = [...due].sort(\n (a, b) => Number(!this.isScheduleRow(a)) - Number(!this.isScheduleRow(b)),\n );\n for (const row of ordered) {\n this.throwIfStopped();\n const binding = this.bindings.get(row.workflow_id);\n if (!binding) {\n // Zombie row: the registry no longer knows this workflow.\n started.push(\n this.startOnLane(\n row.workflow_id,\n () => store.setTriggerStatus(row.workflow_id, \"DISABLED\"),\n false,\n ),\n );\n continue;\n }\n // Its earlier firings still hold every slot: polled now, a trigger that\n // advances its own position (a backfill's cursor) would hand out work\n // that can only queue, and expire or be skipped there. Left due, it is\n // polled on the first tick after a slot frees.\n if (!isSchedule(binding) && this.options.pollHeld?.(row.workflow_id)) {\n continue;\n }\n started.push(\n isSchedule(binding)\n ? this.startOnLane(\n row.workflow_id,\n this.whileBound(binding, () =>\n this.fireSchedule(store, row, binding),\n ),\n false,\n )\n : this.startOnLane(\n row.workflow_id,\n this.whileBound(binding, () => this.poll(store, row, binding)),\n true,\n ),\n );\n }\n this.throwIfStopped();\n started.push(...(await this.startRenewals(store)));\n this.throwIfStopped();\n started.push(this.startOneEnableRetry());\n }\n\n // Listed bindings wait for their lane and a hook slot: one removed or\n // replaced meanwhile is skipped rather than run with its old config.\n private whileBound(\n binding: TriggerBinding,\n task: () => Promise<void>,\n ): () => Promise<void> {\n return () =>\n this.bindings.get(binding.workflowId) === binding\n ? task()\n : Promise.resolve();\n }\n\n private isScheduleRow(row: TriggerStateRow): boolean {\n const binding = this.bindings.get(row.workflow_id);\n return binding !== undefined && isSchedule(binding);\n }\n\n private async startRenewals(\n store: WorkflowRunStore,\n ): Promise<(Promise<void> | undefined)[]> {\n const due = await store.listDueTriggerRenewals(this.now().toISOString());\n return due.map((row) => {\n const binding = this.bindings.get(row.workflow_id);\n if (!binding) {\n return this.startOnLane(\n row.workflow_id,\n () => store.setTriggerStatus(row.workflow_id, \"DISABLED\"),\n false,\n );\n }\n if (isSchedule(binding)) {\n return this.startOnLane(\n row.workflow_id,\n () => store.setTriggerRenewAt(row.workflow_id, null),\n false,\n );\n }\n return this.startOnLane(\n row.workflow_id,\n this.whileBound(binding, () => this.renew(store, row, binding)),\n true,\n );\n });\n }\n\n // A failure backs off but never disables: the subscription may still be\n // live, and the next cron slot tries again regardless.\n private async renew(\n store: WorkflowRunStore,\n row: TriggerStateRow,\n binding: PieceTriggerBinding,\n ): Promise<void> {\n const now = this.now();\n let renew: TriggerRenew | undefined;\n try {\n renew = (await this.deliveryFor(binding)).renew;\n if (!renew) {\n await store.setTriggerRenewAt(row.workflow_id, null);\n return;\n }\n const webhookUrl = await this.webhookUrlOrThrow(binding.workflowId);\n await this.hook(binding, \"onRenew\", { webhookUrl });\n const nextAt = nextRenewAt(renew, now);\n await store.recordRenewSuccess(\n row.workflow_id,\n now.toISOString(),\n nextAt.toISOString(),\n );\n logger.info(\n `Renewed trigger of workflow ${row.workflow_id}; next ${nextAt.toISOString()}`,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const failures = row.renew_failures + 1;\n const backoff = now.getTime() + backoffMs(RENEW_RETRY_BASE_MS, failures);\n const slot = renew ? nextRenewAt(renew, now).getTime() : backoff;\n const retryAt = new Date(Math.min(backoff, slot));\n await store.recordRenewFailure(\n row.workflow_id,\n message,\n now.toISOString(),\n retryAt.toISOString(),\n failures,\n );\n logger.warn(\n `onRenew failed for workflow ${row.workflow_id} (${failures}x): @error; retrying at ${retryAt.toISOString()}`,\n message,\n );\n }\n }\n\n // One fire per due row, however overdue; the next slot is computed from\n // now, so a restart never replays the slots it slept through.\n private async fireSchedule(\n store: WorkflowRunStore,\n row: TriggerStateRow,\n binding: ScheduleTriggerBinding,\n ): Promise<void> {\n const now = this.now();\n try {\n const schedule = parseScheduleConfig(binding.config);\n const scheduledFor = row.next_poll_at ? new Date(row.next_poll_at) : now;\n const nextAt = rescheduleAfterFire(schedule, scheduledFor, now);\n const payload = schedulePayload(schedule, scheduledFor, now);\n const runId = await store.recordScheduleFire(\n now.toISOString(),\n nextAt.toISOString(),\n {\n workflowId: binding.workflowId,\n triggerKind: SCHEDULE_TRIGGER_KIND,\n triggerPayload: payload,\n },\n );\n try {\n this.fire(binding.workflowId, payload, SCHEDULE_TRIGGER_KIND, runId);\n } catch (error) {\n // The slot is consumed, so the run is the firing's only record.\n await this.failRefused([runId], error);\n throw error;\n }\n } catch (error) {\n if (this.stopped) throw error;\n // Only a config that stopped parsing gets here; stop until it is edited.\n const message = error instanceof Error ? error.message : String(error);\n this.enabledOk.delete(binding.workflowId);\n await store.setTriggerStatus(row.workflow_id, \"ERROR\", message);\n logger.error(\n `Schedule fire failed for workflow ${row.workflow_id}: @error`,\n message,\n );\n }\n }\n\n private async poll(\n store: WorkflowRunStore,\n row: TriggerStateRow,\n binding: PieceTriggerBinding,\n ): Promise<void> {\n const now = this.now();\n const rewind = await this.cursorRewind(store, row.workflow_id);\n let refused = false;\n try {\n const result = await this.hook(binding, \"run\").catch((error: unknown) => {\n refused = isShutdownRefusal(error);\n throw error;\n });\n if (!Array.isArray(result.output)) {\n throw new Error(\n `Trigger run returned ${typeof result.output}, expected an array`,\n );\n }\n await this.fireItems(store, binding, result.output, now, rewind, {\n workflowId: row.workflow_id,\n storeState: VESTIGIAL_STORE_STATE,\n nextPollAtIso: new Date(now.getTime() + row.interval_ms).toISOString(),\n });\n } catch (error) {\n if (!refused) await rewind();\n // Not a failure of the trigger's: nothing is recorded against it.\n if (this.stopped) throw error;\n const message = error instanceof Error ? error.message : String(error);\n const failures = row.consecutive_failures + 1;\n const backoff = backoffMs(row.interval_ms, failures);\n await store.recordPollFailure(\n row.workflow_id,\n message,\n now.toISOString(),\n new Date(now.getTime() + backoff).toISOString(),\n failures,\n );\n logger.warn(\n `Poll failed for workflow ${row.workflow_id} (${failures}x): @error`,\n message,\n );\n }\n }\n\n // One workflow run per output item; _dedupe_key suppresses 30s repeats.\n // The batch is journaled in one write, then fired with no await, so a stop\n // lands before the write (rewound) or after the firing (the service's).\n private async fireItems(\n store: WorkflowRunStore,\n binding: PieceTriggerBinding,\n items: unknown[],\n now: Date,\n rewind: Rewind,\n success?: PollSuccess,\n parent?: RunParent,\n ): Promise<string[]> {\n if (items.length === 0) {\n if (success) {\n await store.recordPollSuccess(\n success.workflowId,\n success.storeState,\n now.toISOString(),\n success.nextPollAtIso,\n );\n }\n return [];\n }\n const kind = pieceTriggerKind(binding.block);\n const runIds = await store.journalTriggerItems(\n items.map((item) => ({\n dedupeKey: extractDedupeKey(item),\n options: {\n workflowId: binding.workflowId,\n triggerKind: kind,\n triggerPayload: item,\n ...(parent ? { parent } : {}),\n },\n })),\n DEDUPE_TTL_MS,\n now.toISOString(),\n success,\n );\n const journaled = runIds.flatMap((runId, index) =>\n runId ? [{ runId, item: items[index] }] : [],\n );\n if (this.stopped) {\n const error = new TriggerSupervisorStoppedError();\n await this.redeliver(\n journaled.map(({ runId }) => runId),\n rewind,\n error,\n );\n throw error;\n }\n for (const { runId, item } of journaled) {\n this.fire(binding.workflowId, item, kind, runId);\n }\n return journaled.map(({ runId }) => runId);\n }\n\n // Each refused item is recorded once: the rewound cursor delivers it again,\n // so its run is CANCELLED rather than left to rerun beside the redelivery.\n private async redeliver(\n runIds: string[],\n rewind: Rewind,\n error: Error,\n ): Promise<void> {\n if (!(await rewind(runIds))) await this.failRefused(runIds, error);\n }\n\n // Past stop(); a row this cannot fail is left PENDING for the next owner to start.\n private async failRefused(runIds: string[], error: unknown): Promise<void> {\n try {\n const raw = await this.options.store();\n for (const runId of runIds) {\n await raw?.failRun(\n runId,\n error instanceof Error ? error.message : String(error),\n error instanceof Error ? error.name : undefined,\n );\n }\n } catch (failure) {\n logger.warn(\n `Could not fail the refused runs ${runIds.join(\", \")}`,\n failure,\n );\n }\n }\n}\n\n// At most `limit` tasks at once; the rest start in arrival order.\nclass Slots {\n private active = 0;\n private readonly waiting: (() => void)[] = [];\n\n constructor(private readonly limit: number) {}\n\n async run<T>(task: () => Promise<T>): Promise<T> {\n if (this.active >= Math.max(1, this.limit)) {\n // Handed the slot by the task that frees it, so none can overtake.\n await new Promise<void>((resolve) => this.waiting.push(resolve));\n } else {\n this.active++;\n }\n try {\n return await task();\n } finally {\n const next = this.waiting.shift();\n if (next) next();\n else this.active--;\n }\n }\n}\n","// Config parsing for the core webhook trigger: the editor-facing shape of its form.\n// Verification, redaction and payload mechanics belong to the reactor's service.\nimport type {\n WebhookField,\n WebhookHashAlgorithm,\n WebhookSignatureEncoding,\n} from \"@powerhousedao/shared/processors\";\n\n// Prefixes a config error, as the schedule's parser does.\nconst WEBHOOK = \"Webhook\";\n\nexport const WEBHOOK_TRIGGER_KIND = \"webhook\";\n\nexport const DEFAULT_TOLERANCE_SECONDS = 300;\nexport const DEFAULT_DEDUPE_TTL_SECONDS = 300;\nexport const DEFAULT_RESPONSE_STATUS = 202;\nexport const DEFAULT_SYNC_RESPONSE_STATUS = 200;\n\n// Signature layout named by wire format, not by sender; hash and encoding are\n// separate, so no name carries them. Mirrors the reactor's own WebhookScheme.\nexport type WebhookScheme =\n | \"none\"\n | \"token\"\n | \"hmac\"\n | \"hmac-prefixed\"\n | \"hmac-timestamped\";\n\nconst ALGORITHMS = new Set<WebhookHashAlgorithm>([\"sha1\", \"sha256\", \"sha512\"]);\nconst ENCODINGS = new Set<WebhookSignatureEncoding>([\"hex\", \"base64\"]);\n\n// A signed scheme with no secret is a configuration error, not a runtime one.\nconst SIGNED_SCHEMES = new Set<WebhookScheme>([\n \"token\",\n \"hmac\",\n \"hmac-prefixed\",\n \"hmac-timestamped\",\n]);\n\nconst SCHEMES = new Set<WebhookScheme>([\n \"none\",\n \"token\",\n \"hmac\",\n \"hmac-prefixed\",\n \"hmac-timestamped\",\n]);\n\n// The header each format is most often carried in; the author can override it.\nconst DEFAULT_HEADER: Record<WebhookScheme, string> = {\n none: \"\",\n token: \"x-webhook-token\",\n hmac: \"x-signature\",\n \"hmac-prefixed\": \"x-hub-signature-256\",\n \"hmac-timestamped\": \"stripe-signature\",\n};\n\nexport const HTTP_METHODS = [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"HEAD\",\n] as const;\n\nexport interface WebhookConfig {\n // Uppercase; undefined accepts every method.\n methods?: string[];\n scheme: WebhookScheme;\n // Lowercase header the signature/token is read from; \"\" when scheme is none.\n header: string;\n // secret://v1: ref resolved through the secret store at delivery time.\n secretRef?: string;\n // Replay window for the timestamped scheme.\n toleranceSeconds: number;\n // Digest options a sender picks independently of the layout; undefined leaves\n // the reactor's defaults (sha256, hex, algorithm-derived label) in place.\n algorithm?: WebhookHashAlgorithm;\n encoding?: WebhookSignatureEncoding;\n // \"\" is a real value: a prefixed layout carrying no label at all. Only\n // undefined means \"the algorithm's own label\".\n prefix?: string;\n // async answers before the run; sync waits for it and reports the outcome.\n responseMode: \"async\" | \"sync\";\n responseStatus: number;\n // A field echoed back verbatim instead of starting a run; Activepieces\n // spends onHandshake on the same provider round.\n challengeField?: WebhookField;\n // Where the provider's own event id is. Present, it is the authoritative\n // dedup key for redeliveries (plan/08 §7.2).\n dedupeField?: WebhookField;\n dedupeTtlSeconds: number;\n}\n\nfunction asRecord(config: unknown): Record<string, unknown> {\n if (config && typeof config === \"object\" && !Array.isArray(config)) {\n return config as Record<string, unknown>;\n }\n throw new Error(`${WEBHOOK}: the config must be an object`);\n}\n\nfunction toNumber(value: unknown): number | undefined {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n return Number.isNaN(parsed) ? undefined : parsed;\n }\n return undefined;\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() !== \"\"\n ? value.trim()\n : undefined;\n}\n\n// Where a provider put a value: a bare name is a query param or top-level body field.\n// `header:`/`body:` prefixes exist because senders disagree; object form is accepted too.\nfunction parseWebhookField(value: unknown): WebhookField | undefined {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n const record = value as Record<string, unknown>;\n const header = nonEmptyString(record.header);\n if (header) return { header: header.toLowerCase() };\n const body = nonEmptyString(record.body);\n if (body) return { body };\n throw new Error(\n `${WEBHOOK}: a field source must name either \"header\" or \"body\"`,\n );\n }\n const text = nonEmptyString(value);\n if (!text) return undefined;\n // Only these two prefixes are a source. Any other colon is part of the name,\n // so a provider that uses one in a field name still resolves.\n const match = /^(header|body)\\s*:\\s*(\\S.*)$/i.exec(text);\n if (!match) return text;\n const source = match[1].toLowerCase();\n const name = match[2].trim();\n return source === \"header\" ? { header: name.toLowerCase() } : { body: name };\n}\n\n// \"\" is the empty label, kept as given; only an absent prefix is the default.\nfunction parsePrefix(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\") {\n throw new Error(`${WEBHOOK}: \"prefix\" must be a string`);\n }\n return value;\n}\n\n// A named choice, compared exactly and rejected loudly: an unknown hash would\n// otherwise reach the reactor and fail every delivery.\nfunction parseEnum<T extends string>(\n value: unknown,\n allowed: ReadonlySet<T>,\n field: string,\n): T | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\" || !allowed.has(value as T)) {\n throw new Error(\n `${WEBHOOK}: \"${field}\" must be one of ${[...allowed].join(\", \")}`,\n );\n }\n return value as T;\n}\n\nconst METHOD_CHOICES = new Set<string>([...HTTP_METHODS, \"ANY\"]);\n\nconst RESPONSE_MODES = new Set([\"async\", \"sync\"] as const);\n\n// \"ANY\" or no value means every method; the editor spells it \"ANY\".\nfunction parseMethods(value: unknown): string[] | undefined {\n const list = Array.isArray(value) ? value : [value];\n const methods = list.flatMap((method) => {\n const parsed = parseEnum(method, METHOD_CHOICES, \"methods\");\n return parsed ? [parsed] : [];\n });\n if (methods.includes(\"ANY\")) {\n if (methods.length > 1) {\n throw new Error(`${WEBHOOK}: \"ANY\" cannot be listed with methods`);\n }\n return undefined;\n }\n return methods.length ? methods : undefined;\n}\n\n// Config: { methods?, scheme, header?, secretRef?, toleranceSeconds?,\n// responseMode?, responseStatus?, challengeField? }.\nexport function parseWebhookConfig(config: unknown): WebhookConfig {\n const record = asRecord(config);\n // No default: an unverified endpoint must be chosen, never fallen into.\n if (record.scheme === undefined || record.scheme === null) {\n throw new Error(\n `${WEBHOOK}: \"scheme\" is required; choose \"none\" for an endpoint guarded only by its URL token`,\n );\n }\n const scheme = parseEnum(record.scheme, SCHEMES, \"scheme\")!;\n const secretRef = nonEmptyString(record.secretRef);\n if (SIGNED_SCHEMES.has(scheme) && !secretRef) {\n throw new Error(`${WEBHOOK}: the \"${scheme}\" scheme needs a \"secretRef\"`);\n }\n const responseMode =\n parseEnum(record.responseMode, RESPONSE_MODES, \"responseMode\") ?? \"async\";\n const status =\n toNumber(record.responseStatus) ??\n (responseMode === \"sync\"\n ? DEFAULT_SYNC_RESPONSE_STATUS\n : DEFAULT_RESPONSE_STATUS);\n if (!Number.isInteger(status) || status < 200 || status > 599) {\n throw new Error(\n `${WEBHOOK}: \"responseStatus\" must be an integer between 200 and 599`,\n );\n }\n const tolerance =\n toNumber(record.toleranceSeconds) ?? DEFAULT_TOLERANCE_SECONDS;\n if (!Number.isFinite(tolerance) || tolerance <= 0) {\n throw new Error(`${WEBHOOK}: \"toleranceSeconds\" must be a positive number`);\n }\n const dedupeTtl =\n toNumber(record.dedupeTtlSeconds) ?? DEFAULT_DEDUPE_TTL_SECONDS;\n if (!Number.isFinite(dedupeTtl) || dedupeTtl <= 0) {\n throw new Error(`${WEBHOOK}: \"dedupeTtlSeconds\" must be a positive number`);\n }\n return {\n methods: parseMethods(record.methods),\n scheme,\n header: (\n nonEmptyString(record.header) ?? DEFAULT_HEADER[scheme]\n ).toLowerCase(),\n secretRef,\n toleranceSeconds: tolerance,\n responseMode,\n responseStatus: status,\n algorithm: parseEnum(record.algorithm, ALGORITHMS, \"algorithm\"),\n encoding: parseEnum(record.encoding, ENCODINGS, \"encoding\"),\n prefix: parsePrefix(record.prefix),\n challengeField: parseWebhookField(record.challengeField),\n dedupeField: parseWebhookField(record.dedupeField),\n dedupeTtlSeconds: dedupeTtl,\n };\n}\n\n/** The trigger payload, shaped like Activepieces' catch-webhook contract so\n * authored expressions and adapted pieces agree on where a request's parts are. */\nexport interface WebhookPayload {\n method: string;\n path: string;\n headers: Record<string, string>;\n queryParams: Record<string, string>;\n body: unknown;\n}\n","// The probe a sender sends before it will register a webhook endpoint.\n\n// A trigger declares which shape its sender uses; the piece's own onHandshake\n// decides the answer. Only \"is this a probe\" is decided here.\nimport type {\n WebhookReply,\n WebhookRequest,\n} from \"@powerhousedao/shared/processors\";\nimport { WebhookHandshakeStrategy } from \"@powerhousedao/pieces-framework\";\n\n// The framework's strategies as the strings they carry: a bundle inlines its\n// own copy of the enum, so the value is what crosses, never the member.\nconst strategies: Record<`${WebhookHandshakeStrategy}`, string> =\n WebhookHandshakeStrategy;\n\nexport interface PieceHandshake {\n strategy: string;\n paramName?: string;\n}\n\n// The framework's four live strategies. HEAD_REQUEST names a method rather\n// than a field, so it is the one that does not read `paramName`.\nexport function handshakeMatches(\n handshake: PieceHandshake,\n request: WebhookRequest,\n): boolean {\n if (handshake.strategy === strategies.HEAD_REQUEST) {\n return request.method.toUpperCase() === \"HEAD\";\n }\n const name = handshake.paramName;\n\n // A strategy naming no field can never match: treating it as \"always\" would\n // answer every delivery as a probe and the workflow would never run.\n if (!name) return false;\n switch (handshake.strategy) {\n // Presence, not truthiness: a sender may probe with an empty value, and\n // the indexed types claim a string is always there.\n case strategies.HEADER_PRESENT:\n return Object.hasOwn(request.headers, name.toLowerCase());\n case strategies.QUERY_PRESENT:\n return Object.hasOwn(request.queryParams, name);\n case strategies.BODY_PARAM_PRESENT:\n return (\n typeof request.body === \"object\" &&\n request.body !== null &&\n !Array.isArray(request.body) &&\n name in (request.body as Record<string, unknown>)\n );\n default:\n return false;\n }\n}\n\n// The framework's own default onHandshake is a bare 200, so a hook returning\n// nothing is answered that way rather than treated as a refusal.\nexport function handshakeReply(output: unknown): WebhookReply {\n if (typeof output !== \"object\" || output === null) return { status: 200 };\n const record = output as Record<string, unknown>;\n const status = typeof record.status === \"number\" ? record.status : 200;\n const body = record.body;\n if (body === undefined || body === null) return { status };\n if (typeof body === \"string\") return { status, body };\n return {\n status,\n body: JSON.stringify(body),\n contentType: \"application/json\",\n };\n}\n","// Pure config parsing/matching for the document trigger kinds. Each config\n// field is a string or list; an omitted field matches every value.\n\n// Declared by the reactor piece, fired by this host: the processor sees every\n// operation, so matching one against a filter never leaves the process.\nimport {\n blockKey,\n type BlockIdentity,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n DOCUMENT_CREATED_BLOCK,\n DOCUMENT_DELETED_BLOCK,\n DOCUMENT_EVENT_BLOCK,\n} from \"./reactor-piece.js\";\n\nexport { DOCUMENT_CREATED_BLOCK, DOCUMENT_DELETED_BLOCK, DOCUMENT_EVENT_BLOCK };\n\nexport type TriggerKind =\n | \"document-event\"\n | \"document-created\"\n | \"document-deleted\";\n\n// Keyed by block key, so a trigger pinned to any version finds its kind.\nconst TRIGGER_KIND_BY_BLOCK: Record<string, TriggerKind> = {\n [DOCUMENT_EVENT_BLOCK]: \"document-event\",\n [DOCUMENT_CREATED_BLOCK]: \"document-created\",\n [DOCUMENT_DELETED_BLOCK]: \"document-deleted\",\n};\n\nexport function triggerKindOf(block: BlockIdentity): TriggerKind | undefined {\n return TRIGGER_KIND_BY_BLOCK[blockKey(block)];\n}\n\nexport interface DocumentEventFilter {\n documentType?: string[];\n documentId?: string[];\n actionType?: string[];\n}\n\n// Lifecycle triggers match the document-scope CREATE_DOCUMENT /\n// DELETE_DOCUMENT operations, and fall back to the drive's ADD_FILE /\n// DELETE_NODE when no document-scope operation reaches the processor.\nexport interface LifecycleFilter {\n documentType?: string[];\n // A document that lives outside every drive has no drive id, so a set\n // driveId narrows the trigger to drive members.\n driveId?: string[];\n}\n\n// A created/deleted document is announced by a document-scope operation on\n// the document itself: CREATE_DOCUMENT carries the type and name, and\n// DELETE_DOCUMENT is the only signal that a document is really gone.\nexport function lifecycleKindForDocumentAction(\n actionType: string,\n): TriggerKind | undefined {\n if (actionType === \"CREATE_DOCUMENT\") return \"document-created\";\n if (actionType === \"DELETE_DOCUMENT\") return \"document-deleted\";\n return undefined;\n}\n\n// The drive's own view of the same events. ADD_FILE always accompanies a\n// CREATE_DOCUMENT, so this is a fallback; DELETE_NODE is on its own only\n// unlinking the document from the drive, which the trigger still reports.\nexport function lifecycleKindForDriveAction(\n actionType: string,\n): TriggerKind | undefined {\n if (actionType === \"ADD_FILE\") return \"document-created\";\n if (actionType === \"DELETE_NODE\") return \"document-deleted\";\n return undefined;\n}\n\nfunction toList(value: unknown): string[] | undefined {\n if (typeof value === \"string\") return value ? [value] : undefined;\n if (Array.isArray(value)) {\n const strings = value.filter((item) => typeof item === \"string\");\n return strings.length > 0 ? strings : undefined;\n }\n return undefined;\n}\n\nfunction asRecord(config: unknown): Record<string, unknown> {\n if (config === null || typeof config !== \"object\") return {};\n return config as Record<string, unknown>;\n}\n\nexport function parseEventFilter(config: unknown): DocumentEventFilter {\n const record = asRecord(config);\n return {\n documentType: toList(record.documentType),\n documentId: toList(record.documentId),\n actionType: toList(record.actionType),\n };\n}\n\nexport function parseLifecycleFilter(config: unknown): LifecycleFilter {\n const record = asRecord(config);\n return {\n documentType: toList(record.documentType),\n driveId: toList(record.driveId),\n };\n}\n\nconst ok = (list: string[] | undefined, value: string | undefined) =>\n !list || (value !== undefined && list.includes(value));\n\nexport function matchesEventFilter(\n filter: DocumentEventFilter,\n documentType: string,\n documentId: string,\n actionType: string,\n): boolean {\n return (\n ok(filter.documentType, documentType) &&\n ok(filter.documentId, documentId) &&\n ok(filter.actionType, actionType)\n );\n}\n\n// documentType is undefined when it can't be resolved (e.g. a drive node\n// deletion for a document that is already gone); a set type filter then\n// rejects rather than firing on an unconfirmed match. driveId is null for a\n// document that belongs to no drive, which a set driveId also rejects.\nexport function matchesLifecycleFilter(\n filter: LifecycleFilter,\n documentType: string | undefined | null,\n driveId: string | undefined | null,\n): boolean {\n return (\n ok(filter.documentType, documentType ?? undefined) &&\n ok(filter.driveId, driveId ?? undefined)\n );\n}\n","// OAuth2 apps owned by the publisher, configured once per host, instead of a\n// client id and secret on every connection. A connection names an app in its\n// config (`oauth_app`); a sign-in picks that app's client by where the\n// provider sends the browser back: a loopback callback (the switchboard on the\n// user's own machine) takes the desktop (\"installed\") client, which providers\n// accept on any loopback port and which always signs in with PKCE; anything\n// else takes the web client, whose redirect URI the provider has registered.\n// Client secrets live in the host's secret store; the documents only ever\n// hold the app's id.\n//\n// An app may name a relay instead of a web client: a broker the publisher\n// runs that holds the web client's secret. Its one redirect URI is registered\n// with the provider and forwards the provider's answer to the host the\n// sign-in started on (named in the state); its token URL exchanges and\n// refreshes codes for that host, adding the secret. Hosts whose own callback\n// is not registered with the provider, such as cloud environments with a\n// hostname each, sign in through it with PKCE and never hold the secret. A\n// web client file on the host always wins over the relay.\nimport { readFile } from \"node:fs/promises\";\nimport type { SecretStore } from \"../pieces/index.js\";\n\n/** The connection config key naming an app of the registry. */\nexport const OAUTH_APP = \"oauth_app\";\n/**\n * The connection config key for the scopes to ask for instead of the piece's\n * own: a list, or one space-separated string. A read-only integration asks\n * for `calendar.readonly` where the piece would ask to edit too.\n */\nexport const OAUTH_SCOPES = \"oauth_scopes\";\n\nexport type OAuthClientKind = \"web\" | \"desktop\";\n\nexport interface OAuthAppClient {\n appId: string;\n kind: OAuthClientKind;\n clientId: string;\n clientSecretRef: string;\n}\n\nexport interface OAuthAppRegistry {\n client(appId: string, kind: OAuthClientKind): OAuthAppClient | undefined;\n clients(appId: string): OAuthAppClient[];\n /** The app's relay, or undefined when it has none. */\n relay(appId: string): OAuthAppRelay | undefined;\n}\n\n/** One app as a host configures it: per client kind, the provider's client file. */\nexport interface OAuthAppDefinition {\n id: string;\n /** Paths to the provider's downloaded client files (Google's client_secret_*.json). */\n clients: Partial<Record<OAuthClientKind, string>>;\n /**\n * The broker a web sign-in goes through when the host has no web client\n * file. Absent, a web sign-in needs the web client.\n */\n relay?: OAuthAppRelay;\n}\n\n/**\n * A token broker for an app's web client: the provider sends the browser to\n * `redirectUri`, which forwards to the callback the state names; `tokenUrl`\n * takes the code exchange and every refresh, with `clientId` and no secret.\n */\nexport interface OAuthAppRelay {\n clientId: string;\n redirectUri: string;\n tokenUrl: string;\n}\n\nfunction httpsUrl(raw: unknown): string | undefined {\n if (typeof raw !== \"string\" || raw === \"\") return undefined;\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" || url.username || url.password) {\n return undefined;\n }\n return url.href;\n}\n\n/**\n * A relay as configured, or the reason it cannot be used: it needs a client\n * id and two absolute https URLs without credentials.\n */\nexport function parseRelay(raw: unknown): OAuthAppRelay | string {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return \"not an object with clientId, redirectUri and tokenUrl\";\n }\n const { clientId, redirectUri, tokenUrl } = raw as Record<string, unknown>;\n if (typeof clientId !== \"string\" || clientId === \"\") {\n return \"no clientId\";\n }\n const redirect = httpsUrl(redirectUri);\n if (!redirect) return \"redirectUri is not an absolute https URL\";\n const token = httpsUrl(tokenUrl);\n if (!token) return \"tokenUrl is not an absolute https URL\";\n return { clientId, redirectUri: redirect, tokenUrl: token };\n}\n\nexport class StaticOAuthAppRegistry implements OAuthAppRegistry {\n constructor(\n private readonly entries: readonly OAuthAppClient[],\n private readonly relays: ReadonlyMap<string, OAuthAppRelay> = new Map(),\n ) {}\n\n client(appId: string, kind: OAuthClientKind): OAuthAppClient | undefined {\n return this.entries.find((e) => e.appId === appId && e.kind === kind);\n }\n\n clients(appId: string): OAuthAppClient[] {\n return this.entries.filter((e) => e.appId === appId);\n }\n\n relay(appId: string): OAuthAppRelay | undefined {\n return this.relays.get(appId);\n }\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"::1\"]);\n\n/** Desktop for a callback to this machine, web for one the provider reaches over the internet. */\nexport function clientKindFor(redirectUri: string): OAuthClientKind {\n let host: string;\n try {\n host = new URL(redirectUri).hostname;\n } catch {\n return \"web\";\n }\n return LOOPBACK.has(host) ? \"desktop\" : \"web\";\n}\n\n/**\n * How this host signs in with a publisher's app for a callback: the\n * desktop client for one to this machine; else the web client when the host\n * has its file; else the app's relay; else not at all.\n */\nexport type OAuthSignIn =\n | { mode: \"desktop\" | \"web\"; client: OAuthAppClient }\n | { mode: \"relay\"; relay: OAuthAppRelay }\n | { mode: \"none\"; kind: OAuthClientKind };\n\nexport function oauthSignInFor(\n apps: OAuthAppRegistry,\n appId: string,\n redirectUri: string,\n): OAuthSignIn {\n const kind = clientKindFor(redirectUri);\n const client = apps.client(appId, kind);\n if (client) return { mode: kind, client };\n const relay = kind === \"web\" ? apps.relay(appId) : undefined;\n return relay ? { mode: \"relay\", relay } : { mode: \"none\", kind };\n}\n\n/**\n * Config key the runtime writes after a sign-in: the scopes the provider\n * granted (its token response's `scope`, else the ones asked for). A\n * connection whose `oauth_scopes` reach beyond them needs a new sign-in.\n */\nexport const OAUTH_GRANTED_SCOPES = \"oauth_granted_scopes\";\n\n/** What a sign-in was granted: the token's own `scope`, else what the connection asked for. */\nexport function grantedScopes(\n tokenScope: string | undefined,\n config: Record<string, unknown>,\n): string[] | undefined {\n const granted = (tokenScope ?? \"\").split(/[\\s,]+/).filter(Boolean);\n return granted.length > 0 ? granted : scopesOverride(config);\n}\n\n/** The scopes a connection asks for instead of the piece's, or undefined to keep the piece's. */\nexport function scopesOverride(\n config: Record<string, unknown>,\n): string[] | undefined {\n const raw = config[OAUTH_SCOPES];\n const list = Array.isArray(raw)\n ? raw.filter((s): s is string => typeof s === \"string\")\n : typeof raw === \"string\"\n ? raw.split(/\\s+/)\n : [];\n const scopes = list.map((s) => s.trim()).filter(Boolean);\n return scopes.length > 0 ? scopes : undefined;\n}\n\n/**\n * The client id and secret in a provider's client file: Google's\n * `{ installed | web: { client_id, client_secret } }`, or the two keys at the\n * top level.\n */\nexport function parseClientFile(text: string): {\n clientId: string;\n clientSecret: string;\n} {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new Error(\"not JSON\");\n }\n const root = (parsed ?? {}) as Record<string, unknown>;\n const inner = (root.installed ?? root.web ?? root) as Record<string, unknown>;\n const clientId = inner.client_id;\n const clientSecret = inner.client_secret;\n if (typeof clientId !== \"string\" || !clientId) {\n throw new Error(\"no client_id\");\n }\n if (typeof clientSecret !== \"string\" || !clientSecret) {\n throw new Error(\"no client_secret\");\n }\n return { clientId, clientSecret };\n}\n\n/** The label a client secret carries in the store, so a restart finds it again. */\nexport function clientSecretLabel(appId: string, kind: OAuthClientKind) {\n return `oauth-app:${appId}:${kind}`;\n}\n\n/**\n * Reads each configured client file and keeps its secret in the store under a\n * fixed label: created the first time, rotated when the file changed, left\n * alone otherwise. A client whose file cannot be read is skipped with the\n * reason, so one bad file does not take the others down. A relay without a\n * client id or with a URL that is not absolute https is dropped with the\n * reason.\n */\nexport async function loadOAuthApps(\n definitions: readonly OAuthAppDefinition[],\n store: SecretStore,\n options: {\n read?: (path: string) => Promise<string>;\n onSkip?: (appId: string, kind: OAuthClientKind, reason: string) => void;\n onRelayDropped?: (appId: string, reason: string) => void;\n } = {},\n): Promise<StaticOAuthAppRegistry> {\n const read = options.read ?? ((path: string) => readFile(path, \"utf8\"));\n const existing = new Map(\n (await store.list())\n // A document's secret may share the label; only a host secret is the app's.\n .filter((s) => s.status === \"ACTIVE\" && s.label && s.ownerId === null)\n .map((s) => [s.label!, s.ref]),\n );\n const entries: OAuthAppClient[] = [];\n const relays = new Map<string, OAuthAppRelay>();\n for (const app of definitions) {\n if (app.relay !== undefined) {\n const relay = parseRelay(app.relay);\n if (typeof relay === \"string\") options.onRelayDropped?.(app.id, relay);\n else relays.set(app.id, relay);\n }\n for (const kind of [\"desktop\", \"web\"] as const) {\n const path = app.clients[kind];\n if (!path) continue;\n let client: { clientId: string; clientSecret: string };\n try {\n client = parseClientFile(await read(path));\n } catch (error) {\n options.onSkip?.(\n app.id,\n kind,\n `${path}: ${error instanceof Error ? error.message : String(error)}`,\n );\n continue;\n }\n const label = clientSecretLabel(app.id, kind);\n let ref = existing.get(label);\n if (ref) {\n if ((await store.get(ref, null)) !== client.clientSecret) {\n await store.rotate(ref, client.clientSecret);\n }\n } else {\n ref = (\n await store.create({\n value: client.clientSecret,\n label,\n ownerId: null,\n })\n ).ref;\n }\n entries.push({\n appId: app.id,\n kind,\n clientId: client.clientId,\n clientSecretRef: ref,\n });\n }\n }\n return new StaticOAuthAppRegistry(entries, relays);\n}\n","// The workflow runtime: one instance per host, serving the GraphQL subgraph\n// (config + manual fire) and the workflow-triggers read model alike.\nimport {\n blockKey,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n checkTriggerStrategy,\n coerceManualPayload,\n containsDocumentRef,\n documentRefsIn,\n expandDocumentRefs,\n parseManualInputs,\n type DocumentReference,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n registerTelemetryGauge,\n type ModelManifestEntry,\n} from \"@powerhousedao/reactor\";\nimport type {\n IWebhookEndpoints,\n IWebhookScope,\n WebhookPolicy,\n WebhookReply,\n WebhookRequest,\n} from \"@powerhousedao/shared/processors\";\nimport type { WorkflowCaller, WorkflowRuntimeHostDeps } from \"./host.js\";\n\nimport {\n isLoopStep,\n loopConfigHash,\n loopStructure,\n} from \"../pieces/engine/loops.js\";\nimport { loopItems } from \"../pieces/core/flow.js\";\nimport {\n blockLabel,\n blockPorts,\n builtinPiece,\n containsRedactedMarker,\n describeBuiltinPiece,\n isHostBound,\n stepBlock,\n triggerBlock,\n declaredConnectionIds,\n declaredReactorConnectionIds,\n DEFAULT_EGRESS_POLICY,\n errorNameOf,\n resolvedBlock,\n stepConfigHash,\n pieceModuleRef,\n type IPieceWorker,\n PieceWorkerError,\n PieceWorkerPool,\n PieceWorkerTimeoutError,\n rememberSecrets,\n resolveStepInput,\n runWorkflow,\n RUN_DEADLINE_ERROR_NAME,\n UnsupportedPieceFeatureError,\n authMethodFor,\n isIndeterminateError,\n type PieceAuthDescriptor,\n type BlockDefaults,\n type BlockExecutor,\n type BlockResolution,\n type LocalPiece,\n type ParsedBlockType,\n type PieceTarget,\n type PieceModuleRef,\n type CheckConnectionOutcome,\n type PieceDescriptor,\n type EgressPolicy,\n type ExpressionScope,\n type PieceWorkerSession,\n type ReplayedStep,\n type CarriedStep,\n type WaitpointPort,\n type FlowsPort,\n type HostHttpRequest,\n type HostHttpResponse,\n FLOWS_LIST,\n type RunResponse,\n canonicalJson,\n hashOf,\n unavailableValue,\n type ModelManifestSource,\n type ReactorTap,\n type StepReactorRequest,\n SecretCreatorMismatchError,\n type SecretProvider,\n type SecretStat,\n type SecretStore,\n type StepExecutionRecord,\n type WorkflowRunResult,\n} from \"../pieces/index.js\";\nimport {\n childLogger,\n garbageCollect,\n generateId,\n hashDocumentStateForScope,\n isDenied,\n operationsByActionType,\n sortOperations,\n type Operation,\n type Action,\n type DocumentModelModule,\n type ILogger,\n type OperationWithContext,\n} from \"document-model\";\nimport {\n actions as connectionActions,\n parseReactorConnectionConfig,\n type ConnectionDocument,\n} from \"@powerhousedao/workflow/document-models/connection\";\nimport { idTokenEmail } from \"./id-token.js\";\nimport {\n exchangeCode,\n OAUTH_CLIENT_ID,\n OAUTH_CLIENT_SECRET,\n OAUTH_TOKEN,\n OAuthAttemptStore,\n OAuthError,\n StoreTokenRefresher,\n type OAuthAttemptView,\n type OAuthSignInRefusedError,\n type OAuthStart,\n type OAuthTokenRefresher,\n} from \"./oauth.js\";\nimport {\n actions as workflowActions,\n reducer as workflowReducer,\n utils as workflowUtils,\n type WorkflowDocument,\n type WorkflowState,\n} from \"@powerhousedao/workflow/document-models/workflow\";\nimport {\n DOCUMENT_CREATE_BLOCK,\n DOCUMENT_CREATED_BLOCK,\n DOCUMENT_DELETED_BLOCK,\n DOCUMENT_DISPATCH_BLOCK,\n DOCUMENT_EVENT_BLOCK,\n DOCUMENT_FIND_BLOCK,\n DOCUMENT_GET_BLOCK,\n DOCUMENT_SCHEMA_BLOCK,\n DOCUMENT_TYPES_BLOCK,\n staticString,\n} from \"./reactor-piece.js\";\nimport {\n documentEventTree,\n documentFindTree,\n documentReferenceTree,\n documentTree,\n documentSchemaTree,\n documentTypesTree,\n fieldsFromSdl,\n fromOutputSchema,\n hasOutputSchemaFields,\n fromSample,\n lifecycleTriggerTree,\n manualTriggerTree,\n scheduleTriggerTree,\n treeValue,\n webhookTriggerTree,\n type OutputTree,\n type OutputTreeNode,\n} from \"./output-tree.js\";\nimport {\n fetchPieceActions,\n fetchPieceCatalog,\n fetchPieceDetail,\n fetchPieceTriggers,\n clientAuth,\n type PieceActionsResult,\n type PieceSummary,\n type PieceTriggersResult,\n} from \"./piece-catalog.js\";\nimport {\n actionsResult,\n catalogEntry,\n detailResult,\n localSearchPiece,\n triggersResult,\n} from \"./local-catalog.js\";\nimport {\n indexPieces,\n searchPieces,\n warmSearchIndex,\n type BlockSearchIndex,\n type PieceSearchFilter,\n type PieceSearchResult,\n} from \"./block-search.js\";\nimport { installedPiece, installedPieces } from \"./piece-registry.js\";\nimport { BlockResolver } from \"./block-resolver.js\";\nimport {\n bundleCacheDir,\n configuredEgress,\n createBlockExecutor,\n DocumentConnectionResolver,\n pieceResolver,\n resolveConnectionAuth,\n stepDefinition,\n toWorkflowDefinition,\n truncateForLog,\n} from \"./lib.js\";\nimport { packageFromConnectorId } from \"./connector-id.js\";\nimport { parseScheduleConfig, schedulePayload } from \"./schedule.js\";\nimport type { AttachmentPort, PieceOrigin } from \"../pieces/index.js\";\nimport {\n isNotHereYet,\n SYNC_WAIT_MS,\n waitForSync,\n type WorkflowAccessOptions,\n} from \"./sync-wait.js\";\nimport { createAttachmentPort } from \"./attachment-port.js\";\nimport {\n createPieceStorePort,\n PROJECT_SCOPE_KEY,\n testPartitionKey,\n} from \"./piece-store-port.js\";\nimport {\n currentAttachmentOrigins,\n currentRunUser,\n currentWorkflowId,\n runScopeStats,\n withRunScope,\n type RunAttachmentOrigins,\n type RunUser,\n} from \"./run-scope.js\";\nimport {\n assertConnectionReadable,\n assertReactorConnectionsReadable,\n authEnforced,\n} from \"./reactor-access.js\";\nimport {\n accessDenied,\n isReactorError,\n ReactorAccessDeniedError,\n} from \"./reactor-errors.js\";\nimport { buildReactorRunScope } from \"./run-scope-builder.js\";\nimport {\n designTimeScope,\n NO_JOURNAL,\n reactorTap,\n runJournal,\n unboundReactorConnection,\n} from \"./reactor-session.js\";\nimport {\n PUBLISH_WORKFLOW,\n publishRunUser,\n runUserOfOperation,\n} from \"./run-user.js\";\nimport {\n APPROVAL_BLOCK,\n ASSERT_BLOCK,\n BRANCH_BLOCK,\n LOOP_BLOCK,\n ROUTER_BLOCK,\n DELAY_BLOCK,\n isCoreBlock,\n MANUAL_BLOCK,\n SCHEDULE_BLOCK,\n STOP_BLOCK,\n WAIT_FOR_WEBHOOK_BLOCK,\n WEBHOOK_BLOCK,\n} from \"./core-blocks.js\";\nimport { LocalEncryptedSecretStore } from \"./secret-store.js\";\nimport { runnableDefinition } from \"./runnable.js\";\nimport { resolveVariables } from \"./variables.js\";\nimport {\n draftStepDef,\n scopeReferences,\n testStatusOf,\n triggerSamplePayload,\n untestedError,\n upstreamStepIds,\n type StepTestResult,\n type TestSample,\n} from \"./step-test.js\";\nimport {\n MAX_LIST_RUNS,\n TEST_TRIGGER_KIND,\n WorkflowRunStore,\n isTruncatedStepPayload,\n journaledTriggerDocumentIds,\n triggerDocumentIds,\n WAITING_RUN_STATUS,\n type ErasedRuns,\n type FireClaim,\n type RunPinRow,\n type WaitpointRow,\n type RunRow,\n type StepExecutionRow,\n type TriggerStateRow,\n} from \"./store.js\";\nimport { ParkState } from \"./park-state.js\";\nimport {\n CALL_FLOW_ACTION,\n FAIL_PARENT_HEADER,\n HOST_WAITPOINTS_URL,\n hostBody,\n hostRoute,\n isCallableFlow,\n jsonReply,\n localCallback,\n PARENT_RUN_HEADER,\n populatedFlow,\n SUBFLOWS_PIECE,\n type PopulatedFlow,\n} from \"./subflows.js\";\nimport { decodeRunCursor, encodeRunCursor } from \"./run-cursor.js\";\nimport {\n CANCELLED_RUN_STATUS,\n concurrencyLimit,\n effectiveRunPolicy,\n maxSuspensionMs,\n UNENFORCED_POLICY,\n type EffectiveRunPolicy,\n} from \"./policy.js\";\nimport { WaitpointPoller } from \"./waitpoint-poller.js\";\nimport { WorkflowRunGate } from \"./run-gate.js\";\nimport { DEFAULT_ADMIT_MAX_ELU, RunDispatcher } from \"./run-dispatcher.js\";\nimport { EventLoopMonitor } from \"./event-loop.js\";\nimport {\n RETENTION_SWEEP_INTERVAL_MS,\n runRetentionMs,\n sweepRetention,\n} from \"./run-retention.js\";\nimport { isShutdownRefusal, WorkflowRuntimeClosedError } from \"./shutdown.js\";\nimport {\n TriggerSupervisor,\n type PieceTriggerBinding,\n type TriggerBinding,\n} from \"./trigger-supervisor.js\";\nimport {\n parseWebhookConfig,\n WEBHOOK_TRIGGER_KIND,\n type WebhookConfig,\n type WebhookPayload,\n} from \"./webhook.js\";\nimport {\n handshakeMatches,\n handshakeReply,\n type PieceHandshake,\n} from \"./piece-handshake.js\";\nimport {\n lifecycleKindForDocumentAction,\n lifecycleKindForDriveAction,\n matchesEventFilter,\n matchesLifecycleFilter,\n parseEventFilter,\n parseLifecycleFilter,\n triggerKindOf,\n type DocumentEventFilter,\n type LifecycleFilter,\n type TriggerKind,\n} from \"./trigger-filters.js\";\nimport {\n loadOAuthApps,\n grantedScopes,\n OAUTH_APP,\n OAUTH_GRANTED_SCOPES,\n OAUTH_SCOPES,\n oauthSignInFor,\n scopesOverride,\n type OAuthAppRegistry,\n type OAuthSignIn,\n} from \"./oauth-apps.js\";\nimport { SpanStatusCode, type Span } from \"@opentelemetry/api\";\nimport { createHash, randomBytes, randomUUID } from \"node:crypto\";\nimport { validateHeaderName, validateHeaderValue } from \"node:http\";\nimport type {\n ApprovalRequest,\n ResolveWaitpointInput,\n WaitingRunsArgs,\n WaitpointDescription,\n WaitpointRecord,\n WaitpointResumePayload,\n WaitpointStatus,\n} from \"./waitpoint-types.js\";\nimport {\n WAITPOINT_EXPIRED_ERROR_NAME,\n WAITPOINT_NOT_LIVE_ERROR_NAME,\n} from \"./waitpoint-types.js\";\nimport { tracedSteps, WorkflowTelemetry } from \"../telemetry.js\";\n\n/** Why a firing was journaled CANCELLED without running, when it was. */\nexport type FiringRefusal =\n | \"parked\"\n | \"singleton\"\n | \"stale\"\n | \"queue-full\"\n | \"expired\"\n // An operator cancelled it while it queued or waited.\n | \"cancelled\";\n\nexport { WorkflowRuntimeClosedError };\n\nexport type PersistedRunResult = WorkflowRunResult & {\n runId: string | null;\n refusal?: FiringRefusal;\n};\n\n// A fired run's span, and whether a check refused it before it began.\ninterface RunTrace {\n span: Span;\n refused: boolean;\n}\n\n// A rerun's journaled outputs, replayed instead of executed.\ntype RunResume = {\n completedSteps: Map<string, ReplayedStep>;\n loopItems: Map<string, unknown[]>;\n rerunOf: string;\n};\n\n// The piece a resolved block type loads.\nfunction targetOf(block: ParsedBlockType): PieceTarget {\n return {\n name: block.packageName,\n version: block.version,\n ...(block.source ? { source: block.source } : {}),\n };\n}\n\nfunction localTarget(piece: LocalPiece): PieceTarget {\n return { name: piece.name, version: piece.version, source: \"local\" };\n}\n\nfunction bindingTarget(binding: PieceTriggerBinding): PieceTarget {\n return {\n name: binding.packageName,\n version: binding.version,\n ...(binding.source ? { source: binding.source } : {}),\n };\n}\n\nexport interface ConnectionSummary {\n id: string;\n name: string;\n connectorId: string;\n authType: string;\n status: string;\n accountLabel: string | null;\n}\n\nexport interface ConnectionCheckResult {\n ok: boolean;\n detail: string | null;\n accountLabel: string | null;\n}\n\n/** A journal row with the steps that belong to it, as the subgraph serves it. */\n// Loop iteration rows a run's detail serves.\nexport const RUN_ITERATIONS_LIMIT = 1000;\n\nexport interface RunRecord {\n row: RunRow;\n steps: StepExecutionRow[];\n // Iteration rows journaled, when `steps` holds only the first of them.\n iterationsTotal?: number;\n}\n\nexport interface RunsArgs {\n workflowId?: string;\n driveId?: string;\n limit?: number;\n // Left out in SQL, so they never cost a page its rows.\n excludeTriggerKinds?: string[];\n // False leaves each step's input and output out (null).\n withStepData?: boolean;\n}\n\nexport interface RunsPageArgs extends RunsArgs {\n // From a previous page; resumes after its last run.\n cursor?: string | null;\n}\n\nexport interface RunPage {\n records: RunRecord[];\n hasNextPage: boolean;\n // Pass back as `cursor` for the next page; null when the page is empty.\n cursor: string | null;\n}\n\n// Rows one page request may read past unreadable ones before it returns short.\nconst RUNS_SCAN_LIMIT = 1000;\n\n/** One draft block as this reactor resolves it. */\nexport interface BlockResolutionRecord {\n stepId: string;\n pieceName: string;\n // The version the block pins.\n pieceVersion: string;\n name: string;\n kind: \"action\" | \"trigger\";\n resolvedVersion: string | null;\n source: string | null;\n match: string;\n note: string | null;\n latestVersion: string | null;\n}\n\nexport interface TriggerTestOptions extends WorkflowAccessOptions {\n // The core manual trigger: the sample payload.\n payload?: unknown;\n // The core webhook trigger: how long to wait for a delivery, capped at 5 minutes.\n timeoutMs?: number;\n}\n\nconst WEBHOOK_TEST_TIMEOUT_MS = 5 * 60_000;\n\n// How often PENDING rows another owner left are swept up, and their minimum age.\nexport const PENDING_SWEEP_INTERVAL_MS = 60_000;\n\ninterface WebhookTest {\n config: WebhookConfig;\n resolve: (payload: WebhookPayload) => void;\n reject: (error: Error) => void;\n timer: NodeJS.Timeout;\n}\n\nfunction draftBlocks(state: WorkflowState): { id: string; block: BlockRef }[] {\n return [\n ...(state.trigger\n ? [{ id: state.trigger.id, block: triggerBlock(state.trigger) }]\n : []),\n ...state.steps.map((step) => ({ id: step.id, block: stepBlock(step) })),\n ];\n}\n\nexport interface WebhookEndpointRecord {\n workflowId: string;\n url: string;\n absoluteUrl: boolean;\n armed: boolean;\n createdAt: string;\n}\n\n// Matches the piece worker's default action timeout; a hung check kills the\n// worker instead of hanging the mutation.\nconst CHECK_TIMEOUT_MS = 30_000;\n// Same convention for the design-time descriptor build; a bundle that hangs\n// on import kills the worker instead of the request.\nconst DESCRIBE_TIMEOUT_MS = 30_000;\n\n// Bounded because the registry is seeded once, from the constructor: a sweep\n// that fails past this is reported rather than retried forever.\nconst SEED_ATTEMPTS = 3;\nconst SEED_RETRY_BASE_MS = 250;\n\nconst sleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms).unref());\n\nconst logger = childLogger([\"workflow\", \"runtime\"]);\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\";\nconst WORKFLOW_DOCUMENT_TYPE = \"powerhouse/workflow\";\nconst CONNECTION_DOCUMENT_TYPE = \"powerhouse/connection\";\n// Document creation, deletion and parent linking are appended to the document\n// itself in this scope, not to any drive.\nconst DOCUMENT_SCOPE = \"document\";\n// The relationship type the reactor uses for containment: a drive (or any\n// parent document) -> child document edge.\nconst CHILD_RELATIONSHIP = \"child\";\n\n// What identifies an operation to both dedupe lines below. The ordinal is the\n// reactor's own sequence; a batch without one falls back to the document's.\nfunction operationKey(op: OperationWithContext): string {\n return op.context.ordinal > 0\n ? `o:${op.context.ordinal}`\n : `${op.context.documentId}:${op.context.scope}:${op.context.branch}:${op.operation.index}`;\n}\n\n// A day, because the redelivery this guards is a restart replaying from a\n// cursor that trailed the runs it had already journaled.\nconst OPERATION_DEDUPE_TTL_MS = 24 * 60 * 60_000;\n\n// A journal that failed to open is tried again, no sooner than this, doubling.\nconst STORE_REOPEN_MS = 1_000;\nconst MAX_STORE_REOPEN_MS = 60_000;\n\n// Fires run without a journal row that this process remembers, oldest dropped.\nconst UNJOURNALED_FIRES_LIMIT = 65_536;\n\nfunction stringField(\n record: Record<string, unknown>,\n key: string,\n): string | undefined {\n const value = record[key];\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\nconst ABSENT_ERROR_NAMES = new Set([\n \"DocumentNotFoundError\",\n \"DocumentPurgedError\",\n \"DocumentDeletedError\",\n]);\n\n// Absence is reported by name: the error may cross an RPC boundary.\nfunction isAbsent(error: unknown): boolean {\n return error instanceof Error && ABSENT_ERROR_NAMES.has(error.name);\n}\n\n// A marker names its document's type in its input; the context agrees.\nfunction purgedWorkflowIds(markers: OperationWithContext[]): string[] {\n const ids = markers\n .filter(\n ({ operation, context }) =>\n (stringField(inputRecord(operation.action.input), \"documentType\") ??\n context.documentType) === WORKFLOW_DOCUMENT_TYPE,\n )\n .map(({ context }) => context.documentId);\n return [...new Set(ids)];\n}\n\nfunction inputRecord(input: unknown): Record<string, unknown> {\n if (input === null || typeof input !== \"object\") return {};\n return input as Record<string, unknown>;\n}\n\n// Where a lifecycle payload's driveId / parentId come from: CREATE_DOCUMENT knows\n// nothing about containment, so the parent is read off siblings in the same job.\nexport interface LifecycleParentHint {\n // Set only by a drive operation, which is the only place the drive is named\n // outright.\n driveId?: string;\n // A drive node's parentFolder, or the parent document of a \"child\" edge.\n parentId?: string;\n // The document id a relationship names as its parent, whose type decides\n // whether it is a drive.\n parentCandidate?: string;\n}\n\n// Indexes operations by the document a lifecycle event is about. addFile writes CREATE_DOCUMENT\n// and ADD_RELATIONSHIP in one job (drive known without a read); the drive's ADD_FILE lands later.\nexport function collectLifecycleParentHints(\n operations: OperationWithContext[],\n): Map<string, LifecycleParentHint> {\n const hints = new Map<string, LifecycleParentHint>();\n const merge = (documentId: string, hint: LifecycleParentHint) => {\n const existing = hints.get(documentId);\n hints.set(documentId, existing ? { ...existing, ...hint } : hint);\n };\n for (const { operation, context } of operations) {\n const actionType = operation.action.type;\n const input = inputRecord(operation.action.input);\n if (context.scope === DOCUMENT_SCOPE) {\n if (\n actionType !== \"ADD_RELATIONSHIP\" &&\n actionType !== \"REMOVE_RELATIONSHIP\"\n ) {\n continue;\n }\n if (stringField(input, \"relationshipType\") !== CHILD_RELATIONSHIP) {\n continue;\n }\n const target = stringField(input, \"targetId\");\n const source = stringField(input, \"sourceId\");\n if (!target || !source) continue;\n merge(target, { parentId: source, parentCandidate: source });\n continue;\n }\n if (context.documentType !== DRIVE_DOCUMENT_TYPE) continue;\n if (actionType !== \"ADD_FILE\" && actionType !== \"DELETE_NODE\") continue;\n const nodeId = stringField(input, \"id\");\n if (!nodeId) continue;\n // parentFolder is absent at a drive's root, where the document has no\n // folder parent; the drive itself is reported as driveId, not as parentId.\n merge(nodeId, {\n driveId: context.documentId,\n parentId: stringField(input, \"parentFolder\"),\n });\n }\n return hints;\n}\n\n// User-visible detail of a failed worker request; a piece error contributes only\n// its message, as its serialized properties may hold echoed credentials.\nfunction pieceFailureDetail(error: unknown, timeoutDetail: string): string {\n if (error instanceof PieceWorkerTimeoutError) return timeoutDetail;\n if (error instanceof PieceWorkerError) return error.serialized.message;\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction checkFailureDetail(error: unknown): string {\n return pieceFailureDetail(\n error,\n `Connection check timed out after ${Math.round(CHECK_TIMEOUT_MS / 1000)}s`,\n );\n}\n\ntype TriggerRegistration = {\n workflowId: string;\n} & (\n | { kind: \"document-event\"; filter: DocumentEventFilter }\n | { kind: \"document-created\" | \"document-deleted\"; filter: LifecycleFilter }\n // Request-driven; the reactor mints and owns the endpoint's token.\n | { kind: \"webhook\"; config: WebhookConfig }\n // A piece whose strategy is WEBHOOK: the supervisor still owns its\n // enable/disable state, but requests drive it instead of the tick.\n | { kind: \"piece-webhook\"; binding: PieceTriggerBinding }\n // Timer-driven kinds live in the TriggerSupervisor.\n | { kind: \"piece\" | \"schedule\" }\n);\n\nexport const PIECE_WEBHOOK_KIND = \"piece-webhook\";\n\n// Kinds whose enable/disable lifecycle the supervisor owns, so leaving one\n// has to release its registration.\nconst SUPERVISED_KINDS = new Set([\"piece\", \"schedule\", PIECE_WEBHOOK_KIND]);\n\n// Whether there is anything to authenticate with: a secret handle, or a\n// non-secret config value such as a base URL.\nfunction hasCredentials(state: {\n config?: unknown;\n secretRefs?: { ref: string }[];\n}): boolean {\n if ((state.secretRefs ?? []).length > 0) return true;\n const config = state.config;\n return (\n typeof config === \"object\" &&\n config !== null &&\n Object.keys(config as Record<string, unknown>).length > 0\n );\n}\n\n// How long one source's version listing may take; registration and seeding\n// await it, and a source that does not answer in time contributes nothing.\nconst PIECE_VERSION_LOOKUP_TIMEOUT_MS = 2_000;\n\n// How long before a trigger left unresolved by an unreachable catalog is tried\n// again, doubling to the cap. A reactor that booted during a brief outage has\n// to arm itself once it is over, not wait to be restarted.\nconst UNREACHABLE_RETRY_MS = 30_000;\nconst UNREACHABLE_RETRY_CAP_MS = 15 * 60_000;\n\n// Shared so no refusal path can accidentally answer with a distinguishing body.\nconst UNAUTHORIZED: WebhookReply = { status: 401 };\n\nconst JSON_CONTENT_TYPE = \"application/json; charset=utf-8\";\n\n// How long a sync-mode delivery holds the provider's socket; beyond this the run\n// keeps going and the provider is told so, lest a wedged step tie up connections.\nconst DELIVERY_TIMEOUT_MS =\n Number(process.env.PH_WORKFLOWS_WEBHOOK_TIMEOUT_MS) || 30_000;\n\nconst TIMED_OUT = Symbol(\"webhook delivery timed out\");\n\nconst WEBHOOK_REDELIVERED_REASON =\n \"Redelivered: the runtime shut down before this delivery ran, and the sender was told to retry\";\n\n/** Resolves to TIMED_OUT, and never keeps the process alive waiting to. */\nfunction timeout(ms: number): Promise<typeof TIMED_OUT> {\n return new Promise((resolve) => {\n setTimeout(() => resolve(TIMED_OUT), ms).unref();\n });\n}\n\n/** Shaped like Activepieces' catch-webhook contract so authored expressions and adapted\n * pieces agree where a request's parts are; headers arrive redacted, body decoded. */\nfunction webhookPayload(request: WebhookRequest): WebhookPayload {\n return {\n method: request.method,\n path: request.path,\n headers: request.headers,\n queryParams: request.queryParams,\n body: request.body,\n };\n}\n\nexport const POLL_INTERVAL_CONFIG_KEY = \"pollEverySeconds\";\n\n// pollEverySeconds is ours, not the piece's: lifted out of the trigger config so it\n// never reaches the piece as a prop, yet a change to it alone still rewrites the hash.\nexport function splitPollInterval(config: Record<string, unknown>): {\n config: Record<string, unknown>;\n pollIntervalMs?: number;\n} {\n if (!(POLL_INTERVAL_CONFIG_KEY in config)) return { config };\n const { [POLL_INTERVAL_CONFIG_KEY]: raw, ...rest } = config;\n const seconds = typeof raw === \"string\" ? Number(raw) : raw;\n if (\n typeof seconds !== \"number\" ||\n !Number.isFinite(seconds) ||\n seconds <= 0\n ) {\n logger.warn(\n `Ignoring ${POLL_INTERVAL_CONFIG_KEY}=${JSON.stringify(raw)}: expected a positive number of seconds`,\n );\n return { config: rest };\n }\n return { config: rest, pollIntervalMs: Math.round(seconds * 1000) };\n}\n\nfunction parseWorkflowState(\n resultingState?: string,\n): WorkflowState | undefined {\n if (!resultingState) return undefined;\n try {\n return JSON.parse(resultingState) as WorkflowState;\n } catch {\n return undefined;\n }\n}\n\n// What a registration is decided from, so a draft edit can be told apart.\n// A sync webhook's answer to a firing that did not succeed. A deliberate\n// refusal is a 409 and an overloaded lane a 429, so a provider does not retry\n// either as a server error; anything else is one.\nfunction refusalStatus(refusal: FiringRefusal | undefined): number {\n switch (refusal) {\n case \"parked\":\n case \"singleton\":\n case \"stale\":\n case \"cancelled\":\n return 409;\n case \"queue-full\":\n case \"expired\":\n return 429;\n default:\n return 500;\n }\n}\n\n// A sync request's answer once its run (or resumed leg) ended or waits.\nfunction runResultReply(\n result: PersistedRunResult,\n succeededStatus: number,\n): WebhookReply {\n return {\n status:\n result.status === \"SUCCEEDED\"\n ? succeededStatus\n : result.status === WAITING_RUN_STATUS\n ? 202\n : refusalStatus(result.refusal),\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({\n runId: result.runId,\n status: result.status,\n error: result.error ?? null,\n }),\n };\n}\n\nconst RESPONDED = Symbol(\"a step responded\");\n\n// Headers a step's response may not set: the host frames the reply, and the\n// endpoint shares the host's origin.\nconst DROPPED_RESPONSE_HEADERS = new Set([\n \"connection\",\n \"content-length\",\n \"keep-alive\",\n \"set-cookie\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n// Always sent, over a step's own: its body is served on the host's origin.\nconst ORIGIN_SAFE_HEADERS: Readonly<Record<string, string>> = {\n \"x-content-type-options\": \"nosniff\",\n \"content-security-policy\": \"sandbox\",\n};\n\n// False for what node:http refuses to send, such as a non-Latin-1 value.\nfunction sendableHeader(name: string, value: string): boolean {\n try {\n validateHeaderName(name);\n validateHeaderValue(name, value);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A step's `run.respond` / `run.stop` answer as an HTTP reply. As upstream,\n * none answers 200 with `{}`, and a string body goes as text. */\nexport function runResponseReply(response: RunResponse): WebhookReply {\n const status =\n typeof response.status === \"number\" &&\n Number.isInteger(response.status) &&\n response.status >= 200 &&\n response.status <= 599\n ? response.status\n : 200;\n const body = response.body ?? {};\n let contentType =\n typeof body === \"string\" ? \"text/plain; charset=utf-8\" : JSON_CONTENT_TYPE;\n const headers: Record<string, string> = {};\n const given =\n response.headers && typeof response.headers === \"object\"\n ? response.headers\n : {};\n for (const [rawName, rawValue] of Object.entries(given)) {\n const name = rawName.toLowerCase();\n if (typeof rawValue !== \"string\" && typeof rawValue !== \"number\") continue;\n const value = String(rawValue);\n if (!sendableHeader(name, value)) continue;\n if (name === \"content-type\") contentType = value;\n else if (!DROPPED_RESPONSE_HEADERS.has(name)) headers[name] = value;\n }\n return {\n status,\n contentType,\n body: typeof body === \"string\" ? body : JSON.stringify(body),\n headers: { ...headers, ...ORIGIN_SAFE_HEADERS },\n };\n}\n\n// A `/sync` resume request, held for the leg its waitpoint resumes.\ninterface SyncResume {\n respond: (response: RunResponse) => void;\n ended: (result: PersistedRunResult | undefined) => void;\n // The run ended, or the waitpoint closed, before a leg resumed on it: 409,\n // or 503 when this runtime shut down first.\n closed: (runId: string, status: string, error: string, code?: number) => void;\n}\n\ninterface SyncResumeCandidate {\n entry: SyncResume;\n runId: string;\n // Whether this request's completeWaitpoint won the waitpoint.\n won: Promise<boolean>;\n}\n\n// Runs an operator started rather than a trigger fired.\nconst OPERATOR_RUN_KINDS: ReadonlySet<string> = new Set([\"manual\", \"rerun\"]);\n\nfunction registrationKey(state: WorkflowState): string {\n const trigger = runnableDefinition(state).trigger;\n // The trigger's last test never changes what arms.\n const { lastTest: _lastTest, ...armed } = trigger ?? {};\n return JSON.stringify({ status: state.status, trigger: trigger && armed });\n}\n\n// The reducer refuses a config that is not an object, so none reaches here.\nfunction configRecord(config: unknown): Record<string, unknown> {\n if (config && typeof config === \"object\" && !Array.isArray(config)) {\n return config as Record<string, unknown>;\n }\n return {};\n}\n\n// Workflows whose latest state trigger runs read without a reactor load.\nconst WORKFLOW_CACHE_MAX = 1_000;\n\ninterface CachedWorkflow {\n state: WorkflowState;\n name: string | undefined;\n // The global scope's operation count the state reflects.\n revision: number;\n}\n\n// A partial header (test doubles, old snapshots) reads as revision 0.\nfunction globalRevision(document: WorkflowDocument): number {\n const revision = document.header.revision as\n | Partial<Record<string, number>>\n | undefined;\n return revision?.global ?? 0;\n}\n\n// The name a run is stamped with. A run record is a journal: it snapshots the\n// name alongside the version so a workflow that is later renamed or deleted\n// still reads correctly in its own history. That is why this resolves at run\n// time rather than being looked up when a row is displayed \\u2014 and why the\n// document's name is a fallback for an unset state.name, not a replacement for\n// it.\nfunction runJournalName(\n stateName: string | undefined,\n documentName: string | undefined,\n): string {\n return stateName?.trim() ? stateName : (documentName ?? \"\");\n}\n\n/**\n * One workflow's trigger as the runtime holds it. `trigger` is null when the\n * runtime holds no trigger row (never armed, or a webhook/schedule kind);\n * `park` is set while a failed run keeps the trigger unarmed, until the\n * workflow is re-enabled or re-published.\n */\nexport type WorkflowHealth = {\n trigger: {\n /** ENABLED | DISABLED | ERROR | PARKED */\n status: string;\n lastError: string | null;\n lastPollAt: string | null;\n nextPollAt: string | null;\n consecutiveFailures: number;\n } | null;\n park: { reason: string; parkedAt: string; publishedVersion: number } | null;\n};\n\nexport class WorkflowRuntimeService {\n private readonly host: WorkflowRuntimeHostDeps;\n private readonly logger: ILogger;\n private readonly telemetry: WorkflowTelemetry;\n // The only host surface that carries an attachment client; without one\n // ctx.files stays an inline data URI instead of an attachment reference.\n private readonly attachments?: AttachmentPort;\n private executor?: BlockExecutor;\n private pieceWorkers?: PieceWorkerPool;\n private unobservePool?: () => void;\n private runDispatcher?: RunDispatcher;\n private unobserveDispatcher?: () => void;\n private readonly eventLoop = new EventLoopMonitor();\n private storePromise: Promise<WorkflowRunStore>;\n private storeError?: unknown;\n private storeOpening = false;\n private storeReopenAt = 0;\n private storeReopenMs = STORE_REOPEN_MS;\n private retentionSweep?: () => void;\n private secretsPromise?: Promise<SecretStore>;\n private oauthAttemptsPromise?: Promise<OAuthAttemptStore>;\n private tokenRefresher?: OAuthTokenRefresher;\n private oauthAppsPromise?: Promise<OAuthAppRegistry>;\n private readonly registry = new Map<string, TriggerRegistration>();\n // Awaited before an endpoint answers: a delivery reaching an unseeded\n // registry is refused exactly as an unknown token is, so it looks like one.\n private readonly seedPromise: Promise<void>;\n // What the last seeding attempt failed with, once the retries are spent.\n private seedError?: unknown;\n\n // Seeds the trigger registry and opens the run journal. The host owns this\n // instance's lifetime, so a replaced host means a replaced runtime.\n constructor(host: WorkflowRuntimeHostDeps) {\n this.host = host;\n this.telemetry = new WorkflowTelemetry(host.telemetry);\n this.blockResolver = new BlockResolver({\n local: installedPiece,\n timeoutMs: host.pieceVersionLookupMs ?? PIECE_VERSION_LOOKUP_TIMEOUT_MS,\n hasBlock: (ref, version, source) =>\n this.versionHasBlock(ref, version, source),\n });\n this.logger = host.logger ?? logger;\n this.attachments = host.attachments\n ? createAttachmentPort(host.attachments, {\n documentIdFor: () => currentWorkflowId(),\n canReadRef: async (ref) => {\n const workflowId = currentWorkflowId();\n const origins = currentAttachmentOrigins();\n if (!workflowId) return false;\n // What this run wrote, it may read back.\n if (origins?.written.has(ref)) return true;\n // A host that serves attachments without answering for them reads\n // nothing: an unanswered read is not a permitted one.\n if (!host.canReadAttachmentRef) return false;\n const runUser = currentRunUser();\n return host.canReadAttachmentRef({\n workflowId,\n ref,\n documentIds: [...new Set(origins?.documentIds() ?? [])],\n ...(runUser !== undefined ? { runUser } : {}),\n });\n },\n onWritten: (ref) => currentAttachmentOrigins()?.written.add(ref),\n })\n : undefined;\n this.storePromise = this.openStore();\n this.seedPromise = this.seedWithRetries();\n this.startRetention();\n }\n\n private retentionTimer?: ReturnType<typeof setInterval>;\n\n private startRetention(): void {\n const retentionMs = runRetentionMs();\n if (retentionMs === undefined) return;\n const sweep = () => {\n void this.sweepRetention(retentionMs);\n };\n this.retentionTimer = setInterval(sweep, RETENTION_SWEEP_INTERVAL_MS);\n this.retentionTimer.unref();\n // After the store opens, not on the next hour.\n this.retentionSweep = sweep;\n }\n\n private async sweepRetention(retentionMs: number): Promise<void> {\n const store = await this.store();\n if (!store) return;\n try {\n const swept = await sweepRetention(store, {\n retentionMs,\n dedupeTtlMs: OPERATION_DEDUPE_TTL_MS,\n });\n if (swept.runs > 0) {\n this.logger.info(\n `Pruned ${swept.runs} workflow run(s) past the retention window`,\n );\n }\n } catch (error) {\n this.logger.warn(\"Workflow run retention sweep failed: @error\", error);\n }\n }\n\n // The journal is best-effort: a broken store never blocks runs. One that\n // failed to open is opened again once its backoff has passed.\n async store(): Promise<WorkflowRunStore | undefined> {\n // Never (re)opened after shutdown: opening runs the sweeps, which would\n // fail the next owner's live runs. One already open stays readable, so\n // what this process adopted can still be closed out.\n if (\n !this.closed &&\n this.storeError !== undefined &&\n !this.storeOpening &&\n Date.now() >= this.storeReopenAt\n ) {\n this.storePromise = this.openStore();\n }\n try {\n return await this.storePromise;\n } catch {\n return undefined;\n }\n }\n\n private openStore(): Promise<WorkflowRunStore> {\n this.storeOpening = true;\n const opening = WorkflowRunStore.create(this.host.relationalDb);\n opening.then(\n (store) => {\n this.storeOpening = false;\n if (this.storeError !== undefined) {\n this.logger.info(\"Workflow run store opened after failing to\");\n }\n this.storeError = undefined;\n this.storeReopenMs = STORE_REOPEN_MS;\n this.retentionSweep?.();\n for (const runId of store.orphanedRunIds) void this.endSubflow(runId);\n },\n (error: unknown) => {\n this.storeOpening = false;\n this.storeError = error;\n this.storeReopenAt = Date.now() + this.storeReopenMs;\n this.logger.error(\n \"Failed to open the workflow run store, retrying in @ms ms: @error\",\n this.storeReopenMs,\n error,\n );\n this.storeReopenMs = Math.min(\n this.storeReopenMs * 2,\n MAX_STORE_REOPEN_MS,\n );\n },\n );\n return opening;\n }\n\n // Unlike the journal, a broken secret store must fail resolution loudly.\n secrets(): Promise<SecretStore> {\n this.secretsPromise ??=\n this.host.secrets !== undefined\n ? Promise.resolve(this.host.secrets)\n : LocalEncryptedSecretStore.create(this.host.relationalDb, {\n keyFile: this.host.secretsKeyFile,\n });\n return this.secretsPromise;\n }\n\n private secretProvider(): SecretProvider {\n return {\n get: (ref, owner) => this.secrets().then((s) => s.get(ref, owner)),\n };\n }\n\n // Lower-cased; null for an anonymous caller or a host that names none.\n private callerAddress(ctx: WorkflowCaller | undefined): string | null {\n const subject = ctx ? this.host.subjectOf?.(ctx) : undefined;\n return subject?.address?.toLowerCase() ?? null;\n }\n\n // Mints a secret owned by a connection or workflow, as the caller; the\n // caller must be able to write that document.\n async createSecret(\n input: { value: string; label?: string; ownerId: string },\n ctx?: WorkflowCaller,\n ): Promise<SecretStat> {\n const client = this.host.reactorClient;\n // An editor mints right after creating the document, maybe before sync.\n if (await isNotHereYet(client, input.ownerId)) {\n await waitForSync(\n client,\n input.ownerId,\n () => Promise.resolve(),\n this.host.syncWaitMs ?? SYNC_WAIT_MS,\n );\n }\n await this.assertCanReadDocument(input.ownerId, ctx);\n await this.assertCanWriteDocument(input.ownerId, ctx);\n const document = await client.get(input.ownerId);\n const type = document.header.documentType;\n if (type !== CONNECTION_DOCUMENT_TYPE && type !== WORKFLOW_DOCUMENT_TYPE) {\n throw new Error(\"A secret belongs to a connection or a workflow\");\n }\n return (await this.secrets()).create({\n ...input,\n createdBy: this.callerAddress(ctx),\n });\n }\n\n // Only its creator, while able to write its owner, changes a secret; one\n // saved anonymously is open to any such writer. Being an admin adds nothing.\n private async assertCanManageSecret(\n stat: SecretStat,\n ctx: WorkflowCaller | undefined,\n ): Promise<void> {\n if (stat.ownerId === null) throw new Error(\"This secret has no owner\");\n await this.assertCanReadDocument(stat.ownerId, ctx);\n await this.assertCanWriteDocument(stat.ownerId, ctx);\n if (stat.createdBy !== null && stat.createdBy !== this.callerAddress(ctx)) {\n throw new SecretCreatorMismatchError();\n }\n }\n\n async canManageSecret(\n stat: SecretStat,\n ctx: WorkflowCaller | undefined,\n ): Promise<boolean> {\n return this.assertCanManageSecret(stat, ctx).then(\n () => true,\n () => false,\n );\n }\n\n async rotateSecret(\n ref: string,\n value: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<SecretStat> {\n const store = await this.secrets();\n await this.assertCanManageSecret(await store.stat(ref), ctx);\n return store.rotate(ref, value);\n }\n\n async deleteSecret(\n ref: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<void> {\n const store = await this.secrets();\n await this.assertCanManageSecret(await store.stat(ref), ctx);\n await store.delete(ref);\n }\n\n // Metadata of a secret whose owner the caller can read; null otherwise.\n async secretStat(\n ref: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<SecretStat | null> {\n let stat: SecretStat;\n try {\n stat = await (await this.secrets()).stat(ref);\n } catch {\n // Unknown or malformed ref reads as \"no such secret\".\n return null;\n }\n return (await this.readableSecrets([stat], ctx)).at(0) ?? null;\n }\n\n async listSecrets(ctx: WorkflowCaller | undefined): Promise<SecretStat[]> {\n return this.readableSecrets(await (await this.secrets()).list(), ctx);\n }\n\n private readableSecrets(\n stats: SecretStat[],\n ctx: WorkflowCaller | undefined,\n ): Promise<SecretStat[]> {\n return this.readableRows(\n stats.filter((stat) => stat.ownerId !== null),\n (stat) => stat.ownerId!,\n ctx,\n );\n }\n\n private oauthAttempts(): Promise<OAuthAttemptStore> {\n this.oauthAttemptsPromise ??= OAuthAttemptStore.create(\n this.host.relationalDb,\n );\n return this.oauthAttemptsPromise;\n }\n\n /** The host's OAuth2 apps, their client secrets loaded into the store once. */\n private oauthApps(): Promise<OAuthAppRegistry> {\n this.oauthAppsPromise ??= this.secrets().then((store) =>\n loadOAuthApps(this.host.oauthApps ?? [], store, {\n onSkip: (appId, kind, reason) =>\n logger.warn(\n `OAuth2 app \"${appId}\" has no usable ${kind} client: ${reason}`,\n ),\n onRelayDropped: (appId, reason) =>\n logger.warn(`OAuth2 app \"${appId}\" relay ignored: ${reason}`),\n }),\n );\n return this.oauthAppsPromise;\n }\n\n private oauthRefresher(): OAuthTokenRefresher {\n return (this.tokenRefresher ??= new StoreTokenRefresher(\n () => this.secrets(),\n this.designEgress,\n (connectionId, error) => this.recordSignInRefused(connectionId, error),\n ));\n }\n\n // A provider that refuses a connection's refresh token has ended its\n // sign-in. Recorded as a check would record it, so whatever shows the\n // connection asks for a new sign-in; the next sign-in's check clears it.\n // Once per refusal, not once per poll.\n private async recordSignInRefused(\n connectionId: string,\n error: OAuthSignInRefusedError,\n ): Promise<void> {\n const state = (await this.connectionDocument(connectionId)).state.global;\n // Revocation is a decision: a check never writes over it either.\n if (state.status === \"REVOKED\") return;\n if (state.status === \"ERROR\" && state.lastError === error.message) return;\n await this.host.reactorClient.execute(connectionId, \"main\", [\n connectionActions.recordCheckResult({\n status: \"ERROR\",\n checkedAt: new Date().toISOString(),\n error: error.message,\n }),\n ]);\n }\n\n /** The seeding failure a restart is needed to clear, or undefined while the\n * registry is seeded. Resolves once seeding has finished either way. */\n async seedFailure(): Promise<unknown> {\n await this.seedPromise;\n return this.seedError;\n }\n\n // A seed that never lands leaves every poll and webhook trigger inert until\n // the process restarts, so a transient failure is retried before it stands.\n private async seedWithRetries(): Promise<void> {\n for (let attempt = 1; attempt <= SEED_ATTEMPTS; attempt += 1) {\n try {\n await this.seedRegistry();\n this.seedError = undefined;\n return;\n } catch (error) {\n this.seedError = error;\n if (attempt === SEED_ATTEMPTS) break;\n this.logger.warn(\n `Seeding the trigger registry failed (attempt ${attempt}/${SEED_ATTEMPTS}), retrying: @error`,\n error,\n );\n await sleep(SEED_RETRY_BASE_MS * 2 ** (attempt - 1));\n }\n }\n // Resolved rather than rejected: a delivery racing a dead registry is\n // still answered as an unknown token, not as a broken endpoint.\n this.logger.error(\n `Failed to seed the trigger registry after ${SEED_ATTEMPTS} attempts; its workflows stay inactive until the reactor restarts: @error`,\n this.seedError,\n );\n }\n\n private async seedRegistry(): Promise<void> {\n const page = await this.host.reactorClient.find({\n type: \"powerhouse/workflow\",\n });\n for (const document of page.results as WorkflowDocument[]) {\n const state = document.state.global;\n // Denials live in memory, so a restart re-checks before arming.\n if (state.status === \"ENABLED\") {\n await this.seedReactorAccess(document.header.id, state);\n }\n await this.updateRegistration(document.header.id, state);\n }\n\n // Seeding nothing while endpoints exist is always a fault, and every\n // webhook for this package is dead until the next seed succeeds.\n if (this.registry.size === 0 && (await this.hasWebhookEndpoints())) {\n this.logger.warn(\n \"Trigger registry seeded no workflows, but @count webhook endpoint(s) exist: their deliveries will be refused as unknown tokens\",\n await this.endpointCount(),\n );\n return;\n }\n this.logger.info(\n `Trigger registry seeded: ${this.registry.size} workflow(s)`,\n );\n }\n\n private async endpointCount(): Promise<number> {\n const endpoints = await this.endpoints();\n return endpoints ? (await endpoints.list()).length : 0;\n }\n\n private async hasWebhookEndpoints(): Promise<boolean> {\n return (await this.endpointCount()) > 0;\n }\n\n // The registration key each workflow was last registered from.\n private readonly registeredAs = new Map<string, string>();\n\n // Awaited by callers: the registry must be current before the next request\n // can arrive. Only arming, which does I/O, is left to run on its own.\n\n // One chain per workflow, so its registrations apply in arrival order: a\n // slow one for an older snapshot cannot finish after a newer one.\n private readonly registrationChains = new Map<string, Promise<void>>();\n\n private inRegistrationOrder<T>(\n workflowId: string,\n task: () => Promise<T>,\n ): Promise<T> {\n const prior = this.registrationChains.get(workflowId) ?? Promise.resolve();\n const run = prior.then(task);\n const tail: Promise<void> = run.then(\n () => undefined,\n () => undefined,\n );\n this.registrationChains.set(workflowId, tail);\n void tail.then(() => {\n if (this.registrationChains.get(workflowId) === tail) {\n this.registrationChains.delete(workflowId);\n }\n });\n return run;\n }\n\n // Registers the runnable trigger; `onlyIfChanged` passes over draft edits.\n private updateRegistration(\n workflowId: string,\n state: WorkflowState,\n onlyIfChanged = false,\n ): Promise<void> {\n return this.inRegistrationOrder(workflowId, () =>\n this.registerNow(workflowId, state, onlyIfChanged),\n );\n }\n\n private async registerNow(\n workflowId: string,\n state: WorkflowState,\n onlyIfChanged: boolean,\n ): Promise<void> {\n const key = registrationKey(state);\n if (\n onlyIfChanged &&\n !this.unarmed.has(workflowId) &&\n this.registeredAs.get(workflowId) === key &&\n // The key leaves the version out, but a re-publish lifts a park.\n !(await this.outdatedPark(workflowId, state))\n ) {\n return;\n }\n this.registeredAs.set(workflowId, key);\n try {\n await this.applyRegistration(workflowId, state);\n } catch (error) {\n this.registeredAs.delete(workflowId);\n throw error;\n }\n }\n\n private async applyRegistration(\n workflowId: string,\n state: WorkflowState,\n ): Promise<void> {\n // The ERROR row an unresolvable trigger leaves outlives the trigger, so a\n // workflow registering anything now drops it first, ahead of what follows.\n if (this.unarmed.delete(workflowId)) this.dropSupervised(workflowId);\n // Whatever this registration decides supersedes the pending retry, which\n // re-arms itself below if the catalog is still away.\n this.cancelResolutionRetry(workflowId);\n const denial =\n state.status === \"ENABLED\"\n ? this.reactorDenials.get(workflowId)\n : undefined;\n if (denial) {\n this.refuseArming(workflowId, state, denial);\n return;\n }\n const trigger =\n state.status === \"ENABLED\"\n ? runnableDefinition(state).trigger\n : undefined;\n const block = trigger ? triggerBlock(trigger) : undefined;\n const version = runnableDefinition(state).version;\n // Disabling clears a park, so re-enabling arms the trigger again; so does\n // a re-publish, which the version that failed no longer matches.\n if (state.status !== \"ENABLED\") {\n const held = this.registry.get(workflowId);\n // With the binding held, the supervisor's disable below releases a\n // PARKED row through onDisable; flipping it DISABLED first would skip\n // that release. With none (a boot), nothing here can run onDisable.\n // Not awaited: the lane runs it before the remove() enqueued below.\n this.supervisor()\n .releasePark(workflowId, !(held && SUPERVISED_KINDS.has(held.kind)))\n .catch((error: unknown) => {\n this.laneFailed(\n `Could not clear the park of disabled workflow ${workflowId}`,\n error,\n );\n });\n } else if (await this.outdatedPark(workflowId, state)) {\n // Not awaited either: queued ahead of the upsert below.\n this.supervisor()\n .unpark(workflowId, version)\n .catch((error: unknown) => {\n this.laneFailed(\n `Could not lift the outdated park of workflow ${workflowId}`,\n error,\n );\n });\n }\n // A park the supervisor does not see: matching nothing is what stops it.\n const park = block ? await this.parks.get(workflowId) : undefined;\n if (\n block &&\n (blockKey(block) === WEBHOOK_BLOCK || triggerKindOf(block)) &&\n park &&\n park.published_version >= version\n ) {\n const had = this.registry.get(workflowId);\n this.registry.delete(workflowId);\n if (had && SUPERVISED_KINDS.has(had.kind))\n this.dropSupervised(workflowId);\n this.logger.warn(\n `Workflow ${workflowId} is PARKED; its trigger stays unarmed until the workflow is re-published or re-enabled`,\n );\n return;\n }\n if (block && blockKey(block) === WEBHOOK_BLOCK) {\n await this.registerWebhook(workflowId, block, trigger!.config);\n return;\n }\n const kind: TriggerKind | undefined = block\n ? triggerKindOf(block)\n : undefined;\n const { binding: supervised, resolution } =\n trigger && !kind\n ? await this.supervisedBinding(workflowId, trigger)\n : { binding: undefined, resolution: undefined };\n\n if (!kind && !supervised) {\n const had = this.registry.get(workflowId);\n this.registry.delete(workflowId);\n if (had && SUPERVISED_KINDS.has(had.kind))\n this.dropSupervised(workflowId);\n // After the drop above, so the row this leaves is the last one written.\n if (trigger) this.reportUnarmedTrigger(workflowId, trigger, resolution);\n return;\n }\n if (supervised) {\n if (supervised.kind === \"schedule\") {\n this.registry.set(workflowId, { workflowId, kind: \"schedule\" });\n this.enableSupervised(workflowId, supervised, version);\n return;\n }\n // Registered as a poll binding first, then corrected once the piece's\n // strategy is known: a WEBHOOK trigger must never be handed to the tick.\n this.registry.set(workflowId, { workflowId, kind: \"piece\" });\n await this.registerPieceTrigger(workflowId, supervised, version);\n return;\n }\n const had = this.registry.get(workflowId);\n if (had && SUPERVISED_KINDS.has(had.kind)) this.dropSupervised(workflowId);\n const config = trigger?.config;\n this.registry.set(\n workflowId,\n kind === \"document-event\"\n ? { workflowId, kind, filter: parseEventFilter(config) }\n : { workflowId, kind: kind!, filter: parseLifecycleFilter(config) },\n );\n }\n\n private enableSupervised(\n workflowId: string,\n binding: TriggerBinding,\n publishedVersion: number,\n ): void {\n this.supervisor()\n .upsert(binding, publishedVersion)\n .catch((error: unknown) => {\n this.laneFailed(`Trigger enable failed for ${workflowId}`, error);\n });\n }\n\n // A WEBHOOK-strategy piece needs its endpoint minted before onEnable runs:\n // the piece registers that URL with the provider from inside the hook.\n private async registerPieceTrigger(\n workflowId: string,\n binding: PieceTriggerBinding,\n publishedVersion: number,\n ): Promise<void> {\n const delivery = await this.pieceDelivery(binding);\n if (typeof delivery !== \"string\") {\n this.refusePieceTrigger(workflowId, binding, delivery);\n return;\n }\n const resolved = { ...binding, delivery };\n if (delivery === \"webhook\") {\n this.registry.set(workflowId, {\n workflowId,\n kind: PIECE_WEBHOOK_KIND,\n binding: resolved,\n });\n // Awaited: a delivery landing before the token exists would be refused,\n // and the piece registers this URL with the provider from onEnable.\n await (await this.endpoints())?.endpointFor(workflowId);\n }\n // Arming downloads a bundle and calls the provider; that stays off the\n // operation-ingestion path.\n this.enableSupervised(workflowId, resolved, publishedVersion);\n }\n\n // From the descriptor of the version that will run; never a guess.\n private async pieceDelivery(\n binding: PieceTriggerBinding,\n ): Promise<\"poll\" | \"webhook\" | { reason: string; retry: boolean }> {\n let strategy: unknown;\n try {\n const descriptor = await this.pieceDescriptor(bindingTarget(binding));\n const trigger = descriptor.triggers.find(\n (entry) => entry.name === binding.triggerName,\n );\n if (!trigger) {\n return {\n reason: `${binding.packageName}@${binding.version} has no trigger \"${binding.triggerName}\"`,\n retry: false,\n };\n }\n strategy = trigger.strategy;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n reason: `Could not describe ${blockLabel(binding.block)}: ${message}`,\n retry: true,\n };\n }\n const check = checkTriggerStrategy(strategy);\n if (\"issue\" in check) return { reason: check.issue, retry: false };\n if (check.delivery === \"manual\") {\n return {\n reason: \"A piece's MANUAL trigger cannot be armed here\",\n retry: false,\n };\n }\n return check.delivery;\n }\n\n // An ERROR row, not a fallback: a trigger armed the wrong way never fires.\n private refusePieceTrigger(\n workflowId: string,\n binding: PieceTriggerBinding,\n refusal: { reason: string; retry: boolean },\n ): void {\n this.registry.delete(workflowId);\n this.unarmed.add(workflowId);\n const retryAt = refusal.retry\n ? new Date(Date.now() + this.scheduleResolutionRetry(workflowId))\n : undefined;\n const reason = `The trigger ${blockLabel(binding.block)} is not armed: ${refusal.reason}`;\n this.logger.warn(\"Workflow @workflow: @reason\", workflowId, reason);\n this.supervisor()\n .reject(workflowId, binding.block, binding.config, reason, retryAt)\n .catch((error: unknown) => {\n this.laneFailed(\n `Could not record the refused trigger for workflow ${workflowId}`,\n error,\n );\n });\n }\n\n // A disabled or retyped webhook trigger loses its registry entry, so\n // deliveries stop; the endpoint row stays so re-enabling keeps the URL.\n private async registerWebhook(\n workflowId: string,\n block: BlockRef,\n rawConfig: unknown,\n ): Promise<void> {\n const had = this.registry.get(workflowId);\n if (had && SUPERVISED_KINDS.has(had.kind)) this.dropSupervised(workflowId);\n let config: WebhookConfig;\n try {\n config = parseWebhookConfig(configRecord(rawConfig));\n } catch (error) {\n this.registry.delete(workflowId);\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(\n `Webhook trigger rejected for ${workflowId}: @error`,\n message,\n );\n // An ERROR row, as for any trigger that cannot arm; cleared on re-registration.\n this.unarmed.add(workflowId);\n this.supervisor()\n .reject(workflowId, block, configRecord(rawConfig), message)\n .catch((recordError: unknown) => {\n this.laneFailed(\n `Could not record the rejected webhook trigger for workflow ${workflowId}`,\n recordError,\n );\n });\n return;\n }\n this.registry.set(workflowId, {\n workflowId,\n kind: WEBHOOK_TRIGGER_KIND,\n config,\n });\n // Awaited: a delivery landing before the token exists would be refused.\n await (await this.endpoints())?.endpointFor(workflowId);\n }\n\n // Triggers the supervisor drives on its tick: piece polls and schedules.\n\n // The resolution travels with the binding: whether a trigger failed because\n // no piece answers or because nothing could be asked decides what the caller\n // is told, and only the resolution knows which it was.\n private async supervisedBinding(\n workflowId: string,\n trigger: NonNullable<WorkflowState[\"trigger\"]>,\n ): Promise<{ binding?: TriggerBinding; resolution?: BlockResolution }> {\n const block = triggerBlock(trigger);\n if (blockKey(block) === SCHEDULE_BLOCK) {\n return {\n binding: {\n kind: \"schedule\",\n workflowId,\n block,\n config: configRecord(trigger.config),\n },\n };\n }\n // The other core triggers are fed by the host: nothing for the tick to drive.\n if (isCoreBlock(block)) return {};\n return this.pieceBinding(workflowId, trigger);\n }\n\n private async pieceBinding(\n workflowId: string,\n trigger: NonNullable<WorkflowState[\"trigger\"]>,\n ): Promise<{ binding?: PieceTriggerBinding; resolution: BlockResolution }> {\n const block = triggerBlock(trigger);\n const resolution = await this.resolveBlock(block);\n const parsed = resolvedBlock(resolution);\n // An action is no more a trigger than an unresolved block is.\n if (parsed?.kind !== \"trigger\") return { resolution };\n const { config, pollIntervalMs } = splitPollInterval(\n configRecord(trigger.config),\n );\n const settings = trigger.propertySettings?.filter(\n (setting) => setting.schema !== null && setting.schema !== undefined,\n );\n return {\n resolution,\n binding: {\n workflowId,\n block,\n packageName: parsed.packageName,\n version: parsed.version,\n ...(parsed.source ? { source: parsed.source } : {}),\n match: resolution.match,\n ...(resolution.note ? { note: resolution.note } : {}),\n triggerName: parsed.name,\n config,\n connectionId: trigger.connectionId,\n reactorConnectionId: trigger.reactorConnectionId,\n pollIntervalMs,\n ...(settings && settings.length > 0\n ? { propertySettings: settings }\n : {}),\n },\n };\n }\n\n // The one resolution policy (block-resolver.ts), for steps, triggers, design\n // time and step tests alike. Bounded per source: an unreachable one adds nothing.\n private readonly blockResolver: BlockResolver;\n\n // Descriptors are cached per version, so a candidate is described once.\n private async versionHasBlock(\n ref: BlockRef,\n version: string,\n source: PieceOrigin,\n ): Promise<boolean | undefined> {\n let descriptor: PieceDescriptor;\n try {\n descriptor = await this.pieceDescriptor({\n name: ref.pieceName,\n version,\n source,\n });\n } catch (error) {\n // Loading fails the step itself, with the piece's own error.\n this.logger.debug(\n \"Could not describe @piece: @error\",\n ref.pieceName,\n error,\n );\n return undefined;\n }\n const entries =\n ref.kind === \"trigger\" ? descriptor.triggers : descriptor.actions;\n return entries.some((entry) => entry.name === ref.name);\n }\n\n // (block, version, source) triples already logged as off-pin.\n private readonly loggedResolutions = new Set<string>();\n\n // The closest version that has the named block (versionHasBlock).\n async resolveBlock(\n block: BlockRef,\n options: { fresh?: boolean; latest?: boolean } = {},\n ): Promise<BlockResolution> {\n const resolution = await this.blockResolver.resolve(block, options);\n if (resolvedBlock(resolution)) this.logResolution(resolution);\n return resolution;\n }\n\n private logResolution(resolution: BlockResolution): void {\n if (!resolution.note || !resolution.resolved) return;\n const key = `${blockLabel(resolution.requested)}\\u0000${resolution.resolved.version}\\u0000${resolution.resolved.source ?? \"\"}`;\n if (this.loggedResolutions.has(key)) return;\n this.loggedResolutions.add(key);\n // Scoped names travel as logger values; inline they print as null/pack.\n this.logger.info(\n \"Block @block: @note\",\n blockLabel(resolution.requested),\n resolution.note,\n );\n }\n\n // For the callers that only need the piece.\n private async resolvedPiece(\n block: BlockRef,\n ): Promise<ParsedBlockType | undefined> {\n return resolvedBlock(await this.resolveBlock(block));\n }\n\n // Why the last publish or enable failed the reactor read check (ADR 0005\n // §6). Such a workflow stays unarmed until a later publish or enable passes.\n private readonly reactorDenials = new Map<string, string>();\n\n // True when the denial changed, so registration must be redone.\n private async recheckReactorAccess(\n workflowId: string,\n operation: OperationWithContext[\"operation\"],\n ): Promise<boolean> {\n if (operation.error !== undefined) return false;\n const type = operation.action.type;\n const enabling =\n type === \"SET_WORKFLOW_STATUS\" &&\n (operation.action.input as { status?: string } | undefined)?.status ===\n \"ENABLED\";\n if (type !== PUBLISH_WORKFLOW && !enabling) return false;\n const state =\n parseWorkflowState(operation.resultingState) ??\n (await this.host.reactorClient.get<WorkflowDocument>(workflowId)).state\n .global;\n const before = this.reactorDenials.get(workflowId);\n await this.checkReactorAccess(\n workflowId,\n state,\n type === PUBLISH_WORKFLOW\n ? runUserOfOperation(operation, this.host.hostIdentity)\n : undefined,\n );\n return this.reactorDenials.get(workflowId) !== before;\n }\n\n // Records a denial when the run user may not read the snapshot's reactor\n // connections; any other error is thrown.\n private async checkReactorAccess(\n workflowId: string,\n state: WorkflowState,\n runUser?: RunUser | null,\n ): Promise<void> {\n const { trigger, steps } = runnableDefinition(state);\n const connectionIds = declaredReactorConnectionIds({\n trigger,\n steps,\n edges: [],\n });\n try {\n await assertReactorConnectionsReadable(\n this.host,\n workflowId,\n connectionIds,\n runUser,\n );\n this.reactorDenials.delete(workflowId);\n } catch (error) {\n if (!isReactorError(error, ReactorAccessDeniedError)) throw error;\n this.reactorDenials.set(workflowId, error.message);\n }\n }\n\n // At seeding, a check that fails for any reason leaves the workflow unarmed.\n private async seedReactorAccess(\n workflowId: string,\n state: WorkflowState,\n ): Promise<void> {\n try {\n await this.checkReactorAccess(workflowId, state);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.warn(\n \"Could not check reactor access for workflow @workflow: @error\",\n workflowId,\n error,\n );\n this.reactorDenials.set(workflowId, message);\n }\n }\n\n // Why a workflow is not armed, or undefined when the reactor check passed.\n reactorAccessDenial(workflowId: string): string | undefined {\n return this.reactorDenials.get(workflowId);\n }\n\n private refuseArming(\n workflowId: string,\n state: WorkflowState,\n reason: string,\n ): void {\n const had = this.registry.get(workflowId);\n this.registry.delete(workflowId);\n if (had && SUPERVISED_KINDS.has(had.kind)) this.dropSupervised(workflowId);\n this.logger.warn(\n \"Workflow @workflow is not armed: @reason\",\n workflowId,\n reason,\n );\n this.unarmed.add(workflowId);\n const trigger = runnableDefinition(state).trigger;\n if (!trigger) return;\n this.supervisor()\n .reject(\n workflowId,\n triggerBlock(trigger),\n configRecord(trigger.config),\n reason,\n )\n .catch((error: unknown) => {\n this.laneFailed(\n `Could not record the reactor access denial for workflow ${workflowId}`,\n error,\n );\n });\n }\n\n // Workflows whose trigger resolved to nothing. Remembered only so the row\n // below can be cleared once the workflow registers something again.\n private readonly unarmed = new Set<string>();\n\n // A trigger naming a piece nothing can resolve registers nothing, and used\n // to say nothing either: no entry, no trigger state, no log.\n\n // Both halves of the report matter: the log for whoever is watching the\n // reactor come up, the row for whoever asks later why a workflow is quiet.\n\n // What it says depends on which failure it was. \"No piece answers\" is a\n // fact only when something answered; when the catalog could not be reached\n // it is a guess, and one that sends an operator to install what they have.\n private reportUnarmedTrigger(\n workflowId: string,\n trigger: NonNullable<WorkflowState[\"trigger\"]>,\n resolution: BlockResolution | undefined,\n ): void {\n const block = triggerBlock(trigger);\n // Only a piece trigger is a failure here: the core manual trigger reaches\n // this path in the ordinary course of things.\n if (isCoreBlock(block)) return;\n const unreachable = resolution?.unreachable;\n const retryAt = unreachable\n ? new Date(Date.now() + this.scheduleResolutionRetry(workflowId))\n : undefined;\n const detail = resolution?.note ?? \"it does not resolve\";\n const reason = unreachable\n ? `The piece behind the trigger ${blockLabel(block)} could not be resolved, so this workflow is not armed: ${detail}. ` +\n `Retrying at ${retryAt?.toISOString() ?? \"the next registration\"}; this is a connectivity failure, not a missing piece.`\n : `The trigger ${blockLabel(block)} does not resolve, so this workflow will not arm: ${detail}.`;\n this.logger.warn(\"Workflow @workflow: @reason\", workflowId, reason);\n this.unarmed.add(workflowId);\n this.supervisor()\n .reject(workflowId, block, configRecord(trigger.config), reason, retryAt)\n .catch((error: unknown) => {\n this.laneFailed(\n `Could not record the unresolved trigger for workflow ${workflowId}`,\n error,\n );\n });\n }\n\n // Re-registration attempts for triggers left unresolved by an unreachable\n // catalog, and how long the next one waits.\n private readonly resolutionRetries = new Map<\n string,\n { timer: NodeJS.Timeout; delayMs: number }\n >();\n\n // Nothing else would ever come back to these: an ERROR row is not due for a\n // poll and carries no binding to retry, so without this a reactor that\n // booted during an outage stays unarmed until someone restarts or edits it.\n private scheduleResolutionRetry(workflowId: string): number {\n const previous = this.resolutionRetries.get(workflowId);\n if (previous) clearTimeout(previous.timer);\n const delayMs = Math.min(\n previous ? previous.delayMs * 2 : UNREACHABLE_RETRY_MS,\n UNREACHABLE_RETRY_CAP_MS,\n );\n const timer = setTimeout(() => {\n this.resolutionRetries.delete(workflowId);\n // Re-read rather than replay: the workflow may have been edited or\n // disabled while the catalog was away, and that answer wins.\n this.refreshRegistration(workflowId).catch((error: unknown) => {\n this.logger.warn(\n `Could not retry the unresolved trigger for workflow ${workflowId}`,\n error,\n );\n });\n }, delayMs);\n // Never a reason to hold the process open.\n timer.unref();\n this.resolutionRetries.set(workflowId, { timer, delayMs });\n return delayMs;\n }\n\n private cancelResolutionRetry(workflowId: string): void {\n const pending = this.resolutionRetries.get(workflowId);\n if (!pending) return;\n clearTimeout(pending.timer);\n this.resolutionRetries.delete(workflowId);\n }\n\n private dropSupervised(workflowId: string): void {\n this.supervisor()\n .remove(workflowId)\n .catch((error: unknown) => {\n this.laneFailed(`Trigger disable failed for ${workflowId}`, error);\n });\n }\n\n private async refreshRegistration(\n workflowId: string,\n resultingState?: string,\n onlyIfChanged = false,\n ): Promise<void> {\n // Parsed before awaiting, so only a malformed state falls through to a\n // fresh read; a registration failure must not trigger one.\n const carried = parseWorkflowState(resultingState);\n if (carried) {\n await this.updateRegistration(workflowId, carried, onlyIfChanged);\n return;\n }\n const generation = this.workflowGeneration(workflowId);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n if (document.header.documentType === WORKFLOW_DOCUMENT_TYPE) {\n this.cacheLoaded(workflowId, generation, document);\n }\n await this.updateRegistration(\n workflowId,\n document.state.global,\n onlyIfChanged,\n );\n }\n\n // The manager routes by filter only, so every per-drive processor instance\n // delivers every matching operation; dedup keeps fires once-per-operation.\n private readonly seenOps = new Set<string>();\n // Filled by loads and kept current by onOperations, the feed the trigger\n // registry is built from; manual fires always load.\n private readonly workflowCache = new Map<string, CachedWorkflow>();\n // Bumped by every operation on a workflow: a load that saw a bump while in\n // flight may have read the state before it, so it does not cache.\n private readonly workflowGenerations = new Map<string, number>();\n\n private workflowGeneration(workflowId: string): number {\n return this.workflowGenerations.get(workflowId) ?? 0;\n }\n\n // Caches what a load returned, unless an operation landed during the load.\n private cacheLoaded(\n workflowId: string,\n generation: number,\n document: WorkflowDocument,\n ): void {\n if (this.workflowGeneration(workflowId) !== generation) return;\n this.cacheWorkflow(workflowId, {\n state: document.state.global,\n name: document.header.name,\n revision: globalRevision(document),\n });\n }\n\n private cacheWorkflow(workflowId: string, entry: CachedWorkflow): void {\n const held = this.workflowCache.get(workflowId);\n if (held && held.revision > entry.revision) return;\n this.workflowCache.delete(workflowId);\n this.workflowCache.set(workflowId, entry);\n if (this.workflowCache.size > WORKFLOW_CACHE_MAX) {\n const oldest = this.workflowCache.keys().next().value;\n if (oldest !== undefined) this.workflowCache.delete(oldest);\n }\n }\n private readonly seenOpsQueue: string[] = [];\n\n private alreadySeen(key: string): boolean {\n if (this.seenOps.has(key)) return true;\n this.seenOps.add(key);\n this.seenOpsQueue.push(key);\n if (this.seenOpsQueue.length > 8192) {\n const evicted = this.seenOpsQueue.shift();\n if (evicted) this.seenOps.delete(evicted);\n }\n return false;\n }\n\n // Throws on any failure, so the read model's cursor holds and retries.\n async onDocumentsPurged(\n markers: OperationWithContext[],\n ): Promise<ErasedRuns> {\n this.throwIfClosed();\n const documentIds = [\n ...new Set(markers.map((marker) => marker.context.documentId)),\n ];\n const store = await this.store();\n if (!store) {\n this.logger.error(\n \"Run journal unavailable; purged documents @ids are not erased and the triggers cursor holds until it reopens: @error\",\n documentIds,\n this.storeError,\n );\n throw new Error(\"Erasing purged documents needs the run journal\", {\n cause: this.storeError,\n });\n }\n for (const workflowId of purgedWorkflowIds(markers)) {\n await this.erasePurgedWorkflow(store, workflowId);\n }\n const erased = await this.telemetry.phase(\n \"journal.purge\",\n { \"documents.count\": documentIds.length },\n () => store.eraseRunsForDocuments(documentIds),\n );\n if (erased.runs > 0) {\n this.logger.info(\n \"Erased @runs workflow run(s) of purged documents @ids\",\n erased.runs,\n documentIds,\n );\n }\n return erased;\n }\n\n // Called by the workflow-triggers read model. Registry updates and the\n // journal write for every matched fire are awaited; execution is not, so\n // runs never block operation ingestion.\n async onOperations(operations: OperationWithContext[]): Promise<void> {\n this.throwIfClosed();\n const hints = collectLifecycleParentHints(operations);\n for (const { operation, context } of operations) {\n this.throwIfClosed();\n if (context.scope !== DOCUMENT_SCOPE && context.scope !== \"global\") {\n continue;\n }\n const opKey = operationKey({ operation, context });\n if (this.alreadySeen(opKey)) continue;\n if (context.documentType === WORKFLOW_DOCUMENT_TYPE) {\n this.workflowGenerations.set(\n context.documentId,\n this.workflowGeneration(context.documentId) + 1,\n );\n }\n if (context.scope === DOCUMENT_SCOPE) {\n // Renames, deletes and upgrades: the next run reloads.\n this.workflowCache.delete(context.documentId);\n await this.matchDocumentLifecycle(operation, context, hints);\n await this.forgetDeletedWorkflow(operation, context);\n continue;\n }\n // A workflow edit updates the registry, then falls through: workflow docs are\n // also a document-event source, so a workflow can watch its own type.\n if (context.documentType === \"powerhouse/workflow\") {\n const cached = this.workflowCache.get(context.documentId);\n const carried =\n cached && operation.error === undefined\n ? parseWorkflowState(operation.resultingState)\n : undefined;\n if (cached && carried) {\n this.cacheWorkflow(context.documentId, {\n state: carried,\n name: cached.name,\n revision: operation.index + 1,\n });\n } else if (cached) {\n // No state to apply: refreshRegistration's load refills the entry.\n this.workflowCache.delete(context.documentId);\n }\n // Publish and enable re-check reactor access first.\n const rechecked = await this.recheckReactorAccess(\n context.documentId,\n operation,\n );\n // Only a status or published-trigger change re-arms.\n await this.refreshRegistration(\n context.documentId,\n operation.resultingState,\n !rechecked,\n );\n }\n if (operation.error !== undefined) continue;\n for (const registration of this.registry.values()) {\n if (registration.kind !== \"document-event\") continue;\n const matched = matchesEventFilter(\n registration.filter,\n context.documentType,\n context.documentId,\n operation.action.type,\n );\n if (!matched) continue;\n const payload = {\n documentId: context.documentId,\n documentType: context.documentType,\n branch: context.branch,\n scope: context.scope,\n action: {\n type: operation.action.type,\n input: operation.action.input,\n },\n operation: {\n index: operation.index,\n timestampUtcMs: operation.timestampUtcMs,\n },\n };\n await this.enqueueFire(\n registration.workflowId,\n payload,\n registration.kind,\n `op:${opKey}`,\n );\n }\n if (context.documentType === DRIVE_DOCUMENT_TYPE) {\n await this.matchDriveLifecycle(\n context.documentId,\n operation.action.type,\n operation.action.input,\n { index: operation.index, timestampUtcMs: operation.timestampUtcMs },\n );\n }\n }\n }\n\n // Fires this process ran with no journal row, until the journal takes one.\n // A held triggers cursor re-sweeps them past alreadySeen's window.\n private readonly unjournaledFires = new Set<string>();\n\n private fireUnjournaled(\n fireKey: string,\n workflowId: string,\n payload: unknown,\n kind: string,\n ): void {\n this.unjournaledFires.add(fireKey);\n if (this.unjournaledFires.size > UNJOURNALED_FIRES_LIMIT) {\n const oldest = this.unjournaledFires.values().next().value!;\n this.unjournaledFires.delete(oldest);\n this.logger.warn(\n \"Too many unjournaled workflow fires held; a redelivery of the oldest fires again\",\n );\n }\n this.startFiring(workflowId, payload, kind);\n }\n\n // Journals the fire, then lets it run on its own. Awaiting only the write is\n // the whole point: once this resolves the run is durable, so the read model's\n // cursor may pass the operation that matched it, but nothing here waits on a\n // piece. A journal that cannot take the row still fires, best-effort, and\n // once only in this process: a redelivery claims its dedupe key instead.\n private async enqueueFire(\n workflowId: string,\n payload: unknown,\n kind: string,\n dedupeKey: string,\n ): Promise<void> {\n const fireKey = JSON.stringify([workflowId, dedupeKey]);\n const store = await this.store();\n // Shut down meanwhile: unwritten, so the next owner replays the operation.\n this.throwIfClosed();\n if (this.unjournaledFires.has(fireKey)) {\n if (!store) return;\n try {\n const claimed = await store.claimDedupe(\n workflowId,\n dedupeKey,\n OPERATION_DEDUPE_TTL_MS,\n new Date().toISOString(),\n );\n if (!claimed) {\n // The key already stood for a fire, so this one may have doubled it.\n this.logger.warn(\n `Workflow ${workflowId}: a ${kind} fire this process ran unjournaled had its key already marked fired; it may have run twice`,\n );\n }\n this.unjournaledFires.delete(fireKey);\n } catch (error) {\n this.logger.warn(\n `Could not record the unjournaled ${kind} fire for workflow ${workflowId}: @error`,\n error,\n );\n }\n return;\n }\n if (!store) {\n this.fireUnjournaled(fireKey, workflowId, payload, kind);\n return;\n }\n // The durable half of the dedupe: a crash can leave the cursor behind the\n // run it already wrote, so the replay delivers this operation a second\n // time. The claim counts deliveries, so a fire that takes the process down\n // BEFORE it journals anything is bounded instead of replayed every boot.\n const enqueue = { workflowId, triggerKind: kind, triggerPayload: payload };\n let claim: FireClaim;\n try {\n claim = await store.claimAndEnqueueRun(\n dedupeKey,\n OPERATION_DEDUPE_TTL_MS,\n new Date().toISOString(),\n enqueue,\n );\n } catch (error) {\n this.logger.error(\n `Could not journal the ${kind} fire for workflow ${workflowId}; running it without a durable record`,\n error,\n );\n this.fireUnjournaled(fireKey, workflowId, payload, kind);\n return;\n }\n if (claim.outcome === \"duplicate\") return;\n if (claim.outcome === \"abandoned\") {\n // Loudly, and with a run to point at: the alternative is a reactor that\n // crashes on every boot and says nothing about why.\n this.logger.error(\n `Workflow ${workflowId}: a ${kind} fire has been delivered ` +\n `${claim.attempts} times without ever journaling a run; abandoning ` +\n \"it rather than replaying it on every boot\",\n );\n try {\n await store.journalAbandonedFire(dedupeKey, {\n ...enqueue,\n attempts: claim.attempts,\n });\n } catch (error) {\n this.logger.warn(\n `Could not journal the abandoned ${kind} fire for workflow ${workflowId}: @error`,\n error,\n );\n }\n return;\n }\n this.startFiring(workflowId, payload, kind, claim.runId);\n }\n\n // Journal before fire: a trigger firing is a PENDING run with its payload\n // before fire() reaches an await the shutdown can land in. Resolves once the\n // row is durable; the run itself is not awaited.\n private async fireFromTrigger(\n workflowId: string,\n payload: unknown,\n kind: string,\n ): Promise<void> {\n const runId = await this.journalFiring(workflowId, payload, kind);\n this.startFiring(workflowId, payload, kind, runId);\n }\n\n // Refused with nothing written once closed: the firing's source still holds\n // it. Without a journal the firing runs unrecorded, as every run does then.\n private async journalFiring(\n workflowId: string,\n payload: unknown,\n kind: string,\n ): Promise<string | undefined> {\n const store = await this.store();\n // No await between this check and the write, so none starts after shutdown.\n if (this.closed) throw new WorkflowRuntimeClosedError(workflowId);\n if (!store) return undefined;\n try {\n return await store.enqueueRun({\n workflowId,\n triggerKind: kind,\n triggerPayload: payload,\n });\n } catch (error) {\n this.logger.error(\n `Could not journal the ${kind} fire for workflow ${workflowId}; running it without a durable record`,\n error,\n );\n return undefined;\n }\n }\n\n private startFiring(\n workflowId: string,\n payload: unknown,\n kind: string,\n enqueuedRunId?: string,\n ): void {\n this.fire(\n workflowId,\n payload,\n kind,\n undefined,\n undefined,\n enqueuedRunId,\n ).then(\n (run) => {\n this.logger.info(`${kind} fired workflow ${workflowId}: ${run.status}`);\n },\n (error: unknown) => {\n // Not lost: the journaled row stays PENDING for the next owner.\n if (enqueuedRunId && isShutdownRefusal(error)) {\n this.logger.warn(\n `${kind} fire of workflow ${workflowId} was refused by the shutdown; run ${enqueuedRunId} is left for the next owner to start`,\n );\n return;\n }\n // The message, truncated, rather than the error object: a piece error\n // carries the HTTP response the framework's formatter lifted out of\n // it, which can be a whole HTML error page. An unbounded write on the\n // failure path is how the EPIPE boot loop started (backlog item 5).\n this.logger.error(\n `${kind} run failed for workflow ${workflowId}: @error`,\n truncateForLog(\n error instanceof Error ? error.message : String(error),\n ),\n );\n },\n );\n }\n\n // Skips the second source of a lifecycle fire; the journal's per-document claim\n // decides. Only a match is recorded, so an unknown drive leaves ADD_FILE its turn.\n private readonly firedLifecycle = new Set<string>();\n private readonly firedLifecycleQueue: string[] = [];\n\n private lifecycleAlreadyFired(\n kind: TriggerKind,\n documentId: string,\n ): boolean {\n return this.firedLifecycle.has(`${kind}:${documentId}`);\n }\n\n private recordLifecycleFired(kind: TriggerKind, documentId: string): void {\n const key = `${kind}:${documentId}`;\n if (this.firedLifecycle.has(key)) return;\n this.firedLifecycle.add(key);\n this.firedLifecycleQueue.push(key);\n if (this.firedLifecycleQueue.length > 4096) {\n const evicted = this.firedLifecycleQueue.shift();\n if (evicted) this.firedLifecycle.delete(evicted);\n }\n }\n\n private lifecycleTargets(\n kind: TriggerKind,\n ): { workflowId: string; filter: LifecycleFilter }[] {\n const targets: { workflowId: string; filter: LifecycleFilter }[] = [];\n for (const registration of this.registry.values()) {\n if (registration.kind !== kind) continue;\n // Redundant at runtime, but it is what tells the compiler the surviving\n // registrations carry a LifecycleFilter rather than an event filter.\n if (registration.kind === \"document-event\") continue;\n targets.push({\n workflowId: registration.workflowId,\n filter: registration.filter,\n });\n }\n return targets;\n }\n\n private async fireLifecycle(\n kind: TriggerKind,\n payload: {\n documentId: string;\n documentType: string | null;\n name: string | null;\n driveId: string | null;\n parentId: string | null;\n operation: { index: number; timestampUtcMs: string };\n },\n ): Promise<void> {\n let matched = false;\n for (const target of this.lifecycleTargets(kind)) {\n if (\n !matchesLifecycleFilter(\n target.filter,\n payload.documentType,\n payload.driveId,\n )\n ) {\n continue;\n }\n matched = true;\n // Keyed on the document, not the operation: its CREATE_DOCUMENT and the\n // drive's ADD_FILE project concurrently, and one claim must win.\n await this.enqueueFire(\n target.workflowId,\n payload,\n kind,\n `lifecycle:${kind}:${payload.documentId}`,\n );\n }\n if (matched) this.recordLifecycleFired(kind, payload.documentId);\n }\n\n // A \"child\" edge names the parent document but not its type, and only a drive\n // parent matters to a driveId filter. Cached: a drive gathers many documents.\n private readonly driveParentCache = new Map<string, boolean>();\n\n private async driveIdFromParent(\n parentId: string | undefined,\n ): Promise<string | undefined> {\n if (!parentId) return undefined;\n const cached = this.driveParentCache.get(parentId);\n if (cached !== undefined) return cached ? parentId : undefined;\n try {\n const parent = await this.host.reactorClient.get(parentId);\n const isDrive = parent.header.documentType === DRIVE_DOCUMENT_TYPE;\n if (this.driveParentCache.size > 1024) this.driveParentCache.clear();\n this.driveParentCache.set(parentId, isDrive);\n return isDrive ? parentId : undefined;\n } catch {\n return undefined;\n }\n }\n\n // A deleted workflow is disarmed as a disabled one is, and its trigger row,\n // webhook token and dedupe keys go with it.\n private async forgetDeletedWorkflow(\n operation: OperationWithContext[\"operation\"],\n context: OperationWithContext[\"context\"],\n ): Promise<void> {\n if (operation.action.type !== \"DELETE_DOCUMENT\") return;\n if (operation.error !== undefined) return;\n if (context.documentType !== WORKFLOW_DOCUMENT_TYPE) return;\n const workflowId =\n stringField(inputRecord(operation.action.input), \"documentId\") ??\n context.documentId;\n this.disarmDeleted(workflowId);\n this.workflowCache.delete(workflowId);\n try {\n const store = await this.store();\n await store?.deleteDedupe(workflowId);\n } catch (error) {\n this.logger.warn(\n `Could not drop the dedupe keys of deleted workflow ${workflowId}`,\n error,\n );\n }\n }\n\n // Off the ingestion path: the release queues behind any enable in flight.\n private disarmDeleted(workflowId: string): void {\n this.dropDeleted(workflowId);\n this.releaseDeleted(workflowId).catch((error: unknown) => {\n this.logger.error(\n `Could not disarm deleted workflow ${workflowId}`,\n error,\n );\n });\n }\n\n // The registry goes now, so deliveries stop at once.\n private dropDeleted(workflowId: string): void {\n this.registry.delete(workflowId);\n this.registeredAs.delete(workflowId);\n this.unarmed.delete(workflowId);\n this.cancelResolutionRetry(workflowId);\n this.cancelTriggerTest(workflowId, \"stopped: the workflow was deleted\");\n }\n\n // onDisable, the trigger row, FLOW store and park, then the webhook token,\n // which goes however the rest went.\n private async releaseDeleted(workflowId: string): Promise<void> {\n let failure: { error: unknown } | undefined;\n try {\n await this.supervisor().forget(workflowId);\n } catch (error) {\n failure = { error };\n }\n await (await this.endpoints())?.revoke(workflowId);\n if (failure) throw failure.error;\n }\n\n // As a deletion disarms, but awaited: the cursor must not pass a failure.\n private async erasePurgedWorkflow(\n store: WorkflowRunStore,\n workflowId: string,\n ): Promise<void> {\n this.dropDeleted(workflowId);\n await this.releaseDeleted(workflowId);\n await store.deleteDedupe(workflowId);\n for (const scope of [\"FLOW\", \"PROJECT\"] as const) {\n await store.deletePieceStore(scope, testPartitionKey(scope, workflowId));\n }\n }\n\n // The document's own CREATE_DOCUMENT / DELETE_DOCUMENT, the source of truth: it covers\n // documents outside any drive, carries the real type and name, and alone proves deletion.\n private async matchDocumentLifecycle(\n operation: OperationWithContext[\"operation\"],\n context: OperationWithContext[\"context\"],\n hints: Map<string, LifecycleParentHint>,\n ): Promise<void> {\n const kind = lifecycleKindForDocumentAction(operation.action.type);\n if (!kind) return;\n if (operation.error !== undefined) return;\n const input = inputRecord(operation.action.input);\n // DELETE_DOCUMENT names its target in the input; CREATE_DOCUMENT's input\n // and context agree.\n const documentId = stringField(input, \"documentId\") ?? context.documentId;\n if (this.lifecycleAlreadyFired(kind, documentId)) return;\n if (this.lifecycleTargets(kind).length === 0) return;\n\n const hint = hints.get(documentId);\n const driveId =\n hint?.driveId ?? (await this.driveIdFromParent(hint?.parentCandidate));\n const created = kind === \"document-created\";\n await this.fireLifecycle(kind, {\n documentId,\n // CREATE_DOCUMENT names the model it creates; the stored context type\n // answers for a deletion, where the document can no longer be read.\n documentType:\n (created ? stringField(input, \"model\") : undefined) ??\n (context.documentType || null),\n // Only a creation carries a name; a deleted document's name is gone.\n name: stringField(input, \"name\") ?? null,\n driveId: driveId ?? null,\n parentId: hint?.parentId ?? null,\n operation: {\n index: operation.index,\n timestampUtcMs: operation.timestampUtcMs,\n },\n });\n }\n\n // The drive's fallback view: ADD_FILE always accompanies a CREATE_DOCUMENT, so it fires only\n // when that never reached the processor. DELETE_NODE stands alone — the document stays alive.\n private async matchDriveLifecycle(\n driveId: string,\n actionType: string,\n input: unknown,\n operation: { index: number; timestampUtcMs: string },\n ): Promise<void> {\n const kind = lifecycleKindForDriveAction(actionType);\n if (!kind) return;\n if (this.lifecycleTargets(kind).length === 0) return;\n\n const record = inputRecord(input);\n const documentId = stringField(record, \"id\");\n if (!documentId) return;\n if (this.lifecycleAlreadyFired(kind, documentId)) return;\n let documentType = stringField(record, \"documentType\");\n let name = stringField(record, \"name\") ?? null;\n if (kind === \"document-deleted\") {\n // Best-effort: unlinking a node leaves the document in place. Folder\n // nodes never resolve, so a type filter also skips them.\n try {\n const document = await this.host.reactorClient.get(documentId);\n documentType = document.header.documentType;\n name ??= document.header.name;\n } catch {\n documentType = undefined;\n }\n }\n\n await this.fireLifecycle(kind, {\n documentId,\n documentType: documentType ?? null,\n name,\n driveId,\n parentId: stringField(record, \"parentFolder\") ?? null,\n operation,\n });\n }\n\n private triggerSupervisor?: TriggerSupervisor;\n\n // Parks as queued on the supervisor's lane, read off it.\n private readonly parks = new ParkState(async () =>\n (await this.store())?.listWorkflowParks(),\n );\n\n // Lazily built; started/stopped by the trigger processor's lifecycle.\n supervisor(): TriggerSupervisor {\n this.triggerSupervisor ??= new TriggerSupervisor({\n store: () => this.store(),\n parks: this.parks,\n resolveAuth: async (connectionId, request) => {\n if (!connectionId) return undefined;\n const resolved = await new DocumentConnectionResolver(\n this.host,\n this.secretProvider(),\n this.oauthRefresher(),\n ).resolveWithSecrets(connectionId, request);\n // The supervisor reads these back off the auth value to redact what a\n // trigger hook throws; nothing else travels with it.\n return rememberSecrets(resolved.auth, resolved.secretValues);\n },\n fire: (workflowId, payload, kind, runId) => {\n this.startFiring(workflowId, payload, kind, runId);\n },\n pollHeld: (workflowId) => this.pollHeld(workflowId),\n webhookUrlFor: async (workflowId) =>\n (await this.mintWebhookEndpoint(workflowId))?.url,\n flowsFor: (workflowId, runId) =>\n this.flowsPort(workflowId, runId ?? null),\n reactorAccess: (binding, requireReactor, runUser) =>\n this.triggerReactorAccess(binding, requireReactor, runUser),\n models: this.models,\n // Hooks lease the pool's trigger children; the pool owns their lifetime.\n worker: this.workers().session(\"trigger\"),\n hookConcurrency: this.workers().triggerSlots,\n telemetry: this.telemetry,\n cacheDir: bundleCacheDir(),\n resolver: pieceResolver(),\n // Trigger hooks reach the same services steps do.\n egress: configuredEgress(),\n // Overrides the 60s default; the 1s floor still applies.\n defaultIntervalMs:\n Number(process.env.PH_WORKFLOWS_POLL_INTERVAL_MS) || undefined,\n reconcileIntervalMs:\n Number(process.env.PH_WORKFLOWS_WEBHOOK_RECONCILE_MS) || undefined,\n });\n // Built after shutdown: stopped before anything can queue on it.\n if (this.closed) this.triggerSupervisor.stop();\n return this.triggerSupervisor;\n }\n\n // Lane work refused because this runtime shut down is the designed outcome.\n private laneFailed(message: string, error: unknown): void {\n if (isShutdownRefusal(error)) {\n this.logger.debug(message, error);\n return;\n }\n this.logger.error(message, error);\n }\n\n startTriggerSupervisor(): void {\n this.supervisor().start();\n void this.admitAbandonedRuns();\n void this.deliverAllHeld();\n this.startWaitpointPoller();\n // Then rows left after that pass, by a draining owner or a failed pass;\n // only settled ones, so an owner still draining keeps its own.\n this.pendingSweepTimer ??= setInterval(() => {\n void this.admitAbandonedRuns(PENDING_SWEEP_INTERVAL_MS);\n }, PENDING_SWEEP_INTERVAL_MS);\n this.pendingSweepTimer.unref();\n }\n\n private pendingSweepTimer?: ReturnType<typeof setInterval>;\n private admittingAbandoned = false;\n\n // PENDING runs another owner journaled start here, oldest first and through\n // the same gates as any fire. RUNNING ones were failed at open.\n private async admitAbandonedRuns(minAgeMs?: number): Promise<void> {\n if (this.admittingAbandoned || this.closed) return;\n this.admittingAbandoned = true;\n try {\n const store = await this.store();\n const admitted = await store?.admitAbandonedRuns(\n minAgeMs === undefined\n ? {}\n : { enqueuedBefore: new Date(Date.now() - minAgeMs) },\n );\n for (const run of admitted ?? []) {\n this.startFiring(\n run.workflowId,\n run.triggerPayload,\n run.triggerKind,\n run.runId,\n );\n }\n } catch (error) {\n this.logger.error(\n \"Could not admit the runs a stopped reactor journaled: @error\",\n error,\n );\n } finally {\n this.admittingAbandoned = false;\n }\n }\n\n stopTriggerSupervisor(): void {\n clearInterval(this.pendingSweepTimer);\n this.pendingSweepTimer = undefined;\n this.stopWaitpointPoller();\n this.triggerSupervisor?.stop();\n }\n\n // Set by shutdown. A runtime that lost the workflow singleton is shut down\n // while its reactor keeps serving, so nothing may start a run after it.\n private closed = false;\n\n // For the read model: a delivery refused here stays below its cursor, so\n // the next owner replays it rather than this runtime acknowledging it.\n private throwIfClosed(): void {\n if (this.closed) {\n throw new Error(\n \"This workflow runtime has shut down; the operations are left for the next owner\",\n );\n }\n }\n\n // Teardown for the whole runtime, driven by the host. The run children\n // outlive the reactor otherwise — they are forked, not\n // spawned by it — and a run holding one is over the moment we stop.\n shutdown(): void {\n this.closed = true;\n this.runGate.close();\n this.runDispatcher?.close();\n this.eventLoop.stop();\n this.unobserveDispatcher?.();\n this.unobserveDispatcher = undefined;\n clearInterval(this.retentionTimer);\n for (const { timer } of this.resolutionRetries.values())\n clearTimeout(timer);\n this.resolutionRetries.clear();\n for (const workflowId of [...this.webhookTests.keys()]) {\n this.cancelTriggerTest(workflowId, \"stopped: the runtime shut down\");\n }\n this.stopTriggerSupervisor();\n // Left in place, disposed: clearing it here would let a run that is still\n // between awaits build a replacement and fork into it after teardown.\n this.pieceWorkers?.dispose();\n this.unobservePool?.();\n this.unobservePool = undefined;\n this.designWorker = undefined;\n }\n\n /**\n * Runs a workflow's trigger now, as its schedule or poll would (a sync\n * now): a schedule fires the workflow, a polling trigger polls its source.\n * Never a backfill's pace. False when it has no armed trigger.\n */\n async pollNow(workflowId: string, ctx?: WorkflowCaller): Promise<boolean> {\n if (this.closed) return false;\n await this.assertCanReadWorkflow(workflowId, ctx, undefined);\n return this.supervisor().pollNow(workflowId);\n }\n\n /**\n * How one workflow's trigger stands, for host-side code that keeps\n * workflows running (a processor reconciling the workflows it built): the\n * trigger row, and the park that holds it unarmed. Not caller-filtered:\n * GraphQL callers go through triggerStates.\n */\n async workflowHealth(workflowId: string): Promise<WorkflowHealth> {\n const store = await this.store();\n if (!store) return { trigger: null, park: null };\n const [row, park] = await Promise.all([\n store.getTriggerState(workflowId),\n store.getWorkflowPark(workflowId),\n ]);\n return {\n trigger: row\n ? {\n status: row.status,\n lastError: row.last_error,\n lastPollAt: row.last_poll_at,\n nextPollAt: row.next_poll_at,\n consecutiveFailures: row.consecutive_failures,\n }\n : null,\n park: park\n ? {\n reason: park.reason,\n parkedAt: park.parked_at,\n publishedVersion: park.published_version,\n }\n : null,\n };\n }\n\n // A trigger's state names its workflow and its last error, so the rows are\n // filtered to the workflows this caller may read.\n async triggerStates(ctx?: WorkflowCaller): Promise<TriggerStateRow[]> {\n const store = await this.store();\n if (!store) return [];\n const rows = await store.listTriggerStates();\n return this.readableRows(rows, (row) => row.workflow_id, ctx);\n }\n\n private webhookEndpoints?: IWebhookEndpoints;\n private webhookScope?: IWebhookScope;\n // Held as a promise: seeding runs from the constructor, before the host\n // registers, so a seeded webhook workflow would mint no token and fail to arm.\n private webhookRegistration?: Promise<IWebhookEndpoints | undefined>;\n\n /** Registers the workflow endpoint family with the reactor's webhook service\n * (idempotent). Everything transport-shaped is the service's; only workflow identity is ours. */\n async registerWebhookEndpoint(): Promise<void> {\n if (this.webhookRegistration) {\n await this.webhookRegistration;\n return;\n }\n const webhooks = this.host.webhooks;\n if (!webhooks) {\n this.logger.warn(\n \"This host serves no webhooks; workflows with a webhook trigger will not arm\",\n );\n return;\n }\n this.webhookScope = webhooks;\n this.webhookRegistration = webhooks\n .register({\n name: \"trigger\",\n policyFor: (workflowId) => this.webhookPolicy(workflowId),\n onRequest: (request) => this.deliverWebhook(request),\n })\n .then((endpoints) => {\n this.webhookEndpoints = endpoints;\n return endpoints;\n })\n .catch((error: unknown) => {\n // No webhook store means no webhook triggers, not no workflows:\n // rethrowing would take every other trigger down with it.\n this.logger.warn(\n \"Webhook triggers are unavailable on this host; other triggers are unaffected: @error\",\n error,\n );\n return undefined;\n });\n await this.webhookRegistration;\n }\n\n /** The endpoint family, once registered. Seeding runs before the host starts\n * the runtime, so a caller that needs a token waits rather than finds it missing. */\n private async endpoints(): Promise<IWebhookEndpoints | undefined> {\n if (this.webhookEndpoints) return this.webhookEndpoints;\n // The host normally registers on start, but seeding runs from the\n // constructor and an enable can reach here first. Registering on demand\n // makes the order irrelevant, rather than failing the trigger on a race.\n if (!this.webhookRegistration && this.host.webhooks) {\n await this.registerWebhookEndpoint();\n }\n return await this.webhookRegistration;\n }\n\n /** The per-document policy the service enforces before a delivery reaches this code;\n * undefined means the workflow is not armed, answered exactly as an unknown token is. */\n async webhookPolicy(workflowId: string): Promise<WebhookPolicy | undefined> {\n // Seeding starts from the constructor and a delivery can beat it, and an\n // unseeded registry is indistinguishable from a bad token.\n await this.seedPromise;\n\n // An armed workflow verifies as it runs, whatever a test of its draft says.\n const registration = this.liveWebhook(workflowId);\n if (registration) {\n // A piece owns its own verification and parsing: its run hook decides\n // what the request means, or rejects it.\n if (registration.kind === PIECE_WEBHOOK_KIND) return {};\n return this.policyOf(registration.config, workflowId);\n }\n\n // Unarmed, a waiting test verifies as the draft's trigger would once armed.\n const test = this.webhookTests.get(workflowId);\n return test ? this.policyOf(test.config, workflowId) : undefined;\n }\n\n private liveWebhook(workflowId: string) {\n const registration = this.registry.get(workflowId);\n return registration?.kind === PIECE_WEBHOOK_KIND ||\n registration?.kind === WEBHOOK_TRIGGER_KIND\n ? registration\n : undefined;\n }\n\n private async policyOf(\n config: WebhookConfig,\n workflowId: string,\n ): Promise<WebhookPolicy> {\n return {\n methods: config.methods,\n challengeField: config.challengeField,\n dedupe: config.dedupeField\n ? {\n field: config.dedupeField,\n ttlSeconds: config.dedupeTtlSeconds,\n }\n : undefined,\n verify:\n config.scheme === \"none\"\n ? undefined\n : {\n scheme: config.scheme,\n header: config.header,\n secret: await this.webhookSecret(config, workflowId),\n toleranceSeconds: config.toleranceSeconds,\n algorithm: config.algorithm,\n encoding: config.encoding,\n prefix: config.prefix,\n },\n };\n }\n\n // Design-time: the URL to hand the provider. Minted on demand so an author\n // can copy it before the first delivery.\n async webhookEndpoint(\n workflowId: string,\n ctx?: WorkflowCaller,\n access: WorkflowAccessOptions = {},\n ): Promise<WebhookEndpointRecord | null> {\n // The URL carries the token that is the entire credential for a public\n // route, so handing it out is a read of the workflow itself.\n await this.assertCanReadWorkflow(workflowId, ctx, access.driveId);\n return this.mintWebhookEndpoint(workflowId);\n }\n\n // The supervisor's own lookup: server-side, with no caller to authorize.\n private async mintWebhookEndpoint(\n workflowId: string,\n ): Promise<WebhookEndpointRecord | null> {\n const endpoints = await this.endpoints();\n if (!endpoints) return null;\n const registration = this.registry.get(workflowId);\n const armed =\n registration?.kind === WEBHOOK_TRIGGER_KIND ||\n registration?.kind === PIECE_WEBHOOK_KIND;\n\n // Minted whether or not the workflow is armed: an author has to give the\n // URL to the sender before enabling, and enabling is what accepts.\n\n // `armed` carries the difference instead, so nothing is hidden — and this\n // never scans, which listing every endpoint to find one would.\n\n // A host that does not know its own public origin advertises a bare path; copying that into\n // a provider's console fails with nothing to read, so the author is told here instead.\n const absoluteUrl = this.webhookScope?.hasPublicOrigin ?? false;\n\n const minted = await endpoints.endpointFor(workflowId);\n return {\n workflowId,\n url: minted.url,\n absoluteUrl,\n armed,\n createdAt: minted.createdAt,\n };\n }\n\n /** A delivery the service has already rate-limited, verified, de-duplicated and\n * answered any challenge for; all that is left is deciding what it means. */\n async deliverWebhook(request: WebhookRequest): Promise<WebhookReply> {\n // Retryable: the sender tries again, and reaches the owner that runs it.\n if (this.closed) return { status: 503, unprocessed: true };\n const workflowId = request.key;\n const registration = this.liveWebhook(workflowId);\n // A waiting test samples the delivery; an armed workflow still runs it.\n const test = this.webhookTests.get(workflowId);\n if (test) {\n this.webhookTests.delete(workflowId);\n clearTimeout(test.timer);\n test.resolve(webhookPayload(request));\n if (!registration) return { status: test.config.responseStatus };\n }\n if (!registration) return UNAUTHORIZED;\n if (registration.kind === PIECE_WEBHOOK_KIND) {\n return this.deliverToPiece(registration.binding, request);\n }\n\n const { config } = registration;\n const payload = webhookPayload(request);\n\n // Answered only once journaled: after the reply the sender never retries.\n if (config.responseMode === \"async\") {\n try {\n await this.fireFromTrigger(workflowId, payload, WEBHOOK_TRIGGER_KIND);\n } catch (error) {\n if (error instanceof WorkflowRuntimeClosedError) {\n return { status: 503, unprocessed: true };\n }\n throw error;\n }\n return { status: config.responseStatus };\n }\n let runId: string | undefined;\n try {\n runId = await this.journalFiring(\n workflowId,\n payload,\n WEBHOOK_TRIGGER_KIND,\n );\n } catch (error) {\n if (error instanceof WorkflowRuntimeClosedError) {\n return { status: 503, unprocessed: true };\n }\n throw error;\n }\n // Sync mode holds the provider's socket, so the wait is bounded. On expiry the run is left\n // going — cancelling would lose announced work — and the 504 retry is what dedupe absorbs.\n const firing = this.fire(\n workflowId,\n payload,\n WEBHOOK_TRIGGER_KIND,\n undefined,\n undefined,\n runId,\n ).then(\n (result) => ({ ok: true, result }) as const,\n (error: unknown) => ({ ok: false, error }) as const,\n );\n let replied = false;\n const takeReply = () => !replied && (replied = true);\n // A step's respond answers first, and the run goes on.\n let sent: RunResponse | undefined;\n let responded: () => void = () => undefined;\n const respondedFirst = new Promise<typeof RESPONDED>((resolve) => {\n responded = () => resolve(RESPONDED);\n });\n const responder = (response: RunResponse) => {\n if (sent || !takeReply()) return;\n sent = response;\n responded();\n };\n // A queued run an operator cancelled answers at once, not when it dequeues.\n let ended: PersistedRunResult | undefined;\n let endedEarly: () => void = () => undefined;\n const endedFirst = new Promise<{ ok: true; result: PersistedRunResult }>(\n (resolve) => {\n endedEarly = () => resolve({ ok: true, result: ended! });\n },\n );\n const ender = (result: PersistedRunResult) => {\n if (ended || !takeReply()) return;\n ended = result;\n endedEarly();\n };\n if (runId) {\n this.heldReplies.set(runId, takeReply);\n this.runResponders.set(runId, responder);\n this.queuedReplies.set(runId, ender);\n }\n let run: Awaited<typeof firing> | typeof TIMED_OUT;\n try {\n const raced = await Promise.race([\n firing,\n respondedFirst,\n endedFirst,\n timeout(DELIVERY_TIMEOUT_MS),\n ]);\n // respondedFirst resolves only after `sent` is set.\n if (sent) return runResponseReply(sent);\n run = raced as Exclude<typeof raced, typeof RESPONDED>;\n // A shutdown that took the reply first is answered 503, not 504.\n if (run === TIMED_OUT && !takeReply()) {\n run = ended ? { ok: true, result: ended } : await firing;\n }\n } finally {\n if (runId) {\n this.heldReplies.delete(runId);\n if (this.runResponders.get(runId) === responder) {\n this.runResponders.delete(runId);\n }\n if (this.queuedReplies.get(runId) === ender) {\n this.queuedReplies.delete(runId);\n }\n }\n }\n\n if (run === TIMED_OUT) {\n this.logger.warn(\n `Webhook run for ${workflowId} exceeded ${DELIVERY_TIMEOUT_MS}ms; answering 504 while it continues`,\n );\n return {\n status: 504,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({\n status: \"RUNNING\",\n error: \"The run did not finish in time\",\n }),\n };\n }\n\n if (!run.ok) {\n // Not run, and not this runtime's to run: the sender retries and\n // reaches the owner. A 500 would keep the dedupe key and lose it.\n if (run.error instanceof WorkflowRuntimeClosedError) {\n return { status: 503, unprocessed: true };\n }\n const message =\n run.error instanceof Error ? run.error.message : String(run.error);\n this.logger.error(\n `Webhook run failed for ${workflowId}: @error`,\n message,\n );\n return {\n status: 500,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({ error: message }),\n };\n }\n\n return runResultReply(run.result, config.responseStatus);\n }\n\n // The probe a sender sends before it will register the endpoint. Answered by\n // the piece: only its own code knows what the sender wants echoed back.\n private async pieceHandshake(\n binding: PieceTriggerBinding,\n request: WebhookRequest,\n ): Promise<WebhookReply | undefined> {\n const handshake = await this.pieceHandshakeConfig(binding);\n if (!handshake || !handshakeMatches(handshake, request)) return undefined;\n try {\n const result = await this.supervisor().handshake(\n binding,\n webhookPayload(request),\n );\n return handshakeReply(result.output);\n } catch (error) {\n // A failed probe is the sender's answer, so it must not look like a\n // delivery: 500 tells it to retry rather than that the endpoint is gone.\n this.logger[isShutdownRefusal(error) ? \"debug\" : \"error\"](\n \"Handshake failed for @block on workflow @workflow\",\n blockLabel(binding.block),\n binding.workflowId,\n error,\n );\n return { status: 500 };\n }\n }\n\n private async pieceHandshakeConfig(\n binding: PieceTriggerBinding,\n ): Promise<PieceHandshake | undefined> {\n try {\n const descriptor = await this.pieceDescriptor(bindingTarget(binding));\n return descriptor.triggers.find(\n (entry) => entry.name === binding.triggerName,\n )?.handshake;\n } catch (error) {\n // A delivery must not fail because the descriptor could not be read; the\n // cost of guessing wrong is one probe answered as a delivery.\n this.logger.warn(\n \"Could not read the handshake config for @block\",\n blockLabel(binding.block),\n error,\n );\n return undefined;\n }\n }\n\n // The piece owns verification and parsing, so there is no scheme to check\n // here: its run hook decides what the request means, or rejects it.\n private async deliverToPiece(\n binding: PieceTriggerBinding,\n request: WebhookRequest,\n ): Promise<WebhookReply> {\n // A callable workflow is called by a run of this reactor, never over HTTP.\n if (isCallableFlow(binding)) return UNAUTHORIZED;\n const probe = await this.pieceHandshake(binding, request);\n if (probe) return probe;\n\n const payload = webhookPayload(request);\n // Answered before the hook runs, as Activepieces does: a provider must not\n // wait on piece code, and its retry would only duplicate the delivery.\n this.supervisor()\n .deliverWebhook(binding.workflowId, payload)\n .then(\n () => {\n this.logger.info(\n \"Webhook delivered to @block for workflow @workflow\",\n blockLabel(binding.block),\n binding.workflowId,\n );\n },\n (error: unknown) => {\n this.laneFailed(\n `Webhook delivery failed for workflow ${binding.workflowId}`,\n error,\n );\n },\n );\n return { status: 200 };\n }\n\n // A missing or deleted secret is a rejection, not an error: the endpoint is\n // configured as signed and there is nothing to verify against.\n private async webhookSecret(\n config: WebhookConfig,\n workflowId: string,\n ): Promise<string | undefined> {\n if (!config.secretRef) return undefined;\n try {\n return await (\n await this.secrets()\n ).get(config.secretRef, { documentId: workflowId, kind: \"workflow\" });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(\n `Webhook secret unavailable for ${workflowId}: @error`,\n message,\n );\n return undefined;\n }\n }\n\n // Importable models for every piece child this runtime forks.\n private readonly models: ModelManifestSource = {\n entries: () => this.host.modelManifest?.() ?? [],\n lookup: (documentType) => this.modelEntries(documentType),\n };\n\n // Without a type: every type the reactor has registered, plus the boot list.\n private async modelEntries(\n documentType: string | undefined,\n ): Promise<ModelManifestEntry[]> {\n const lookup = this.host.modelEntries?.bind(this.host);\n if (!lookup) return [];\n if (documentType !== undefined) return lookup(documentType);\n const types = new Set(\n (this.host.modelManifest?.() ?? []).map((entry) => entry.documentType),\n );\n const modules = await this.host.reactorClient.getDocumentModelModules();\n for (const module of modules.results) {\n types.add(module.documentModel.global.id);\n }\n return [...types].flatMap((type) => lookup(type));\n }\n\n // The requireReactor a block's descriptor declares.\n private async declaredReactor(\n block: ParsedBlockType,\n ): Promise<\"read\" | \"write\" | undefined> {\n if (builtinPiece(block.packageName)) return undefined;\n const descriptor = await this.pieceDescriptor(targetOf(block));\n const blocks =\n block.kind === \"trigger\" ? descriptor.triggers : descriptor.actions;\n return blocks.find((candidate) => candidate.name === block.name)\n ?.requireReactor;\n }\n\n // The timeout and retry an action declares, at the version the step runs.\n private async blockDefaults(\n block: BlockRef,\n ): Promise<BlockDefaults | undefined> {\n if (block.kind !== \"action\" || builtinPiece(block.pieceName)) {\n return undefined;\n }\n const parsed = resolvedBlock(await this.resolveBlock(block));\n if (!parsed) return undefined;\n const descriptor = await this.pieceDescriptor(targetOf(parsed));\n const action = descriptor.actions.find(\n (candidate) => candidate.name === parsed.name,\n );\n if (!action) return undefined;\n const { defaultTimeoutSeconds, defaultRetry } = action;\n if (defaultTimeoutSeconds === undefined && defaultRetry === undefined) {\n return undefined;\n }\n return {\n ...(defaultTimeoutSeconds !== undefined\n ? { timeoutSeconds: defaultTimeoutSeconds }\n : {}),\n ...(defaultRetry !== undefined ? { retry: defaultRetry } : {}),\n };\n }\n\n // Who a caller acts as at design time and in a single-step test.\n private callerRunUser(ctx: WorkflowCaller | undefined): RunUser | null {\n const subject = ctx ? this.host.subjectOf?.(ctx) : undefined;\n return subject?.address ? { address: subject.address, subject } : null;\n }\n\n // The bound reactor connection's scope, which the run user must be able to read.\n private async reactorScope(\n reactorConnectionId: string | null | undefined,\n requireReactor: \"read\" | \"write\",\n runUser: RunUser | null,\n ) {\n if (reactorConnectionId?.includes(\"{{\")) {\n throw unboundReactorConnection(reactorConnectionId);\n }\n const base = await buildReactorRunScope(this.host, {\n reactorConnectionId,\n requireReactor,\n runUser,\n });\n if (runUser && reactorConnectionId) {\n await assertConnectionReadable(this.host, reactorConnectionId, runUser);\n }\n return base;\n }\n\n // ctx.reactor for a step: the run user, or the caller in a single-step test.\n private async stepReactorAccess(\n request: StepReactorRequest,\n ): Promise<ReactorTap | undefined> {\n const declared = await this.declaredReactor(request.block);\n if (!declared) return undefined;\n const base = await this.telemetry.phase(\"reactor.scope\", {}, () =>\n this.reactorScope(\n request.reactorConnectionId,\n declared,\n currentRunUser() ?? null,\n ),\n );\n return reactorTap(this.host, base, runJournal(), {}, this.telemetry);\n }\n\n // A live hook acts as the publisher; a design-time test passes the caller.\n private async triggerReactorAccess(\n binding: PieceTriggerBinding,\n requireReactor: \"read\" | \"write\",\n runUser: RunUser | null | undefined,\n ): Promise<ReactorTap> {\n const bound = binding.reactorConnectionId;\n const user =\n runUser !== undefined\n ? runUser\n : ((await assertReactorConnectionsReadable(\n this.host,\n binding.workflowId,\n new Set(bound ? [bound] : []),\n )) ?? null);\n const base = await this.reactorScope(bound, requireReactor, user);\n return reactorTap(this.host, base, NO_JOURNAL, {}, this.telemetry);\n }\n\n // Option resolvers read as the GraphQL caller, within a bound connection.\n private async designReactorAccess(\n block: ParsedBlockType,\n ctx: WorkflowCaller | undefined,\n reactorConnectionId: string | undefined,\n ): Promise<ReactorTap | undefined> {\n if (!(await this.declaredReactor(block))) return undefined;\n const runUser = this.callerRunUser(ctx);\n if (!runUser && authEnforced(this.host)) {\n throw accessDenied(\n \"Design-time reactor access requires a signed-in caller while auth enforcement is on\",\n );\n }\n if (reactorConnectionId) {\n await this.reactorScope(reactorConnectionId, \"read\", runUser);\n }\n return reactorTap(this.host, designTimeScope(runUser), NO_JOURNAL);\n }\n\n private readonly descriptors = new Map<string, PieceDescriptor>();\n private designWorker?: IPieceWorker;\n\n // Describe, options and connection checks lease children like a run's steps.\n private createDesignWorker(): IPieceWorker {\n return this.workers().session(\"design\");\n }\n\n // Design-time piece code runs under the policy a run would get, so nothing\n // the editor does reaches somewhere a step could not.\n\n // Held rather than inlined for the reason the supervisor holds one: a\n // deployment whose isolation lives elsewhere has to be able to widen it.\n // Design-time piece code — a dropdown's options(), a connection check — runs\n // under the same policy a step does, widened the same way. Without that, the\n // editor cannot offer the lines of a floor it is about to poll.\n private designEgress: EgressPolicy | undefined =\n configuredEgress() ?? DEFAULT_EGRESS_POLICY;\n\n private readonly describing = new Map<string, Promise<PieceDescriptor>>();\n\n // Keyed on the resolved version and its source, never on what was asked for.\n private pieceDescriptor(target: PieceTarget): Promise<PieceDescriptor> {\n const cacheKey = `${target.source ?? \"\"}:${target.name}@${target.version}`;\n const cached = this.descriptors.get(cacheKey);\n if (cached) return Promise.resolve(cached);\n let pending = this.describing.get(cacheKey);\n if (!pending) {\n pending = this.describe(target, cacheKey).finally(() =>\n this.describing.delete(cacheKey),\n );\n this.describing.set(cacheKey, pending);\n }\n return pending;\n }\n\n private async describe(\n target: PieceTarget,\n cacheKey: string,\n ): Promise<PieceDescriptor> {\n const { name: packageName, version } = target;\n const builtin = builtinPiece(packageName);\n if (builtin) return describeBuiltinPiece(builtin);\n let descriptor = this.descriptors.get(cacheKey);\n if (!descriptor) {\n const piece = await pieceResolver().resolve(target);\n // Loading the bundle runs the piece module's top-level code, so the\n // descriptor is built in the worker, never in the reactor process.\n this.designWorker ??= this.createDesignWorker();\n let output: unknown;\n try {\n const result = await this.designWorker.describePiece(\n // Loading the module runs piece-authored top-level code, which\n // has no business reaching anything at all.\n {\n ...pieceModuleRef(piece),\n packageName,\n version,\n ...(this.designEgress ? { egress: this.designEgress } : {}),\n },\n { timeoutMs: DESCRIBE_TIMEOUT_MS },\n );\n output = result.output;\n } catch (error) {\n throw new Error(\n pieceFailureDetail(\n error,\n `Loading piece \"${packageName}\" timed out after ${Math.round(DESCRIBE_TIMEOUT_MS / 1000)}s`,\n ),\n { cause: error },\n );\n }\n descriptor = output as PieceDescriptor;\n this.descriptors.set(cacheKey, descriptor);\n }\n return descriptor;\n }\n\n // The workflows a drive holds that this caller may read, so a drive app can\n // scope runs to its own.\n async driveWorkflowIds(\n driveId: string,\n ctx?: WorkflowCaller,\n ): Promise<string[]> {\n await this.assertCanReadDocument(driveId, ctx);\n const ids = await this.workflowNodeIds(driveId);\n return this.readableRows(ids, (id) => id, ctx);\n }\n\n private async workflowNodeIds(driveId: string): Promise<string[]> {\n let page = await this.host.reactorClient.drives.listNodes(driveId);\n const nodes = [...page.results];\n // A drive past one page would otherwise scope runs to a prefix of its\n // workflows and read as a history that never happened.\n while (page.next) {\n page = await page.next();\n nodes.push(...page.results);\n }\n // Only file nodes carry a documentType, so `in` also rules out folders.\n return nodes\n .filter(\n (node) =>\n \"documentType\" in node &&\n node.documentType === WORKFLOW_DOCUMENT_TYPE,\n )\n .map((node) => node.id);\n }\n\n // The run journal, scoped to what this caller may read: a run carries its\n // trigger payload and every step's input and output.\n async runs(args: RunsArgs, ctx?: WorkflowCaller): Promise<RunRecord[]> {\n return (await this.runsPage(args, ctx)).records;\n }\n\n // One page, newest first. Access is the host's per-document call, so it\n // can't go into SQL: batches are read and filtered until the page is full.\n runsPage(args: RunsPageArgs, ctx?: WorkflowCaller): Promise<RunPage> {\n return this.telemetry.phase(\n \"runs.page\",\n {\n \"runs.scope\": args.workflowId\n ? \"workflow\"\n : args.driveId\n ? \"drive\"\n : \"all\",\n },\n async (span) => {\n const page = await this.listRunsPage(args, ctx);\n span.setAttribute(\"runs.returned\", page.records.length);\n return page;\n },\n );\n }\n\n private async listRunsPage(\n args: RunsPageArgs,\n ctx?: WorkflowCaller,\n ): Promise<RunPage> {\n const empty: RunPage = { records: [], hasNextPage: false, cursor: null };\n const after = args.cursor ? decodeRunCursor(args.cursor) : undefined;\n const store = await this.store();\n if (!store) return empty;\n // A drive scopes runs to the workflows it holds; an explicit workflowId is\n // narrower still, so it wins.\n let scope: string | string[] | undefined;\n if (args.workflowId) {\n await this.assertCanReadDocument(args.workflowId, ctx);\n scope = args.workflowId;\n } else if (args.driveId) {\n scope = await this.driveWorkflowIds(args.driveId, ctx);\n if (scope.length === 0) return empty;\n }\n // An unscoped listing is every workflow in the reactor, so it needs a\n // caller to filter by; no caller is served no run either way.\n if (!ctx) return empty;\n const pageSize = Math.min(Math.max(args.limit ?? 25, 1), MAX_LIST_RUNS);\n const batchSize = Math.min(pageSize + 1, MAX_LIST_RUNS);\n const served: RunRow[] = [];\n let position = after;\n let scanned = 0;\n let exhausted = false;\n // One past the page tells whether another follows.\n while (served.length <= pageSize && scanned < RUNS_SCAN_LIMIT) {\n const batch = await store.listRuns(scope, batchSize, {\n after: position,\n excludeTriggerKinds: args.excludeTriggerKinds,\n });\n scanned += batch.length;\n const last = batch.at(-1);\n if (last) position = { enqueuedAt: last.enqueued_at, id: last.id };\n served.push(\n ...(await this.servedRuns(\n await this.readableRows(batch, (row) => row.workflow_id, ctx),\n ctx,\n )),\n );\n if (batch.length < batchSize) {\n exhausted = true;\n break;\n }\n }\n const rows = served.slice(0, pageSize);\n const full = served.length > pageSize;\n const lastRow = rows.at(-1);\n // Out of scan budget: resume after the last row read, served or not.\n const resumeAt =\n full || exhausted\n ? lastRow && { enqueuedAt: lastRow.enqueued_at, id: lastRow.id }\n : position;\n // Loop iterations are left to the run's detail.\n const steps = await store.getStepsForRuns(\n rows.map((row) => row.id),\n { withData: args.withStepData ?? true },\n );\n return {\n records: rows.map((row) => ({ row, steps: steps.get(row.id) ?? [] })),\n hasNextPage: full || !exhausted,\n cursor: resumeAt ? encodeRunCursor(resumeAt) : null,\n };\n }\n\n // One run, or null when the caller may not read its workflow: \"not yours\"\n // and \"no such run\" must not be distinguishable.\n async run(runId: string, ctx?: WorkflowCaller): Promise<RunRecord | null> {\n const store = await this.store();\n if (!store || !ctx) return null;\n const row = await store.getRun(runId);\n if (!row) return null;\n if (!(await this.canReadDocument(row.workflow_id, ctx))) return null;\n if ((await this.servedRuns([row], ctx)).length === 0) return null;\n const steps = await store.getSteps(row.id, {\n withIterations: true,\n iterationLimit: RUN_ITERATIONS_LIMIT,\n });\n const shown = steps.filter((step) => step.step_path !== step.step_id);\n const total =\n shown.length < RUN_ITERATIONS_LIMIT\n ? shown.length\n : await store.countIterations(row.id);\n return {\n row,\n steps,\n ...(total > shown.length ? { iterationsTotal: total } : {}),\n };\n }\n\n // Design-time: the powerhouse/connection documents this caller may read,\n // read as the caller and then held to the host's own check.\n async connections(ctx?: WorkflowCaller): Promise<ConnectionSummary[]> {\n const subject = ctx && this.host.subjectOf?.(ctx);\n let page = await this.host.reactorClient.find(\n { type: \"powerhouse/connection\" },\n subject ? { subject } : undefined,\n );\n const found = [...page.results];\n // Every page, then the check: filtering one page would hide the rest.\n while (page.next) {\n page = await page.next();\n found.push(...page.results);\n }\n const readable = await this.readableDocuments(\n found as ConnectionDocument[],\n ctx,\n );\n // A listing serves a document any domain scope of which is readable, so\n // one whose global scope the gate stripped is dropped here.\n const withGlobal = readable.filter(\n (document) =>\n (document.state as Partial<ConnectionDocument[\"state\"]>).global !==\n undefined,\n );\n return withGlobal.map((document) => {\n const state = document.state.global;\n return {\n id: document.header.id,\n name: state.name,\n connectorId: state.connectorId,\n authType: state.authType,\n status: state.status,\n accountLabel: state.accountLabel ?? null,\n };\n });\n }\n\n // Runs the piece's auth.validate, then auth.getConnectionIdentifier for the\n // account label, against the connection's credentials; records the outcome.\n async checkConnection(\n connectionId: string,\n ctx?: WorkflowCaller,\n ): Promise<ConnectionCheckResult> {\n await this.assertCanReadDocument(connectionId, ctx);\n // A check records its outcome on the connection, so this is a write: a\n // read-only caller is refused before anything is fetched or resolved.\n await this.assertCanWriteDocument(connectionId, ctx);\n return this.checkConnectionDocument(\n await this.connectionDocument(connectionId),\n );\n }\n\n private async connectionDocument(\n connectionId: string,\n ): Promise<ConnectionDocument> {\n const document =\n await this.host.reactorClient.get<ConnectionDocument>(connectionId);\n if (document.header.documentType !== \"powerhouse/connection\") {\n throw new Error(\n `Document \"${connectionId}\" is not a powerhouse/connection`,\n );\n }\n return document;\n }\n\n // The check itself; the caller has already been authorized.\n private async checkConnectionDocument(\n document: ConnectionDocument,\n ): Promise<ConnectionCheckResult> {\n const connectionId = document.header.id;\n const state = document.state.global;\n const accountLabel = state.accountLabel ?? null;\n\n // Revocation is a decision, not an observation: recording any result here\n // would write ERROR over it and let the next check resolve the secrets.\n if (state.status === \"REVOKED\") {\n return { ok: false, detail: \"Connection is revoked\", accountLabel };\n }\n // Judged on what the connection holds, not on `status`: SET_CONNECTOR\n // leaves UNCONFIGURED behind and only a recorded check clears it, so\n // trusting the flag here refuses the first check of every connection —\n // the one an author runs the moment they finish filling it in.\n // No credentials: the reactor decides each call, so only the config is checked.\n if (state.authType === \"REACTOR\") {\n const parsed = parseReactorConnectionConfig(state.config);\n return this.recordCheckResult(document, {\n ok: parsed.ok,\n detail: parsed.ok\n ? `Local reactor, ${parsed.config.access ?? \"write\"} access`\n : parsed.error,\n accountLabel,\n });\n }\n if (state.authType !== \"NONE\" && !hasCredentials(state)) {\n return this.recordCheckResult(document, {\n ok: false,\n detail: \"Connection is not configured\",\n accountLabel,\n });\n }\n // No bundle work for auth kinds the runtime cannot execute yet.\n if (state.authType === \"OIDC\") {\n return this.recordCheckResult(document, {\n ok: false,\n detail: `${state.authType} connections are not supported by the runtime yet`,\n accountLabel,\n });\n }\n\n const packageName = packageFromConnectorId(state.connectorId);\n let moduleRef: PieceModuleRef;\n try {\n // A person pressed \"check\", quite possibly because they just fixed the\n // connectivity that made the last answer a miss: ask again rather than\n // serve them a remembered one, and wait for the real answer.\n // A connection names no version: the installed piece, else the newest.\n const found = await this.blockResolver.latest(packageName, {\n fresh: true,\n });\n if (found.version === undefined) {\n throw new Error(\n `Could not resolve a version for piece \"${packageName}\"` +\n (found.unreachable ? `: ${found.unreachable}` : \"\"),\n );\n }\n moduleRef = pieceModuleRef(\n await pieceResolver().resolve({\n name: packageName,\n version: found.version,\n source: found.source,\n }),\n );\n } catch (error) {\n return this.recordCheckResult(document, {\n ok: false,\n detail: error instanceof Error ? error.message : String(error),\n accountLabel,\n });\n }\n\n // Through the shared decision, so a revoked connection is refused here as\n // it is on a run; the document is already in hand, so no second fetch.\n let shapedAuth: unknown;\n try {\n shapedAuth = await resolveConnectionAuth(\n document,\n this.secretProvider(),\n { piecePackage: packageName },\n this.oauthRefresher(),\n );\n } catch (error) {\n // A missing or deleted secret names its ref in the message.\n return this.recordCheckResult(document, {\n ok: false,\n detail: error instanceof Error ? error.message : String(error),\n accountLabel,\n });\n }\n\n // Plaintext auth crosses only into the piece worker: the auth's hooks are\n // untrusted piece code and must not run in the reactor process.\n let outcome: CheckConnectionOutcome;\n try {\n this.designWorker ??= this.createDesignWorker();\n const result = await this.designWorker.checkConnection(\n // A check that reaches somewhere a run could not would call a\n // connection healthy that every step using it will fail on.\n {\n ...moduleRef,\n auth: shapedAuth,\n ...(this.designEgress ? { egress: this.designEgress } : {}),\n },\n { timeoutMs: CHECK_TIMEOUT_MS },\n );\n outcome = result.output as CheckConnectionOutcome;\n } catch (error) {\n return this.recordCheckResult(document, {\n ok: false,\n detail: checkFailureDetail(error),\n accountLabel,\n });\n }\n\n if (!outcome.valid) {\n return this.recordCheckResult(document, {\n ok: false,\n detail: outcome.detail ?? \"Connection check failed\",\n accountLabel,\n });\n }\n // The label is best-effort: a failure keeps the previous one.\n if (outcome.identifierError) {\n this.logger.warn(\n \"Connection @id kept its label: getConnectionIdentifier failed: @detail\",\n connectionId,\n outcome.identifierError,\n );\n }\n return this.recordCheckResult(document, {\n ok: true,\n detail: outcome.declared\n ? null\n : \"piece declares no auth.validate; credentials resolved\",\n // The piece's own label first; else the account the sign-in's ID token\n // names (asked for with `openid email`); else the one it had.\n accountLabel:\n outcome.accountLabel ?? idTokenEmail(shapedAuth) ?? accountLabel,\n });\n }\n\n // How startOAuth would sign in with the publisher's app `appId` for this\n // callback; \"none\" for an app this host does not know.\n async oauthSignInMode(\n appId: string,\n redirectUri: string,\n ): Promise<OAuthSignIn[\"mode\"]> {\n return oauthSignInFor(await this.oauthApps(), appId, redirectUri).mode;\n }\n\n // Opens an OAuth2 sign-in for a connection that brings its own app. The\n // host serves redirectUri and passes what it receives to completeOAuth.\n async startOAuth(\n connectionId: string,\n ctx: WorkflowCaller | undefined,\n options: { redirectUri: string; returnUrl?: string },\n ): Promise<OAuthStart> {\n await this.assertCanReadDocument(connectionId, ctx);\n // Signing in stores a token on the connection.\n await this.assertCanWriteDocument(connectionId, ctx);\n const state = (await this.connectionDocument(connectionId)).state.global;\n if (state.authType !== \"OAUTH2\") {\n throw new OAuthError(\"This connection does not sign in with OAuth2\");\n }\n const {\n [OAUTH_CLIENT_ID]: ownClientId,\n [OAUTH_APP]: appId,\n [OAUTH_SCOPES]: _scopes,\n [OAUTH_GRANTED_SCOPES]: _granted,\n ...props\n } = (state.config ?? {}) as Record<string, unknown>;\n const scopes = scopesOverride(\n (state.config ?? {}) as Record<string, unknown>,\n );\n let clientId: string;\n let clientSecretRef: string | null;\n let pkce = false;\n // What a sign-in through the app's relay changes: the provider's\n // redirect URI, the token URL, and what the state carries after a dot.\n let redirectUri = options.redirectUri;\n let tokenUrl: string | undefined;\n let stateSuffix: string | undefined;\n if (typeof appId === \"string\" && appId !== \"\") {\n // The publisher's app: its desktop client for a callback to this\n // machine, its web client otherwise, else its relay.\n const signIn = oauthSignInFor(\n await this.oauthApps(),\n appId,\n options.redirectUri,\n );\n if (signIn.mode === \"none\") {\n throw new OAuthError(\n `The app \"${appId}\" has no ${signIn.kind} client on this host; configure it in workflows.oauthApps`,\n );\n }\n if (signIn.mode === \"relay\") {\n const { relay } = signIn;\n // The provider knows the relay, not this host: it sends the browser\n // there, and the relay forwards code and state to the callback the\n // state names. The attempt keeps the relay's redirect URI, so the\n // exchange names the one the provider saw, and its token URL, which\n // adds the secret this host never holds; PKCE binds the code to\n // this host, which alone holds the verifier.\n clientId = relay.clientId;\n clientSecretRef = null;\n redirectUri = relay.redirectUri;\n tokenUrl = relay.tokenUrl;\n stateSuffix = Buffer.from(options.redirectUri, \"utf8\").toString(\n \"base64url\",\n );\n pkce = true;\n } else {\n clientId = signIn.client.clientId;\n clientSecretRef = signIn.client.clientSecretRef;\n pkce = signIn.mode === \"desktop\";\n }\n } else {\n if (typeof ownClientId !== \"string\" || ownClientId === \"\") {\n throw new OAuthError(\"Set the client ID before connecting\");\n }\n const ref = state.secretRefs.find(\n (entry) => entry.name === OAUTH_CLIENT_SECRET,\n )?.ref;\n if (!ref) {\n throw new OAuthError(\"Save the client secret before connecting\");\n }\n clientId = ownClientId;\n clientSecretRef = ref;\n }\n\n const packageName = packageFromConnectorId(state.connectorId);\n const found = await this.blockResolver.latest(packageName);\n if (found.version === undefined) {\n throw new OAuthError(\n `Could not resolve a version for piece \"${packageName}\"` +\n (found.unreachable ? `: ${found.unreachable}` : \"\"),\n );\n }\n const descriptor = await this.pieceDescriptor({\n name: packageName,\n version: found.version,\n source: found.source,\n });\n const method = authMethodFor(descriptor.auth, \"OAUTH2\") as\n | PieceAuthDescriptor\n | undefined;\n if (!method?.oauth2) {\n throw new OAuthError(`\"${packageName}\" does not sign in with OAuth2`);\n }\n if (method.unsupported) {\n throw new UnsupportedPieceFeatureError(\n `Piece \"${packageName}\"`,\n method.unsupported,\n );\n }\n return (await this.oauthAttempts()).start({\n connectionId,\n method: method.oauth2,\n props,\n clientId,\n clientSecretRef,\n redirectUri,\n ...(tokenUrl ? { tokenUrl } : {}),\n ...(options.returnUrl ? { returnUrl: options.returnUrl } : {}),\n ...(scopes ? { scopes } : {}),\n ...(pkce ? { pkce } : {}),\n ...(stateSuffix ? { stateSuffix } : {}),\n createdBy: this.callerAddress(ctx),\n });\n }\n\n // How a sign-in stands, for the editor that opened it.\n async oauthAttempt(\n state: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<OAuthAttemptView | null> {\n const view = await (await this.oauthAttempts()).view(state);\n if (!view) return null;\n await this.assertCanReadDocument(view.connectionId, ctx);\n return view;\n }\n\n // The provider's redirect. No caller: the state, minted for an authorized\n // caller and good for one exchange, is what vouches for it.\n async completeOAuth(callback: {\n state: string;\n code?: string;\n error?: string;\n errorDescription?: string;\n }): Promise<{\n ok: boolean;\n detail: string | null;\n returnUrl: string | null;\n }> {\n const attempts = await this.oauthAttempts();\n const attempt = await attempts.claim(callback.state);\n if (!attempt) {\n return {\n ok: false,\n detail: \"This sign-in link has expired or was already used\",\n returnUrl: null,\n };\n }\n const fail = async (detail: string) => {\n await attempts.finish(attempt.state, detail);\n return { ok: false, detail, returnUrl: attempt.return_url };\n };\n if (callback.error || !callback.code) {\n return fail(\n callback.errorDescription ??\n (callback.error\n ? `The provider refused the sign-in (${callback.error})`\n : \"The provider sent no authorization code\"),\n );\n }\n\n try {\n const document = await this.connectionDocument(attempt.connection_id);\n const state = document.state.global;\n const config = (state.config ?? {}) as Record<string, unknown>;\n // Changed while the user was signing in: the token would belong to\n // another app than the one the connection now names.\n const appId = config[OAUTH_APP];\n // A relayed attempt holds no secret ref; only the app's relay matches it.\n const relayed = attempt.client_secret_ref === null;\n let fromRegistry = false;\n if (typeof appId === \"string\" && appId !== \"\") {\n const apps = await this.oauthApps();\n fromRegistry = relayed\n ? apps.relay(appId)?.clientId === attempt.client_id\n : apps.clients(appId).some((c) => c.clientId === attempt.client_id);\n }\n if (\n state.authType !== \"OAUTH2\" ||\n (!fromRegistry &&\n (relayed || config[OAUTH_CLIENT_ID] !== attempt.client_id))\n ) {\n return await fail(\"The connection changed during sign-in; try again\");\n }\n const secrets = await this.secrets();\n const connectionId = document.header.id;\n const tokens = await exchangeCode(\n attempt,\n callback.code,\n // A relay adds the secret itself; a host app's client secret has\n // no owner document.\n attempt.client_secret_ref === null\n ? null\n : await secrets.get(\n attempt.client_secret_ref,\n fromRegistry\n ? null\n : { documentId: connectionId, kind: \"connection\" },\n ),\n this.designEgress,\n fromRegistry,\n );\n const value = JSON.stringify(tokens);\n const existing = state.secretRefs.find(\n (entry) => entry.name === OAUTH_TOKEN,\n );\n let ref = existing?.ref;\n // Rotated in place only when this connection owns it and whoever signed\n // in may change it; else a new one, so no one's secret is overwritten.\n try {\n const stat = ref ? await secrets.stat(ref) : undefined;\n if (\n ref &&\n stat?.ownerId === connectionId &&\n (stat.createdBy === null || stat.createdBy === attempt.created_by)\n ) {\n await secrets.rotate(ref, value);\n } else {\n ref = undefined;\n }\n } catch {\n ref = undefined;\n }\n if (!ref) {\n ref = (\n await secrets.create({\n value,\n label: `${state.name || \"connection\"} · OAuth2 token`,\n ownerId: connectionId,\n createdBy: attempt.created_by,\n })\n ).ref;\n await this.host.reactorClient.execute(document.header.id, \"main\", [\n connectionActions.setSecretRef({\n id: existing?.id ?? generateId(),\n name: OAUTH_TOKEN,\n ref,\n }),\n ]);\n }\n // What this sign-in covers, so an app asking for more scopes later\n // can tell the token does not reach them and ask for a new sign-in.\n const granted = grantedScopes(tokens.scope, config);\n if (granted) {\n await this.host.reactorClient.execute(document.header.id, \"main\", [\n connectionActions.setConfigValue({\n name: OAUTH_GRANTED_SCOPES,\n value: granted,\n }),\n ]);\n }\n const result = await this.checkConnectionDocument(\n await this.connectionDocument(attempt.connection_id),\n );\n if (!result.ok) {\n return await fail(result.detail ?? \"Connection check failed\");\n }\n await attempts.finish(attempt.state, null);\n return { ok: true, detail: null, returnUrl: attempt.return_url };\n } catch (error) {\n this.logger.warn(\n \"OAuth2 sign-in for connection @id failed: @error\",\n attempt.connection_id,\n error,\n );\n return fail(error instanceof Error ? error.message : String(error));\n }\n }\n\n private async recordCheckResult(\n document: ConnectionDocument,\n result: ConnectionCheckResult,\n ): Promise<ConnectionCheckResult> {\n const actionList: Action[] = [\n connectionActions.recordCheckResult({\n status: result.ok ? \"OK\" : \"ERROR\",\n checkedAt: new Date().toISOString(),\n error: result.ok ? undefined : (result.detail ?? undefined),\n }),\n ];\n // Stored so the connections query and the editors show it.\n const label = result.accountLabel;\n if (label && label !== (document.state.global.accountLabel ?? null)) {\n actionList.push(\n connectionActions.setAccountLabel({ accountLabel: label }),\n );\n }\n await this.host.reactorClient.execute(\n document.header.id,\n \"main\",\n actionList,\n );\n return result;\n }\n\n // The pieces this reactor holds locally, described from their own code.\n\n // One failure does not sink the catalog: a package whose piece cannot be\n // loaded is logged and left out, the way an unreachable listing would be.\n private async localPieces(): Promise<\n { piece: LocalPiece; descriptor: PieceDescriptor }[]\n > {\n const described = await Promise.all(\n installedPieces().map(async (piece) => {\n try {\n const descriptor = await this.pieceDescriptor(localTarget(piece));\n return { piece, descriptor };\n } catch (error) {\n this.logger.warn(\n 'Could not describe the package piece \"@piece\": @error',\n piece.name,\n String(error),\n );\n return undefined;\n }\n }),\n );\n return described.filter((entry) => entry !== undefined);\n }\n\n private async localPiece(\n packageName: string,\n ): Promise<{ piece: LocalPiece; descriptor: PieceDescriptor } | undefined> {\n const piece = installedPiece(packageName);\n if (!piece) return undefined;\n return {\n piece,\n descriptor: await this.pieceDescriptor(localTarget(piece)),\n };\n }\n\n // Package pieces plus the published catalog, the local ones winning their\n // own names. The listing is remote, so it may be the half that fails: with\n // local pieces to show, that is logged rather than served as no catalog.\n async pieceCatalog(): Promise<PieceSummary[]> {\n const local = await this.localPieces();\n const entries = local.map(({ piece, descriptor }) =>\n catalogEntry(descriptor, piece.name, piece.version),\n );\n const names = new Set(entries.map((entry) => entry.name));\n let published: PieceSummary[];\n try {\n published = await fetchPieceCatalog();\n } catch (error) {\n if (entries.length === 0) throw error;\n this.logger.warn(\"Serving package pieces only: @error\", String(error));\n published = [];\n }\n const publishedVersions = new Map(\n published.map((entry) => [entry.name, entry.version]),\n );\n return [\n ...entries.map((entry) => {\n const publishedVersion = publishedVersions.get(entry.name);\n return publishedVersion ? { ...entry, publishedVersion } : entry;\n }),\n ...published.filter((entry) => !names.has(entry.name)),\n ].sort((a, b) => a.displayName.localeCompare(b.displayName));\n }\n\n // A version reads that version; without one, the installed piece or the latest.\n async pieceActions(\n packageName: string,\n version?: string,\n ): Promise<PieceActionsResult> {\n const local = await this.localPieceAt(packageName, version);\n return local\n ? actionsResult(local.descriptor, local.piece.name, local.piece.version)\n : fetchPieceActions(packageName, version);\n }\n\n async pieceTriggers(\n packageName: string,\n version?: string,\n ): Promise<PieceTriggersResult> {\n const local = await this.localPieceAt(packageName, version);\n return local\n ? triggersResult(local.descriptor, local.piece.name, local.piece.version)\n : fetchPieceTriggers(packageName, version);\n }\n\n // The published index takes a large download; a host starts it at boot.\n warmPieceSearch(): void {\n warmSearchIndex();\n }\n\n // Catalog search, with this reactor's own pieces always in it: the index\n // behind the published half may still be building, or unreachable.\n async searchPieces(\n query: string,\n filter: PieceSearchFilter,\n ): Promise<PieceSearchResult> {\n let local: BlockSearchIndex | undefined;\n try {\n local = indexPieces(\n (await this.localPieces()).map(({ piece, descriptor }) =>\n localSearchPiece(descriptor, piece.name, piece.version),\n ),\n );\n } catch (error) {\n // The published half is still worth serving without them.\n this.logger.warn(\n \"Could not index the package pieces: @error\",\n String(error),\n );\n }\n return searchPieces(query, filter, local);\n }\n\n async pieceDetail(packageName: string, version?: string): Promise<unknown> {\n const local = await this.localPieceAt(packageName, version);\n return local\n ? detailResult(local.descriptor, local.piece.name, local.piece.version)\n : fetchPieceDetail(packageName, version);\n }\n\n // The installed piece when it answers for the version asked (or none was).\n private async localPieceAt(\n packageName: string,\n version: string | undefined,\n ): Promise<{ piece: LocalPiece; descriptor: PieceDescriptor } | undefined> {\n const piece = installedPiece(packageName);\n if (!piece) return undefined;\n if (version && version !== piece.version && !isHostBound(piece.name)) {\n return undefined;\n }\n return this.localPiece(packageName);\n }\n\n // Design-time: the action/trigger descriptor (props, auth) driving the\n // editor form; triggers come back under a \"trigger\" key.\n async blockDescriptor(block: BlockRef): Promise<unknown> {\n const parsed = await this.resolvedPiece(block);\n if (!parsed) return null;\n const descriptor = await this.pieceDescriptor(targetOf(parsed));\n // Refused here so no form is ever drawn for a block that cannot run.\n if (descriptor.unsupported) {\n throw new UnsupportedPieceFeatureError(\n `Piece \"${parsed.packageName}\"`,\n descriptor.unsupported,\n );\n }\n const common = {\n displayName: descriptor.displayName,\n logoUrl: descriptor.logoUrl,\n auth: clientAuth(descriptor.auth),\n };\n if (parsed.kind === \"trigger\") {\n const trigger = descriptor.triggers.find(\n (entry) => entry.name === parsed.name,\n );\n if (trigger?.unsupported) {\n throw new UnsupportedPieceFeatureError(\n `Trigger \"${parsed.name}\" of \"${parsed.packageName}\"`,\n trigger.unsupported,\n );\n }\n return trigger ? { ...common, trigger } : null;\n }\n const action = descriptor.actions.find(\n (entry) => entry.name === parsed.name,\n );\n return action ? { ...common, action } : null;\n }\n\n // Design-time entry points hand a connection's live credentials to piece\n // code, so the caller must be allowed to read the connection document.\n\n // A missing context means the request arrived through a path that cannot\n // identify its caller; that is a refusal, not a pass.\n // Keeps only what this caller may read. Without a context nothing is\n // readable, which is what an unauthenticated listing should return.\n private async readableDocuments<T extends { header: { id: string } }>(\n documents: T[],\n ctx: WorkflowCaller | undefined,\n ): Promise<T[]> {\n if (!ctx) return [];\n const host = this.host;\n const allowed = await Promise.all(\n documents.map((document) =>\n host\n .assertCanRead(document.header.id, ctx)\n .then(() => true)\n .catch(() => false),\n ),\n );\n return documents.filter((_, index) => allowed[index]);\n }\n\n // The same filter for journal rows, which carry the document they belong to\n // rather than being one.\n private async readableRows<T>(\n rows: T[],\n documentIdOf: (row: T) => string,\n ctx: WorkflowCaller | undefined,\n ): Promise<T[]> {\n if (!ctx) return [];\n const allowed = await Promise.all(\n rows.map((row) => this.canReadDocument(documentIdOf(row), ctx)),\n );\n return rows.filter((_, index) => allowed[index]);\n }\n\n private canReadDocument(\n documentId: string,\n ctx: WorkflowCaller,\n ): Promise<boolean> {\n return this.host\n .assertCanRead(documentId, ctx)\n .then(() => true)\n .catch(() => false);\n }\n\n // A run carries its trigger payload and every step's input and output, drawn\n // from the documents its trigger names and those the reactor port handed its\n // steps, so it is served only to a caller who is served each of them. One no\n // longer live has no content left to protect, or a deletion's runs would be\n // served to nobody.\n private async servedRuns(\n rows: RunRow[],\n ctx: WorkflowCaller | undefined,\n ): Promise<RunRow[]> {\n if (!ctx) return [];\n const decisions = new Map<string, Promise<boolean>>();\n const store = await this.store();\n const documents = await store?.getRunDocumentsForRuns(\n rows.map((row) => row.id),\n );\n const served = await Promise.all(\n rows.map((row) =>\n this.servesDocuments(\n [\n ...journaledTriggerDocumentIds(row.trigger_payload),\n ...(documents?.get(row.id) ?? []),\n ],\n ctx,\n decisions,\n ),\n ),\n );\n return rows.filter((_, index) => served[index]);\n }\n\n private async servesDocuments(\n documentIds: string[],\n ctx: WorkflowCaller,\n decisions = new Map<string, Promise<boolean>>(),\n ): Promise<boolean> {\n const served = await Promise.all(\n [...new Set(documentIds)].map((documentId) => {\n let decision = decisions.get(documentId);\n if (!decision) {\n decision = this.servesRunDocument(documentId, ctx);\n decisions.set(documentId, decision);\n }\n return decision;\n }),\n );\n return served.every(Boolean);\n }\n\n private async servesRunDocument(\n documentId: string,\n ctx: WorkflowCaller,\n ): Promise<boolean> {\n if (await this.canReadDocument(documentId, ctx)) return true;\n try {\n await this.host.reactorClient.get(documentId, { scopes: [\"document\"] });\n } catch (error) {\n return isAbsent(error);\n }\n return false;\n }\n\n private async assertCanReadDocument(\n documentId: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<void> {\n if (!ctx) {\n throw new Error(\"Connection access requires an authenticated request\");\n }\n await this.host.assertCanRead(documentId, ctx);\n }\n\n // A caller allowed on the drive waits (bounded) for a workflow that has not\n // reached this reactor; anyone else is refused at once.\n private async assertCanReadWorkflow(\n workflowId: string,\n ctx: WorkflowCaller | undefined,\n driveId: string | undefined,\n ): Promise<void> {\n try {\n await this.assertCanReadDocument(workflowId, ctx);\n } catch (denied) {\n const client = this.host.reactorClient;\n if (!driveId || !(await isNotHereYet(client, workflowId))) throw denied;\n await this.assertCanReadDocument(driveId, ctx);\n await waitForSync(\n client,\n workflowId,\n () => this.assertCanReadDocument(workflowId, ctx),\n this.host.syncWaitMs ?? SYNC_WAIT_MS,\n );\n }\n }\n\n private async assertCanWriteDocument(\n documentId: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<void> {\n if (!ctx) {\n throw new Error(\"Connection access requires an authenticated request\");\n }\n await this.host.assertCanWrite(documentId, ctx);\n }\n\n // Design-time DROPDOWN options() / DYNAMIC props(), run in the piece worker.\n async blockOptions(\n block: BlockRef,\n propName: string,\n input?: unknown,\n connectionId?: string,\n ctx?: WorkflowCaller,\n searchValue?: string,\n // The step's reactor connection, which narrows what a resolver reads.\n reactorConnectionId?: string,\n // The workflow being edited; ctx.flows.list lists what it may call.\n editedWorkflowId?: string,\n ): Promise<unknown> {\n // Auth-dependent options() resolvers need the step's connection. Nothing\n // about the request authorizes it, so the caller's own read access does.\n if (connectionId) await this.assertCanReadDocument(connectionId, ctx);\n if (reactorConnectionId) {\n await this.assertCanReadDocument(reactorConnectionId, ctx);\n }\n // Only ctx.flows needs the workflow; one not readable yet (e.g. not synced\n // from the editor) lists no flows rather than failing every dropdown.\n const workflowId =\n editedWorkflowId &&\n (await this.assertCanReadDocument(editedWorkflowId, ctx).then(\n () => true,\n () => false,\n ))\n ? editedWorkflowId\n : undefined;\n const resolution = await this.resolveBlock(block);\n const parsed = resolvedBlock(resolution);\n if (!parsed) {\n throw new Error(\n resolution.note ?? `${blockLabel(block)} does not resolve`,\n );\n }\n if (builtinPiece(parsed.packageName)) {\n throw new Error(`${blockLabel(block)} has no options to resolve`);\n }\n let auth: unknown;\n if (connectionId) {\n auth = await new DocumentConnectionResolver(\n this.host,\n this.secretProvider(),\n this.oauthRefresher(),\n ).resolve(connectionId, { piecePackage: parsed.packageName });\n }\n const piece = await pieceResolver().resolve(targetOf(parsed));\n const reactor = await this.designReactorAccess(\n parsed,\n ctx,\n reactorConnectionId,\n );\n this.designWorker ??= this.createDesignWorker();\n const result = await this.designWorker.resolveOptions(\n {\n ...pieceModuleRef(piece),\n actionName: parsed.name,\n kind: parsed.kind,\n propName,\n refresherValues: (input ?? {}) as Record<string, unknown>,\n ...(searchValue !== undefined ? { searchValue } : {}),\n auth,\n projectId: PROJECT_SCOPE_KEY,\n // Options come from the same service the step will call: the editor\n // must not offer a choice a run cannot reach.\n ...(this.designEgress ? { egress: this.designEgress } : {}),\n ...(workflowId ? { flows: true } : {}),\n },\n {\n ...(reactor ? { reactor } : {}),\n ...(workflowId\n ? {\n hostCalls: {\n [FLOWS_LIST]: (payload: unknown) =>\n this.listFlows(\n workflowId,\n (payload as { externalIds?: string[] } | undefined)\n ?.externalIds,\n ctx,\n ),\n },\n }\n : {}),\n },\n );\n return result.output;\n }\n\n // Authored output shape of a block, for the editor's expression picker.\n async blockOutputTree(\n block: BlockRef,\n config?: unknown,\n ): Promise<OutputTree> {\n const record = (config ?? {}) as Record<string, unknown>;\n switch (blockKey(block)) {\n case MANUAL_BLOCK: {\n const nodes = manualTriggerTree(parseManualInputs(record));\n return { source: nodes.length > 0 ? \"static\" : \"none\", nodes };\n }\n case SCHEDULE_BLOCK:\n return { source: \"static\", nodes: scheduleTriggerTree() };\n case WEBHOOK_BLOCK:\n return { source: \"static\", nodes: webhookTriggerTree() };\n case BRANCH_BLOCK:\n return {\n source: \"static\",\n nodes: [\n { name: \"operator\", type: \"String!\" },\n { name: \"left\", type: \"value\" },\n { name: \"right\", type: \"value\" },\n { name: \"result\", type: \"Boolean!\" },\n ],\n };\n case ROUTER_BLOCK:\n return {\n source: \"static\",\n nodes: [\n {\n name: \"branch\",\n type: \"String\",\n description: \"The matched branch's name; null for otherwise\",\n },\n {\n name: \"index\",\n type: \"Int\",\n description: \"The matched branch, from 1; null for otherwise\",\n },\n ],\n };\n case LOOP_BLOCK:\n return {\n source: \"static\",\n nodes: [\n {\n name: \"item\",\n type: \"value\",\n description: \"The current item; the last one after the loop\",\n },\n { name: \"index\", type: \"Int!\", description: \"From 1\" },\n { name: \"count\", type: \"Int\", description: \"Set after the loop\" },\n {\n name: \"iterations\",\n type: \"array\",\n description: \"Set after the loop: each item's step outputs\",\n children: [\n { name: \"index\", type: \"Int!\" },\n { name: \"item\", type: \"value\" },\n { name: \"steps\", type: \"JSONObject!\" },\n ],\n },\n ],\n };\n case ASSERT_BLOCK:\n return { source: \"static\", nodes: [{ name: \"value\", type: \"value\" }] };\n case DELAY_BLOCK:\n return {\n source: \"static\",\n nodes: [{ name: \"resumedAt\", type: \"DateTime!\" }],\n };\n case APPROVAL_BLOCK:\n return {\n source: \"static\",\n nodes: [\n { name: \"approved\", type: \"Boolean!\" },\n { name: \"reason\", type: \"String\" },\n {\n name: \"decidedBy\",\n type: \"String\",\n description: \"The approver's DID\",\n },\n { name: \"decidedAt\", type: \"DateTime!\" },\n ],\n };\n case STOP_BLOCK:\n return {\n source: \"static\",\n nodes: [\n {\n name: \"response\",\n type: \"JSONObject\",\n description: \"The answer sent, when one was set\",\n },\n ],\n };\n case WAIT_FOR_WEBHOOK_BLOCK:\n return {\n source: \"static\",\n nodes: [\n {\n name: \"body\",\n type: \"Unknown\",\n description: \"The resuming request's body\",\n },\n { name: \"headers\", type: \"JSONObject!\" },\n { name: \"queryParams\", type: \"JSONObject!\" },\n ],\n };\n case DOCUMENT_CREATED_BLOCK:\n case DOCUMENT_DELETED_BLOCK:\n return { source: \"static\", nodes: lifecycleTriggerTree() };\n case DOCUMENT_EVENT_BLOCK: {\n const inputChildren = await this.operationInputFields(\n staticString(record.documentType),\n staticString(record.actionType),\n );\n return {\n source: inputChildren.length > 0 ? \"schema\" : \"static\",\n nodes: documentEventTree(inputChildren),\n };\n }\n case DOCUMENT_FIND_BLOCK:\n return { source: \"static\", nodes: documentFindTree() };\n case DOCUMENT_SCHEMA_BLOCK:\n return { source: \"static\", nodes: documentSchemaTree() };\n case DOCUMENT_TYPES_BLOCK:\n return { source: \"static\", nodes: documentTypesTree() };\n case DOCUMENT_GET_BLOCK: {\n // The type may come from a sibling hint when the id is an expression.\n const stateChildren = await this.stateFields(\n staticString(record.documentType),\n );\n return {\n source: stateChildren.length > 0 ? \"schema\" : \"static\",\n nodes: documentTree(stateChildren),\n };\n }\n case DOCUMENT_CREATE_BLOCK:\n case DOCUMENT_DISPATCH_BLOCK:\n return { source: \"static\", nodes: documentReferenceTree() };\n default: {\n const parsed = await this.resolvedPiece(block);\n if (!parsed) return { source: \"none\", nodes: [] };\n // Described from the version that runs, not the catalog's latest.\n const detail = detailResult(\n await this.pieceDescriptor(targetOf(parsed)),\n parsed.packageName,\n parsed.version,\n ) as {\n actions?: Record<string, unknown>;\n triggers?: Record<string, unknown>;\n };\n const entry = (\n parsed.kind === \"trigger\" ? detail.triggers : detail.actions\n )?.[parsed.name] as\n | { outputSchema?: unknown; sampleData?: unknown }\n | undefined;\n if (entry?.outputSchema) {\n const nodes = fromOutputSchema(entry.outputSchema);\n if (nodes.length > 0) return { source: \"schema\", nodes };\n // Fields that all map to the whole output: the output is a scalar.\n if (hasOutputSchemaFields(entry.outputSchema)) {\n return { source: \"schema\", nodes: [] };\n }\n }\n if (entry?.sampleData !== undefined && entry.sampleData !== null) {\n const nodes = fromSample(entry.sampleData);\n if (nodes.length > 0) return { source: \"sample\", nodes };\n }\n return { source: \"none\", nodes: [] };\n }\n }\n }\n\n private async stateFields(documentType?: string) {\n if (!documentType) return [];\n try {\n const module =\n await this.host.reactorClient.getDocumentModelModule(documentType);\n const model = module.documentModel.global;\n const sdl = model.specifications.at(-1)?.state.global.schema;\n return sdl ? fieldsFromSdl(sdl, { state: model.name }) : [];\n } catch {\n return [];\n }\n }\n\n private async operationInputFields(\n documentType?: string,\n actionType?: string,\n ) {\n if (!documentType || !actionType) return [];\n try {\n const module =\n await this.host.reactorClient.getDocumentModelModule(documentType);\n const operation = operationForActionType(module, actionType);\n return operation?.name && operation.schema\n ? fieldsFromSdl(operation.schema, { input: operation.name })\n : [];\n } catch {\n return [];\n }\n }\n\n // Runs the draft trigger's test hook; the test store prefix keeps cursors\n // intact. The sample is journaled as a \"test\" run and noted as lastTest.\n\n // It resolves the trigger's connection and hands the credentials to piece\n // code, so the caller must be able to read both documents.\n // Core triggers: manual takes `payload` as its sample, schedule samples a\n // fire now, and webhook waits (up to `timeoutMs`) for the next delivery.\n async testTrigger(\n workflowId: string,\n ctx?: WorkflowCaller,\n options: TriggerTestOptions = {},\n ): Promise<unknown> {\n await this.assertCanReadWorkflow(workflowId, ctx, options.driveId);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n const state = document.state.global;\n const trigger = state.trigger;\n if (!trigger) throw new Error(\"Workflow has no trigger\");\n if (trigger.connectionId) {\n await this.assertCanReadDocument(trigger.connectionId, ctx);\n }\n if (trigger.reactorConnectionId) {\n await this.assertCanReadDocument(trigger.reactorConnectionId, ctx);\n }\n const test = await this.triggerTest(workflowId, trigger, options, ctx);\n const startedAt = new Date().toISOString();\n const recordTest = (\n outcome: Pick<\n StepExecutionRecord,\n \"status\" | \"output\" | \"port\" | \"error\" | \"errorName\"\n >,\n ) =>\n this.recordTest(workflowId, state, document.header.name, {\n stepId: trigger.id,\n key: \"trigger\",\n pieceName: trigger.pieceName,\n blockName: trigger.triggerName,\n input: test.input,\n ...outcome,\n startedAt,\n endedAt: new Date().toISOString(),\n });\n let output: unknown;\n try {\n output = await test.sample();\n } catch (error) {\n // A host call the hook made may have committed the write it asked for,\n // so the test neither succeeded nor failed. It takes no port either.\n const errorName = errorNameOf(error);\n await recordTest({\n status: isIndeterminateError(error) ? \"INDETERMINATE\" : \"FAILED\",\n error: pieceFailureDetail(error, \"Trigger test timed out\"),\n ...(errorName ? { errorName } : {}),\n });\n throw error;\n }\n await recordTest({ status: \"SUCCEEDED\", output, port: \"next\" });\n return output;\n }\n\n // What a trigger test samples, and the config it journals as input.\n private async triggerTest(\n workflowId: string,\n trigger: NonNullable<WorkflowState[\"trigger\"]>,\n options: TriggerTestOptions,\n ctx?: WorkflowCaller,\n ): Promise<{ input: unknown; sample: () => Promise<unknown> }> {\n const config = configRecord(trigger.config);\n const block = triggerBlock(trigger);\n switch (blockKey(block)) {\n case MANUAL_BLOCK:\n return {\n input: config,\n sample: () => Promise.resolve(options.payload ?? {}),\n };\n case SCHEDULE_BLOCK: {\n const schedule = parseScheduleConfig(config);\n return {\n input: config,\n sample: () => {\n const now = new Date();\n return Promise.resolve(schedulePayload(schedule, now, now));\n },\n };\n }\n case WEBHOOK_BLOCK: {\n const webhook = parseWebhookConfig(config);\n // Minted now, so the author can send to it while this waits.\n if (!(await this.endpoints())) {\n throw new Error(\"This host serves no webhooks\");\n }\n await this.mintWebhookEndpoint(workflowId);\n return {\n input: config,\n sample: () =>\n this.awaitWebhookTest(workflowId, webhook, options.timeoutMs),\n };\n }\n }\n const { binding } = await this.pieceBinding(workflowId, trigger);\n if (!binding) {\n throw new Error(\n `${blockLabel(block)} is not a trigger this runtime can test`,\n );\n }\n return {\n input: binding.config,\n // A trigger test acts as its caller.\n sample: () =>\n this.supervisor().test(binding, { runUser: this.callerRunUser(ctx) }),\n };\n }\n\n // One-shot listeners: the next delivery to the workflow's endpoint is the\n // sample. It runs the workflow only if the workflow is armed.\n private readonly webhookTests = new Map<string, WebhookTest>();\n\n private awaitWebhookTest(\n workflowId: string,\n config: WebhookConfig,\n timeoutMs = WEBHOOK_TEST_TIMEOUT_MS,\n ): Promise<WebhookPayload> {\n this.cancelTriggerTest(workflowId, \"superseded by a newer test\");\n const waitMs = Math.min(Math.max(timeoutMs, 0), WEBHOOK_TEST_TIMEOUT_MS);\n return new Promise<WebhookPayload>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.webhookTests.delete(workflowId);\n reject(\n new Error(\n `No webhook delivery arrived within ${Math.round(waitMs / 1000)}s`,\n ),\n );\n }, waitMs);\n timer.unref();\n this.webhookTests.set(workflowId, { config, resolve, reject, timer });\n });\n }\n\n /** Stops a waiting webhook test; false when none was waiting. */\n cancelTriggerTest(workflowId: string, reason = \"cancelled\"): boolean {\n const pending = this.webhookTests.get(workflowId);\n if (!pending) return false;\n this.webhookTests.delete(workflowId);\n clearTimeout(pending.timer);\n pending.reject(new Error(`Trigger test ${reason}`));\n return true;\n }\n\n // The caller may read the workflow, as for a test.\n async cancelTriggerTestFor(\n workflowId: string,\n ctx?: WorkflowCaller,\n ): Promise<boolean> {\n await this.assertCanReadDocument(workflowId, ctx);\n return this.cancelTriggerTest(workflowId);\n }\n\n // Journals a design-time test as a one-step \"test\" run, then points the\n // tested block's lastTest at it. Both are best-effort.\n private async recordTest(\n workflowId: string,\n state: WorkflowState,\n name: string | undefined,\n record: StepExecutionRecord,\n ): Promise<void> {\n const store = await this.store();\n if (!store) return;\n let runId: string;\n try {\n runId = await store.startRun({\n workflowId,\n workflowName: runJournalName(state.name, name),\n workflowVersion: state.version,\n triggerKind: TEST_TRIGGER_KIND,\n });\n await store.recordStep(runId, 0, record);\n // An INDETERMINATE step ends a real run FAILED (coordinator.ts), and a\n // test run says the same rather than reading green: the step row carries\n // the INDETERMINATE status, the run row carries that it did not confirm.\n const indeterminate = record.status === \"INDETERMINATE\";\n const error = indeterminate\n ? `This test is INDETERMINATE: ${record.error ?? \"a host call it made timed out\"}`\n : record.error;\n await store.finishRun(runId, {\n status: record.status === \"SUCCEEDED\" ? \"SUCCEEDED\" : \"FAILED\",\n steps: [record],\n ...(error ? { error } : {}),\n ...(record.errorName ? { errorName: record.errorName } : {}),\n });\n } catch (error) {\n this.logger.warn(\n `Could not journal the test of \"@step\" on workflow ${workflowId}: @error`,\n record.key,\n error,\n );\n return;\n }\n await this.noteLastTest(\n workflowId,\n record,\n runId,\n record.endedAt ?? new Date().toISOString(),\n );\n }\n\n private async noteLastTest(\n workflowId: string,\n record: Pick<StepExecutionRecord, \"stepId\" | \"key\">,\n runId: string,\n testedAt: string,\n ): Promise<void> {\n try {\n await this.host.reactorClient.execute(workflowId, \"main\", [\n workflowActions.setLastTest({ id: record.stepId, runId, testedAt }),\n ]);\n } catch (error) {\n this.logger.warn(\n `Could not record the last test of \"@step\" on workflow ${workflowId}: @error`,\n record.key,\n error,\n );\n }\n }\n\n // Without a journal there is nowhere durable to keep ctx.store, so the\n // executor falls back to the worker's heap.\n private blockExecutor(store: WorkflowRunStore | undefined): BlockExecutor {\n return (this.executor ??= tracedSteps(\n createBlockExecutor(\n this.host,\n this.secretProvider(),\n this.attachments,\n store ? createPieceStorePort(store, currentWorkflowId) : undefined,\n // A step resolves its block the way every other caller does, so a\n // trigger that arms cannot be followed by a step that cannot start.\n (block) => this.resolveBlock(block),\n this.oauthRefresher(),\n (request) => this.stepReactorAccess(request),\n this.telemetry,\n ),\n this.telemetry,\n ));\n }\n\n // Every piece request leases a warm child from one pool: runs, the editor\n // and trigger hooks. Unset sizes come from the container's cores and memory.\n private workers(): PieceWorkerPool {\n if (this.pieceWorkers) return this.pieceWorkers;\n const env = (name: string) => Number(process.env[name]) || undefined;\n // Where 0 is a setting rather than \"unset\".\n const count = (name: string) => {\n const value = Number(process.env[name] || Number.NaN);\n return value >= 0 ? value : undefined;\n };\n const pool = new PieceWorkerPool({\n models: this.models,\n size: env(\"PH_WORKFLOWS_RUN_CONCURRENCY\"),\n maxQueueDepth: env(\"PH_WORKFLOWS_RUN_QUEUE_DEPTH\"),\n heapMb: env(\"PH_WORKFLOWS_WORKER_MEMORY_MB\"),\n maxRequests: env(\"PH_WORKFLOWS_WORKER_MAX_REQUESTS\"),\n minWarm: count(\"PH_WORKFLOWS_WORKER_MIN\"),\n triggerSlots: env(\"PH_WORKFLOWS_TRIGGER_SLOTS\"),\n reactorThreads: this.host.reactorThreads,\n telemetry: this.telemetry,\n });\n // Built after shutdown, by a late supervisor or editor call: forks nothing.\n if (this.closed) {\n pool.dispose();\n return (this.pieceWorkers = pool);\n }\n const unobservePool = this.telemetry.observeWorkerPool(() => pool.stats());\n const unregisterGauge = registerTelemetryGauge(\"workflow.pool\", () =>\n pool.memoryStats(),\n );\n const unregisterRuns = registerTelemetryGauge(\n \"workflow.runs\",\n runScopeStats,\n );\n this.unobservePool = () => {\n unobservePool();\n unregisterGauge();\n unregisterRuns();\n };\n return (this.pieceWorkers = pool);\n }\n\n // Eight runs in flight per child by default: one waiting out a retry holds its\n // place. Built after shutdown, it admits nothing.\n private dispatcher(): RunDispatcher {\n if (this.runDispatcher) return this.runDispatcher;\n const configured = Number(process.env.PH_WORKFLOWS_ADMIT_MAX_ELU);\n const dispatcher = new RunDispatcher({\n maxInFlight:\n Number(process.env.PH_WORKFLOWS_RUNS_IN_FLIGHT) ||\n 8 * this.workers().size,\n maxElu:\n configured > 0 && configured <= 1 ? configured : DEFAULT_ADMIT_MAX_ELU,\n loop: this.eventLoop,\n });\n this.runDispatcher = dispatcher;\n if (this.closed) {\n dispatcher.close();\n return dispatcher;\n }\n this.eventLoop.start();\n this.unobserveDispatcher = this.telemetry.observeDispatcher(() => ({\n ...dispatcher.stats(),\n utilization: this.eventLoop.utilization(),\n }));\n return dispatcher;\n }\n\n async fire(\n workflowId: string,\n triggerPayload?: unknown,\n triggerKind = \"manual\",\n resume?: RunResume,\n ctx?: WorkflowCaller,\n // A PENDING run this workflow's trigger journaled, adopted rather than created.\n enqueuedRunId?: string,\n ): Promise<PersistedRunResult> {\n if (this.closed) {\n return this.refuseClosed(\n await this.store(),\n workflowId,\n enqueuedRunId,\n triggerKind,\n );\n }\n const started = performance.now();\n const attributes = {\n \"workflow.id\": workflowId,\n \"trigger.kind\": triggerKind,\n ...(resume ? { \"run.rerun_of\": resume.rerunOf } : {}),\n };\n // Counted from here, before the gate: a firing still reading its workflow\n // holds a slot's worth of work as much as one already admitted.\n this.unsettledFirings.set(\n workflowId,\n (this.unsettledFirings.get(workflowId) ?? 0) + 1,\n );\n const traced = this.telemetry.span(\n \"workflow.run\",\n attributes,\n async (span) => {\n const run: RunTrace = { span, refused: false };\n let status = \"FAILED\";\n try {\n const result = await this.runFired(\n run,\n workflowId,\n triggerPayload,\n triggerKind,\n resume,\n ctx,\n enqueuedRunId,\n );\n status = result.status;\n if (status === \"FAILED\") {\n span.setStatus({ code: SpanStatusCode.ERROR, message: status });\n }\n return result;\n } finally {\n // Refused by access, type or status: not a failed run.\n if (run.refused) status = \"REFUSED\";\n span.setAttribute(\"run.status\", status);\n this.telemetry.recordRun(\n performance.now() - started,\n status,\n triggerKind,\n );\n }\n },\n );\n try {\n return await traced;\n } finally {\n this.settleFiring(workflowId);\n if (enqueuedRunId) void this.endSubflow(enqueuedRunId);\n }\n }\n\n private async runFired(\n run: RunTrace,\n workflowId: string,\n triggerPayload: unknown,\n triggerKind: string,\n resume: RunResume | undefined,\n ctx: WorkflowCaller | undefined,\n enqueuedRunId: string | undefined,\n ): Promise<PersistedRunResult> {\n // `policy.runTimeoutSeconds` is measured from HERE, the moment the firing\n // reaches the runtime — not from admission. The queue wait is part of the\n // time the run took: computing the deadline after admit() meant a firing\n // could sit in a QUEUE lane for an hour under a 30-second timeout and then\n // run anyway, with its whole budget intact. The point of a run timeout is\n // that a trigger's work is either done inside it or not done at all.\n const firedAt = Date.now();\n const store = await this.store();\n let state: WorkflowState;\n // Carried out of the try so the run journal can fall back to it: a\n // workflow's state.name is a separate field from the document's name and\n // starts empty, so a workflow created without setting it stamps \"\" on every\n // run it ever makes. The drive still lists it correctly, which is what makes\n // the blank column in a run table look like a UI fault rather than a\n // missing value.\n let documentName: string | undefined;\n let definition: ReturnType<typeof toWorkflowDefinition>;\n let runUser: RunUser | null | undefined;\n // The workflow's generation as read: a wait it outlasts re-reads nothing.\n let readGeneration: number;\n // The global revision the state reflects; a run that waits pins it.\n let revision: number;\n try {\n // \"manual\" is the only kind a caller can ask for; every other one is\n // system-initiated. An adopted manual row passed this check when journaled.\n if (triggerKind === \"manual\" && !enqueuedRunId) {\n await this.assertCanReadDocument(workflowId, ctx).catch((error) => {\n run.refused = true;\n throw error;\n });\n }\n // A caller's fire or rerun reads fresh; a trigger's run reads the cache.\n const cached =\n triggerKind === \"manual\" || resume\n ? undefined\n : this.workflowCache.get(workflowId);\n if (cached) {\n state = cached.state;\n documentName = cached.name;\n revision = cached.revision;\n readGeneration = this.workflowGeneration(workflowId);\n } else {\n const generation = this.workflowGeneration(workflowId);\n readGeneration = generation;\n const document = await this.telemetry.phase(\"load\", {}, () =>\n this.host.reactorClient.get<WorkflowDocument>(workflowId),\n );\n if (document.header.documentType !== \"powerhouse/workflow\") {\n run.refused = true;\n throw new Error(\n `Document \"${workflowId}\" is not a powerhouse/workflow`,\n );\n }\n state = document.state.global;\n documentName = document.header.name;\n revision = globalRevision(document);\n this.cacheLoaded(workflowId, generation, document);\n }\n if (state.status !== \"ENABLED\") {\n run.refused = true;\n throw new Error(\n `Workflow is ${state.status}; only ENABLED workflows can fire`,\n );\n }\n // A caller's fire is checked against the manual trigger's inputs; a\n // rerun or an adopted row keeps the payload it was journaled with.\n if (triggerKind === \"manual\" && !resume && !enqueuedRunId) {\n const fired = runnableDefinition(state).trigger;\n const inputs =\n fired && blockKey(triggerBlock(fired)) === MANUAL_BLOCK\n ? parseManualInputs(configRecord(fired.config))\n : [];\n if (inputs.length > 0) {\n try {\n triggerPayload = coerceManualPayload(inputs, triggerPayload);\n } catch (error) {\n run.refused = true;\n throw error;\n }\n }\n }\n definition = toWorkflowDefinition(state);\n const reactorConnections = declaredReactorConnectionIds(definition);\n // Before each run: grants can change after the publish was checked.\n runUser =\n reactorConnections.size === 0\n ? undefined\n : await this.telemetry\n .phase(\"run_user\", {}, () =>\n assertReactorConnectionsReadable(\n this.host,\n workflowId,\n reactorConnections,\n ),\n )\n .catch((error: unknown) => {\n run.refused = isReactorError(error, ReactorAccessDeniedError);\n throw error;\n });\n } catch (error) {\n // An adopted row is already durable: closing it out here is what keeps\n // a refused fire from leaving a PENDING run nothing will ever start.\n if (enqueuedRunId) {\n await store?.failRun(\n enqueuedRunId,\n error instanceof Error ? error.message : String(error),\n errorNameOf(error),\n );\n }\n throw error;\n }\n // A manual fire is journaled as it queues, so a crash while it waits\n // leaves it for the next boot; one admitted at once is written as before.\n let journaling: Promise<void> | undefined;\n const journalOnQueue = () => {\n if (triggerKind !== \"manual\" || enqueuedRunId || resume || journaling) {\n return;\n }\n if (!store) return;\n journaling = store\n .enqueueRun({ workflowId, triggerKind, triggerPayload })\n .then((runId) => {\n enqueuedRunId = runId;\n });\n // Awaited once admitted; until then nothing else may observe it.\n journaling.catch(() => undefined);\n };\n // Bound once, to the connections this definition names: an edit landing\n // mid-run cannot widen what the run may resolve.\n const connections = declaredConnectionIds(definition);\n const executor = this.blockExecutor(store);\n\n const runnable = runnableDefinition(state);\n // `policy.concurrency`, enforced. SINGLETON refuses here, before the run\n // row is adopted, so a dropped firing is journaled as the CANCELLED run it\n // is rather than disappearing; QUEUE and a bounded PARALLEL wait.\n const policy = effectiveRunPolicy(runnable);\n this.runLimits.set(workflowId, concurrencyLimit(policy));\n const deadline = policy.runTimeoutSeconds\n ? firedAt + policy.runTimeoutSeconds * 1000\n : undefined;\n const skipped = (reason: string, refusal: FiringRefusal) =>\n this.skipFiring(\n store,\n workflowId,\n enqueuedRunId,\n {\n reason,\n triggerKind,\n triggerPayload,\n workflowName: runJournalName(state.name, documentName),\n workflowVersion: runnable.version,\n },\n refusal,\n );\n let parked: string | undefined;\n try {\n parked = await this.parkedFiring(\n workflowId,\n triggerKind,\n runnable.version,\n );\n } catch (error) {\n // As a refused read above: an adopted row must not stay PENDING.\n if (enqueuedRunId) {\n await store?.failRun(\n enqueuedRunId,\n error instanceof Error ? error.message : String(error),\n errorNameOf(error),\n );\n }\n throw error;\n }\n if (parked) return skipped(parked, \"parked\");\n const admission = await this.runGate.admit(\n workflowId,\n policy,\n journalOnQueue,\n );\n try {\n await journaling;\n } catch (error) {\n if (admission.admitted) admission.release();\n throw error;\n }\n // Shut down while it waited, or as it was handed the slot: refused, not\n // journaled as a fresh CANCELLED run.\n if (this.closed) {\n if (admission.admitted) admission.release();\n return this.refuseClosed(store, workflowId, enqueuedRunId, triggerKind);\n }\n if (!admission.admitted) {\n if (admission.refusal === \"closed\") {\n return this.refuseClosed(store, workflowId, enqueuedRunId, triggerKind);\n }\n return skipped(admission.reason, admission.refusal);\n }\n // A firing that queued read the workflow before it waited: disabled,\n // re-published or parked meanwhile, it must not run on that old read.\n const staleAfter = async (): Promise<string | undefined> => {\n try {\n return await this.staleAfterWait(\n workflowId,\n triggerKind,\n runnable.version,\n readGeneration,\n );\n } catch (error) {\n return (\n \"Skipped: the workflow could not be read again after this firing \" +\n `waited for its slot: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n };\n if (admission.waited) {\n const stale = await staleAfter();\n if (stale) {\n admission.release();\n return skipped(stale, \"stale\");\n }\n }\n // The wait itself outlived the run's deadline, so there is nothing left to\n // run it in: CANCELLED without executing a single step, rather than a side\n // effect fired long after the timeout that was supposed to bound it. The\n // slot goes back first — this firing is not going to use it.\n const expired = () =>\n skipped(\n `Skipped: this firing waited past its runTimeoutSeconds ` +\n `(${policy.runTimeoutSeconds}s) for a concurrency slot and was ` +\n \"cancelled without running\",\n \"expired\",\n );\n if (deadline !== undefined && Date.now() >= deadline) {\n admission.release();\n return expired();\n }\n // Then the cap across workflows: runs in flight, and a busy main thread.\n let dispatched: () => void;\n let dispatcherWaited = false;\n try {\n dispatched = await this.dispatcher().admit(workflowId, () => {\n dispatcherWaited = true;\n journalOnQueue();\n });\n } catch (error) {\n // The refusal below closes out the row this fire journaled while queued.\n await journaling?.catch(() => undefined);\n admission.release();\n if (this.closed)\n return this.refuseClosed(store, workflowId, enqueuedRunId, triggerKind);\n throw error;\n }\n try {\n await journaling;\n } catch (error) {\n dispatched();\n admission.release();\n throw error;\n }\n if (this.closed || (deadline !== undefined && Date.now() >= deadline)) {\n dispatched();\n admission.release();\n return this.closed\n ? this.refuseClosed(store, workflowId, enqueuedRunId, triggerKind)\n : expired();\n }\n if (dispatcherWaited) {\n const stale = await staleAfter();\n if (stale) {\n dispatched();\n admission.release();\n return skipped(stale, \"stale\");\n }\n }\n\n let runId: string | null = enqueuedRunId ?? null;\n // This run's child, forked at its first piece step and killed below. Free\n // until then, so a run of document blocks never takes a slot.\n let session: PieceWorkerSession | undefined;\n // EVERYTHING after admit() belongs inside this try, the journal writes\n // below included: a throw between the admission and the finally would\n // never release the slot, and a leaked slot wedges the workflow for the\n // life of the process — SINGLETON refuses every later firing, QUEUE waits\n // for a run that is already over.\n try {\n const journaled = await this.telemetry.phase(\n \"journal.start\",\n {},\n async (): Promise<{ runId: string | null; cancelled?: boolean }> => {\n if (enqueuedRunId) {\n const adopted = await store?.beginRun(enqueuedRunId, {\n workflowName: runJournalName(state.name, documentName),\n workflowVersion: runnable.version,\n });\n // Cancelled while it queued: the row is closed out already.\n if (adopted === false) return { runId: null, cancelled: true };\n return { runId: enqueuedRunId };\n }\n return {\n runId:\n (await store?.startRun({\n workflowId,\n workflowName: runJournalName(state.name, documentName),\n workflowVersion: runnable.version,\n triggerKind,\n triggerPayload,\n rerunOf: resume?.rerunOf,\n })) ?? null,\n };\n },\n );\n if (journaled.cancelled) {\n const row = enqueuedRunId\n ? await store?.getRun(enqueuedRunId)\n : undefined;\n return {\n status: CANCELLED_RUN_STATUS,\n steps: [],\n runId: enqueuedRunId ?? null,\n ...(row?.error ? { error: row.error } : {}),\n refusal: \"cancelled\",\n };\n }\n runId = journaled.runId;\n if (runId) run.span.setAttribute(\"run.id\", runId);\n // Shut down during the journal write: refused here, and the journal\n // records the run as failed rather than leaving it to be swept up.\n if (this.closed) throw new WorkflowRuntimeClosedError(workflowId);\n if (runId && !resume) {\n await this.startPieceTrigger(workflowId, runId, triggerPayload);\n }\n session = this.workers().session();\n const { result, handed } = await this.executeLeg({\n workflowId,\n runId,\n store,\n session,\n definition,\n runnable,\n policy,\n // From firedAt, so the queue wait and the document read count\n // against the timeout rather than being free.\n deadline,\n connections,\n runUser,\n triggerPayload,\n executor,\n completedSteps: resume?.completedSteps,\n loopItems: resume?.loopItems,\n replayed: resume?.completedSteps,\n pin: () => ({\n definition_hash: this.definitionHash(workflowId, state),\n definition_op_index: revision,\n definition_scope_hash: scopeHash(state),\n }),\n });\n // `policy.onFailure`, enforced: PARK stops the trigger refiring, NOTIFY\n // says so where an operator will see it, IGNORE is the old behaviour.\n // Only for a trigger's firing: an operator's run says nothing about it.\n if (result.status === \"FAILED\" && !OPERATOR_RUN_KINDS.has(triggerKind)) {\n await this.applyFailureMode(\n policy,\n workflowId,\n runnable.version,\n runId,\n result.error,\n );\n }\n const finished = { ...result, runId };\n if (!ctx) return finished;\n // Handed back only as `run` would serve it, so a step's output never\n // reaches a caller the journal would withhold it from.\n const ids = [...triggerDocumentIds(triggerPayload), ...handed];\n return (await this.servesDocuments(ids, ctx))\n ? finished\n : { status: finished.status, steps: [], runId };\n } catch (error) {\n if (store && runId) {\n const message = error instanceof Error ? error.message : String(error);\n const closed = await store.failRun(runId, message, errorNameOf(error));\n this.answerClosed(closed, runId, { status: \"FAILED\", error: message });\n }\n throw error;\n } finally {\n // The run owns the child, however it ended: closing kills it and hands\n // the slot to whichever run is waiting.\n session?.close();\n // And the concurrency slot, so the next QUEUE'd firing starts.\n admission.release();\n dispatched();\n }\n }\n\n // One leg of a run, from start or resume until it ends (closing its\n // waitpoints) or waits (leaving the run WAITING with its pin).\n private async executeLeg(leg: {\n workflowId: string;\n runId: string | null;\n store: WorkflowRunStore | undefined;\n session: PieceWorkerSession;\n definition: ReturnType<typeof toWorkflowDefinition>;\n runnable: ReturnType<typeof runnableDefinition>;\n policy: EffectiveRunPolicy;\n deadline: number | undefined;\n connections: ReadonlySet<string>;\n runUser: RunUser | null | undefined;\n triggerPayload: unknown;\n executor: BlockExecutor;\n completedSteps?: Map<string, ReplayedStep>;\n loopItems?: Map<string, unknown[]>;\n carriedSteps?: Map<string, CarriedStep>;\n resume?: { stepId: string; payload: unknown };\n firstOrdinal?: number;\n // Journaled outputs this leg treats as written by the run.\n replayed?: unknown;\n written?: ReadonlySet<string>;\n // Documents earlier legs were handed.\n handed?: Iterable<string>;\n // The definition a WAITING leg pins; absent when it is pinned already.\n pin?: () => RunPinRow;\n // Answers the sync request that resumed this leg; a first leg answers\n // the webhook delivery held for its run.\n respond?: (response: RunResponse) => void;\n }): Promise<{ result: WorkflowRunResult; handed: Set<string> }> {\n const { workflowId, runId, store, policy } = leg;\n let journalFailed = false;\n // Recorded whether or not the write lands: it is what lets finishRun put a\n // lost row back where the step ran.\n const executionOrder = new Map<string, number>();\n // Resolved per leg, so a rotated secret takes effect on the next one.\n const { variables, secretValues } = await resolveVariables(\n leg.runnable.variables,\n this.secretProvider(),\n workflowId,\n );\n const handed = new Set<string>(leg.handed);\n const attachments = attachmentOrigins(\n leg.triggerPayload,\n handed,\n leg.replayed,\n );\n for (const ref of leg.written ?? []) attachments.written.add(ref);\n // Created only when a step asks; a run that never pauses writes nothing.\n const waitpoints =\n store && runId\n ? this.waitpointPort(\n store,\n workflowId,\n runId,\n maxSuspensionMs(leg.runnable),\n )\n : undefined;\n const respond =\n leg.respond ??\n (runId && !leg.resume\n ? (response: RunResponse) => this.runResponders.get(runId)?.(response)\n : undefined);\n let result = await withRunScope(\n {\n workflowId,\n runId,\n connections: leg.connections,\n pieceWorker: leg.session,\n ...(leg.runUser !== undefined ? { runUser: leg.runUser } : {}),\n attachments,\n recordDocuments: async (documentIds: string[]) => {\n for (const documentId of documentIds) handed.add(documentId);\n if (store && runId) {\n await store.recordRunDocuments(runId, documentIds);\n }\n },\n ...(waitpoints ? { waitpoints: waitpoints.port } : {}),\n flows: this.flowsPort(workflowId, runId),\n },\n () =>\n runWorkflow({\n definition: { ...leg.definition, variables },\n executor: leg.executor,\n declaredPorts: blockPorts,\n blockDefaults: (block) => this.blockDefaults(block),\n ...(secretValues.length > 0 ? { redactValues: secretValues } : {}),\n triggerPayload: leg.triggerPayload,\n completedSteps: leg.completedSteps,\n ...(leg.loopItems ? { loopItems: leg.loopItems } : {}),\n ...(leg.carriedSteps ? { carriedSteps: leg.carriedSteps } : {}),\n ...(leg.resume ? { resume: leg.resume } : {}),\n ...(leg.firstOrdinal !== undefined\n ? { firstOrdinal: leg.firstOrdinal }\n : {}),\n ...(respond ? { onRespond: respond } : {}),\n // `policy.defaultRetry` and `policy.runTimeoutSeconds`, enforced.\n ...(policy.defaultRetry ? { defaultRetry: policy.defaultRetry } : {}),\n ...(leg.deadline !== undefined ? { deadline: leg.deadline } : {}),\n // Journal each step as it lands, so a reactor that dies mid-run\n // still leaves a rerunnable record of the work it finished.\n onStep:\n store && runId\n ? async (record, ordinal) => {\n if (!record.path) executionOrder.set(record.stepId, ordinal);\n try {\n await this.telemetry.phase(\"journal.step\", {}, () =>\n store.recordStep(runId, ordinal, record),\n );\n } catch (error) {\n // Swallowed on purpose, but logged once per run: a dead\n // journal must not look exactly like a healthy one.\n if (journalFailed) return;\n journalFailed = true;\n this.logger.warn(\n `Run ${runId}: journaling step \"@step\" failed; the run continues without per-step durability: @error`,\n record.key,\n error,\n );\n }\n }\n : undefined,\n }),\n );\n if (store && runId) {\n let waiting = result.status === WAITING_RUN_STATUS;\n try {\n const { held, closed } = await this.journalFinish(\n store,\n runId,\n result,\n executionOrder,\n waiting ? leg.pin?.() : undefined,\n );\n this.answerClosed(closed, runId, {\n status: waiting ? CANCELLED_RUN_STATUS : result.status,\n error: waiting\n ? \"The step that created this waitpoint no longer waits on it\"\n : (result.error ?? \"The run ended without resuming on it\"),\n });\n if (!held) {\n result = await this.endUnheldWait(store, runId, result);\n waiting = false;\n }\n } catch (error) {\n // The run is over and its result is the caller's; a journal that\n // cannot say so must not turn a finished run into a failed one.\n this.logger.warn(\n `Run ${runId}: closing the run journal out failed; the run's outcome stands`,\n error,\n );\n }\n if (waiting) {\n // Pausing answers the held request with the waitpoint's responseToSend.\n const toSend =\n result.waiting && waitpoints?.responseFor(result.waiting.waitpointId);\n if (toSend) respond?.(toSend);\n // A resume that arrived before WAITING was written is delivered now.\n await this.deliverHeld(runId);\n }\n }\n return { result, handed };\n }\n\n // Its own method so that no closure of executeLeg, the run scope's among\n // them, shares a context with the run's result: anything that keeps the\n // scope's async context alive would keep every step's output with it.\n private journalFinish(\n store: WorkflowRunStore,\n runId: string,\n result: WorkflowRunResult,\n executionOrder: ReadonlyMap<string, number>,\n pin: RunPinRow | undefined,\n ) {\n return this.telemetry.phase(\"journal.finish\", {}, () =>\n store.finishRun(runId, result, executionOrder, pin),\n );\n }\n\n // A leg that waited without a live waitpoint of its step: ended as expiry\n // ends a run when the waitpoint expired meanwhile, else FAILED.\n private async endUnheldWait(\n store: WorkflowRunStore,\n runId: string,\n result: WorkflowRunResult,\n ): Promise<WorkflowRunResult> {\n const on = result.waiting;\n const step = result.steps.find((record) => record.stepId === on?.stepId);\n const row = on ? await store.getWaitpoint(on.waitpointId) : undefined;\n const ours = row?.run_id === runId && row.step_id === on?.stepId;\n const end =\n ours && row.status === \"EXPIRED\"\n ? {\n status: \"CANCELLED\" as const,\n reason:\n `The wait at step \"${row.step_key}\" expired at ` +\n `${row.expires_at} before the run could wait on it`,\n errorName: WAITPOINT_EXPIRED_ERROR_NAME,\n }\n : {\n status: \"FAILED\" as const,\n reason:\n `Step \"${step?.key ?? on?.stepId}\" waited on waitpoint ` +\n `\"${on?.waitpointId}\", which is not a live waitpoint it created`,\n errorName: WAITPOINT_NOT_LIVE_ERROR_NAME,\n };\n const closed = await store.endWait(runId, {\n ...end,\n waitpoints: \"EXPIRED\",\n });\n this.answerClosed(closed, runId, { status: end.status, error: end.reason });\n return {\n status: end.status,\n error: end.reason,\n errorName: end.errorName,\n steps: result.steps.map((record) =>\n record === step\n ? {\n ...record,\n status: \"FAILED\",\n error: end.reason,\n errorName: end.errorName,\n }\n : record,\n ),\n };\n }\n\n // Firings of one workflow at a time; see run-gate.ts.\n private readonly runGate = new WorkflowRunGate();\n // Firings of each workflow not yet settled, from the moment they reach the\n // runtime (before the gate) until their run ends, and each workflow's slot\n // count as its last firing read it: together they hold a poll that could\n // only hand out work to queue (pollHeld).\n private readonly unsettledFirings = new Map<string, number>();\n private readonly runLimits = new Map<string, number | null>();\n\n /**\n * Whether a due poll of this workflow's trigger should wait: its runs are\n * serialised (QUEUE, SINGLETON, a bounded PARALLEL) and every slot is taken\n * by a firing that has not settled. A polling trigger that hands out work\n * advances its own position when polled (the backfill's for-every moves its\n * cursor), so a poll now would only add a firing that waits in the queue,\n * where it can expire past `runTimeoutSeconds` or be skipped by a park,\n * with the position already gone. The supervisor leaves the poll due and\n * looks again on its next tick.\n */\n private pollHeld(workflowId: string): boolean {\n const limit = this.runLimits.get(workflowId);\n if (limit === undefined || limit === null) return false;\n return (this.unsettledFirings.get(workflowId) ?? 0) >= limit;\n }\n\n private settleFiring(workflowId: string): void {\n const left = (this.unsettledFirings.get(workflowId) ?? 1) - 1;\n if (left > 0) this.unsettledFirings.set(workflowId, left);\n else this.unsettledFirings.delete(workflowId);\n }\n // Sync deliveries still holding the sender's socket, by run. Taking one\n // commits the delivery to a 503, before a 504 can.\n private readonly heldReplies = new Map<string, () => boolean>();\n // Sync deliveries a step's `run.respond` / `run.stop` may answer, by run.\n private readonly runResponders = new Map<\n string,\n (response: RunResponse) => void\n >();\n // Sync deliveries a cancel of their queued run answers, by run.\n private readonly queuedReplies = new Map<\n string,\n (result: PersistedRunResult) => void\n >();\n // `/sync` resume requests held for the leg their waitpoint resumes. Each\n // learns whether it won the waitpoint; only the winner is answered.\n private readonly syncResumes = new Map<string, Set<SyncResumeCandidate>>();\n\n /** Why a trigger's firing of a PARKED workflow is refused; undefined when\n * it is not parked, or when an operator started the run. */\n private async parkedFiring(\n workflowId: string,\n triggerKind: string,\n publishedVersion: number,\n ): Promise<string | undefined> {\n if (OPERATOR_RUN_KINDS.has(triggerKind)) return undefined;\n const park = await this.parks.get(workflowId);\n if (!park || park.published_version < publishedVersion) return undefined;\n return `Skipped: this workflow is PARKED (${park.reason})`;\n }\n\n /** Why a firing that waited for its slot may no longer run, if it may not. */\n private async staleAfterWait(\n workflowId: string,\n triggerKind: string,\n publishedVersion: number,\n readGeneration: number,\n ): Promise<string | undefined> {\n if (this.workflowGeneration(workflowId) === readGeneration) {\n return this.parkedFiring(workflowId, triggerKind, publishedVersion);\n }\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n const state = document.state.global;\n if (state.status !== \"ENABLED\") {\n return `Skipped: the workflow became ${state.status} while this firing waited for its slot`;\n }\n if (runnableDefinition(state).version !== publishedVersion) {\n return \"Skipped: the workflow was re-published while this firing waited for its slot\";\n }\n return this.parkedFiring(workflowId, triggerKind, publishedVersion);\n }\n\n /** Whether the workflow is still ENABLED at this published version. An\n * unreadable document counts as unchanged, so a failure still parks. */\n private async stillRunsVersion(\n workflowId: string,\n publishedVersion: number,\n ): Promise<boolean> {\n let state: WorkflowState;\n try {\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n state = document.state.global;\n } catch (error) {\n this.logger.warn(\n `Could not re-read workflow ${workflowId} before parking it: @error`,\n error,\n );\n return true;\n }\n return (\n state.status === \"ENABLED\" &&\n runnableDefinition(state).version === publishedVersion\n );\n }\n\n /** A park recorded against an earlier published version than this state's. */\n private async outdatedPark(\n workflowId: string,\n state: WorkflowState,\n ): Promise<boolean> {\n if (state.status !== \"ENABLED\") return false;\n const park = await this.parks.get(workflowId);\n return (\n park !== undefined &&\n runnableDefinition(state).version > park.published_version\n );\n }\n\n /**\n * A firing SINGLETON refused.\n *\n * Journaled as a CANCELLED run rather than dropped: a firing that vanished\n * is indistinguishable from a trigger that never fired, which is the class\n * of bug this work package exists to stamp out. An already-enqueued row is\n * closed out in place, so nothing is left PENDING for a sweep to find.\n */\n // An adopted row is durable, so a refused firing closes it out: left\n // PENDING, the next owner reads its dedupe claim as handled and never runs it.\n private async refuseClosed(\n store: WorkflowRunStore | undefined,\n workflowId: string,\n enqueuedRunId: string | undefined,\n triggerKind: string,\n ): Promise<never> {\n const error = new WorkflowRuntimeClosedError(workflowId);\n if (enqueuedRunId) {\n // Answered 503, the sender's retry is the record: not left to rerun.\n const redelivered = this.heldReplies.get(enqueuedRunId)?.() ?? false;\n // A trigger's source has moved past it: the next owner starts it. A\n // manual caller hears the refusal now, so that run stays failed.\n if (!redelivered && triggerKind !== \"manual\") {\n try {\n await store?.releaseAdmission(enqueuedRunId);\n } catch (failure) {\n this.logger.warn(\n `Could not give back the boot admission of run ${enqueuedRunId}: @error`,\n failure,\n );\n }\n throw error;\n }\n try {\n if (redelivered) {\n await store?.cancelRun(enqueuedRunId, WEBHOOK_REDELIVERED_REASON);\n } else {\n await store?.failRun(\n enqueuedRunId,\n error.message,\n errorNameOf(error),\n );\n }\n } catch (failure) {\n this.logger.warn(\n `Could not close out run ${enqueuedRunId} after shutdown: @error`,\n failure,\n );\n }\n }\n throw error;\n }\n\n private async skipFiring(\n store: WorkflowRunStore | undefined,\n workflowId: string,\n enqueuedRunId: string | undefined,\n details: {\n reason: string;\n triggerKind: string;\n triggerPayload?: unknown;\n workflowName: string;\n workflowVersion: number;\n },\n refusal: FiringRefusal,\n ): Promise<PersistedRunResult> {\n this.logger.info(`Workflow ${workflowId}: ${details.reason}`);\n let runId = enqueuedRunId ?? null;\n if (store) {\n try {\n let adopted = true;\n if (runId) {\n // The row is already durable, with its trigger payload; adopt and\n // close it rather than leaving a PENDING run for a sweep to find.\n adopted = await store.beginRun(runId, details);\n } else {\n runId = await store.startRun({ workflowId, ...details });\n }\n if (adopted) {\n await store.cancelRun(runId, details.reason);\n } else {\n // An operator closed it out while it queued: its own end is the answer.\n const row = await store.getRun(runId);\n if (row) {\n return {\n status: row.status as PersistedRunResult[\"status\"],\n steps: [],\n runId,\n ...(row.error ? { error: row.error } : {}),\n refusal:\n row.status === CANCELLED_RUN_STATUS ? \"cancelled\" : refusal,\n };\n }\n }\n } catch (error) {\n this.logger.warn(\n `Could not journal the skipped firing of workflow ${workflowId}: @error`,\n error,\n );\n }\n }\n return { status: CANCELLED_RUN_STATUS, steps: [], runId, refusal };\n }\n\n /**\n * `policy.onFailure` for a run that failed terminally.\n *\n * PARK is the document model's own default, so this is where enforcing the\n * knob becomes visible: a terminal failure parks the workflow, whatever its\n * trigger kind, and nothing fires it until it is re-published or\n * re-enabled. That is what PARK means, and\n * leaving a broken workflow firing every minute is what it meant before.\n *\n * NOTIFY logs at error level, which is the only notification channel this\n * engine has; it is marked as such rather than pretending to page anyone.\n */\n private async applyFailureMode(\n policy: EffectiveRunPolicy,\n workflowId: string,\n publishedVersion: number,\n runId: string | null,\n error: string | undefined,\n ): Promise<void> {\n // A run that failed as the runtime shut down says nothing about the\n // workflow, and a park now would land in the next owner's journal.\n if (policy.onFailure === \"IGNORE\" || this.closed) return;\n const detail = error ?? \"the run failed\";\n if (policy.onFailure === \"NOTIFY\") {\n this.logger.error(\n `Workflow ${workflowId} run ${runId ?? \"(unjournaled)\"} failed and ` +\n `its policy is NOTIFY: @error`,\n detail,\n );\n return;\n }\n const store = await this.store();\n if (!store) return;\n const reason = `Parked after a failed run (policy.onFailure = PARK): ${detail}`;\n try {\n // The run may have outlived its version: a disable or re-publish that\n // landed meanwhile is not the state that failed.\n if (!(await this.stillRunsVersion(workflowId, publishedVersion))) return;\n if (this.closed) return;\n // The park row covers every trigger kind; the trigger_state row is what\n // stops the supervisor polling a schedule or piece trigger.\n const trigger = await this.supervisor().park(\n workflowId,\n publishedVersion,\n reason,\n );\n // Checked again after the write, so a change racing the park wins: one\n // that landed before this read is undone here, one after it clears the\n // park in its own registration.\n if (!(await this.stillRunsVersion(workflowId, publishedVersion))) {\n // A registration of the change arms on its own: a park never blocks\n // a version newer than the one that failed.\n await this.supervisor().liftPark(workflowId, publishedVersion, trigger);\n return;\n }\n // In registration order, and only while this park stands: a registration\n // of a newer version that already ran must keep its entry.\n const stands = await this.inRegistrationOrder(workflowId, async () => {\n const park = await this.parks.get(workflowId);\n const current = park?.published_version === publishedVersion;\n const registered = this.registry.get(workflowId);\n if (current && registered && !SUPERVISED_KINDS.has(registered.kind)) {\n this.registry.delete(workflowId);\n }\n return current;\n });\n if (!stands) return;\n this.logger.error(\n `Workflow ${workflowId} is PARKED after run ${runId ?? \"(unjournaled)\"} ` +\n \"failed; its trigger will not fire again until the workflow is \" +\n \"re-published or re-enabled\",\n );\n } catch (parkError) {\n this.logger.warn(\n `Applying onFailure = PARK to workflow ${workflowId} after a failed run failed; whether it is parked is unknown: @error`,\n parkError,\n );\n }\n }\n\n // Resume a FAILED run: journaled step outputs replay, execution restarts\n // at the first step that didn't succeed. Runs the current runnable definition.\n async rerun(\n runId: string,\n ctx?: WorkflowCaller,\n ): Promise<PersistedRunResult> {\n const store = await this.store();\n if (!store) throw new Error(\"Run journal is unavailable\");\n const run = await store.getRun(runId);\n if (!run) throw new Error(`Run \"${runId}\" not found`);\n // A replay is the workflow's own side effects again, so it is the\n // workflow — not the run id — that the caller has to be allowed to touch.\n await this.assertCanReadDocument(run.workflow_id, ctx);\n if (!ctx || (await this.servedRuns([run], ctx)).length === 0) {\n throw new Error(`Run \"${runId}\" not found`);\n }\n // A test ran one block on sample data; replaying it as a run would fire\n // the whole published workflow, side effects included\n if (run.trigger_kind === \"test\") {\n throw new Error(\n `Run \"${runId}\" tested a single step or trigger; test it again instead of rerunning it`,\n );\n }\n // A run its deadline cancelled resumes too; a refused firing never ran.\n const deadlineCancelled =\n run.status === CANCELLED_RUN_STATUS &&\n run.error_name === RUN_DEADLINE_ERROR_NAME;\n if (run.status !== \"FAILED\" && !deadlineCancelled) {\n throw new Error(\n `Only FAILED runs, and runs their deadline cancelled, can be rerun; run is ${run.status}`,\n );\n }\n const triggerPayload =\n run.trigger_payload === null\n ? undefined\n : (JSON.parse(run.trigger_payload) as unknown);\n // The journal capped an oversized payload to a marker (store.ts,\n // STEP_PAYLOAD_MAX_BYTES); replaying it would hand the marker to the\n // workflow as trigger data. Refuse before anything runs.\n if (isTruncatedStepPayload(triggerPayload)) {\n throw new Error(\n `Trigger payload of run \"${runId}\" was truncated by the journal and ` +\n \"cannot be replayed; fire the workflow again instead of rerunning it\",\n );\n }\n // The journal holds a redacted copy of the payload, so replaying it would\n // hand a marker to whatever the trigger fed. Refuse before anything runs.\n if (containsRedactedMarker(triggerPayload)) {\n throw new Error(\n `Trigger payload of run \"${runId}\" was redacted and cannot be ` +\n \"replayed; fire the workflow again instead of rerunning it\",\n );\n }\n const document = await this.host.reactorClient.get<WorkflowDocument>(\n run.workflow_id,\n );\n const runnable = runnableDefinition(document.state.global);\n const currentSteps = new Map(\n runnable.steps.map((step) => [step.id, stepDefinition(step)]),\n );\n const current = {\n steps: [...currentSteps.values()],\n edges: runnable.edges,\n };\n const structure = loopStructure(current);\n const hashes = new Map<string, string>();\n const hashNow = (step: ReturnType<typeof stepDefinition>) => {\n let hash = hashes.get(step.id);\n if (hash === undefined) {\n hash = isLoopStep(step)\n ? loopConfigHash(step, current, structure)\n : stepConfigHash(step);\n hashes.set(step.id, hash);\n }\n return hash;\n };\n const readers = new Map<string, Promise<boolean>>();\n const rereads = (step: ReturnType<typeof stepDefinition>) => {\n let reads = readers.get(step.id);\n if (!reads) readers.set(step.id, (reads = this.rereads(step)));\n return reads;\n };\n // Reuse an output only while the step is the step that produced it: same\n // key, and the same definition hash (block type, config, connection, schemas;\n // a loop's body shape too). Keyed by path: loop iterations replay one by one.\n const completedSteps = new Map<string, ReplayedStep>();\n const loopItemsByPath = new Map<string, unknown[]>();\n const rows = await store.getSteps(runId, { withIterations: true });\n for (const row of rows) {\n const step = currentSteps.get(row.step_id);\n if (\n !step ||\n step.key !== row.step_key ||\n row.config_hash === null ||\n hashNow(step) !== row.config_hash\n ) {\n continue;\n }\n // A loop runs again; its items tell which iterations can replay.\n if (isLoopStep(step)) {\n const input =\n row.input === null ? undefined : (JSON.parse(row.input) as unknown);\n if (input === undefined || isTruncatedStepPayload(input)) continue;\n try {\n loopItemsByPath.set(row.step_path, loopItems(input));\n } catch {\n // Items that were never a list ran no iteration.\n }\n continue;\n }\n if (row.status !== \"SUCCEEDED\" && row.status !== \"REPLAYED\") continue;\n const output =\n row.output === null ? undefined : (JSON.parse(row.output) as unknown);\n // The journal capped this output to a marker (store.ts,\n // STEP_PAYLOAD_MAX_BYTES). The step still counts as COMPLETED: it\n // succeeded, it had side effects, and re-running it would do them again\n // — which is exactly what dropping it from this map used to mean\n // (backlog item 15). Its output is unavailable instead, and a\n // downstream step that reads it fails the rerun by name. A declared\n // read has no side effect to repeat, so it re-runs instead.\n if (isTruncatedStepPayload(output)) {\n if (await rereads(step)) continue;\n completedSteps.set(row.step_path, {\n port: row.port,\n outputTruncated: true,\n // Carried so this rerun's REPLAYED row journals the marker again. A\n // NULL there would read as an ordinary replay on the NEXT rerun, and\n // the truncation fact would be gone after one generation.\n truncatedOutput: output,\n });\n continue;\n }\n // Reads re-read the documents they referenced; a succeeded write is never\n // repeated. An INDETERMINATE step is not in this map, so it runs again.\n if (containsDocumentRef(output) && (await rereads(step))) {\n continue;\n }\n completedSteps.set(row.step_path, { output, port: row.port });\n }\n return this.fire(\n run.workflow_id,\n triggerPayload,\n \"rerun\",\n { completedSteps, loopItems: loopItemsByPath, rerunOf: runId },\n ctx,\n );\n }\n\n // Whether a rerun executes this step again rather than reuse its output.\n private async rereads(\n step: ReturnType<typeof stepDefinition>,\n ): Promise<boolean> {\n const parsed = resolvedBlock(await this.resolveBlock(stepBlock(step)));\n return parsed ? (await this.declaredReactor(parsed)) === \"read\" : false;\n }\n\n // ── sub-flows ─────────────────────────────────────────────────────────────\n\n // ctx.flows and ctx.server for a run, a trigger hook or a step test.\n private flowsPort(workflowId: string, runId: string | null): FlowsPort {\n const base = this.resumeBaseUrl();\n return {\n list: (params) => this.listFlows(workflowId, params.externalIds),\n request: (request) => this.hostRequest(workflowId, runId, request),\n ...(base ? { publicUrl: new URL(base).origin } : {}),\n };\n }\n\n private resumeBaseUrl(): string | undefined {\n const configured = this.host.waitpointBaseUrl?.replace(/\\/+$/, \"\");\n return configured && URL.canParse(configured) ? configured : undefined;\n }\n\n // The drives a workflow is in: the project a callable flow is offered within.\n private async drivesOf(workflowId: string): Promise<string[]> {\n try {\n const parents = await this.host.reactorClient.getIncomingRelationships(\n workflowId,\n CHILD_RELATIONSHIP,\n );\n return parents.results\n .filter((parent) => parent.header.documentType === DRIVE_DOCUMENT_TYPE)\n .map((parent) => parent.header.id);\n } catch (error) {\n this.logger.debug(\n \"Could not read the drives of workflow @workflow: @error\",\n workflowId,\n error,\n );\n return [];\n }\n }\n\n // The workflows of the drives this one is in, itself included.\n private async callableWorkflowIds(workflowId: string): Promise<string[]> {\n const ids = new Set([workflowId]);\n for (const driveId of await this.drivesOf(workflowId)) {\n for (const id of await this.workflowNodeIds(driveId)) ids.add(id);\n }\n return [...ids];\n }\n\n // A Callable Flow workflow the reader reads, as Activepieces lists it.\n private async callableFlow(\n id: string,\n reads: (documentId: string) => Promise<boolean>,\n ): Promise<PopulatedFlow | undefined> {\n try {\n const document = await this.host.reactorClient.get<WorkflowDocument>(id);\n if (document.header.documentType !== WORKFLOW_DOCUMENT_TYPE) {\n return undefined;\n }\n const trigger = runnableDefinition(document.state.global).trigger;\n if (!trigger || !isCallableFlow(trigger) || !(await reads(id))) {\n return undefined;\n }\n return populatedFlow(id, document.state.global, document.header.name);\n } catch {\n return undefined;\n }\n }\n\n /** `ctx.flows.list`, as Activepieces' PopulatedFlow records: the Callable\n * Flow workflows the caller (else the calling workflow's run user) reads. */\n async listFlows(\n workflowId: string,\n externalIds?: string[],\n ctx?: WorkflowCaller,\n ): Promise<{ data: PopulatedFlow[] }> {\n const ids = (await this.callableWorkflowIds(workflowId)).filter(\n (id) => !externalIds || externalIds.includes(id),\n );\n const reads = await this.flowReader(workflowId, ctx);\n const flows = await Promise.all(\n ids.map((id) => this.callableFlow(id, reads)),\n );\n return { data: flows.filter((flow) => flow !== undefined) };\n }\n\n // Who lists flows: a design-time caller, else the calling workflow's run user.\n private async flowReader(\n workflowId: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<(documentId: string) => Promise<boolean>> {\n if (ctx) return (id) => this.canReadDocument(id, ctx);\n const runUser =\n currentRunUser() ??\n (await publishRunUser(\n this.host.reactorClient,\n workflowId,\n this.host.hostIdentity,\n ).catch(() => null));\n if (!runUser) {\n const open = !authEnforced(this.host);\n return () => Promise.resolve(open);\n }\n return (id) =>\n this.host.reactorClient\n .isServed(id, { subject: runUser.subject })\n .catch(() => false);\n }\n\n // A piece's fetch to ctx.server.apiUrl, answered in process.\n private async hostRequest(\n workflowId: string,\n runId: string | null,\n request: HostHttpRequest,\n ): Promise<HostHttpResponse> {\n const route = hostRoute(request);\n if (!route) {\n return jsonReply(404, {\n message: `Nothing is served at ${request.method} ${request.path}`,\n });\n }\n const body = hostBody(request);\n if (route.kind === \"callback\") {\n const { status } = await this.resumeByToken(route.token, {\n body,\n headers: request.headers,\n queryParams: {},\n });\n // As upstream: a response nothing was waiting for is discarded, and the\n // callee's Return Response fails on it.\n return jsonReply(200, { status, discarded: status === \"gone\" });\n }\n return this.dispatchSubflow(\n workflowId,\n runId,\n route.workflowId,\n request.headers,\n body,\n );\n }\n\n // listFlows' rules for one target: itself, or a workflow sharing a drive.\n private async flowCallableFrom(\n callerId: string,\n targetId: string,\n ): Promise<PopulatedFlow | undefined> {\n if (targetId !== callerId) {\n const [callerDrives, targetDrives] = await Promise.all([\n this.drivesOf(callerId),\n this.drivesOf(targetId),\n ]);\n if (!targetDrives.some((drive) => callerDrives.includes(drive))) {\n return undefined;\n }\n }\n return this.callableFlow(\n targetId,\n await this.flowReader(callerId, undefined),\n );\n }\n\n // Call Flow: a run of a callable workflow in the caller's drive, linked to\n // the caller's run so a failure can fail the caller.\n private async dispatchSubflow(\n callerId: string,\n runId: string | null,\n targetId: string,\n headers: Record<string, string>,\n body: unknown,\n ): Promise<HostHttpResponse> {\n const flow = await this.flowCallableFrom(callerId, targetId);\n if (!flow) {\n return jsonReply(404, {\n message: `No workflow \"${targetId}\" is callable from workflow \"${callerId}\"`,\n });\n }\n const registration = this.registry.get(targetId);\n const binding =\n registration?.kind === PIECE_WEBHOOK_KIND\n ? registration.binding\n : undefined;\n if (!binding || !isCallableFlow(binding)) {\n return jsonReply(409, {\n message: `Workflow \"${flow.version.displayName}\" is not enabled with a Callable Flow trigger`,\n });\n }\n const claimed = headers[PARENT_RUN_HEADER];\n if (runId && claimed && claimed !== runId) {\n return jsonReply(403, {\n message: `Run \"${runId}\" cannot call on behalf of run \"${claimed}\"`,\n });\n }\n const request = (\n body && typeof body === \"object\" ? body : { data: body }\n ) as { data?: unknown; callbackUrl?: unknown };\n const callback =\n typeof request.callbackUrl === \"string\"\n ? localCallback(request.callbackUrl, this.resumeBaseUrl())\n : undefined;\n let waitpointId: string | null = null;\n if (runId && callback && headers[FAIL_PARENT_HEADER] === \"true\") {\n const store = await this.store();\n const waitpoint = await store?.getWaitpointByTokenHash(\n tokenHash(callback.token),\n );\n if (waitpoint?.run_id === runId) waitpointId = waitpoint.id;\n }\n const payload = {\n method: \"POST\",\n path: `/v1/webhooks/${targetId}`,\n headers,\n queryParams: {},\n body: {\n data: request.data ?? null,\n ...(request.callbackUrl !== undefined\n ? { callbackUrl: callback?.url ?? request.callbackUrl }\n : {}),\n },\n };\n try {\n const runIds = await this.supervisor().deliverWebhook(\n targetId,\n payload,\n runId ? { runId, waitpointId } : undefined,\n );\n return jsonReply(200, { runId: runIds.at(0) ?? null });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return jsonReply(500, { message });\n }\n }\n\n // The piece trigger's onStart, once per run before its first step.\n private async startPieceTrigger(\n workflowId: string,\n runId: string,\n payload: unknown,\n ): Promise<void> {\n const registration = this.registry.get(workflowId);\n const binding =\n registration?.kind === PIECE_WEBHOOK_KIND\n ? registration.binding\n : registration?.kind === \"piece\"\n ? this.supervisor().pieceBinding(workflowId)\n : undefined;\n if (!binding) return;\n const descriptor = await this.pieceDescriptor(bindingTarget(binding));\n const trigger = descriptor.triggers.find(\n (entry) => entry.name === binding.triggerName,\n );\n if (!trigger?.onStart) return;\n await this.supervisor().onStart(binding, runId, payload);\n }\n\n // An ended called run drops its callback key. One that did not succeed\n // resolves its caller's waitpoint as an error, failing the caller's Call Flow.\n private async endSubflow(runId: string): Promise<void> {\n try {\n const store = await this.store();\n if (!store) return;\n const parent = await store.getRunParent(runId);\n if (!parent) return;\n const run = await store.getRun(runId);\n if (!run) return;\n const failed = FAILED_SUBFLOW_STATUSES.has(run.status);\n if (!failed && run.status !== \"SUCCEEDED\") return;\n await store.deletePieceStoreValue(\n \"FLOW\",\n run.workflow_id,\n `${CALLABLE_FLOW_KEY_PREFIX}${runId}`,\n );\n if (!parent.waitpointId || !failed) return;\n const completed = await store.completeWaitpoint(parent.waitpointId, {\n payload: {\n body: {\n status: \"error\",\n data: {\n message:\n run.error ?? `The called workflow's run ended ${run.status}`,\n runId,\n },\n },\n headers: {},\n queryParams: {},\n },\n });\n if (completed) await this.deliverHeld(completed.run_id);\n } catch (error) {\n this.logger.warn(\n \"Could not fail the caller of run @run: @error\",\n runId,\n error,\n );\n }\n }\n\n // ── suspend and resume ────────────────────────────────────────────────────\n\n // Runs WAITING for a resume claim's admission, before the claim lands.\n private readonly resuming = new Set<string>();\n // Our hash of a published definition, by workflow and version.\n private readonly definitionHashes = new Map<string, string>();\n\n /** Our hash of the runnable definition: computed once per published version. */\n private definitionHash(workflowId: string, state: WorkflowState): string {\n const runnable = runnableDefinition(state);\n // A draft has no version that pins it, so it is hashed each time.\n if (!runnable.published) return hashOf(canonicalJson(runnable));\n const key = `${workflowId}@${runnable.version}`;\n let hash = this.definitionHashes.get(key);\n if (hash === undefined) {\n hash = hashOf(canonicalJson(runnable));\n if (this.definitionHashes.size >= WORKFLOW_CACHE_MAX) {\n this.definitionHashes.clear();\n }\n this.definitionHashes.set(key, hash);\n }\n return hash;\n }\n\n // One run's waitpoints, as its steps create them.\n private waitpointPort(\n store: WorkflowRunStore,\n workflowId: string,\n runId: string,\n suspendMs: number | null,\n ): {\n port: WaitpointPort;\n responseFor: (waitpointId: string) => RunResponse | undefined;\n } {\n // responseToSend by waitpoint, answered when the run waits on it.\n const responses = new Map<string, RunResponse>();\n // The resume URL by waitpoint: the store keeps only its token's hash.\n const urls = new Map<string, string>();\n const resumeBaseUrl = this.resumeBaseUrl();\n const port: WaitpointPort = {\n ...(resumeBaseUrl ? { resumeBaseUrl } : {}),\n create: async (request) => {\n // Call Flow's callback is only ever posted in process.\n const baseUrl =\n request.pieceName === SUBFLOWS_PIECE &&\n request.blockName === CALL_FLOW_ACTION\n ? HOST_WAITPOINTS_URL\n : resumeBaseUrl;\n if (!baseUrl && request.type === \"WEBHOOK\" && !request.approval) {\n throw new Error(\n \"This host serves no resume URLs: resume URLs need an HTTP host\",\n );\n }\n const createdAt = new Date();\n const resumeAt = request.resumeDateTime\n ? new Date(Date.parse(request.resumeDateTime)).toISOString()\n : null;\n if (resumeAt && Date.parse(resumeAt) > MAX_WAITPOINT_MS) {\n throw new Error(\n `A delay until ${resumeAt} is past ${MAX_WAITPOINT_ISO}, the latest a run can wait until`,\n );\n }\n const expiresAt = waitpointExpiry(createdAt, request, suspendMs);\n if (request.type === \"DELAY\" && resumeAt && suspendMs !== null) {\n if (Date.parse(resumeAt) - createdAt.getTime() > suspendMs) {\n throw new Error(\n `A delay until ${resumeAt} is longer than the workflow's maxSuspensionDays allows`,\n );\n }\n }\n // Approvals are decided in the editor and delays come due, so neither\n // gets a token. A deprecated generateResumeUrl minted its own already.\n const token =\n baseUrl && !request.approval && request.type !== \"DELAY\"\n ? (request.token ?? randomBytes(32).toString(\"base64url\"))\n : null;\n const id = randomUUID();\n const { waitpoint, created: inserted } = await store.createWaitpoint({\n id,\n run_id: runId,\n workflow_id: workflowId,\n step_id: request.stepId,\n step_key: request.stepKey,\n step_path: request.stepId,\n piece_name: request.pieceName,\n block_name: request.blockName,\n type: request.type,\n kind: request.approval\n ? \"approval\"\n : request.type === \"DELAY\"\n ? \"delay\"\n : \"webhook\",\n status: \"PENDING\",\n token_hash: token ? tokenHash(token) : null,\n created_at: createdAt.toISOString(),\n resume_at: resumeAt,\n expires_at: request.type === \"DELAY\" ? null : expiresAt,\n resolved_at: null,\n decided_by: null,\n approval: request.approval ? JSON.stringify(request.approval) : null,\n resume_payload: null,\n response_to_send: request.responseToSend\n ? JSON.stringify(request.responseToSend)\n : null,\n });\n if (!inserted) {\n // The step's live waitpoint, with the URL this leg minted for it.\n const known = urls.get(waitpoint.id);\n if (waitpoint.token_hash !== null && known === undefined) {\n throw new Error(\n `Step \"${request.stepKey}\" has a waitpoint from an earlier leg, whose resume URL cannot be issued again`,\n );\n }\n return { id: waitpoint.id, resumeUrl: known ?? \"\" };\n }\n const resumeUrl = token ? `${baseUrl}/${token}` : \"\";\n if (token) urls.set(id, resumeUrl);\n if (request.responseToSend) responses.set(id, request.responseToSend);\n const due = request.type === \"DELAY\" ? resumeAt : expiresAt;\n if (due) this.waitpointPoller.nudge(due);\n return { id, resumeUrl };\n },\n };\n return {\n port,\n responseFor: (waitpointId) => responses.get(waitpointId),\n };\n }\n\n /** Re-enters a WAITING run that holds a COMPLETED waitpoint, through the\n * dispatcher. Whoever writes second, the resume or the WAITING, delivers. */\n private async deliverHeld(runId: string): Promise<void> {\n if (this.closed) return this.answerShutDown(runId);\n if (this.resuming.has(runId)) return;\n try {\n const store = await this.store();\n if (!store || !(await store.hasCompletedWaitpoint(runId))) return;\n const run = await store.getRun(runId);\n if (run?.status !== WAITING_RUN_STATUS) {\n return this.answerNotWaiting(store, runId, run?.status);\n }\n if (this.resuming.has(runId)) return;\n this.resuming.add(runId);\n void this.resumeRun(runId, run.workflow_id);\n } catch (error) {\n this.logger.warn(`Could not resume run ${runId}: @error`, error);\n }\n }\n\n // A leg running here answers its held resumes itself; otherwise the run\n // ended or another runtime holds it, and none here ever will.\n private answerNotWaiting(\n store: WorkflowRunStore,\n runId: string,\n status: string | undefined,\n ): void {\n if (store.isRunInFlight(runId)) return;\n this.answerUnresumed(runId, {\n status: status ?? \"gone\",\n error: \"The run is not waiting to resume in this runtime\",\n code: 409,\n });\n }\n\n // Wakes due DELAY waitpoints and expires overdue ones; runs on the owner only.\n private readonly waitpointPoller = new WaitpointPoller({\n store: () => this.store(),\n resume: (runId) => this.deliverHeld(runId),\n ended: (end) => {\n this.answerClosed(end.closed, end.runId, {\n status: CANCELLED_RUN_STATUS,\n error: end.reason,\n });\n return this.endSubflow(end.runId);\n },\n logger: {\n warn: (message: string, ...args: unknown[]) =>\n this.logger.warn(message, ...args),\n },\n });\n private unobserveSuspended?: () => void;\n\n /** Test hook: one waitpoint poll pass now; a no-op until the supervisor starts. */\n pollWaitpointsNow(): Promise<void> {\n return this.waitpointPoller.poll();\n }\n\n private startWaitpointPoller(): void {\n if (this.closed) return;\n this.unobserveSuspended ??= this.telemetry.observeSuspended(() =>\n this.waitpointPoller.suspendedRuns(),\n );\n this.waitpointPoller.start();\n }\n\n private stopWaitpointPoller(): void {\n this.waitpointPoller.stop();\n this.unobserveSuspended?.();\n this.unobserveSuspended = undefined;\n }\n\n // Answers `/sync` resumes held for a run that ended before its leg resumed.\n private async answerHeldResumes(\n store: WorkflowRunStore,\n runId: string,\n error: string,\n ): Promise<void> {\n if (this.syncResumes.size === 0) return;\n const rows = (await store.listWaitpointsForRuns([runId])).get(runId) ?? [];\n this.answerClosed(\n rows.map((row) => row.id),\n runId,\n { status: CANCELLED_RUN_STATUS, error },\n );\n }\n\n // Answers `/sync` resumes held on waitpoints that closed without resuming.\n private answerClosed(\n waitpointIds: readonly string[],\n runId: string,\n end: { status: string; error: string },\n ): void {\n if (this.syncResumes.size === 0) return;\n for (const id of waitpointIds) {\n this.heldResume(id)?.closed(runId, end.status, end.error);\n }\n }\n\n // The held `/sync` request that won this waitpoint, answered once it knows.\n private heldResume(waitpointId: string): SyncResume | undefined {\n const candidates = [...(this.syncResumes.get(waitpointId) ?? [])];\n if (candidates.length === 0) return undefined;\n const winner = (async () => {\n for (const candidate of candidates) {\n if (await candidate.won) return candidate.entry;\n }\n return undefined;\n })();\n return {\n respond: (response) => void winner.then((e) => e?.respond(response)),\n ended: (result) => void winner.then((e) => e?.ended(result)),\n closed: (runId, status, error, code) =>\n void winner.then((e) => e?.closed(runId, status, error, code)),\n };\n }\n\n // Answers the `/sync` resumes held on this run's waitpoints, before any leg\n // could resume it here.\n private answerUnresumed(\n runId: string,\n end: { status: string; error: string; code: number },\n ): void {\n for (const [id, candidates] of this.syncResumes) {\n if (![...candidates].some((candidate) => candidate.runId === runId)) {\n continue;\n }\n this.heldResume(id)?.closed(runId, end.status, end.error, end.code);\n }\n }\n\n // Held resumes a stopped process never delivered.\n private async deliverAllHeld(): Promise<void> {\n try {\n const store = await this.store();\n for (const runId of (await store?.heldRunIds()) ?? []) {\n await this.deliverHeld(runId);\n }\n } catch (error) {\n this.logger.warn(\"Could not deliver held resumes: @error\", error);\n }\n }\n\n private resumeRun(\n runId: string,\n workflowId: string,\n ): Promise<PersistedRunResult | undefined> {\n const started = performance.now();\n const attributes = {\n \"workflow.id\": workflowId,\n \"trigger.kind\": \"resume\",\n \"run.id\": runId,\n };\n return this.telemetry.span(\"workflow.run\", attributes, async (span) => {\n let status = \"REFUSED\";\n try {\n const result = await this.runResumed(runId, workflowId);\n void this.endSubflow(runId);\n if (result) status = result.status;\n if (status === \"FAILED\") {\n span.setStatus({ code: SpanStatusCode.ERROR, message: status });\n }\n return result;\n } finally {\n span.setAttribute(\"run.status\", status);\n this.telemetry.recordRun(performance.now() - started, status, \"resume\");\n }\n });\n }\n\n // Undefined when the run was not resumed: cancelled, claimed elsewhere, or\n // the runtime shut down while it waited for admission.\n private async runResumed(\n runId: string,\n workflowId: string,\n ): Promise<PersistedRunResult | undefined> {\n // The workflow's concurrency slot, as a firing takes it, then the\n // dispatcher's. A resume queues for the slot rather than being dropped.\n const admission = await this.runGate.admit(\n workflowId,\n await this.resumePolicy(workflowId),\n undefined,\n { resume: true },\n );\n if (!admission.admitted) {\n this.resuming.delete(runId);\n this.answerShutDown(runId);\n return undefined;\n }\n let dispatched: () => void;\n try {\n dispatched = await this.dispatcher().admit(workflowId);\n } catch {\n admission.release();\n this.resuming.delete(runId);\n this.answerShutDown(runId);\n return undefined;\n }\n const store = await this.store();\n let claimed = false;\n let redeliver = false;\n let session: PieceWorkerSession | undefined;\n let held: SyncResume | undefined;\n let outcome: PersistedRunResult | undefined;\n try {\n if (!store || this.closed) {\n this.answerShutDown(runId);\n return undefined;\n }\n claimed = await store.claimWaitingRun(runId);\n this.resuming.delete(runId);\n if (!claimed) {\n this.answerNotWaiting(\n store,\n runId,\n (await store.getRun(runId))?.status,\n );\n return undefined;\n }\n const row = await store.getRun(runId);\n if (!row) throw new Error(`Run \"${runId}\" not found`);\n // Read fresh: the cache can trail a disable the resume must honour.\n const generation = this.workflowGeneration(workflowId);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n if (document.header.documentType === WORKFLOW_DOCUMENT_TYPE) {\n this.cacheLoaded(workflowId, generation, document);\n }\n const current = document.state.global;\n const stopped = await this.resumeStopped(\n workflowId,\n row.trigger_kind,\n current,\n );\n if (stopped) {\n const closed = await store.endWait(runId, {\n status: CANCELLED_RUN_STATUS,\n reason: stopped.reason,\n errorName: stopped.errorName,\n waitpoints: \"CANCELLED\",\n });\n claimed = false;\n this.answerClosed(closed, runId, {\n status: CANCELLED_RUN_STATUS,\n error: stopped.reason,\n });\n return {\n status: CANCELLED_RUN_STATUS,\n steps: [],\n runId,\n error: stopped.reason,\n errorName: stopped.errorName,\n refusal: \"cancelled\",\n };\n }\n const consumed = await store.consumeCompletedWaitpoint(runId);\n if (!consumed) {\n await store.returnToWaiting(runId);\n claimed = false;\n // A waitpoint completed while this leg held the claim found it RUNNING.\n redeliver = true;\n return undefined;\n }\n const { waitpoint } = consumed;\n held = this.heldResume(waitpoint.id);\n this.answerClosed(consumed.closed, runId, {\n status: \"RUNNING\",\n error: \"The run resumed on another of its waitpoints\",\n });\n const state = await this.pinnedState(workflowId, runId, store, current);\n const runnable = runnableDefinition(state);\n const definition = toWorkflowDefinition(state);\n const policy = effectiveRunPolicy(runnable);\n const connections = declaredConnectionIds(definition);\n const reactorConnections = declaredReactorConnectionIds(definition);\n const runUser =\n reactorConnections.size === 0\n ? undefined\n : await assertReactorConnectionsReadable(\n this.host,\n workflowId,\n reactorConnections,\n );\n const journal = carriedFromJournal(await store.getSteps(runId));\n if (!journal.waitingStepId) {\n throw new Error(`Run \"${runId}\" has no waiting step to resume`);\n }\n session = this.workers().session();\n const { result } = await this.executeLeg({\n workflowId,\n runId,\n store,\n session,\n definition,\n runnable,\n policy,\n // Each leg gets the whole budget: the wait is not run time.\n deadline: policy.runTimeoutSeconds\n ? Date.now() + policy.runTimeoutSeconds * 1000\n : undefined,\n connections,\n runUser,\n triggerPayload: journaledTriggerPayload(row.trigger_payload),\n executor: this.blockExecutor(store),\n carriedSteps: journal.carried,\n resume: {\n stepId: journal.waitingStepId,\n payload: parseJson(waitpoint.resume_payload) ?? {},\n },\n firstOrdinal: journal.nextOrdinal,\n written: journal.attachmentRefs,\n handed: await store.getRunDocuments(runId),\n ...(held ? { respond: held.respond } : {}),\n });\n if (\n result.status === \"FAILED\" &&\n !OPERATOR_RUN_KINDS.has(row.trigger_kind)\n ) {\n await this.applyFailureMode(\n policy,\n workflowId,\n runnable.version,\n runId,\n result.error,\n );\n }\n outcome = { ...result, runId };\n return outcome;\n } catch (error) {\n if (store && claimed) {\n const message = error instanceof Error ? error.message : String(error);\n const errorName = errorNameOf(error) ?? \"Error\";\n // The waiting step fails with the run; a held resume hears why.\n const closed = await store\n .endWait(runId, {\n status: \"FAILED\",\n reason: message,\n errorName,\n waitpoints: \"CANCELLED\",\n })\n .catch(() => []);\n this.answerClosed(closed, runId, { status: \"FAILED\", error: message });\n outcome = {\n status: \"FAILED\",\n steps: [],\n runId,\n error: message,\n errorName,\n };\n }\n this.logger.warn(`Resuming run ${runId} failed: @error`, error);\n return undefined;\n } finally {\n this.resuming.delete(runId);\n session?.close();\n dispatched();\n admission.release();\n held?.ended(outcome);\n if (redeliver) void this.deliverHeld(runId);\n }\n }\n\n // Answers held `/sync` resumes 503 when shutdown refused their leg; the\n // waitpoint stays COMPLETED and the next owner delivers it.\n private answerShutDown(runId: string): void {\n if (!this.closed) return;\n this.answerUnresumed(runId, {\n status: WAITING_RUN_STATUS,\n error: \"The runtime shut down before the run could resume\",\n code: 503,\n });\n }\n\n // The policy for the gate a resume shares with firings, cached as a trigger's\n // run reads it. Unreadable, no gate: the claimed run's own read then fails it.\n private async resumePolicy(workflowId: string): Promise<EffectiveRunPolicy> {\n try {\n let state = this.workflowCache.get(workflowId)?.state;\n if (!state) {\n const generation = this.workflowGeneration(workflowId);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n if (document.header.documentType === WORKFLOW_DOCUMENT_TYPE) {\n this.cacheLoaded(workflowId, generation, document);\n }\n state = document.state.global;\n }\n return effectiveRunPolicy(runnableDefinition(state));\n } catch {\n return UNENFORCED_POLICY;\n }\n }\n\n // Why a waiting run must not resume on the workflow as it is now.\n private async resumeStopped(\n workflowId: string,\n triggerKind: string,\n current: WorkflowState,\n ): Promise<{ reason: string; errorName: string } | undefined> {\n if (current.status !== \"ENABLED\") {\n return {\n reason: `The workflow is ${current.status}; a run waiting on it does not resume`,\n errorName: WORKFLOW_DISABLED_ERROR_NAME,\n };\n }\n const parked = await this.parkedFiring(\n workflowId,\n triggerKind,\n runnableDefinition(current).version,\n );\n return parked\n ? { reason: parked, errorName: WORKFLOW_PARKED_ERROR_NAME }\n : undefined;\n }\n\n // The state a suspended run resumes on: the current one when its definition\n // still hashes the same, else rebuilt at the revision it pinned.\n private async pinnedState(\n workflowId: string,\n runId: string,\n store: WorkflowRunStore,\n current: WorkflowState,\n ): Promise<WorkflowState> {\n const pin = await store.getRunPin(runId);\n if (!pin?.definition_hash) return current;\n if (this.definitionHash(workflowId, current) === pin.definition_hash) {\n return current;\n }\n return this.rebuildWorkflowState(workflowId, pin);\n }\n\n // Replays the global operations below the pinned revision; the reactor does\n // not honour ViewFilter.revision yet. The hash check below catches a miss.\n private async rebuildWorkflowState(\n workflowId: string,\n pin: RunPinRow,\n ): Promise<WorkflowState> {\n const revision = pin.definition_op_index ?? 0;\n const operations: Operation[] = [];\n let page = await this.host.reactorClient.getOperations(workflowId, {\n scopes: [\"document\", \"global\"],\n });\n operations.push(...page.results);\n while (page.next) {\n page = await page.next();\n operations.push(...page.results);\n }\n const applied = (operation: Operation) =>\n !operation.error && !isDenied(operation);\n // The first global operation past the pin, for upgrades without a revision.\n const past = sortOperations(\n operations.filter(\n (operation) =>\n operation.action.scope === \"global\" && operation.index >= revision,\n ),\n ).at(0);\n // Placed by its revision snapshot, else its timestamp, as replay places it.\n const atOrBeforePin = (operation: Operation) => {\n const at = (operation.action.input as { revision?: { global?: number } })\n .revision?.global;\n if (at !== undefined) return at <= revision;\n return !past || operation.timestampUtcMs <= past.timestampUtcMs;\n };\n // An upgrade that seeds a snapshot starts the state there, as the reactor does.\n const seed = sortOperations(\n operations.filter(\n (operation) =>\n operation.action.scope === \"document\" &&\n operation.action.type === \"UPGRADE_DOCUMENT\" &&\n applied(operation) &&\n atOrBeforePin(operation),\n ),\n )\n .map(\n (operation) =>\n (operation.action.input as { initialState?: { global?: unknown } })\n .initialState,\n )\n .filter((state) => state?.global !== undefined)\n .at(-1);\n let document = workflowUtils.createDocument(seed as never);\n const global = sortOperations(\n operations.filter(\n (operation) =>\n operation.action.scope === \"global\" && operation.index < revision,\n ),\n );\n // Undone operations drop out first, as a replay of the document does.\n for (const operation of garbageCollect(global).filter(applied)) {\n document = workflowReducer(document, operation.action as never);\n }\n const state = document.state.global;\n if (\n scopeHash(state) !== pin.definition_scope_hash ||\n this.definitionHash(workflowId, state) !== pin.definition_hash\n ) {\n throw new Error(\n `The workflow was re-published while this run waited, and the ` +\n `definition it started from could not be rebuilt at revision ${revision}`,\n );\n }\n return state;\n }\n\n /** Resolves a WEBHOOK waitpoint from the editor, as the calling DID. */\n async resolveWaitpoint(\n waitpointId: string,\n input: ResolveWaitpointInput,\n ctx?: WorkflowCaller,\n ): Promise<WaitpointRecord> {\n const store = await this.store();\n if (!store) throw new Error(\"Run journal is unavailable\");\n const waitpoint = await store.getWaitpoint(waitpointId);\n if (!waitpoint) throw new Error(`Waitpoint \"${waitpointId}\" not found`);\n await this.assertCanReadDocument(waitpoint.workflow_id, ctx);\n await this.assertCanWriteDocument(waitpoint.workflow_id, ctx);\n // Its approval holds the run's data, so only a caller served the run.\n const owner = await store.getRun(waitpoint.run_id);\n if (!owner || (await this.servedRuns([owner], ctx)).length === 0) {\n throw new Error(`Waitpoint \"${waitpointId}\" not found`);\n }\n if (waitpoint.type !== \"WEBHOOK\") {\n throw new Error(`Waitpoint \"${waitpointId}\" is a ${waitpoint.type}`);\n }\n const decidedBy = this.callerDid(ctx);\n const approval = parseJson(waitpoint.approval) as ApprovalRequest | null;\n if (approval && approval.approvers.length > 0) {\n const listed =\n decidedBy !== undefined &&\n approval.approvers.some((approver) =>\n sameApprover(approver, decidedBy),\n );\n if (!listed) {\n throw new Error(\"You are not one of this approval's approvers\");\n }\n }\n const reason = input.reason?.trim() || undefined;\n const reasonRequired =\n approval?.reasonRequiredOn === \"both\" ||\n (approval?.reasonRequiredOn === \"reject\" && !input.approved);\n if (reasonRequired && !reason) {\n throw new Error(\"A reason is required for this decision\");\n }\n const decidedAt = new Date().toISOString();\n const payload: WaitpointResumePayload = {\n queryParams: {\n action: input.approved ? \"approve\" : \"disapprove\",\n ...(reason ? { reason } : {}),\n },\n body: {\n approved: input.approved,\n reason: reason ?? null,\n decidedBy: decidedBy ?? null,\n decidedAt,\n },\n headers: {},\n };\n const completed = await store.completeWaitpoint(waitpointId, {\n payload,\n decidedBy: decidedBy ?? null,\n resolvedAt: decidedAt,\n });\n if (!completed) {\n const now = await store.getWaitpoint(waitpointId);\n const run = await store.getRun(waitpoint.run_id);\n const live =\n run?.status === \"RUNNING\" || run?.status === WAITING_RUN_STATUS;\n const status =\n now?.status !== \"PENDING\"\n ? (now?.status ?? \"gone\")\n : waitpointExpired(now)\n ? \"EXPIRED\"\n : live\n ? \"not the one its run waits on\"\n : `on a ${run?.status ?? \"deleted\"} run`;\n throw new Error(\n `Waitpoint \"${waitpointId}\" is ${status}; it can no longer be resolved`,\n );\n }\n await this.deliverHeld(completed.run_id);\n return waitpointRecord(completed);\n }\n\n /** A POST to a resume URL. Single-use: only a PENDING waitpoint resumes. */\n resumeWaitpointByToken(\n token: string,\n payload: WaitpointResumePayload,\n ): Promise<{ status: \"resumed\" | \"already\" | \"gone\" }> {\n return this.resumeByToken(token, payload);\n }\n\n /** A POST to a resume URL's `/sync`, held like a sync webhook until the\n * resumed leg responds, waits, ends, or times out. The first answer wins. */\n async resumeWaitpointByTokenSync(\n token: string,\n payload: WaitpointResumePayload,\n options: { timeoutMs?: number } = {},\n ): Promise<{ status: \"resumed\" | \"already\" | \"gone\"; reply?: WebhookReply }> {\n let hold: ReturnType<typeof this.holdSyncResume> | undefined;\n try {\n const { status } = await this.resumeByToken(\n token,\n payload,\n (id, runId) => {\n hold = this.holdSyncResume(id, runId);\n return hold.decided;\n },\n );\n if (status !== \"resumed\" || !hold) return { status };\n return {\n status,\n reply: await hold.reply(options.timeoutMs ?? DELIVERY_TIMEOUT_MS),\n };\n } finally {\n hold?.release();\n }\n }\n\n // Registered before the waitpoint completes: its leg may start at once.\n private holdSyncResume(waitpointId: string, runId: string) {\n let settle: (reply: WebhookReply) => void = () => undefined;\n const answer = new Promise<WebhookReply>((resolve) => {\n settle = resolve;\n });\n let done = false;\n const finish = (reply: WebhookReply) => {\n if (done) return;\n done = true;\n settle(reply);\n };\n const entry: SyncResume = {\n respond: (response) => finish(runResponseReply(response)),\n ended: (result) =>\n finish(\n result\n ? runResultReply(result, 200)\n : {\n status: 500,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({ error: \"The run could not resume\" }),\n },\n ),\n closed: (runId, status, error, code = 409) =>\n finish({\n status: code,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({ runId, status, error }),\n }),\n };\n let decided: (won: boolean) => void = () => undefined;\n const candidate: SyncResumeCandidate = {\n entry,\n runId,\n won: new Promise<boolean>((resolve) => {\n decided = resolve;\n }),\n };\n const held = this.syncResumes.get(waitpointId) ?? new Set();\n this.syncResumes.set(waitpointId, held);\n held.add(candidate);\n return {\n decided,\n reply: async (timeoutMs: number): Promise<WebhookReply> => {\n const raced = await Promise.race([answer, timeout(timeoutMs)]);\n if (raced !== TIMED_OUT) return raced;\n done = true;\n return {\n status: 504,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({\n status: \"RUNNING\",\n error: \"The run did not finish in time\",\n }),\n };\n },\n release: () => {\n decided(false);\n held.delete(candidate);\n if (held.size === 0 && this.syncResumes.get(waitpointId) === held) {\n this.syncResumes.delete(waitpointId);\n }\n },\n };\n }\n\n private async resumeByToken(\n token: string,\n payload: WaitpointResumePayload,\n // Called before the claim; told whether this request won the waitpoint.\n beforeComplete?: (\n waitpointId: string,\n runId: string,\n ) => (won: boolean) => void,\n ): Promise<{ status: \"resumed\" | \"already\" | \"gone\" }> {\n const store = await this.store();\n if (!store || !token) return { status: \"gone\" };\n const waitpoint = await store.getWaitpointByTokenHash(tokenHash(token));\n // Only a webhook resumes by token: never an approval or a delay.\n if (!waitpoint || waitpoint.kind !== \"webhook\") return { status: \"gone\" };\n let completed: WaitpointRow | undefined;\n if (waitpoint.status === \"PENDING\") {\n const decided = beforeComplete?.(waitpoint.id, waitpoint.run_id);\n try {\n completed = await store.completeWaitpoint(waitpoint.id, { payload });\n } finally {\n decided?.(completed !== undefined);\n }\n }\n if (!completed) {\n const now = (await store.getWaitpoint(waitpoint.id))?.status;\n if (now === \"CONSUMED\") return { status: \"already\" };\n // Completed but not yet consumed: already, unless its run has ended.\n const run =\n now === \"COMPLETED\" ? await store.getRun(waitpoint.run_id) : undefined;\n const live =\n run?.status === \"RUNNING\" || run?.status === WAITING_RUN_STATUS;\n return { status: live ? \"already\" : \"gone\" };\n }\n await this.deliverHeld(completed.run_id);\n return { status: \"resumed\" };\n }\n\n /** What a resume URL's confirm page shows. */\n async describeWaitpointByToken(\n token: string,\n ): Promise<WaitpointDescription | undefined> {\n const store = await this.store();\n if (!store || !token) return undefined;\n const waitpoint = await store.getWaitpointByTokenHash(tokenHash(token));\n if (!waitpoint || waitpoint.kind !== \"webhook\") return undefined;\n const run = await store.getRun(waitpoint.run_id);\n const live =\n run?.status === \"RUNNING\" || run?.status === WAITING_RUN_STATUS;\n // An ended run's waitpoint never resumes, whatever its row still says.\n const status =\n !live &&\n (waitpoint.status === \"PENDING\" || waitpoint.status === \"COMPLETED\")\n ? \"CANCELLED\"\n : (waitpoint.status as WaitpointStatus);\n const state = await this.workflowStateForPage(waitpoint.workflow_id);\n const step = state?.steps.find((entry) => entry.id === waitpoint.step_id);\n const action = step\n ? await this.blockDisplayName({\n pieceName: step.pieceName,\n pieceVersion: step.pieceVersion,\n kind: \"action\",\n name: step.actionName,\n })\n : undefined;\n const trigger = state?.trigger\n ? ((await this.blockDisplayName({\n pieceName: state.trigger.pieceName,\n pieceVersion: state.trigger.pieceVersion,\n kind: \"trigger\",\n name: state.trigger.triggerName,\n })) ?? state.trigger.triggerName)\n : undefined;\n return {\n workflowName: run?.workflow_name || state?.name || \"\",\n stepName: step?.name || waitpoint.step_key,\n status,\n ...(state?.description ? { workflowDescription: state.description } : {}),\n ...(action ? { actionName: action } : {}),\n waitingSince: waitpoint.created_at,\n ...(waitpoint.expires_at ? { expiresAt: waitpoint.expires_at } : {}),\n ...(run ? { startedAt: run.enqueued_at } : {}),\n ...(trigger ? { triggerName: trigger } : {}),\n };\n }\n\n // Best effort, for a page anyone with the link opens: no error escapes.\n private async workflowStateForPage(\n workflowId: string,\n ): Promise<WorkflowState | undefined> {\n const cached = this.workflowCache.get(workflowId)?.state;\n if (cached) return cached;\n try {\n const generation = this.workflowGeneration(workflowId);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n if (document.header.documentType !== WORKFLOW_DOCUMENT_TYPE) {\n return undefined;\n }\n this.cacheLoaded(workflowId, generation, document);\n return document.state.global;\n } catch {\n return undefined;\n }\n }\n\n // The action's or trigger's display name, or undefined when not described.\n private async blockDisplayName(block: BlockRef): Promise<string | undefined> {\n try {\n const parsed = resolvedBlock(await this.resolveBlock(block));\n if (!parsed) return undefined;\n const descriptor = await this.pieceDescriptor(targetOf(parsed));\n const entries =\n block.kind === \"trigger\" ? descriptor.triggers : descriptor.actions;\n return entries.find((entry) => entry.name === parsed.name)?.displayName;\n } catch {\n return undefined;\n }\n }\n\n /** The waitpoints of one run, for a caller who may read the run. */\n async waitpointsForRun(\n runId: string,\n ctx?: WorkflowCaller,\n ): Promise<WaitpointRecord[]> {\n const store = await this.store();\n if (!store || !(await this.run(runId, ctx))) return [];\n const rows = (await store.listWaitpointsForRuns([runId])).get(runId) ?? [];\n return rows.map(waitpointRecord);\n }\n\n /** WAITING runs this caller may read, oldest first, with their waitpoints. */\n async waitingRuns(\n args: WaitingRunsArgs,\n ctx?: WorkflowCaller,\n ): Promise<Array<{ run: RunRecord; waitpoints: WaitpointRecord[] }>> {\n const store = await this.store();\n if (!store || !ctx) return [];\n let scope: string | string[] | undefined;\n if (args.workflowId) {\n await this.assertCanReadDocument(args.workflowId, ctx);\n scope = args.workflowId;\n } else if (args.driveId) {\n scope = await this.driveWorkflowIds(args.driveId, ctx);\n if (scope.length === 0) return [];\n }\n const rows = await this.servedRuns(\n await this.readableRows(\n await store.listWaitingRuns(scope, args.first ?? 50),\n (row) => row.workflow_id,\n ctx,\n ),\n ctx,\n );\n const ids = rows.map((row) => row.id);\n const steps = await store.getStepsForRuns(ids, { withData: false });\n const waitpoints = await store.listWaitpointsForRuns(ids);\n return rows.map((row) => ({\n run: { row, steps: steps.get(row.id) ?? [] },\n waitpoints: (waitpoints.get(row.id) ?? []).map(waitpointRecord),\n }));\n }\n\n /** Cancels a WAITING or PENDING run; its waitpoints stop resuming. */\n async cancelRun(runId: string, ctx?: WorkflowCaller): Promise<RunRecord> {\n const store = await this.store();\n if (!store) throw new Error(\"Run journal is unavailable\");\n const run = await store.getRun(runId);\n if (!run) throw new Error(`Run \"${runId}\" not found`);\n await this.assertCanReadDocument(run.workflow_id, ctx);\n await this.assertCanWriteDocument(run.workflow_id, ctx);\n // It answers with the run's steps, so only to a caller served the run.\n if (!ctx || (await this.servedRuns([run], ctx)).length === 0) {\n throw new Error(`Run \"${runId}\" not found`);\n }\n const refuse = (status: string) =>\n status === \"RUNNING\"\n ? new Error(\"Cancelling a RUNNING run is not supported yet (#3226)\")\n : new Error(\n `Run is ${status}; only WAITING and PENDING runs can be cancelled`,\n );\n if (run.status !== WAITING_RUN_STATUS && run.status !== \"PENDING\") {\n throw refuse(run.status);\n }\n const by = this.callerDid(ctx);\n const reason = by ? `Cancelled by ${by}` : \"Cancelled\";\n const cancelled = await store.cancelIdleRun(runId, reason);\n if (!cancelled) {\n throw refuse((await store.getRun(runId))?.status ?? \"gone\");\n }\n await this.answerHeldResumes(store, runId, reason);\n await this.endSubflow(runId);\n const row = (await store.getRun(runId))!;\n this.queuedReplies.get(runId)?.({\n status: row.status as PersistedRunResult[\"status\"],\n steps: [],\n runId,\n ...(row.error ? { error: row.error } : {}),\n refusal: \"cancelled\",\n });\n return { row, steps: await store.getSteps(runId) };\n }\n\n // The caller's DID, as the host reads it.\n private callerDid(ctx: WorkflowCaller | undefined): string | undefined {\n if (!ctx) return undefined;\n const subject = this.host.subjectOf?.(ctx);\n if (subject?.address) return subject.address;\n const user = (ctx as { user?: { address?: unknown } }).user;\n return typeof user?.address === \"string\" ? user.address : undefined;\n }\n\n // Runs one draft step against the latest test outputs of the blocks it\n // reads, journals it as a \"test\" run and notes it as the step's lastTest.\n\n // It hands the step's connection to piece code, so the caller must be able\n // to read the workflow and that connection, as for testTrigger.\n async testStep(\n workflowId: string,\n stepId: string,\n ctx?: WorkflowCaller,\n access: WorkflowAccessOptions = {},\n ): Promise<StepTestResult> {\n await this.assertCanReadWorkflow(workflowId, ctx, access.driveId);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n const state = document.state.global;\n const step = state.steps.find((candidate) => candidate.id === stepId);\n if (!step) throw new Error(`Step \"${stepId}\" not found`);\n if (step.connectionId) {\n await this.assertCanReadDocument(step.connectionId, ctx);\n }\n if (step.reactorConnectionId) {\n await this.assertCanReadDocument(step.reactorConnectionId, ctx);\n }\n const refused = (error: string): StepTestResult => ({\n runId: null,\n status: \"FAILED\",\n error,\n durationMs: 0,\n });\n\n const upstream = await this.testScope(state, step, ctx);\n if (\"error\" in upstream) return refused(upstream.error);\n let resolved;\n try {\n resolved = await resolveVariables(\n state.variables,\n this.secretProvider(),\n workflowId,\n );\n } catch (error) {\n return refused(error instanceof Error ? error.message : String(error));\n }\n const { variables, secretValues } = resolved;\n const definition = {\n name: state.name,\n trigger: null,\n steps: [draftStepDef(step)],\n edges: [],\n variables,\n };\n // A journaled sample carries markers where secrets were: refuse to hand\n // them to the step as if they were values.\n let input: unknown;\n try {\n input = resolveStepInput(definition.steps[0], {\n trigger: { payload: upstream.triggerPayload },\n steps: upstream.priorSteps,\n variables: Object.fromEntries(variables.map((v) => [v.key, v.value])),\n });\n } catch {\n // The run below fails the step with the same error, and journals it.\n input = step.config;\n }\n if (containsRedactedMarker(input) && !containsRedactedMarker(step.config)) {\n const sources = upstream.samples\n .filter((sample) => containsRedactedMarker(sample.value))\n .map((sample) => sample.label);\n return refused(\n `\"${step.key}\" reads a value redacted from the last test of ${sources.join(\", \") || \"an earlier block\"}`,\n );\n }\n\n const store = await this.store();\n let runId: string | null = null;\n try {\n runId =\n (await store?.startRun({\n workflowId,\n workflowName: runJournalName(state.name, document.header.name),\n workflowVersion: state.version,\n triggerKind: TEST_TRIGGER_KIND,\n })) ?? null;\n } catch (error) {\n this.logger.warn(\n `Could not journal the test of \"@step\" on workflow ${workflowId}: @error`,\n step.key,\n error,\n );\n }\n const executor = this.blockExecutor(store);\n const handed = new Set<string>();\n const started = Date.now();\n let session: PieceWorkerSession | undefined;\n let result: WorkflowRunResult;\n try {\n session = this.workers().session();\n const journaledRunId = runId;\n result = await withRunScope(\n {\n workflowId,\n runId,\n connections: declaredConnectionIds(definition),\n pieceWorker: session,\n stepTest: true,\n // A single-step test acts as its caller.\n runUser: this.callerRunUser(ctx),\n attachments: attachmentOrigins(\n upstream.triggerPayload,\n handed,\n upstream.priorSteps,\n ),\n recordDocuments: async (documentIds: string[]) => {\n for (const documentId of documentIds) handed.add(documentId);\n if (store && journaledRunId) {\n await store.recordRunDocuments(journaledRunId, documentIds);\n }\n },\n },\n () =>\n runWorkflow({\n definition,\n executor,\n // A test runs once: the action's timeout applies, its retry not.\n blockDefaults: async (block) => {\n const timeoutSeconds = (await this.blockDefaults(block))\n ?.timeoutSeconds;\n return timeoutSeconds ? { timeoutSeconds } : undefined;\n },\n ...(secretValues.length > 0 ? { redactValues: secretValues } : {}),\n triggerPayload: upstream.triggerPayload,\n priorSteps: upstream.priorSteps,\n onStep:\n store && journaledRunId\n ? (record, ordinal) =>\n store.recordStep(journaledRunId, ordinal, record)\n : undefined,\n }),\n );\n } catch (error) {\n if (store && runId) {\n const detail = error instanceof Error ? error.message : String(error);\n await store\n .failRun(runId, detail, errorNameOf(error))\n .catch(() => undefined);\n await this.noteLastTest(\n workflowId,\n { stepId: step.id, key: step.key },\n runId,\n new Date().toISOString(),\n );\n }\n throw error;\n } finally {\n session?.close();\n }\n const durationMs = Date.now() - started;\n const [record] = result.steps;\n if (store && runId) {\n try {\n await store.finishRun(runId, result);\n } catch (error) {\n this.logger.warn(\n `Run ${runId}: closing the test of \"@step\" out failed: @error`,\n step.key,\n error,\n );\n }\n await this.noteLastTest(\n workflowId,\n record,\n runId,\n record.endedAt ?? new Date().toISOString(),\n );\n }\n // Served as `run` would serve it: documents the caller cannot read stay out.\n const ids = [...triggerDocumentIds(upstream.triggerPayload), ...handed];\n const served = ctx ? await this.servesDocuments(ids, ctx) : false;\n return {\n runId,\n status: testStatusOf(record.status),\n ...(served && record.output !== undefined\n ? { output: record.output }\n : {}),\n ...(record.error ? { error: record.error } : {}),\n ...(record.errorName ? { errorName: record.errorName } : {}),\n durationMs,\n };\n }\n\n // The scope a step test runs in: the trigger's and each read step's latest\n // test output. An untested block it reads is an error naming that block.\n private async testScope(\n state: WorkflowState,\n step: WorkflowState[\"steps\"][number],\n ctx: WorkflowCaller | undefined,\n ): Promise<\n | { error: string }\n | {\n triggerPayload?: unknown;\n priorSteps: ExpressionScope[\"steps\"];\n samples: { label: string; value: unknown }[];\n }\n > {\n const refs = scopeReferences(step.config);\n const samples: { label: string; value: unknown }[] = [];\n let triggerPayload: unknown;\n if (refs.trigger && state.trigger) {\n const sample = await this.lastTestSample(\n {\n id: state.trigger.id,\n pieceName: state.trigger.pieceName,\n name: state.trigger.triggerName,\n lastTest: state.trigger.lastTest,\n },\n ctx,\n );\n if (sample.kind !== \"succeeded\") {\n return { error: untestedError(\"the trigger\", sample) };\n }\n const read = await this.readReferencedDocuments(sample.output, ctx);\n if (\"error\" in read) {\n return { error: `The last test of the trigger read ${read.error}` };\n }\n const { payload, empty } = triggerSamplePayload(read.value);\n if (empty) {\n return {\n error: \"Test the trigger first: its last test returned no items\",\n };\n }\n triggerPayload = payload;\n samples.push({ label: \"the trigger\", value: payload });\n }\n const upstream = upstreamStepIds(state, step.id);\n const read = state.steps.filter(\n (candidate) =>\n candidate.id !== step.id &&\n (refs.steps.has(candidate.key) ||\n (refs.allSteps && upstream.has(candidate.id))),\n );\n const priorSteps: ExpressionScope[\"steps\"] = {};\n for (const candidate of read) {\n // A skipped step continues with a null output, as in a run.\n if (candidate.skip === true) {\n priorSteps[candidate.key] = { output: null };\n continue;\n }\n const label = `\"${candidate.key}\"`;\n const sample = await this.lastTestSample(\n {\n id: candidate.id,\n pieceName: candidate.pieceName,\n name: candidate.actionName,\n lastTest: candidate.lastTest,\n },\n ctx,\n );\n const fields = refs.steps.get(candidate.key);\n const readsErrorOnly =\n fields !== undefined && [...fields].every((field) => field === \"error\");\n if (sample.kind === \"failed\" && readsErrorOnly) {\n priorSteps[candidate.key] = { error: sample.error };\n continue;\n }\n if (sample.kind !== \"succeeded\") {\n return { error: untestedError(label, sample) };\n }\n const read = await this.readReferencedDocuments(sample.output, ctx);\n if (\"error\" in read) {\n return { error: `The last test of ${label} read ${read.error}` };\n }\n priorSteps[candidate.key] = { output: read.value };\n samples.push({ label, value: read.value });\n }\n return { triggerPayload, priorSteps, samples };\n }\n\n // A journaled sample with each document it references read now, as the\n // caller: the journal keeps references, not state.\n private async readReferencedDocuments(\n value: unknown,\n ctx: WorkflowCaller | undefined,\n ): Promise<{ value: unknown } | { error: string }> {\n const references = documentRefsIn(value);\n if (references.length === 0) return { value };\n const subject = ctx ? this.host.subjectOf?.(ctx) : undefined;\n const key = (reference: DocumentReference) =>\n `${reference.branch}:${reference.documentId}`;\n const read = new Map<string, Record<string, unknown>>();\n for (const reference of references) {\n if (read.has(key(reference))) continue;\n try {\n await this.assertCanReadDocument(reference.documentId, ctx);\n const document = await this.host.reactorClient.get(\n reference.documentId,\n { branch: reference.branch, ...(subject ? { subject } : {}) },\n );\n read.set(key(reference), {\n header: document.header,\n state: document.state,\n });\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return {\n error: `document \"${reference.documentId}\", which cannot be read now: ${detail}`,\n };\n }\n }\n return {\n value: expandDocumentRefs(value, (reference) =>\n read.get(key(reference))!,\n ),\n };\n }\n\n // A journaled sample's document references as the picker's document shape:\n // the reference's own header fields, and the model's global state fields.\n private async documentShapes(\n value: unknown,\n ): Promise<{ value: unknown; nodes: OutputTreeNode[] }> {\n const types = [\n ...new Set(documentRefsIn(value).map((ref) => ref.documentType)),\n ];\n const fields = new Map(\n await Promise.all(\n types.map(\n async (type) => [type, await this.stateFields(type)] as const,\n ),\n ),\n );\n const treeOf = (reference: DocumentReference) =>\n documentTree(fields.get(reference.documentType) ?? []);\n const expanded = expandDocumentRefs(value, (reference) => {\n const shape = treeValue(treeOf(reference));\n return {\n ...shape,\n header: {\n ...(shape.header as Record<string, unknown>),\n id: reference.documentId,\n documentType: reference.documentType,\n branch: reference.branch,\n revision: reference.revision,\n },\n };\n });\n return { value: expanded, nodes: fromSample(value, 0, treeOf) };\n }\n\n // A block's lastTest, read back from the journal. A test of a different\n // block, or one the caller may not see, is no sample.\n private async lastTestSample(\n block: {\n id: string;\n pieceName: string;\n name: string;\n lastTest?: { runId: string; testedAt: string } | null;\n },\n ctx: WorkflowCaller | undefined,\n ): Promise<TestSample> {\n const lastTest = block.lastTest;\n const store = await this.store();\n if (!lastTest || !store) return { kind: \"untested\" };\n const run = await store.getRun(lastTest.runId);\n if (!run) return { kind: \"untested\" };\n if ((await this.servedRuns([run], ctx)).length === 0) {\n return { kind: \"hidden\" };\n }\n const row = (await store.getSteps(run.id)).find(\n (candidate) => candidate.step_id === block.id,\n );\n if (!row) return { kind: \"untested\" };\n if (row.piece_name !== block.pieceName || row.block_name !== block.name) {\n return { kind: \"stale\" };\n }\n const { runId, testedAt } = lastTest;\n if (row.status === \"FAILED\") {\n return { kind: \"failed\", runId, testedAt, error: row.error ?? \"\" };\n }\n // Not a sample either way: the test neither returned an output nor failed,\n // so a draft step that read it would be standing on a null nobody\n // confirmed. Its own kind, so the message says which of the two it is.\n if (row.status === \"INDETERMINATE\") return { kind: \"indeterminate\" };\n const output =\n row.output === null ? null : (JSON.parse(row.output) as unknown);\n // The journal capped this output to a marker (store.ts,\n // STEP_PAYLOAD_MAX_BYTES); serving it would hand the marker to a draft\n // step, or to the expression picker, as if it were the block's data.\n if (isTruncatedStepPayload(output)) return { kind: \"truncated\" };\n return { kind: \"succeeded\", runId, testedAt, output };\n }\n\n // Output tree of a draft step or trigger for the expression picker: its\n // latest test output when there is one, else the block's authored shape.\n async stepOutputTree(\n workflowId: string,\n stepId: string,\n ctx?: WorkflowCaller,\n ): Promise<OutputTree> {\n await this.assertCanReadDocument(workflowId, ctx);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n const state = document.state.global;\n const isTrigger = state.trigger?.id === stepId;\n const step = state.steps.find((candidate) => candidate.id === stepId);\n const found =\n isTrigger && state.trigger\n ? { ...state.trigger, block: triggerBlock(state.trigger) }\n : step\n ? { ...step, block: stepBlock(step) }\n : undefined;\n if (!found) throw new Error(`Step \"${stepId}\" not found`);\n const sample = await this.lastTestSample(\n {\n id: found.id,\n pieceName: found.block.pieceName,\n name: found.block.name,\n lastTest: found.lastTest,\n },\n ctx,\n );\n if (sample.kind === \"succeeded\") {\n const journaled = isTrigger\n ? triggerSamplePayload(sample.output).payload\n : sample.output;\n // Documents the test read are journaled as references; their fields\n // come from the model, never from journaled state.\n const { value, nodes } = await this.documentShapes(journaled);\n return {\n source: \"test\",\n nodes,\n sample: value,\n testedAt: sample.testedAt,\n runId: sample.runId,\n };\n }\n return this.blockOutputTree(found.block, found.config);\n }\n\n // Every block of the draft as this reactor would run it, for the editor's\n // version badges and \"update available\".\n async blockResolutions(\n workflowId: string,\n ctx?: WorkflowCaller,\n ): Promise<BlockResolutionRecord[]> {\n const state = await this.draftOf(workflowId, ctx);\n return Promise.all(\n draftBlocks(state).map(async ({ id, block }) => {\n const resolution = await this.resolveBlock(block, { latest: true });\n return {\n stepId: id,\n pieceName: block.pieceName,\n pieceVersion: block.pieceVersion,\n name: block.name,\n kind: block.kind,\n resolvedVersion: resolution.resolved?.version ?? null,\n source: resolution.resolved?.source ?? null,\n match: resolution.match,\n note: resolution.note ?? null,\n latestVersion: resolution.latestVersion ?? null,\n };\n }),\n );\n }\n\n private async draftOf(\n workflowId: string,\n ctx: WorkflowCaller | undefined,\n ): Promise<WorkflowState> {\n await this.assertCanReadDocument(workflowId, ctx);\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n return document.state.global;\n }\n}\n\n// The hash the reactor gives a document's global scope after an operation.\nfunction scopeHash(state: WorkflowState): string {\n return hashDocumentStateForScope({ state: { global: state } }, \"global\");\n}\n\n// Upstream's Callable Flow keeps the caller's callback under this key + run id.\nconst CALLABLE_FLOW_KEY_PREFIX = \"callableFlow_\";\n\n// A called run ending in one of these fails a caller that waits on it.\nconst FAILED_SUBFLOW_STATUSES = new Set([\n \"FAILED\",\n \"CANCELLED\",\n \"INDETERMINATE\",\n]);\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n// Past its expiry, whether or not the poller has swept it yet.\nfunction waitpointExpired(waitpoint: WaitpointRow): boolean {\n return (\n waitpoint.expires_at !== null &&\n Date.parse(waitpoint.expires_at) <= Date.now()\n );\n}\n\nfunction parseJson(value: string | null): unknown {\n return value === null ? null : (JSON.parse(value) as unknown);\n}\n\nexport { WAITPOINT_EXPIRED_ERROR_NAME, WAITPOINT_NOT_LIVE_ERROR_NAME };\n// A waiting run cancelled because its workflow stopped running.\nexport const WORKFLOW_DISABLED_ERROR_NAME = \"WorkflowDisabled\";\nexport const WORKFLOW_PARKED_ERROR_NAME = \"WorkflowParked\";\n\n// The store compares waitpoint times as ISO strings, which sort by time only\n// up to year 9999: '+010000-…' sorts before '2026-…'.\nconst MAX_WAITPOINT_ISO = \"9999-12-31T23:59:59.999Z\";\nconst MAX_WAITPOINT_MS = Date.parse(MAX_WAITPOINT_ISO);\n\n// The sooner of the block's own expiry and the policy's suspension bound,\n// capped at MAX_WAITPOINT_ISO.\nfunction waitpointExpiry(\n createdAt: Date,\n request: { expiresAt?: string },\n suspendMs: number | null,\n): string | null {\n const own = request.expiresAt ? Date.parse(request.expiresAt) : NaN;\n const bound = suspendMs === null ? NaN : createdAt.getTime() + suspendMs;\n const candidates = [own, bound].filter((at) => !Number.isNaN(at));\n return candidates.length > 0\n ? new Date(Math.min(...candidates, MAX_WAITPOINT_MS)).toISOString()\n : null;\n}\n\n// An approver listed as a DID (did:pkh:…:0xabc) or a bare address.\nfunction sameApprover(approver: string, caller: string): boolean {\n const tail = (value: string) => value.split(\":\").pop()!.toLowerCase();\n return (\n approver.toLowerCase() === caller.toLowerCase() ||\n tail(approver) === tail(caller)\n );\n}\n\nexport function waitpointRecord(row: WaitpointRow): WaitpointRecord {\n return {\n id: row.id,\n runId: row.run_id,\n workflowId: row.workflow_id,\n stepId: row.step_id,\n stepKey: row.step_key,\n stepPath: row.step_path,\n pieceName: row.piece_name,\n blockName: row.block_name,\n type: row.type as WaitpointRecord[\"type\"],\n kind: row.kind as WaitpointRecord[\"kind\"],\n status: row.status as WaitpointStatus,\n createdAt: row.created_at,\n resumeAt: row.resume_at,\n expiresAt: row.expires_at,\n resolvedAt: row.resolved_at,\n decidedBy: row.decided_by,\n approval: parseJson(row.approval) as ApprovalRequest | null,\n };\n}\n\n// A journaled value a resumed run reads: a capped one is unavailable whole, a\n// redacted leaf only at its own path, so a step that reads either fails by name.\nfunction journaledValue(raw: string | null, what: string): unknown {\n const value = raw === null ? undefined : (JSON.parse(raw) as unknown);\n if (isTruncatedStepPayload(value)) {\n return unavailableValue(\n `${what} is unavailable: the run journal truncated it past the payload cap`,\n );\n }\n return redactedLeavesUnavailable(value, what, []);\n}\n\nfunction redactedLeavesUnavailable(\n value: unknown,\n what: string,\n path: (string | number)[],\n): unknown {\n if (!containsRedactedMarker(value)) return value;\n if (typeof value === \"string\") {\n // The path ends the message: a colon after a sensitive key reads as a secret.\n const at = path.length > 0 ? ` at \"${path.join(\".\")}\"` : \"\";\n return unavailableValue(\n `${what} is unavailable: the run journal holds it redacted${at}`,\n );\n }\n if (Array.isArray(value)) {\n return value.map((entry, index) =>\n redactedLeavesUnavailable(entry, what, [...path, index]),\n );\n }\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n redactedLeavesUnavailable(entry, what, [...path, key]),\n ]),\n );\n}\n\nfunction journaledTriggerPayload(raw: string | null): unknown {\n return journaledValue(raw, \"The trigger payload\");\n}\n\nconst ATTACHMENT_REF_TEXT = /\"(attachment:\\/\\/[^\"\\\\]*)\"/g;\n\n// What a suspended run's journal hands its resume: the steps it carries,\n// the step that waits, and the attachment refs its outputs hold.\nfunction carriedFromJournal(rows: StepExecutionRow[]): {\n carried: Map<string, CarriedStep>;\n waitingStepId: string | undefined;\n nextOrdinal: number;\n attachmentRefs: Set<string>;\n} {\n const carried = new Map<string, CarriedStep>();\n const attachmentRefs = new Set<string>();\n let waitingStepId: string | undefined;\n let nextOrdinal = 0;\n for (const row of rows) {\n nextOrdinal = Math.max(nextOrdinal, row.ordinal + 1);\n // Scanned as text: the outputs are parsed only when a step reads them.\n for (const match of row.output?.matchAll(ATTACHMENT_REF_TEXT) ?? []) {\n attachmentRefs.add(match[1]!);\n }\n const what = `Output of step \"${row.step_key}\"`;\n switch (row.status) {\n case \"WAITING\":\n waitingStepId = row.step_id;\n break;\n case \"SUCCEEDED\":\n case \"REPLAYED\":\n carried.set(row.step_id, {\n status: row.status,\n port: row.port,\n output: () => journaledValue(row.output, what),\n });\n break;\n case \"FAILED\":\n carried.set(row.step_id, {\n status: \"FAILED\",\n port: \"error\",\n output: () => undefined,\n error: row.error ?? \"\",\n });\n break;\n case \"SKIPPED\":\n // Only an author's pass carries a port; an unreached skip is redecided.\n if (row.port) {\n carried.set(row.step_id, {\n status: \"SKIPPED\",\n port: row.port,\n output: () => null,\n });\n }\n break;\n }\n }\n return { carried, waitingStepId, nextOrdinal, attachmentRefs };\n}\n\n/** The runtime a host composes: one instance, its lifetime the host's. */\nexport function createWorkflowRuntime(\n deps: WorkflowRuntimeHostDeps,\n): WorkflowRuntimeService {\n return new WorkflowRuntimeService(deps);\n}\n\n// A run's attachments come from its trigger's document, the documents its\n// steps were handed, and the files its own steps wrote. Journaled outputs a\n// rerun or test replays count as written: an earlier run of this workflow\n// already wrote or was allowed to read every ref in them.\nfunction attachmentOrigins(\n triggerPayload: unknown,\n handed: ReadonlySet<string>,\n replayed?: unknown,\n): RunAttachmentOrigins {\n const written = new Set<string>();\n collectAttachmentRefs(replayed, written);\n return {\n documentIds: () => [...triggerDocumentIds(triggerPayload), ...handed],\n written,\n };\n}\n\nfunction collectAttachmentRefs(value: unknown, found: Set<string>): void {\n if (typeof value === \"string\") {\n if (value.startsWith(\"attachment://\")) found.add(value);\n } else if (Array.isArray(value)) {\n for (const entry of value) collectAttachmentRefs(entry, found);\n } else if (value instanceof Map) {\n for (const entry of value.values()) collectAttachmentRefs(entry, found);\n } else if (typeof value === \"object\" && value !== null) {\n for (const entry of Object.values(value))\n collectAttachmentRefs(entry, found);\n }\n}\n\nfunction operationForActionType(\n module: DocumentModelModule,\n actionType: string,\n) {\n const structured = operationsByActionType(module);\n const storedName =\n structured.size === 0 ? actionType : structured.get(actionType)?.storedName;\n return module.documentModel.global.specifications\n .at(-1)\n ?.modules.flatMap((specModule) => specModule.operations)\n .find((operation) => operation.name === storedName);\n}\n","// Workflow execution is a SINGLETON pinned to one reactor (multi-reactor plan,\n// agreed decision 3). Non-Node reactors cannot compose the engine at all — it\n// forks child processes — so the real hazard is TWO NODE REPLICAS over one\n// journal, which is not a theoretical one: `WorkflowRunStore.create` fails\n// every RUNNING run when the journal opens, and the runtime's start admits\n// every PENDING one, skipping only THIS process's `runsInFlight`. A second\n// replica booting therefore fails the first replica's live runs, runs its\n// queued ones a second time, and then both of them arm every trigger.\n//\n// This is that guard, made structural rather than documented: a durable claim\n// on the run journal's own database, taken before the runtime is built. One\n// row, one owner, a heartbeat, and takeover once the lease expires.\n//\n// A dedicated table rather than the `trigger_state.lease_owner` /\n// `lease_expires_at` columns: those are PER TRIGGER, which is the wrong\n// granularity (the sweeps and the supervisor are per PROCESS), and a lease is\n// not trigger state — it outlives every row in that table. They stay in the\n// schema, always null and unread.\nimport type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport { sql } from \"kysely\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport { hostname } from \"node:os\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst logger = childLogger([\"workflow\", \"runtime\", \"singleton\"]);\n\n/**\n * Names this process as the workflow singleton's owner.\n *\n * Set it to a STABLE name per deployment slot (`switchboard-0`, the\n * StatefulSet pod name, the Render service id). The owner name is the\n * operator's contract: a restart under the same name re-claims its own lease\n * once the old heartbeat is stale instead of waiting out\n * {@link SINGLETON_LEASE_TTL_MS}.\n *\n * Unset, the owner is derived from a STABLE identity — the hostname and a\n * fingerprint of the journal's own storage location ({@link\n * AcquireSingletonOptions.storageId}) — not from the pid and a random suffix.\n * A random per-process owner meant every unclean kill locked the next boot out\n * for the whole {@link SINGLETON_LEASE_TTL_MS}: the dead process's lease was\n * nobody's to re-claim, and `release()` never ran. One deployment slot\n * restarting is the common case and it has to be quick; a genuine second\n * replica still differs, by hostname or by the journal it points at.\n */\nexport const WORKFLOW_SINGLETON_OWNER_ENV = \"PH_WORKFLOWS_SINGLETON_OWNER\";\n\n/** How long a claim stays valid without a heartbeat. */\nexport const SINGLETON_LEASE_TTL_MS = 60_000;\n\n/** How often the holder renews it; a third of the TTL, so two renewals may be\n * lost (a GC pause, a slow database) before anyone may take over. */\nexport const SINGLETON_HEARTBEAT_MS = SINGLETON_LEASE_TTL_MS / 3;\n\n/**\n * How long the holder's heartbeat must have been silent before a claim under\n * the SAME owner name takes the lease over, short of its expiry. Two renewal\n * periods: a live holder renews well inside it, and its self-fence fires\n * before it passes.\n */\nexport const SINGLETON_STALE_HEARTBEATS = 2;\n\n/** The one row. The table holds a single lease, named rather than keyed by a\n * magic empty string, so a `SELECT *` reads legibly in an operator's shell. */\nconst LEASE_ID = \"workflow-runtime\";\n\n// Timestamps are the database's own clock: two hosts never compare their\n// process clocks against each other.\ninterface SingletonLeaseRow {\n id: string;\n owner: string;\n /** Random per claim, never configured: two processes under one stable\n * owner name still hold different instances. */\n instance: string;\n acquired_at: Date;\n heartbeat_at: Date;\n expires_at: Date;\n}\n\n// Not `singleton_lease`: an unreleased branch build created that name with\n// text timestamps and no instance column, which CREATE IF NOT EXISTS would\n// keep and every claim would then fail on.\ninterface SingletonLeaseDB {\n workflow_singleton: SingletonLeaseRow;\n}\n\nconst dbNow = () => sql<Date>`now()`;\nconst dbNowPlus = (ms: number) =>\n sql<Date>`now() + ${ms} * interval '1 millisecond'`;\n\n/** Another live process holds the singleton. The refusal is the point: a host\n * that cannot own workflow execution must not compose the engine. */\nexport class WorkflowSingletonConflictError extends Error {\n constructor(\n readonly owner: string,\n readonly expiresAt: string,\n readonly wouldBe: string,\n ) {\n super(\n `Workflow execution is a singleton and \"${owner}\" holds it until ` +\n `${expiresAt}; this process (\"${wouldBe}\") must not compose the ` +\n \"workflow runtime. Two replicas over one run journal fail each \" +\n \"other's live runs and arm every trigger twice. Run workflows on \" +\n `exactly one reactor, or set ${WORKFLOW_SINGLETON_OWNER_ENV} to the ` +\n \"same stable owner name on the slot that owns them so a restart \" +\n \"re-claims its own lease.\",\n );\n this.name = \"WorkflowSingletonConflictError\";\n }\n}\n\n/**\n * Why a holder stopped owning workflow execution.\n *\n * - `taken`: a renewal matched no row, so another claim holds the lease\n * (`heldBy` names it when the row still exists).\n * - `unrenewable`: no renewal landed for long enough that another claim could\n * take it over; none was seen to.\n */\nexport type WorkflowSingletonLoss =\n | { reason: \"taken\"; heldBy: string | undefined }\n | { reason: \"unrenewable\"; silentMs: number };\n\n/** A held claim, renewed from the moment it is taken. The host releases it on\n * shutdown, so the next boot does not wait out the TTL. */\nexport interface WorkflowSingletonLease {\n readonly owner: string;\n /** Renews once; false when the lease is no longer ours. */\n heartbeat(): Promise<boolean>;\n /** Stops renewing and drops the row if it is still ours. */\n release(): Promise<void>;\n}\n\nexport interface AcquireSingletonOptions {\n relationalDb: IRelationalDb;\n logger?: ILogger;\n /** Defaults to {@link WORKFLOW_SINGLETON_OWNER_ENV}, then\n * `<hostname>/<storageId fingerprint>`. */\n owner?: string;\n /**\n * Where this host's journal lives — a Postgres URL, an absolute PGlite\n * directory — as the stable half of the default owner name. Hashed, so a\n * connection string's credentials never reach the lease row or a log line.\n *\n * It is what separates two hosts that share a hostname but not a journal,\n * and it is stable across restarts, which is the whole point.\n */\n storageId?: string;\n ttlMs?: number;\n heartbeatMs?: number;\n /** Called once, when this process stops owning workflow execution. */\n onLost?: (loss: WorkflowSingletonLoss) => void;\n /**\n * Whether a holder that cannot renew reports itself lost before anyone\n * could take over. On by default. Off for a journal no other process can\n * open (embedded PGlite): nothing can take the lease, so a stalled renewal\n * is only logged.\n */\n selfFence?: boolean;\n /**\n * The journal is embedded and this process has it open, so nobody else can\n * be alive behind the lease: a restart takes back its own at once. Waiting\n * for the heartbeat to go stale is for a holder that might still be running.\n */\n exclusive?: boolean;\n env?: Record<string, string | undefined>;\n}\n\n/**\n * The owner name this process claims under.\n *\n * `<hostname>/<storage fingerprint>`, so it is the same name on every boot of\n * one deployment slot — a restart re-claims its OWN lease once the dead\n * process's heartbeat is stale, rather than waiting out the TTL — and a different\n * name on any host or journal that is genuinely somebody else.\n *\n * The storage location is hashed, never printed: it can be a Postgres URL with\n * credentials in it, and the owner name goes into a database row an operator\n * reads and into every log line about the lease.\n *\n * The residual case a stable name cannot tell apart is two processes on ONE\n * host over ONE journal, which is a misconfiguration those two already share\n * (one read-model directory, one run journal). It is not silent: the loser's\n * heartbeat finds the lease taken and says so by name.\n */\nexport function singletonOwnerName(\n env: Record<string, string | undefined> = process.env,\n storageId?: string,\n): string {\n const configured = env[WORKFLOW_SINGLETON_OWNER_ENV]?.trim();\n if (configured) return configured;\n return `${hostname()}/${storageFingerprint(storageId)}`;\n}\n\nfunction storageFingerprint(storageId: string | undefined): string {\n const source = storageId?.trim();\n if (!source) return \"default\";\n return createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 12);\n}\n\nasync function ensureTable(db: IRelationalDb<SingletonLeaseDB>): Promise<void> {\n await db.schema\n .createTable(\"workflow_singleton\")\n .addColumn(\"id\", \"text\", (col) => col.primaryKey())\n .addColumn(\"owner\", \"text\", (col) => col.notNull())\n .addColumn(\"instance\", \"text\", (col) => col.notNull())\n .addColumn(\"acquired_at\", \"timestamptz\", (col) => col.notNull())\n .addColumn(\"heartbeat_at\", \"timestamptz\", (col) => col.notNull())\n .addColumn(\"expires_at\", \"timestamptz\", (col) => col.notNull())\n .ifNotExists()\n .execute();\n}\n\n// unique_violation, duplicate_object (the table's row type) and\n// duplicate_table/schema: two hosts on a fresh database both passed IF NOT\n// EXISTS, and the loser hit the catalog. The schema and the table can each\n// race once, so three attempts suffice.\nconst DDL_ATTEMPTS = 3;\nconst CONCURRENT_DDL_CODES = new Set([\"23505\", \"42710\", \"42P06\", \"42P07\"]);\n\nfunction isConcurrentDdl(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return typeof code === \"string\" && CONCURRENT_DDL_CODES.has(code);\n}\n\nasync function openLeaseTable(\n relationalDb: IRelationalDb,\n): Promise<IRelationalDb<SingletonLeaseDB>> {\n const open = async () => {\n const db = (await relationalDb.createNamespace(\n \"workflow_runtime\",\n )) as IRelationalDb<SingletonLeaseDB>;\n await ensureTable(db);\n return db;\n };\n for (let attempt = 1; ; attempt++) {\n try {\n return await open();\n } catch (error) {\n if (attempt >= DDL_ATTEMPTS || !isConcurrentDdl(error)) throw error;\n }\n }\n}\n\n/**\n * Claims the workflow singleton, or refuses.\n *\n * Three steps, each one a single statement whose own outcome is the claim — a\n * prior `SELECT` would be a race:\n *\n * 1. `INSERT … ON CONFLICT DO NOTHING RETURNING` — the first ever boot.\n * 2. `UPDATE … WHERE expires_at <= now OR (owner = me AND heartbeat stale)\n * RETURNING` — a dead lease taken over once it has expired, or our own\n * slot's lease once its holder stopped renewing (a restart under a stable\n * owner name), never a live holder's. Either way the row gets this claim's\n * instance, so the previous holder's heartbeat and release no longer\n * match.\n * 3. Neither matched: someone live holds it, and we refuse by name.\n */\nexport async function acquireWorkflowSingletonLease(\n options: AcquireSingletonOptions,\n): Promise<WorkflowSingletonLease> {\n const log = options.logger ?? logger;\n const ttlMs = options.ttlMs ?? SINGLETON_LEASE_TTL_MS;\n const heartbeatMs = options.heartbeatMs ?? SINGLETON_HEARTBEAT_MS;\n const staleMs = heartbeatMs * SINGLETON_STALE_HEARTBEATS;\n const owner =\n options.owner ?? singletonOwnerName(options.env, options.storageId);\n const instance = randomUUID();\n\n const db = await openLeaseTable(options.relationalDb);\n\n const stamps = () => ({\n heartbeat_at: dbNow(),\n expires_at: dbNowPlus(ttlMs),\n });\n\n const claim = async (): Promise<boolean> => {\n const inserted = await db\n .insertInto(\"workflow_singleton\")\n .values({\n id: LEASE_ID,\n owner,\n instance,\n acquired_at: dbNow(),\n ...stamps(),\n })\n .onConflict((oc) => oc.column(\"id\").doNothing())\n .returning(\"owner\")\n .executeTakeFirst();\n if (inserted !== undefined) return true;\n const taken = await db\n .updateTable(\"workflow_singleton\")\n .set({ owner, instance, acquired_at: dbNow(), ...stamps() })\n .where(\"id\", \"=\", LEASE_ID)\n .where((eb) =>\n eb.or([\n eb(\"expires_at\", \"<=\", dbNow()),\n // Never from a live holder, even under our own name: the new\n // process opening the journal would fail the old one's live runs.\n eb.and([\n eb(\"owner\", \"=\", owner),\n eb(\n \"heartbeat_at\",\n \"<=\",\n dbNowPlus(options.exclusive ? 0 : -staleMs),\n ),\n ]),\n ]),\n )\n .returning(\"owner\")\n .executeTakeFirst();\n return taken !== undefined;\n };\n\n const claimSentAt = performance.now();\n if (!(await claim())) {\n const held = await db\n .selectFrom(\"workflow_singleton\")\n .selectAll()\n .where(\"id\", \"=\", LEASE_ID)\n .executeTakeFirst();\n throw new WorkflowSingletonConflictError(\n held?.owner ?? \"unknown\",\n held ? new Date(held.expires_at).toISOString() : \"unknown\",\n owner,\n );\n }\n log.info(\n `Workflow singleton claimed by \"${owner}\" (lease ${ttlMs}ms, renewed every ${heartbeatMs}ms)`,\n );\n\n // Local monotonic time, never compared with the database's: only how long\n // this process has gone without a renewal it knows landed.\n const localNow = () => performance.now();\n const tickMs = heartbeatMs / 4;\n // Before anyone may take the lease: a stale same-owner claim, or expiry.\n const takeableAfterMs = Math.min(staleMs, ttlMs);\n const fenceMs = takeableAfterMs - Math.min(heartbeatMs, ttlMs) / 2;\n const selfFence = options.selfFence ?? true;\n let renewedAt = claimSentAt;\n let renewFailed = false;\n let inFlight: Promise<boolean> | undefined;\n let timer: NodeJS.Timeout | undefined;\n let lost = false;\n // Only a renewal that matched no row proves another claim holds it.\n let takenOver = false;\n let releasing = false;\n\n const stop = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n };\n\n const markLost = (loss: WorkflowSingletonLoss) => {\n if (lost) return;\n lost = true;\n stop();\n log.error(\n loss.reason === \"taken\"\n ? `Workflow singleton lease of \"${owner}\" was taken over by ` +\n `\"${loss.heldBy ?? \"nobody\"}\"; this process no longer owns ` +\n \"workflow execution and stops running it.\"\n : `Workflow singleton lease of \"${owner}\" could not be renewed for ` +\n `${Math.round(loss.silentMs)}ms, long enough that another process ` +\n \"could take it over (none was seen to); this process stops \" +\n \"running workflows.\",\n );\n options.onLost?.(loss);\n };\n\n // Keyed on the instance as well as the owner: under a stable owner name an\n // old process must never renew a newer process's claim.\n const renew = async (): Promise<boolean> => {\n const sentAt = localNow();\n const renewed = await db\n .updateTable(\"workflow_singleton\")\n .set(stamps())\n .where(\"id\", \"=\", LEASE_ID)\n .where(\"owner\", \"=\", owner)\n .where(\"instance\", \"=\", instance)\n .returning(\"owner\")\n .executeTakeFirst();\n if (renewed !== undefined) {\n renewedAt = sentAt;\n return true;\n }\n if (releasing || lost) return false;\n let heldBy: string | undefined;\n try {\n const held = await db\n .selectFrom(\"workflow_singleton\")\n .select(\"owner\")\n .where(\"id\", \"=\", LEASE_ID)\n .executeTakeFirst();\n heldBy = held?.owner;\n } catch {\n heldBy = undefined;\n }\n takenOver = true;\n markLost({ reason: \"taken\", heldBy });\n return false;\n };\n\n const heartbeat = (): Promise<boolean> => {\n if (lost) return Promise.resolve(false);\n inFlight ??= renew().finally(() => {\n inFlight = undefined;\n });\n return inFlight;\n };\n\n // From the claim, not from the host's start: composing can outlast the TTL.\n timer = setInterval(() => {\n if (lost || releasing) return;\n const silentMs = localNow() - renewedAt;\n // Checked even while a renewal hangs: journal writes are best-effort, so\n // a holder that cannot renew would otherwise keep running workflows.\n if (selfFence && silentMs >= fenceMs) {\n markLost({ reason: \"unrenewable\", silentMs });\n return;\n }\n if (inFlight) return;\n // A failed renewal retries every tick rather than every period.\n if (!renewFailed && silentMs < heartbeatMs - tickMs / 2) return;\n heartbeat().then(\n () => {\n renewFailed = false;\n },\n (error: unknown) => {\n renewFailed = true;\n log.warn(\"Workflow singleton heartbeat failed: @error\", error);\n },\n );\n }, tickMs);\n // The claim must not be what keeps the process alive.\n timer.unref();\n\n return {\n owner,\n heartbeat,\n async release() {\n releasing = true;\n stop();\n if (takenOver) return;\n // A renewal answered after the DELETE would read as a lost lease.\n if (inFlight) {\n await Promise.race([\n inFlight.catch(() => false),\n new Promise((resolve) => setTimeout(resolve, tickMs).unref()),\n ]);\n }\n // After a self-fence too: the DELETE matches only this instance's row,\n // and leaving it costs the next boot under another owner the TTL.\n try {\n await db\n .deleteFrom(\"workflow_singleton\")\n .where(\"id\", \"=\", LEASE_ID)\n .where(\"owner\", \"=\", owner)\n .where(\"instance\", \"=\", instance)\n .execute();\n } catch (error) {\n // The lease expires on its own; a failed release costs the next boot\n // the TTL, nothing more.\n log.warn(\n \"Could not release the workflow singleton lease: @error\",\n error,\n );\n }\n },\n };\n}\n","// The runtime's operation intake, as a reactor read model: the cursor beneath\n// it makes an event written while the runtime was down catch up, not vanish.\nimport {\n BaseReadModel,\n defaultReadModelIndexingConfig,\n isPurgeMarker,\n type DocumentViewDatabase,\n type IConsistencyTracker,\n type IOperationIndex,\n type IWriteCache,\n type ReadModelRegistrationStage,\n} from \"@powerhousedao/reactor\";\nimport type { OperationWithContext } from \"document-model\";\nimport type { Kysely } from \"kysely\";\nimport type { WorkflowHealth, WorkflowRuntimeService } from \"./service.js\";\n\nexport const WORKFLOW_TRIGGERS_READ_MODEL = \"workflow-triggers\";\n\n// Post-ready, so a piece that reads the document that fired it sees the state\n// that fired it. The host registers with this; the engine decides it.\nexport const WORKFLOW_TRIGGERS_READ_MODEL_STAGE: ReadModelRegistrationStage =\n \"post_ready\";\n\n/**\n * What a processor on the runtime's host reads through\n * `getReadModel(WORKFLOW_TRIGGERS_READ_MODEL)`: whether a workflow's trigger\n * is armed, failing or parked. The model exists only where the runtime runs.\n */\nexport interface WorkflowHealthReader {\n health(workflowId: string): Promise<WorkflowHealth>;\n}\n\n// Hands every batch to onOperations and keeps the reactor's ViewState cursor.\n// Triggers fire forward only, so a first registration starts at head, not zero.\nexport class WorkflowTriggersReadModel\n extends BaseReadModel\n implements WorkflowHealthReader\n{\n constructor(\n db: Kysely<DocumentViewDatabase>,\n operationIndex: IOperationIndex,\n writeCache: IWriteCache,\n consistencyTracker: IConsistencyTracker,\n private readonly runtime: WorkflowRuntimeService,\n ) {\n super(db, operationIndex, writeCache, consistencyTracker, {\n readModelId: WORKFLOW_TRIGGERS_READ_MODEL,\n rebuildStateOnInit: false,\n indexing: defaultReadModelIndexingConfig,\n startFrom: \"head\",\n // Runs live on the relational handle, and a fire must not hold a lock.\n purgeFence: \"skip\",\n });\n }\n\n health(workflowId: string): Promise<WorkflowHealth> {\n return this.runtime.workflowHealth(workflowId);\n }\n\n // The only await that matters here: onOperations journals every matched fire\n // before it resolves, so the cursor a sweep moves never passes a lost event.\n protected override async commitOperations(\n items: OperationWithContext[],\n ): Promise<void> {\n const markers = items.filter((item) => isPurgeMarker(item.operation));\n if (markers.length === 0) {\n await this.runtime.onOperations(items);\n return;\n }\n await this.runtime.onOperations(\n items.filter((item) => !isPurgeMarker(item.operation)),\n );\n await this.runtime.onDocumentsPurged(markers);\n }\n}\n"],"x_google_ignoreList":[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,gBAAgB;AACtB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAE3B,MAAM,wBAAQ,IAAI,IAAoB;AACtC,MAAM,2BAAW,IAAI,IAAqC;AAO1D,eAAe,QACb,KACA,MACA,OACyB;CACzB,MAAM,SAAS,MAAM,IAAI,GAAG;CAC5B,IAAI,CAAC,SAAS,UAAU,OAAO,YAAY,KAAK,IAAI,GAAG,OAAO,OAAO;CACrE,MAAM,UAAU,SAAS,IAAI,GAAG;CAChC,IAAI,SAAS,OAAO;CACpB,MAAM,UAAU,KAAK,CAAC,CACnB,MAAM,UAAU;EAEf,IAAI,MAAM,SAAS,eAAe;GAChC,MAAM,MAAM,MAAM,SAAS,WAAW,gBAAgB;GACtD,MAAM,IAAI,KAAK;IAAE;IAAO,WAAW,KAAK,IAAI,IAAI;GAAI,CAAC;EACvD;EACA,OAAO;CACT,CAAC,CAAC,CACD,cAAc,SAAS,OAAO,GAAG,CAAC;CACrC,SAAS,IAAI,KAAK,OAAO;CACzB,OAAO;AACT;AAEA,eAAe,QACb,KACA,WACA,SAC4C;CAC5C,MAAM,WAAW,MAAM,MAAM,KAAK;EA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