@powerhousedao/reactor-workflow 6.2.3-dev.32 → 6.2.3-dev.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["logger","up","clientAuth","action","trigger","logger","createAction","logger","parseScheduleConfig","parseSharedSchedule","up","trim","logger","logger","logger","targetOf","parseScheduleConfig","asRecord","connectionActions","parseScheduleConfig","workflowActions"],"sources":["../src/pieces/activepieces/piece-versions.ts","../src/reactor/attachment-port.ts","../src/reactor/package-name.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/reactor-port.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/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/store.ts","../src/reactor/run-cursor.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/service.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.\nconst LISTED_TTL_MS = 5 * 60_000;\nconst ABSENT_TTL_MS = 5 * 60_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 { AttachmentPort } from \"../pieces/index.js\";\nimport { FileTooLargeError, maxFileBytes } from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport { open, readFile, rm } from \"node:fs/promises\";\n\nconst logger = childLogger([\"workflow\", \"attachments\"]);\n\n// The slice of IAttachmentClient this needs, declared structurally so the\n// subgraph does not depend on the attachments package's types.\nexport interface AttachmentClientLike {\n upload(input: {\n file: Blob;\n fileName?: string;\n mimeType?: string;\n }): Promise<{ ref?: string } & Record<string, unknown>>;\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: { documentId: string; ref: string }): Promise<{\n header: { sizeBytes?: number; mimeType?: string; fileName?: string };\n body: ReadableStream<Uint8Array>;\n }>;\n}\n\nfunction refOf(result: Record<string, unknown>): string {\n const direct = result.ref;\n if (typeof direct === \"string\") return direct;\n // Some client versions nest the reference under the reservation.\n const nested = (result.reservation as { ref?: unknown } | undefined)?.ref;\n if (typeof nested === \"string\") return nested;\n throw new Error(\"The attachment store returned no reference for the upload\");\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 function createAttachmentPort(\n client: AttachmentClientLike,\n // Attachment reads are authorized against a document, and a step's refs come\n // from its own run journal: the workflow document is what vouches for them.\n documentIdFor: () => string | undefined,\n // Whether that document really references the ref. A step carries no caller,\n // so this relationship is all that stands between it and any known blob.\n canReadRef: (documentId: string, ref: string) => Promise<boolean>,\n): AttachmentPort {\n return {\n async read(ref, destPath) {\n const documentId = 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 canReadRef(documentId, ref))) {\n throw new Error(\n `Cannot resolve ${ref}: workflow document \"${documentId}\" does not reference it`,\n );\n }\n const limit = maxFileBytes();\n const { header, body } = await client.download({ documentId, ref });\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 =\n header.mimeType !== undefined && header.mimeType !== \"\"\n ? header.mimeType\n : undefined;\n return { fileName: header.fileName, contentType };\n },\n\n async write(file) {\n const bytes = await readFile(file.path);\n const result = await client.upload({\n file: new Blob([new Uint8Array(bytes)], {\n type: file.contentType ?? \"application/octet-stream\",\n }),\n fileName: file.fileName,\n mimeType: file.contentType,\n });\n const ref = refOf(result);\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","// 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 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 client_secret_ref: string;\n code_verifier: string | null;\n redirect_uri: string;\n token_url: string;\n authorization_method: string | null;\n return_url: 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 provider's whole token response; pieces read fields off it.\n data: Record<string, unknown>;\n}\n\nexport class OAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OAuthError\";\n }\n}\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\", (col) => col.notNull())\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(\"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}\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 clientSecretRef: string;\n redirectUri: string;\n returnUrl?: string;\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 state = base64url(randomBytes(32));\n const pkce = method.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 if (method.scope.length > 0) params.set(\"scope\", method.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: fillOAuthUrl(method.tokenUrl, input.props),\n authorization_method: method.authorizationMethod ?? null,\n return_url: input.returnUrl ?? 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 );\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 clientSecret: string,\n): { form: Record<string, string>; headers: Record<string, string> } {\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\" | \"authorization_method\" | \"redirect_url\"\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 data: { ...previous?.data, ...response },\n };\n}\n\nexport async function exchangeCode(\n attempt: OAuthAttemptRow,\n code: string,\n clientSecret: string,\n egress?: EgressPolicy,\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 egress,\n );\n return tokenSetFrom(response, {\n token_url: attempt.token_url,\n authorization_method: method,\n redirect_url: attempt.redirect_uri,\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 OAuthError(\"Stored OAuth2 token is malformed; reconnect\");\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.\n refreshIfDue(source: OAuthConnectionSource): 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 ) {}\n\n refreshIfDue(source: OAuthConnectionSource): Promise<void> {\n const refOf = (name: string) =>\n source.secretRefs?.find((entry) => entry.name === name)?.ref;\n const tokenRef = refOf(OAUTH_TOKEN);\n const secretRef = refOf(OAUTH_CLIENT_SECRET);\n const clientId = source.config?.[OAUTH_CLIENT_ID];\n if (!tokenRef || !secretRef || typeof clientId !== \"string\") {\n return Promise.resolve();\n }\n let pending = this.inFlight.get(tokenRef);\n if (!pending) {\n pending = this.refresh(tokenRef, secretRef, clientId).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 secretRef: string,\n clientId: string,\n ): Promise<void> {\n const store = await this.secrets();\n const tokens = parseTokenSet(await store.get(tokenRef));\n if (!tokenDue(tokens, Math.round(Date.now() / 1000))) return;\n const auth = clientAuth(\n tokens.authorization_method,\n clientId,\n await store.get(secretRef),\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 this.egress,\n );\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\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 new OAuthError(\n `Refreshing the OAuth2 token failed; reconnect: ${detail}`,\n );\n }\n // A sign-in that landed meanwhile is newer than this refresh.\n const current = parseTokenSet(await store.get(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","// 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\n// Named where it is enforced: this is the one piece served ctx.reactor, and\n// the blocks below are the surface that port exists for.\nimport { blockKey } from \"@powerhousedao/pieces-framework/block-type\";\nimport { REACTOR_PORT_PIECE } from \"../pieces/index.js\";\n\nexport const REACTOR_PIECE = REACTOR_PORT_PIECE;\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 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.\nexport function fromSample(value: unknown, depth = 0): OutputTreeNode[] {\n if (value === null || typeof value !== \"object\" || depth > MAX_DEPTH) {\n return [];\n }\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>);\n return 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);\n return {\n name,\n type: kind,\n ...(children.length > 0 ? { children } : {}),\n };\n });\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// Envelope both document blocks return; state children come from the model.\nexport function documentBlockTree(\n stateChildren: OutputTreeNode[],\n): OutputTreeNode[] {\n return [\n leaf(\"documentId\", \"PHID!\"),\n leaf(\"documentType\", \"String!\"),\n leaf(\"name\", \"String\"),\n {\n name: \"state\",\n type: \"object\",\n description: \"Document global state after the actions applied\",\n ...(stateChildren.length > 0 ? { children: stateChildren } : {}),\n },\n ];\n}\n\nexport function documentGetTree(\n stateChildren: OutputTreeNode[],\n): OutputTreeNode[] {\n return [\n ...documentBlockTree(stateChildren).filter((node) => node.name !== \"state\"),\n leaf(\"slug\", \"String\"),\n {\n name: \"state\",\n type: \"object\",\n description: \"Document global state as read\",\n ...(stateChildren.length > 0 ? { children: stateChildren } : {}),\n },\n ];\n}\n\nexport function documentFindTree(): OutputTreeNode[] {\n return [\n leaf(\"count\", \"Int!\"),\n {\n name: \"documents\",\n type: \"array\",\n children: [\n leaf(\"documentId\", \"PHID!\"),\n leaf(\"documentType\", \"String!\"),\n leaf(\"name\", \"String\"),\n leaf(\"slug\", \"String\"),\n ],\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\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/flows 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, calling other platform flows.\n \"@activepieces/piece-todos\",\n \"@activepieces/piece-tables\",\n \"@activepieces/piece-subflows\",\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 { 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\";\nconst CACHE_TTL_MS = 60 * 60 * 1000;\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\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 // 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 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\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 ? fetchJson(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 ${source?.baseUrl ?? \"?\"} did not answer: ${String(fromRegistry.reason)}`,\n );\n }\n if (fromCloud.status === \"rejected\") {\n if (registry.length === 0) throw asError(fromCloud.reason);\n logger.warn(`Serving registry pieces only: ${String(fromCloud.reason)}`);\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\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 registry as CatalogSuggestionEntry[],\n cloud as CatalogSuggestionEntry[],\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[]): 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 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[]),\n toSummaries(lists.cloud as CatalogEntry[]),\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 configured registry answers for its own pieces, and\n// anything it does not have comes from the cloud.\n// Only a 404 is the configured registry saying it does not serve that name.\n\n// Anything else -- a 500, a timeout, a refused connection -- is the registry\n// failing to answer, and falling through on that would quietly hand a name the\n// deployment reserved for its own registry to the public cloud instead.\nfunction registrySilentOn(error: unknown): boolean {\n return error instanceof CatalogStatusError && error.status === 404;\n}\n\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 if (!registrySilentOn(error)) throw error;\n logger.debug(\n `${source.baseUrl} does not serve \"${packageName}\": ${String(error)}`,\n );\n }\n }\n return fetchJson(pieceUrl(packageName, version));\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() + CACHE_TTL_MS });\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() + CACHE_TTL_MS,\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() + CACHE_TTL_MS,\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 { BlockSearchHit } 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 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's blocks as search hits, so a block the reactor ships is findable\n// whether or not the published catalog answered.\nexport function localSearchHits(\n descriptor: PieceDescriptor,\n pieceName: string,\n version: string,\n): BlockSearchHit[] {\n const pieceDisplayName = descriptor.displayName || pieceName;\n const logoUrl = descriptor.logoUrl ?? \"\";\n return [\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}\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 // 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 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","// Action/trigger name search over the whole catalog. The index is built\n// lazily from one list request (suggestionType=ACTION_AND_TRIGGER) and cached.\nimport {\n fetchCatalogWithSuggestions,\n reasonOf,\n type CatalogSuggestionEntry,\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 type BlockSearchStatus = \"ready\" | \"indexing\" | \"error\";\n\nexport interface BlockSearchResult {\n status: BlockSearchStatus;\n hits: BlockSearchHit[];\n // Number of pieces the index covers; 0 while indexing.\n indexedPieces: number;\n error: string | null;\n}\n\ninterface IndexEntry {\n hit: BlockSearchHit;\n // Lower-cased searchable text, in ranking order.\n name: string;\n description: string;\n piece: string;\n}\n\nexport interface BlockSearchIndex {\n entries: IndexEntry[];\n pieces: number;\n}\n\nconst INDEX_TTL_MS = 60 * 60 * 1000;\nconst DEFAULT_LIMIT = 30;\nconst MAX_LIMIT = 100;\n\nexport function buildSearchIndex(\n raw: CatalogSuggestionEntry[],\n): BlockSearchIndex {\n const entries: IndexEntry[] = [];\n let pieces = 0;\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 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 const displayName = item.displayName ?? item.name;\n const description = item.description ?? \"\";\n entries.push({\n hit: {\n pieceName,\n pieceVersion,\n name: item.name,\n pieceDisplayName,\n logoUrl,\n displayName,\n description,\n kind,\n strategy: kind === \"trigger\" ? (item.type ?? null) : null,\n ...reasonOf(\n pieceUnsupported ??\n (kind === \"trigger\" ? unsupportedTrigger(item) : undefined),\n ),\n },\n name: `${displayName} ${item.name}`.toLowerCase(),\n description: description.toLowerCase(),\n piece: pieceDisplayName.toLowerCase(),\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 += 1;\n }\n return { entries, pieces };\n}\n\n// Pieces a reactor package ships, indexed the same way. They are handed in\n// rather than fetched: the catalog API has never heard of them.\nexport function indexFromHits(hits: BlockSearchHit[]): BlockSearchIndex {\n const pieces = new Set<string>();\n const entries = hits.map((hit) => {\n pieces.add(hit.pieceName);\n return {\n hit,\n name: `${hit.displayName} ${hit.name}`.toLowerCase(),\n description: hit.description.toLowerCase(),\n piece: hit.pieceDisplayName.toLowerCase(),\n };\n });\n return { entries, pieces: pieces.size };\n}\n\n// A piece this reactor installed wins its own name, the way it does in the\n// catalog: listing both would offer a versioned published block beside the\n// installed one, and picking the published block would bypass the copy that\n// actually runs.\nfunction merge(\n index: BlockSearchIndex | undefined,\n local: BlockSearchIndex | undefined,\n): BlockSearchIndex {\n const localEntries = local?.entries ?? [];\n const localNames = new Set(localEntries.map((entry) => entry.hit.pieceName));\n const published = (index?.entries ?? []).filter(\n (entry) => !localNames.has(entry.hit.pieceName),\n );\n const shadowed = new Set(\n (index?.entries ?? [])\n .map((entry) => entry.hit.pieceName)\n .filter((name) => localNames.has(name)),\n );\n return {\n entries: [...localEntries, ...published],\n // Each package counted once, so the total says how many pieces were\n // searched rather than how many listings were merged.\n pieces: (local?.pieces ?? 0) + (index?.pieces ?? 0) - shadowed.size,\n };\n}\n\n// Every query token must appear somewhere; hits rank by where the first\n// token lands: name prefix, then name, then piece name, then description.\nexport function searchIndex(\n index: BlockSearchIndex,\n query: string,\n limit = DEFAULT_LIMIT,\n): BlockSearchHit[] {\n const tokens = query.toLowerCase().split(/\\s+/).filter(Boolean);\n if (tokens.length === 0) return [];\n const scored: { score: number; entry: IndexEntry }[] = [];\n for (const entry of index.entries) {\n const haystack = `${entry.name} ${entry.piece} ${entry.description}`;\n if (!tokens.every((token) => haystack.includes(token))) continue;\n const first = tokens[0];\n const score = entry.name.startsWith(first)\n ? 0\n : entry.name.includes(first)\n ? 1\n : entry.piece.includes(first)\n ? 2\n : 3;\n scored.push({ score, entry });\n }\n scored.sort(\n (a, b) =>\n a.score - b.score ||\n a.entry.hit.displayName.localeCompare(b.entry.hit.displayName),\n );\n return scored\n .slice(0, Math.min(Math.max(limit, 1), MAX_LIMIT))\n .map(({ entry }) => entry.hit);\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// Never blocks on the index build: callers poll while status is \"indexing\".\n\n// The status describes the published catalog alone, because that is the half\n// that can be slow or unreachable. Local pieces are searched either way, so a\n// reactor with no network still finds the blocks it ships.\nexport function searchBlocks(\n query: string,\n limit?: number,\n local?: BlockSearchIndex,\n): BlockSearchResult {\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 hits: searchIndex(merge(undefined, local), query, limit),\n indexedPieces: local?.pieces ?? 0,\n error: message,\n };\n }\n if (!index.value) {\n return {\n status: \"indexing\",\n hits: searchIndex(merge(undefined, local), query, limit),\n indexedPieces: local?.pieces ?? 0,\n error: null,\n };\n }\n const merged = merge(index.value, local);\n return {\n status: \"ready\",\n hits: searchIndex(merged, query, limit),\n indexedPieces: merged.pieces,\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 { IPieceWorker } from \"../pieces/index.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport interface RunScope {\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}\n\nconst storage = new AsyncLocalStorage<RunScope>();\n\nexport function withRunScope<T>(\n scope: RunScope,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(scope, fn);\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 currentStepTest(): boolean {\n return storage.getStore()?.stepTest ?? false;\n}\n","// The host's half of `ctx.reactor`: the operations a package piece asks for,\n// run against this reactor through the subgraph's client.\n\n// Everything here is what could not cross the worker boundary — model modules\n// and their factories, drive nodes, a PHDocument's operations — so the piece\n// keeps the block's own semantics and the reactor stays on this side of it.\nimport type { WorkflowCaller, WorkflowRuntimeHostDeps } from \"./host.js\";\nimport { currentDocumentRecorder } from \"./run-scope.js\";\nimport type {\n ReactorCreateInput,\n ReactorDocumentSummary,\n ReactorExecuteInput,\n ReactorFindInput,\n ReactorModelDetail,\n ReactorModelSummary,\n ReactorPort,\n} from \"../pieces/index.js\";\nimport {\n createAction,\n withSignaturePolicy,\n type Action,\n type PHDocument,\n} from \"document-model\";\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\";\nconst DRIVE_DOCUMENT_TYPES = new Set([\n DRIVE_DOCUMENT_TYPE,\n \"powerhouse/reactor-drive\",\n]);\n\n// The index rejects an empty filter, so a typeless sweep asks per type; this\n// caps what each one contributes before the caller slices.\nconst FIND_PAGE_LIMIT = 100;\n\n// Design time resolves options for an editor, never edits documents: a piece\n// asking to write there is refused rather than authorized.\nconst DESIGN_TIME_WRITES_REFUSED =\n \"Reactor writes are not available while resolving design-time options\";\n\nconst DESIGN_TIME_CALLER_REQUIRED =\n \"Design-time reactor access requires an authenticated request\";\n\n// Base actions every document type accepts, beyond its model's own.\nconst BASE_ACTIONS = [\n {\n type: \"SET_NAME\",\n module: \"base\",\n inputSchema: \"input SetNameInput {\\n name: String!\\n}\",\n },\n];\n\ninterface DriveTarget {\n driveId: string;\n parentFolder?: string;\n}\n\n// The value at a dotted path inside a document's global state. Anything that\n// is not a plain object on the way down ends the walk: a path into a scalar is\n// a mismatch, not an error, because the documents being filtered are of one\n// type only by convention and the step cannot know every shape it will meet.\nfunction stateValueAt(document: PHDocument, path: string): unknown {\n const globalState = (document.state as Record<string, unknown>).global;\n let current: unknown = globalState;\n for (const segment of path.split(\".\")) {\n if (typeof current !== \"object\" || current === null) return undefined;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n// Compared as strings, so a step whose value came from an expression matches a\n// number in state: every expression resolves to text by the time it reaches\n// here, and `\"42\" !== 42` would make the match silently impossible.\nexport function matchesState(\n document: PHDocument,\n match: { path: string; value: string } | undefined,\n): boolean {\n if (!match) return true;\n const value = stateValueAt(document, match.path);\n if (typeof value === \"string\") return value === match.value;\n // Only the scalars a state field plausibly holds. A path landing on an\n // object, an array or nothing is a mismatch rather than an error — the\n // documents being filtered share a type only by convention, and the step\n // cannot know every shape it will meet.\n if (\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\"\n ) {\n return String(value) === match.value;\n }\n return false;\n}\n\nexport function documentSummary(\n document: PHDocument,\n withState: boolean,\n): ReactorDocumentSummary {\n const globalState = (document.state as Record<string, unknown>).global;\n const stateName =\n globalState && typeof globalState === \"object\"\n ? (globalState as Record<string, unknown>).name\n : undefined;\n return {\n documentId: document.header.id,\n documentType: document.header.documentType,\n // Models usually keep the display name in state; header name can lag.\n name:\n (typeof stateName === \"string\" && stateName) ||\n document.header.name ||\n \"\",\n slug: document.header.slug,\n ...(withState ? { state: globalState } : {}),\n };\n}\n\n// Reducer failures don't reject execute(): the operation is still recorded,\n// with the reason on operation.error and the state left exactly as it was.\n\n// So a dispatch that wrote nothing at all comes back looking like any other,\n// and the only thing standing between that and a step reporting success is\n// this. It fails the call instead, which is what the block needs: its payload\n// may be model output, and a silent no-op is the worst way to learn that.\n\n// Per scope, because an operation's index counts within its own scope. A tail\n// taken across all of them sorts one scope's indexes against another's, and a\n// document-scope CREATE_DOCUMENT at index 0 displaces the failed global\n// operation at index 0 that a fresh document's first dispatch leaves.\nfunction assertOperationsApplied(\n document: PHDocument,\n dispatched: readonly { scope?: string }[],\n): void {\n const perScope = new Map<string, number>();\n for (const action of dispatched) {\n const scope = action.scope ?? \"global\";\n perScope.set(scope, (perScope.get(scope) ?? 0) + 1);\n }\n const failed = [...perScope].flatMap(([scope, count]) =>\n [...(document.operations[scope] ?? [])]\n .sort((a, b) => a.index - b.index)\n .slice(-count)\n .filter((operation) => operation.error !== undefined),\n );\n if (failed.length === 0) return;\n // All of them: a payload a model wrote tends to fail a field at a time, and\n // naming only the first sends the author back for another run to find the\n // next. The reducer's own message carries the field and what it wanted.\n throw new Error(\n failed\n .map(\n (operation) =>\n `Action ${operation.action.type} failed: ${operation.error ?? \"unknown error\"}`,\n )\n .join(\"; \"),\n );\n}\n\nexport class SubgraphReactorPort implements ReactorPort {\n constructor(private readonly host: WorkflowRuntimeHostDeps) {}\n\n private get client() {\n return this.host.reactorClient;\n }\n\n async models(): Promise<ReactorModelSummary[]> {\n const page = await this.client.getDocumentModelModules();\n return page.results\n .map((module) => module.documentModel.global)\n .map((model) => ({ documentType: model.id, name: model.name }))\n .filter((entry) => entry.documentType)\n .sort((a, b) => a.documentType.localeCompare(b.documentType));\n }\n\n async model(documentType: string): Promise<ReactorModelDetail> {\n const module = await this.client.getDocumentModelModule(documentType);\n const model = module.documentModel.global;\n const latest = model.specifications.at(-1);\n return {\n documentType,\n name: model.name,\n stateSchema: latest?.state.global.schema ?? null,\n actions: [\n // flatMap rather than filter+map: an unnamed operation is dropped, and\n // this is the shape that narrows `name` for the caller's benefit.\n ...(latest?.modules ?? []).flatMap((specModule) =>\n specModule.operations.flatMap((operation) =>\n operation.name\n ? [\n {\n type: operation.name,\n module: specModule.name,\n inputSchema: operation.schema ?? null,\n },\n ]\n : [],\n ),\n ),\n ...BASE_ACTIONS,\n ],\n };\n }\n\n async get(input: {\n documentId: string;\n branch?: string;\n }): Promise<ReactorDocumentSummary> {\n const document = await this.client.get<PHDocument>(input.documentId);\n return this.handOver(documentSummary(document, true));\n }\n\n async find(input: ReactorFindInput): Promise<ReactorDocumentSummary[]> {\n const limit = input.limit ?? FIND_PAGE_LIMIT;\n let results: PHDocument[];\n if (input.documentType) {\n // The index takes both, so a step that named a type and a drive gets\n // documents of that type in that drive — not every document of the type.\n results = await this.findByType(\n input.documentType,\n limit,\n input.parentId,\n );\n } else if (input.parentId) {\n const page = await this.client.find(\n { parentId: input.parentId },\n undefined,\n {\n cursor: \"\",\n limit,\n },\n );\n results = page.results;\n } else {\n // The index rejects an empty filter, so sweep every installed type.\n const types = (await this.models()).map((model) => model.documentType);\n const pages = await Promise.all(\n types.map((type) => this.findByType(type, limit)),\n );\n results = pages.flat();\n }\n const seen = new Set<string>();\n return this.handOver(\n results\n .filter((document) => {\n if (seen.has(document.header.id)) return false;\n seen.add(document.header.id);\n return true;\n })\n // The index cannot query state, so a state match is applied to the page\n // that was read. A caller that needs to match across more documents than\n // the page holds raises `limit`; silently matching a prefix of the type\n // would look like \"no such document\".\n .filter((document) => matchesState(document, input.match))\n .map((document) => documentSummary(document, input.withState === true)),\n );\n }\n\n async create(input: ReactorCreateInput): Promise<ReactorDocumentSummary> {\n const target = input.parentId\n ? await this.resolveDriveTarget(input.parentId)\n : null;\n if (!target) {\n const created = await this.client.createEmpty<PHDocument>(\n input.documentType,\n { parentIdentifier: input.parentId },\n );\n // createEmpty takes no name, so naming it is a first operation. The\n // drive path below sets the header instead, before the file lands.\n if (!input.name) return this.handOver(documentSummary(created, true));\n const naming = createAction(\"SET_NAME\", { name: input.name });\n const named = await this.client.execute<PHDocument>(\n created.header.id,\n \"main\",\n [naming],\n );\n assertOperationsApplied(named, [naming]);\n return this.handOver(documentSummary(named, true));\n }\n // createEmpty only records the parent relationship; a drive also needs an\n // ADD_FILE node, or the document is created but invisible in the drive.\n const module = await this.client.getDocumentModelModule(input.documentType);\n const empty = withSignaturePolicy(\n module.utils.createDocument() as PHDocument,\n await this.client.getCreateSignaturePolicy(),\n );\n // The node name comes from the header, so set it before the file lands.\n if (input.name) empty.header.name = input.name;\n const created = await this.client.drives.addFile<PHDocument>(\n target.driveId,\n empty,\n target.parentFolder,\n );\n return this.handOver(documentSummary(created, true));\n }\n\n async execute(input: ReactorExecuteInput): Promise<ReactorDocumentSummary> {\n const actions: Action[] = input.actions.map((entry) =>\n createAction(\n entry.type,\n entry.input,\n undefined,\n undefined,\n entry.scope ?? \"global\",\n ),\n );\n const document = await this.client.execute<PHDocument>(\n input.documentId,\n input.branch ?? \"main\",\n actions,\n );\n // The inputs rather than the built actions: they carry the scope each one\n // was asked for, which is the scope its operation was appended to.\n assertOperationsApplied(document, input.actions);\n return this.handOver(documentSummary(document, true));\n }\n\n // A run is served only with what its steps read, so each document is\n // journaled against the run before its summary leaves the host.\n private async handOver<\n T extends ReactorDocumentSummary | ReactorDocumentSummary[],\n >(summaries: T): Promise<T> {\n const record = currentDocumentRecorder();\n if (record) {\n const list: ReactorDocumentSummary[] = Array.isArray(summaries)\n ? summaries\n : [summaries];\n await record(list.map((summary) => summary.documentId));\n }\n return summaries;\n }\n\n private async findByType(\n type: string,\n limit: number,\n parentId?: string,\n ): Promise<PHDocument[]> {\n try {\n const page = await this.client.find(\n { type, ...(parentId ? { parentId } : {}) },\n undefined,\n { cursor: \"\", limit },\n );\n return page.results;\n } catch {\n // One unreadable model must not sink a whole-reactor sweep.\n return [];\n }\n }\n\n // Where a new document's drive node belongs, when the parent implies one.\n private async resolveDriveTarget(\n parentId: string,\n ): Promise<DriveTarget | null> {\n try {\n const parent = await this.client.get<PHDocument>(parentId);\n // A plain document parent gets a relationship only, as before.\n return DRIVE_DOCUMENT_TYPES.has(parent.header.documentType)\n ? { driveId: parent.header.id }\n : null;\n } catch {\n // Not a document at all: it may be a folder node inside a drive.\n return this.findFolderDrive(parentId);\n }\n }\n\n private async findFolderDrive(nodeId: string): Promise<DriveTarget | null> {\n // Every type that counts as a drive, not just the common one: a folder in\n // a reactor-drive would otherwise look like no drive at all.\n const pages = await Promise.all(\n [...DRIVE_DOCUMENT_TYPES].map((type) =>\n this.findByType(type, FIND_PAGE_LIMIT),\n ),\n );\n for (const drive of pages.flat()) {\n try {\n const node = await this.client.drives.getNode(drive.header.id, nodeId);\n if (node.kind === \"folder\") {\n return { driveId: drive.header.id, parentFolder: nodeId };\n }\n } catch {\n // Not in this drive.\n }\n }\n return null;\n }\n}\n\n// Design-time `ctx.reactor`, bound to the caller behind the GraphQL request.\n// A piece's options()/props() code is the package's, not the reactor's.\nexport class ScopedDesignTimeReactorPort implements ReactorPort {\n private readonly inner: SubgraphReactorPort;\n\n constructor(\n private readonly host: WorkflowRuntimeHostDeps,\n private readonly caller: WorkflowCaller | undefined,\n ) {\n this.inner = new SubgraphReactorPort(host);\n }\n\n models(): Promise<ReactorModelSummary[]> {\n return this.inner.models();\n }\n\n model(documentType: string): Promise<ReactorModelDetail> {\n return this.inner.model(documentType);\n }\n\n async get(input: {\n documentId: string;\n branch?: string;\n }): Promise<ReactorDocumentSummary> {\n if (!this.caller) throw new Error(DESIGN_TIME_CALLER_REQUIRED);\n await this.host.assertCanRead(input.documentId, this.caller);\n return this.inner.get(input);\n }\n\n async find(input: ReactorFindInput): Promise<ReactorDocumentSummary[]> {\n const found = await this.inner.find(input);\n // Filtered rather than refused: one unreadable document in a sweep is not\n // the caller's error, and the list is what options() offers.\n const allowed = await Promise.all(\n found.map((document) => this.canRead(document.documentId)),\n );\n return found.filter((_, index) => allowed[index]);\n }\n\n create(_input: ReactorCreateInput): Promise<ReactorDocumentSummary> {\n return Promise.reject(new Error(DESIGN_TIME_WRITES_REFUSED));\n }\n\n execute(_input: ReactorExecuteInput): Promise<ReactorDocumentSummary> {\n return Promise.reject(new Error(DESIGN_TIME_WRITES_REFUSED));\n }\n\n private async canRead(documentId: string): Promise<boolean> {\n if (!this.caller) return false;\n return this.host\n .assertCanRead(documentId, this.caller)\n .then(() => true)\n .catch(() => false);\n }\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}=${showCursor(value)} from workflow ${flowKey()}; keeping ${\n isPlausibleCursor(kept, now) ? String(kept) : \"no cursor\"\n }`,\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 type { WorkflowRuntimeHostDeps } from \"./host.js\";\nimport {\n ActivepiecesBlockExecutor,\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 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 { join } from \"node:path\";\nimport {\n currentBoundConnections,\n currentPieceWorker,\n currentRunId,\n currentStepTest,\n currentWorkflowId,\n} from \"./run-scope.js\";\nimport { PROJECT_SCOPE_KEY } from \"./piece-store-port.js\";\nimport { packagePieces } from \"./piece-registry.js\";\nimport { SubgraphReactorPort } from \"./reactor-port.js\";\nimport { packageFromConnectorId } from \"./connector-id.js\";\nimport { runnableDefinition, type RunnableDefinition } from \"./runnable.js\";\nimport type { OAuthTokenRefresher } from \"./oauth.js\";\n\nconst pieceLogger = childLogger([\"workflow\", \"piece\"]);\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\") await oauth?.refreshIfDue(source);\n return shapeConnection(source, secrets);\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(process.cwd(), \".ph\", \"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 process.cwd(),\n \".ph\",\n \"ap-attachment-staging\",\n);\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): BlockExecutor {\n // No handler map: the document blocks are a piece now, and they reach the\n // reactor through the port below like any other package piece would.\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 // 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 // Served only to a piece this reactor's packages ship; the executor\n // withholds it from everything the resolver fetched.\n reactor: new SubgraphReactorPort(host),\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 const line = `[${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 ? { attachments, stagingRoot: ATTACHMENT_STAGING_DIR }\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 config: step.config,\n timeoutSeconds: step.timeoutSeconds,\n propertySettings: propertySettings(step.propertySettings),\n skip: step.skip,\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 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","// 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 ASSERT_BLOCK = action(\"assert\");\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 type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport {\n parseSecretRef,\n secretRefFromId,\n SecretDeletedError,\n SecretNotFoundError,\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 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(\"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 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 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(process.cwd(), \".ph\", \"secrets.key\");\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 }\n const key = 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 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: { value: string; label?: string }): Promise<SecretStat> {\n const now = new Date().toISOString();\n const row: SecretRow = {\n id: randomBytes(16).toString(\"hex\"),\n label: input.label ?? 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 async get(ref: string): Promise<string> {\n const row = await this.row(ref);\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 * The error for a SECRET names its ref, never a value. */\nexport async function resolveVariables(\n variables: readonly TypedVariable[],\n secrets: SecretProvider,\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 } 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 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 status: \"SUCCEEDED\" | \"FAILED\";\n output?: unknown;\n error?: string;\n durationMs: number;\n}\n\n// What a single-step test reads a tested block's sample from.\nexport type TestSample =\n | { kind: \"untested\" | \"stale\" | \"hidden\" }\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 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 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","// 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 type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport {\n redact,\n redactMessage,\n type StepExecutionRecord,\n type WorkflowRunResult,\n} from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport { sql, type Kysely } from \"kysely\";\nimport { randomUUID } from \"node:crypto\";\nimport { PROJECT_SCOPE_KEY } from \"./piece-store-port.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 // 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 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 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}\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 status: string; // ENABLED | DISABLED | ERROR\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 // Written for rolling-deploy overlap; not enforced yet.\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}\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\nexport interface WorkflowRuntimeDB {\n run: RunRow;\n step_execution: StepExecutionRow;\n run_document: RunDocumentRow;\n trigger_state: TriggerStateRow;\n trigger_dedupe: TriggerDedupeRow;\n piece_store: PieceStoreRow;\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 run that was matched and journaled but never started. Recorded as FAILED\n// so it is both visible and rerunnable: rerun() replays the trigger payload\n// with no completed steps, which is exactly the run that never happened.\nexport const ABANDONED_PENDING_RUN_ERROR =\n \"Reactor stopped before the matched trigger started its run; rerun it to fire the workflow with the same payload\";\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\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(\"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 // Additive migration for journals created before per-step journaling: the\n // upsert in recordStep/finishRun needs this constraint to conflict on.\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 // 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 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\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 // 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 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 return migrateTriggerStoreState(db);\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 );\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// 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.\nfunction stepValues(runId: string, ordinal: number, step: StepExecutionRecord) {\n return {\n run_id: runId,\n ordinal,\n step_id: step.stepId,\n step_key: step.key,\n piece_name: step.pieceName,\n block_name: step.blockName,\n status: step.status,\n input: jsonOrNull(redact(step.input)),\n output: jsonOrNull(redact(step.output)),\n port: step.port ?? null,\n error: step.error ? redactMessage(step.error) : 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 };\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 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: string | null,\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 })\n .onConflict((oc) => oc.columns([\"workflow_id\", \"dedupe_key\"]).doNothing())\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_key\",\n \"piece_name\",\n \"block_name\",\n \"status\",\n \"port\",\n \"error\",\n \"started_at\",\n \"ended_at\",\n \"piece_version\",\n \"piece_source\",\n \"version_match\",\n \"version_note\",\n \"config_hash\",\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}\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\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 await store.recoverAbandonedRuns();\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 let query = this.db\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: ORPHANED_RUN_ERROR,\n ended_at: new Date().toISOString(),\n })\n .where(\"status\", \"=\", \"RUNNING\");\n // Failing a run this process is still executing would hand rerun() a live\n // run, and its side effects would happen twice.\n if (this.runsInFlight.size > 0) {\n query = query.where(\"id\", \"not in\", [...this.runsInFlight]);\n }\n // Counted off RETURNING: the knex-backed dialect reports no row count.\n const recovered = (await query.returning(\"id\").execute()).length;\n if (recovered > 0) {\n logger.warn(\n `Recovered ${recovered} workflow run(s) left RUNNING by a stopped reactor; they are now FAILED and rerunnable`,\n );\n }\n return recovered;\n }\n\n // A PENDING run left by a stopped process: it was matched and journaled but\n // nothing ever started it. Recovery for RUNNING runs cannot reach it — that\n // sweep must not touch a row a live enqueue is about to adopt — so it gets\n // its own pass, run once when the journal opens.\n async recoverAbandonedRuns(): Promise<number> {\n let query = this.db\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: ABANDONED_PENDING_RUN_ERROR,\n ended_at: new Date().toISOString(),\n })\n .where(\"status\", \"=\", PENDING_RUN_STATUS);\n if (this.runsInFlight.size > 0) {\n query = query.where(\"id\", \"not in\", [...this.runsInFlight]);\n }\n // Counted off RETURNING: the knex-backed dialect reports no row count.\n const recovered = (await query.returning(\"id\").execute()).length;\n if (recovered > 0) {\n logger.warn(\n `Recovered ${recovered} workflow run(s) journaled by a stopped reactor but never started; they are now FAILED and rerunnable`,\n );\n }\n return recovered;\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.insertPendingRun(this.db, id, options);\n // In flight from here: the row is this process's to finish, and no sweep\n // of either kind may close it out underneath the run about to start.\n this.runsInFlight.add(id);\n return id;\n }\n\n // Claims the dedupe key and journals the PENDING run in one transaction, so\n // a crash cannot keep the claim without the run. Null when already claimed.\n async claimAndEnqueueRun(\n dedupeKey: string,\n ttlMs: number,\n nowIso: string,\n options: EnqueueRunOptions,\n ): Promise<string | null> {\n const id = randomUUID();\n const claimed = await this.db.transaction().execute(async (trx) => {\n if (\n !(await claimDedupeIn(\n trx,\n options.workflowId,\n dedupeKey,\n ttlMs,\n nowIso,\n id,\n ))\n ) {\n return false;\n }\n await this.insertPendingRun(trx, id, options);\n return true;\n });\n if (!claimed) return null;\n this.runsInFlight.add(id);\n return id;\n }\n\n private async insertPendingRun(\n db: Kysely<WorkflowRuntimeDB>,\n id: string,\n options: EnqueueRunOptions,\n ): Promise<void> {\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: jsonOrNull(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 })\n .execute();\n }\n\n // Adopts an enqueued row: the run starts now, with the definition fire() read.\n async beginRun(\n runId: string,\n details: { workflowName: string; workflowVersion: number },\n ): Promise<void> {\n this.runsInFlight.add(runId);\n 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 .execute();\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: jsonOrNull(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 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_id): a re-executed step corrects its row.\n async recordStep(\n runId: string,\n ordinal: number,\n step: StepExecutionRecord,\n ): Promise<void> {\n const values = stepValues(runId, ordinal, step);\n const { run_id: _run, step_id: _step, ...mutable } = values;\n await this.db\n .insertInto(\"step_execution\")\n .values({ id: randomUUID(), ...values })\n .onConflict((oc) =>\n oc.columns([\"run_id\", \"step_id\"]).doUpdateSet(mutable),\n )\n .execute();\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 async finishRun(\n runId: string,\n result: WorkflowRunResult,\n executionOrder?: ReadonlyMap<string, number>,\n ): Promise<void> {\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 if (result.steps.length > 0) {\n try {\n await this.sweepSteps(runId, result, 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 notes = runWarningNotes(result);\n await this.db\n .updateTable(\"run\")\n .set({\n status: result.status,\n error: result.error ? redactMessage(result.error) : null,\n ended_at: new Date().toISOString(),\n warnings: notes.length,\n warning_notes: notes.length > 0 ? JSON.stringify(notes) : null,\n })\n .where(\"id\", \"=\", runId)\n .execute();\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 .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.db\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_id\"]).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 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 async failRun(runId: string, error: string): Promise<void> {\n this.runsInFlight.delete(runId);\n await this.db\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: redactMessage(error),\n ended_at: new Date().toISOString(),\n })\n .where(\"id\", \"=\", runId)\n .execute();\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 async getSteps(runId: string): Promise<StepExecutionRow[]> {\n return this.db\n .selectFrom(\"step_execution\")\n .selectAll()\n .where(\"run_id\", \"=\", runId)\n .orderBy(\"ordinal\", \"asc\")\n .execute();\n }\n\n // Steps of many runs in one query, each run's in execution order. Without\n // `withData` the input and output blobs are left out (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 .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) return;\n await this.db\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 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 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 this.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 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, null);\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 // 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\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 // 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","// 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","// Opt-in pruning of the run journal. Off unless PH_WORKFLOWS_RUN_RETENTION_DAYS\n// is a positive number; finished runs older than that go with their children.\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// Undefined means retention is off.\nexport function runRetentionMs(\n env: Record<string, string | undefined> = process.env,\n): number | undefined {\n const days = Number(env[RUN_RETENTION_ENV]);\n return days > 0 ? days * DAY_MS : undefined;\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 // 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(`Unsupported setSchedule cron \"${cron}\"; using the default`);\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 {\n blockLabel,\n bundleResolver,\n canonicalJson,\n checkDynamicProperties,\n DEFAULT_EGRESS_POLICY,\n hashOf,\n DynamicPropertiesError,\n extractDedupeKey,\n pieceModuleRef,\n PieceWorker,\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 PieceResolver,\n type PieceWorkerResult,\n type PropertySettingDef,\n type RecordedSchedule,\n type TriggerHookRequest,\n type TriggerRenew,\n} from \"../pieces/index.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 { 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 TriggerStateRow,\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 // 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 resolveAuth: (\n connectionId: string | null | undefined,\n request?: ConnectionRequest,\n ) => Promise<unknown>;\n fire: (workflowId: string, payload: unknown, kind: string) => void;\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?: PieceWorker;\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 // 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 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(`Unsupported setSchedule cron \"${cron}\"; using the default`);\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\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: PieceWorker;\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 timer?: NodeJS.Timeout;\n // Lifecycle ops serialize so enable/disable/poll never interleave per store.\n private ops: Promise<unknown> = Promise.resolve();\n private ticking = false;\n private warnedMissingJournal = false;\n\n constructor(private readonly options: TriggerSupervisorOptions) {\n this.worker = options.worker ?? new PieceWorker();\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.now = options.now ?? (() => new Date());\n this.egress =\n options.egress === undefined\n ? DEFAULT_EGRESS_POLICY\n : (options.egress ?? undefined);\n }\n\n start(): void {\n if (this.timer) return;\n this.timer = setInterval(() => {\n this.tick().catch((error: unknown) => {\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.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: registration churn and ticks share one lane.\n private enqueue<T>(task: () => Promise<T>): Promise<T> {\n const run = this.ops.then(task);\n this.ops = run.catch(() => undefined);\n return run;\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 upsert(binding: TriggerBinding): Promise<void> {\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 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(() => this.enable(binding, previous));\n }\n\n remove(workflowId: string): Promise<void> {\n const binding = this.unbind(workflowId);\n return this.enqueue(() => this.disable(workflowId, binding));\n }\n\n // A deleted workflow: disabled as remove() does, then its row and FLOW\n // store 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 return this.enqueue(async () => {\n const store = await this.options.store();\n if (!store) return;\n await this.disable(workflowId, binding);\n await store.deleteTriggerState(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.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(() =>\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.options.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. ${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(binding: PieceTriggerBinding): Promise<unknown> {\n return this.enqueue(async () => {\n const store = await this.options.store();\n try {\n const result = await this.hook(binding, \"test\");\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(() => this.hook(binding, \"onHandshake\", { payload }));\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 deliverWebhook(workflowId: string, payload: unknown): Promise<void> {\n return this.enqueue(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.options.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 try {\n const result = await this.hook(binding, \"run\", { payload });\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 if (row?.status === \"ENABLED\") {\n await store.recordPollSuccess(\n workflowId,\n VESTIGIAL_STORE_STATE,\n now.toISOString(),\n new Date(now.getTime() + row.interval_ms).toISOString(),\n );\n }\n for (const item of result.output) {\n await this.fireItem(store, binding, item, now);\n }\n } catch (error) {\n await rewind();\n throw error;\n }\n });\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<() => Promise<void>> {\n const before = await store.listPieceStore(\"FLOW\", workflowId);\n return async () => {\n try {\n await store.deletePieceStore(\"FLOW\", workflowId);\n for (const [key, value] of Object.entries(before)) {\n await store.setPieceStoreValue(\"FLOW\", workflowId, key, value);\n }\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 }\n };\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 } = {},\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.options.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 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: { flowId: binding.workflowId, projectId: PROJECT_SCOPE_KEY },\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 },\n {\n timeoutMs: this.hookTimeoutMs,\n ...(pieceStore ? { hostCalls: storeHandlers(pieceStore) } : {}),\n },\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 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 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.options.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 existing = await store.getTriggerState(binding.workflowId);\n const now = this.now();\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 const webhook = runtime.delivery === \"webhook\";\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: \"ENABLED\",\n store_state: VESTIGIAL_STORE_STATE,\n interval_ms: intervalMs,\n next_poll_at: 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 ${blockLabel(binding.block)} for workflow ${binding.workflowId} (every ${intervalMs}ms)`,\n );\n } catch (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): ${message}` +\n (retryAt\n ? `; retrying at ${retryAt.toISOString()}`\n : \"; not retrying\"),\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 // 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: \"ENABLED\",\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}: ${message}`,\n );\n }\n }\n\n private async disable(\n workflowId: string,\n binding?: TriggerBinding,\n ): Promise<void> {\n const store = await this.options.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.options.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 async tick(): Promise<void> {\n if (this.ticking) return;\n this.ticking = true;\n try {\n await this.enqueue(() => this.pollDue());\n } finally {\n this.ticking = false;\n }\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 async retryOneEnable(): Promise<void> {\n const now = this.now().getTime();\n const next = [...this.enableRetries]\n .filter(([, retry]) => retry.at <= now)\n .sort((a, b) => a[1].at - b[1].at)\n .at(0);\n if (!next) return;\n const [workflowId, retry] = next;\n const binding = this.bindings.get(workflowId);\n if (!binding) {\n this.enableRetries.delete(workflowId);\n return;\n }\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 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 pollDue(): Promise<void> {\n const store = await this.options.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 for (const row of due) {\n const binding = this.bindings.get(row.workflow_id);\n if (!binding) {\n // Zombie row: the registry no longer knows this workflow.\n await store.setTriggerStatus(row.workflow_id, \"DISABLED\");\n continue;\n }\n if (isSchedule(binding)) {\n await this.fireSchedule(store, row, binding);\n } else {\n await this.poll(store, row, binding);\n }\n }\n await this.renewDue(store);\n await this.retryOneEnable();\n }\n\n private async renewDue(store: WorkflowRunStore): Promise<void> {\n const due = await store.listDueTriggerRenewals(this.now().toISOString());\n for (const row of due) {\n const binding = this.bindings.get(row.workflow_id);\n if (!binding) {\n await store.setTriggerStatus(row.workflow_id, \"DISABLED\");\n continue;\n }\n if (isSchedule(binding)) {\n await store.setTriggerRenewAt(row.workflow_id, null);\n continue;\n }\n await this.renew(store, row, binding);\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): ${message}; retrying at ${retryAt.toISOString()}`,\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 await store.recordPollSuccess(\n row.workflow_id,\n \"{}\",\n now.toISOString(),\n nextAt.toISOString(),\n );\n this.options.fire(\n binding.workflowId,\n schedulePayload(schedule, scheduledFor, now),\n SCHEDULE_TRIGGER_KIND,\n );\n } catch (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}: ${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 try {\n const result = await this.hook(binding, \"run\");\n if (!Array.isArray(result.output)) {\n throw new Error(\n `Trigger run returned ${typeof result.output}, expected an array`,\n );\n }\n await store.recordPollSuccess(\n row.workflow_id,\n VESTIGIAL_STORE_STATE,\n now.toISOString(),\n new Date(now.getTime() + row.interval_ms).toISOString(),\n );\n for (const item of result.output) {\n await this.fireItem(store, binding, item, now);\n }\n } catch (error) {\n await rewind();\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): ${message}`,\n );\n }\n }\n\n // One workflow run per output item; _dedupe_key suppresses 30s repeats.\n private async fireItem(\n store: WorkflowRunStore,\n binding: PieceTriggerBinding,\n item: unknown,\n now: Date,\n ): Promise<void> {\n const dedupeKey = extractDedupeKey(item);\n if (dedupeKey) {\n const claimed = await store.claimDedupe(\n binding.workflowId,\n dedupeKey,\n DEDUPE_TTL_MS,\n now.toISOString(),\n );\n if (!claimed) return;\n }\n this.options.fire(\n binding.workflowId,\n item,\n pieceTriggerKind(binding.block),\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","// 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 { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\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 blockLabel,\n blockPorts,\n builtinPiece,\n containsRedactedMarker,\n describeBuiltinPiece,\n isHostBound,\n servesReactorPort,\n stepBlock,\n triggerBlock,\n declaredConnectionIds,\n DEFAULT_EGRESS_POLICY,\n resolvedBlock,\n stepConfigHash,\n pieceModuleRef,\n reactorHandlers,\n PieceWorker,\n PieceWorkerError,\n PieceWorkerPool,\n PieceWorkerTimeoutError,\n rememberSecrets,\n resolveExpressions,\n runWorkflow,\n UnsupportedPieceFeatureError,\n authMethodFor,\n type PieceAuthDescriptor,\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 SecretProvider,\n type SecretStore,\n type StepExecutionRecord,\n type WorkflowRunResult,\n} from \"../pieces/index.js\";\nimport {\n childLogger,\n generateId,\n type Action,\n type ILogger,\n type OperationWithContext,\n} from \"document-model\";\nimport {\n actions as connectionActions,\n type ConnectionDocument,\n} from \"@powerhousedao/workflow/document-models/connection\";\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 OAuthStart,\n type OAuthTokenRefresher,\n} from \"./oauth.js\";\nimport {\n actions as workflowActions,\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 documentBlockTree,\n documentEventTree,\n documentFindTree,\n documentGetTree,\n documentSchemaTree,\n documentTypesTree,\n fieldsFromSdl,\n fromOutputSchema,\n hasOutputSchemaFields,\n fromSample,\n lifecycleTriggerTree,\n scheduleTriggerTree,\n webhookTriggerTree,\n type OutputTree,\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 localSearchHits,\n triggersResult,\n} from \"./local-catalog.js\";\nimport {\n indexFromHits,\n searchBlocks,\n type BlockSearchIndex,\n type BlockSearchResult,\n} from \"./block-search.js\";\nimport { installedPiece, installedPieces } from \"./piece-registry.js\";\nimport { BlockResolver } from \"./block-resolver.js\";\nimport { ScopedDesignTimeReactorPort } from \"./reactor-port.js\";\nimport {\n bundleCacheDir,\n configuredEgress,\n createBlockExecutor,\n DocumentConnectionResolver,\n pieceResolver,\n resolveConnectionAuth,\n stepDefinition,\n toWorkflowDefinition,\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 { createPieceStorePort, PROJECT_SCOPE_KEY } from \"./piece-store-port.js\";\nimport { currentWorkflowId, withRunScope } from \"./run-scope.js\";\nimport {\n ASSERT_BLOCK,\n BRANCH_BLOCK,\n isCoreBlock,\n MANUAL_BLOCK,\n SCHEDULE_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 triggerSamplePayload,\n untestedError,\n upstreamStepIds,\n type StepTestResult,\n type TestSample,\n} from \"./step-test.js\";\nimport {\n MAX_LIST_RUNS,\n WorkflowRunStore,\n type RunRow,\n type StepExecutionRow,\n type TriggerStateRow,\n} from \"./store.js\";\nimport { decodeRunCursor, encodeRunCursor } from \"./run-cursor.js\";\nimport {\n RETENTION_SWEEP_INTERVAL_MS,\n runRetentionMs,\n sweepRetention,\n} from \"./run-retention.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\";\n\nexport type PersistedRunResult = WorkflowRunResult & { runId: string | null };\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. */\nexport interface RunRecord {\n row: RunRow;\n steps: StepExecutionRow[];\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\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\";\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\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\n// The documents a run's trigger names: the one whose operation fired it, and\n// the drive it sits in.\nfunction 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\nfunction triggerDocumentIds(payload: unknown): string[] {\n const record = inputRecord(payload);\n return [\n ...new Set(\n [\n stringField(record, \"documentId\"),\n stringField(record, \"driveId\"),\n ].filter((id): id is string => id !== undefined),\n ),\n ];\n}\n\n// Absence is reported by name: the error may cross an RPC boundary.\nfunction isAbsent(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"DocumentNotFoundError\" ||\n error.name === \"DocumentDeletedError\")\n );\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\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.\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 run kind a design-time test is journaled under.\nexport const TEST_TRIGGER_KIND = \"test\";\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// 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\nexport class WorkflowRuntimeService {\n private readonly host: WorkflowRuntimeHostDeps;\n private readonly logger: ILogger;\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 readonly storePromise: Promise<WorkflowRunStore>;\n private secretsPromise?: Promise<SecretStore>;\n private oauthAttemptsPromise?: Promise<OAuthAttemptStore>;\n private tokenRefresher?: OAuthTokenRefresher;\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.logger = host.logger ?? logger;\n this.attachments = host.attachments\n ? createAttachmentPort(\n host.attachments,\n () => currentWorkflowId(),\n // A host that serves attachments without answering for them reads\n // nothing: an unanswerable relationship is not a permitted one.\n (documentId, ref) =>\n host.canReadAttachmentRef?.(documentId, ref) ??\n Promise.resolve(false),\n )\n : undefined;\n this.storePromise = WorkflowRunStore.create(host.relationalDb);\n this.storePromise.catch((error: unknown) => {\n this.logger.error(\"Failed to open the workflow run store: @error\", error);\n });\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 void this.storePromise.then(sweep, () => undefined);\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.\n async store(): Promise<WorkflowRunStore | undefined> {\n try {\n return await this.storePromise;\n } catch {\n return undefined;\n }\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 { get: (ref) => this.secrets().then((store) => store.get(ref)) };\n }\n\n private oauthAttempts(): Promise<OAuthAttemptStore> {\n this.oauthAttemptsPromise ??= OAuthAttemptStore.create(\n this.host.relationalDb,\n );\n return this.oauthAttemptsPromise;\n }\n\n private oauthRefresher(): OAuthTokenRefresher {\n return (this.tokenRefresher ??= new StoreTokenRefresher(\n () => this.secrets(),\n this.designEgress,\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 await this.updateRegistration(document.header.id, document.state.global);\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 // Registers the runnable trigger; `onlyIfChanged` passes over draft edits.\n private async updateRegistration(\n workflowId: string,\n state: WorkflowState,\n onlyIfChanged = false,\n ): Promise<void> {\n const key = registrationKey(state);\n if (\n onlyIfChanged &&\n !this.unarmed.has(workflowId) &&\n this.registeredAs.get(workflowId) === key\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 trigger =\n state.status === \"ENABLED\"\n ? runnableDefinition(state).trigger\n : undefined;\n const block = trigger ? triggerBlock(trigger) : undefined;\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);\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);\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(workflowId: string, binding: TriggerBinding): void {\n this.supervisor()\n .upsert(binding)\n .catch((error: unknown) => {\n this.logger.error(`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 ): 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);\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.logger.error(\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}: ${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.logger.error(\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 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 = new BlockResolver({\n local: installedPiece,\n timeoutMs: PIECE_VERSION_LOOKUP_TIMEOUT_MS,\n hasBlock: (ref, version, source) =>\n this.versionHasBlock(ref, version, source),\n });\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 // 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.logger.error(\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.logger.error(`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 document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\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 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 // 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 const hints = collectLifecycleParentHints(operations);\n for (const { operation, context } of operations) {\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.scope === DOCUMENT_SCOPE) {\n await this.matchDocumentLifecycle(operation, context, hints, opKey);\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 // Only a status or published-trigger change re-arms.\n await this.refreshRegistration(\n context.documentId,\n operation.resultingState,\n true,\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 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 opKey,\n );\n }\n }\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.\n private async enqueueFire(\n workflowId: string,\n payload: unknown,\n kind: string,\n opKey: string,\n ): Promise<void> {\n const store = await this.store();\n if (!store) {\n this.fireFromTrigger(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 time.\n let runId: string | null;\n try {\n runId = await store.claimAndEnqueueRun(\n `op:${opKey}`,\n OPERATION_DEDUPE_TTL_MS,\n new Date().toISOString(),\n { workflowId, triggerKind: kind, 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 this.fireFromTrigger(workflowId, payload, kind);\n return;\n }\n if (runId === null) return;\n this.fireFromTrigger(workflowId, payload, kind, runId);\n }\n\n private fireFromTrigger(\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 this.logger.error(\n `${kind} run failed for workflow ${workflowId}`,\n error,\n );\n },\n );\n }\n\n // Fires once per document, from whichever source reports it first. Only a fire that\n // matched is recorded, so a creation with 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 opKey: string,\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 await this.enqueueFire(target.workflowId, payload, kind, opKey);\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 try {\n await (await this.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 // The registry goes now, so deliveries stop at once. onDisable and the\n // token revoke queue behind any enable in flight, off the ingestion path.\n private disarmDeleted(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 this.supervisor()\n .forget(workflowId)\n .then(async () => (await this.endpoints())?.revoke(workflowId))\n .catch((error: unknown) => {\n this.logger.error(\n `Could not disarm deleted workflow ${workflowId}`,\n error,\n );\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 opKey: string,\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(\n kind,\n {\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 opKey,\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 opKey: 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(\n kind,\n {\n documentId,\n documentType: documentType ?? null,\n name,\n driveId,\n parentId: stringField(record, \"parentFolder\") ?? null,\n operation,\n },\n opKey,\n );\n }\n\n private triggerSupervisor?: TriggerSupervisor;\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 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) => {\n this.fireFromTrigger(workflowId, payload, kind);\n },\n webhookUrlFor: async (workflowId) =>\n (await this.mintWebhookEndpoint(workflowId))?.url,\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 return this.triggerSupervisor;\n }\n\n startTriggerSupervisor(): void {\n this.supervisor().start();\n }\n\n stopTriggerSupervisor(): void {\n this.triggerSupervisor?.stop();\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 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 // Forked on the editor's first request and never replaced, so it outlives\n // a hot reload unless it goes with everything else.\n this.designWorker?.dispose();\n this.designWorker = undefined;\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 // A waiting test verifies as the draft's trigger would once armed.\n const test = this.webhookTests.get(workflowId);\n if (test) return this.policyOf(test.config, workflowId);\n\n const registration = this.registry.get(workflowId);\n if (!registration) return undefined;\n\n // A piece owns its own verification and parsing: its run hook decides what\n // the request means, or rejects it.\n if (registration.kind === PIECE_WEBHOOK_KIND) return {};\n if (registration.kind !== WEBHOOK_TRIGGER_KIND) return undefined;\n return this.policyOf(registration.config, workflowId);\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 const workflowId = request.key;\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 return { status: test.config.responseStatus };\n }\n const registration = this.registry.get(workflowId);\n if (!registration) return UNAUTHORIZED;\n if (registration.kind === PIECE_WEBHOOK_KIND) {\n return this.deliverToPiece(registration.binding, request);\n }\n if (registration.kind !== WEBHOOK_TRIGGER_KIND) return UNAUTHORIZED;\n\n const { config } = registration;\n const payload = webhookPayload(request);\n\n if (config.responseMode === \"async\") {\n this.fireFromTrigger(workflowId, payload, WEBHOOK_TRIGGER_KIND);\n return { status: config.responseStatus };\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 run = await Promise.race([\n this.fire(workflowId, payload, WEBHOOK_TRIGGER_KIND).then(\n (result) => ({ ok: true, result }) as const,\n (error: unknown) => ({ ok: false, error }) as const,\n ),\n timeout(DELIVERY_TIMEOUT_MS),\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 const message =\n run.error instanceof Error ? run.error.message : String(run.error);\n this.logger.error(`Webhook run failed for ${workflowId}: ${message}`);\n return {\n status: 500,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({ error: message }),\n };\n }\n\n return {\n status: run.result.status === \"SUCCEEDED\" ? config.responseStatus : 500,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({\n runId: run.result.runId,\n status: run.result.status,\n error: run.result.error ?? null,\n }),\n };\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.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 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.logger.error(\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 (await this.secrets()).get(config.secretRef);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(\n `Webhook secret unavailable for ${workflowId}: ${message}`,\n );\n return undefined;\n }\n }\n\n private readonly descriptors = new Map<string, PieceDescriptor>();\n private designWorker?: PieceWorker;\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 ??= new PieceWorker();\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 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 const ids = nodes\n .filter(\n (node) =>\n \"documentType\" in node &&\n node.documentType === WORKFLOW_DOCUMENT_TYPE,\n )\n .map((node) => node.id);\n return this.readableRows(ids, (id) => id, ctx);\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 async runsPage(args: RunsPageArgs, ctx?: WorkflowCaller): 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 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 return { row, steps: await store.getSteps(row.id) };\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 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 ??= new PieceWorker();\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 accountLabel: outcome.accountLabel ?? accountLabel,\n });\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 { [OAUTH_CLIENT_ID]: clientId, ...props } = (state.config ??\n {}) as Record<string, unknown>;\n if (typeof clientId !== \"string\" || clientId === \"\") {\n throw new OAuthError(\"Set the client ID before connecting\");\n }\n const clientSecretRef = state.secretRefs.find(\n (entry) => entry.name === OAUTH_CLIENT_SECRET,\n )?.ref;\n if (!clientSecretRef) {\n throw new OAuthError(\"Save the client secret before connecting\");\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: options.redirectUri,\n ...(options.returnUrl ? { returnUrl: options.returnUrl } : {}),\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 if (\n state.authType !== \"OAUTH2\" ||\n 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 tokens = await exchangeCode(\n attempt,\n callback.code,\n await secrets.get(attempt.client_secret_ref),\n this.designEgress,\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 try {\n if (ref) await secrets.rotate(ref, value);\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 })\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 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.name}\": ${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: ${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 // 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 searchBlocks(\n query: string,\n limit?: number,\n ): Promise<BlockSearchResult> {\n let local: BlockSearchIndex | undefined;\n try {\n local = indexFromHits(\n (await this.localPieces()).flatMap(({ piece, descriptor }) =>\n localSearchHits(descriptor, piece.name, piece.version),\n ),\n );\n } catch (error) {\n // The published half is still worth serving without them.\n this.logger.warn(`Could not index the package pieces: ${String(error)}`);\n }\n return searchBlocks(query, limit, 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 ): 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 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 this.designWorker ??= new PieceWorker();\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 // The reactor piece's options() reads the reactor it offers choices\n // from, over the same port a step of it would use.\n\n // The same identity rule the run path applies: design time is not a\n // way round it, and a piece offered the member would have none.\n ...(servesReactorPort(parsed.packageName)\n ? { reactorAccess: true }\n : {}),\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 },\n servesReactorPort(parsed.packageName)\n ? {\n hostCalls: reactorHandlers(\n new ScopedDesignTimeReactorPort(this.host, ctx),\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 return { source: \"none\", nodes: [] };\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 ASSERT_BLOCK:\n return { source: \"static\", nodes: [{ name: \"value\", type: \"value\" }] };\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: documentGetTree(stateChildren),\n };\n }\n case DOCUMENT_CREATE_BLOCK:\n case DOCUMENT_DISPATCH_BLOCK: {\n const stateChildren = await this.stateFields(\n staticString(record.documentType),\n );\n return {\n source: stateChildren.length > 0 ? \"schema\" : \"static\",\n nodes: documentBlockTree(stateChildren),\n };\n }\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 latest = module.documentModel.global.specifications.at(-1);\n for (const specModule of latest?.modules ?? []) {\n for (const operation of specModule.operations) {\n if (operation.name === actionType && operation.schema) {\n return fieldsFromSdl(operation.schema, { input: operation.name });\n }\n }\n }\n return [];\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 const test = await this.triggerTest(workflowId, trigger, options);\n const startedAt = new Date().toISOString();\n const recordTest = (\n outcome: Pick<\n StepExecutionRecord,\n \"status\" | \"output\" | \"port\" | \"error\"\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 await recordTest({\n status: \"FAILED\",\n error: pieceFailureDetail(error, \"Trigger test timed out\"),\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 ): 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 sample: () => this.supervisor().test(binding),\n };\n }\n\n // One-shot listeners: the next delivery to the workflow's endpoint is the\n // sample, and runs nothing.\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 await store.finishRun(runId, {\n status: record.status === \"FAILED\" ? \"FAILED\" : \"SUCCEEDED\",\n steps: [record],\n ...(record.error ? { error: record.error } : {}),\n });\n } catch (error) {\n this.logger.warn(\n `Could not journal the test of \"${record.key}\" on workflow ${workflowId}`,\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 \"${record.key}\" on workflow ${workflowId}`,\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 ??= 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 ));\n }\n\n // One child per run, N runs at a time. Sized by the operator: each slot is a\n // node process, so this is the reactor's real connector concurrency.\n private workers(): PieceWorkerPool {\n // A queue depth of 0 waits without limit, which is what one shared worker\n // did — a cap turns a saturated pool into failures instead of latency.\n return (this.pieceWorkers ??= new PieceWorkerPool({\n size: Number(process.env.PH_WORKFLOWS_RUN_CONCURRENCY) || undefined,\n maxQueueDepth:\n Number(process.env.PH_WORKFLOWS_RUN_QUEUE_DEPTH) || undefined,\n }));\n }\n\n async fire(\n workflowId: string,\n triggerPayload?: unknown,\n triggerKind = \"manual\",\n resume?: {\n completedSteps: Map<string, { output?: unknown; port?: string | null }>;\n rerunOf: string;\n },\n ctx?: WorkflowCaller,\n // A run this workflow's trigger already journaled as PENDING. Adopted\n // rather than created, so the row a matched operation left behind is the\n // row the run finishes in.\n enqueuedRunId?: string,\n ): Promise<PersistedRunResult> {\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 try {\n // \"manual\" is the only kind a caller can ask for; every other one is\n // system-initiated and already authorized by whatever armed the trigger.\n if (triggerKind === \"manual\") {\n await this.assertCanReadDocument(workflowId, ctx);\n }\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n if (document.header.documentType !== \"powerhouse/workflow\") {\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 if (state.status !== \"ENABLED\") {\n throw new Error(\n `Workflow is ${state.status}; only ENABLED workflows can fire`,\n );\n }\n definition = toWorkflowDefinition(state);\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 );\n }\n throw error;\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 let runId: string | null = enqueuedRunId ?? null;\n if (enqueuedRunId) {\n await store?.beginRun(enqueuedRunId, {\n workflowName: runJournalName(state.name, documentName),\n workflowVersion: runnable.version,\n });\n } else {\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 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 // 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 try {\n // Inside the try: a pool disposed while this run was starting up refuses\n // here, and the journal records the run as failed rather than leaving it\n // to be swept up as an orphan.\n session = this.workers().session();\n // Resolved per run, so a rotated secret takes effect on the next one.\n const { variables, secretValues } = await resolveVariables(\n runnable.variables,\n this.secretProvider(),\n );\n const journal = store;\n const journaledRunId = runId;\n const handed = new Set<string>();\n const result = await withRunScope(\n {\n workflowId,\n runId,\n connections,\n pieceWorker: session,\n recordDocuments: async (documentIds: string[]) => {\n for (const documentId of documentIds) handed.add(documentId);\n if (journal && journaledRunId) {\n await journal.recordRunDocuments(journaledRunId, documentIds);\n }\n },\n },\n () =>\n runWorkflow({\n definition: { ...definition, variables },\n executor,\n declaredPorts: blockPorts,\n ...(secretValues.length > 0 ? { redactValues: secretValues } : {}),\n triggerPayload,\n completedSteps: resume?.completedSteps,\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 executionOrder.set(record.stepId, ordinal);\n try {\n await store.recordStep(runId, ordinal, record);\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 \"${record.key}\" failed; the run continues without per-step durability`,\n error,\n );\n }\n }\n : undefined,\n }),\n );\n if (store && runId) {\n try {\n await store.finishRun(runId, result, executionOrder);\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 }\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 await store.failRun(\n runId,\n error instanceof Error ? error.message : String(error),\n );\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 }\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 if (run.status !== \"FAILED\") {\n throw new Error(`Only FAILED runs can be rerun; run is ${run.status}`);\n }\n const triggerPayload =\n run.trigger_payload === null\n ? undefined\n : (JSON.parse(run.trigger_payload) as unknown);\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 currentSteps = new Map(\n runnableDefinition(document.state.global).steps.map((step) => [\n step.id,\n stepDefinition(step),\n ]),\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 const completedSteps = new Map<\n string,\n { output?: unknown; port?: string | null }\n >();\n for (const row of await store.getSteps(runId)) {\n if (row.status !== \"SUCCEEDED\" && row.status !== \"REPLAYED\") continue;\n const current = currentSteps.get(row.step_id);\n if (\n !current ||\n current.key !== row.step_key ||\n row.config_hash === null ||\n stepConfigHash(current) !== row.config_hash\n ) {\n continue;\n }\n completedSteps.set(row.step_id, {\n output:\n row.output === null ? undefined : (JSON.parse(row.output) as unknown),\n port: row.port,\n });\n }\n return this.fire(\n run.workflow_id,\n triggerPayload,\n \"rerun\",\n { completedSteps, rerunOf: runId },\n ctx,\n );\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 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(state.variables, this.secretProvider());\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 = resolveExpressions(step.config, {\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.key}\" on workflow ${workflowId}`,\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 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 ...(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.failRun(runId, detail).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.key}\" out failed`,\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: record.status === \"FAILED\" ? \"FAILED\" : \"SUCCEEDED\",\n ...(served && record.output !== undefined\n ? { output: record.output }\n : {}),\n ...(record.error ? { error: record.error } : {}),\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 { payload, empty } = triggerSamplePayload(sample.output);\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 priorSteps[candidate.key] = { output: sample.output };\n samples.push({ label, value: sample.output });\n }\n return { triggerPayload, priorSteps, samples };\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 const output =\n row.output === null ? null : (JSON.parse(row.output) as unknown);\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 value = isTrigger\n ? triggerSamplePayload(sample.output).payload\n : sample.output;\n return {\n source: \"test\",\n nodes: fromSample(value),\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 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","// 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 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, Transaction } from \"kysely\";\nimport type { 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// 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 extends BaseReadModel {\n // Set by init() when no cursor row exists, cleared by the first batch that\n // writes one: nothing else tells a fresh registration from a restart.\n private freshRegistration = false;\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 });\n }\n\n // No row means no backlog a trigger could want, so base init()'s ordinal-zero\n // row and full replay are precisely what a first registration must skip.\n override async init(): Promise<void> {\n if ((await this.loadState()) === undefined) {\n this.freshRegistration = true;\n return;\n }\n this.freshRegistration = false;\n await super.init();\n }\n\n // The fresh mark lifts only once a batch is through: a pass that threw rolled\n // back the insert below, and the batch after it has to write the row again.\n override async indexOperations(items: OperationWithContext[]): Promise<void> {\n if (items.length === 0) return;\n await super.indexOperations(items);\n this.freshRegistration = false;\n }\n\n // The only await that matters here: onOperations journals every matched fire\n // before it resolves, so the cursor saved after it never passes a lost event.\n protected override async commitOperations(\n items: OperationWithContext[],\n ): Promise<void> {\n await this.runtime.onOperations(items);\n }\n\n // super.saveState only UPDATEs, so the row init() skipped appears here, in the\n // transaction that first advances the cursor. Conflict-safe: a second process.\n protected override async saveState(\n trx: Transaction<DocumentViewDatabase>,\n items: OperationWithContext[],\n ): Promise<void> {\n if (this.freshRegistration) {\n await trx\n .insertInto(\"ViewState\")\n .values({ readModelId: this.config.readModelId, lastOrdinal: 0 })\n .onConflict((oc) => oc.column(\"readModelId\").doNothing())\n .execute();\n }\n await super.saveState(trx, items);\n }\n}\n"],"x_google_ignoreList":[23,24,25,26,27,28,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],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,gBAAgB;AACtB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAE3B,MAAM,wBAAQ,IAAI,IAAoB;AACtC,MAAM,2BA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aAAa,KAAK;CACvC;CAIA,MAAyB,UACvB,KACA,OACe;EACf,IAAI,KAAK,mBACP,MAAM,IACH,WAAW,WAAW,CAAC,CACvB,OAAO;GAAE,aAAa,KAAK,OAAO;GAAa,aAAa;EAAE,CAAC,CAAC,CAChE,YAAY,OAAO,GAAG,OAAO,aAAa,CAAC,CAAC,UAAU,CAAC,CAAC,CACxD,QAAQ;EAEb,MAAM,MAAM,UAAU,KAAK,KAAK;CAClC;AACF"}
1
+ {"version":3,"file":"index.js","names":["logger","up","clientAuth","action","trigger","logger","createAction","logger","parseScheduleConfig","parseSharedSchedule","up","trim","logger","logger","logger","targetOf","parseScheduleConfig","asRecord","connectionActions","parseScheduleConfig","workflowActions"],"sources":["../src/pieces/activepieces/piece-versions.ts","../src/reactor/attachment-port.ts","../src/reactor/package-name.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/reactor-port.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/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/store.ts","../src/reactor/run-cursor.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/service.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.\nconst LISTED_TTL_MS = 5 * 60_000;\nconst ABSENT_TTL_MS = 5 * 60_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 { AttachmentPort } from \"../pieces/index.js\";\nimport { FileTooLargeError, maxFileBytes } from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport { open, readFile, rm } from \"node:fs/promises\";\n\nconst logger = childLogger([\"workflow\", \"attachments\"]);\n\n// The slice of IAttachmentClient this needs, declared structurally so the\n// subgraph does not depend on the attachments package's types.\nexport interface AttachmentClientLike {\n upload(input: {\n file: Blob;\n fileName?: string;\n mimeType?: string;\n }): Promise<{ ref?: string } & Record<string, unknown>>;\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: { documentId: string; ref: string }): Promise<{\n header: { sizeBytes?: number; mimeType?: string; fileName?: string };\n body: ReadableStream<Uint8Array>;\n }>;\n}\n\nfunction refOf(result: Record<string, unknown>): string {\n const direct = result.ref;\n if (typeof direct === \"string\") return direct;\n // Some client versions nest the reference under the reservation.\n const nested = (result.reservation as { ref?: unknown } | undefined)?.ref;\n if (typeof nested === \"string\") return nested;\n throw new Error(\"The attachment store returned no reference for the upload\");\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 function createAttachmentPort(\n client: AttachmentClientLike,\n // Attachment reads are authorized against a document, and a step's refs come\n // from its own run journal: the workflow document is what vouches for them.\n documentIdFor: () => string | undefined,\n // Whether that document really references the ref. A step carries no caller,\n // so this relationship is all that stands between it and any known blob.\n canReadRef: (documentId: string, ref: string) => Promise<boolean>,\n): AttachmentPort {\n return {\n async read(ref, destPath) {\n const documentId = 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 canReadRef(documentId, ref))) {\n throw new Error(\n `Cannot resolve ${ref}: workflow document \"${documentId}\" does not reference it`,\n );\n }\n const limit = maxFileBytes();\n const { header, body } = await client.download({ documentId, ref });\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 =\n header.mimeType !== undefined && header.mimeType !== \"\"\n ? header.mimeType\n : undefined;\n return { fileName: header.fileName, contentType };\n },\n\n async write(file) {\n const bytes = await readFile(file.path);\n const result = await client.upload({\n file: new Blob([new Uint8Array(bytes)], {\n type: file.contentType ?? \"application/octet-stream\",\n }),\n fileName: file.fileName,\n mimeType: file.contentType,\n });\n const ref = refOf(result);\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","// 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 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 client_secret_ref: string;\n code_verifier: string | null;\n redirect_uri: string;\n token_url: string;\n authorization_method: string | null;\n return_url: 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 provider's whole token response; pieces read fields off it.\n data: Record<string, unknown>;\n}\n\nexport class OAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OAuthError\";\n }\n}\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\", (col) => col.notNull())\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(\"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}\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 clientSecretRef: string;\n redirectUri: string;\n returnUrl?: string;\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 state = base64url(randomBytes(32));\n const pkce = method.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 if (method.scope.length > 0) params.set(\"scope\", method.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: fillOAuthUrl(method.tokenUrl, input.props),\n authorization_method: method.authorizationMethod ?? null,\n return_url: input.returnUrl ?? 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 );\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 clientSecret: string,\n): { form: Record<string, string>; headers: Record<string, string> } {\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\" | \"authorization_method\" | \"redirect_url\"\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 data: { ...previous?.data, ...response },\n };\n}\n\nexport async function exchangeCode(\n attempt: OAuthAttemptRow,\n code: string,\n clientSecret: string,\n egress?: EgressPolicy,\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 egress,\n );\n return tokenSetFrom(response, {\n token_url: attempt.token_url,\n authorization_method: method,\n redirect_url: attempt.redirect_uri,\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 OAuthError(\"Stored OAuth2 token is malformed; reconnect\");\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.\n refreshIfDue(source: OAuthConnectionSource): 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 ) {}\n\n refreshIfDue(source: OAuthConnectionSource): Promise<void> {\n const refOf = (name: string) =>\n source.secretRefs?.find((entry) => entry.name === name)?.ref;\n const tokenRef = refOf(OAUTH_TOKEN);\n const secretRef = refOf(OAUTH_CLIENT_SECRET);\n const clientId = source.config?.[OAUTH_CLIENT_ID];\n if (!tokenRef || !secretRef || typeof clientId !== \"string\") {\n return Promise.resolve();\n }\n let pending = this.inFlight.get(tokenRef);\n if (!pending) {\n pending = this.refresh(tokenRef, secretRef, clientId).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 secretRef: string,\n clientId: string,\n ): Promise<void> {\n const store = await this.secrets();\n const tokens = parseTokenSet(await store.get(tokenRef));\n if (!tokenDue(tokens, Math.round(Date.now() / 1000))) return;\n const auth = clientAuth(\n tokens.authorization_method,\n clientId,\n await store.get(secretRef),\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 this.egress,\n );\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\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 new OAuthError(\n `Refreshing the OAuth2 token failed; reconnect: ${detail}`,\n );\n }\n // A sign-in that landed meanwhile is newer than this refresh.\n const current = parseTokenSet(await store.get(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","// 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\n// Named where it is enforced: this is the one piece served ctx.reactor, and\n// the blocks below are the surface that port exists for.\nimport { blockKey } from \"@powerhousedao/pieces-framework/block-type\";\nimport { REACTOR_PORT_PIECE } from \"../pieces/index.js\";\n\nexport const REACTOR_PIECE = REACTOR_PORT_PIECE;\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 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.\nexport function fromSample(value: unknown, depth = 0): OutputTreeNode[] {\n if (value === null || typeof value !== \"object\" || depth > MAX_DEPTH) {\n return [];\n }\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>);\n return 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);\n return {\n name,\n type: kind,\n ...(children.length > 0 ? { children } : {}),\n };\n });\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// Envelope both document blocks return; state children come from the model.\nexport function documentBlockTree(\n stateChildren: OutputTreeNode[],\n): OutputTreeNode[] {\n return [\n leaf(\"documentId\", \"PHID!\"),\n leaf(\"documentType\", \"String!\"),\n leaf(\"name\", \"String\"),\n {\n name: \"state\",\n type: \"object\",\n description: \"Document global state after the actions applied\",\n ...(stateChildren.length > 0 ? { children: stateChildren } : {}),\n },\n ];\n}\n\nexport function documentGetTree(\n stateChildren: OutputTreeNode[],\n): OutputTreeNode[] {\n return [\n ...documentBlockTree(stateChildren).filter((node) => node.name !== \"state\"),\n leaf(\"slug\", \"String\"),\n {\n name: \"state\",\n type: \"object\",\n description: \"Document global state as read\",\n ...(stateChildren.length > 0 ? { children: stateChildren } : {}),\n },\n ];\n}\n\nexport function documentFindTree(): OutputTreeNode[] {\n return [\n leaf(\"count\", \"Int!\"),\n {\n name: \"documents\",\n type: \"array\",\n children: [\n leaf(\"documentId\", \"PHID!\"),\n leaf(\"documentType\", \"String!\"),\n leaf(\"name\", \"String\"),\n leaf(\"slug\", \"String\"),\n ],\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\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/flows 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, calling other platform flows.\n \"@activepieces/piece-todos\",\n \"@activepieces/piece-tables\",\n \"@activepieces/piece-subflows\",\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 { 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\";\nconst CACHE_TTL_MS = 60 * 60 * 1000;\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\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 // 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 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\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 ? fetchJson(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 ${source?.baseUrl ?? \"?\"} did not answer: ${String(fromRegistry.reason)}`,\n );\n }\n if (fromCloud.status === \"rejected\") {\n if (registry.length === 0) throw asError(fromCloud.reason);\n logger.warn(`Serving registry pieces only: ${String(fromCloud.reason)}`);\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\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 registry as CatalogSuggestionEntry[],\n cloud as CatalogSuggestionEntry[],\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[]): 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 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[]),\n toSummaries(lists.cloud as CatalogEntry[]),\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 configured registry answers for its own pieces, and\n// anything it does not have comes from the cloud.\n// Only a 404 is the configured registry saying it does not serve that name.\n\n// Anything else -- a 500, a timeout, a refused connection -- is the registry\n// failing to answer, and falling through on that would quietly hand a name the\n// deployment reserved for its own registry to the public cloud instead.\nfunction registrySilentOn(error: unknown): boolean {\n return error instanceof CatalogStatusError && error.status === 404;\n}\n\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 if (!registrySilentOn(error)) throw error;\n logger.debug(\n `${source.baseUrl} does not serve \"${packageName}\": ${String(error)}`,\n );\n }\n }\n return fetchJson(pieceUrl(packageName, version));\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() + CACHE_TTL_MS });\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() + CACHE_TTL_MS,\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() + CACHE_TTL_MS,\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 { BlockSearchHit } 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 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's blocks as search hits, so a block the reactor ships is findable\n// whether or not the published catalog answered.\nexport function localSearchHits(\n descriptor: PieceDescriptor,\n pieceName: string,\n version: string,\n): BlockSearchHit[] {\n const pieceDisplayName = descriptor.displayName || pieceName;\n const logoUrl = descriptor.logoUrl ?? \"\";\n return [\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}\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 // 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 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","// Action/trigger name search over the whole catalog. The index is built\n// lazily from one list request (suggestionType=ACTION_AND_TRIGGER) and cached.\nimport {\n fetchCatalogWithSuggestions,\n reasonOf,\n type CatalogSuggestionEntry,\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 type BlockSearchStatus = \"ready\" | \"indexing\" | \"error\";\n\nexport interface BlockSearchResult {\n status: BlockSearchStatus;\n hits: BlockSearchHit[];\n // Number of pieces the index covers; 0 while indexing.\n indexedPieces: number;\n error: string | null;\n}\n\ninterface IndexEntry {\n hit: BlockSearchHit;\n // Lower-cased searchable text, in ranking order.\n name: string;\n description: string;\n piece: string;\n}\n\nexport interface BlockSearchIndex {\n entries: IndexEntry[];\n pieces: number;\n}\n\nconst INDEX_TTL_MS = 60 * 60 * 1000;\nconst DEFAULT_LIMIT = 30;\nconst MAX_LIMIT = 100;\n\nexport function buildSearchIndex(\n raw: CatalogSuggestionEntry[],\n): BlockSearchIndex {\n const entries: IndexEntry[] = [];\n let pieces = 0;\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 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 const displayName = item.displayName ?? item.name;\n const description = item.description ?? \"\";\n entries.push({\n hit: {\n pieceName,\n pieceVersion,\n name: item.name,\n pieceDisplayName,\n logoUrl,\n displayName,\n description,\n kind,\n strategy: kind === \"trigger\" ? (item.type ?? null) : null,\n ...reasonOf(\n pieceUnsupported ??\n (kind === \"trigger\" ? unsupportedTrigger(item) : undefined),\n ),\n },\n name: `${displayName} ${item.name}`.toLowerCase(),\n description: description.toLowerCase(),\n piece: pieceDisplayName.toLowerCase(),\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 += 1;\n }\n return { entries, pieces };\n}\n\n// Pieces a reactor package ships, indexed the same way. They are handed in\n// rather than fetched: the catalog API has never heard of them.\nexport function indexFromHits(hits: BlockSearchHit[]): BlockSearchIndex {\n const pieces = new Set<string>();\n const entries = hits.map((hit) => {\n pieces.add(hit.pieceName);\n return {\n hit,\n name: `${hit.displayName} ${hit.name}`.toLowerCase(),\n description: hit.description.toLowerCase(),\n piece: hit.pieceDisplayName.toLowerCase(),\n };\n });\n return { entries, pieces: pieces.size };\n}\n\n// A piece this reactor installed wins its own name, the way it does in the\n// catalog: listing both would offer a versioned published block beside the\n// installed one, and picking the published block would bypass the copy that\n// actually runs.\nfunction merge(\n index: BlockSearchIndex | undefined,\n local: BlockSearchIndex | undefined,\n): BlockSearchIndex {\n const localEntries = local?.entries ?? [];\n const localNames = new Set(localEntries.map((entry) => entry.hit.pieceName));\n const published = (index?.entries ?? []).filter(\n (entry) => !localNames.has(entry.hit.pieceName),\n );\n const shadowed = new Set(\n (index?.entries ?? [])\n .map((entry) => entry.hit.pieceName)\n .filter((name) => localNames.has(name)),\n );\n return {\n entries: [...localEntries, ...published],\n // Each package counted once, so the total says how many pieces were\n // searched rather than how many listings were merged.\n pieces: (local?.pieces ?? 0) + (index?.pieces ?? 0) - shadowed.size,\n };\n}\n\n// Every query token must appear somewhere; hits rank by where the first\n// token lands: name prefix, then name, then piece name, then description.\nexport function searchIndex(\n index: BlockSearchIndex,\n query: string,\n limit = DEFAULT_LIMIT,\n): BlockSearchHit[] {\n const tokens = query.toLowerCase().split(/\\s+/).filter(Boolean);\n if (tokens.length === 0) return [];\n const scored: { score: number; entry: IndexEntry }[] = [];\n for (const entry of index.entries) {\n const haystack = `${entry.name} ${entry.piece} ${entry.description}`;\n if (!tokens.every((token) => haystack.includes(token))) continue;\n const first = tokens[0];\n const score = entry.name.startsWith(first)\n ? 0\n : entry.name.includes(first)\n ? 1\n : entry.piece.includes(first)\n ? 2\n : 3;\n scored.push({ score, entry });\n }\n scored.sort(\n (a, b) =>\n a.score - b.score ||\n a.entry.hit.displayName.localeCompare(b.entry.hit.displayName),\n );\n return scored\n .slice(0, Math.min(Math.max(limit, 1), MAX_LIMIT))\n .map(({ entry }) => entry.hit);\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// Never blocks on the index build: callers poll while status is \"indexing\".\n\n// The status describes the published catalog alone, because that is the half\n// that can be slow or unreachable. Local pieces are searched either way, so a\n// reactor with no network still finds the blocks it ships.\nexport function searchBlocks(\n query: string,\n limit?: number,\n local?: BlockSearchIndex,\n): BlockSearchResult {\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 hits: searchIndex(merge(undefined, local), query, limit),\n indexedPieces: local?.pieces ?? 0,\n error: message,\n };\n }\n if (!index.value) {\n return {\n status: \"indexing\",\n hits: searchIndex(merge(undefined, local), query, limit),\n indexedPieces: local?.pieces ?? 0,\n error: null,\n };\n }\n const merged = merge(index.value, local);\n return {\n status: \"ready\",\n hits: searchIndex(merged, query, limit),\n indexedPieces: merged.pieces,\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 { IPieceWorker } from \"../pieces/index.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport interface RunScope {\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}\n\nconst storage = new AsyncLocalStorage<RunScope>();\n\nexport function withRunScope<T>(\n scope: RunScope,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(scope, fn);\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 currentStepTest(): boolean {\n return storage.getStore()?.stepTest ?? false;\n}\n","// The host's half of `ctx.reactor`: the operations a package piece asks for,\n// run against this reactor through the subgraph's client.\n\n// Everything here is what could not cross the worker boundary — model modules\n// and their factories, drive nodes, a PHDocument's operations — so the piece\n// keeps the block's own semantics and the reactor stays on this side of it.\nimport type { WorkflowCaller, WorkflowRuntimeHostDeps } from \"./host.js\";\nimport { currentDocumentRecorder } from \"./run-scope.js\";\nimport type {\n ReactorCreateInput,\n ReactorDocumentSummary,\n ReactorExecuteInput,\n ReactorFindInput,\n ReactorModelDetail,\n ReactorModelSummary,\n ReactorPort,\n} from \"../pieces/index.js\";\nimport {\n createAction,\n withSignaturePolicy,\n type Action,\n type PHDocument,\n} from \"document-model\";\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\";\nconst DRIVE_DOCUMENT_TYPES = new Set([\n DRIVE_DOCUMENT_TYPE,\n \"powerhouse/reactor-drive\",\n]);\n\n// The index rejects an empty filter, so a typeless sweep asks per type; this\n// caps what each one contributes before the caller slices.\nconst FIND_PAGE_LIMIT = 100;\n\n// Design time resolves options for an editor, never edits documents: a piece\n// asking to write there is refused rather than authorized.\nconst DESIGN_TIME_WRITES_REFUSED =\n \"Reactor writes are not available while resolving design-time options\";\n\nconst DESIGN_TIME_CALLER_REQUIRED =\n \"Design-time reactor access requires an authenticated request\";\n\n// Base actions every document type accepts, beyond its model's own.\nconst BASE_ACTIONS = [\n {\n type: \"SET_NAME\",\n module: \"base\",\n inputSchema: \"input SetNameInput {\\n name: String!\\n}\",\n },\n];\n\ninterface DriveTarget {\n driveId: string;\n parentFolder?: string;\n}\n\n// The value at a dotted path inside a document's global state. Anything that\n// is not a plain object on the way down ends the walk: a path into a scalar is\n// a mismatch, not an error, because the documents being filtered are of one\n// type only by convention and the step cannot know every shape it will meet.\nfunction stateValueAt(document: PHDocument, path: string): unknown {\n const globalState = (document.state as Record<string, unknown>).global;\n let current: unknown = globalState;\n for (const segment of path.split(\".\")) {\n if (typeof current !== \"object\" || current === null) return undefined;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n// Compared as strings, so a step whose value came from an expression matches a\n// number in state: every expression resolves to text by the time it reaches\n// here, and `\"42\" !== 42` would make the match silently impossible.\nexport function matchesState(\n document: PHDocument,\n match: { path: string; value: string } | undefined,\n): boolean {\n if (!match) return true;\n const value = stateValueAt(document, match.path);\n if (typeof value === \"string\") return value === match.value;\n // Only the scalars a state field plausibly holds. A path landing on an\n // object, an array or nothing is a mismatch rather than an error — the\n // documents being filtered share a type only by convention, and the step\n // cannot know every shape it will meet.\n if (\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\"\n ) {\n return String(value) === match.value;\n }\n return false;\n}\n\nexport function documentSummary(\n document: PHDocument,\n withState: boolean,\n): ReactorDocumentSummary {\n const globalState = (document.state as Record<string, unknown>).global;\n const stateName =\n globalState && typeof globalState === \"object\"\n ? (globalState as Record<string, unknown>).name\n : undefined;\n return {\n documentId: document.header.id,\n documentType: document.header.documentType,\n // Models usually keep the display name in state; header name can lag.\n name:\n (typeof stateName === \"string\" && stateName) ||\n document.header.name ||\n \"\",\n slug: document.header.slug,\n ...(withState ? { state: globalState } : {}),\n };\n}\n\n// Reducer failures don't reject execute(): the operation is still recorded,\n// with the reason on operation.error and the state left exactly as it was.\n\n// So a dispatch that wrote nothing at all comes back looking like any other,\n// and the only thing standing between that and a step reporting success is\n// this. It fails the call instead, which is what the block needs: its payload\n// may be model output, and a silent no-op is the worst way to learn that.\n\n// Per scope, because an operation's index counts within its own scope. A tail\n// taken across all of them sorts one scope's indexes against another's, and a\n// document-scope CREATE_DOCUMENT at index 0 displaces the failed global\n// operation at index 0 that a fresh document's first dispatch leaves.\nfunction assertOperationsApplied(\n document: PHDocument,\n dispatched: readonly { scope?: string }[],\n): void {\n const perScope = new Map<string, number>();\n for (const action of dispatched) {\n const scope = action.scope ?? \"global\";\n perScope.set(scope, (perScope.get(scope) ?? 0) + 1);\n }\n const failed = [...perScope].flatMap(([scope, count]) =>\n [...(document.operations[scope] ?? [])]\n .sort((a, b) => a.index - b.index)\n .slice(-count)\n .filter((operation) => operation.error !== undefined),\n );\n if (failed.length === 0) return;\n // All of them: a payload a model wrote tends to fail a field at a time, and\n // naming only the first sends the author back for another run to find the\n // next. The reducer's own message carries the field and what it wanted.\n throw new Error(\n failed\n .map(\n (operation) =>\n `Action ${operation.action.type} failed: ${operation.error ?? \"unknown error\"}`,\n )\n .join(\"; \"),\n );\n}\n\nexport class SubgraphReactorPort implements ReactorPort {\n constructor(private readonly host: WorkflowRuntimeHostDeps) {}\n\n private get client() {\n return this.host.reactorClient;\n }\n\n async models(): Promise<ReactorModelSummary[]> {\n const page = await this.client.getDocumentModelModules();\n return page.results\n .map((module) => module.documentModel.global)\n .map((model) => ({ documentType: model.id, name: model.name }))\n .filter((entry) => entry.documentType)\n .sort((a, b) => a.documentType.localeCompare(b.documentType));\n }\n\n async model(documentType: string): Promise<ReactorModelDetail> {\n const module = await this.client.getDocumentModelModule(documentType);\n const model = module.documentModel.global;\n const latest = model.specifications.at(-1);\n return {\n documentType,\n name: model.name,\n stateSchema: latest?.state.global.schema ?? null,\n actions: [\n // flatMap rather than filter+map: an unnamed operation is dropped, and\n // this is the shape that narrows `name` for the caller's benefit.\n ...(latest?.modules ?? []).flatMap((specModule) =>\n specModule.operations.flatMap((operation) =>\n operation.name\n ? [\n {\n type: operation.name,\n module: specModule.name,\n inputSchema: operation.schema ?? null,\n },\n ]\n : [],\n ),\n ),\n ...BASE_ACTIONS,\n ],\n };\n }\n\n async get(input: {\n documentId: string;\n branch?: string;\n }): Promise<ReactorDocumentSummary> {\n const document = await this.client.get<PHDocument>(input.documentId);\n return this.handOver(documentSummary(document, true));\n }\n\n async find(input: ReactorFindInput): Promise<ReactorDocumentSummary[]> {\n const limit = input.limit ?? FIND_PAGE_LIMIT;\n let results: PHDocument[];\n if (input.documentType) {\n // The index takes both, so a step that named a type and a drive gets\n // documents of that type in that drive — not every document of the type.\n results = await this.findByType(\n input.documentType,\n limit,\n input.parentId,\n );\n } else if (input.parentId) {\n const page = await this.client.find(\n { parentId: input.parentId },\n undefined,\n {\n cursor: \"\",\n limit,\n },\n );\n results = page.results;\n } else {\n // The index rejects an empty filter, so sweep every installed type.\n const types = (await this.models()).map((model) => model.documentType);\n const pages = await Promise.all(\n types.map((type) => this.findByType(type, limit)),\n );\n results = pages.flat();\n }\n const seen = new Set<string>();\n return this.handOver(\n results\n .filter((document) => {\n if (seen.has(document.header.id)) return false;\n seen.add(document.header.id);\n return true;\n })\n // The index cannot query state, so a state match is applied to the page\n // that was read. A caller that needs to match across more documents than\n // the page holds raises `limit`; silently matching a prefix of the type\n // would look like \"no such document\".\n .filter((document) => matchesState(document, input.match))\n .map((document) => documentSummary(document, input.withState === true)),\n );\n }\n\n async create(input: ReactorCreateInput): Promise<ReactorDocumentSummary> {\n const target = input.parentId\n ? await this.resolveDriveTarget(input.parentId)\n : null;\n if (!target) {\n const created = await this.client.createEmpty<PHDocument>(\n input.documentType,\n { parentIdentifier: input.parentId },\n );\n // createEmpty takes no name, so naming it is a first operation. The\n // drive path below sets the header instead, before the file lands.\n if (!input.name) return this.handOver(documentSummary(created, true));\n const naming = createAction(\"SET_NAME\", { name: input.name });\n const named = await this.client.execute<PHDocument>(\n created.header.id,\n \"main\",\n [naming],\n );\n assertOperationsApplied(named, [naming]);\n return this.handOver(documentSummary(named, true));\n }\n // createEmpty only records the parent relationship; a drive also needs an\n // ADD_FILE node, or the document is created but invisible in the drive.\n const module = await this.client.getDocumentModelModule(input.documentType);\n const empty = withSignaturePolicy(\n module.utils.createDocument() as PHDocument,\n await this.client.getCreateSignaturePolicy(),\n );\n // The node name comes from the header, so set it before the file lands.\n if (input.name) empty.header.name = input.name;\n const created = await this.client.drives.addFile<PHDocument>(\n target.driveId,\n empty,\n target.parentFolder,\n );\n return this.handOver(documentSummary(created, true));\n }\n\n async execute(input: ReactorExecuteInput): Promise<ReactorDocumentSummary> {\n const actions: Action[] = input.actions.map((entry) =>\n createAction(\n entry.type,\n entry.input,\n undefined,\n undefined,\n entry.scope ?? \"global\",\n ),\n );\n const document = await this.client.execute<PHDocument>(\n input.documentId,\n input.branch ?? \"main\",\n actions,\n );\n // The inputs rather than the built actions: they carry the scope each one\n // was asked for, which is the scope its operation was appended to.\n assertOperationsApplied(document, input.actions);\n return this.handOver(documentSummary(document, true));\n }\n\n // A run is served only with what its steps read, so each document is\n // journaled against the run before its summary leaves the host.\n private async handOver<\n T extends ReactorDocumentSummary | ReactorDocumentSummary[],\n >(summaries: T): Promise<T> {\n const record = currentDocumentRecorder();\n if (record) {\n const list: ReactorDocumentSummary[] = Array.isArray(summaries)\n ? summaries\n : [summaries];\n await record(list.map((summary) => summary.documentId));\n }\n return summaries;\n }\n\n private async findByType(\n type: string,\n limit: number,\n parentId?: string,\n ): Promise<PHDocument[]> {\n try {\n const page = await this.client.find(\n { type, ...(parentId ? { parentId } : {}) },\n undefined,\n { cursor: \"\", limit },\n );\n return page.results;\n } catch {\n // One unreadable model must not sink a whole-reactor sweep.\n return [];\n }\n }\n\n // Where a new document's drive node belongs, when the parent implies one.\n private async resolveDriveTarget(\n parentId: string,\n ): Promise<DriveTarget | null> {\n try {\n const parent = await this.client.get<PHDocument>(parentId);\n // A plain document parent gets a relationship only, as before.\n return DRIVE_DOCUMENT_TYPES.has(parent.header.documentType)\n ? { driveId: parent.header.id }\n : null;\n } catch {\n // Not a document at all: it may be a folder node inside a drive.\n return this.findFolderDrive(parentId);\n }\n }\n\n private async findFolderDrive(nodeId: string): Promise<DriveTarget | null> {\n // Every type that counts as a drive, not just the common one: a folder in\n // a reactor-drive would otherwise look like no drive at all.\n const pages = await Promise.all(\n [...DRIVE_DOCUMENT_TYPES].map((type) =>\n this.findByType(type, FIND_PAGE_LIMIT),\n ),\n );\n for (const drive of pages.flat()) {\n try {\n const node = await this.client.drives.getNode(drive.header.id, nodeId);\n if (node.kind === \"folder\") {\n return { driveId: drive.header.id, parentFolder: nodeId };\n }\n } catch {\n // Not in this drive.\n }\n }\n return null;\n }\n}\n\n// Design-time `ctx.reactor`, bound to the caller behind the GraphQL request.\n// A piece's options()/props() code is the package's, not the reactor's.\nexport class ScopedDesignTimeReactorPort implements ReactorPort {\n private readonly inner: SubgraphReactorPort;\n\n constructor(\n private readonly host: WorkflowRuntimeHostDeps,\n private readonly caller: WorkflowCaller | undefined,\n ) {\n this.inner = new SubgraphReactorPort(host);\n }\n\n models(): Promise<ReactorModelSummary[]> {\n return this.inner.models();\n }\n\n model(documentType: string): Promise<ReactorModelDetail> {\n return this.inner.model(documentType);\n }\n\n async get(input: {\n documentId: string;\n branch?: string;\n }): Promise<ReactorDocumentSummary> {\n if (!this.caller) throw new Error(DESIGN_TIME_CALLER_REQUIRED);\n await this.host.assertCanRead(input.documentId, this.caller);\n return this.inner.get(input);\n }\n\n async find(input: ReactorFindInput): Promise<ReactorDocumentSummary[]> {\n const found = await this.inner.find(input);\n // Filtered rather than refused: one unreadable document in a sweep is not\n // the caller's error, and the list is what options() offers.\n const allowed = await Promise.all(\n found.map((document) => this.canRead(document.documentId)),\n );\n return found.filter((_, index) => allowed[index]);\n }\n\n create(_input: ReactorCreateInput): Promise<ReactorDocumentSummary> {\n return Promise.reject(new Error(DESIGN_TIME_WRITES_REFUSED));\n }\n\n execute(_input: ReactorExecuteInput): Promise<ReactorDocumentSummary> {\n return Promise.reject(new Error(DESIGN_TIME_WRITES_REFUSED));\n }\n\n private async canRead(documentId: string): Promise<boolean> {\n if (!this.caller) return false;\n return this.host\n .assertCanRead(documentId, this.caller)\n .then(() => true)\n .catch(() => false);\n }\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}=${showCursor(value)} from workflow ${flowKey()}; keeping ${\n isPlausibleCursor(kept, now) ? String(kept) : \"no cursor\"\n }`,\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 type { WorkflowRuntimeHostDeps } from \"./host.js\";\nimport {\n ActivepiecesBlockExecutor,\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 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 { join } from \"node:path\";\nimport {\n currentBoundConnections,\n currentPieceWorker,\n currentRunId,\n currentStepTest,\n currentWorkflowId,\n} from \"./run-scope.js\";\nimport { PROJECT_SCOPE_KEY } from \"./piece-store-port.js\";\nimport { packagePieces } from \"./piece-registry.js\";\nimport { SubgraphReactorPort } from \"./reactor-port.js\";\nimport { packageFromConnectorId } from \"./connector-id.js\";\nimport { runnableDefinition, type RunnableDefinition } from \"./runnable.js\";\nimport type { OAuthTokenRefresher } from \"./oauth.js\";\n\nconst pieceLogger = childLogger([\"workflow\", \"piece\"]);\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\") await oauth?.refreshIfDue(source);\n return shapeConnection(source, secrets);\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(process.cwd(), \".ph\", \"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 process.cwd(),\n \".ph\",\n \"ap-attachment-staging\",\n);\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): BlockExecutor {\n // No handler map: the document blocks are a piece now, and they reach the\n // reactor through the port below like any other package piece would.\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 // 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 // Served only to a piece this reactor's packages ship; the executor\n // withholds it from everything the resolver fetched.\n reactor: new SubgraphReactorPort(host),\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 const line = `[${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 ? { attachments, stagingRoot: ATTACHMENT_STAGING_DIR }\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 config: step.config,\n timeoutSeconds: step.timeoutSeconds,\n propertySettings: propertySettings(step.propertySettings),\n skip: step.skip,\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 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","// 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 ASSERT_BLOCK = action(\"assert\");\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 type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport {\n parseSecretRef,\n secretRefFromId,\n SecretDeletedError,\n SecretNotFoundError,\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 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(\"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 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 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(process.cwd(), \".ph\", \"secrets.key\");\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 }\n const key = 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 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: { value: string; label?: string }): Promise<SecretStat> {\n const now = new Date().toISOString();\n const row: SecretRow = {\n id: randomBytes(16).toString(\"hex\"),\n label: input.label ?? 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 async get(ref: string): Promise<string> {\n const row = await this.row(ref);\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 * The error for a SECRET names its ref, never a value. */\nexport async function resolveVariables(\n variables: readonly TypedVariable[],\n secrets: SecretProvider,\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 } 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 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 status: \"SUCCEEDED\" | \"FAILED\";\n output?: unknown;\n error?: string;\n durationMs: number;\n}\n\n// What a single-step test reads a tested block's sample from.\nexport type TestSample =\n | { kind: \"untested\" | \"stale\" | \"hidden\" }\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 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 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","// 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 type { IRelationalDb } from \"@powerhousedao/shared/processors\";\nimport {\n redact,\n redactMessage,\n type StepExecutionRecord,\n type WorkflowRunResult,\n} from \"../pieces/index.js\";\nimport { childLogger } from \"document-model\";\nimport { sql, type Kysely } from \"kysely\";\nimport { randomUUID } from \"node:crypto\";\nimport { PROJECT_SCOPE_KEY } from \"./piece-store-port.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 // 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 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 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}\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 status: string; // ENABLED | DISABLED | ERROR\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 // Written for rolling-deploy overlap; not enforced yet.\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}\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\nexport interface WorkflowRuntimeDB {\n run: RunRow;\n step_execution: StepExecutionRow;\n run_document: RunDocumentRow;\n trigger_state: TriggerStateRow;\n trigger_dedupe: TriggerDedupeRow;\n piece_store: PieceStoreRow;\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 run that was matched and journaled but never started. Recorded as FAILED\n// so it is both visible and rerunnable: rerun() replays the trigger payload\n// with no completed steps, which is exactly the run that never happened.\nexport const ABANDONED_PENDING_RUN_ERROR =\n \"Reactor stopped before the matched trigger started its run; rerun it to fire the workflow with the same payload\";\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\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(\"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 // Additive migration for journals created before per-step journaling: the\n // upsert in recordStep/finishRun needs this constraint to conflict on.\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 // 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 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\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 // 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 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 return migrateTriggerStoreState(db);\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 );\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// 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.\nfunction stepValues(runId: string, ordinal: number, step: StepExecutionRecord) {\n return {\n run_id: runId,\n ordinal,\n step_id: step.stepId,\n step_key: step.key,\n piece_name: step.pieceName,\n block_name: step.blockName,\n status: step.status,\n input: jsonOrNull(redact(step.input)),\n output: jsonOrNull(redact(step.output)),\n port: step.port ?? null,\n error: step.error ? redactMessage(step.error) : 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 };\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 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: string | null,\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 })\n .onConflict((oc) => oc.columns([\"workflow_id\", \"dedupe_key\"]).doNothing())\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_key\",\n \"piece_name\",\n \"block_name\",\n \"status\",\n \"port\",\n \"error\",\n \"started_at\",\n \"ended_at\",\n \"piece_version\",\n \"piece_source\",\n \"version_match\",\n \"version_note\",\n \"config_hash\",\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}\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\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 await store.recoverAbandonedRuns();\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 let query = this.db\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: ORPHANED_RUN_ERROR,\n ended_at: new Date().toISOString(),\n })\n .where(\"status\", \"=\", \"RUNNING\");\n // Failing a run this process is still executing would hand rerun() a live\n // run, and its side effects would happen twice.\n if (this.runsInFlight.size > 0) {\n query = query.where(\"id\", \"not in\", [...this.runsInFlight]);\n }\n // Counted off RETURNING: the knex-backed dialect reports no row count.\n const recovered = (await query.returning(\"id\").execute()).length;\n if (recovered > 0) {\n logger.warn(\n `Recovered ${recovered} workflow run(s) left RUNNING by a stopped reactor; they are now FAILED and rerunnable`,\n );\n }\n return recovered;\n }\n\n // A PENDING run left by a stopped process: it was matched and journaled but\n // nothing ever started it. Recovery for RUNNING runs cannot reach it — that\n // sweep must not touch a row a live enqueue is about to adopt — so it gets\n // its own pass, run once when the journal opens.\n async recoverAbandonedRuns(): Promise<number> {\n let query = this.db\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: ABANDONED_PENDING_RUN_ERROR,\n ended_at: new Date().toISOString(),\n })\n .where(\"status\", \"=\", PENDING_RUN_STATUS);\n if (this.runsInFlight.size > 0) {\n query = query.where(\"id\", \"not in\", [...this.runsInFlight]);\n }\n // Counted off RETURNING: the knex-backed dialect reports no row count.\n const recovered = (await query.returning(\"id\").execute()).length;\n if (recovered > 0) {\n logger.warn(\n `Recovered ${recovered} workflow run(s) journaled by a stopped reactor but never started; they are now FAILED and rerunnable`,\n );\n }\n return recovered;\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.insertPendingRun(this.db, id, options);\n // In flight from here: the row is this process's to finish, and no sweep\n // of either kind may close it out underneath the run about to start.\n this.runsInFlight.add(id);\n return id;\n }\n\n // Claims the dedupe key and journals the PENDING run in one transaction, so\n // a crash cannot keep the claim without the run. Null when already claimed.\n async claimAndEnqueueRun(\n dedupeKey: string,\n ttlMs: number,\n nowIso: string,\n options: EnqueueRunOptions,\n ): Promise<string | null> {\n const id = randomUUID();\n const claimed = await this.db.transaction().execute(async (trx) => {\n if (\n !(await claimDedupeIn(\n trx,\n options.workflowId,\n dedupeKey,\n ttlMs,\n nowIso,\n id,\n ))\n ) {\n return false;\n }\n await this.insertPendingRun(trx, id, options);\n return true;\n });\n if (!claimed) return null;\n this.runsInFlight.add(id);\n return id;\n }\n\n private async insertPendingRun(\n db: Kysely<WorkflowRuntimeDB>,\n id: string,\n options: EnqueueRunOptions,\n ): Promise<void> {\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: jsonOrNull(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 })\n .execute();\n }\n\n // Adopts an enqueued row: the run starts now, with the definition fire() read.\n async beginRun(\n runId: string,\n details: { workflowName: string; workflowVersion: number },\n ): Promise<void> {\n this.runsInFlight.add(runId);\n 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 .execute();\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: jsonOrNull(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 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_id): a re-executed step corrects its row.\n async recordStep(\n runId: string,\n ordinal: number,\n step: StepExecutionRecord,\n ): Promise<void> {\n const values = stepValues(runId, ordinal, step);\n const { run_id: _run, step_id: _step, ...mutable } = values;\n await this.db\n .insertInto(\"step_execution\")\n .values({ id: randomUUID(), ...values })\n .onConflict((oc) =>\n oc.columns([\"run_id\", \"step_id\"]).doUpdateSet(mutable),\n )\n .execute();\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 async finishRun(\n runId: string,\n result: WorkflowRunResult,\n executionOrder?: ReadonlyMap<string, number>,\n ): Promise<void> {\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 if (result.steps.length > 0) {\n try {\n await this.sweepSteps(runId, result, 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 notes = runWarningNotes(result);\n await this.db\n .updateTable(\"run\")\n .set({\n status: result.status,\n error: result.error ? redactMessage(result.error) : null,\n ended_at: new Date().toISOString(),\n warnings: notes.length,\n warning_notes: notes.length > 0 ? JSON.stringify(notes) : null,\n })\n .where(\"id\", \"=\", runId)\n .execute();\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 .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.db\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_id\"]).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 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 async failRun(runId: string, error: string): Promise<void> {\n this.runsInFlight.delete(runId);\n await this.db\n .updateTable(\"run\")\n .set({\n status: \"FAILED\",\n error: redactMessage(error),\n ended_at: new Date().toISOString(),\n })\n .where(\"id\", \"=\", runId)\n .execute();\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 async getSteps(runId: string): Promise<StepExecutionRow[]> {\n return this.db\n .selectFrom(\"step_execution\")\n .selectAll()\n .where(\"run_id\", \"=\", runId)\n .orderBy(\"ordinal\", \"asc\")\n .execute();\n }\n\n // Steps of many runs in one query, each run's in execution order. Without\n // `withData` the input and output blobs are left out (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 .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) return;\n await this.db\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 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 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 this.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 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, null);\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 // 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\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 // 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","// 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","// Opt-in pruning of the run journal. Off unless PH_WORKFLOWS_RUN_RETENTION_DAYS\n// is a positive number; finished runs older than that go with their children.\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// Undefined means retention is off.\nexport function runRetentionMs(\n env: Record<string, string | undefined> = process.env,\n): number | undefined {\n const days = Number(env[RUN_RETENTION_ENV]);\n return days > 0 ? days * DAY_MS : undefined;\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 // 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(`Unsupported setSchedule cron \"${cron}\"; using the default`);\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 {\n blockLabel,\n bundleResolver,\n canonicalJson,\n checkDynamicProperties,\n DEFAULT_EGRESS_POLICY,\n hashOf,\n DynamicPropertiesError,\n extractDedupeKey,\n pieceModuleRef,\n PieceWorker,\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 PieceResolver,\n type PieceWorkerResult,\n type PropertySettingDef,\n type RecordedSchedule,\n type TriggerHookRequest,\n type TriggerRenew,\n} from \"../pieces/index.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 { 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 TriggerStateRow,\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 // 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 resolveAuth: (\n connectionId: string | null | undefined,\n request?: ConnectionRequest,\n ) => Promise<unknown>;\n fire: (workflowId: string, payload: unknown, kind: string) => void;\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?: PieceWorker;\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 // 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 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(`Unsupported setSchedule cron \"${cron}\"; using the default`);\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\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: PieceWorker;\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 timer?: NodeJS.Timeout;\n // Lifecycle ops serialize so enable/disable/poll never interleave per store.\n private ops: Promise<unknown> = Promise.resolve();\n private ticking = false;\n private warnedMissingJournal = false;\n\n constructor(private readonly options: TriggerSupervisorOptions) {\n this.worker = options.worker ?? new PieceWorker();\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.now = options.now ?? (() => new Date());\n this.egress =\n options.egress === undefined\n ? DEFAULT_EGRESS_POLICY\n : (options.egress ?? undefined);\n }\n\n start(): void {\n if (this.timer) return;\n this.timer = setInterval(() => {\n this.tick().catch((error: unknown) => {\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.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: registration churn and ticks share one lane.\n private enqueue<T>(task: () => Promise<T>): Promise<T> {\n const run = this.ops.then(task);\n this.ops = run.catch(() => undefined);\n return run;\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 upsert(binding: TriggerBinding): Promise<void> {\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 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(() => this.enable(binding, previous));\n }\n\n remove(workflowId: string): Promise<void> {\n const binding = this.unbind(workflowId);\n return this.enqueue(() => this.disable(workflowId, binding));\n }\n\n // A deleted workflow: disabled as remove() does, then its row and FLOW\n // store 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 return this.enqueue(async () => {\n const store = await this.options.store();\n if (!store) return;\n await this.disable(workflowId, binding);\n await store.deleteTriggerState(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.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(() =>\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.options.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. ${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(binding: PieceTriggerBinding): Promise<unknown> {\n return this.enqueue(async () => {\n const store = await this.options.store();\n try {\n const result = await this.hook(binding, \"test\");\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(() => this.hook(binding, \"onHandshake\", { payload }));\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 deliverWebhook(workflowId: string, payload: unknown): Promise<void> {\n return this.enqueue(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.options.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 try {\n const result = await this.hook(binding, \"run\", { payload });\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 if (row?.status === \"ENABLED\") {\n await store.recordPollSuccess(\n workflowId,\n VESTIGIAL_STORE_STATE,\n now.toISOString(),\n new Date(now.getTime() + row.interval_ms).toISOString(),\n );\n }\n for (const item of result.output) {\n await this.fireItem(store, binding, item, now);\n }\n } catch (error) {\n await rewind();\n throw error;\n }\n });\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<() => Promise<void>> {\n const before = await store.listPieceStore(\"FLOW\", workflowId);\n return async () => {\n try {\n await store.deletePieceStore(\"FLOW\", workflowId);\n for (const [key, value] of Object.entries(before)) {\n await store.setPieceStoreValue(\"FLOW\", workflowId, key, value);\n }\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 }\n };\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 } = {},\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.options.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 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: { flowId: binding.workflowId, projectId: PROJECT_SCOPE_KEY },\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 },\n {\n timeoutMs: this.hookTimeoutMs,\n ...(pieceStore ? { hostCalls: storeHandlers(pieceStore) } : {}),\n },\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 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 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.options.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 existing = await store.getTriggerState(binding.workflowId);\n const now = this.now();\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 const webhook = runtime.delivery === \"webhook\";\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: \"ENABLED\",\n store_state: VESTIGIAL_STORE_STATE,\n interval_ms: intervalMs,\n next_poll_at: 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 ${blockLabel(binding.block)} for workflow ${binding.workflowId} (every ${intervalMs}ms)`,\n );\n } catch (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): ${message}` +\n (retryAt\n ? `; retrying at ${retryAt.toISOString()}`\n : \"; not retrying\"),\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 // 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: \"ENABLED\",\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}: ${message}`,\n );\n }\n }\n\n private async disable(\n workflowId: string,\n binding?: TriggerBinding,\n ): Promise<void> {\n const store = await this.options.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.options.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 async tick(): Promise<void> {\n if (this.ticking) return;\n this.ticking = true;\n try {\n await this.enqueue(() => this.pollDue());\n } finally {\n this.ticking = false;\n }\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 async retryOneEnable(): Promise<void> {\n const now = this.now().getTime();\n const next = [...this.enableRetries]\n .filter(([, retry]) => retry.at <= now)\n .sort((a, b) => a[1].at - b[1].at)\n .at(0);\n if (!next) return;\n const [workflowId, retry] = next;\n const binding = this.bindings.get(workflowId);\n if (!binding) {\n this.enableRetries.delete(workflowId);\n return;\n }\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 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 pollDue(): Promise<void> {\n const store = await this.options.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 for (const row of due) {\n const binding = this.bindings.get(row.workflow_id);\n if (!binding) {\n // Zombie row: the registry no longer knows this workflow.\n await store.setTriggerStatus(row.workflow_id, \"DISABLED\");\n continue;\n }\n if (isSchedule(binding)) {\n await this.fireSchedule(store, row, binding);\n } else {\n await this.poll(store, row, binding);\n }\n }\n await this.renewDue(store);\n await this.retryOneEnable();\n }\n\n private async renewDue(store: WorkflowRunStore): Promise<void> {\n const due = await store.listDueTriggerRenewals(this.now().toISOString());\n for (const row of due) {\n const binding = this.bindings.get(row.workflow_id);\n if (!binding) {\n await store.setTriggerStatus(row.workflow_id, \"DISABLED\");\n continue;\n }\n if (isSchedule(binding)) {\n await store.setTriggerRenewAt(row.workflow_id, null);\n continue;\n }\n await this.renew(store, row, binding);\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): ${message}; retrying at ${retryAt.toISOString()}`,\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 await store.recordPollSuccess(\n row.workflow_id,\n \"{}\",\n now.toISOString(),\n nextAt.toISOString(),\n );\n this.options.fire(\n binding.workflowId,\n schedulePayload(schedule, scheduledFor, now),\n SCHEDULE_TRIGGER_KIND,\n );\n } catch (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}: ${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 try {\n const result = await this.hook(binding, \"run\");\n if (!Array.isArray(result.output)) {\n throw new Error(\n `Trigger run returned ${typeof result.output}, expected an array`,\n );\n }\n await store.recordPollSuccess(\n row.workflow_id,\n VESTIGIAL_STORE_STATE,\n now.toISOString(),\n new Date(now.getTime() + row.interval_ms).toISOString(),\n );\n for (const item of result.output) {\n await this.fireItem(store, binding, item, now);\n }\n } catch (error) {\n await rewind();\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): ${message}`,\n );\n }\n }\n\n // One workflow run per output item; _dedupe_key suppresses 30s repeats.\n private async fireItem(\n store: WorkflowRunStore,\n binding: PieceTriggerBinding,\n item: unknown,\n now: Date,\n ): Promise<void> {\n const dedupeKey = extractDedupeKey(item);\n if (dedupeKey) {\n const claimed = await store.claimDedupe(\n binding.workflowId,\n dedupeKey,\n DEDUPE_TTL_MS,\n now.toISOString(),\n );\n if (!claimed) return;\n }\n this.options.fire(\n binding.workflowId,\n item,\n pieceTriggerKind(binding.block),\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","// 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 { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\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 blockLabel,\n blockPorts,\n builtinPiece,\n containsRedactedMarker,\n describeBuiltinPiece,\n isHostBound,\n servesReactorPort,\n stepBlock,\n triggerBlock,\n declaredConnectionIds,\n DEFAULT_EGRESS_POLICY,\n resolvedBlock,\n stepConfigHash,\n pieceModuleRef,\n reactorHandlers,\n PieceWorker,\n PieceWorkerError,\n PieceWorkerPool,\n PieceWorkerTimeoutError,\n rememberSecrets,\n resolveExpressions,\n runWorkflow,\n UnsupportedPieceFeatureError,\n authMethodFor,\n type PieceAuthDescriptor,\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 SecretProvider,\n type SecretStore,\n type StepExecutionRecord,\n type WorkflowRunResult,\n} from \"../pieces/index.js\";\nimport {\n childLogger,\n generateId,\n type Action,\n type ILogger,\n type OperationWithContext,\n} from \"document-model\";\nimport {\n actions as connectionActions,\n type ConnectionDocument,\n} from \"@powerhousedao/workflow/document-models/connection\";\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 OAuthStart,\n type OAuthTokenRefresher,\n} from \"./oauth.js\";\nimport {\n actions as workflowActions,\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 documentBlockTree,\n documentEventTree,\n documentFindTree,\n documentGetTree,\n documentSchemaTree,\n documentTypesTree,\n fieldsFromSdl,\n fromOutputSchema,\n hasOutputSchemaFields,\n fromSample,\n lifecycleTriggerTree,\n scheduleTriggerTree,\n webhookTriggerTree,\n type OutputTree,\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 localSearchHits,\n triggersResult,\n} from \"./local-catalog.js\";\nimport {\n indexFromHits,\n searchBlocks,\n type BlockSearchIndex,\n type BlockSearchResult,\n} from \"./block-search.js\";\nimport { installedPiece, installedPieces } from \"./piece-registry.js\";\nimport { BlockResolver } from \"./block-resolver.js\";\nimport { ScopedDesignTimeReactorPort } from \"./reactor-port.js\";\nimport {\n bundleCacheDir,\n configuredEgress,\n createBlockExecutor,\n DocumentConnectionResolver,\n pieceResolver,\n resolveConnectionAuth,\n stepDefinition,\n toWorkflowDefinition,\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 { createPieceStorePort, PROJECT_SCOPE_KEY } from \"./piece-store-port.js\";\nimport { currentWorkflowId, withRunScope } from \"./run-scope.js\";\nimport {\n ASSERT_BLOCK,\n BRANCH_BLOCK,\n isCoreBlock,\n MANUAL_BLOCK,\n SCHEDULE_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 triggerSamplePayload,\n untestedError,\n upstreamStepIds,\n type StepTestResult,\n type TestSample,\n} from \"./step-test.js\";\nimport {\n MAX_LIST_RUNS,\n WorkflowRunStore,\n type RunRow,\n type StepExecutionRow,\n type TriggerStateRow,\n} from \"./store.js\";\nimport { decodeRunCursor, encodeRunCursor } from \"./run-cursor.js\";\nimport {\n RETENTION_SWEEP_INTERVAL_MS,\n runRetentionMs,\n sweepRetention,\n} from \"./run-retention.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\";\n\nexport type PersistedRunResult = WorkflowRunResult & { runId: string | null };\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. */\nexport interface RunRecord {\n row: RunRow;\n steps: StepExecutionRow[];\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\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\";\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\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\n// The documents a run's trigger names: the one whose operation fired it, and\n// the drive it sits in.\nfunction 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\nfunction triggerDocumentIds(payload: unknown): string[] {\n const record = inputRecord(payload);\n return [\n ...new Set(\n [\n stringField(record, \"documentId\"),\n stringField(record, \"driveId\"),\n ].filter((id): id is string => id !== undefined),\n ),\n ];\n}\n\n// Absence is reported by name: the error may cross an RPC boundary.\nfunction isAbsent(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"DocumentNotFoundError\" ||\n error.name === \"DocumentDeletedError\")\n );\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\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.\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 run kind a design-time test is journaled under.\nexport const TEST_TRIGGER_KIND = \"test\";\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// 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\nexport class WorkflowRuntimeService {\n private readonly host: WorkflowRuntimeHostDeps;\n private readonly logger: ILogger;\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 readonly storePromise: Promise<WorkflowRunStore>;\n private secretsPromise?: Promise<SecretStore>;\n private oauthAttemptsPromise?: Promise<OAuthAttemptStore>;\n private tokenRefresher?: OAuthTokenRefresher;\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.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(\n host.attachments,\n () => currentWorkflowId(),\n // A host that serves attachments without answering for them reads\n // nothing: an unanswerable relationship is not a permitted one.\n (documentId, ref) =>\n host.canReadAttachmentRef?.(documentId, ref) ??\n Promise.resolve(false),\n )\n : undefined;\n this.storePromise = WorkflowRunStore.create(host.relationalDb);\n this.storePromise.catch((error: unknown) => {\n this.logger.error(\"Failed to open the workflow run store: @error\", error);\n });\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 void this.storePromise.then(sweep, () => undefined);\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.\n async store(): Promise<WorkflowRunStore | undefined> {\n try {\n return await this.storePromise;\n } catch {\n return undefined;\n }\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 { get: (ref) => this.secrets().then((store) => store.get(ref)) };\n }\n\n private oauthAttempts(): Promise<OAuthAttemptStore> {\n this.oauthAttemptsPromise ??= OAuthAttemptStore.create(\n this.host.relationalDb,\n );\n return this.oauthAttemptsPromise;\n }\n\n private oauthRefresher(): OAuthTokenRefresher {\n return (this.tokenRefresher ??= new StoreTokenRefresher(\n () => this.secrets(),\n this.designEgress,\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 await this.updateRegistration(document.header.id, document.state.global);\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 // Registers the runnable trigger; `onlyIfChanged` passes over draft edits.\n private async updateRegistration(\n workflowId: string,\n state: WorkflowState,\n onlyIfChanged = false,\n ): Promise<void> {\n const key = registrationKey(state);\n if (\n onlyIfChanged &&\n !this.unarmed.has(workflowId) &&\n this.registeredAs.get(workflowId) === key\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 trigger =\n state.status === \"ENABLED\"\n ? runnableDefinition(state).trigger\n : undefined;\n const block = trigger ? triggerBlock(trigger) : undefined;\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);\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);\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(workflowId: string, binding: TriggerBinding): void {\n this.supervisor()\n .upsert(binding)\n .catch((error: unknown) => {\n this.logger.error(`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 ): 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);\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.logger.error(\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}: ${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.logger.error(\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 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 // 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.logger.error(\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.logger.error(`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 document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\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 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 // 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 const hints = collectLifecycleParentHints(operations);\n for (const { operation, context } of operations) {\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.scope === DOCUMENT_SCOPE) {\n await this.matchDocumentLifecycle(operation, context, hints, opKey);\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 // Only a status or published-trigger change re-arms.\n await this.refreshRegistration(\n context.documentId,\n operation.resultingState,\n true,\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 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 opKey,\n );\n }\n }\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.\n private async enqueueFire(\n workflowId: string,\n payload: unknown,\n kind: string,\n opKey: string,\n ): Promise<void> {\n const store = await this.store();\n if (!store) {\n this.fireFromTrigger(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 time.\n let runId: string | null;\n try {\n runId = await store.claimAndEnqueueRun(\n `op:${opKey}`,\n OPERATION_DEDUPE_TTL_MS,\n new Date().toISOString(),\n { workflowId, triggerKind: kind, 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 this.fireFromTrigger(workflowId, payload, kind);\n return;\n }\n if (runId === null) return;\n this.fireFromTrigger(workflowId, payload, kind, runId);\n }\n\n private fireFromTrigger(\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 this.logger.error(\n `${kind} run failed for workflow ${workflowId}`,\n error,\n );\n },\n );\n }\n\n // Fires once per document, from whichever source reports it first. Only a fire that\n // matched is recorded, so a creation with 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 opKey: string,\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 await this.enqueueFire(target.workflowId, payload, kind, opKey);\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 try {\n await (await this.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 // The registry goes now, so deliveries stop at once. onDisable and the\n // token revoke queue behind any enable in flight, off the ingestion path.\n private disarmDeleted(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 this.supervisor()\n .forget(workflowId)\n .then(async () => (await this.endpoints())?.revoke(workflowId))\n .catch((error: unknown) => {\n this.logger.error(\n `Could not disarm deleted workflow ${workflowId}`,\n error,\n );\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 opKey: string,\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(\n kind,\n {\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 opKey,\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 opKey: 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(\n kind,\n {\n documentId,\n documentType: documentType ?? null,\n name,\n driveId,\n parentId: stringField(record, \"parentFolder\") ?? null,\n operation,\n },\n opKey,\n );\n }\n\n private triggerSupervisor?: TriggerSupervisor;\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 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) => {\n this.fireFromTrigger(workflowId, payload, kind);\n },\n webhookUrlFor: async (workflowId) =>\n (await this.mintWebhookEndpoint(workflowId))?.url,\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 return this.triggerSupervisor;\n }\n\n startTriggerSupervisor(): void {\n this.supervisor().start();\n }\n\n stopTriggerSupervisor(): void {\n this.triggerSupervisor?.stop();\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 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 // Forked on the editor's first request and never replaced, so it outlives\n // a hot reload unless it goes with everything else.\n this.designWorker?.dispose();\n this.designWorker = undefined;\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 // A waiting test verifies as the draft's trigger would once armed.\n const test = this.webhookTests.get(workflowId);\n if (test) return this.policyOf(test.config, workflowId);\n\n const registration = this.registry.get(workflowId);\n if (!registration) return undefined;\n\n // A piece owns its own verification and parsing: its run hook decides what\n // the request means, or rejects it.\n if (registration.kind === PIECE_WEBHOOK_KIND) return {};\n if (registration.kind !== WEBHOOK_TRIGGER_KIND) return undefined;\n return this.policyOf(registration.config, workflowId);\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 const workflowId = request.key;\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 return { status: test.config.responseStatus };\n }\n const registration = this.registry.get(workflowId);\n if (!registration) return UNAUTHORIZED;\n if (registration.kind === PIECE_WEBHOOK_KIND) {\n return this.deliverToPiece(registration.binding, request);\n }\n if (registration.kind !== WEBHOOK_TRIGGER_KIND) return UNAUTHORIZED;\n\n const { config } = registration;\n const payload = webhookPayload(request);\n\n if (config.responseMode === \"async\") {\n this.fireFromTrigger(workflowId, payload, WEBHOOK_TRIGGER_KIND);\n return { status: config.responseStatus };\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 run = await Promise.race([\n this.fire(workflowId, payload, WEBHOOK_TRIGGER_KIND).then(\n (result) => ({ ok: true, result }) as const,\n (error: unknown) => ({ ok: false, error }) as const,\n ),\n timeout(DELIVERY_TIMEOUT_MS),\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 const message =\n run.error instanceof Error ? run.error.message : String(run.error);\n this.logger.error(`Webhook run failed for ${workflowId}: ${message}`);\n return {\n status: 500,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({ error: message }),\n };\n }\n\n return {\n status: run.result.status === \"SUCCEEDED\" ? config.responseStatus : 500,\n contentType: JSON_CONTENT_TYPE,\n body: JSON.stringify({\n runId: run.result.runId,\n status: run.result.status,\n error: run.result.error ?? null,\n }),\n };\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.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 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.logger.error(\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 (await this.secrets()).get(config.secretRef);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(\n `Webhook secret unavailable for ${workflowId}: ${message}`,\n );\n return undefined;\n }\n }\n\n private readonly descriptors = new Map<string, PieceDescriptor>();\n private designWorker?: PieceWorker;\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 ??= new PieceWorker();\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 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 const ids = nodes\n .filter(\n (node) =>\n \"documentType\" in node &&\n node.documentType === WORKFLOW_DOCUMENT_TYPE,\n )\n .map((node) => node.id);\n return this.readableRows(ids, (id) => id, ctx);\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 async runsPage(args: RunsPageArgs, ctx?: WorkflowCaller): 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 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 return { row, steps: await store.getSteps(row.id) };\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 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 ??= new PieceWorker();\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 accountLabel: outcome.accountLabel ?? accountLabel,\n });\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 { [OAUTH_CLIENT_ID]: clientId, ...props } = (state.config ??\n {}) as Record<string, unknown>;\n if (typeof clientId !== \"string\" || clientId === \"\") {\n throw new OAuthError(\"Set the client ID before connecting\");\n }\n const clientSecretRef = state.secretRefs.find(\n (entry) => entry.name === OAUTH_CLIENT_SECRET,\n )?.ref;\n if (!clientSecretRef) {\n throw new OAuthError(\"Save the client secret before connecting\");\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: options.redirectUri,\n ...(options.returnUrl ? { returnUrl: options.returnUrl } : {}),\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 if (\n state.authType !== \"OAUTH2\" ||\n 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 tokens = await exchangeCode(\n attempt,\n callback.code,\n await secrets.get(attempt.client_secret_ref),\n this.designEgress,\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 try {\n if (ref) await secrets.rotate(ref, value);\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 })\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 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.name}\": ${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: ${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 // 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 searchBlocks(\n query: string,\n limit?: number,\n ): Promise<BlockSearchResult> {\n let local: BlockSearchIndex | undefined;\n try {\n local = indexFromHits(\n (await this.localPieces()).flatMap(({ piece, descriptor }) =>\n localSearchHits(descriptor, piece.name, piece.version),\n ),\n );\n } catch (error) {\n // The published half is still worth serving without them.\n this.logger.warn(`Could not index the package pieces: ${String(error)}`);\n }\n return searchBlocks(query, limit, 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 ): 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 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 this.designWorker ??= new PieceWorker();\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 // The reactor piece's options() reads the reactor it offers choices\n // from, over the same port a step of it would use.\n\n // The same identity rule the run path applies: design time is not a\n // way round it, and a piece offered the member would have none.\n ...(servesReactorPort(parsed.packageName)\n ? { reactorAccess: true }\n : {}),\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 },\n servesReactorPort(parsed.packageName)\n ? {\n hostCalls: reactorHandlers(\n new ScopedDesignTimeReactorPort(this.host, ctx),\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 return { source: \"none\", nodes: [] };\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 ASSERT_BLOCK:\n return { source: \"static\", nodes: [{ name: \"value\", type: \"value\" }] };\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: documentGetTree(stateChildren),\n };\n }\n case DOCUMENT_CREATE_BLOCK:\n case DOCUMENT_DISPATCH_BLOCK: {\n const stateChildren = await this.stateFields(\n staticString(record.documentType),\n );\n return {\n source: stateChildren.length > 0 ? \"schema\" : \"static\",\n nodes: documentBlockTree(stateChildren),\n };\n }\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 latest = module.documentModel.global.specifications.at(-1);\n for (const specModule of latest?.modules ?? []) {\n for (const operation of specModule.operations) {\n if (operation.name === actionType && operation.schema) {\n return fieldsFromSdl(operation.schema, { input: operation.name });\n }\n }\n }\n return [];\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 const test = await this.triggerTest(workflowId, trigger, options);\n const startedAt = new Date().toISOString();\n const recordTest = (\n outcome: Pick<\n StepExecutionRecord,\n \"status\" | \"output\" | \"port\" | \"error\"\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 await recordTest({\n status: \"FAILED\",\n error: pieceFailureDetail(error, \"Trigger test timed out\"),\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 ): 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 sample: () => this.supervisor().test(binding),\n };\n }\n\n // One-shot listeners: the next delivery to the workflow's endpoint is the\n // sample, and runs nothing.\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 await store.finishRun(runId, {\n status: record.status === \"FAILED\" ? \"FAILED\" : \"SUCCEEDED\",\n steps: [record],\n ...(record.error ? { error: record.error } : {}),\n });\n } catch (error) {\n this.logger.warn(\n `Could not journal the test of \"${record.key}\" on workflow ${workflowId}`,\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 \"${record.key}\" on workflow ${workflowId}`,\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 ??= 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 ));\n }\n\n // One child per run, N runs at a time. Sized by the operator: each slot is a\n // node process, so this is the reactor's real connector concurrency.\n private workers(): PieceWorkerPool {\n // A queue depth of 0 waits without limit, which is what one shared worker\n // did — a cap turns a saturated pool into failures instead of latency.\n return (this.pieceWorkers ??= new PieceWorkerPool({\n size: Number(process.env.PH_WORKFLOWS_RUN_CONCURRENCY) || undefined,\n maxQueueDepth:\n Number(process.env.PH_WORKFLOWS_RUN_QUEUE_DEPTH) || undefined,\n }));\n }\n\n async fire(\n workflowId: string,\n triggerPayload?: unknown,\n triggerKind = \"manual\",\n resume?: {\n completedSteps: Map<string, { output?: unknown; port?: string | null }>;\n rerunOf: string;\n },\n ctx?: WorkflowCaller,\n // A run this workflow's trigger already journaled as PENDING. Adopted\n // rather than created, so the row a matched operation left behind is the\n // row the run finishes in.\n enqueuedRunId?: string,\n ): Promise<PersistedRunResult> {\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 try {\n // \"manual\" is the only kind a caller can ask for; every other one is\n // system-initiated and already authorized by whatever armed the trigger.\n if (triggerKind === \"manual\") {\n await this.assertCanReadDocument(workflowId, ctx);\n }\n const document =\n await this.host.reactorClient.get<WorkflowDocument>(workflowId);\n if (document.header.documentType !== \"powerhouse/workflow\") {\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 if (state.status !== \"ENABLED\") {\n throw new Error(\n `Workflow is ${state.status}; only ENABLED workflows can fire`,\n );\n }\n definition = toWorkflowDefinition(state);\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 );\n }\n throw error;\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 let runId: string | null = enqueuedRunId ?? null;\n if (enqueuedRunId) {\n await store?.beginRun(enqueuedRunId, {\n workflowName: runJournalName(state.name, documentName),\n workflowVersion: runnable.version,\n });\n } else {\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 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 // 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 try {\n // Inside the try: a pool disposed while this run was starting up refuses\n // here, and the journal records the run as failed rather than leaving it\n // to be swept up as an orphan.\n session = this.workers().session();\n // Resolved per run, so a rotated secret takes effect on the next one.\n const { variables, secretValues } = await resolveVariables(\n runnable.variables,\n this.secretProvider(),\n );\n const journal = store;\n const journaledRunId = runId;\n const handed = new Set<string>();\n const result = await withRunScope(\n {\n workflowId,\n runId,\n connections,\n pieceWorker: session,\n recordDocuments: async (documentIds: string[]) => {\n for (const documentId of documentIds) handed.add(documentId);\n if (journal && journaledRunId) {\n await journal.recordRunDocuments(journaledRunId, documentIds);\n }\n },\n },\n () =>\n runWorkflow({\n definition: { ...definition, variables },\n executor,\n declaredPorts: blockPorts,\n ...(secretValues.length > 0 ? { redactValues: secretValues } : {}),\n triggerPayload,\n completedSteps: resume?.completedSteps,\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 executionOrder.set(record.stepId, ordinal);\n try {\n await store.recordStep(runId, ordinal, record);\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 \"${record.key}\" failed; the run continues without per-step durability`,\n error,\n );\n }\n }\n : undefined,\n }),\n );\n if (store && runId) {\n try {\n await store.finishRun(runId, result, executionOrder);\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 }\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 await store.failRun(\n runId,\n error instanceof Error ? error.message : String(error),\n );\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 }\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 if (run.status !== \"FAILED\") {\n throw new Error(`Only FAILED runs can be rerun; run is ${run.status}`);\n }\n const triggerPayload =\n run.trigger_payload === null\n ? undefined\n : (JSON.parse(run.trigger_payload) as unknown);\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 currentSteps = new Map(\n runnableDefinition(document.state.global).steps.map((step) => [\n step.id,\n stepDefinition(step),\n ]),\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 const completedSteps = new Map<\n string,\n { output?: unknown; port?: string | null }\n >();\n for (const row of await store.getSteps(runId)) {\n if (row.status !== \"SUCCEEDED\" && row.status !== \"REPLAYED\") continue;\n const current = currentSteps.get(row.step_id);\n if (\n !current ||\n current.key !== row.step_key ||\n row.config_hash === null ||\n stepConfigHash(current) !== row.config_hash\n ) {\n continue;\n }\n completedSteps.set(row.step_id, {\n output:\n row.output === null ? undefined : (JSON.parse(row.output) as unknown),\n port: row.port,\n });\n }\n return this.fire(\n run.workflow_id,\n triggerPayload,\n \"rerun\",\n { completedSteps, rerunOf: runId },\n ctx,\n );\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 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(state.variables, this.secretProvider());\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 = resolveExpressions(step.config, {\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.key}\" on workflow ${workflowId}`,\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 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 ...(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.failRun(runId, detail).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.key}\" out failed`,\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: record.status === \"FAILED\" ? \"FAILED\" : \"SUCCEEDED\",\n ...(served && record.output !== undefined\n ? { output: record.output }\n : {}),\n ...(record.error ? { error: record.error } : {}),\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 { payload, empty } = triggerSamplePayload(sample.output);\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 priorSteps[candidate.key] = { output: sample.output };\n samples.push({ label, value: sample.output });\n }\n return { triggerPayload, priorSteps, samples };\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 const output =\n row.output === null ? null : (JSON.parse(row.output) as unknown);\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 value = isTrigger\n ? triggerSamplePayload(sample.output).payload\n : sample.output;\n return {\n source: \"test\",\n nodes: fromSample(value),\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 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","// 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 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 { 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// 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 extends BaseReadModel {\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 });\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 await this.runtime.onOperations(items);\n }\n}\n"],"x_google_ignoreList":[23,24,25,26,27,28,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],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgBA,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;CACr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