@pgxsinkit/server 0.6.1 → 0.6.3

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
@@ -2,29 +2,29 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/circuits/subscribe.ts", "../src/circuits/compile.ts", "../src/circuits/edge.ts", "../src/circuits/stream-token.ts", "../src/circuits/engine-client.ts", "../src/events/pgmq-queue.ts", "../src/events/queue.ts", "../src/events/route.ts", "../src/events/identity.ts", "../src/mutations/route.ts", "../src/operations-log/schema.ts", "../src/operations-log/writer.ts", "../src/sql-state.ts", "../src/mutations/plpgsql-apply.ts", "../src/operations-log/ddl.ts", "../src/cors-origin.ts", "../src/router.ts", "../src/migrations/utilities.ts", "../src/events/consumer.ts", "../src/events/ddl.ts"],
4
4
  "sourcesContent": [
5
- "import type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport type {\n JwtClaims,\n RegistryRelations,\n RegistryTables,\n SyncRuntimeStatus,\n SyncServerAddress,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport { batchEventPaths, getSyncRegistryStreams } from \"@pgxsinkit/contracts\";\n\nimport type { EntitlementSet } from \"./circuits/edge\";\nimport type { CircuitsEngineClient } from \"./circuits/engine-client\";\nimport {\n barrierPath,\n createBarrierHandler,\n createRefreshHandler,\n createReleaseHandler,\n createSubscribeHandler,\n refreshPath,\n releasePath,\n subscribePath,\n} from \"./circuits/subscribe\";\nimport { createPgmqEventQueue } from \"./events/pgmq-queue\";\nimport type { EventQueue } from \"./events/queue\";\nimport { createEventIngestHandler, type EventGate, type EventsEnqueuedHook } from \"./events/route\";\nimport {\n authoritativeMutationPaths,\n batchMutationPaths,\n createMutationHandler,\n type StartupVerificationMode,\n} from \"./mutations/route\";\nimport { ensureOperationsLogSchema } from \"./operations-log/ddl\";\nimport type { OperationsLogConfig } from \"./operations-log/types\";\nimport { FetchRouter, type CorsScope } from \"./router\";\n\nconst defaultAllowedOrigins = [\"http://localhost:5173\", \"http://localhost:5174\"];\n\ninterface BunServerHandle {\n stop: () => void;\n}\n\ninterface BunNamespace {\n serve: (options: {\n port: number;\n hostname?: string;\n idleTimeout?: number;\n fetch: (request: Request) => Response | Promise<Response>;\n }) => BunServerHandle;\n}\n\n/**\n * How the operations-log table's presence is resolved at startup (ADR-0030 decision 3):\n * - `\"probe\"` (default): the safe degradation posture (ADR-0030) — one query ensures/confirms the table,\n * and logging is disabled at runtime (with a warning) if it is absent, so a missing table degrades\n * gracefully instead of failing writes.\n * - `\"enabled\"`: assume the table exists — NO query. If it is actually absent, writes then fail loudly.\n * - `\"disabled\"`: turn logging off with NO query.\n *\n * `\"enabled\" | \"disabled\"` are the serverless posture: paired with `startupVerification: \"deploy-time\"`,\n * a fresh worker sends zero queries before the mutation transaction itself.\n */\nexport type OperationsLogStartupMode = \"probe\" | \"enabled\" | \"disabled\";\n\n/**\n * The `deployment` profile owns the server's startup query posture (ADR-0030 decision 3). Its defaults\n * are the safe degradation posture — probe-and-verify at startup — so a long-lived host that never sets\n * it still verifies and degrades gracefully; serverless / per-request workers set\n * `{ startupVerification: \"deploy-time\", operationsLog: \"enabled\" | \"disabled\" }` for a\n * zero-startup-query first write.\n */\nexport interface DeploymentProfile {\n /** Governs ONLY the RLS auth-helper verify now (apply-fn drift is self-verifying). Default `\"in-process\"`. */\n startupVerification?: StartupVerificationMode;\n /** How the operations-log table presence is resolved. Default `\"probe\"`. */\n operationsLog?: OperationsLogStartupMode;\n}\n\nexport interface CreateSyncServerOptions<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n registry: TRegistry;\n db: TDb;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n /**\n * When set, the server serves the NATIVE read path's control plane (ADR-0055): subscribe, stream-token\n * re-mint, and the engine convergence barrier. Without it, none of those routes is registered and the\n * deployment is write-only.\n *\n * They share the single `resolveAuthClaims` adapter with the write path (ADR-0003), so read and write\n * authorization cannot diverge.\n */\n readPath?: {\n /** The Circuits engine's control API — never client-reachable; only this process calls it. */\n engine: CircuitsEngineClient;\n /**\n * The live entitlement set backing the shared tier. Omit when the registry declares no shared\n * shape — a shared subscription is then refused with that reason rather than silently allowed.\n */\n entitlements?: EntitlementSet;\n /** The stream-token signing key, shared with the edge. */\n key: CryptoKey;\n /** Per-deployment override of ADR-0055's 5-minute token lifetime. */\n ttlSeconds?: number;\n /** How long the barrier answer may be cached. Default 0 — see `createBarrierHandler`. */\n barrierMaxAgeSeconds?: number;\n /** Optional per-request extra params passed to the private tier's row filters. */\n resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;\n };\n operationsLog?: {\n enabled?: boolean;\n };\n /** Health check endpoint. Enabled by default at `/health`; `false` disables it, `{ path }` relocates it. */\n healthCheck?: boolean | { path: string };\n port?: number;\n host?: string;\n idleTimeoutSeconds?: number;\n allowedOrigins?: string[];\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n /**\n * The startup query posture (ADR-0030). The apply function now verifies its own ADR-0018 fingerprint\n * in-body on every call (SQLSTATE `PXS01` on drift), so there is no startup drift check to configure;\n * this governs only the RLS auth-helper verify and the operations-log presence resolution. Defaults\n * are the safe degradation posture (ADR-0030). See {@link DeploymentProfile}.\n */\n deployment?: DeploymentProfile;\n /**\n * The **Event lane**'s consent/entitlement gate (ADR-0053 decision 1): the lane's one function, and so an\n * option here rather than a registry field (the registry stays declarative data only). Called once per\n * event, after its payload validated and its identity resolved, and before anything is enqueued; a refusal\n * is a per-event `refused` verdict. Absent → every well-formed event is allowed. See {@link EventGate}.\n */\n eventGate?: EventGate;\n /**\n * Fired after an ingest request ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02): the\n * deployment-agnostic seam a SERVERLESS deployment uses to nudge whatever endpoint runs the consumer's\n * `drainOnce()`, so an interactive append drains in milliseconds instead of waiting for the next\n * scheduled tick. Fire-and-forget — it is called after the commit, its throw is caught and warn-logged,\n * and the scheduled sweep (not the nudge) is the delivery guarantee. Absent → nothing is nudged, which is\n * right for a deployment hosting the long-lived runner. See {@link EventsEnqueuedHook}.\n */\n onEventsEnqueued?: EventsEnqueuedHook;\n /**\n * The Event lane's queue backend. Defaults to the shipped pgmq backend over this server's own `db`\n * (`createPgmqEventQueue`), which is what makes an enqueue join the endpoint's transaction. Override it to\n * run the lane on another backend, or to substitute a fake in tests.\n */\n eventQueue?: EventQueue;\n /**\n * Opt-in per-request timing log (default false). When on, each mutation and shape-proxy request emits\n * one compact `[pgxsinkit-timing]` line with an ISO-8601(ms, UTC) timestamp and phase durations, for\n * attributing wall-clock latency against the client's `syncDebug` lines. Off by default — a pure\n * diagnostic surface that adds no standing query or latency when unset.\n */\n logTimings?: boolean;\n /**\n * The roles the INSTALLED apply function was generated with (`pgxsinkit-generate\n * --grant-execute-to <role>`, ADR-0054). Default `[]` — owner-only, the default the CLI generates.\n *\n * It is not a grant this server performs; it is how the server reproduces the artifact's ADR-0018\n * fingerprint, which hashes the ACL along with the rest of the body. Generate with a grant and leave\n * this unset and every write fails `PXS01` (stale artifact) — so the two lists must stay identical.\n */\n applyFunctionGrantExecuteTo?: readonly string[];\n /**\n * The schema the INSTALLED apply function lives in (`pgxsinkit-generate --function-schema <schema>`).\n * Default: unset — the artifact is generated unqualified and resolved through the connection's\n * `search_path`.\n *\n * It does two things at once, which is why one option drives both: the schema is part of the\n * fingerprinted body (the function names itself in its own self-check), AND it is how this server\n * QUALIFIES the call. Generate with `--function-schema` and leave this unset and the call goes out\n * unqualified — which either finds nothing (`42883`) or, worse, finds a same-named function elsewhere\n * on the `search_path` that then fails `PXS01` against a fingerprint it does not carry. The two must\n * name the same schema.\n */\n applyFunctionSchema?: string;\n}\n\nexport interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {\n tables: Array<keyof TRegistry & string>;\n modes: Record<string, TRegistry[keyof TRegistry][\"mode\"]>;\n}\n\nexport interface SyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n drizzle: TDb;\n fetch: (request: Request) => Promise<Response>;\n request: (path: string, init?: RequestInit) => Promise<Response>;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n status: SyncRuntimeStatus;\n address: SyncServerAddress | null;\n diagnostics: () => ServerDiagnostics<TRegistry>;\n}\n\nexport function createSyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n>(options: CreateSyncServerOptions<TRegistry, TDb>): SyncServer<TRegistry, TDb> {\n const db = options.db;\n const router = new FetchRouter();\n let bunServer: BunServerHandle | undefined;\n\n const status: SyncRuntimeStatus = {\n phase: \"ready\",\n isRunning: false,\n };\n\n let address: SyncServerAddress | null = null;\n const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);\n const operationsLogStartup = options.deployment?.operationsLog ?? \"probe\";\n // ADR-0030: how operations_log presence is resolved decides whether startup issues a query at all.\n // - \"probe\" (default): thread the presence probe into the effective config. operations_log is an\n // *optional* feature (default-enabled), so if logging was requested but the table is absent, disable\n // it at runtime rather than letting every write fail on a missing table — the documented degradation\n // (ensureOperationsLogSchema warns and returns `false`). The route awaits `operationsLogReady` before\n // any logOperation, so the corrected flag is in effect by the time logging runs, and the route holds\n // this same config object. (Board dogfooding: discarding this boolean 500'd every mutation on a\n // missing optional table.)\n // - \"enabled\": assume the table exists — NO query; logging stays on (an actual absence then fails\n // writes loudly, by design). \"disabled\": logging off — NO query.\n let operationsLogReady: Promise<void>;\n if (operationsLogStartup === \"probe\") {\n operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig).then((present) => {\n operationsLogConfig.enabled = operationsLogConfig.enabled && present;\n });\n } else {\n if (operationsLogStartup === \"disabled\") {\n operationsLogConfig.enabled = false;\n }\n operationsLogReady = Promise.resolve();\n }\n\n // CORS covers the canonical /api/* routes, plus the native control plane's own /sync/v1/* prefix.\n const corsScopes: CorsScope[] = [{ prefix: \"/api/\" }];\n if (options.readPath) {\n corsScopes.push({ prefix: \"/sync/v1/\" });\n }\n router.setCors(\n {\n origins: options.allowedOrigins ?? defaultAllowedOrigins,\n allowMethods: [\"GET\", \"POST\", \"OPTIONS\"],\n // `apikey`: a deployment gateway (Supabase) expects it on every request, so the browser client\n // sends it; it must be allowed in the preflight even though the server itself ignores it.\n allowHeaders: [\"Content-Type\", \"Authorization\", \"apikey\"],\n },\n corsScopes,\n );\n\n router.setErrorHandler((error) => {\n status.phase = \"degraded\";\n status.lastError = error instanceof Error ? error.message : \"Unexpected error\";\n options.onStatusChange?.(status);\n\n if (isValidationError(error)) {\n return Response.json({ message: \"Validation failed\", issues: error.issues }, { status: 400 });\n }\n\n return Response.json({ message: error instanceof Error ? error.message : \"Unexpected error\" }, { status: 500 });\n });\n\n const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);\n if (healthCheckPath) {\n router.get(healthCheckPath, () => Response.json({ ok: true }));\n }\n\n // The single mutation ingress point — all writes go through POST /api/mutations.\n const mutationHandlers = createMutationHandler(\n db,\n options.registry,\n operationsLogConfig,\n operationsLogReady,\n options.resolveAuthClaims,\n options.deployment?.startupVerification ?? \"in-process\",\n options.logTimings ?? false,\n options.applyFunctionGrantExecuteTo ?? [],\n options.applyFunctionSchema,\n );\n for (const path of batchMutationPaths) {\n router.post(path, mutationHandlers.batch);\n }\n for (const path of authoritativeMutationPaths) {\n router.post(path, mutationHandlers.authoritative);\n }\n\n // The Event lane's ingestion endpoint (ADR-0053 decision 3), mounted ONLY when the registry registers at\n // least one Event stream — a registry without streams has no event lane, and the path stays a 404. Nothing\n // is probed or provisioned here: the queues are deploy-time DDL (`pgxsinkit-generate --events`), so the\n // route preserves the zero-startup-query posture.\n const eventStreams = getSyncRegistryStreams(options.registry);\n if (eventStreams && Object.keys(eventStreams).length > 0) {\n const eventQueue = options.eventQueue ?? createPgmqEventQueue({ db });\n const eventHandler = createEventIngestHandler(db, options.registry, eventQueue, {\n ...(options.resolveAuthClaims ? { resolveAuthClaims: options.resolveAuthClaims } : {}),\n ...(options.eventGate ? { eventGate: options.eventGate } : {}),\n ...(options.onEventsEnqueued ? { onEventsEnqueued: options.onEventsEnqueued } : {}),\n logTimings: options.logTimings ?? false,\n });\n for (const path of batchEventPaths) {\n router.post(path, eventHandler);\n }\n }\n\n // The native control plane (ADR-0055). It shares the same resolveAuthClaims adapter as the write\n // path, so read and write authorization can never diverge (ADR-0003).\n //\n // Note what is NOT here: any route that serves shape DATA. Reads terminate on durable-streams\n // through the edge, which is the whole point of the topology — this process is asked once, at\n // subscribe time, and is then out of the read path entirely.\n if (options.readPath) {\n const readPath = options.readPath;\n const resolveAuthClaims = options.resolveAuthClaims;\n // Refused at construction, not at the first subscribe. Every read is bound to a subject in both\n // tiers (ADR-0055): the private tier fuses it into the predicate and the shared tier checks it\n // against the entitlement set, and a stream token with no subject would name a bearer no\n // revocation could ever reach. So a read path with no way to resolve a subject cannot grant\n // anything — it is a contradiction, and the only useful moment to say so is now, rather than as\n // a 401 every client then sits in.\n if (resolveAuthClaims === undefined) {\n throw new Error(\n \"[pgxsinkit] createSyncServer: `readPath` was configured without `resolveAuthClaims`. The native \" +\n \"read path mints a per-subject stream token, so it cannot serve a deployment that has no way to \" +\n \"resolve a subject. Provide `resolveAuthClaims`, or drop `readPath` for a write-only deployment.\",\n );\n }\n const subscribeOptions = {\n registry: options.registry,\n engine: readPath.engine,\n ...(readPath.entitlements ? { entitlements: readPath.entitlements } : {}),\n key: readPath.key,\n ...(readPath.ttlSeconds !== undefined ? { ttlSeconds: readPath.ttlSeconds } : {}),\n resolveAuthClaims,\n };\n\n router.post(subscribePath, createSubscribeHandler(subscribeOptions));\n router.post(refreshPath, createRefreshHandler(subscribeOptions));\n // The close half of subscribe. Every grant subscribe handed out is a named claim on an engine\n // shape, and a live claim blocks dormancy and eviction — so without this route every shape waits\n // out its full lease window before it can be reclaimed. The release is idempotent (each grant\n // names its own claim), and a release that never arrives is reclaimed by the lease anyway; see\n // `releaseStreamGrants`.\n router.post(releasePath, createReleaseHandler({ engine: readPath.engine, key: readPath.key, resolveAuthClaims }));\n router.get(\n barrierPath,\n createBarrierHandler({\n engine: readPath.engine,\n resolveAuthClaims,\n ...(readPath.barrierMaxAgeSeconds !== undefined ? { maxAgeSeconds: readPath.barrierMaxAgeSeconds } : {}),\n }),\n );\n }\n\n const fetch = router.fetch;\n\n return {\n drizzle: db,\n fetch,\n request: (path, init) => {\n const baseUrl = address === null ? \"http://localhost\" : `http://${address.host}:${address.port}`;\n return fetch(new Request(new URL(path, baseUrl).toString(), init));\n },\n start: async () => {\n if (bunServer) {\n return;\n }\n\n const bun = getBunNamespace();\n if (!bun) {\n throw new Error(\"createSyncServer.start() requires the Bun runtime\");\n }\n\n const host = options.host ?? \"0.0.0.0\";\n const port = options.port ?? 3001;\n const idleTimeout = options.idleTimeoutSeconds;\n\n bunServer = bun.serve({\n hostname: host,\n port,\n ...(idleTimeout !== undefined ? { idleTimeout } : {}),\n fetch,\n });\n\n status.isRunning = true;\n status.phase = \"ready\";\n delete status.lastError;\n address = { host, port };\n options.onStatusChange?.(status);\n },\n stop: async () => {\n bunServer?.stop();\n bunServer = undefined;\n status.isRunning = false;\n options.onStatusChange?.(status);\n },\n status,\n get address() {\n return address;\n },\n diagnostics: () => ({\n tables: Object.keys(options.registry) as Array<keyof TRegistry & string>,\n modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),\n }),\n };\n}\n\nexport function buildRegistrySchema<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): RegistryTables<TRegistry> {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction resolveHealthCheckPath(config?: boolean | { path: string }, defaultEnabled = false): string | null {\n if (config === false) {\n return null;\n }\n\n if (config === undefined && !defaultEnabled) {\n return null;\n }\n\n if (typeof config === \"object\" && \"path\" in config) {\n return config.path;\n }\n\n return \"/health\";\n}\n\nfunction getBunNamespace(): BunNamespace | undefined {\n const maybeBun = (globalThis as { Bun?: BunNamespace }).Bun;\n return maybeBun;\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction resolveOperationsLogConfig(options?: { enabled?: boolean }): OperationsLogConfig {\n return {\n enabled: options?.enabled ?? true,\n };\n}\n\nexport { authoritativeMutationPaths, batchMutationPaths, createMutationHandler } from \"./mutations/route\";\nexport type { StartupVerificationMode } from \"./mutations/route\";\nexport type { CorsConfig, CorsScope, FetchHandler, RouterErrorHandler } from \"./router\";\nexport { FetchRouter } from \"./router\";\nexport { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from \"./mutations/plpgsql-apply\";\nexport type { ApplyFunctionRenderOptions } from \"./mutations/plpgsql-apply\";\nexport { renderPgxsinkitUtilitiesMigration } from \"./migrations/utilities\";\nexport { ensureOperationsLogSchema, operationsLogRegclassTarget } from \"./operations-log/ddl\";\nexport { operationsLogTable } from \"./operations-log/schema\";\nexport { readSqlState } from \"./sql-state\";\nexport {\n createEventIngestHandler,\n eventIngestRequiresClaims,\n EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,\n} from \"./events/route\";\nexport type {\n CreateEventIngestHandlerOptions,\n EventGate,\n EventGateDecision,\n EventGateInput,\n EventIngestDb,\n EventsEnqueuedHook,\n EventsEnqueuedInfo,\n} from \"./events/route\";\nexport { assertEventQueueReceipts, eventStreamQueueName, MalformedEventQueueMessageError } from \"./events/queue\";\nexport type {\n DeadLetteredEventMessage,\n DeliveredEventMessage,\n EventQueue,\n EventQueueExecutor,\n EventQueueReadOptions,\n EventQueueReceipt,\n} from \"./events/queue\";\nexport { createPgmqEventQueue, PGMQ_DEAD_LETTER_KEY } from \"./events/pgmq-queue\";\nexport type { CreatePgmqEventQueueOptions } from \"./events/pgmq-queue\";\nexport {\n computeEventPollWaitMs,\n defineEventConsumer,\n DEFAULT_EVENT_CONSUMER_BATCH_SIZE,\n DEFAULT_EVENT_DRAIN_BUDGET_MS,\n DEFAULT_EVENT_MAX_ATTEMPTS,\n DEFAULT_EVENT_POLL_CEILING_MS,\n DEFAULT_EVENT_POLL_FACTOR,\n DEFAULT_EVENT_POLL_FLOOR_MS,\n DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n} from \"./events/consumer\";\nexport type {\n DefineEventConsumerOptions,\n EventConsumer,\n EventConsumerBatch,\n EventConsumerCallback,\n EventConsumerPollOptions,\n EventConsumerSleep,\n EventDeadLetterReport,\n EventDrainOptions,\n EventDrainSummary,\n EventPollReport,\n} from \"./events/consumer\";\nexport {\n EVENT_LANE_FINGERPRINT_PREFIX,\n eventLaneDdlFingerprint,\n eventLaneStreamNames,\n renderEventLaneMigration,\n} from \"./events/ddl\";\nexport { resolveEventIdentity } from \"./events/identity\";\nexport type { IdentityResolution } from \"./events/identity\";\n\n// The Circuits-native read path (ADR-0055) — shape lifecycle only. Reads terminate on\n// durable-streams and never traverse the engine.\nexport { compileShapeRequest, fingerprintShapeRequest, resolveEntryByShapeKey } from \"./circuits/compile\";\nexport type { CompiledShapeRequest, ShapeRequest } from \"./circuits/compile\";\nexport { CircuitsEngineError, createCircuitsEngineClient } from \"./circuits/engine-client\";\nexport type { CircuitsEngineClient, CircuitsEngineOptions } from \"./circuits/engine-client\";\nexport type { CircuitsShapeHandle, CreateShapeRequest } from \"./circuits/wire\";\nexport {\n DEFAULT_STREAM_TOKEN_TTL_SECONDS,\n findGrant,\n importStreamTokenKey,\n mintStreamToken,\n verifyStreamToken,\n} from \"./circuits/stream-token\";\nexport type {\n MintStreamTokenOptions,\n VerifyStreamTokenOptions,\n StreamGrant,\n StreamTokenClaims,\n StreamTokenVerification,\n} from \"./circuits/stream-token\";\nexport {\n authorizeStreamRead,\n createStreamGate,\n EntitlementsUnavailableError,\n readStreamToken,\n STREAM_READ_EXPOSED_HEADERS,\n} from \"./circuits/edge\";\nexport type { EntitlementSet, GateDecision, StreamAuthorizationOptions, StreamGateOptions } from \"./circuits/edge\";\nexport {\n barrierPath,\n CircuitsLeaseConfigError,\n createBarrierHandler,\n createRefreshHandler,\n createReleaseHandler,\n createSubscribeHandler,\n refreshPath,\n refreshStreamToken,\n releasePath,\n releaseStreamGrants,\n subscribePath,\n subscribeToShapes,\n} from \"./circuits/subscribe\";\nexport type {\n DeniedSubscription,\n GrantedSubscription,\n RefreshResult,\n SubscribeOptions,\n SubscribeResult,\n SubscriptionRequest,\n} from \"./circuits/subscribe\";\n",
6
- "import {\n readShapeTier,\n type JwtClaims,\n type PredicateValue,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n compileShapeRequest,\n fingerprintShapeRequest,\n resolveEntryByShapeKey,\n type CompiledShapeRequest,\n} from \"./compile\";\nimport { EntitlementsUnavailableError, type EntitlementSet } from \"./edge\";\nimport { CircuitsEngineError, type CircuitsEngineClient } from \"./engine-client\";\nimport { DEFAULT_STREAM_TOKEN_TTL_SECONDS, mintStreamToken, verifyStreamToken, type StreamGrant } from \"./stream-token\";\nimport type { CircuitsShapeHandle, CreateShapeRequest } from \"./wire\";\n\n/**\n * One shape a client wants to follow.\n *\n * A shape KEY and nothing else — deliberately (ADR-0055 decision 6). A shared-tier shape fans out to\n * one stream per scope the subject holds, and the control plane does that expansion because it is\n * the only side that knows the answer: it holds the entitlement set. A client naming its own scopes\n * could only ever restate that set redundantly or contradict it, and every contradiction is a\n * denial it then has to reconcile at boot.\n */\nexport interface SubscriptionRequest {\n shapeKey: string;\n}\n\n/** A subscription the control plane granted: what to read, and where. */\nexport interface GrantedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n shapeId: string;\n /** The durable-streams path, which is what the client follows through the edge. */\n streamPath: string;\n}\n\n/** A subscription the control plane declined, with why. */\nexport interface DeniedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n reason: string;\n}\n\nexport interface SubscribeResult {\n /** The stream token covering every granted subscription. Absent when nothing was granted. */\n token?: string;\n /** Seconds since the epoch. The client re-mints before this, in one request for the whole batch. */\n expiresAt?: number;\n granted: GrantedSubscription[];\n denied: DeniedSubscription[];\n}\n\nexport interface SubscribeOptions {\n registry: SyncTableRegistry;\n engine: CircuitsEngineClient;\n /**\n * The live entitlement set backing the SHARED tier.\n *\n * Optional, because a registry with no shared-tier shape has nothing to ask it. Omitting it is a\n * statement that this deployment has none: a shared-tier subscription is then refused with that\n * reason rather than silently permitted, so adding the first shared shape fails loudly instead of\n * serving one subject's rows to everyone.\n */\n entitlements?: EntitlementSet;\n /** The stream-token signing key, shared with the edge — the same process holds both. */\n key: CryptoKey;\n /** Per-deployment override of ADR-0055's 5-minute default. */\n ttlSeconds?: number;\n /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */\n params?: Record<string, unknown>;\n}\n\n/**\n * The engine's subscription lease is shorter than this deployment's token TTL — a **configuration**\n * fault, not a request one.\n *\n * The control plane renews every live claim on exactly one cadence: the token re-mint, which the\n * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The\n * engine releases a claim not renewed within `leaseSeconds` (`CIRCUITS_SHAPE_IDLE_SECS`).\n * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a\n * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The\n * factor of two is the margin for exactly one missed refresh.\n *\n * Refused loudly rather than papered over, because both numbers are the operator's and neither the\n * subject nor the client can do anything about either. The routes answer 503 — \"this deployment, not\n * you\" — and never a denial: a client told it lost entitlement truncates its rows.\n */\nexport class CircuitsLeaseConfigError extends Error {\n /** The engine's `CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */\n readonly leaseSeconds: number;\n /** The stream-token TTL this control plane is configured with. */\n readonly ttlSeconds: number;\n\n constructor(leaseSeconds: number, ttlSeconds: number) {\n super(\n `[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` +\n `CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +\n `(${ttlSeconds}s, the \\`ttlSeconds\\` option). Claims are renewed on the token re-mint, so a single ` +\n `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` +\n `it. Raise CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \\`ttlSeconds\\` to ` +\n `at most ${Math.floor(leaseSeconds / 2)}, or set CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +\n `leases entirely.`,\n );\n this.name = \"CircuitsLeaseConfigError\";\n this.leaseSeconds = leaseSeconds;\n this.ttlSeconds = ttlSeconds;\n }\n}\n\n/**\n * `leaseSeconds === 0` means the engine has dormancy — and with it leases — switched off, so there is\n * no window to fall out of and nothing to check. Anything else must cover two re-mints.\n */\nfunction assertLeaseCoversTtl(leaseSeconds: number, ttlSeconds: number): void {\n if (leaseSeconds !== 0 && leaseSeconds < 2 * ttlSeconds) throw new CircuitsLeaseConfigError(leaseSeconds, ttlSeconds);\n}\n\n/**\n * The engine must record a claim under the name it was given — on the create that TAKES it and on\n * every create that RENEWS it alike.\n *\n * An engine that renames a claim is one this control plane can neither renew nor release by id, which\n * is the whole protocol (fork ADR-0008): the renewal would take a second claim every time, and the\n * release would name something the engine never held. That is the wrong engine, not a degraded one,\n * so it throws rather than degrading — there is no answer this client could go on to give.\n */\nfunction assertClaimRecorded(handle: CircuitsShapeHandle, claim: string): void {\n if (handle.subscription === claim) return;\n throw new Error(\n `[pgxsinkit] the engine recorded this shape claim under \\`${handle.subscription}\\` rather than the ` +\n `subscription id it was sent (\\`${claim}\\`). Renewal and release are BY that id (fork ADR-0008), ` +\n `so an engine that renames a claim is not the one this client targets.`,\n );\n}\n\n/**\n * Compile one shape for one scope — the single form both the subscribe and the re-mint paths use.\n *\n * Shared between them on purpose: the re-mint RENEWS each grant's engine claim by repeating the create\n * that took it, so the request it sends has to be the request subscribe would build today. Two\n * spellings of \"compile this grant\" would be two chances for a renew to name a different definition\n * than the grant it is renewing — which the engine would answer with a different handle, and this\n * route would read as a revocation.\n */\nfunction compileGrant(\n options: Pick<SubscribeOptions, \"registry\" | \"params\">,\n claims: JwtClaims | null,\n shapeKey: string,\n scope?: readonly PredicateValue[],\n): CompiledShapeRequest {\n return compileShapeRequest(options.registry, {\n shapeKey,\n claims,\n ...(scope !== undefined ? { scope } : {}),\n ...(options.params ? { params: options.params } : {}),\n });\n}\n\n/** What a renewal attempt came to. `renewed` is the only outcome that keeps the grant. */\ntype RenewalOutcome = { renewed: true } | { revoked: string };\n\n/**\n * Renew one grant's engine claim: the SAME create, repeated with the SAME subscription id.\n *\n * This is the whole of the lease protocol on our side (fork ADR-0008). The engine has no separate\n * renew route because it needs none — a create naming a claim the shape already holds returns the same\n * handle, counts nothing, and moves the lease. So the re-mint, which already re-authorizes every grant\n * on the client's own refresh cadence, renews for free and renews exactly the grants that survived.\n *\n * The two failure outcomes are both \"this is no longer the stream the client follows\", and both end in\n * `revoked` rather than an error, because the client's answer to a revocation — truncate and\n * re-subscribe — is precisely the right one:\n *\n * - **A different handle.** The claim lapsed, or the shape was evicted, so this call re-subscribed\n * instead of renewing (ADR-0007) and the engine handed back a fresh shape on a fresh path. The\n * grant names the old one. The claim just taken is released immediately: nothing is following that\n * new stream, and the client's re-subscribe will take its own.\n * - **409.** The id names a different shape. Nothing was taken, so there is nothing to give back.\n *\n * Anything else the engine says is an OUTAGE and propagates — the route answers 503. A revocation\n * would tell the client it lost the scope, and a client told that clears the rows. An engine that\n * renames the claim propagates too, through {@link assertClaimRecorded}: that one is not an outage\n * either, it is the wrong engine.\n */\nasync function renewGrantClaim(\n engine: CircuitsEngineClient,\n request: CreateShapeRequest,\n grant: StreamGrant,\n ttlSeconds: number,\n): Promise<RenewalOutcome> {\n let handle;\n try {\n handle = await engine.createShape({ ...request, subscription: grant.claim });\n } catch (error) {\n if (error instanceof CircuitsEngineError && error.status === 409) {\n return { revoked: \"subscription id is held by another shape; re-subscribe\" };\n }\n throw error;\n }\n assertClaimRecorded(handle, grant.claim);\n // The handle comparison and the release of a fresh claim come BEFORE the lease guard, deliberately:\n // a misconfigured window is fatal to this request, and throwing it first would strand the claim\n // this very call just took.\n if (handle.shapeId !== grant.shapeId || handle.streamPath !== grant.path) {\n await engine.releaseShape(handle.shapeId, grant.claim);\n return { revoked: \"shape stream changed; re-subscribe\" };\n }\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n return { renewed: true };\n}\n\n/**\n * What one requested shape expands to: the scopes to compile it at.\n *\n * `[undefined]` — a single scope-less compile — is the private tier, whose subject arrives in the\n * claims instead. A shared-tier shape expands to one entry per entitled scope, and none is a\n * refusal rather than an empty success: a subject with no scopes has nothing to read, and returning\n * zero grants silently would leave the client waiting on streams that were never created.\n *\n * An unknown shapeKey deliberately expands to `[undefined]` and is refused downstream by\n * `compileShapeRequest`, so the message for \"no such shape\" has exactly one author.\n *\n * Throws {@link EntitlementsUnavailableError} when the set exists but cannot be trusted yet — an\n * outage, not a refusal, and the route turns it into a 503.\n */\nfunction expandToScopes(\n options: Pick<SubscribeOptions, \"registry\" | \"entitlements\">,\n subject: string,\n shapeKey: string,\n): { scopes: readonly (readonly PredicateValue[] | undefined)[] } | { refusal: string } {\n const entry: SyncTableEntry | undefined = resolveEntryByShapeKey(options.registry, shapeKey);\n const shape = entry?.shape;\n if (shape == null) return { scopes: [undefined] };\n if (readShapeTier(shape) === \"private\") return { scopes: [undefined] };\n\n if (options.entitlements === undefined) {\n return { refusal: \"shared-tier shape, but this deployment configured no entitlement set\" };\n }\n // A refusal above, a THROW here, and the difference is permanence. \"No entitlement set configured\"\n // is a statement about this deployment that will read the same on every future request. \"Not ready\"\n // is a statement about this instant, and answering it with a denial would tell the client it lost\n // the scope — which makes it clear those rows. See {@link EntitlementsUnavailableError}.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n const held = options.entitlements.scopesFor(subject, shapeKey);\n if (held.length === 0) return { refusal: \"no entitled scopes\" };\n return { scopes: held };\n}\n\n/**\n * Subscribe to a batch of shapes: compile each against the registry, check entitlement, register it\n * with the engine, and mint ONE token covering all of them.\n *\n * A shared-tier shape FANS OUT: one stream per scope the subject holds, so K requested shapes yield\n * however many grants their entitlements come to. Expansion happens here rather than on the client\n * because this is the side holding the entitlement set — see {@link SubscriptionRequest}.\n *\n * A partial result rather than an all-or-nothing one. A subject holding K scopes at boot may\n * legitimately have lost one of them, and failing the whole batch on that would deny them the K-1\n * they still hold — so a denial is reported per subscription and the rest proceed.\n *\n * That partiality covers AUTHORIZATION only. An engine that cannot answer — degraded, unreachable —\n * is not a denial and must never be reported as one: a client told \"not entitled\" truncates that\n * scope and unsubscribes, so reporting an outage that way would turn a transient engine fault into\n * client-side data loss. Engine failures propagate, and the route answers 503.\n *\n * An entitlement set that is not `ready` joins it. It is the same shape of failure — a dependency\n * that cannot answer right now — and the client's response to a denial is the same clear, so it\n * propagates as {@link EntitlementsUnavailableError} and the route answers 503 too. What stays a\n * denial is the set being absent altogether: that is a deployment's permanent configuration.\n *\n * Entitlement is checked HERE as well as at the edge, and the duplication is deliberate: this is\n * what stops a shape being created and a capability minted for a scope the subject never held. The\n * edge's check bounds how long an already-minted one keeps working.\n */\nexport async function subscribeToShapes(\n options: SubscribeOptions,\n claims: JwtClaims | null,\n requests: readonly SubscriptionRequest[],\n now: number,\n): Promise<SubscribeResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const granted: GrantedSubscription[] = [];\n const denied: DeniedSubscription[] = [];\n const grants: StreamGrant[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const request of requests) {\n const deny = (reason: string, scope?: readonly PredicateValue[]) =>\n denied.push({ shapeKey: request.shapeKey, ...(scope !== undefined ? { scope } : {}), reason });\n\n // Every read is bound to a subject, both tiers. The private tier fuses the subject into the\n // predicate and the shared tier checks it against the entitlement set, but neither has an\n // anonymous form — a token with no subject would name a bearer no revocation could reach.\n if (subject === null) {\n deny(\"no subject\");\n continue;\n }\n\n const expanded = expandToScopes(options, subject, request.shapeKey);\n if (\"refusal\" in expanded) {\n deny(expanded.refusal);\n continue;\n }\n\n for (const scope of expanded.scopes) {\n const scoped = scope !== undefined ? { scope } : {};\n const compiled = compileGrant(options, claims, request.shapeKey, scope);\n if (compiled.outcome === \"deny\") {\n deny(compiled.reason, scope);\n continue;\n }\n\n // Enumeration said yes; ask the predicate too. The two are required to agree, and when they do\n // not it is this side that must catch it: the edge checks `permits` on EVERY read, so a scope\n // only `scopesFor` believes in would mint a capability for a stream the client can never\n // actually read. Better a denial it can see now than a stream that 403s forever.\n if (compiled.tier === \"shared\" && !options.entitlements?.permits(subject, request.shapeKey, scope ?? [])) {\n deny(\"not entitled to this scope\", scope);\n continue;\n }\n\n // The private tier's grant records WHAT was authorized, not merely that something was. Its\n // predicate is a function of this subject's claims, and those change under the client's feet —\n // a role removed mid-session — so the re-mint has to be able to ask whether the shape this\n // grant points at is still the shape these claims compile to. The fingerprint is how it asks\n // without storing anything (ADR-0055 decision 6). The shared tier needs none: its predicate is\n // generated from the scope values, which the entitlement re-check already covers.\n const fp = compiled.tier === \"private\" ? { fp: await fingerprintShapeRequest(compiled.request) } : {};\n\n // The claim is NAMED before it is taken, and the name is ours (fork ADR-0008). That is what\n // makes this create idempotent — a repeat with the same id renews rather than joining twice —\n // and what makes the release retry-safe: `DELETE ?subscription=…` drops this claim and only\n // this one. A uuid per grant, never per shape: two grants that deduplicate onto one shapeId are\n // two joins, and one id could only ever release one of them.\n const claim = crypto.randomUUID();\n\n // Deliberately unguarded: see the note above on why an engine fault is not a denial.\n const handle = await options.engine.createShape({ ...compiled.request, subscription: claim });\n assertClaimRecorded(handle, claim);\n // Checked per create rather than once at boot: the lease window is the engine's to report, and\n // this is the only place it is reported. A misconfigured pairing must surface as a 503 on the\n // very first subscribe, not as sessions quietly lapsing an idle window later.\n //\n // The claim is already taken by the time this can trip, so it is handed back before the error\n // leaves — nobody will ever follow this stream. Best effort, and the failure is SWALLOWED: the\n // configuration fault is what the operator has to see, and a release that also fails must not\n // mask it. An unreleased claim lapses on its own.\n try {\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n } catch (error) {\n await options.engine.releaseShape(handle.shapeId, claim).catch(() => {});\n throw error;\n }\n\n granted.push({ shapeKey: request.shapeKey, ...scoped, shapeId: handle.shapeId, streamPath: handle.streamPath });\n // The grant carries the shapeId this `createShape` returned AND the claim it was taken under,\n // and together they are what make the renew and release routes possible at all: both are\n // stateless, so the signed token is the only record of what this session holds.\n grants.push({\n path: handle.streamPath,\n shapeKey: request.shapeKey,\n shapeId: handle.shapeId,\n claim,\n ...scoped,\n ...fp,\n });\n }\n }\n\n if (subject === null || grants.length === 0) return { granted, denied };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, denied };\n}\n\n/**\n * The subscribe route: verified claims in, a token and stream paths out.\n *\n * Deliberately a POST that returns paths rather than a redirect to them. The client needs the whole\n * batch to open K long-polls and to know when to re-mint, and a redirect would give it one stream\n * and no expiry.\n */\nexport function createSubscribeHandler(\n options: SubscribeOptions & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleSubscribe(request: Request): Promise<Response> {\n let body: { subscriptions?: SubscriptionRequest[] };\n try {\n body = (await request.json()) as { subscriptions?: SubscriptionRequest[] };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (!Array.isArray(body.subscriptions)) {\n return Response.json({ error: \"subscriptions must be an array\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n\n // Unauthenticated is NOT a denial, for the same reason an engine outage is not: a client told\n // \"not entitled\" truncates the scope and unsubscribes, so answering an expired JWT that way\n // turns a re-login into data loss. 401 is what makes it a distinct, recoverable status the\n // client can retry through (ADR-0013).\n //\n // The check is on the SUBJECT, not on the claims object: a verified token with no `sub` names a\n // bearer no revocation could ever reach, so it is exactly as unusable as no token at all. A\n // deployment with no auth adapter never reaches here — `createSyncServer` refuses that pairing\n // at construction.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: SubscribeResult;\n try {\n result = await subscribeToShapes(options, claims, body.subscriptions, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer is an OUTAGE, and 503 is what keeps the client retrying.\n // Relaying it as a per-subscription denial would tell the client it lost entitlement, and a\n // client told that truncates the scope and unsubscribes — turning a transient fault into data\n // loss.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n // A lease window shorter than the token TTL is an operator's misconfiguration, and it joins the\n // 503s for the same reason: it is a statement about this deployment, never about this subject's\n // entitlements. Denying instead would make an unserviceable pairing look like lost access.\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n // 200 even when everything was denied: the per-subscription reasons ARE the response, and\n // collapsing them to a status code would tell a client that lost one scope out of K nothing\n // about which one.\n return Response.json(result);\n };\n}\n\nexport interface RefreshResult {\n token?: string;\n expiresAt?: number;\n /** Grants that survived re-authorization — see {@link refreshStreamToken} for what that is per tier. */\n granted: StreamGrant[];\n /**\n * Grants the subject may no longer read as granted: a shared scope they have lost, or a private\n * shape their current claims no longer compile to. The client truncates each and unsubscribes,\n * then re-subscribes for whatever it is entitled to now.\n */\n revoked: DeniedSubscription[];\n}\n\n/**\n * Re-mint a stream token from an existing one (ADR-0055 decision 6).\n *\n * The expiring token IS the request: its signature proves this control plane issued those grants, so\n * nothing has to be stored server-side to know what the subject held, and the edge stays stateless on\n * both halves. Expiry is deliberately not enforced here — a token is presented for re-mint precisely\n * because it is at or past its TTL — but the signature is, and **every grant is re-authorized**.\n * That re-check is what makes the TTL a revocation bound rather than a formality.\n *\n * BOTH TIERS are re-authorized, by the question each tier's authorization actually turns on.\n *\n * - Shared: the live entitlement set. Its predicate is generated from the scope values, so it cannot\n * drift with the subject; what can change is whether the subject still holds the scope.\n * - Private: **recompile the shape with the subject's CURRENT claims** and compare the fingerprint\n * the grant carries. A private predicate may read ANY verified claim, not only `sub`, so a subject\n * demoted mid-session — a role dropped, a tenant changed — is still the same authenticated subject\n * and would sail through a check that only re-verified the JWT. Re-verifying the JWT proves the\n * bearer is still who they were; it says nothing about whether the shape they hold is still the\n * shape their claims compile to, and only recompiling answers that.\n *\n * A fingerprint mismatch is a REVOCATION by design, including when the recompiled predicate would\n * still permit the subject something. The grant names one stream, that stream serves the old\n * predicate, and this route may not hand out a new one — the client's re-subscribe is where a new\n * shape is created, and this route is not that. So the grant is revoked, the client re-subscribes, the\n * control plane creates the shape its current claims compile to, and because the handle differs the\n * client re-snapshots through ADR-0056 decision 7's must-refetch.\n *\n * **This is also where every surviving grant's engine claim is RENEWED** (fork ADR-0008). A claim is a\n * lease: the engine releases one not renewed within `leaseSeconds`, because native reads terminate on\n * durable-streams and the renewal is the only liveness signal it has. Renewing here rather than on a\n * timer is what makes the cadence honest — this route already runs once per subject per TTL window and\n * already decides which grants are still authorized, so the renewal covers exactly the grants that\n * survived and costs no extra round trip. A revoked grant is deliberately NOT renewed: its lease\n * lapses and the engine reclaims the shape.\n *\n * The renewal is the same create, repeated with the grant's own `claim` id. Its outcomes are in\n * {@link renewGrantClaim}; a renewal that comes back a different handle, or 409s, revokes the grant\n * with a re-subscribe reason rather than failing the whole re-mint.\n *\n * `registry` is therefore REQUIRED rather than optional: a refresh route that cannot recompile cannot\n * re-authorize the private tier — and now cannot renew either, since the renewal IS the compiled\n * create. `engine` is required for the same reason.\n *\n * Throws {@link EntitlementsUnavailableError} rather than revoking when the set cannot be consulted —\n * the same outage-is-not-a-denial rule {@link subscribeToShapes} follows, and it matters more here:\n * `revoked` is the wire's clear-this-scope instruction, and this route runs every few minutes for\n * the life of every subscription. An engine that cannot answer a renewal joins it, as does a lease\n * window this deployment's TTL does not fit inside ({@link CircuitsLeaseConfigError}).\n */\nexport async function refreshStreamToken(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\">,\n claims: JwtClaims | null,\n expiringToken: string,\n now: number,\n): Promise<RefreshResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const verified = await verifyStreamToken(options.key, expiringToken, now, { allowExpired: true });\n if (!verified.ok || subject === null) return { granted: [], revoked: [] };\n\n // The token names its subject; a token presented by anyone else is not a re-mint, it is a theft.\n if (verified.claims.sub !== subject) return { granted: [], revoked: [] };\n\n const granted: StreamGrant[] = [];\n const revoked: DeniedSubscription[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const grant of verified.claims.grants) {\n const scoped = grant.scope !== undefined ? { scope: grant.scope } : {};\n if (grant.scope === undefined) {\n // Private tier: re-authorize by recompiling. See the note above on why the signed grant alone\n // is not the entitlement — the predicate is a function of claims that may have changed since\n // it was issued.\n const compiled = compileGrant(options, claims, grant.shapeKey);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, reason: compiled.reason });\n continue;\n }\n if (grant.fp === undefined) {\n // Nothing to compare against, so nothing that could establish this grant is still the right\n // one. Fail closed rather than trust it: the recovery is a re-subscribe, which costs the\n // client a re-snapshot and costs the subject nothing they are still entitled to.\n revoked.push({\n shapeKey: grant.shapeKey,\n reason: \"private grant carries no fingerprint and cannot be re-authorized\",\n });\n continue;\n }\n if ((await fingerprintShapeRequest(compiled.request)) !== grant.fp) {\n revoked.push({ shapeKey: grant.shapeKey, reason: \"shape predicate changed for this subject\" });\n continue;\n }\n // Re-authorized, so renew the claim it holds — the recompiled request is exactly the one that\n // took it, which the fingerprint just proved.\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n continue;\n }\n if (options.entitlements === undefined) {\n // Permanent, and therefore a real revocation: this deployment has no entitlement set, so a\n // shared grant can never be re-minted and the scope is not coming back.\n //\n // Worded as the EDGE words the same condition, and deliberately not as \"entitlements\n // unavailable\" — that string is now the 503 outage body, which means the exact opposite here:\n // an outage says nothing about this subject's scopes and must never clear a row.\n revoked.push({\n shapeKey: grant.shapeKey,\n ...scoped,\n reason: \"shared-tier grant, but this deployment configured no entitlement set\",\n });\n continue;\n }\n // Transient, and therefore NOT a revocation. `revoked` is an instruction to clear the scope, and\n // a re-mint is the most routine request on this route — an entitlement subscription that is a few\n // seconds behind would otherwise empty a subject's store every time it reconnected.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n if (!options.entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: \"not entitled to this scope\" });\n continue;\n }\n // Still entitled, so renew. The shared tier carries no fingerprint — its predicate is generated\n // from the scope values, which is why the entitlement check above is the whole question — so the\n // request is recompiled here, through the same {@link compileGrant} subscribe used.\n const compiled = compileGrant(options, claims, grant.shapeKey, grant.scope);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: compiled.reason });\n continue;\n }\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n }\n\n if (granted.length === 0) return { granted, revoked };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants: granted, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, revoked };\n}\n\n/**\n * The re-mint route. Takes the expiring token, answers with a fresh one and the list of grants that\n * did not survive re-authorization — the shared tier's against the live entitlement set, the private\n * tier's against a recompile with the subject's current claims — and **renews the engine claim of\n * every grant that did survive** (fork ADR-0008).\n *\n * `registry` for that recompile and `engine` for that renewal, both required for the reasons\n * {@link refreshStreamToken} gives.\n *\n * 200 even when everything was revoked, for the same reason subscribe answers 200 on a full denial:\n * the per-grant reasons ARE the response, and a client that lost one scope of K needs to know which.\n */\nexport function createRefreshHandler(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\"> & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRefresh(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // Same as subscribe: an unauthenticated re-mint is a credential problem, not a revocation. The\n // difference matters more here — a `revoked` answer makes the client truncate, and a token\n // expiring is the single most ordinary thing that happens on this route.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: RefreshResult;\n try {\n result = await refreshStreamToken(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // 503, never a `revoked` list: an entitlement set that cannot answer has said nothing about\n // this subject's scopes, and a client that read it as a revocation would clear rows it still\n // holds. The client retries with the token it already has, which the edge keeps honouring\n // until its TTL lapses.\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n // An engine that could not answer a RENEWAL is the same case: the claim is still held (a lease\n // outlives a failed renewal by the rest of its window), the token the client holds still works,\n // and a `revoked` answer would clear rows over a transient fault.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n throw error;\n }\n return Response.json(result);\n };\n}\n\n/**\n * Give back the engine claims a token's grants acquired — the close half of subscribe.\n *\n * **Why this route exists.** A native `POST /shapes` with a definition the engine already holds does\n * not create a second shape: it JOINS the existing one, under a claim of its own. Live claims are\n * load-bearing rather than bookkeeping — one live claim blocks both dormancy and eviction, precisely\n * because native durable-streams reads bypass the engine entirely, so a claim is the only thing that\n * tells it a reader it cannot see still exists. Without a release, a shape waits out its whole lease\n * window before it can go dormant, every time.\n *\n * **The token IS the request**, exactly as on the re-mint path: its signature proves this control\n * plane minted these grants, so nothing has to be stored server-side to know what was acquired.\n * Verified with `allowExpired`, and that is not a weakening — a session releases at CLOSE, which is\n * routinely past a 5-minute TTL, and expiry bounds how long a grant keeps *working*, not what it\n * proves was issued. A release grants its bearer nothing; the only thing it can do is give away\n * claims that this token's own subject holds.\n *\n * **ONE release per GRANT, deliberately not deduplicated by `shapeId`.** Two grants naming one shape\n * are two joins — the engine deduplicated identical definitions and counted both (ADR-0055 decision\n * 6) — so collapsing them here would return one of two claims and leak the other permanently. Each\n * grant releases its OWN claim (`DELETE /shapes/{id}?subscription=<claim>`), which is what makes one\n * release distinguishable from the other at all.\n *\n * **Idempotent and retry-safe** (fork ADR-0008). A claim is named, so releasing it twice is releasing\n * it once: the second `DELETE` is a no-op `200` and cannot touch another subscriber's claim. That is\n * a change in kind from the anonymous refcount decrement this route was first written against, and it\n * collapses the old asymmetry — a client, a proxy or an operator may repeat a release freely. A\n * release that never arrives at all is not a permanent leak either: the claim is a LEASE, renewed on\n * the token re-mint, so a session that crashed or was unloaded has its claims reclaimed by the engine\n * within `leaseSeconds`. What this route buys is promptness, not correctness.\n *\n * Refusals are refusals, not no-ops: a bad signature or a mismatched subject answers an error rather\n * than `{ released: 0 }`, because a token presented by anyone but its own subject is not a release,\n * it is an attempt to drop the victim's claims.\n */\nexport async function releaseStreamGrants(\n options: { engine: CircuitsEngineClient; key: CryptoKey },\n claims: JwtClaims | null,\n token: string,\n now: number,\n): Promise<{ released: number } | { refused: string }> {\n const subject = typeof claims?.sub === \"string\" && claims.sub !== \"\" ? claims.sub : null;\n if (subject === null) return { refused: \"unauthenticated\" };\n\n const verified = await verifyStreamToken(options.key, token, now, { allowExpired: true });\n if (!verified.ok) return { refused: verified.reason };\n if (verified.claims.sub !== subject) return { refused: \"token subject does not match the caller\" };\n\n for (const grant of verified.claims.grants) {\n await options.engine.releaseShape(grant.shapeId, grant.claim);\n }\n return { released: verified.claims.grants.length };\n}\n\n/**\n * The release route: the token a session was given, back at its close.\n *\n * **Safe to call more than once.** Every grant releases a NAMED claim, so a repeat is the same act\n * once (fork ADR-0008) — a duplicate close, a proxy retry or an operator replaying a request all\n * answer 200 and change nothing. The client still sends it at most once, but that is now a matter of\n * not making a pointless request rather than of correctness.\n *\n * 403 rather than 200 on a refusal — see {@link releaseStreamGrants} for why a refused release must\n * be visible. 401 when the caller has no subject, the same rule subscribe and re-mint follow: an\n * unauthenticated call is a credential problem, and it is the one thing here a client could fix.\n */\nexport function createReleaseHandler(\n options: {\n engine: CircuitsEngineClient;\n key: CryptoKey;\n } & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRelease(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: { released: number } | { refused: string };\n try {\n result = await releaseStreamGrants(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer has not dropped the claims. 503 says \"this deployment, not\n // you\", and a client is free to come back: releases are named and therefore idempotent (fork\n // ADR-0008), so a retry that races a release which actually landed is a no-op rather than a\n // theft. Whether it retries or not, the residue is bounded by the lease — an unreleased claim\n // lapses within `leaseSeconds` of its last renewal.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n if (\"refused\" in result) return Response.json({ error: result.refused }, { status: 403 });\n return Response.json(result);\n };\n}\n\n/** The control-plane paths the native read path mounts. */\nexport const subscribePath = \"/sync/v1/subscribe\";\nexport const refreshPath = \"/sync/v1/refresh\";\nexport const releasePath = \"/sync/v1/release\";\n\n/**\n * The convergence-barrier route (ADR-0056 decision 4).\n *\n * Proxied rather than exposed: the engine's control plane is unauthenticated by design and is not\n * client-reachable, so surfacing the barrier on our own authenticated endpoint costs nothing and\n * keeps the trust boundary intact.\n *\n * `maxAgeSeconds` may cache the answer briefly, but only a HEALTHY one. For the `pendingFlips` term\n * staleness is safe in exactly one direction — it moves the barrier backwards, so a stale reading can\n * only DELAY an alignment, never satisfy one falsely. `flipFailures` inverts that: a cached\n * pre-degradation zero would let a group align against an engine that has already\n * lost membership effects, which is precisely the alignment the term exists to refuse. So a degraded\n * reading is never cached and never served from cache, and the cache window is exactly the bound on\n * how long a client may align against a freshly-degraded engine — which is why the default is 0.\n */\nexport function createBarrierHandler(options: {\n engine: CircuitsEngineClient;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n maxAgeSeconds?: number;\n}) {\n let cached: { at: number; body: BarrierBody } | null = null;\n const maxAge = options.maxAgeSeconds ?? 0;\n\n return async function handleBarrier(request: Request): Promise<Response> {\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // The barrier says nothing about any subject's data — only whether the engine has finished\n // propagating — but it is still engine internals, so it needs a caller we recognise.\n if (options.resolveAuthClaims && claims === null) {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n const now = Date.now() / 1000;\n if (cached && now - cached.at < maxAge) return Response.json(cached.body);\n\n const state = await options.engine.replicationState();\n const body = { pendingFlips: state.pendingFlips, flipFailures: state.flipFailures };\n cached = body.flipFailures > 0 ? null : { at: now, body };\n return Response.json(body);\n };\n}\n\nexport const barrierPath = \"/sync/v1/barrier\";\n\n/** The barrier as the client reads it — the engine's LSN is operator detail and stays server-side. */\ninterface BarrierBody {\n pendingFlips: number;\n /** Abandoned flip batches. Non-zero is terminal for a group reading it, and is never cached. */\n flipFailures: number;\n}\n",
7
- "import { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport {\n conjoinPredicates,\n DENY_ALL_PREDICATE,\n isAndPredicate,\n isIsNullPredicate,\n isLeafPredicate,\n readShapeTier,\n type JwtClaims,\n type Predicate,\n type PredicateValue,\n type ShapeSpec,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { CreateShapeRequest } from \"./wire\";\n\n/** What a client asks the control plane for: a declared shape, plus the inputs its tier consumes. */\nexport interface ShapeRequest {\n /** The shape's unique identity, exactly as declared. Never a table name the client chose. */\n shapeKey: string;\n /** Verified claims. The private tier's only subject input; the shared tier never sees them. */\n claims: JwtClaims | null;\n /**\n * SHARED TIER — the scope values, positionally matching the shape's declared `scope` columns.\n * `null` is a legal value and compiles to `IS NULL`, so an absent element and a null one are\n * different things: arity is checked strictly rather than padded.\n */\n scope?: readonly PredicateValue[];\n /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */\n params?: Record<string, unknown>;\n}\n\n/**\n * The outcome of compiling a request. A denial is a first-class result rather than an exception\n * because it is an ordinary, expected outcome — an anonymous caller, a subject with no membership —\n * and because the caller's response to it (no handle, no shape, 403) is the same for every reason.\n */\nexport type CompiledShapeRequest =\n | { outcome: \"create\"; tier: \"shared\" | \"private\"; request: CreateShapeRequest }\n | { outcome: \"deny\"; reason: string };\n\n/**\n * Resolve the entry a request selects by its **`shapeKey`** — not by table name, since several\n * shapes (a read projection and its owner) legitimately read one physical table under distinct keys.\n * Schema qualification is significant. Returns undefined when nothing declares that key, and the\n * caller fails closed.\n */\nexport function resolveEntryByShapeKey(registry: SyncTableRegistry, shapeKey: string): SyncTableEntry | undefined {\n return Object.values(registry).find((entry) => entry?.shape?.shapeKey === shapeKey);\n}\n\n/**\n * The physical table the engine reads.\n *\n * Circuits introspects `information_schema` with `table_schema = 'public'` and keys its tables by\n * bare name, so a schema-qualified registry target has no engine-side spelling. Rather than send a\n * name that would 404 deep inside shape creation, refuse here with the reason — a real limitation of\n * the engine, tracked against the fork, not something the control plane can paper over.\n */\nfunction resolveShapeTarget(shape: ShapeSpec): { table: string } | { refusal: string } {\n const target = shape.physicalTable ?? shape.tableName;\n if (!target.includes(\".\")) return { table: target };\n const [schema] = target.split(\".\");\n if (schema === \"public\") return { table: target.slice(\"public.\".length) };\n return {\n refusal:\n `shape \"${shape.shapeKey}\" reads \"${target}\", but the engine introspects the public schema ` +\n `only and names tables bare — a non-public target has no shape it can be created under.`,\n };\n}\n\n/**\n * The columns the ENGINE emits onto the stream, or undefined for the whole row.\n *\n * Not the same set as the columns the CLIENT receives, and the difference is load-bearing. Read off\n * `shape.rowFilter.columns` when the registry declares one — which for a read projection is the\n * client keep-set PLUS its `serverOnlyColumns` — otherwise off `localTable`, so a shape with no\n * allow-list emits exactly what the local schema declares.\n *\n * `serverOnlyColumns` therefore ARE emitted by the engine, deliberately: an egress\n * `serverProjection.rowTransform` has to READ them, and the engine is the only thing that can fetch\n * them. They come off the wire at the stream edge, which strips every rewritten row back to the local\n * table's columns AFTER the transform has run (`createStreamGate`, ADR-0055 decision 5). So the\n * ordering hazard between rewriting and omission is ANSWERED — transform first, strip second, in one\n * place — rather than dissolved: this function must not \"helpfully\" narrow the allow-list to the\n * client keep-set, because that would starve the transform of its inputs and fail it open.\n */\nfunction emittedColumns(entry: SyncTableEntry): string[] | undefined {\n const explicit = entry.shape?.rowFilter?.columns;\n if (explicit != null && explicit.length > 0) return [...explicit];\n if (entry.clientProjection?.omitColumns == null) return undefined;\n return getTableConfig(entry.localTable).columns.map((column) => column.name);\n}\n\n/**\n * Compile a shape request into the engine's `POST /shapes` body, or a denial.\n *\n * The whole predicate is built here, in the control plane, from the registry — nothing predicate\n * shaped arrives on the wire. That is strictly stronger than the proxy's \"discard the client's\n * `where`\": there is no `where` on the wire to discard, so no parameter parsing to get right and no\n * grammar for a client to probe.\n */\nexport function compileShapeRequest(registry: SyncTableRegistry, request: ShapeRequest): CompiledShapeRequest {\n const entry = resolveEntryByShapeKey(registry, request.shapeKey);\n const shape = entry?.shape;\n if (entry == null || shape == null) {\n return { outcome: \"deny\", reason: `no shape declares shapeKey \"${request.shapeKey}\"` };\n }\n\n const target = resolveShapeTarget(shape);\n if (\"refusal\" in target) return { outcome: \"deny\", reason: target.refusal };\n\n const tier = readShapeTier(shape);\n const subject =\n tier === \"shared\" ? scopePredicate(shape, request.scope) : privatePredicate(shape, request.claims, request.params);\n if (\"refusal\" in subject) return { outcome: \"deny\", reason: subject.refusal };\n\n const where = conjoinPredicates(subject.predicate, shape.where);\n\n const narrowing = assertLocalPrimaryKeyIsPinned(entry, where);\n if (narrowing != null) return { outcome: \"deny\", reason: narrowing };\n\n const columns = emittedColumns(entry);\n\n return {\n outcome: \"create\",\n tier,\n request: {\n table: target.table,\n ...(where !== undefined ? { where } : {}),\n ...(columns !== undefined ? { columns } : {}),\n },\n };\n}\n\n/**\n * The shared tier's predicate: an `AND` of equalities over the declared scope columns, generated —\n * never authored. Every property the tier depends on comes from that generation. Two shapes of a\n * family cannot overlap, because a row carries one value per scope column. Two subscribers holding\n * the same scope values produce byte-identical requests, which is what lets Circuits collapse them\n * onto one stream and what makes the resulting stream cacheable at all.\n */\nfunction scopePredicate(\n shape: ShapeSpec,\n values: readonly PredicateValue[] | undefined,\n): { predicate: Predicate | undefined } | { refusal: string } {\n const columns = shape.scope ?? [];\n if (values == null) {\n return { refusal: `shape \"${shape.shapeKey}\" is shared-tier and requires ${columns.length} scope value(s)` };\n }\n if (values.length !== columns.length) {\n return {\n refusal:\n `shape \"${shape.shapeKey}\" takes ${columns.length} scope value(s) ` +\n `(${columns.join(\", \")}) but got ${values.length}`,\n };\n }\n\n const equalities = columns.map((col, index): Predicate => {\n const value = values[index]!;\n // NULL is a scope value like any other, and `col = NULL` is UNKNOWN for every row — so the one\n // that would silently match nothing is the one that has to become `IS NULL`.\n return value === null ? { col, isNull: true } : { col, op: \"eq\", value };\n });\n\n return { predicate: conjoinPredicates(...equalities) };\n}\n\n/**\n * Every column pinned to exactly one value by a predicate's **top-level conjunction**.\n *\n * Conservative on purpose: only `col = value` and `col IS NULL` conjuncts pin, and only where they\n * sit in the outermost `AND` chain. A branch under `OR` or `NOT` admits more than one value for its\n * column by construction, and an `IN (subquery)` admits as many as the subquery returns — none of\n * those pin, so none are collected.\n */\nfunction pinnedColumns(node: Predicate | undefined, into: Set<string> = new Set()): Set<string> {\n if (node == null) return into;\n if (isAndPredicate(node)) {\n for (const child of node.and) pinnedColumns(child, into);\n return into;\n }\n if (isIsNullPredicate(node)) {\n into.add(node.col);\n return into;\n }\n if (isLeafPredicate(node) && node.op === \"eq\") {\n into.add(node.col);\n }\n return into;\n}\n\n/**\n * Refuse a `clientProjection.localPrimaryKey` that narrows the server key without the predicate\n * pinning what it drops.\n *\n * The second of the two checks replacing ADR-0014's primary-key collision tripwire, and the one case\n * where a collision was never machinery at all. Narrowing is the point of `localPrimaryKey` — server\n * key `(owner_id, card_id)` becomes local key `(card_id)` because the caller only ever syncs their\n * own rows — and it is sound *exactly when* the shape's predicate admits one value for every dropped\n * column. Pinned, two server rows can never collapse onto one local key. Unpinned, they can, and the\n * client would silently keep whichever arrived last: under a plain INSERT that surfaced as a PK\n * collision, and under `upsert` it does not surface at all.\n *\n * Checked here rather than at `defineSyncTable` because the predicate is claims-dependent: what pins\n * `owner_id` is the subject fused into it, which does not exist until a real caller subscribes. The\n * refusal is therefore per-subscription, and lands at the same place and in the same form as every\n * other compile denial.\n */\nfunction assertLocalPrimaryKeyIsPinned(entry: SyncTableEntry, where: Predicate | undefined): string | null {\n const localKey = entry.clientProjection?.localPrimaryKey?.columns;\n if (localKey == null || localKey.length === 0) return null;\n\n const localKeySet = new Set<string>(localKey);\n const dropped = entry.primaryKey.columns.filter((column) => !localKeySet.has(column));\n if (dropped.length === 0) return null;\n\n const pinned = pinnedColumns(where);\n const unpinned = dropped.filter((column) => !pinned.has(column));\n if (unpinned.length === 0) return null;\n\n return (\n `shape \"${entry.shape!.shapeKey}\" declares clientProjection.localPrimaryKey ` +\n `(${localKey.join(\", \")}), dropping ${unpinned.join(\", \")} from the server primary key ` +\n `(${entry.primaryKey.columns.join(\", \")}) — but this caller's predicate does not pin ` +\n `${unpinned.length === 1 ? \"that column\" : \"those columns\"} to a single value, so two server rows ` +\n `could collapse onto one local key. Pin it with a top-level equality in the shape's rowFilter (or ` +\n `its scope), or widen localPrimaryKey to include it.`\n );\n}\n\n/** The private tier's predicate: the registry's own claims-fused filter, or a denial. */\nfunction privatePredicate(\n shape: ShapeSpec,\n claims: JwtClaims | null,\n params: Record<string, unknown> | undefined,\n): { predicate: Predicate | undefined } | { refusal: string } {\n const filter = shape.rowFilter?.customPredicate;\n if (filter == null) return { predicate: undefined };\n\n const resolved = filter(claims ?? {}, params);\n // Reference identity: a denied subject gets no shape at\n // all rather than an empty one, so nothing is created and nothing has to be torn down later.\n if (resolved === DENY_ALL_PREDICATE) {\n return { refusal: `shape \"${shape.shapeKey}\" denies this caller` };\n }\n return { predicate: resolved ?? undefined };\n}\n\n/**\n * Canonical JSON: object keys sorted, `undefined` members dropped, array order preserved.\n *\n * Emitted as a string directly rather than by rebuilding an object and handing it to\n * `JSON.stringify`, because a rebuilt object's key order is not entirely ours to choose — a JS engine\n * enumerates integer-like keys numerically ahead of insertion order, so a sorted rebuild is only\n * *usually* serialized in the order it was sorted into. Writing the bytes here removes the\n * \"usually\".\n *\n * Array order IS significant and is kept: `columns` is a projection whose order the engine sees, and\n * an `and`/`or` chain's operand order is part of the predicate as sent.\n */\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value ?? null);\n if (Array.isArray(value)) return `[${value.map((member) => canonicalJson(member ?? null)).join(\",\")}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, member]) => member !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : 1));\n return `{${entries.map(([key, member]) => `${JSON.stringify(key)}:${canonicalJson(member)}`).join(\",\")}}`;\n}\n\n/**\n * A content fingerprint of a compiled shape request — SHA-256 over its canonical JSON, lowercase hex.\n *\n * CANONICAL because the input is not a literal an author wrote: a predicate reaches here through\n * `rowFilter.customPredicate`, whose closure may assemble `{ col, op, value }` in whatever order its\n * branches happen to take, and `p.and(a, b)` on one path may nest where another flattens. Two\n * compiles that MEAN the same thing must fingerprint the same, or the equality below degrades into a\n * test of how the author's code was written on the day.\n *\n * This is an AUTHORIZATION equality check, not a cache key. Two requests fingerprinting the same are\n * the same shape to the engine — same table, same predicate, same projection — so a subject whose\n * recompiled shape still fingerprints as the one their grant names is still authorized for exactly\n * the stream that grant points at. A collision is therefore not a performance regression, it is an\n * authorization one, which is why this is a cryptographic digest and not a cheap hash.\n *\n * Used by the re-mint path (ADR-0055 decision 6) to re-authorize a private-tier grant against the\n * subject's current claims. Never sent to the engine, which knows nothing about it.\n */\nexport async function fingerprintShapeRequest(request: CreateShapeRequest): Promise<string> {\n const canonical = canonicalJson({\n table: request.table,\n where: request.where,\n columns: request.columns,\n changesOnly: request.changesOnly,\n });\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(canonical));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n",
8
- "import { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport type { PredicateValue, RowTransform, RowTransformContext, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { resolveEntryByShapeKey } from \"./compile\";\nimport { findGrant, verifyStreamToken, type StreamGrant } from \"./stream-token\";\n\n/**\n * The live entitlement set the edge checks a shared-tier read against (ADR-0055 decision 7).\n *\n * An interface, not an implementation, because the source is a Circuits subscription over the\n * membership relations themselves — freshness is engine propagation, not a cache TTL, and there is\n * no database on the read path.\n */\nexport interface EntitlementSet {\n /**\n * Whether the entitlement set can be trusted right now. False while the subscription is catching\n * up, degraded, or stale.\n *\n * The edge denies when this is false. An unavailable entitlement set is never a permit — the\n * failure mode of the alternative is a disclosure, and the failure mode of this one is a subject\n * retrying a read.\n */\n readonly ready: boolean;\n /** Whether `subject` may read `shapeKey` at `scope`. */\n permits(subject: string, shapeKey: string, scope: readonly PredicateValue[]): boolean;\n /**\n * Every scope of `shapeKey` that `subject` holds, each an ordered tuple matching the shape's\n * declared scope columns.\n *\n * This is what lets a client subscribe by shape alone (ADR-0055 decision 6): it names\n * `offering_content`, and the control plane answers with one stream per offering the subject can\n * actually read. The alternative — the client naming scopes — makes it restate something only this\n * set knows, so its every answer is either redundant or wrong.\n *\n * Enumeration and `permits` must agree: a scope returned here that `permits` would refuse is a\n * grant the edge then rejects on every read.\n */\n scopesFor(subject: string, shapeKey: string): readonly (readonly PredicateValue[])[];\n}\n\n/**\n * The entitlement set cannot be consulted right now — it is catching up, degraded, or stale.\n *\n * An OUTAGE, and thrown rather than reported per subscription for exactly the reason an engine fault\n * is: a client told \"not entitled\" clears that scope and unsubscribes (ADR-0055 decision 6), so\n * relaying an unavailable set as a denial would turn a transient control-plane condition into\n * client-side data loss. The routes map it to 503, which is a status a client retries through.\n *\n * The EDGE does not throw this. A read arriving while the set is unavailable is denied (see\n * {@link EntitlementSet.ready}) and a denied read is not a revocation — it is a request the client\n * makes again.\n */\nexport class EntitlementsUnavailableError extends Error {\n constructor() {\n super(\n \"[pgxsinkit] the entitlement set is unavailable — it is catching up, degraded or stale; \" +\n \"shared-tier subscriptions cannot be decided right now\",\n );\n this.name = \"EntitlementsUnavailableError\";\n }\n}\n\nexport interface StreamGateOptions {\n /** Verifies the stream token. Minted by the control plane in the same process. */\n key: CryptoKey;\n /**\n * The registry the granted shapes are declared in — REQUIRED, unlike every other option here.\n *\n * The gate needs it to answer one question per read: does this shape declare a\n * `serverProjection.rowTransform`, and must its bytes therefore be rewritten before they reach the\n * client (ADR-0055 decision 5)? A gate that cannot see the registry cannot know, so it would proxy\n * a transform shape's raw rows — including the `serverOnlyColumns` fetched solely for the transform\n * — with nothing anywhere reporting a discrepancy. Making it required is what makes that mount\n * impossible to write, which is why it is not optional \"for deployments with no transform shape\":\n * the leak arrives on the day someone adds the first one, in a file nobody was editing.\n */\n registry: SyncTableRegistry;\n /**\n * The live entitlement set backing the shared tier. Optional for the same reason it is optional on\n * the control plane: a deployment whose registry declares no shared shape has nothing to ask it.\n * Absent, a shared-tier grant is DENIED rather than waved through — the two sides then agree that\n * an unconfigured entitlement set can never permit.\n */\n entitlements?: EntitlementSet;\n /**\n * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the\n * same value the engine is given as `CIRCUITS_DS_URL`, since both address the same paths.\n */\n durableStreamsUrl: string;\n /**\n * Deployment-supplied runtime params, handed to an egress `rowTransform` as its context's `params`\n * — the same values `SubscribeOptions.params` hands to `rowFilter.customPredicate`. A deployment\n * that configures them on one side and not the other gives its registry two different runtime\n * environments for one shape, so mount both from the same source.\n */\n params?: Record<string, unknown>;\n /** Injected for tests; defaults to the ambient `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * What DECIDING one read needs: the signing key, plus the entitlement set the shared tier is checked\n * against.\n *\n * Spelled as the gate's options with everything else relaxed to optional, rather than as\n * {@link StreamGateOptions} itself, because a caller that wants only the decision — a mount that\n * proxies for itself, a test pinning the authorization rules — has no gate to configure, and\n * requiring it to invent a `registry` and a `durableStreamsUrl` would demand values the answer\n * provably does not depend on.\n */\nexport type StreamAuthorizationOptions = Pick<StreamGateOptions, \"key\" | \"entitlements\"> &\n Partial<Omit<StreamGateOptions, \"key\" | \"entitlements\">>;\n\nexport type GateDecision =\n | {\n allow: true;\n grant: StreamGrant;\n /**\n * The token's subject. Carried on the decision because the egress transform stage needs it and\n * re-verifying the token to recover it would pay for a second HMAC on every rewritten read —\n * the verification that established it already happened here.\n */\n subject: string;\n }\n | { allow: false; reason: string };\n\n/**\n * Authorize one read of one stream path.\n *\n * Two checks, and they are not redundant. The token is a capability bounded by its TTL, which is the\n * only bound available when a hit-serving CDN sits in front and the request never reaches us. The\n * entitlement lookup is live, and bounds revocation by propagation latency instead whenever the\n * request does reach us. Which one binds is a property of the deployment, not of this code.\n *\n * A private-tier grant has no scope to check, so the token is the whole authorization and its TTL is\n * the whole revocation bound. That is the same bound a CDN-fronted shared read has, and it is worth\n * stating rather than leaving to be inferred.\n */\nexport async function authorizeStreamRead(\n options: StreamAuthorizationOptions,\n token: string | null,\n path: string,\n now: number,\n): Promise<GateDecision> {\n if (token == null || token === \"\") return { allow: false, reason: \"no stream token\" };\n\n const verified = await verifyStreamToken(options.key, token, now);\n if (!verified.ok) return { allow: false, reason: verified.reason };\n\n const grant = findGrant(verified.claims, path);\n if (grant == null) return { allow: false, reason: \"token grants no such stream\" };\n\n const subject = verified.claims.sub;\n if (grant.scope === undefined) return { allow: true, grant, subject };\n\n const entitlements = options.entitlements;\n if (entitlements === undefined) {\n return { allow: false, reason: \"shared-tier grant, but this deployment configured no entitlement set\" };\n }\n if (!entitlements.ready) return { allow: false, reason: \"entitlements unavailable\" };\n if (!entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n return { allow: false, reason: \"not entitled to this scope\" };\n }\n return { allow: true, grant, subject };\n}\n\n/**\n * Read the stream token off a request.\n *\n * `Authorization`, never a query parameter, and this is a correctness condition rather than a\n * convention: the cache key is the URL, so a token in the URL gives every subscriber a distinct key\n * and destroys precisely the sharing the shared tier exists for. A cache must also be configured not\n * to vary on this header — which it can only do if the header is where the token is.\n */\nexport function readStreamToken(request: Request): string | null {\n const header = request.headers.get(\"authorization\");\n if (header == null) return null;\n const [scheme, value] = header.split(\" \");\n return scheme?.toLowerCase() === \"bearer\" && value ? value : null;\n}\n\n/**\n * The response headers a browser must be allowed to READ off a stream-edge response.\n *\n * CORS lets script see only a short safelist of response headers (`cache-control`, `content-language`,\n * `content-length`, `content-type`, `expires`, `last-modified`, `pragma`). Every header the\n * durable-streams protocol answers with is outside it, so a CROSS-ORIGIN reader sees NONE of them\n * unless the mount names them on `Access-Control-Expose-Headers`.\n *\n * Two generations of client read these. `@pgxsinkit/client`'s own reader (`READ_RESPONSE_HEADERS` in\n * its `circuits/long-poll.ts`, which a unit test holds to this list) steers by `Stream-Next-Offset`,\n * `Stream-Up-To-Date` (a presence check, which is why it is easy to miss), `Stream-Cursor` and\n * `Stream-Closed`. Stripped of them it cannot make progress and fails the read, loudly. Clients still\n * in the field on `@durable-streams/client` (0.2.x, which pgxsinkit read through until ADR-0065\n * decision 6) drive their whole read loop off the same four and also read `stream-sse-data-encoding`\n * (SSE payload decoding) and `etag` (the stream-metadata path). Stripped of them, that client never\n * learns an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which\n * presents as a hot loop of hundreds of requests per second per shape with no error raised anywhere.\n * Both floor their retry backoff on `Retry-After`; without it they fall back on their own schedule.\n *\n * `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are read by neither. They are named here\n * anyway because this list is a statement about the ds protocol's response namespace rather than about\n * which subset one client version happens to read today — exposing a header a response never carries\n * is inert, while omitting one that it does carry wedges the reader. The `Producer-*` headers are\n * deliberately absent: they belong to the write path, which does not come through this gate.\n *\n * EVERY mount of `createStreamGate` must put these on `Access-Control-Expose-Headers` of the ACTUAL\n * (non-preflight) response. The gate cannot do it itself — it forwards the upstream response's\n * headers (verbatim for an ordinary shape, minus the caching ones for a rewritten one), and an\n * exposure list is meaningless without the `Access-Control-Allow-Origin` decision that only the mount\n * owns.\n */\nexport const STREAM_READ_EXPOSED_HEADERS: readonly string[] = [\n \"stream-next-offset\",\n \"stream-up-to-date\",\n \"stream-cursor\",\n \"stream-closed\",\n \"stream-seq\",\n \"stream-ttl\",\n \"stream-expires-at\",\n \"stream-sse-data-encoding\",\n \"etag\",\n \"retry-after\",\n];\n\n/**\n * A durable-streams long-poll body as the transform stage handles it.\n *\n * Deliberately NOT `StreamEnvelope`: the gate is a proxy, and typing the body as the contract would\n * assert that the edge validates a wire form it only ever forwards. All it needs to know is that an\n * envelope may carry a `value` object — a delete envelope is key-only, so it has nothing to rewrite\n * and nothing to disclose.\n */\ninterface ProxiedEnvelope {\n value?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * The response headers a rewritten body may be answered with.\n *\n * `cache-control: private, no-store` is the governing invariant, not a precaution: a transform makes\n * the bytes a function of the SUBJECT, so nothing between this edge and the browser that requested\n * them may share or store them. `etag` goes for the same reason — an upstream validator describes the\n * bytes durable-streams holds, not the ones we just produced, and honouring it would let a\n * revalidation return another subject's rewrite. `content-length` and `content-encoding` describe a\n * body that no longer exists: the length changed under the rewrite, and `fetch` already decoded what\n * it handed us.\n *\n * Everything else is kept VERBATIM — every `stream-*` header and the content type. The client's whole\n * read loop drives off them (see {@link STREAM_READ_EXPOSED_HEADERS}); an edge that dropped\n * `stream-next-offset` while rewriting would present as a failed read (to a client still on\n * `@durable-streams/client`, a hot loop), not as a redaction bug.\n */\nfunction rewrittenEgressHeaders(upstream: Headers): Headers {\n const headers = new Headers(upstream);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.delete(\"etag\");\n headers.set(\"cache-control\", \"private, no-store\");\n return headers;\n}\n\n/** Whether this read asks for SSE framing, by either of the two ways the ds protocol expresses it. */\nfunction asksForSse(request: Request): boolean {\n return (\n new URL(request.url).searchParams.get(\"live\") === \"sse\" ||\n (request.headers.get(\"accept\") ?? \"\").includes(\"text/event-stream\")\n );\n}\n\n/**\n * The edge: gate, then proxy bytes — rewriting them only for the shapes that declare a rewrite.\n *\n * There is no per-read FILTERING here at all, and no per-read rewriting for shapes that declare none.\n * Predicates were resolved at shape creation, so what remains for almost every read is a decision and\n * a copy — which is why this can sit in the TypeScript control-plane process without CPU being the\n * axis that decides where it belongs.\n *\n * A shape that declares `serverProjection.rowTransform` is the one exception: it is rewritten HERE,\n * per request, with the subject taken from the stream token, and answered `private, no-store`. This\n * is the rewriting origin ADR-0055 decision 5 names, confined to the shapes that incur it — a\n * transform shape gives up CDN shareability and SSE framing, and every other shape gives up nothing.\n * The transform's `serverOnlyColumns` are fetched by the engine so the transform can read them and\n * are stripped here, after it runs, to the columns the client's local table declares.\n *\n * The claims a transform sees at the edge are `{ sub }` and nothing else: a stream token carries the\n * subject, not the JWT it was minted from, and re-deriving richer claims per read would put an auth\n * provider call on the read path this whole topology exists to keep off it. A transform that needs\n * more than the subject is therefore NOT expressible at egress — put the subject-dependent part in\n * the shape's private `rowFilter.customPredicate`, which is compiled at subscribe time from the full\n * verified claims.\n */\nexport function createStreamGate(options: StreamGateOptions) {\n const doFetch = options.fetch ?? fetch;\n const base = options.durableStreamsUrl.replace(/\\/+$/, \"\");\n\n return async function handleStreamRead(request: Request, path: string, now: number): Promise<Response> {\n const decision = await authorizeStreamRead(options, readStreamToken(request), path, now);\n if (!decision.allow) {\n return new Response(JSON.stringify({ error: decision.reason }), {\n status: 403,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Resolved by shapeKey, exactly as the control plane resolved it to create the shape, so the edge\n // and the control plane cannot disagree about which declaration governs this stream.\n const entry = resolveEntryByShapeKey(options.registry, decision.grant.shapeKey);\n const transform: RowTransform | undefined = entry?.serverProjection?.rowTransform;\n\n // Refused BEFORE the upstream fetch: the rewrite needs a whole JSON body per response, and SSE\n // delivers a frame stream instead. Parsing that would mean a second body parser for a mode no\n // pgxsinkit client uses, so the mode is declined rather than half-supported.\n if (transform != null && asksForSse(request)) {\n return new Response(\n JSON.stringify({ error: \"this shape is rewritten at egress and is served as JSON long-poll only\" }),\n { status: 406, headers: { \"content-type\": \"application/json\" } },\n );\n }\n\n // Forward the ds protocol's own query string untouched — offsets and the live flag are the\n // protocol's, not ours, and rewriting them is how a proxy ends up owning a contract it does not\n // define. The token does NOT travel on: durable-streams has no read authorization in any\n // implementation, so it would only be an unread secret sitting in another service's logs.\n const upstreamUrl = new URL(`${base}/${path}`);\n upstreamUrl.search = new URL(request.url).search;\n\n const forwarded = new Headers(request.headers);\n forwarded.delete(\"authorization\");\n forwarded.delete(\"host\");\n\n const init: RequestInit = { method: request.method, headers: forwarded, signal: request.signal };\n\n // A downstream that walks away mid-long-poll (a client's clean `stop()`/unsubscribe) aborts\n // `request.signal`, and the forwarded fetch rejects with an AbortError. That is the cancellation\n // working as designed, not a failure — but left to propagate it surfaced as a 500 plus a raw\n // DOMException in every consumer's error log, once per stream, at every clean shutdown. Nothing\n // is ever delivered on an aborted request, so answer the mount's await with 499 (client closed\n // request) and stay quiet. A rejection with the signal NOT aborted is a real failure and still\n // propagates.\n const upstreamFetch = async (): Promise<Response> => {\n try {\n return await doFetch(upstreamUrl, init);\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n };\n\n // The pass-through path hands back the upstream Response OBJECT, untouched. Not \"an equivalent\n // response\" — the same one, so a shape that declares no transform pays nothing for the existence\n // of this stage and keeps whatever caching headers durable-streams answered with.\n if (transform == null || entry == null) return upstreamFetch();\n\n const upstream = await upstreamFetch();\n if (upstream.status === 499) return upstream;\n const headers = rewrittenEgressHeaders(upstream.headers);\n\n // 204 long-poll timeouts, 304s, upstream errors, and HEAD probes: nothing to rewrite, but they\n // are still answers about a subject-dependent stream, so they leave with the same no-store,\n // no-etag posture. HEAD belongs here because it answers `application/json` with NO body — parsing\n // it would throw on a request that is only asking for the headers.\n if (\n request.method === \"HEAD\" ||\n upstream.status !== 200 ||\n !(upstream.headers.get(\"content-type\") ?? \"\").includes(\"application/json\")\n ) {\n return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });\n }\n\n // The body read can abort the same way the fetch can (the poll delivered headers, the client\n // left before the body finished) — same cancellation, same quiet answer.\n let parsed: unknown;\n try {\n parsed = (await upstream.json()) as unknown;\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n const isBatch = Array.isArray(parsed);\n const envelopes = (isBatch ? parsed : [parsed]) as ProxiedEnvelope[];\n\n // The client keep-set: the columns the LOCAL table declares, computed once per request. Stripping\n // to it after the transform runs is what keeps `serverOnlyColumns` — fetched by the engine solely\n // so the transform could read them — off the client wire, and it also drops any key a transform\n // invented, so an egress rewrite can never widen the shape the client's schema was built for.\n const keep = new Set(getTableConfig(entry.localTable).columns.map((column) => column.name));\n const context: RowTransformContext = {\n claims: { sub: decision.subject },\n ...(options.params ? { params: options.params } : {}),\n };\n\n const rewritten = envelopes.map((envelope) => {\n const value = envelope?.value;\n if (value == null || typeof value !== \"object\") return envelope;\n const transformed = transform(value as Record<string, unknown>, context);\n const stripped: Record<string, unknown> = {};\n for (const [column, cell] of Object.entries(transformed)) {\n if (keep.has(column)) stripped[column] = cell;\n }\n return { ...envelope, value: stripped };\n });\n\n // Answered in the shape it arrived in. A ds long-poll body is an array, and the single-object case\n // is only defensive — re-emitting it as an array would corrupt a body the client can parse today.\n return new Response(JSON.stringify(isBatch ? rewritten : rewritten[0]), {\n status: upstream.status,\n statusText: upstream.statusText,\n headers,\n });\n };\n}\n",
5
+ "import type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport type {\n JwtClaims,\n RegistryRelations,\n RegistryTables,\n SyncRuntimeStatus,\n SyncServerAddress,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport { batchEventPaths, getSyncRegistryStreams } from \"@pgxsinkit/contracts\";\n\nimport type { EntitlementSet } from \"./circuits/edge\";\nimport type { CircuitsEngineClient } from \"./circuits/engine-client\";\nimport {\n barrierPath,\n createBarrierHandler,\n createRefreshHandler,\n createReleaseHandler,\n createSubscribeHandler,\n refreshPath,\n releasePath,\n type SubscribeEngineErrorReporter,\n subscribePath,\n} from \"./circuits/subscribe\";\nimport { createPgmqEventQueue } from \"./events/pgmq-queue\";\nimport type { EventQueue } from \"./events/queue\";\nimport { createEventIngestHandler, type EventGate, type EventsEnqueuedHook } from \"./events/route\";\nimport {\n authoritativeMutationPaths,\n batchMutationPaths,\n createMutationHandler,\n type StartupVerificationMode,\n} from \"./mutations/route\";\nimport { ensureOperationsLogSchema } from \"./operations-log/ddl\";\nimport type { OperationsLogConfig } from \"./operations-log/types\";\nimport { type CorsScope, FetchRouter } from \"./router\";\n\nconst defaultAllowedOrigins = [\"http://localhost:5173\", \"http://localhost:5174\"];\n\ninterface BunServerHandle {\n stop: () => void;\n}\n\ninterface BunNamespace {\n serve: (options: {\n port: number;\n hostname?: string;\n idleTimeout?: number;\n fetch: (request: Request) => Response | Promise<Response>;\n }) => BunServerHandle;\n}\n\n/**\n * How the operations-log table's presence is resolved at startup (ADR-0030 decision 3):\n * - `\"probe\"` (default): the safe degradation posture (ADR-0030) — one query ensures/confirms the table,\n * and logging is disabled at runtime (with a warning) if it is absent, so a missing table degrades\n * gracefully instead of failing writes.\n * - `\"enabled\"`: assume the table exists — NO query. If it is actually absent, writes then fail loudly.\n * - `\"disabled\"`: turn logging off with NO query.\n *\n * `\"enabled\" | \"disabled\"` are the serverless posture: paired with `startupVerification: \"deploy-time\"`,\n * a fresh worker sends zero queries before the mutation transaction itself.\n */\nexport type OperationsLogStartupMode = \"probe\" | \"enabled\" | \"disabled\";\n\n/**\n * The `deployment` profile owns the server's startup query posture (ADR-0030 decision 3). Its defaults\n * are the safe degradation posture — probe-and-verify at startup — so a long-lived host that never sets\n * it still verifies and degrades gracefully; serverless / per-request workers set\n * `{ startupVerification: \"deploy-time\", operationsLog: \"enabled\" | \"disabled\" }` for a\n * zero-startup-query first write.\n */\nexport interface DeploymentProfile {\n /** Governs ONLY the RLS auth-helper verify now (apply-fn drift is self-verifying). Default `\"in-process\"`. */\n startupVerification?: StartupVerificationMode;\n /** How the operations-log table presence is resolved. Default `\"probe\"`. */\n operationsLog?: OperationsLogStartupMode;\n}\n\nexport interface CreateSyncServerOptions<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n registry: TRegistry;\n db: TDb;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n /**\n * When set, the server serves the NATIVE read path's control plane (ADR-0055): subscribe, stream-token\n * re-mint, and the engine convergence barrier. Without it, none of those routes is registered and the\n * deployment is write-only.\n *\n * They share the single `resolveAuthClaims` adapter with the write path (ADR-0003), so read and write\n * authorization cannot diverge.\n */\n readPath?: {\n /** The Circuits engine's control API — never client-reachable; only this process calls it. */\n engine: CircuitsEngineClient;\n /**\n * The live entitlement set backing the shared tier. Omit when the registry declares no shared\n * shape — a shared subscription is then refused with that reason rather than silently allowed.\n */\n entitlements?: EntitlementSet;\n /** The stream-token signing key, shared with the edge. */\n key: CryptoKey;\n /** Per-deployment override of ADR-0055's 5-minute token lifetime. */\n ttlSeconds?: number;\n /** How long the barrier answer may be cached. Default 0 — see `createBarrierHandler`. */\n barrierMaxAgeSeconds?: number;\n /** Optional per-request extra params passed to the private tier's row filters. */\n resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;\n /** Reports sanitized shape-registration refusals from subscribe. Defaults to `console.error`. */\n onSubscribeEngineError?: SubscribeEngineErrorReporter;\n };\n operationsLog?: {\n enabled?: boolean;\n };\n /** Health check endpoint. Enabled by default at `/health`; `false` disables it, `{ path }` relocates it. */\n healthCheck?: boolean | { path: string };\n port?: number;\n host?: string;\n idleTimeoutSeconds?: number;\n allowedOrigins?: string[];\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n /**\n * The startup query posture (ADR-0030). The apply function now verifies its own ADR-0018 fingerprint\n * in-body on every call (SQLSTATE `PXS01` on drift), so there is no startup drift check to configure;\n * this governs only the RLS auth-helper verify and the operations-log presence resolution. Defaults\n * are the safe degradation posture (ADR-0030). See {@link DeploymentProfile}.\n */\n deployment?: DeploymentProfile;\n /**\n * The **Event lane**'s consent/entitlement gate (ADR-0053 decision 1): the lane's one function, and so an\n * option here rather than a registry field (the registry stays declarative data only). Called once per\n * event, after its payload validated and its identity resolved, and before anything is enqueued; a refusal\n * is a per-event `refused` verdict. Absent → every well-formed event is allowed. See {@link EventGate}.\n */\n eventGate?: EventGate;\n /**\n * Fired after an ingest request ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02): the\n * deployment-agnostic seam a SERVERLESS deployment uses to nudge whatever endpoint runs the consumer's\n * `drainOnce()`, so an interactive append drains in milliseconds instead of waiting for the next\n * scheduled tick. Fire-and-forget — it is called after the commit, its throw is caught and warn-logged,\n * and the scheduled sweep (not the nudge) is the delivery guarantee. Absent → nothing is nudged, which is\n * right for a deployment hosting the long-lived runner. See {@link EventsEnqueuedHook}.\n */\n onEventsEnqueued?: EventsEnqueuedHook;\n /**\n * The Event lane's queue backend. Defaults to the shipped pgmq backend over this server's own `db`\n * (`createPgmqEventQueue`), which is what makes an enqueue join the endpoint's transaction. Override it to\n * run the lane on another backend, or to substitute a fake in tests.\n */\n eventQueue?: EventQueue;\n /**\n * Opt-in per-request timing log (default false). When on, each mutation and shape-proxy request emits\n * one compact `[pgxsinkit-timing]` line with an ISO-8601(ms, UTC) timestamp and phase durations, for\n * attributing wall-clock latency against the client's `syncDebug` lines. Off by default — a pure\n * diagnostic surface that adds no standing query or latency when unset.\n */\n logTimings?: boolean;\n /**\n * The roles the INSTALLED apply function was generated with (`pgxsinkit-generate\n * --grant-execute-to <role>`, ADR-0054). Default `[]` — owner-only, the default the CLI generates.\n *\n * It is not a grant this server performs; it is how the server reproduces the artifact's ADR-0018\n * fingerprint, which hashes the ACL along with the rest of the body. Generate with a grant and leave\n * this unset and every write fails `PXS01` (stale artifact) — so the two lists must stay identical.\n */\n applyFunctionGrantExecuteTo?: readonly string[];\n /**\n * The schema the INSTALLED apply function lives in (`pgxsinkit-generate --function-schema <schema>`).\n * Default: unset — the artifact is generated unqualified and resolved through the connection's\n * `search_path`.\n *\n * It does two things at once, which is why one option drives both: the schema is part of the\n * fingerprinted body (the function names itself in its own self-check), AND it is how this server\n * QUALIFIES the call. Generate with `--function-schema` and leave this unset and the call goes out\n * unqualified — which either finds nothing (`42883`) or, worse, finds a same-named function elsewhere\n * on the `search_path` that then fails `PXS01` against a fingerprint it does not carry. The two must\n * name the same schema.\n */\n applyFunctionSchema?: string;\n}\n\nexport interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {\n tables: Array<keyof TRegistry & string>;\n modes: Record<string, TRegistry[keyof TRegistry][\"mode\"]>;\n}\n\nexport interface SyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n drizzle: TDb;\n fetch: (request: Request) => Promise<Response>;\n request: (path: string, init?: RequestInit) => Promise<Response>;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n status: SyncRuntimeStatus;\n address: SyncServerAddress | null;\n diagnostics: () => ServerDiagnostics<TRegistry>;\n}\n\nexport function createSyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n>(options: CreateSyncServerOptions<TRegistry, TDb>): SyncServer<TRegistry, TDb> {\n const db = options.db;\n const router = new FetchRouter();\n let bunServer: BunServerHandle | undefined;\n\n const status: SyncRuntimeStatus = {\n phase: \"ready\",\n isRunning: false,\n };\n\n let address: SyncServerAddress | null = null;\n const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);\n const operationsLogStartup = options.deployment?.operationsLog ?? \"probe\";\n // ADR-0030: how operations_log presence is resolved decides whether startup issues a query at all.\n // - \"probe\" (default): thread the presence probe into the effective config. operations_log is an\n // *optional* feature (default-enabled), so if logging was requested but the table is absent, disable\n // it at runtime rather than letting every write fail on a missing table — the documented degradation\n // (ensureOperationsLogSchema warns and returns `false`). The route awaits `operationsLogReady` before\n // any logOperation, so the corrected flag is in effect by the time logging runs, and the route holds\n // this same config object. (Board dogfooding: discarding this boolean 500'd every mutation on a\n // missing optional table.)\n // - \"enabled\": assume the table exists — NO query; logging stays on (an actual absence then fails\n // writes loudly, by design). \"disabled\": logging off — NO query.\n let operationsLogReady: Promise<void>;\n if (operationsLogStartup === \"probe\") {\n operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig).then((present) => {\n operationsLogConfig.enabled = operationsLogConfig.enabled && present;\n });\n } else {\n if (operationsLogStartup === \"disabled\") {\n operationsLogConfig.enabled = false;\n }\n operationsLogReady = Promise.resolve();\n }\n\n // CORS covers the canonical /api/* routes, plus the native control plane's own /sync/v1/* prefix.\n const corsScopes: CorsScope[] = [{ prefix: \"/api/\" }];\n if (options.readPath) {\n corsScopes.push({ prefix: \"/sync/v1/\" });\n }\n router.setCors(\n {\n origins: options.allowedOrigins ?? defaultAllowedOrigins,\n allowMethods: [\"GET\", \"POST\", \"OPTIONS\"],\n // `apikey`: a deployment gateway (Supabase) expects it on every request, so the browser client\n // sends it; it must be allowed in the preflight even though the server itself ignores it.\n allowHeaders: [\"Content-Type\", \"Authorization\", \"apikey\"],\n },\n corsScopes,\n );\n\n router.setErrorHandler((error) => {\n status.phase = \"degraded\";\n status.lastError = error instanceof Error ? error.message : \"Unexpected error\";\n options.onStatusChange?.(status);\n\n if (isValidationError(error)) {\n return Response.json({ message: \"Validation failed\", issues: error.issues }, { status: 400 });\n }\n\n return Response.json({ message: error instanceof Error ? error.message : \"Unexpected error\" }, { status: 500 });\n });\n\n const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);\n if (healthCheckPath) {\n router.get(healthCheckPath, () => Response.json({ ok: true }));\n }\n\n // The single mutation ingress point — all writes go through POST /api/mutations.\n const mutationHandlers = createMutationHandler(\n db,\n options.registry,\n operationsLogConfig,\n operationsLogReady,\n options.resolveAuthClaims,\n options.deployment?.startupVerification ?? \"in-process\",\n options.logTimings ?? false,\n options.applyFunctionGrantExecuteTo ?? [],\n options.applyFunctionSchema,\n );\n for (const path of batchMutationPaths) {\n router.post(path, mutationHandlers.batch);\n }\n for (const path of authoritativeMutationPaths) {\n router.post(path, mutationHandlers.authoritative);\n }\n\n // The Event lane's ingestion endpoint (ADR-0053 decision 3), mounted ONLY when the registry registers at\n // least one Event stream — a registry without streams has no event lane, and the path stays a 404. Nothing\n // is probed or provisioned here: the queues are deploy-time DDL (`pgxsinkit-generate --events`), so the\n // route preserves the zero-startup-query posture.\n const eventStreams = getSyncRegistryStreams(options.registry);\n if (eventStreams && Object.keys(eventStreams).length > 0) {\n const eventQueue = options.eventQueue ?? createPgmqEventQueue({ db });\n const eventHandler = createEventIngestHandler(db, options.registry, eventQueue, {\n ...(options.resolveAuthClaims ? { resolveAuthClaims: options.resolveAuthClaims } : {}),\n ...(options.eventGate ? { eventGate: options.eventGate } : {}),\n ...(options.onEventsEnqueued ? { onEventsEnqueued: options.onEventsEnqueued } : {}),\n logTimings: options.logTimings ?? false,\n });\n for (const path of batchEventPaths) {\n router.post(path, eventHandler);\n }\n }\n\n // The native control plane (ADR-0055). It shares the same resolveAuthClaims adapter as the write\n // path, so read and write authorization can never diverge (ADR-0003).\n //\n // Note what is NOT here: any route that serves shape DATA. Reads terminate on durable-streams\n // through the edge, which is the whole point of the topology — this process is asked once, at\n // subscribe time, and is then out of the read path entirely.\n if (options.readPath) {\n const readPath = options.readPath;\n const resolveAuthClaims = options.resolveAuthClaims;\n // Refused at construction, not at the first subscribe. Every read is bound to a subject in both\n // tiers (ADR-0055): the private tier fuses it into the predicate and the shared tier checks it\n // against the entitlement set, and a stream token with no subject would name a bearer no\n // revocation could ever reach. So a read path with no way to resolve a subject cannot grant\n // anything — it is a contradiction, and the only useful moment to say so is now, rather than as\n // a 401 every client then sits in.\n if (resolveAuthClaims === undefined) {\n throw new Error(\n \"[pgxsinkit] createSyncServer: `readPath` was configured without `resolveAuthClaims`. The native \" +\n \"read path mints a per-subject stream token, so it cannot serve a deployment that has no way to \" +\n \"resolve a subject. Provide `resolveAuthClaims`, or drop `readPath` for a write-only deployment.\",\n );\n }\n const subscribeOptions = {\n registry: options.registry,\n engine: readPath.engine,\n ...(readPath.entitlements ? { entitlements: readPath.entitlements } : {}),\n key: readPath.key,\n ...(readPath.ttlSeconds !== undefined ? { ttlSeconds: readPath.ttlSeconds } : {}),\n resolveAuthClaims,\n };\n\n router.post(\n subscribePath,\n createSubscribeHandler({\n ...subscribeOptions,\n ...(readPath.onSubscribeEngineError ? { onSubscribeEngineError: readPath.onSubscribeEngineError } : {}),\n }),\n );\n router.post(refreshPath, createRefreshHandler(subscribeOptions));\n // The close half of subscribe. Every grant subscribe handed out is a named claim on an engine\n // shape, and a live claim blocks dormancy and eviction — so without this route every shape waits\n // out its full lease window before it can be reclaimed. The release is idempotent (each grant\n // names its own claim), and a release that never arrives is reclaimed by the lease anyway; see\n // `releaseStreamGrants`.\n router.post(releasePath, createReleaseHandler({ engine: readPath.engine, key: readPath.key, resolveAuthClaims }));\n router.get(\n barrierPath,\n createBarrierHandler({\n engine: readPath.engine,\n resolveAuthClaims,\n ...(readPath.barrierMaxAgeSeconds !== undefined ? { maxAgeSeconds: readPath.barrierMaxAgeSeconds } : {}),\n }),\n );\n }\n\n const fetch = router.fetch;\n\n return {\n drizzle: db,\n fetch,\n request: (path, init) => {\n const baseUrl = address === null ? \"http://localhost\" : `http://${address.host}:${address.port}`;\n return fetch(new Request(new URL(path, baseUrl).toString(), init));\n },\n start: async () => {\n if (bunServer) {\n return;\n }\n\n const bun = getBunNamespace();\n if (!bun) {\n throw new Error(\"createSyncServer.start() requires the Bun runtime\");\n }\n\n const host = options.host ?? \"0.0.0.0\";\n const port = options.port ?? 3001;\n const idleTimeout = options.idleTimeoutSeconds;\n\n bunServer = bun.serve({\n hostname: host,\n port,\n ...(idleTimeout !== undefined ? { idleTimeout } : {}),\n fetch,\n });\n\n status.isRunning = true;\n status.phase = \"ready\";\n delete status.lastError;\n address = { host, port };\n options.onStatusChange?.(status);\n },\n stop: async () => {\n bunServer?.stop();\n bunServer = undefined;\n status.isRunning = false;\n options.onStatusChange?.(status);\n },\n status,\n get address() {\n return address;\n },\n diagnostics: () => ({\n tables: Object.keys(options.registry) as Array<keyof TRegistry & string>,\n modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),\n }),\n };\n}\n\nexport function buildRegistrySchema<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): RegistryTables<TRegistry> {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction resolveHealthCheckPath(config?: boolean | { path: string }, defaultEnabled = false): string | null {\n if (config === false) {\n return null;\n }\n\n if (config === undefined && !defaultEnabled) {\n return null;\n }\n\n if (typeof config === \"object\" && \"path\" in config) {\n return config.path;\n }\n\n return \"/health\";\n}\n\nfunction getBunNamespace(): BunNamespace | undefined {\n const maybeBun = (globalThis as { Bun?: BunNamespace }).Bun;\n return maybeBun;\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction resolveOperationsLogConfig(options?: { enabled?: boolean }): OperationsLogConfig {\n return {\n enabled: options?.enabled ?? true,\n };\n}\n\nexport { authoritativeMutationPaths, batchMutationPaths, createMutationHandler } from \"./mutations/route\";\nexport type { StartupVerificationMode } from \"./mutations/route\";\nexport type { CorsConfig, CorsScope, FetchHandler, RouterErrorHandler } from \"./router\";\nexport { FetchRouter } from \"./router\";\nexport { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from \"./mutations/plpgsql-apply\";\nexport type { ApplyFunctionRenderOptions } from \"./mutations/plpgsql-apply\";\nexport { renderPgxsinkitUtilitiesMigration } from \"./migrations/utilities\";\nexport { ensureOperationsLogSchema, operationsLogRegclassTarget } from \"./operations-log/ddl\";\nexport { operationsLogTable } from \"./operations-log/schema\";\nexport { readSqlState } from \"./sql-state\";\nexport {\n createEventIngestHandler,\n eventIngestRequiresClaims,\n EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,\n} from \"./events/route\";\nexport type {\n CreateEventIngestHandlerOptions,\n EventGate,\n EventGateDecision,\n EventGateInput,\n EventIngestDb,\n EventsEnqueuedHook,\n EventsEnqueuedInfo,\n} from \"./events/route\";\nexport { assertEventQueueReceipts, eventStreamQueueName, MalformedEventQueueMessageError } from \"./events/queue\";\nexport type {\n DeadLetteredEventMessage,\n DeliveredEventMessage,\n EventQueue,\n EventQueueExecutor,\n EventQueueReadOptions,\n EventQueueReceipt,\n} from \"./events/queue\";\nexport { createPgmqEventQueue, PGMQ_DEAD_LETTER_KEY } from \"./events/pgmq-queue\";\nexport type { CreatePgmqEventQueueOptions } from \"./events/pgmq-queue\";\nexport {\n computeEventPollWaitMs,\n defineEventConsumer,\n DEFAULT_EVENT_CONSUMER_BATCH_SIZE,\n DEFAULT_EVENT_DRAIN_BUDGET_MS,\n DEFAULT_EVENT_MAX_ATTEMPTS,\n DEFAULT_EVENT_POLL_CEILING_MS,\n DEFAULT_EVENT_POLL_FACTOR,\n DEFAULT_EVENT_POLL_FLOOR_MS,\n DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n} from \"./events/consumer\";\nexport type {\n DefineEventConsumerOptions,\n EventConsumer,\n EventConsumerBatch,\n EventConsumerCallback,\n EventConsumerPollOptions,\n EventConsumerSleep,\n EventDeadLetterReport,\n EventDrainOptions,\n EventDrainSummary,\n EventPollReport,\n} from \"./events/consumer\";\nexport {\n EVENT_LANE_FINGERPRINT_PREFIX,\n eventLaneDdlFingerprint,\n eventLaneStreamNames,\n renderEventLaneMigration,\n} from \"./events/ddl\";\nexport { resolveEventIdentity } from \"./events/identity\";\nexport type { IdentityResolution } from \"./events/identity\";\n\n// The Circuits-native read path (ADR-0055) — shape lifecycle only. Reads terminate on\n// durable-streams and never traverse the engine.\nexport { compileShapeRequest, fingerprintShapeRequest, resolveEntryByShapeKey } from \"./circuits/compile\";\nexport type { CompiledShapeRequest, ShapeRequest } from \"./circuits/compile\";\nexport { CircuitsEngineError, createCircuitsEngineClient } from \"./circuits/engine-client\";\nexport type { CircuitsEngineClient, CircuitsEngineOptions } from \"./circuits/engine-client\";\nexport type { CircuitsShapeHandle, CreateShapeRequest } from \"./circuits/wire\";\nexport {\n DEFAULT_STREAM_TOKEN_TTL_SECONDS,\n findGrant,\n importStreamTokenKey,\n mintStreamToken,\n verifyStreamToken,\n} from \"./circuits/stream-token\";\nexport type {\n MintStreamTokenOptions,\n VerifyStreamTokenOptions,\n StreamGrant,\n StreamTokenClaims,\n StreamTokenVerification,\n} from \"./circuits/stream-token\";\nexport {\n authorizeStreamRead,\n createStreamGate,\n EntitlementsUnavailableError,\n readStreamToken,\n STREAM_READ_EXPOSED_HEADERS,\n} from \"./circuits/edge\";\nexport type { EntitlementSet, GateDecision, StreamAuthorizationOptions, StreamGateOptions } from \"./circuits/edge\";\nexport {\n barrierPath,\n CircuitsLeaseConfigError,\n createBarrierHandler,\n createRefreshHandler,\n createReleaseHandler,\n createSubscribeHandler,\n refreshPath,\n refreshStreamToken,\n releasePath,\n releaseStreamGrants,\n subscribePath,\n subscribeToShapes,\n} from \"./circuits/subscribe\";\nexport type {\n DeniedSubscription,\n GrantedSubscription,\n RefreshResult,\n SubscribeEngineErrorDiagnostic,\n SubscribeEngineErrorReporter,\n SubscribeOptions,\n SubscribeResult,\n SubscriptionRequest,\n} from \"./circuits/subscribe\";\n",
6
+ "import {\n type JwtClaims,\n type PredicateValue,\n readShapeTier,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n type CompiledShapeRequest,\n compileShapeRequest,\n fingerprintShapeRequest,\n resolveEntryByShapeKey,\n} from \"./compile\";\nimport { type EntitlementSet, EntitlementsUnavailableError } from \"./edge\";\nimport { type CircuitsEngineClient, CircuitsEngineError } from \"./engine-client\";\nimport { DEFAULT_STREAM_TOKEN_TTL_SECONDS, mintStreamToken, type StreamGrant, verifyStreamToken } from \"./stream-token\";\nimport type { CircuitsShapeHandle, CreateShapeRequest } from \"./wire\";\n\n/**\n * One shape a client wants to follow.\n *\n * A shape KEY and nothing else — deliberately (ADR-0055 decision 6). A shared-tier shape fans out to\n * one stream per scope the subject holds, and the control plane does that expansion because it is\n * the only side that knows the answer: it holds the entitlement set. A client naming its own scopes\n * could only ever restate that set redundantly or contradict it, and every contradiction is a\n * denial it then has to reconcile at boot.\n */\nexport interface SubscriptionRequest {\n shapeKey: string;\n}\n\n/** A subscription the control plane granted: what to read, and where. */\nexport interface GrantedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n shapeId: string;\n /** The durable-streams path, which is what the client follows through the edge. */\n streamPath: string;\n}\n\n/** A subscription the control plane declined, with why. */\nexport interface DeniedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n reason: string;\n}\n\nexport interface SubscribeResult {\n /** The stream token covering every granted subscription. Absent when nothing was granted. */\n token?: string;\n /** Seconds since the epoch. The client re-mints before this, in one request for the whole batch. */\n expiresAt?: number;\n granted: GrantedSubscription[];\n denied: DeniedSubscription[];\n}\n\n/** Operator context for a shape-registration refusal at subscribe. */\nexport interface SubscribeEngineErrorDiagnostic {\n /** HTTP status from the engine. The subscribe response itself is a 503. */\n status: number;\n reason:\n | \"unknown_table\"\n | \"unknown_column\"\n | \"engine_booting\"\n | \"engine_degraded\"\n | \"request_refused\"\n | \"engine_unavailable\";\n /** Registry key and configured source table of the failed registration. */\n shapeKey: string;\n table: string;\n /** Registered keys among the first 16 requests, deduplicated. */\n batchShapeKeys: readonly string[];\n batchSize: number;\n}\n\n/** Reports sanitized operator context. An asynchronous report does not delay the response. */\nexport type SubscribeEngineErrorReporter = (diagnostic: SubscribeEngineErrorDiagnostic) => void | Promise<void>;\n\nexport interface SubscribeOptions {\n registry: SyncTableRegistry;\n engine: CircuitsEngineClient;\n /**\n * The live entitlement set backing the SHARED tier.\n *\n * Optional, because a registry with no shared-tier shape has nothing to ask it. Omitting it is a\n * statement that this deployment has none: a shared-tier subscription is then refused with that\n * reason rather than silently permitted, so adding the first shared shape fails loudly instead of\n * serving one subject's rows to everyone.\n */\n entitlements?: EntitlementSet;\n /** The stream-token signing key, shared with the edge — the same process holds both. */\n key: CryptoKey;\n /** Per-deployment override of ADR-0055's 5-minute default. */\n ttlSeconds?: number;\n /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */\n params?: Record<string, unknown>;\n /** Reports engine refusals. The HTTP handler defaults this to `console.error`. */\n onSubscribeEngineError?: SubscribeEngineErrorReporter;\n}\n\nfunction subscribeEngineRefusalReason(error: CircuitsEngineError): SubscribeEngineErrorDiagnostic[\"reason\"] {\n // Engine errors can quote predicate values. Classify a small JSON body using fixed reasons and\n // keep every byte from the response itself out of the diagnostic.\n if ((error.status === 400 || error.status === 503) && error.body.length <= 1024) {\n try {\n const body = JSON.parse(error.body) as { error?: unknown } | null;\n if (typeof body?.error === \"string\") {\n if (error.status === 400) {\n if (body.error.startsWith(\"unknown table '\")) return \"unknown_table\";\n if (body.error.startsWith(\"unknown column '\")) return \"unknown_column\";\n } else {\n if (body.error.startsWith(\"engine is still booting\")) return \"engine_booting\";\n if (body.error.startsWith(\"degraded: subquery membership effects were lost\")) return \"engine_degraded\";\n }\n }\n } catch {\n // Upstream proxies can return non-JSON responses. The status is still useful.\n }\n }\n return error.status >= 400 && error.status < 500 ? \"request_refused\" : \"engine_unavailable\";\n}\n\nfunction boundedDiagnosticLabel(value: string): string {\n const limit = 128;\n const label = value.slice(0, limit).replace(/[\\p{C}\\p{Zl}\\p{Zp}]/gu, \"?\");\n return value.length > limit ? `${label}…` : label;\n}\n\nfunction reportSubscribeEngineError(\n options: SubscribeOptions,\n error: CircuitsEngineError,\n shapeKey: string,\n table: string,\n batch: readonly SubscriptionRequest[],\n): void {\n const report = options.onSubscribeEngineError;\n if (!report) return;\n try {\n const entries = Object.values(options.registry);\n const keys = new Set<string>();\n for (const request of batch.slice(0, 16)) {\n if (\n typeof request?.shapeKey === \"string\" &&\n entries.some((entry) => entry?.shape?.shapeKey === request.shapeKey)\n ) {\n keys.add(boundedDiagnosticLabel(request.shapeKey));\n }\n }\n const diagnostic: SubscribeEngineErrorDiagnostic = {\n status: error.status,\n reason: subscribeEngineRefusalReason(error),\n shapeKey: boundedDiagnosticLabel(shapeKey),\n table: boundedDiagnosticLabel(table),\n batchShapeKeys: [...keys],\n batchSize: batch.length,\n };\n void Promise.resolve(report(diagnostic)).catch(() => {});\n } catch {\n // Diagnostics must preserve the retryable response even if the host reporter throws.\n }\n}\n\n/**\n * The engine's subscription lease is shorter than this deployment's token TTL — a **configuration**\n * fault, not a request one.\n *\n * The control plane renews every live claim on exactly one cadence: the token re-mint, which the\n * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The\n * engine releases a claim not renewed within `leaseSeconds` (`CIRCUITS_SHAPE_IDLE_SECS`).\n * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a\n * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The\n * factor of two is the margin for exactly one missed refresh.\n *\n * Refused loudly rather than papered over, because both numbers are the operator's and neither the\n * subject nor the client can do anything about either. The routes answer 503 — \"this deployment, not\n * you\" — and never a denial: a client told it lost entitlement truncates its rows.\n */\nexport class CircuitsLeaseConfigError extends Error {\n /** The engine's `CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */\n readonly leaseSeconds: number;\n /** The stream-token TTL this control plane is configured with. */\n readonly ttlSeconds: number;\n\n constructor(leaseSeconds: number, ttlSeconds: number) {\n super(\n `[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` +\n `CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +\n `(${ttlSeconds}s, the \\`ttlSeconds\\` option). Claims are renewed on the token re-mint, so a single ` +\n `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` +\n `it. Raise CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \\`ttlSeconds\\` to ` +\n `at most ${Math.floor(leaseSeconds / 2)}, or set CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +\n `leases entirely.`,\n );\n this.name = \"CircuitsLeaseConfigError\";\n this.leaseSeconds = leaseSeconds;\n this.ttlSeconds = ttlSeconds;\n }\n}\n\n/**\n * `leaseSeconds === 0` means the engine has dormancy — and with it leases — switched off, so there is\n * no window to fall out of and nothing to check. Anything else must cover two re-mints.\n */\nfunction assertLeaseCoversTtl(leaseSeconds: number, ttlSeconds: number): void {\n if (leaseSeconds !== 0 && leaseSeconds < 2 * ttlSeconds) throw new CircuitsLeaseConfigError(leaseSeconds, ttlSeconds);\n}\n\n/**\n * The engine must record a claim under the name it was given — on the create that TAKES it and on\n * every create that RENEWS it alike.\n *\n * An engine that renames a claim is one this control plane can neither renew nor release by id, which\n * is the whole protocol (fork ADR-0008): the renewal would take a second claim every time, and the\n * release would name something the engine never held. That is the wrong engine, not a degraded one,\n * so it throws rather than degrading — there is no answer this client could go on to give.\n */\nfunction assertClaimRecorded(handle: CircuitsShapeHandle, claim: string): void {\n if (handle.subscription === claim) return;\n throw new Error(\n `[pgxsinkit] the engine recorded this shape claim under \\`${handle.subscription}\\` rather than the ` +\n `subscription id it was sent (\\`${claim}\\`). Renewal and release are BY that id (fork ADR-0008), ` +\n `so an engine that renames a claim is not the one this client targets.`,\n );\n}\n\n/**\n * Compile one shape for one scope — the single form both the subscribe and the re-mint paths use.\n *\n * Shared between them on purpose: the re-mint RENEWS each grant's engine claim by repeating the create\n * that took it, so the request it sends has to be the request subscribe would build today. Two\n * spellings of \"compile this grant\" would be two chances for a renew to name a different definition\n * than the grant it is renewing — which the engine would answer with a different handle, and this\n * route would read as a revocation.\n */\nfunction compileGrant(\n options: Pick<SubscribeOptions, \"registry\" | \"params\">,\n claims: JwtClaims | null,\n shapeKey: string,\n scope?: readonly PredicateValue[],\n): CompiledShapeRequest {\n return compileShapeRequest(options.registry, {\n shapeKey,\n claims,\n ...(scope !== undefined ? { scope } : {}),\n ...(options.params ? { params: options.params } : {}),\n });\n}\n\n/** What a renewal attempt came to. `renewed` is the only outcome that keeps the grant. */\ntype RenewalOutcome = { renewed: true } | { revoked: string };\n\n/**\n * Renew one grant's engine claim: the SAME create, repeated with the SAME subscription id.\n *\n * This is the whole of the lease protocol on our side (fork ADR-0008). The engine has no separate\n * renew route because it needs none — a create naming a claim the shape already holds returns the same\n * handle, counts nothing, and moves the lease. So the re-mint, which already re-authorizes every grant\n * on the client's own refresh cadence, renews for free and renews exactly the grants that survived.\n *\n * The two failure outcomes are both \"this is no longer the stream the client follows\", and both end in\n * `revoked` rather than an error, because the client's answer to a revocation — truncate and\n * re-subscribe — is precisely the right one:\n *\n * - **A different handle.** The claim lapsed, or the shape was evicted, so this call re-subscribed\n * instead of renewing (ADR-0007) and the engine handed back a fresh shape on a fresh path. The\n * grant names the old one. The claim just taken is released immediately: nothing is following that\n * new stream, and the client's re-subscribe will take its own.\n * - **409.** The id names a different shape. Nothing was taken, so there is nothing to give back.\n *\n * Anything else the engine says is an OUTAGE and propagates — the route answers 503. A revocation\n * would tell the client it lost the scope, and a client told that clears the rows. An engine that\n * renames the claim propagates too, through {@link assertClaimRecorded}: that one is not an outage\n * either, it is the wrong engine.\n */\nasync function renewGrantClaim(\n engine: CircuitsEngineClient,\n request: CreateShapeRequest,\n grant: StreamGrant,\n ttlSeconds: number,\n): Promise<RenewalOutcome> {\n let handle;\n try {\n handle = await engine.createShape({ ...request, subscription: grant.claim });\n } catch (error) {\n if (error instanceof CircuitsEngineError && error.status === 409) {\n return { revoked: \"subscription id is held by another shape; re-subscribe\" };\n }\n throw error;\n }\n assertClaimRecorded(handle, grant.claim);\n // The handle comparison and the release of a fresh claim come BEFORE the lease guard, deliberately:\n // a misconfigured window is fatal to this request, and throwing it first would strand the claim\n // this very call just took.\n if (handle.shapeId !== grant.shapeId || handle.streamPath !== grant.path) {\n await engine.releaseShape(handle.shapeId, grant.claim);\n return { revoked: \"shape stream changed; re-subscribe\" };\n }\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n return { renewed: true };\n}\n\n/**\n * What one requested shape expands to: the scopes to compile it at.\n *\n * `[undefined]` — a single scope-less compile — is the private tier, whose subject arrives in the\n * claims instead. A shared-tier shape expands to one entry per entitled scope, and none is a\n * refusal rather than an empty success: a subject with no scopes has nothing to read, and returning\n * zero grants silently would leave the client waiting on streams that were never created.\n *\n * An unknown shapeKey deliberately expands to `[undefined]` and is refused downstream by\n * `compileShapeRequest`, so the message for \"no such shape\" has exactly one author.\n *\n * Throws {@link EntitlementsUnavailableError} when the set exists but cannot be trusted yet — an\n * outage, not a refusal, and the route turns it into a 503.\n */\nfunction expandToScopes(\n options: Pick<SubscribeOptions, \"registry\" | \"entitlements\">,\n subject: string,\n shapeKey: string,\n): { scopes: readonly (readonly PredicateValue[] | undefined)[] } | { refusal: string } {\n const entry: SyncTableEntry | undefined = resolveEntryByShapeKey(options.registry, shapeKey);\n const shape = entry?.shape;\n if (shape == null) return { scopes: [undefined] };\n if (readShapeTier(shape) === \"private\") return { scopes: [undefined] };\n\n if (options.entitlements === undefined) {\n return { refusal: \"shared-tier shape, but this deployment configured no entitlement set\" };\n }\n // A refusal above, a THROW here, and the difference is permanence. \"No entitlement set configured\"\n // is a statement about this deployment that will read the same on every future request. \"Not ready\"\n // is a statement about this instant, and answering it with a denial would tell the client it lost\n // the scope — which makes it clear those rows. See {@link EntitlementsUnavailableError}.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n const held = options.entitlements.scopesFor(subject, shapeKey);\n if (held.length === 0) return { refusal: \"no entitled scopes\" };\n return { scopes: held };\n}\n\n/**\n * Subscribe to a batch of shapes: compile each against the registry, check entitlement, register it\n * with the engine, and mint ONE token covering all of them.\n *\n * A shared-tier shape FANS OUT: one stream per scope the subject holds, so K requested shapes yield\n * however many grants their entitlements come to. Expansion happens here rather than on the client\n * because this is the side holding the entitlement set — see {@link SubscriptionRequest}.\n *\n * A partial result rather than an all-or-nothing one. A subject holding K scopes at boot may\n * legitimately have lost one of them, and failing the whole batch on that would deny them the K-1\n * they still hold — so a denial is reported per subscription and the rest proceed.\n *\n * That partiality covers AUTHORIZATION only. An engine that cannot answer — degraded, unreachable —\n * is not a denial and must never be reported as one: a client told \"not entitled\" truncates that\n * scope and unsubscribes, so reporting an outage that way would turn a transient engine fault into\n * client-side data loss. Engine failures propagate, and the route answers 503.\n *\n * An entitlement set that is not `ready` joins it. It is the same shape of failure — a dependency\n * that cannot answer right now — and the client's response to a denial is the same clear, so it\n * propagates as {@link EntitlementsUnavailableError} and the route answers 503 too. What stays a\n * denial is the set being absent altogether: that is a deployment's permanent configuration.\n *\n * Entitlement is checked HERE as well as at the edge, and the duplication is deliberate: this is\n * what stops a shape being created and a capability minted for a scope the subject never held. The\n * edge's check bounds how long an already-minted one keeps working.\n */\nexport async function subscribeToShapes(\n options: SubscribeOptions,\n claims: JwtClaims | null,\n requests: readonly SubscriptionRequest[],\n now: number,\n): Promise<SubscribeResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const granted: GrantedSubscription[] = [];\n const denied: DeniedSubscription[] = [];\n const grants: StreamGrant[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const request of requests) {\n const deny = (reason: string, scope?: readonly PredicateValue[]) =>\n denied.push({ shapeKey: request.shapeKey, ...(scope !== undefined ? { scope } : {}), reason });\n\n // Every read is bound to a subject, both tiers. The private tier fuses the subject into the\n // predicate and the shared tier checks it against the entitlement set, but neither has an\n // anonymous form — a token with no subject would name a bearer no revocation could reach.\n if (subject === null) {\n deny(\"no subject\");\n continue;\n }\n\n const expanded = expandToScopes(options, subject, request.shapeKey);\n if (\"refusal\" in expanded) {\n deny(expanded.refusal);\n continue;\n }\n\n for (const scope of expanded.scopes) {\n const scoped = scope !== undefined ? { scope } : {};\n const compiled = compileGrant(options, claims, request.shapeKey, scope);\n if (compiled.outcome === \"deny\") {\n deny(compiled.reason, scope);\n continue;\n }\n\n // Enumeration said yes; ask the predicate too. The two are required to agree, and when they do\n // not it is this side that must catch it: the edge checks `permits` on EVERY read, so a scope\n // only `scopesFor` believes in would mint a capability for a stream the client can never\n // actually read. Better a denial it can see now than a stream that 403s forever.\n if (compiled.tier === \"shared\" && !options.entitlements?.permits(subject, request.shapeKey, scope ?? [])) {\n deny(\"not entitled to this scope\", scope);\n continue;\n }\n\n // The private tier's grant records WHAT was authorized, not merely that something was. Its\n // predicate is a function of this subject's claims, and those change under the client's feet —\n // a role removed mid-session — so the re-mint has to be able to ask whether the shape this\n // grant points at is still the shape these claims compile to. The fingerprint is how it asks\n // without storing anything (ADR-0055 decision 6). The shared tier needs none: its predicate is\n // generated from the scope values, which the entitlement re-check already covers.\n const fp = compiled.tier === \"private\" ? { fp: await fingerprintShapeRequest(compiled.request) } : {};\n\n // The claim is NAMED before it is taken, and the name is ours (fork ADR-0008). That is what\n // makes this create idempotent — a repeat with the same id renews rather than joining twice —\n // and what makes the release retry-safe: `DELETE ?subscription=…` drops this claim and only\n // this one. A uuid per grant, never per shape: two grants that deduplicate onto one shapeId are\n // two joins, and one id could only ever release one of them.\n const claim = crypto.randomUUID();\n\n let handle: CircuitsShapeHandle;\n try {\n handle = await options.engine.createShape({ ...compiled.request, subscription: claim });\n } catch (error) {\n if (error instanceof CircuitsEngineError) {\n reportSubscribeEngineError(options, error, request.shapeKey, compiled.request.table, requests);\n }\n throw error;\n }\n assertClaimRecorded(handle, claim);\n // Checked per create rather than once at boot: the lease window is the engine's to report, and\n // this is the only place it is reported. A misconfigured pairing must surface as a 503 on the\n // very first subscribe, not as sessions quietly lapsing an idle window later.\n //\n // The claim is already taken by the time this can trip, so it is handed back before the error\n // leaves — nobody will ever follow this stream. Best effort, and the failure is SWALLOWED: the\n // configuration fault is what the operator has to see, and a release that also fails must not\n // mask it. An unreleased claim lapses on its own.\n try {\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n } catch (error) {\n await options.engine.releaseShape(handle.shapeId, claim).catch(() => {});\n throw error;\n }\n\n granted.push({ shapeKey: request.shapeKey, ...scoped, shapeId: handle.shapeId, streamPath: handle.streamPath });\n // The grant carries the shapeId this `createShape` returned AND the claim it was taken under,\n // and together they are what make the renew and release routes possible at all: both are\n // stateless, so the signed token is the only record of what this session holds.\n grants.push({\n path: handle.streamPath,\n shapeKey: request.shapeKey,\n shapeId: handle.shapeId,\n claim,\n ...scoped,\n ...fp,\n });\n }\n }\n\n if (subject === null || grants.length === 0) return { granted, denied };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, denied };\n}\n\n/**\n * The subscribe route: verified claims in, a token and stream paths out.\n *\n * Deliberately a POST that returns paths rather than a redirect to them. The client needs the whole\n * batch to open K long-polls and to know when to re-mint, and a redirect would give it one stream\n * and no expiry.\n */\nexport function createSubscribeHandler(\n options: SubscribeOptions & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n const subscribeOptions: SubscribeOptions = {\n ...options,\n onSubscribeEngineError:\n options.onSubscribeEngineError ??\n ((diagnostic) => {\n console.error(\"[pgxsinkit] subscribe shape registration failed\", diagnostic);\n }),\n };\n return async function handleSubscribe(request: Request): Promise<Response> {\n let body: { subscriptions?: SubscriptionRequest[] };\n try {\n body = (await request.json()) as { subscriptions?: SubscriptionRequest[] };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (!Array.isArray(body.subscriptions)) {\n return Response.json({ error: \"subscriptions must be an array\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n\n // Unauthenticated is NOT a denial, for the same reason an engine outage is not: a client told\n // \"not entitled\" truncates the scope and unsubscribes, so answering an expired JWT that way\n // turns a re-login into data loss. 401 is what makes it a distinct, recoverable status the\n // client can retry through (ADR-0013).\n //\n // The check is on the SUBJECT, not on the claims object: a verified token with no `sub` names a\n // bearer no revocation could ever reach, so it is exactly as unusable as no token at all. A\n // deployment with no auth adapter never reaches here — `createSyncServer` refuses that pairing\n // at construction.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: SubscribeResult;\n try {\n result = await subscribeToShapes(subscribeOptions, claims, body.subscriptions, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer is an OUTAGE, and 503 is what keeps the client retrying.\n // Relaying it as a per-subscription denial would tell the client it lost entitlement, and a\n // client told that truncates the scope and unsubscribes — turning a transient fault into data\n // loss.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n // A lease window shorter than the token TTL is an operator's misconfiguration, and it joins the\n // 503s for the same reason: it is a statement about this deployment, never about this subject's\n // entitlements. Denying instead would make an unserviceable pairing look like lost access.\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n // 200 even when everything was denied: the per-subscription reasons ARE the response, and\n // collapsing them to a status code would tell a client that lost one scope out of K nothing\n // about which one.\n return Response.json(result);\n };\n}\n\nexport interface RefreshResult {\n token?: string;\n expiresAt?: number;\n /** Grants that survived re-authorization — see {@link refreshStreamToken} for what that is per tier. */\n granted: StreamGrant[];\n /**\n * Grants the subject may no longer read as granted: a shared scope they have lost, or a private\n * shape their current claims no longer compile to. The client truncates each and unsubscribes,\n * then re-subscribes for whatever it is entitled to now.\n */\n revoked: DeniedSubscription[];\n}\n\n/**\n * Re-mint a stream token from an existing one (ADR-0055 decision 6).\n *\n * The expiring token IS the request: its signature proves this control plane issued those grants, so\n * nothing has to be stored server-side to know what the subject held, and the edge stays stateless on\n * both halves. Expiry is deliberately not enforced here — a token is presented for re-mint precisely\n * because it is at or past its TTL — but the signature is, and **every grant is re-authorized**.\n * That re-check is what makes the TTL a revocation bound rather than a formality.\n *\n * BOTH TIERS are re-authorized, by the question each tier's authorization actually turns on.\n *\n * - Shared: the live entitlement set. Its predicate is generated from the scope values, so it cannot\n * drift with the subject; what can change is whether the subject still holds the scope.\n * - Private: **recompile the shape with the subject's CURRENT claims** and compare the fingerprint\n * the grant carries. A private predicate may read ANY verified claim, not only `sub`, so a subject\n * demoted mid-session — a role dropped, a tenant changed — is still the same authenticated subject\n * and would sail through a check that only re-verified the JWT. Re-verifying the JWT proves the\n * bearer is still who they were; it says nothing about whether the shape they hold is still the\n * shape their claims compile to, and only recompiling answers that.\n *\n * A fingerprint mismatch is a REVOCATION by design, including when the recompiled predicate would\n * still permit the subject something. The grant names one stream, that stream serves the old\n * predicate, and this route may not hand out a new one — the client's re-subscribe is where a new\n * shape is created, and this route is not that. So the grant is revoked, the client re-subscribes, the\n * control plane creates the shape its current claims compile to, and because the handle differs the\n * client re-snapshots through ADR-0056 decision 7's must-refetch.\n *\n * **This is also where every surviving grant's engine claim is RENEWED** (fork ADR-0008). A claim is a\n * lease: the engine releases one not renewed within `leaseSeconds`, because native reads terminate on\n * durable-streams and the renewal is the only liveness signal it has. Renewing here rather than on a\n * timer is what makes the cadence honest — this route already runs once per subject per TTL window and\n * already decides which grants are still authorized, so the renewal covers exactly the grants that\n * survived and costs no extra round trip. A revoked grant is deliberately NOT renewed: its lease\n * lapses and the engine reclaims the shape.\n *\n * The renewal is the same create, repeated with the grant's own `claim` id. Its outcomes are in\n * {@link renewGrantClaim}; a renewal that comes back a different handle, or 409s, revokes the grant\n * with a re-subscribe reason rather than failing the whole re-mint.\n *\n * `registry` is therefore REQUIRED rather than optional: a refresh route that cannot recompile cannot\n * re-authorize the private tier — and now cannot renew either, since the renewal IS the compiled\n * create. `engine` is required for the same reason.\n *\n * Throws {@link EntitlementsUnavailableError} rather than revoking when the set cannot be consulted —\n * the same outage-is-not-a-denial rule {@link subscribeToShapes} follows, and it matters more here:\n * `revoked` is the wire's clear-this-scope instruction, and this route runs every few minutes for\n * the life of every subscription. An engine that cannot answer a renewal joins it, as does a lease\n * window this deployment's TTL does not fit inside ({@link CircuitsLeaseConfigError}).\n */\nexport async function refreshStreamToken(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\">,\n claims: JwtClaims | null,\n expiringToken: string,\n now: number,\n): Promise<RefreshResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const verified = await verifyStreamToken(options.key, expiringToken, now, { allowExpired: true });\n if (!verified.ok || subject === null) return { granted: [], revoked: [] };\n\n // The token names its subject; a token presented by anyone else is not a re-mint, it is a theft.\n if (verified.claims.sub !== subject) return { granted: [], revoked: [] };\n\n const granted: StreamGrant[] = [];\n const revoked: DeniedSubscription[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const grant of verified.claims.grants) {\n const scoped = grant.scope !== undefined ? { scope: grant.scope } : {};\n if (grant.scope === undefined) {\n // Private tier: re-authorize by recompiling. See the note above on why the signed grant alone\n // is not the entitlement — the predicate is a function of claims that may have changed since\n // it was issued.\n const compiled = compileGrant(options, claims, grant.shapeKey);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, reason: compiled.reason });\n continue;\n }\n if (grant.fp === undefined) {\n // Nothing to compare against, so nothing that could establish this grant is still the right\n // one. Fail closed rather than trust it: the recovery is a re-subscribe, which costs the\n // client a re-snapshot and costs the subject nothing they are still entitled to.\n revoked.push({\n shapeKey: grant.shapeKey,\n reason: \"private grant carries no fingerprint and cannot be re-authorized\",\n });\n continue;\n }\n if ((await fingerprintShapeRequest(compiled.request)) !== grant.fp) {\n revoked.push({ shapeKey: grant.shapeKey, reason: \"shape predicate changed for this subject\" });\n continue;\n }\n // Re-authorized, so renew the claim it holds — the recompiled request is exactly the one that\n // took it, which the fingerprint just proved.\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n continue;\n }\n if (options.entitlements === undefined) {\n // Permanent, and therefore a real revocation: this deployment has no entitlement set, so a\n // shared grant can never be re-minted and the scope is not coming back.\n //\n // Worded as the EDGE words the same condition, and deliberately not as \"entitlements\n // unavailable\" — that string is now the 503 outage body, which means the exact opposite here:\n // an outage says nothing about this subject's scopes and must never clear a row.\n revoked.push({\n shapeKey: grant.shapeKey,\n ...scoped,\n reason: \"shared-tier grant, but this deployment configured no entitlement set\",\n });\n continue;\n }\n // Transient, and therefore NOT a revocation. `revoked` is an instruction to clear the scope, and\n // a re-mint is the most routine request on this route — an entitlement subscription that is a few\n // seconds behind would otherwise empty a subject's store every time it reconnected.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n if (!options.entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: \"not entitled to this scope\" });\n continue;\n }\n // Still entitled, so renew. The shared tier carries no fingerprint — its predicate is generated\n // from the scope values, which is why the entitlement check above is the whole question — so the\n // request is recompiled here, through the same {@link compileGrant} subscribe used.\n const compiled = compileGrant(options, claims, grant.shapeKey, grant.scope);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: compiled.reason });\n continue;\n }\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n }\n\n if (granted.length === 0) return { granted, revoked };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants: granted, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, revoked };\n}\n\n/**\n * The re-mint route. Takes the expiring token, answers with a fresh one and the list of grants that\n * did not survive re-authorization — the shared tier's against the live entitlement set, the private\n * tier's against a recompile with the subject's current claims — and **renews the engine claim of\n * every grant that did survive** (fork ADR-0008).\n *\n * `registry` for that recompile and `engine` for that renewal, both required for the reasons\n * {@link refreshStreamToken} gives.\n *\n * 200 even when everything was revoked, for the same reason subscribe answers 200 on a full denial:\n * the per-grant reasons ARE the response, and a client that lost one scope of K needs to know which.\n */\nexport function createRefreshHandler(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\"> & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRefresh(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // Same as subscribe: an unauthenticated re-mint is a credential problem, not a revocation. The\n // difference matters more here — a `revoked` answer makes the client truncate, and a token\n // expiring is the single most ordinary thing that happens on this route.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: RefreshResult;\n try {\n result = await refreshStreamToken(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // 503, never a `revoked` list: an entitlement set that cannot answer has said nothing about\n // this subject's scopes, and a client that read it as a revocation would clear rows it still\n // holds. The client retries with the token it already has, which the edge keeps honouring\n // until its TTL lapses.\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n // An engine that could not answer a RENEWAL is the same case: the claim is still held (a lease\n // outlives a failed renewal by the rest of its window), the token the client holds still works,\n // and a `revoked` answer would clear rows over a transient fault.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n throw error;\n }\n return Response.json(result);\n };\n}\n\n/**\n * Give back the engine claims a token's grants acquired — the close half of subscribe.\n *\n * **Why this route exists.** A native `POST /shapes` with a definition the engine already holds does\n * not create a second shape: it JOINS the existing one, under a claim of its own. Live claims are\n * load-bearing rather than bookkeeping — one live claim blocks both dormancy and eviction, precisely\n * because native durable-streams reads bypass the engine entirely, so a claim is the only thing that\n * tells it a reader it cannot see still exists. Without a release, a shape waits out its whole lease\n * window before it can go dormant, every time.\n *\n * **The token IS the request**, exactly as on the re-mint path: its signature proves this control\n * plane minted these grants, so nothing has to be stored server-side to know what was acquired.\n * Verified with `allowExpired`, and that is not a weakening — a session releases at CLOSE, which is\n * routinely past a 5-minute TTL, and expiry bounds how long a grant keeps *working*, not what it\n * proves was issued. A release grants its bearer nothing; the only thing it can do is give away\n * claims that this token's own subject holds.\n *\n * **ONE release per GRANT, deliberately not deduplicated by `shapeId`.** Two grants naming one shape\n * are two joins — the engine deduplicated identical definitions and counted both (ADR-0055 decision\n * 6) — so collapsing them here would return one of two claims and leak the other permanently. Each\n * grant releases its OWN claim (`DELETE /shapes/{id}?subscription=<claim>`), which is what makes one\n * release distinguishable from the other at all.\n *\n * **Idempotent and retry-safe** (fork ADR-0008). A claim is named, so releasing it twice is releasing\n * it once: the second `DELETE` is a no-op `200` and cannot touch another subscriber's claim. That is\n * a change in kind from the anonymous refcount decrement this route was first written against, and it\n * collapses the old asymmetry — a client, a proxy or an operator may repeat a release freely. A\n * release that never arrives at all is not a permanent leak either: the claim is a LEASE, renewed on\n * the token re-mint, so a session that crashed or was unloaded has its claims reclaimed by the engine\n * within `leaseSeconds`. What this route buys is promptness, not correctness.\n *\n * Refusals are refusals, not no-ops: a bad signature or a mismatched subject answers an error rather\n * than `{ released: 0 }`, because a token presented by anyone but its own subject is not a release,\n * it is an attempt to drop the victim's claims.\n */\nexport async function releaseStreamGrants(\n options: { engine: CircuitsEngineClient; key: CryptoKey },\n claims: JwtClaims | null,\n token: string,\n now: number,\n): Promise<{ released: number } | { refused: string }> {\n const subject = typeof claims?.sub === \"string\" && claims.sub !== \"\" ? claims.sub : null;\n if (subject === null) return { refused: \"unauthenticated\" };\n\n const verified = await verifyStreamToken(options.key, token, now, { allowExpired: true });\n if (!verified.ok) return { refused: verified.reason };\n if (verified.claims.sub !== subject) return { refused: \"token subject does not match the caller\" };\n\n for (const grant of verified.claims.grants) {\n await options.engine.releaseShape(grant.shapeId, grant.claim);\n }\n return { released: verified.claims.grants.length };\n}\n\n/**\n * The release route: the token a session was given, back at its close.\n *\n * **Safe to call more than once.** Every grant releases a NAMED claim, so a repeat is the same act\n * once (fork ADR-0008) — a duplicate close, a proxy retry or an operator replaying a request all\n * answer 200 and change nothing. The client still sends it at most once, but that is now a matter of\n * not making a pointless request rather than of correctness.\n *\n * 403 rather than 200 on a refusal — see {@link releaseStreamGrants} for why a refused release must\n * be visible. 401 when the caller has no subject, the same rule subscribe and re-mint follow: an\n * unauthenticated call is a credential problem, and it is the one thing here a client could fix.\n */\nexport function createReleaseHandler(\n options: {\n engine: CircuitsEngineClient;\n key: CryptoKey;\n } & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRelease(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: { released: number } | { refused: string };\n try {\n result = await releaseStreamGrants(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer has not dropped the claims. 503 says \"this deployment, not\n // you\", and a client is free to come back: releases are named and therefore idempotent (fork\n // ADR-0008), so a retry that races a release which actually landed is a no-op rather than a\n // theft. Whether it retries or not, the residue is bounded by the lease — an unreleased claim\n // lapses within `leaseSeconds` of its last renewal.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n if (\"refused\" in result) return Response.json({ error: result.refused }, { status: 403 });\n return Response.json(result);\n };\n}\n\n/** The control-plane paths the native read path mounts. */\nexport const subscribePath = \"/sync/v1/subscribe\";\nexport const refreshPath = \"/sync/v1/refresh\";\nexport const releasePath = \"/sync/v1/release\";\n\n/**\n * The convergence-barrier route (ADR-0056 decision 4).\n *\n * Proxied rather than exposed: the engine's control plane is unauthenticated by design and is not\n * client-reachable, so surfacing the barrier on our own authenticated endpoint costs nothing and\n * keeps the trust boundary intact.\n *\n * `maxAgeSeconds` may cache the answer briefly, but only a HEALTHY one. For the `pendingFlips` term\n * staleness is safe in exactly one direction — it moves the barrier backwards, so a stale reading can\n * only DELAY an alignment, never satisfy one falsely. `flipFailures` inverts that: a cached\n * pre-degradation zero would let a group align against an engine that has already\n * lost membership effects, which is precisely the alignment the term exists to refuse. So a degraded\n * reading is never cached and never served from cache, and the cache window is exactly the bound on\n * how long a client may align against a freshly-degraded engine — which is why the default is 0.\n */\nexport function createBarrierHandler(options: {\n engine: CircuitsEngineClient;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n maxAgeSeconds?: number;\n}) {\n let cached: { at: number; body: BarrierBody } | null = null;\n const maxAge = options.maxAgeSeconds ?? 0;\n\n return async function handleBarrier(request: Request): Promise<Response> {\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // The barrier says nothing about any subject's data — only whether the engine has finished\n // propagating — but it is still engine internals, so it needs a caller we recognise.\n if (options.resolveAuthClaims && claims === null) {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n const now = Date.now() / 1000;\n if (cached && now - cached.at < maxAge) return Response.json(cached.body);\n\n const state = await options.engine.replicationState();\n const body = { pendingFlips: state.pendingFlips, flipFailures: state.flipFailures };\n cached = body.flipFailures > 0 ? null : { at: now, body };\n return Response.json(body);\n };\n}\n\nexport const barrierPath = \"/sync/v1/barrier\";\n\n/** The barrier as the client reads it — the engine's LSN is operator detail and stays server-side. */\ninterface BarrierBody {\n pendingFlips: number;\n /** Abandoned flip batches. Non-zero is terminal for a group reading it, and is never cached. */\n flipFailures: number;\n}\n",
7
+ "import { getTableName, getTableSchema } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport {\n conjoinPredicates,\n DENY_ALL_PREDICATE,\n isAndPredicate,\n isIsNullPredicate,\n isLeafPredicate,\n type JwtClaims,\n type Predicate,\n type PredicateValue,\n readShapeTier,\n type ShapeSpec,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { CreateShapeRequest } from \"./wire\";\n\n/** What a client asks the control plane for: a declared shape, plus the inputs its tier consumes. */\nexport interface ShapeRequest {\n /** The shape's unique identity, exactly as declared. Never a table name the client chose. */\n shapeKey: string;\n /** Verified claims. The private tier's only subject input; the shared tier never sees them. */\n claims: JwtClaims | null;\n /**\n * SHARED TIER — the scope values, positionally matching the shape's declared `scope` columns.\n * `null` is a legal value and compiles to `IS NULL`, so an absent element and a null one are\n * different things: arity is checked strictly rather than padded.\n */\n scope?: readonly PredicateValue[];\n /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */\n params?: Record<string, unknown>;\n}\n\n/**\n * The outcome of compiling a request. A denial is a first-class result rather than an exception\n * because it is an ordinary, expected outcome — an anonymous caller, a subject with no membership —\n * and because the caller's response to it (no handle, no shape, 403) is the same for every reason.\n */\nexport type CompiledShapeRequest =\n | { outcome: \"create\"; tier: \"shared\" | \"private\"; request: CreateShapeRequest }\n | { outcome: \"deny\"; reason: string };\n\n/**\n * Resolve the entry a request selects by its **`shapeKey`** — not by table name, since several\n * shapes (a read projection and its owner) legitimately read one physical table under distinct keys.\n * Schema qualification is significant. Returns undefined when nothing declares that key, and the\n * caller fails closed. An ambiguous key is a registry configuration error.\n */\nexport function resolveEntryByShapeKey(registry: SyncTableRegistry, shapeKey: string): SyncTableEntry | undefined {\n const matches = Object.values(registry).filter((entry) => entry?.shape?.shapeKey === shapeKey);\n if (matches.length > 1) {\n throw new Error(`shapeKey \"${shapeKey}\" is declared by multiple registry entries`);\n }\n return matches[0];\n}\n\n/** The physical table the engine reads. Keep public requests in their existing fingerprint form. */\nfunction resolveShapeTarget(entry: SyncTableEntry, shape: ShapeSpec): string {\n const schema = getTableSchema(entry.table);\n // A dot in a Drizzle identifier is literal but the native API treats it as a table separator.\n if (getTableName(entry.table).includes(\".\") || schema?.includes(\".\")) {\n throw new Error(`shape \"${shape.shapeKey}\" has a dot in a Postgres schema or table identifier`);\n }\n const target = shape.physicalTable ?? shape.tableName;\n const separator = target.indexOf(\".\");\n if (separator !== -1) {\n return target.startsWith(\"public.\") && target.lastIndexOf(\".\") === separator ? target.slice(separator + 1) : target;\n }\n return schema === undefined || schema === \"public\" ? target : `${schema}.${target}`;\n}\n\n/**\n * The columns the ENGINE emits onto the stream, or undefined for the whole row.\n *\n * Not the same set as the columns the CLIENT receives, and the difference is load-bearing. Read off\n * `shape.rowFilter.columns` when the registry declares one — which for a read projection is the\n * client keep-set PLUS its `serverOnlyColumns` — otherwise off `localTable`, so a shape with no\n * allow-list emits exactly what the local schema declares.\n *\n * `serverOnlyColumns` therefore ARE emitted by the engine, deliberately: an egress\n * `serverProjection.rowTransform` has to READ them, and the engine is the only thing that can fetch\n * them. They come off the wire at the stream edge, which strips every rewritten row back to the local\n * table's columns AFTER the transform has run (`createStreamGate`, ADR-0055 decision 5). So the\n * ordering hazard between rewriting and omission is ANSWERED — transform first, strip second, in one\n * place — rather than dissolved: this function must not \"helpfully\" narrow the allow-list to the\n * client keep-set, because that would starve the transform of its inputs and fail it open.\n */\nfunction emittedColumns(entry: SyncTableEntry): string[] | undefined {\n const explicit = entry.shape?.rowFilter?.columns;\n if (explicit != null && explicit.length > 0) return [...explicit];\n if (entry.clientProjection?.omitColumns == null) return undefined;\n return getTableConfig(entry.localTable).columns.map((column) => column.name);\n}\n\n/**\n * Compile a shape request into the engine's `POST /shapes` body, or a denial.\n *\n * The whole predicate is built here, in the control plane, from the registry — nothing predicate\n * shaped arrives on the wire. That is strictly stronger than the proxy's \"discard the client's\n * `where`\": there is no `where` on the wire to discard, so no parameter parsing to get right and no\n * grammar for a client to probe.\n */\nexport function compileShapeRequest(registry: SyncTableRegistry, request: ShapeRequest): CompiledShapeRequest {\n const entry = resolveEntryByShapeKey(registry, request.shapeKey);\n const shape = entry?.shape;\n if (entry == null || shape == null) {\n return { outcome: \"deny\", reason: `no shape declares shapeKey \"${request.shapeKey}\"` };\n }\n\n const tier = readShapeTier(shape);\n const subject =\n tier === \"shared\" ? scopePredicate(shape, request.scope) : privatePredicate(shape, request.claims, request.params);\n if (\"refusal\" in subject) return { outcome: \"deny\", reason: subject.refusal };\n\n const where = conjoinPredicates(subject.predicate, shape.where);\n\n const narrowing = assertLocalPrimaryKeyIsPinned(entry, where);\n if (narrowing != null) return { outcome: \"deny\", reason: narrowing };\n\n const columns = emittedColumns(entry);\n\n return {\n outcome: \"create\",\n tier,\n request: {\n table: resolveShapeTarget(entry, shape),\n ...(where !== undefined ? { where } : {}),\n ...(columns !== undefined ? { columns } : {}),\n },\n };\n}\n\n/**\n * The shared tier's predicate: an `AND` of equalities over the declared scope columns, generated —\n * never authored. Every property the tier depends on comes from that generation. Two shapes of a\n * family cannot overlap, because a row carries one value per scope column. Two subscribers holding\n * the same scope values produce byte-identical requests, which is what lets Circuits collapse them\n * onto one stream and what makes the resulting stream cacheable at all.\n */\nfunction scopePredicate(\n shape: ShapeSpec,\n values: readonly PredicateValue[] | undefined,\n): { predicate: Predicate | undefined } | { refusal: string } {\n const columns = shape.scope ?? [];\n if (values == null) {\n return { refusal: `shape \"${shape.shapeKey}\" is shared-tier and requires ${columns.length} scope value(s)` };\n }\n if (values.length !== columns.length) {\n return {\n refusal:\n `shape \"${shape.shapeKey}\" takes ${columns.length} scope value(s) ` +\n `(${columns.join(\", \")}) but got ${values.length}`,\n };\n }\n\n const equalities = columns.map((col, index): Predicate => {\n const value = values[index]!;\n // NULL is a scope value like any other, and `col = NULL` is UNKNOWN for every row — so the one\n // that would silently match nothing is the one that has to become `IS NULL`.\n return value === null ? { col, isNull: true } : { col, op: \"eq\", value };\n });\n\n return { predicate: conjoinPredicates(...equalities) };\n}\n\n/**\n * Every column pinned to exactly one value by a predicate's **top-level conjunction**.\n *\n * Conservative on purpose: only `col = value` and `col IS NULL` conjuncts pin, and only where they\n * sit in the outermost `AND` chain. A branch under `OR` or `NOT` admits more than one value for its\n * column by construction, and an `IN (subquery)` admits as many as the subquery returns — none of\n * those pin, so none are collected.\n */\nfunction pinnedColumns(node: Predicate | undefined, into: Set<string> = new Set()): Set<string> {\n if (node == null) return into;\n if (isAndPredicate(node)) {\n for (const child of node.and) pinnedColumns(child, into);\n return into;\n }\n if (isIsNullPredicate(node)) {\n into.add(node.col);\n return into;\n }\n if (isLeafPredicate(node) && node.op === \"eq\") {\n into.add(node.col);\n }\n return into;\n}\n\n/**\n * Refuse a `clientProjection.localPrimaryKey` that narrows the server key without the predicate\n * pinning what it drops.\n *\n * The second of the two checks replacing ADR-0014's primary-key collision tripwire, and the one case\n * where a collision was never machinery at all. Narrowing is the point of `localPrimaryKey` — server\n * key `(owner_id, card_id)` becomes local key `(card_id)` because the caller only ever syncs their\n * own rows — and it is sound *exactly when* the shape's predicate admits one value for every dropped\n * column. Pinned, two server rows can never collapse onto one local key. Unpinned, they can, and the\n * client would silently keep whichever arrived last: under a plain INSERT that surfaced as a PK\n * collision, and under `upsert` it does not surface at all.\n *\n * Checked here rather than at `defineSyncTable` because the predicate is claims-dependent: what pins\n * `owner_id` is the subject fused into it, which does not exist until a real caller subscribes. The\n * refusal is therefore per-subscription, and lands at the same place and in the same form as every\n * other compile denial.\n */\nfunction assertLocalPrimaryKeyIsPinned(entry: SyncTableEntry, where: Predicate | undefined): string | null {\n const localKey = entry.clientProjection?.localPrimaryKey?.columns;\n if (localKey == null || localKey.length === 0) return null;\n\n const localKeySet = new Set<string>(localKey);\n const dropped = entry.primaryKey.columns.filter((column) => !localKeySet.has(column));\n if (dropped.length === 0) return null;\n\n const pinned = pinnedColumns(where);\n const unpinned = dropped.filter((column) => !pinned.has(column));\n if (unpinned.length === 0) return null;\n\n return (\n `shape \"${entry.shape!.shapeKey}\" declares clientProjection.localPrimaryKey ` +\n `(${localKey.join(\", \")}), dropping ${unpinned.join(\", \")} from the server primary key ` +\n `(${entry.primaryKey.columns.join(\", \")}) — but this caller's predicate does not pin ` +\n `${unpinned.length === 1 ? \"that column\" : \"those columns\"} to a single value, so two server rows ` +\n `could collapse onto one local key. Pin it with a top-level equality in the shape's rowFilter (or ` +\n `its scope), or widen localPrimaryKey to include it.`\n );\n}\n\n/** The private tier's predicate: the registry's own claims-fused filter, or a denial. */\nfunction privatePredicate(\n shape: ShapeSpec,\n claims: JwtClaims | null,\n params: Record<string, unknown> | undefined,\n): { predicate: Predicate | undefined } | { refusal: string } {\n const filter = shape.rowFilter?.customPredicate;\n if (filter == null) return { predicate: undefined };\n\n const resolved = filter(claims ?? {}, params);\n // Reference identity: a denied subject gets no shape at\n // all rather than an empty one, so nothing is created and nothing has to be torn down later.\n if (resolved === DENY_ALL_PREDICATE) {\n return { refusal: `shape \"${shape.shapeKey}\" denies this caller` };\n }\n return { predicate: resolved ?? undefined };\n}\n\n/**\n * Canonical JSON: object keys sorted, `undefined` members dropped, array order preserved.\n *\n * Emitted as a string directly rather than by rebuilding an object and handing it to\n * `JSON.stringify`, because a rebuilt object's key order is not entirely ours to choose — a JS engine\n * enumerates integer-like keys numerically ahead of insertion order, so a sorted rebuild is only\n * *usually* serialized in the order it was sorted into. Writing the bytes here removes the\n * \"usually\".\n *\n * Array order IS significant and is kept: `columns` is a projection whose order the engine sees, and\n * an `and`/`or` chain's operand order is part of the predicate as sent.\n */\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value ?? null);\n if (Array.isArray(value)) return `[${value.map((member) => canonicalJson(member ?? null)).join(\",\")}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, member]) => member !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : 1));\n return `{${entries.map(([key, member]) => `${JSON.stringify(key)}:${canonicalJson(member)}`).join(\",\")}}`;\n}\n\n/**\n * A content fingerprint of a compiled shape request — SHA-256 over its canonical JSON, lowercase hex.\n *\n * CANONICAL because the input is not a literal an author wrote: a predicate reaches here through\n * `rowFilter.customPredicate`, whose closure may assemble `{ col, op, value }` in whatever order its\n * branches happen to take, and `p.and(a, b)` on one path may nest where another flattens. Two\n * compiles that MEAN the same thing must fingerprint the same, or the equality below degrades into a\n * test of how the author's code was written on the day.\n *\n * This is an AUTHORIZATION equality check, not a cache key. Two requests fingerprinting the same are\n * the same shape to the engine — same table, same predicate, same projection — so a subject whose\n * recompiled shape still fingerprints as the one their grant names is still authorized for exactly\n * the stream that grant points at. A collision is therefore not a performance regression, it is an\n * authorization one, which is why this is a cryptographic digest and not a cheap hash.\n *\n * Used by the re-mint path (ADR-0055 decision 6) to re-authorize a private-tier grant against the\n * subject's current claims. Never sent to the engine, which knows nothing about it.\n */\nexport async function fingerprintShapeRequest(request: CreateShapeRequest): Promise<string> {\n const canonical = canonicalJson({\n table: request.table,\n where: request.where,\n columns: request.columns,\n changesOnly: request.changesOnly,\n });\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(canonical));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n",
8
+ "import { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport type { PredicateValue, RowTransform, RowTransformContext, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { resolveEntryByShapeKey } from \"./compile\";\nimport { findGrant, type StreamGrant, verifyStreamToken } from \"./stream-token\";\n\n/**\n * The live entitlement set the edge checks a shared-tier read against (ADR-0055 decision 7).\n *\n * An interface, not an implementation, because the source is a Circuits subscription over the\n * membership relations themselves — freshness is engine propagation, not a cache TTL, and there is\n * no database on the read path.\n */\nexport interface EntitlementSet {\n /**\n * Whether the entitlement set can be trusted right now. False while the subscription is catching\n * up, degraded, or stale.\n *\n * The edge denies when this is false. An unavailable entitlement set is never a permit — the\n * failure mode of the alternative is a disclosure, and the failure mode of this one is a subject\n * retrying a read.\n */\n readonly ready: boolean;\n /** Whether `subject` may read `shapeKey` at `scope`. */\n permits(subject: string, shapeKey: string, scope: readonly PredicateValue[]): boolean;\n /**\n * Every scope of `shapeKey` that `subject` holds, each an ordered tuple matching the shape's\n * declared scope columns.\n *\n * This is what lets a client subscribe by shape alone (ADR-0055 decision 6): it names\n * `offering_content`, and the control plane answers with one stream per offering the subject can\n * actually read. The alternative — the client naming scopes — makes it restate something only this\n * set knows, so its every answer is either redundant or wrong.\n *\n * Enumeration and `permits` must agree: a scope returned here that `permits` would refuse is a\n * grant the edge then rejects on every read.\n */\n scopesFor(subject: string, shapeKey: string): readonly (readonly PredicateValue[])[];\n}\n\n/**\n * The entitlement set cannot be consulted right now — it is catching up, degraded, or stale.\n *\n * An OUTAGE, and thrown rather than reported per subscription for exactly the reason an engine fault\n * is: a client told \"not entitled\" clears that scope and unsubscribes (ADR-0055 decision 6), so\n * relaying an unavailable set as a denial would turn a transient control-plane condition into\n * client-side data loss. The routes map it to 503, which is a status a client retries through.\n *\n * The EDGE does not throw this. A read arriving while the set is unavailable is denied (see\n * {@link EntitlementSet.ready}) and a denied read is not a revocation — it is a request the client\n * makes again.\n */\nexport class EntitlementsUnavailableError extends Error {\n constructor() {\n super(\n \"[pgxsinkit] the entitlement set is unavailable — it is catching up, degraded or stale; \" +\n \"shared-tier subscriptions cannot be decided right now\",\n );\n this.name = \"EntitlementsUnavailableError\";\n }\n}\n\nexport interface StreamGateOptions {\n /** Verifies the stream token. Minted by the control plane in the same process. */\n key: CryptoKey;\n /**\n * The registry the granted shapes are declared in — REQUIRED, unlike every other option here.\n *\n * The gate needs it to answer one question per read: does this shape declare a\n * `serverProjection.rowTransform`, and must its bytes therefore be rewritten before they reach the\n * client (ADR-0055 decision 5)? A gate that cannot see the registry cannot know, so it would proxy\n * a transform shape's raw rows — including the `serverOnlyColumns` fetched solely for the transform\n * — with nothing anywhere reporting a discrepancy. Making it required is what makes that mount\n * impossible to write, which is why it is not optional \"for deployments with no transform shape\":\n * the leak arrives on the day someone adds the first one, in a file nobody was editing.\n */\n registry: SyncTableRegistry;\n /**\n * The live entitlement set backing the shared tier. Optional for the same reason it is optional on\n * the control plane: a deployment whose registry declares no shared shape has nothing to ask it.\n * Absent, a shared-tier grant is DENIED rather than waved through — the two sides then agree that\n * an unconfigured entitlement set can never permit.\n */\n entitlements?: EntitlementSet;\n /**\n * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the\n * same value the engine is given as `CIRCUITS_DS_URL`, since both address the same paths.\n */\n durableStreamsUrl: string;\n /**\n * Deployment-supplied runtime params, handed to an egress `rowTransform` as its context's `params`\n * — the same values `SubscribeOptions.params` hands to `rowFilter.customPredicate`. A deployment\n * that configures them on one side and not the other gives its registry two different runtime\n * environments for one shape, so mount both from the same source.\n */\n params?: Record<string, unknown>;\n /** Injected for tests; defaults to the ambient `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * What DECIDING one read needs: the signing key, plus the entitlement set the shared tier is checked\n * against.\n *\n * Spelled as the gate's options with everything else relaxed to optional, rather than as\n * {@link StreamGateOptions} itself, because a caller that wants only the decision — a mount that\n * proxies for itself, a test pinning the authorization rules — has no gate to configure, and\n * requiring it to invent a `registry` and a `durableStreamsUrl` would demand values the answer\n * provably does not depend on.\n */\nexport type StreamAuthorizationOptions = Pick<StreamGateOptions, \"key\" | \"entitlements\"> &\n Partial<Omit<StreamGateOptions, \"key\" | \"entitlements\">>;\n\nexport type GateDecision =\n | {\n allow: true;\n grant: StreamGrant;\n /**\n * The token's subject. Carried on the decision because the egress transform stage needs it and\n * re-verifying the token to recover it would pay for a second HMAC on every rewritten read —\n * the verification that established it already happened here.\n */\n subject: string;\n }\n | { allow: false; reason: string };\n\n/**\n * Authorize one read of one stream path.\n *\n * Two checks, and they are not redundant. The token is a capability bounded by its TTL, which is the\n * only bound available when a hit-serving CDN sits in front and the request never reaches us. The\n * entitlement lookup is live, and bounds revocation by propagation latency instead whenever the\n * request does reach us. Which one binds is a property of the deployment, not of this code.\n *\n * A private-tier grant has no scope to check, so the token is the whole authorization and its TTL is\n * the whole revocation bound. That is the same bound a CDN-fronted shared read has, and it is worth\n * stating rather than leaving to be inferred.\n */\nexport async function authorizeStreamRead(\n options: StreamAuthorizationOptions,\n token: string | null,\n path: string,\n now: number,\n): Promise<GateDecision> {\n if (token == null || token === \"\") return { allow: false, reason: \"no stream token\" };\n\n const verified = await verifyStreamToken(options.key, token, now);\n if (!verified.ok) return { allow: false, reason: verified.reason };\n\n const grant = findGrant(verified.claims, path);\n if (grant == null) return { allow: false, reason: \"token grants no such stream\" };\n\n const subject = verified.claims.sub;\n if (grant.scope === undefined) return { allow: true, grant, subject };\n\n const entitlements = options.entitlements;\n if (entitlements === undefined) {\n return { allow: false, reason: \"shared-tier grant, but this deployment configured no entitlement set\" };\n }\n if (!entitlements.ready) return { allow: false, reason: \"entitlements unavailable\" };\n if (!entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n return { allow: false, reason: \"not entitled to this scope\" };\n }\n return { allow: true, grant, subject };\n}\n\n/**\n * Read the stream token off a request.\n *\n * `Authorization`, never a query parameter, and this is a correctness condition rather than a\n * convention: the cache key is the URL, so a token in the URL gives every subscriber a distinct key\n * and destroys precisely the sharing the shared tier exists for. A cache must also be configured not\n * to vary on this header — which it can only do if the header is where the token is.\n */\nexport function readStreamToken(request: Request): string | null {\n const header = request.headers.get(\"authorization\");\n if (header == null) return null;\n const [scheme, value] = header.split(\" \");\n return scheme?.toLowerCase() === \"bearer\" && value ? value : null;\n}\n\n/**\n * The response headers a browser must be allowed to READ off a stream-edge response.\n *\n * CORS lets script see only a short safelist of response headers (`cache-control`, `content-language`,\n * `content-length`, `content-type`, `expires`, `last-modified`, `pragma`). Every header the\n * durable-streams protocol answers with is outside it, so a CROSS-ORIGIN reader sees NONE of them\n * unless the mount names them on `Access-Control-Expose-Headers`.\n *\n * Two generations of client read these. `@pgxsinkit/client`'s own reader (`READ_RESPONSE_HEADERS` in\n * its `circuits/long-poll.ts`, which a unit test holds to this list) steers by `Stream-Next-Offset`,\n * `Stream-Up-To-Date` (a presence check, which is why it is easy to miss), `Stream-Cursor` and\n * `Stream-Closed`. Stripped of them it cannot make progress and fails the read, loudly. Clients still\n * in the field on `@durable-streams/client` (0.2.x, which pgxsinkit read through until ADR-0065\n * decision 6) drive their whole read loop off the same four and also read `stream-sse-data-encoding`\n * (SSE payload decoding) and `etag` (the stream-metadata path). Stripped of them, that client never\n * learns an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which\n * presents as a hot loop of hundreds of requests per second per shape with no error raised anywhere.\n * Both floor their retry backoff on `Retry-After`; without it they fall back on their own schedule.\n *\n * `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are read by neither. They are named here\n * anyway because this list is a statement about the ds protocol's response namespace rather than about\n * which subset one client version happens to read today — exposing a header a response never carries\n * is inert, while omitting one that it does carry wedges the reader. The `Producer-*` headers are\n * deliberately absent: they belong to the write path, which does not come through this gate.\n *\n * EVERY mount of `createStreamGate` must put these on `Access-Control-Expose-Headers` of the ACTUAL\n * (non-preflight) response. The gate cannot do it itself — it forwards the upstream response's\n * headers (verbatim for an ordinary shape, minus the caching ones for a rewritten one), and an\n * exposure list is meaningless without the `Access-Control-Allow-Origin` decision that only the mount\n * owns.\n */\nexport const STREAM_READ_EXPOSED_HEADERS: readonly string[] = [\n \"stream-next-offset\",\n \"stream-up-to-date\",\n \"stream-cursor\",\n \"stream-closed\",\n \"stream-seq\",\n \"stream-ttl\",\n \"stream-expires-at\",\n \"stream-sse-data-encoding\",\n \"etag\",\n \"retry-after\",\n];\n\n/**\n * A durable-streams long-poll body as the transform stage handles it.\n *\n * Deliberately NOT `StreamEnvelope`: the gate is a proxy, and typing the body as the contract would\n * assert that the edge validates a wire form it only ever forwards. All it needs to know is that an\n * envelope may carry a `value` object — a delete envelope is key-only, so it has nothing to rewrite\n * and nothing to disclose.\n */\ninterface ProxiedEnvelope {\n value?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * The response headers a rewritten body may be answered with.\n *\n * `cache-control: private, no-store` is the governing invariant, not a precaution: a transform makes\n * the bytes a function of the SUBJECT, so nothing between this edge and the browser that requested\n * them may share or store them. `etag` goes for the same reason — an upstream validator describes the\n * bytes durable-streams holds, not the ones we just produced, and honouring it would let a\n * revalidation return another subject's rewrite. `content-length` and `content-encoding` describe a\n * body that no longer exists: the length changed under the rewrite, and `fetch` already decoded what\n * it handed us.\n *\n * Everything else is kept VERBATIM — every `stream-*` header and the content type. The client's whole\n * read loop drives off them (see {@link STREAM_READ_EXPOSED_HEADERS}); an edge that dropped\n * `stream-next-offset` while rewriting would present as a failed read (to a client still on\n * `@durable-streams/client`, a hot loop), not as a redaction bug.\n */\nfunction rewrittenEgressHeaders(upstream: Headers): Headers {\n const headers = new Headers(upstream);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.delete(\"etag\");\n headers.set(\"cache-control\", \"private, no-store\");\n return headers;\n}\n\n/** Whether this read asks for SSE framing, by either of the two ways the ds protocol expresses it. */\nfunction asksForSse(request: Request): boolean {\n return (\n new URL(request.url).searchParams.get(\"live\") === \"sse\" ||\n (request.headers.get(\"accept\") ?? \"\").includes(\"text/event-stream\")\n );\n}\n\n/**\n * The edge: gate, then proxy bytes — rewriting them only for the shapes that declare a rewrite.\n *\n * There is no per-read FILTERING here at all, and no per-read rewriting for shapes that declare none.\n * Predicates were resolved at shape creation, so what remains for almost every read is a decision and\n * a copy — which is why this can sit in the TypeScript control-plane process without CPU being the\n * axis that decides where it belongs.\n *\n * A shape that declares `serverProjection.rowTransform` is the one exception: it is rewritten HERE,\n * per request, with the subject taken from the stream token, and answered `private, no-store`. This\n * is the rewriting origin ADR-0055 decision 5 names, confined to the shapes that incur it — a\n * transform shape gives up CDN shareability and SSE framing, and every other shape gives up nothing.\n * The transform's `serverOnlyColumns` are fetched by the engine so the transform can read them and\n * are stripped here, after it runs, to the columns the client's local table declares.\n *\n * The claims a transform sees at the edge are `{ sub }` and nothing else: a stream token carries the\n * subject, not the JWT it was minted from, and re-deriving richer claims per read would put an auth\n * provider call on the read path this whole topology exists to keep off it. A transform that needs\n * more than the subject is therefore NOT expressible at egress — put the subject-dependent part in\n * the shape's private `rowFilter.customPredicate`, which is compiled at subscribe time from the full\n * verified claims.\n */\nexport function createStreamGate(options: StreamGateOptions) {\n const doFetch = options.fetch ?? fetch;\n const base = options.durableStreamsUrl.replace(/\\/+$/, \"\");\n\n return async function handleStreamRead(request: Request, path: string, now: number): Promise<Response> {\n const decision = await authorizeStreamRead(options, readStreamToken(request), path, now);\n if (!decision.allow) {\n return new Response(JSON.stringify({ error: decision.reason }), {\n status: 403,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Resolved by shapeKey, exactly as the control plane resolved it to create the shape, so the edge\n // and the control plane cannot disagree about which declaration governs this stream.\n const entry = resolveEntryByShapeKey(options.registry, decision.grant.shapeKey);\n const transform: RowTransform | undefined = entry?.serverProjection?.rowTransform;\n\n // Refused BEFORE the upstream fetch: the rewrite needs a whole JSON body per response, and SSE\n // delivers a frame stream instead. Parsing that would mean a second body parser for a mode no\n // pgxsinkit client uses, so the mode is declined rather than half-supported.\n if (transform != null && asksForSse(request)) {\n return new Response(\n JSON.stringify({ error: \"this shape is rewritten at egress and is served as JSON long-poll only\" }),\n { status: 406, headers: { \"content-type\": \"application/json\" } },\n );\n }\n\n // Forward the ds protocol's own query string untouched — offsets and the live flag are the\n // protocol's, not ours, and rewriting them is how a proxy ends up owning a contract it does not\n // define. The token does NOT travel on: durable-streams has no read authorization in any\n // implementation, so it would only be an unread secret sitting in another service's logs.\n const upstreamUrl = new URL(`${base}/${path}`);\n upstreamUrl.search = new URL(request.url).search;\n\n const forwarded = new Headers(request.headers);\n forwarded.delete(\"authorization\");\n forwarded.delete(\"host\");\n\n const init: RequestInit = { method: request.method, headers: forwarded, signal: request.signal };\n\n // A downstream that walks away mid-long-poll (a client's clean `stop()`/unsubscribe) aborts\n // `request.signal`, and the forwarded fetch rejects with an AbortError. That is the cancellation\n // working as designed, not a failure — but left to propagate it surfaced as a 500 plus a raw\n // DOMException in every consumer's error log, once per stream, at every clean shutdown. Nothing\n // is ever delivered on an aborted request, so answer the mount's await with 499 (client closed\n // request) and stay quiet. A rejection with the signal NOT aborted is a real failure and still\n // propagates.\n const upstreamFetch = async (): Promise<Response> => {\n try {\n return await doFetch(upstreamUrl, init);\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n };\n\n // The pass-through path hands back the upstream Response OBJECT, untouched. Not \"an equivalent\n // response\" — the same one, so a shape that declares no transform pays nothing for the existence\n // of this stage and keeps whatever caching headers durable-streams answered with.\n if (transform == null || entry == null) return upstreamFetch();\n\n const upstream = await upstreamFetch();\n if (upstream.status === 499) return upstream;\n const headers = rewrittenEgressHeaders(upstream.headers);\n\n // 204 long-poll timeouts, 304s, upstream errors, and HEAD probes: nothing to rewrite, but they\n // are still answers about a subject-dependent stream, so they leave with the same no-store,\n // no-etag posture. HEAD belongs here because it answers `application/json` with NO body — parsing\n // it would throw on a request that is only asking for the headers.\n if (\n request.method === \"HEAD\" ||\n upstream.status !== 200 ||\n !(upstream.headers.get(\"content-type\") ?? \"\").includes(\"application/json\")\n ) {\n return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });\n }\n\n // The body read can abort the same way the fetch can (the poll delivered headers, the client\n // left before the body finished) — same cancellation, same quiet answer.\n let parsed: unknown;\n try {\n parsed = (await upstream.json()) as unknown;\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n const isBatch = Array.isArray(parsed);\n const envelopes = (isBatch ? parsed : [parsed]) as ProxiedEnvelope[];\n\n // The client keep-set: the columns the LOCAL table declares, computed once per request. Stripping\n // to it after the transform runs is what keeps `serverOnlyColumns` — fetched by the engine solely\n // so the transform could read them — off the client wire, and it also drops any key a transform\n // invented, so an egress rewrite can never widen the shape the client's schema was built for.\n const keep = new Set(getTableConfig(entry.localTable).columns.map((column) => column.name));\n const context: RowTransformContext = {\n claims: { sub: decision.subject },\n ...(options.params ? { params: options.params } : {}),\n };\n\n const rewritten = envelopes.map((envelope) => {\n const value = envelope?.value;\n if (value == null || typeof value !== \"object\") return envelope;\n const transformed = transform(value as Record<string, unknown>, context);\n const stripped: Record<string, unknown> = {};\n for (const [column, cell] of Object.entries(transformed)) {\n if (keep.has(column)) stripped[column] = cell;\n }\n return { ...envelope, value: stripped };\n });\n\n // Answered in the shape it arrived in. A ds long-poll body is an array, and the single-object case\n // is only defensive — re-emitting it as an array would corrupt a body the client can parse today.\n return new Response(JSON.stringify(isBatch ? rewritten : rewritten[0]), {\n status: upstream.status,\n statusText: upstream.statusText,\n headers,\n });\n };\n}\n",
9
9
  "import type { PredicateValue } from \"@pgxsinkit/contracts\";\n\n/**\n * One stream a token admits its bearer to.\n *\n * The grant is **self-describing**: it carries the durable-streams path together with the shape and\n * scope that path serves. That is what keeps the edge stateless. Shape creation happened on whichever\n * replica the client reached, and the edge is replica-scaled, so a path→scope map held in memory\n * would have to be shared between replicas — a second piece of distributed state on the read path,\n * to answer a question the token can simply carry.\n */\nexport interface StreamGrant {\n /** The durable-streams path, e.g. `shape/s1`. */\n path: string;\n /** The shape this path serves — the entitlement rule's binding key. */\n shapeKey: string;\n /**\n * The engine claim this grant acquired — one `POST /shapes` join — so the session that holds it can\n * release exactly what it acquired.\n *\n * Carried rather than looked up, for the same reason the path and scope are: the release route is\n * stateless, and the signed token is the only proof of what the control plane handed out. It is not\n * the same thing as {@link StreamGrant.path}: the engine's own id is what `DELETE /shapes/{id}`\n * takes, and two grants can legitimately name ONE shapeId when the engine deduplicated two\n * identical definitions (ADR-0055 decision 6) — which is precisely why release counts grants, not\n * distinct ids.\n */\n shapeId: string;\n /**\n * The **subscription id** this grant's claim was taken under — the name the control plane gave it\n * on `POST /shapes` (fork ADR-0008).\n *\n * Carried for the same reason {@link StreamGrant.shapeId} is: renewal and release are stateless.\n * The re-mint renews this exact claim (the same create, repeated with this id) and the release\n * route drops this exact claim (`DELETE /shapes/{id}?subscription=…`) — both of them from the\n * signed token alone, with nothing remembered server-side. It is also what makes a release\n * idempotent: a claim named is a claim that can only be given back once, however many times the\n * request arrives.\n *\n * Distinct per grant even when two grants share a `shapeId`: two joins onto one deduplicated shape\n * are two claims, and one id could only ever release one of them.\n */\n claim: string;\n /**\n * Scope values, positionally matching the shape's declared scope columns. Shared tier only; a\n * private-tier grant has none, and its authorization is the token itself.\n */\n scope?: readonly PredicateValue[];\n /**\n * PRIVATE TIER ONLY: the fingerprint of the compiled shape request this grant authorized.\n *\n * A re-mint recompiles the shape with the subject's CURRENT claims and admits the grant only if the\n * result fingerprints the same; a grant without one cannot be re-authorized and is revoked. That is\n * what keeps the re-mint stateless — the token carries the thing that was authorized, so nothing\n * server-side has to remember it.\n *\n * Shared-tier grants carry none, and deliberately: their predicate is generated from the scope\n * values alone, so it cannot drift with the subject's claims and the live entitlement re-check is\n * the whole question.\n */\n fp?: string;\n}\n\n/** The verified body of a stream token. */\nexport interface StreamTokenClaims {\n /** The subject the token was minted for. */\n sub: string;\n grants: StreamGrant[];\n /** Issued-at and expiry, seconds since the epoch. */\n iat: number;\n exp: number;\n}\n\nexport interface MintStreamTokenOptions {\n sub: string;\n grants: readonly StreamGrant[];\n /**\n * Lifetime in seconds. The ADR-0055 default is 5 minutes, which is also the revocation bound when\n * a hit-serving third-party CDN sits in front: shorten it where that bound matters more than the\n * re-mint traffic, lengthen it where it does not.\n */\n ttlSeconds?: number;\n /** Seconds since the epoch. Injected so minting is testable and so a batch shares one issue time. */\n now: number;\n}\n\nexport const DEFAULT_STREAM_TOKEN_TTL_SECONDS = 300;\n\nexport type StreamTokenVerification = { ok: true; claims: StreamTokenClaims } | { ok: false; reason: string };\n\n/**\n * The signing key. HMAC-SHA256 over a compact JWS: the same process mints and verifies, so there is\n * one trust domain and no reason to pay for asymmetric keys — and no reason to take a JWT dependency\n * into a published library for what Web Crypto already does.\n *\n * The token still IS a JWT, so it stays readable by ordinary tooling when someone has to debug one.\n */\nexport async function importStreamTokenKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", new TextEncoder().encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n \"verify\",\n ]);\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...bytes))\n .replaceAll(\"+\", \"-\")\n .replaceAll(\"/\", \"_\")\n .replaceAll(\"=\", \"\");\n}\n\nfunction base64UrlDecode(value: string): Uint8Array<ArrayBuffer> {\n const padded = value\n .replaceAll(\"-\", \"+\")\n .replaceAll(\"_\", \"/\")\n .padEnd(Math.ceil(value.length / 4) * 4, \"=\");\n const binary = atob(padded);\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nconst HEADER = base64UrlEncode(new TextEncoder().encode(JSON.stringify({ alg: \"HS256\", typ: \"JWT\" })));\n\n/**\n * Mint one token for a whole batch of grants.\n *\n * Batched by design, not as an optimisation: a subject in K scopes holds K subscriptions, and\n * re-minting per subscription would put K requests on every TTL boundary for every subject. One\n * token covering all K collapses that to one request per subject per window.\n */\nexport async function mintStreamToken(key: CryptoKey, options: MintStreamTokenOptions): Promise<string> {\n const ttl = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n const claims: StreamTokenClaims = {\n sub: options.sub,\n grants: options.grants.map((grant) => ({\n path: grant.path,\n shapeKey: grant.shapeKey,\n shapeId: grant.shapeId,\n claim: grant.claim,\n ...(grant.scope !== undefined ? { scope: [...grant.scope] } : {}),\n ...(grant.fp !== undefined ? { fp: grant.fp } : {}),\n })),\n iat: options.now,\n exp: options.now + ttl,\n };\n\n const body = base64UrlEncode(new TextEncoder().encode(JSON.stringify(claims)));\n const signingInput = `${HEADER}.${body}`;\n const signature = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(signingInput));\n return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;\n}\n\n/**\n * Verify a token and read its grants back.\n *\n * `now` is the request-start time, and is passed rather than read here so that a long-poll held open\n * across the expiry is judged by when it started — the alternative silently kills connections\n * mid-flight at the TTL boundary, which presents as a stall rather than as the re-auth it is.\n *\n * Signature verification goes through `crypto.subtle.verify`, so the comparison is the platform's\n * constant-time one rather than a string equality that leaks by how early it diverges.\n */\nexport interface VerifyStreamTokenOptions {\n /**\n * Accept a token past its expiry, for the **re-mint path only**.\n *\n * The signature is still verified, so the grants are still ones this control plane issued — that is\n * the whole claim being relied on. Expiry bounds how long a grant keeps *working*, and the re-mint\n * re-authorizes every grant before re-signing — the shared tier against the live entitlement set,\n * the private tier by recompiling its shape against the subject's current claims — so an expired\n * token buys its bearer nothing on its own. Never set this on a read.\n */\n allowExpired?: boolean;\n}\n\nexport async function verifyStreamToken(\n key: CryptoKey,\n token: string,\n now: number,\n options?: VerifyStreamTokenOptions,\n): Promise<StreamTokenVerification> {\n const parts = token.split(\".\");\n if (parts.length !== 3) return { ok: false, reason: \"malformed token\" };\n const [header, body, signature] = parts as [string, string, string];\n if (header !== HEADER) return { ok: false, reason: \"unexpected token header\" };\n\n let valid: boolean;\n try {\n valid = await crypto.subtle.verify(\n \"HMAC\",\n key,\n base64UrlDecode(signature),\n new TextEncoder().encode(`${header}.${body}`),\n );\n } catch {\n return { ok: false, reason: \"malformed signature\" };\n }\n if (!valid) return { ok: false, reason: \"bad signature\" };\n\n let claims: StreamTokenClaims;\n try {\n claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(body))) as StreamTokenClaims;\n } catch {\n return { ok: false, reason: \"malformed payload\" };\n }\n if (typeof claims.sub !== \"string\" || !Array.isArray(claims.grants) || typeof claims.exp !== \"number\") {\n return { ok: false, reason: \"malformed payload\" };\n }\n if (claims.exp <= now && options?.allowExpired !== true) return { ok: false, reason: \"expired\" };\n\n return { ok: true, claims };\n}\n\n/**\n * The grant covering a requested stream path, if the token carries one.\n *\n * Exact path match, deliberately: durable-streams paths are a monotonic counter (`shape/s1`,\n * `shape/s2`, …), so they are enumerable rather than capability-bearing, and any prefix or pattern\n * match over them would hand the bearer streams the control plane never granted.\n */\nexport function findGrant(claims: StreamTokenClaims, path: string): StreamGrant | undefined {\n return claims.grants.find((grant) => grant.path === path);\n}\n",
10
10
  "import type { CircuitsShapeHandle, CreateShapeRequest } from \"./wire\";\n\nexport interface CircuitsEngineOptions {\n /** Base URL of the Circuits engine's control API, e.g. `http://circuits-engine:4000`. */\n baseUrl: string;\n /** Injected for tests; defaults to the ambient `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * An engine call that did not return 2xx, carrying the status so a caller can map it to its own.\n *\n * The one status with a MEANING rather than a severity is **409**: a create whose `subscription` id\n * is already held by a different shape (fork ADR-0008 — one name, one shape). It is the caller's\n * conflict, not an outage, and no retry changes it; match it as `error.status === 409` and re-subscribe\n * under a fresh id. Everything else is either a request this client built wrong (4xx) or an engine\n * that could not answer (5xx), and both propagate as a 503 to the client.\n */\nexport class CircuitsEngineError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string, message: string) {\n super(message);\n this.name = \"CircuitsEngineError\";\n this.status = status;\n this.body = body;\n }\n}\n\n/**\n * The control plane's client for the Circuits engine.\n *\n * Only the shape LIFECYCLE goes through here. Reads never do: they terminate on durable-streams,\n * which is the whole point of the native topology — the engine is asked once, at subscribe time,\n * for a stream to follow, and is then out of the read path entirely.\n */\nexport function createCircuitsEngineClient(options: CircuitsEngineOptions) {\n const doFetch = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n\n async function call(path: string, init: RequestInit): Promise<unknown> {\n const headers = new Headers(init.headers);\n headers.set(\"content-type\", \"application/json\");\n const response = await doFetch(`${base}${path}`, { ...init, headers });\n const body = await response.text();\n if (!response.ok) {\n throw new CircuitsEngineError(\n response.status,\n body,\n `[pgxsinkit] circuits engine ${init.method ?? \"GET\"} ${path} → ${response.status}: ${body}`,\n );\n }\n return body === \"\" ? undefined : JSON.parse(body);\n }\n\n return {\n /**\n * Register a shape and get the stream to follow — **and renew that registration**.\n *\n * There is deliberately no `renewShape`: a renewal IS this call, repeated with the same\n * `request.subscription` on the same definition (fork ADR-0008). The engine answers the same\n * handle, counts nothing extra, and moves the lease forward. That is also why a create whose\n * response was lost can simply be sent again, and why the control plane's token re-mint can renew\n * every live claim without a second route.\n *\n * Two outcomes a caller must distinguish:\n * - **409** ({@link CircuitsEngineError.status}) — the id names a DIFFERENT shape already. One\n * name, one shape; nothing was taken, and a retry will not change it.\n * - a **different handle** — the claim had lapsed or the shape was evicted, so this call\n * re-subscribed rather than renewed. The stream the old grant named is not this one (ADR-0007).\n *\n * The engine shares by definition: two identical bodies collapse onto one maintained stream and\n * return the same handle. Nothing here has to check for that or cache against it — which is\n * exactly why the shared tier's predicate must be GENERATED. Two subscribers in one scope produce\n * identical bodies only because neither's identity reached the predicate; they are still two\n * distinct subscriptions, because each names its own claim.\n *\n * The answer is VALIDATED, not cast, for the same reason {@link replicationState} validates the\n * barrier: an engine that acknowledges a create without saying which subscription it recorded or\n * how long that subscription lives cannot be renewed or released by id at all, and defaulting\n * either field would invent a lease this control plane was never promised.\n */\n async createShape(request: CreateShapeRequest): Promise<CircuitsShapeHandle> {\n const body = (await call(\"/shapes\", {\n method: \"POST\",\n body: JSON.stringify(request),\n })) as Partial<CircuitsShapeHandle> | null;\n if (body === null || typeof body !== \"object\") throw unusableCreate(\"the body\", body);\n if (typeof body.shapeId !== \"string\") throw unusableCreate(\"shapeId\", body.shapeId);\n if (typeof body.streamPath !== \"string\") throw unusableCreate(\"streamPath\", body.streamPath);\n if (typeof body.subscription !== \"string\" || body.subscription === \"\") {\n throw unusableCreate(\"subscription\", body.subscription);\n }\n if (typeof body.leaseSeconds !== \"number\") throw unusableCreate(\"leaseSeconds\", body.leaseSeconds);\n return body as CircuitsShapeHandle;\n },\n\n /**\n * Release ONE named subscription's claim on a shape (`DELETE /shapes/{id}?subscription=…`).\n *\n * **Idempotent**, and that is the whole point of naming the claim: releasing one that is already\n * gone is a no-op `200` rather than a decrement that steals another subscriber's. A caller whose\n * response was lost may simply send it again.\n *\n * There is no anonymous form here. The engine still accepts a bare `DELETE /shapes/{id}` as a\n * legacy refcount decrement, but it carries no claim identity and is not retry-safe, so this\n * client never issues one.\n *\n * The shape itself survives its other subscribers and then follows the engine's retention\n * lifecycle (idle → dormant → evicted); this is a release, not a delete.\n */\n async releaseShape(shapeId: string, subscription: string): Promise<void> {\n const query = `?subscription=${encodeURIComponent(subscription)}`;\n await call(`/shapes/${encodeURIComponent(shapeId)}${query}`, { method: \"DELETE\" });\n },\n\n /**\n * The engine's convergence barrier (ADR-0056): where replication is, how many\n * computed-but-undelivered subquery flips remain, and how many flip batches the engine gave up\n * on.\n *\n * The engine answers a `sync` field beside these and it is deliberately NOT read: it is the\n * `__el_sync` sentinel watermark — an i64 the engine's conformance harness bumps and waits on as\n * a global quiescence fence — which no pgxsinkit database ever writes, so it is 0 everywhere and\n * says nothing about convergence.\n *\n * `pendingFlips > 0` means a revocation has been computed and not yet written to any stream,\n * which no wire-format watermark can see. That is the term the Electric wire could not express\n * at all, and the reason the barrier is read out of band rather than inferred from a position.\n *\n * `flipFailures > 0` means a batch was **abandoned** after exhausting its propagation retries:\n * those membership effects are gone rather than late. The engine keeps the abandoned batch's\n * `pendingFlips` count held — so the waiting terms never falsely read converged — and latches\n * itself degraded: `/ready` answers 503, so do its membership-bearing routes, and a reaper\n * deletes every subquery shape stream. Recovery is an operator restart.\n *\n * The answer is VALIDATED, not cast. An engine that does not report both counters cannot answer\n * the question this barrier asks, and defaulting a missing term to zero would manufacture a\n * converged reading out of an engine that never claimed one.\n */\n async replicationState(): Promise<CircuitsReplicationState> {\n const body = (await call(\"/replication/lsn\", { method: \"GET\" })) as Partial<CircuitsReplicationState>;\n if (body === null || typeof body !== \"object\") throw unusableBarrier(\"the body\", body);\n if (body.lsn !== null && typeof body.lsn !== \"string\") throw unusableBarrier(\"lsn\", body.lsn);\n if (typeof body.pendingFlips !== \"number\") throw unusableBarrier(\"pendingFlips\", body.pendingFlips);\n if (typeof body.flipFailures !== \"number\") throw unusableBarrier(\"flipFailures\", body.flipFailures);\n return { lsn: body.lsn, pendingFlips: body.pendingFlips, flipFailures: body.flipFailures };\n },\n };\n}\n\n/**\n * An engine whose barrier this client cannot read is not a degraded engine — it is the wrong engine,\n * and saying so is the point. Silently tolerating the omission would leave a gate claiming to check a\n * term nothing reports.\n */\nfunction unusableBarrier(field: string, value: unknown): Error {\n return new Error(\n `[pgxsinkit] the engine's GET /replication/lsn answered with an unusable \\`${field}\\` (${JSON.stringify(value)}). ` +\n `This client requires an engine reporting the whole convergence barrier — \\`lsn\\`, \\`pendingFlips\\` and ` +\n `\\`flipFailures\\` (ADR-0056 decision 3); the engine at this URL is not the one this client targets.`,\n );\n}\n\n/**\n * An engine whose create answer this client cannot read is not a degraded engine — it is the wrong\n * engine, exactly as {@link unusableBarrier} says of the barrier. A create that does not name the\n * subscription it was recorded under, or the window that subscription must be renewed within, leaves\n * a claim nothing can renew and nothing can release by id; defaulting either would manufacture a\n * lease the engine never granted.\n */\nfunction unusableCreate(field: string, value: unknown): Error {\n return new Error(\n `[pgxsinkit] the engine's POST /shapes answered with an unusable \\`${field}\\` (${JSON.stringify(value)}). ` +\n `This client requires an engine that records every shape claim under a named, leased subscription — ` +\n `\\`shapeId\\`, \\`streamPath\\`, \\`subscription\\` and \\`leaseSeconds\\` (fork ADR-0008); the engine at this ` +\n `URL is not the one this client targets.`,\n );\n}\n\nexport type CircuitsEngineClient = ReturnType<typeof createCircuitsEngineClient>;\n\n/** What `GET /replication/lsn` answers that this client reads — these fields exactly, no more. */\nexport interface CircuitsReplicationState {\n /** The ingest head — where the replication tailer has read to. */\n lsn: string | null;\n pendingFlips: number;\n /**\n * Flip batches the engine abandoned after exhausting their retries. Non-zero means membership\n * effects were **lost**, not delayed: the batch's pending count stays held, the engine is latched\n * degraded, and only a restart clears it.\n */\n flipFailures: number;\n}\n",
11
- "import { sql } from \"drizzle-orm\";\n\nimport { eventQueueMessageSchema, type EventQueueMessage } from \"@pgxsinkit/contracts\";\n\nimport {\n assertEventQueueReceipts,\n eventStreamQueueName,\n MalformedEventQueueMessageError,\n type DeadLetteredEventMessage,\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueExecutor,\n type EventQueueReadOptions,\n type EventQueueReceipt,\n} from \"./queue\";\n\n/**\n * The shipped {@link EventQueue} backend: **pgmq** (ADR-0053 decision 5). Postgres-native, so the Event lane\n * adds no new infrastructure to the supabase-ecosystem stacks consumers already run, and an enqueue joins the\n * endpoint's own transaction rather than crossing a second system.\n *\n * One queue per Event stream (`pgxsinkit_events_<stream>`), so a poison event or a slow consumer in one stream\n * can never head-of-line-block another. Queues are provisioned at DEPLOY time (`pgxsinkit-generate --events`),\n * never created at runtime: the endpoint may enqueue long before any runner first starts, and a\n * create-if-missing probe would put a query back in front of the zero-startup-query posture.\n *\n * **pgmq assumptions**, all read off pgmq's own extension SQL and pinned by the integration lane:\n * - The extension is NOT relocatable and its control file declares `schema = 'pgmq'`, so every call is\n * `pgmq.`-qualified and the schema is never configurable here.\n * - Its control file declares no `requires`, so the DDL needs no `CASCADE` (pg_partman is needed only for\n * PARTITIONED queues, which the toolkit never creates).\n * - Per-queue tables are `pgmq.q_<queue>` and `pgmq.a_<queue>` (`pgmq.format_table_name`); the archive is the\n * dead-letter storage.\n *\n * SQL tier discipline: pgmq's surface IS a set of SQL functions and two dynamically-named tables, so Drizzle's\n * tier-1 builders cannot express any of it. Everything below is tier 2 — a tagged `sql` template with the\n * queue name and every value as BOUND PARAMETERS and each table name as a typed `sql.identifier`; no\n * identifier or value is ever baked into the template text.\n */\n\n/**\n * The reserved key the dead-letter reason is stamped under, INSIDE the archived message body.\n *\n * Least surface, deliberately: pgmq's archive is the dead-letter storage (no library-owned DLQ table), the\n * archive row has no free column to carry a reason, and its `headers` column only exists on newer pgmq\n * versions. So the reason rides one reserved key on the ARCHIVED body — the live queue row is never mutated,\n * a normally-consumed message is byte-identical to what was enqueued, and the key is stripped again by\n * {@link EventQueue.listDeadLetters} / {@link EventQueue.requeueDeadLetter} so a requeued message is exactly\n * the message that was enqueued.\n */\nexport const PGMQ_DEAD_LETTER_KEY = \"__pgxsinkitDeadLetter\";\n\nexport interface CreatePgmqEventQueueOptions {\n /** The default executor — the server's drizzle handle. Per-call executors (a transaction) take precedence. */\n db: EventQueueExecutor;\n}\n\ninterface DeliveredRow {\n receipt: string;\n deliveryCount: number;\n enqueuedAtUs: string;\n message: string;\n}\n\ninterface DeadLetterRow {\n id: string;\n deliveryCount: number;\n deadLetteredAtUs: string;\n message: string;\n reason: string | null;\n}\n\ninterface CountRow {\n affected: number;\n}\n\ninterface ReceiptRow {\n receipt: string | null;\n}\n\nfunction toRows<TRow>(result: unknown): TRow[] {\n return Array.from(result as Iterable<unknown>, (row) => row as TRow);\n}\n\n/** Parse a queue body back into the contract shape, naming the offending receipt if it is not one. */\nfunction parseQueueMessage(stream: string, receipt: EventQueueReceipt, body: string): EventQueueMessage {\n let raw: unknown;\n try {\n raw = JSON.parse(body);\n } catch (error) {\n throw new MalformedEventQueueMessageError(stream, receipt, error instanceof Error ? error.message : \"invalid JSON\");\n }\n const parsed = eventQueueMessageSchema.safeParse(raw);\n if (!parsed.success) {\n throw new MalformedEventQueueMessageError(stream, receipt, parsed.error.message);\n }\n return parsed.data;\n}\n\nexport function createPgmqEventQueue(options: CreatePgmqEventQueueOptions): EventQueue {\n const run = (executor: EventQueueExecutor | undefined, query: Parameters<EventQueueExecutor[\"execute\"]>[0]) =>\n (executor ?? options.db).execute(query);\n\n return {\n enqueueBatch: async (messages, executor) => {\n if (messages.length === 0) {\n return;\n }\n\n // Group by Event stream, preserving the order the endpoint assembled: one `send_batch` per stream, all\n // inside the CALLER's transaction, so a mixed flush batch is enqueued atomically or not at all.\n const byStream = new Map<string, EventQueueMessage[]>();\n for (const message of messages) {\n const bucket = byStream.get(message.stream);\n if (bucket) {\n bucket.push(message);\n } else {\n byStream.set(message.stream, [message]);\n }\n }\n\n for (const [stream, streamMessages] of byStream) {\n const queueName = eventStreamQueueName(stream);\n // The bodies ride as ONE bound json parameter expanded to `jsonb[]` in SQL — never a driver-specific\n // array binding, and never string-built SQL.\n await run(\n executor,\n sql`SELECT pgmq.send_batch(${queueName}, ARRAY(SELECT jsonb_array_elements(${JSON.stringify(streamMessages)}::text::jsonb)))`,\n );\n }\n },\n\n readBatch: async (stream: string, readOptions: EventQueueReadOptions): Promise<DeliveredEventMessage[]> => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT \"msg_id\"::text AS \"receipt\", \"read_ct\" AS \"deliveryCount\", (EXTRACT(EPOCH FROM \"enqueued_at\") * 1000000)::bigint::text AS \"enqueuedAtUs\", \"message\"::text AS \"message\" FROM pgmq.read(${queueName}, ${readOptions.visibilityTimeoutSeconds}, ${readOptions.maxMessages})`,\n );\n\n return toRows<DeliveredRow>(result).map((row) => ({\n receipt: row.receipt,\n stream,\n message: parseQueueMessage(stream, row.receipt, row.message),\n deliveryCount: Number(row.deliveryCount),\n enqueuedAtUs: row.enqueuedAtUs,\n }));\n },\n\n extendVisibility: async (stream, receipts, visibilityTimeoutSeconds, executor) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n // pgmq gained an ARRAY-taking `set_vt` only in 1.8.0, while the single-message form has existed\n // throughout — and the toolkit pins no pgmq version. So the portable shape is the single-message\n // function applied over the receipts with a LATERAL: still ONE statement and one round trip, but it\n // works on every pgmq a consumer's supabase-ecosystem stack might carry. The `::int` cast picks the\n // seconds-offset overload over the `timestamptz` one.\n const result = await run(\n executor,\n sql`SELECT count(*)::int AS \"affected\" FROM unnest(string_to_array(${receipts.join(\",\")}, ',')::bigint[]) AS \"renewed\"(\"msg_id\"), LATERAL pgmq.set_vt(${queueName}, \"renewed\".\"msg_id\", ${visibilityTimeoutSeconds}::int) AS \"extended\"`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n ack: async (stream, receipts) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.delete(${queueName}, string_to_array(${receipts.join(\",\")}, ',')::bigint[])`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n deadLetter: async (stream, receipts, reason) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const ids = receipts.join(\",\");\n\n // pgmq's own archive move first — it is the version-correct transfer (it carries every column the\n // installed pgmq version has, including ones this code does not know about).\n const archived = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.archive(${queueName}, string_to_array(${ids}, ',')::bigint[])`,\n );\n\n // Then stamp the reason onto the ARCHIVED body. Deliberately second: if it fails the message is still\n // dead-lettered (the fail-safe direction), and the archived row is terminal so nothing races this.\n await run(\n undefined,\n sql`UPDATE pgmq.${sql.identifier(`a_${queueName}`)} SET \"message\" = COALESCE(\"message\", '{}'::jsonb) || jsonb_build_object(${PGMQ_DEAD_LETTER_KEY}::text, jsonb_build_object('reason', ${reason}::text, 'atUs', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000000)::bigint::text)) WHERE \"msg_id\" = ANY(string_to_array(${ids}, ',')::bigint[])`,\n );\n\n return Number(toRows<CountRow>(archived)[0]?.affected ?? 0);\n },\n\n listDeadLetters: async (stream, limit) => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT \"msg_id\"::text AS \"id\", \"read_ct\" AS \"deliveryCount\", (EXTRACT(EPOCH FROM \"archived_at\") * 1000000)::bigint::text AS \"deadLetteredAtUs\", (\"message\" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS \"message\", \"message\" -> ${PGMQ_DEAD_LETTER_KEY}::text ->> 'reason' AS \"reason\" FROM pgmq.${sql.identifier(`a_${queueName}`)} ORDER BY \"msg_id\" DESC LIMIT ${limit}`,\n );\n\n return toRows<DeadLetterRow>(result).map((row): DeadLetteredEventMessage => {\n const message = parseQueueMessage(stream, row.id, row.message);\n return {\n id: row.id,\n stream,\n message,\n ...(row.reason != null ? { reason: row.reason } : {}),\n deliveryCount: Number(row.deliveryCount),\n deadLetteredAtUs: row.deadLetteredAtUs,\n };\n });\n },\n\n requeueDeadLetter: async (stream, id) => {\n assertEventQueueReceipts([id]);\n const queueName = eventStreamQueueName(stream);\n // ONE statement: the archive row is removed and its (reason-stripped) body re-sent in the same command,\n // so a requeue can never leave the message both dead-lettered and queued.\n const result = await run(\n undefined,\n sql`WITH restored AS (DELETE FROM pgmq.${sql.identifier(`a_${queueName}`)} WHERE \"msg_id\" = ${id}::bigint RETURNING \"message\") SELECT pgmq.send(${queueName}, \"message\" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS \"receipt\" FROM restored`,\n );\n return toRows<ReceiptRow>(result)[0]?.receipt ?? null;\n },\n };\n}\n",
11
+ "import { sql } from \"drizzle-orm\";\n\nimport { type EventQueueMessage, eventQueueMessageSchema } from \"@pgxsinkit/contracts\";\n\nimport {\n assertEventQueueReceipts,\n type DeadLetteredEventMessage,\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueExecutor,\n type EventQueueReadOptions,\n type EventQueueReceipt,\n eventStreamQueueName,\n MalformedEventQueueMessageError,\n} from \"./queue\";\n\n/**\n * The shipped {@link EventQueue} backend: **pgmq** (ADR-0053 decision 5). Postgres-native, so the Event lane\n * adds no new infrastructure to the supabase-ecosystem stacks consumers already run, and an enqueue joins the\n * endpoint's own transaction rather than crossing a second system.\n *\n * One queue per Event stream (`pgxsinkit_events_<stream>`), so a poison event or a slow consumer in one stream\n * can never head-of-line-block another. Queues are provisioned at DEPLOY time (`pgxsinkit-generate --events`),\n * never created at runtime: the endpoint may enqueue long before any runner first starts, and a\n * create-if-missing probe would put a query back in front of the zero-startup-query posture.\n *\n * **pgmq assumptions**, all read off pgmq's own extension SQL and pinned by the integration lane:\n * - The extension is NOT relocatable and its control file declares `schema = 'pgmq'`, so every call is\n * `pgmq.`-qualified and the schema is never configurable here.\n * - Its control file declares no `requires`, so the DDL needs no `CASCADE` (pg_partman is needed only for\n * PARTITIONED queues, which the toolkit never creates).\n * - Per-queue tables are `pgmq.q_<queue>` and `pgmq.a_<queue>` (`pgmq.format_table_name`); the archive is the\n * dead-letter storage.\n *\n * SQL tier discipline: pgmq's surface IS a set of SQL functions and two dynamically-named tables, so Drizzle's\n * tier-1 builders cannot express any of it. Everything below is tier 2 — a tagged `sql` template with the\n * queue name and every value as BOUND PARAMETERS and each table name as a typed `sql.identifier`; no\n * identifier or value is ever baked into the template text.\n */\n\n/**\n * The reserved key the dead-letter reason is stamped under, INSIDE the archived message body.\n *\n * Least surface, deliberately: pgmq's archive is the dead-letter storage (no library-owned DLQ table), the\n * archive row has no free column to carry a reason, and its `headers` column only exists on newer pgmq\n * versions. So the reason rides one reserved key on the ARCHIVED body — the live queue row is never mutated,\n * a normally-consumed message is byte-identical to what was enqueued, and the key is stripped again by\n * {@link EventQueue.listDeadLetters} / {@link EventQueue.requeueDeadLetter} so a requeued message is exactly\n * the message that was enqueued.\n */\nexport const PGMQ_DEAD_LETTER_KEY = \"__pgxsinkitDeadLetter\";\n\nexport interface CreatePgmqEventQueueOptions {\n /** The default executor — the server's drizzle handle. Per-call executors (a transaction) take precedence. */\n db: EventQueueExecutor;\n}\n\ninterface DeliveredRow {\n receipt: string;\n deliveryCount: number;\n enqueuedAtUs: string;\n message: string;\n}\n\ninterface DeadLetterRow {\n id: string;\n deliveryCount: number;\n deadLetteredAtUs: string;\n message: string;\n reason: string | null;\n}\n\ninterface CountRow {\n affected: number;\n}\n\ninterface ReceiptRow {\n receipt: string | null;\n}\n\nfunction toRows<TRow>(result: unknown): TRow[] {\n return Array.from(result as Iterable<unknown>, (row) => row as TRow);\n}\n\n/** Parse a queue body back into the contract shape, naming the offending receipt if it is not one. */\nfunction parseQueueMessage(stream: string, receipt: EventQueueReceipt, body: string): EventQueueMessage {\n let raw: unknown;\n try {\n raw = JSON.parse(body);\n } catch (error) {\n throw new MalformedEventQueueMessageError(stream, receipt, error instanceof Error ? error.message : \"invalid JSON\");\n }\n const parsed = eventQueueMessageSchema.safeParse(raw);\n if (!parsed.success) {\n throw new MalformedEventQueueMessageError(stream, receipt, parsed.error.message);\n }\n return parsed.data;\n}\n\nexport function createPgmqEventQueue(options: CreatePgmqEventQueueOptions): EventQueue {\n const run = (executor: EventQueueExecutor | undefined, query: Parameters<EventQueueExecutor[\"execute\"]>[0]) =>\n (executor ?? options.db).execute(query);\n\n return {\n enqueueBatch: async (messages, executor) => {\n if (messages.length === 0) {\n return;\n }\n\n // Group by Event stream, preserving the order the endpoint assembled: one `send_batch` per stream, all\n // inside the CALLER's transaction, so a mixed flush batch is enqueued atomically or not at all.\n const byStream = new Map<string, EventQueueMessage[]>();\n for (const message of messages) {\n const bucket = byStream.get(message.stream);\n if (bucket) {\n bucket.push(message);\n } else {\n byStream.set(message.stream, [message]);\n }\n }\n\n for (const [stream, streamMessages] of byStream) {\n const queueName = eventStreamQueueName(stream);\n // The bodies ride as ONE bound json parameter expanded to `jsonb[]` in SQL — never a driver-specific\n // array binding, and never string-built SQL.\n await run(\n executor,\n sql`SELECT pgmq.send_batch(${queueName}, ARRAY(SELECT jsonb_array_elements(${JSON.stringify(streamMessages)}::text::jsonb)))`,\n );\n }\n },\n\n readBatch: async (stream: string, readOptions: EventQueueReadOptions): Promise<DeliveredEventMessage[]> => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT \"msg_id\"::text AS \"receipt\", \"read_ct\" AS \"deliveryCount\", (EXTRACT(EPOCH FROM \"enqueued_at\") * 1000000)::bigint::text AS \"enqueuedAtUs\", \"message\"::text AS \"message\" FROM pgmq.read(${queueName}, ${readOptions.visibilityTimeoutSeconds}, ${readOptions.maxMessages})`,\n );\n\n return toRows<DeliveredRow>(result).map((row) => ({\n receipt: row.receipt,\n stream,\n message: parseQueueMessage(stream, row.receipt, row.message),\n deliveryCount: Number(row.deliveryCount),\n enqueuedAtUs: row.enqueuedAtUs,\n }));\n },\n\n extendVisibility: async (stream, receipts, visibilityTimeoutSeconds, executor) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n // pgmq gained an ARRAY-taking `set_vt` only in 1.8.0, while the single-message form has existed\n // throughout — and the toolkit pins no pgmq version. So the portable shape is the single-message\n // function applied over the receipts with a LATERAL: still ONE statement and one round trip, but it\n // works on every pgmq a consumer's supabase-ecosystem stack might carry. The `::int` cast picks the\n // seconds-offset overload over the `timestamptz` one.\n const result = await run(\n executor,\n sql`SELECT count(*)::int AS \"affected\" FROM unnest(string_to_array(${receipts.join(\",\")}, ',')::bigint[]) AS \"renewed\"(\"msg_id\"), LATERAL pgmq.set_vt(${queueName}, \"renewed\".\"msg_id\", ${visibilityTimeoutSeconds}::int) AS \"extended\"`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n ack: async (stream, receipts) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.delete(${queueName}, string_to_array(${receipts.join(\",\")}, ',')::bigint[])`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n deadLetter: async (stream, receipts, reason) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const ids = receipts.join(\",\");\n\n // pgmq's own archive move first — it is the version-correct transfer (it carries every column the\n // installed pgmq version has, including ones this code does not know about).\n const archived = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.archive(${queueName}, string_to_array(${ids}, ',')::bigint[])`,\n );\n\n // Then stamp the reason onto the ARCHIVED body. Deliberately second: if it fails the message is still\n // dead-lettered (the fail-safe direction), and the archived row is terminal so nothing races this.\n await run(\n undefined,\n sql`UPDATE pgmq.${sql.identifier(`a_${queueName}`)} SET \"message\" = COALESCE(\"message\", '{}'::jsonb) || jsonb_build_object(${PGMQ_DEAD_LETTER_KEY}::text, jsonb_build_object('reason', ${reason}::text, 'atUs', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000000)::bigint::text)) WHERE \"msg_id\" = ANY(string_to_array(${ids}, ',')::bigint[])`,\n );\n\n return Number(toRows<CountRow>(archived)[0]?.affected ?? 0);\n },\n\n listDeadLetters: async (stream, limit) => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT \"msg_id\"::text AS \"id\", \"read_ct\" AS \"deliveryCount\", (EXTRACT(EPOCH FROM \"archived_at\") * 1000000)::bigint::text AS \"deadLetteredAtUs\", (\"message\" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS \"message\", \"message\" -> ${PGMQ_DEAD_LETTER_KEY}::text ->> 'reason' AS \"reason\" FROM pgmq.${sql.identifier(`a_${queueName}`)} ORDER BY \"msg_id\" DESC LIMIT ${limit}`,\n );\n\n return toRows<DeadLetterRow>(result).map((row): DeadLetteredEventMessage => {\n const message = parseQueueMessage(stream, row.id, row.message);\n return {\n id: row.id,\n stream,\n message,\n ...(row.reason != null ? { reason: row.reason } : {}),\n deliveryCount: Number(row.deliveryCount),\n deadLetteredAtUs: row.deadLetteredAtUs,\n };\n });\n },\n\n requeueDeadLetter: async (stream, id) => {\n assertEventQueueReceipts([id]);\n const queueName = eventStreamQueueName(stream);\n // ONE statement: the archive row is removed and its (reason-stripped) body re-sent in the same command,\n // so a requeue can never leave the message both dead-lettered and queued.\n const result = await run(\n undefined,\n sql`WITH restored AS (DELETE FROM pgmq.${sql.identifier(`a_${queueName}`)} WHERE \"msg_id\" = ${id}::bigint RETURNING \"message\") SELECT pgmq.send(${queueName}, \"message\" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS \"receipt\" FROM restored`,\n );\n return toRows<ReceiptRow>(result)[0]?.receipt ?? null;\n },\n };\n}\n",
12
12
  "import type { SQL } from \"drizzle-orm\";\n\nimport {\n EVENT_STREAM_NAME_MAX_LENGTH,\n EVENT_STREAM_NAME_PATTERN,\n EVENT_STREAM_QUEUE_PREFIX,\n type EventQueueMessage,\n} from \"@pgxsinkit/contracts\";\n\n/**\n * The **Event lane**'s queue seam (ADR-0053 decision 5): a narrow, backend-agnostic interface over\n * \"enqueue a batch / consume with a visibility timeout / ack / dead-letter (+ enumerate and requeue)\".\n *\n * It is deliberately MECHANICS ONLY — there is no loop, no polling cadence, no wake policy and no\n * retry/backoff here. Those are the consumer runner's internals (ADR-0053 decision 7) and stay out of the\n * seam so a backend swap can never change pacing, and so the ingestion endpoint depends on nothing but\n * `enqueueBatch`.\n *\n * The interface, not the storage, is the contract: dead-letter STORAGE is backend-defined (the shipped pgmq\n * backend uses pgmq's own per-queue archive rather than a library-owned DLQ table), and v1 ships one backend.\n */\n\n/**\n * The minimal SQL seam a backend executes through — satisfied by a drizzle `PgAsyncDatabase` AND by the\n * transaction handle its `transaction()` callback receives. The ingestion endpoint enqueues INSIDE its own\n * transaction (a batch is enqueued atomically or the request fails retryably), so every mutating method\n * takes an optional executor rather than owning a connection.\n */\nexport interface EventQueueExecutor {\n execute: (query: SQL) => Promise<unknown>;\n}\n\n/**\n * An opaque handle for one delivered message, used to ack or dead-letter it. Backend-defined (pgmq: the\n * `msg_id` as a decimal string) — never parsed or ordered by callers.\n */\nexport type EventQueueReceipt = string;\n\nexport interface EventQueueReadOptions {\n /**\n * How long a delivered message stays invisible to other consumers, in seconds. The runner renews or lets\n * it lapse; the queue seam only applies what it is given.\n */\n visibilityTimeoutSeconds: number;\n /** At most this many messages (each message is one single-stream sub-batch). */\n maxMessages: number;\n}\n\n/** One message delivered by {@link EventQueue.readBatch}: a single-stream sub-batch plus its delivery metadata. */\nexport interface DeliveredEventMessage {\n receipt: EventQueueReceipt;\n /** The Event-stream name this message was read from (also carried inside `message`). */\n stream: string;\n message: EventQueueMessage;\n /**\n * How many times this message has been DELIVERED (pgmq's `read_ct`), including the current delivery — the\n * attempt counter a runner's dead-letter-after-N policy reads. Never a client-supplied value.\n */\n deliveryCount: number;\n /** When the message was enqueued, in unix microseconds (decimal string). */\n enqueuedAtUs: string;\n}\n\n/** One dead-lettered message, as enumerated from the backend's dead-letter storage. */\nexport interface DeadLetteredEventMessage {\n /** The dead-letter identity, and the handle {@link EventQueue.requeueDeadLetter} takes. */\n id: EventQueueReceipt;\n stream: string;\n message: EventQueueMessage;\n /** The reason recorded when it was dead-lettered, when one was recorded. */\n reason?: string;\n deliveryCount: number;\n /** When it was dead-lettered, in unix microseconds (decimal string). */\n deadLetteredAtUs: string;\n}\n\nexport interface EventQueue {\n /**\n * Enqueue whole messages. Called by the ingestion endpoint inside its own transaction, so passing\n * `executor` is what makes a multi-stream flush batch atomic: every message lands or none does\n * (ADR-0053 decision 4 — the endpoint never partially enqueues). Without an executor the backend uses its\n * own handle, and a multi-message call is then only as atomic as that handle.\n */\n enqueueBatch: (messages: readonly EventQueueMessage[], executor?: EventQueueExecutor) => Promise<void>;\n /** Deliver up to `maxMessages` messages of one Event stream, made invisible for the visibility timeout. */\n readBatch: (stream: string, options: EventQueueReadOptions) => Promise<DeliveredEventMessage[]>;\n /**\n * Push delivered messages' invisibility out to `visibilityTimeoutSeconds` FROM NOW — the lease RENEWAL a\n * consumer runner performs while it is still working through a read (one read makes a whole batch\n * invisible at once, so without renewal the later messages of a slow batch would become visible to another\n * runner while the first is still working toward them).\n *\n * Returns how many were actually extended. A receipt that is no longer queued (already acked or\n * dead-lettered) is simply not counted — a renewal racing a settle is ordinary, never an error.\n */\n extendVisibility: (\n stream: string,\n receipts: readonly EventQueueReceipt[],\n visibilityTimeoutSeconds: number,\n executor?: EventQueueExecutor,\n ) => Promise<number>;\n /** Acknowledge (permanently remove) delivered messages. Returns how many were actually removed. */\n ack: (stream: string, receipts: readonly EventQueueReceipt[]) => Promise<number>;\n /** Move delivered messages to dead-letter storage with a recorded reason. Returns how many moved. */\n deadLetter: (stream: string, receipts: readonly EventQueueReceipt[], reason: string) => Promise<number>;\n /** Enumerate an Event stream's dead-lettered messages, most recent first. */\n listDeadLetters: (stream: string, limit: number) => Promise<DeadLetteredEventMessage[]>;\n /**\n * Put one dead-lettered message back on its queue — a DELIBERATE act (ADR-0053 decision 7), never\n * automatic. Resolves with the requeued message's new receipt, or `null` when the id is not dead-lettered.\n */\n requeueDeadLetter: (stream: string, id: EventQueueReceipt) => Promise<EventQueueReceipt | null>;\n}\n\n/**\n * A queue message whose body is not a well-formed {@link EventQueueMessage}. The endpoint is the only writer\n * of these queues and it writes contract-shaped bodies, so this means a hand-inserted or corrupted message.\n * It carries the receipt precisely so a consumer runner can dead-letter exactly that message rather than\n * failing the whole read.\n */\nexport class MalformedEventQueueMessageError extends Error {\n readonly stream: string;\n readonly receipt: EventQueueReceipt;\n\n constructor(stream: string, receipt: EventQueueReceipt, detail: string) {\n super(`pgxsinkit: queue message ${receipt} on Event stream \"${stream}\" is not a valid queue message — ${detail}`);\n this.name = \"MalformedEventQueueMessageError\";\n this.stream = stream;\n this.receipt = receipt;\n }\n}\n\n/**\n * The queue name an Event stream is provisioned under: `pgxsinkit_events_<stream>` (ADR-0053 decision 5), the\n * SAME derivation the deploy-time DDL emits — one definition, so a runtime call can never address a queue the\n * migration did not create.\n *\n * The name is re-validated here even though `defineSyncRegistry` already validated it at module eval:\n * the queue name is interpolated into backend SQL, and a value arriving from a non-registry caller must not\n * be able to smuggle anything past that.\n */\nexport function eventStreamQueueName(stream: string): string {\n if (!EVENT_STREAM_NAME_PATTERN.test(stream) || stream.length > EVENT_STREAM_NAME_MAX_LENGTH) {\n throw new Error(\n `pgxsinkit: \"${stream}\" is not a usable Event-stream name — it must match ` +\n `${EVENT_STREAM_NAME_PATTERN.source} and be at most ${EVENT_STREAM_NAME_MAX_LENGTH} characters.`,\n );\n }\n return `${EVENT_STREAM_QUEUE_PREFIX}${stream}`;\n}\n\n/** Receipts are backend-issued decimal ids; anything else never reaches the backend's SQL. */\nexport function assertEventQueueReceipts(receipts: readonly EventQueueReceipt[]): void {\n for (const receipt of receipts) {\n if (!/^\\d+$/.test(receipt)) {\n throw new Error(`pgxsinkit: \"${receipt}\" is not a valid event-queue receipt (expected a decimal id).`);\n }\n }\n}\n",
13
- "import {\n batchEventRequestSchema,\n getSyncRegistryStreams,\n isZodSchema,\n MAX_EVENT_PAYLOAD_BYTES,\n MAX_EVENT_REQUEST_BYTES,\n MAX_EVENTS_PER_BATCH,\n type EventAck,\n type EventEnvelope,\n type EventQueueMessage,\n type EventStreamRegistry,\n type JwtClaims,\n type StampedEvent,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { FetchHandler } from \"../router\";\nimport { resolveEventIdentity } from \"./identity\";\nimport type { EventQueue, EventQueueExecutor } from \"./queue\";\n\n/**\n * The **Event lane**'s ingestion endpoint (ADR-0053 decisions 3, 4 and 5): the mutation endpoint's sibling,\n * minus what events don't need. `createSyncServer` mounts it automatically at `batchEventPaths` when — and\n * only when — the registry registers at least one Event stream.\n *\n * Two shapes of verdict, and the split is the whole design:\n *\n * - **Framing is batch-level.** A body over the request cap OR an events array over the per-batch count cap\n * (413), unparseable JSON or a body that fails the strict envelope parse (400), missing claims (401), or an\n * unavailable queue (503) is a WHOLE-batch fault: a malformed item without a parseable `eventId` cannot\n * receive a per-event verdict, and a queue that cannot take the batch must not half-take it.\n * - **Every well-formed envelope gets a per-event verdict.** `acked` (enqueued), `refused` (the gating hook\n * said no), `rejected` (schema-invalid payload for a KNOWN stream, oversized payload, or an unresolvable\n * identity claim) and `deferred` (an Event stream this server does not know — ordinary rollout skew, and\n * the ONLY non-terminal verdict). A batch-level 400 on one bad event would wedge the whole Outbox behind\n * that row, which is exactly what the layering avoids.\n *\n * It keeps the write path's **zero-startup-query** posture (ADR-0030): nothing is probed, verified or created\n * at construction — queue provisioning is deploy-time DDL — so the first statement this route sends is the\n * enqueue transaction itself.\n */\n\n/** What the gating hook is told about one event. `identity` is already resolved from the verified claims. */\nexport interface EventGateInput {\n /** The Event-stream name — the key the hook dispatches on. */\n stream: string;\n /** The client's envelope, with its payload already validated against the stream's registered schema. */\n event: EventEnvelope;\n /** The verified claims of the ingesting request (`{}` when the registry needs none). */\n claims: JwtClaims;\n /** The server-stamped identity this event would carry onto the queue. */\n identity: Record<string, string>;\n}\n\n/** `true` allows; `false` or `{ allow: false, reason }` refuses (a TERMINAL `refused` verdict). */\nexport type EventGateDecision = boolean | { allow: boolean; reason?: string };\n\n/**\n * The consent/entitlement gate (ADR-0053 decision 1): the one FUNCTION of the Event lane's contract, and so a\n * `createSyncServer` option rather than a registry field (the registry stays declarative data only).\n *\n * Called **once per event**, after the payload validated and the identity resolved, and before anything is\n * enqueued. Per-event (rather than per stream × batch) is the simplest correct shape: a consent or entitlement\n * decision may legitimately depend on the payload, and a per-batch hook could only express the subset that\n * does not. The claims are constant across a batch, so a hook that consults a store should memoize on them —\n * a batch can carry up to `MAX_EVENTS_PER_BATCH` events.\n *\n * A hook that THROWS fails the whole batch retryably (500, nothing enqueued): a gate that cannot decide must\n * never be read as \"allow\".\n */\nexport type EventGate = (input: EventGateInput) => EventGateDecision | Promise<EventGateDecision>;\n\n/** What {@link EventsEnqueuedHook} is told about a request that enqueued something. */\nexport interface EventsEnqueuedInfo {\n /** The Event streams this request put a sub-batch onto, deduplicated, in first-appearance order. */\n streams: string[];\n}\n\n/**\n * Fired after a request has ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02) — the\n * deployment-agnostic seam a serverless deployment uses to NUDGE its drain function.\n *\n * The library stays out of the transport: this hook hands over \"something landed on these streams\" and the\n * deployment decides what that means. A long-lived runner deployment wires nothing (its poller is already\n * about to read). A serverless one fires a fetch-and-forget at whatever endpoint calls the consumer's\n * `drainOnce()`, so an interactive append is drained in milliseconds rather than at the next scheduled tick.\n *\n * **It is latency, never delivery.** The scheduled sweep is the guarantee; a nudge that is lost, refused or\n * never sent costs nothing but time. So it is fire-and-forget by construction: it is called AFTER the\n * enqueue transaction committed, its return value is ignored (it is `void` — do not await anything through\n * it), and a throw is caught and warn-logged rather than affecting the response the client already earned.\n */\nexport type EventsEnqueuedHook = (info: EventsEnqueuedInfo) => void;\n\n/** The minimal transaction seam the endpoint needs — satisfied by a drizzle `PgAsyncDatabase`. */\nexport interface EventIngestDb {\n transaction: <TResult>(callback: (tx: EventQueueExecutor) => Promise<TResult>) => Promise<TResult>;\n}\n\nexport interface CreateEventIngestHandlerOptions {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n eventGate?: EventGate;\n /** See {@link EventsEnqueuedHook}. Fired only when something was actually enqueued. */\n onEventsEnqueued?: EventsEnqueuedHook;\n logTimings?: boolean;\n}\n\n/**\n * What a 503 asks the client to wait, in seconds. The client honours `Retry-After` over its own jittered\n * backoff when it asks for longer, so this is a floor on the retry of a batch the queue could not take.\n */\nexport const EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS = 5;\n\nconst encoder = new TextEncoder();\n\nfunction byteLengthOf(value: string): number {\n return encoder.encode(value).length;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** What {@link readBodyWithinLimit} answers with: the decoded body, or the batch-level status to return. */\ntype BodyRead = { ok: true; text: string } | { ok: false; status: 400 | 413 };\n\n/**\n * Read the request body WHILE enforcing the byte cap, aborting the moment the accumulated bytes exceed it.\n *\n * `request.text()` would buffer the whole body first and measure afterwards, which protects the JSON parse\n * and the queue but NOT memory: `Content-Length` is a claim, and a chunked (or simply lying) caller can omit\n * or understate it. This endpoint is public, so the cap has to bound what is ever held — hence a reader loop\n * that counts as it goes and cancels the stream on the first chunk that crosses the line, buffering at most\n * one chunk past the cap and never the rest of the upload.\n *\n * A body that cannot be read at all (including a request with no body) is a 400: it is a framing fault, and\n * a batch-level one, exactly like unparseable JSON.\n */\nasync function readBodyWithinLimit(request: Request, limit: number): Promise<BodyRead> {\n const body = request.body;\n if (body == null) {\n return { ok: false, status: 400 };\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (value == null) {\n continue;\n }\n total += value.byteLength;\n if (total > limit) {\n // Stop the peer rather than draining the rest of an oversized upload into a buffer we will discard.\n await reader.cancel().catch(() => undefined);\n return { ok: false, status: 413 };\n }\n chunks.push(value);\n }\n } catch {\n return { ok: false, status: 400 };\n }\n\n const buffer = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return { ok: true, text: new TextDecoder().decode(buffer) };\n}\n\nfunction errorResponse(message: string, status: number, headers?: Record<string, string>): Response {\n // `batchEventErrorSchema`: a non-2xx is always a whole-batch fault, so the body carries a message and\n // nothing to attribute.\n return Response.json({ message }, { status, ...(headers ? { headers } : {}) });\n}\n\n/**\n * Whether ANY registered Event stream declares an identity field — i.e. whether ingest NEEDS verified claims.\n * The mutation path's posture, mirrored: it demands claims when the registry actually requires them (an RLS\n * policy or an `authClaim` managed field) rather than unconditionally. A registry whose streams declare no\n * identity at all stamps nothing from claims, so it does not force an auth adapter into existence.\n */\nexport function eventIngestRequiresClaims(streams: EventStreamRegistry): boolean {\n return Object.values(streams).some((entry) => Object.keys(entry.identity ?? {}).length > 0);\n}\n\nexport function createEventIngestHandler<TRegistry extends SyncTableRegistry>(\n db: EventIngestDb,\n registry: TRegistry,\n queue: EventQueue,\n options: CreateEventIngestHandlerOptions = {},\n): FetchHandler {\n const streams = getSyncRegistryStreams(registry) ?? {};\n const requiresClaims = eventIngestRequiresClaims(streams);\n const perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n const handle = async (request: Request): Promise<Response> => {\n const started = options.logTimings ? perfNow() : 0;\n let authMs = 0;\n let enqueueMs = 0;\n\n const finish = (response: Response, eventCount: number): Response => {\n if (options.logTimings) {\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route: \"events\",\n authMs: Math.round(authMs),\n enqueueMs: Math.round(enqueueMs),\n totalMs: Math.round(perfNow() - started),\n events: eventCount,\n status: response.status,\n }),\n );\n }\n return response;\n };\n\n // 1. Request-shape limits, BEFORE any parse — and the cap BOUNDS MEMORY, it does not merely report on it\n // afterwards. A truthful `Content-Length` is the cheap fast path (refused without reading a byte);\n // otherwise the body is read through a counting reader that aborts the moment it crosses the cap, so a\n // chunked or lying caller cannot make this public endpoint buffer an arbitrary upload.\n const declaredLength = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > MAX_EVENT_REQUEST_BYTES) {\n return finish(\n errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413),\n 0,\n );\n }\n\n const bodyRead = await readBodyWithinLimit(request, MAX_EVENT_REQUEST_BYTES);\n if (!bodyRead.ok) {\n return finish(\n bodyRead.status === 413\n ? errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413)\n : errorResponse(\"Invalid batch event request: the body could not be read\", 400),\n 0,\n );\n }\n const rawText = bodyRead.text;\n\n // 2. Strict framing. Unreachable through the library (appends are validated, envelopes are library-built)\n // — this layer exists for library bugs and non-library callers.\n let rawBody: unknown;\n try {\n rawBody = JSON.parse(rawText);\n } catch {\n return finish(errorResponse(\"Invalid batch event request: the body is not valid JSON\", 400), 0);\n }\n\n // Request-shape limits are 413, NOT 400 (ADR-0053 decision 3): an over-count is a LIMIT violation, and\n // the client must distinguish it from malformed framing. `batchEventRequestSchema` caps the array too, so\n // the count is checked here — after the JSON parse, before the strict parse — or the schema would answer\n // first with a 400. Only the count is read; every other malformation still falls through to the 400 below.\n if (isPlainObject(rawBody) && Array.isArray(rawBody[\"events\"]) && rawBody[\"events\"].length > MAX_EVENTS_PER_BATCH) {\n return finish(\n errorResponse(`Event batch carries more than the ${MAX_EVENTS_PER_BATCH}-event per-request limit`, 413),\n 0,\n );\n }\n\n const framing = batchEventRequestSchema.safeParse(rawBody);\n if (!framing.success) {\n return finish(errorResponse(`Invalid batch event request: ${framing.error.message}`, 400), 0);\n }\n const events = framing.data.events;\n\n // 3. Claims, resolved through the ONE adapter the read and write paths share, so an event's attribution\n // can never be authorized differently from a write.\n const authStart = options.logTimings ? perfNow() : 0;\n const resolvedClaims = await options.resolveAuthClaims?.(request);\n if (options.logTimings) authMs = perfNow() - authStart;\n\n if (requiresClaims && !isPlainObject(resolvedClaims)) {\n return finish(\n errorResponse(\"Event streams with claim-stamped identity require validated JWT claims\", 401),\n events.length,\n );\n }\n const claims: JwtClaims = isPlainObject(resolvedClaims) ? resolvedClaims : {};\n\n // 4. Per-event verdicts, in request order. Survivors are split by Event stream — insertion order gives\n // each stream's sub-batch the events in the order the client appended them (ADR-0053 decision 5).\n const acks: EventAck[] = [];\n const byStream = new Map<string, StampedEvent[]>();\n\n for (const event of events) {\n const entry = streams[event.stream];\n if (!entry) {\n // NOT terminal: a client rolled out ahead of its server is ordinary deployment skew, and deleting\n // its events would be data loss on a normal path.\n acks.push({\n eventId: event.eventId,\n status: \"deferred\",\n reason: `Unknown Event stream \"${event.stream}\" — this server registers none by that name`,\n });\n continue;\n }\n\n if (!isZodSchema(entry.payload)) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Event stream \"${event.stream}\" is registered without a usable payload schema`,\n });\n continue;\n }\n\n // THE authoritative parse: the one whose OUTPUT is taken. The JSON-NORMALIZED form of `parsed.data`\n // (never the raw envelope payload) is what gets stamped onto the queue and what the consumer callback\n // receives — the normalization is the JSON round-trip below, and it is part of the contract, not an\n // artefact: a transform producing a `Date` delivers that date's ISO STRING, and nested `undefined`\n // properties are dropped.\n //\n // The schema itself EXECUTES at both boundaries, and that is worth being exact about: `appendEvent`\n // already ran it on the client as pure validation — discarding the result and storing the caller's\n // original value — so what arrives here is the value that was appended, never a once-transformed one.\n // A transform CALLBACK therefore runs twice while its result is only ever taken once, which is exactly\n // why the lane requires transforms to be pure and deterministic: an effectful or environment-dependent\n // one is unsupported, because this server's run is the one that counts and nothing reconciles it\n // against the client's.\n const parsedPayload = entry.payload.safeParse(event.payload);\n if (!parsedPayload.success) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Payload failed the schema registered for Event stream \"${event.stream}\": ${parsedPayload.error.message}`,\n });\n continue;\n }\n\n // The authoritative parse's OUTPUT still has to reach the queue as JSON, and a schema is free to\n // produce something JSON cannot carry: `z.string().transform(BigInt)` makes `JSON.stringify` THROW,\n // and a transform returning `undefined` makes it RETURN `undefined`. Untrapped, the throw would fail\n // the WHOLE batch with a 500 — and the Outbox, having had no verdict, would resend that same event\n // forever, wedging every sibling behind it. So it is a TERMINAL per-event `rejected`, and deliberately\n // its own reason: labelling it \"exceeds the byte limit\" would send an author hunting a size problem\n // that does not exist. (The size check below stays exactly what it says.)\n //\n // This serialization is NOT merely a check — it IS the normalization the consumer contract names. A\n // successful `JSON.stringify` does not mean the value belongs to the JSON domain: a `Date` stringifies\n // to an ISO string, a nested `undefined` property vanishes, an `undefined` array member becomes `null`.\n // Enqueueing `parsedPayload.data` itself would hand an in-memory/fake queue the un-normalized value\n // while real pgmq (which serializes into `jsonb`) delivered the normalized one — the same event\n // observed as two different values depending on the backend. So these exact bytes are what is parsed\n // back and stamped below, and every backend, the fake and pgmq alike, sees the identical payload.\n let payloadJson: string | undefined;\n let serializationFailure: unknown;\n try {\n payloadJson = JSON.stringify(parsedPayload.data);\n } catch (error) {\n serializationFailure = error;\n }\n if (payloadJson === undefined) {\n const detail = serializationFailure instanceof Error ? serializationFailure.message : undefined;\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason:\n `The payload schema's parse for Event stream \"${event.stream}\" produced a value that cannot be ` +\n `serialized as JSON${detail != null ? `: ${detail}` : \"\"}`,\n });\n continue;\n }\n\n if (byteLengthOf(payloadJson) > MAX_EVENT_PAYLOAD_BYTES) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Payload exceeds the ${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit`,\n });\n continue;\n }\n\n // Identity is resolved BEFORE the gate so the hook can consult the attribution it is gating; an\n // unresolvable identity is a rejection in its own right and never reaches the hook.\n const resolvedIdentity = resolveEventIdentity(claims, entry.identity ?? {});\n if (!resolvedIdentity.ok) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason:\n `Identity field \"${resolvedIdentity.field}\" of Event stream \"${event.stream}\" could not be ` +\n `stamped from claim path ${JSON.stringify(resolvedIdentity.claimPath)}: ${resolvedIdentity.detail}`,\n });\n continue;\n }\n\n if (options.eventGate) {\n let decision: EventGateDecision;\n try {\n decision = await options.eventGate({\n stream: event.stream,\n event,\n claims,\n identity: resolvedIdentity.identity,\n });\n } catch (error) {\n // A gate that cannot decide must never be read as \"allow\". Fail the batch retryably: nothing is\n // enqueued, the Outbox keeps every row, and the client retries.\n console.error(\"[pgxsinkit] event gate threw; refusing the whole batch\", error);\n return finish(errorResponse(\"The event gate failed; nothing was enqueued\", 500), events.length);\n }\n\n const allowed = typeof decision === \"boolean\" ? decision : decision.allow;\n if (!allowed) {\n const reason = typeof decision === \"boolean\" ? undefined : decision.reason;\n acks.push({\n eventId: event.eventId,\n status: \"refused\",\n ...(reason ? { reason } : { reason: `Refused by the event gate for Event stream \"${event.stream}\"` }),\n });\n continue;\n }\n }\n\n // `payloadJson` is exactly the bytes the queue will carry, so parsing it back yields exactly the value\n // the consumer will observe — whatever backend is behind the seam. (`JSON.parse` of a string that\n // `JSON.stringify` just produced cannot throw.)\n const normalizedPayload: unknown = JSON.parse(payloadJson);\n\n const stamped: StampedEvent = {\n eventId: event.eventId,\n occurredAtUs: event.occurredAtUs,\n identity: resolvedIdentity.identity,\n payload: normalizedPayload,\n };\n const bucket = byStream.get(event.stream);\n if (bucket) {\n bucket.push(stamped);\n } else {\n byStream.set(event.stream, [stamped]);\n }\n acks.push({ eventId: event.eventId, status: \"acked\" });\n }\n\n // 5. One message per Event stream, all enqueued in ONE transaction. Atomic or nothing (ADR-0053\n // decision 4): the endpoint never partially enqueues and never buffers on the queue's behalf — the\n // Outbox is the buffer.\n const messages: EventQueueMessage[] = Array.from(byStream, ([stream, streamEvents]) => ({\n stream,\n events: streamEvents,\n }));\n\n if (messages.length > 0) {\n const enqueueStart = options.logTimings ? perfNow() : 0;\n try {\n await db.transaction(async (tx) => {\n await queue.enqueueBatch(messages, tx);\n });\n } catch (error) {\n // Deliberately generic to the client (the detail can name schema/queue internals); the operator gets\n // the full error on the server's own log.\n console.error(\"[pgxsinkit] event enqueue failed; nothing was enqueued\", error);\n return finish(\n errorResponse(\"The event queue is unavailable; nothing was enqueued\", 503, {\n \"Retry-After\": String(EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS),\n }),\n events.length,\n );\n }\n if (options.logTimings) enqueueMs = perfNow() - enqueueStart;\n\n // The nudge (ADR-0053 amendment): AFTER the commit, never awaited, never able to change the verdict\n // the client already earned. `byStream`'s keys are unique by construction, so the hook gets the\n // deduplicated stream names of this request in first-appearance order.\n if (options.onEventsEnqueued) {\n try {\n options.onEventsEnqueued({ streams: [...byStream.keys()] });\n } catch (error) {\n // A failed nudge costs latency, never delivery: the scheduled sweep is the guarantee.\n console.warn(\"[pgxsinkit] the `onEventsEnqueued` hook threw; the events are enqueued regardless\", error);\n }\n }\n }\n\n return finish(Response.json({ acks }), events.length);\n };\n\n return handle;\n}\n",
13
+ "import {\n batchEventRequestSchema,\n type EventAck,\n type EventEnvelope,\n type EventQueueMessage,\n type EventStreamRegistry,\n getSyncRegistryStreams,\n isZodSchema,\n type JwtClaims,\n MAX_EVENT_PAYLOAD_BYTES,\n MAX_EVENT_REQUEST_BYTES,\n MAX_EVENTS_PER_BATCH,\n type StampedEvent,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { FetchHandler } from \"../router\";\nimport { resolveEventIdentity } from \"./identity\";\nimport type { EventQueue, EventQueueExecutor } from \"./queue\";\n\n/**\n * The **Event lane**'s ingestion endpoint (ADR-0053 decisions 3, 4 and 5): the mutation endpoint's sibling,\n * minus what events don't need. `createSyncServer` mounts it automatically at `batchEventPaths` when — and\n * only when — the registry registers at least one Event stream.\n *\n * Two shapes of verdict, and the split is the whole design:\n *\n * - **Framing is batch-level.** A body over the request cap OR an events array over the per-batch count cap\n * (413), unparseable JSON or a body that fails the strict envelope parse (400), missing claims (401), or an\n * unavailable queue (503) is a WHOLE-batch fault: a malformed item without a parseable `eventId` cannot\n * receive a per-event verdict, and a queue that cannot take the batch must not half-take it.\n * - **Every well-formed envelope gets a per-event verdict.** `acked` (enqueued), `refused` (the gating hook\n * said no), `rejected` (schema-invalid payload for a KNOWN stream, oversized payload, or an unresolvable\n * identity claim) and `deferred` (an Event stream this server does not know — ordinary rollout skew, and\n * the ONLY non-terminal verdict). A batch-level 400 on one bad event would wedge the whole Outbox behind\n * that row, which is exactly what the layering avoids.\n *\n * It keeps the write path's **zero-startup-query** posture (ADR-0030): nothing is probed, verified or created\n * at construction — queue provisioning is deploy-time DDL — so the first statement this route sends is the\n * enqueue transaction itself.\n */\n\n/** What the gating hook is told about one event. `identity` is already resolved from the verified claims. */\nexport interface EventGateInput {\n /** The Event-stream name — the key the hook dispatches on. */\n stream: string;\n /** The client's envelope, with its payload already validated against the stream's registered schema. */\n event: EventEnvelope;\n /** The verified claims of the ingesting request (`{}` when the registry needs none). */\n claims: JwtClaims;\n /** The server-stamped identity this event would carry onto the queue. */\n identity: Record<string, string>;\n}\n\n/** `true` allows; `false` or `{ allow: false, reason }` refuses (a TERMINAL `refused` verdict). */\nexport type EventGateDecision = boolean | { allow: boolean; reason?: string };\n\n/**\n * The consent/entitlement gate (ADR-0053 decision 1): the one FUNCTION of the Event lane's contract, and so a\n * `createSyncServer` option rather than a registry field (the registry stays declarative data only).\n *\n * Called **once per event**, after the payload validated and the identity resolved, and before anything is\n * enqueued. Per-event (rather than per stream × batch) is the simplest correct shape: a consent or entitlement\n * decision may legitimately depend on the payload, and a per-batch hook could only express the subset that\n * does not. The claims are constant across a batch, so a hook that consults a store should memoize on them —\n * a batch can carry up to `MAX_EVENTS_PER_BATCH` events.\n *\n * A hook that THROWS fails the whole batch retryably (500, nothing enqueued): a gate that cannot decide must\n * never be read as \"allow\".\n */\nexport type EventGate = (input: EventGateInput) => EventGateDecision | Promise<EventGateDecision>;\n\n/** What {@link EventsEnqueuedHook} is told about a request that enqueued something. */\nexport interface EventsEnqueuedInfo {\n /** The Event streams this request put a sub-batch onto, deduplicated, in first-appearance order. */\n streams: string[];\n}\n\n/**\n * Fired after a request has ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02) — the\n * deployment-agnostic seam a serverless deployment uses to NUDGE its drain function.\n *\n * The library stays out of the transport: this hook hands over \"something landed on these streams\" and the\n * deployment decides what that means. A long-lived runner deployment wires nothing (its poller is already\n * about to read). A serverless one fires a fetch-and-forget at whatever endpoint calls the consumer's\n * `drainOnce()`, so an interactive append is drained in milliseconds rather than at the next scheduled tick.\n *\n * **It is latency, never delivery.** The scheduled sweep is the guarantee; a nudge that is lost, refused or\n * never sent costs nothing but time. So it is fire-and-forget by construction: it is called AFTER the\n * enqueue transaction committed, its return value is ignored (it is `void` — do not await anything through\n * it), and a throw is caught and warn-logged rather than affecting the response the client already earned.\n */\nexport type EventsEnqueuedHook = (info: EventsEnqueuedInfo) => void;\n\n/** The minimal transaction seam the endpoint needs — satisfied by a drizzle `PgAsyncDatabase`. */\nexport interface EventIngestDb {\n transaction: <TResult>(callback: (tx: EventQueueExecutor) => Promise<TResult>) => Promise<TResult>;\n}\n\nexport interface CreateEventIngestHandlerOptions {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n eventGate?: EventGate;\n /** See {@link EventsEnqueuedHook}. Fired only when something was actually enqueued. */\n onEventsEnqueued?: EventsEnqueuedHook;\n logTimings?: boolean;\n}\n\n/**\n * What a 503 asks the client to wait, in seconds. The client honours `Retry-After` over its own jittered\n * backoff when it asks for longer, so this is a floor on the retry of a batch the queue could not take.\n */\nexport const EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS = 5;\n\nconst encoder = new TextEncoder();\n\nfunction byteLengthOf(value: string): number {\n return encoder.encode(value).length;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** What {@link readBodyWithinLimit} answers with: the decoded body, or the batch-level status to return. */\ntype BodyRead = { ok: true; text: string } | { ok: false; status: 400 | 413 };\n\n/**\n * Read the request body WHILE enforcing the byte cap, aborting the moment the accumulated bytes exceed it.\n *\n * `request.text()` would buffer the whole body first and measure afterwards, which protects the JSON parse\n * and the queue but NOT memory: `Content-Length` is a claim, and a chunked (or simply lying) caller can omit\n * or understate it. This endpoint is public, so the cap has to bound what is ever held — hence a reader loop\n * that counts as it goes and cancels the stream on the first chunk that crosses the line, buffering at most\n * one chunk past the cap and never the rest of the upload.\n *\n * A body that cannot be read at all (including a request with no body) is a 400: it is a framing fault, and\n * a batch-level one, exactly like unparseable JSON.\n */\nasync function readBodyWithinLimit(request: Request, limit: number): Promise<BodyRead> {\n const body = request.body;\n if (body == null) {\n return { ok: false, status: 400 };\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (value == null) {\n continue;\n }\n total += value.byteLength;\n if (total > limit) {\n // Stop the peer rather than draining the rest of an oversized upload into a buffer we will discard.\n await reader.cancel().catch(() => undefined);\n return { ok: false, status: 413 };\n }\n chunks.push(value);\n }\n } catch {\n return { ok: false, status: 400 };\n }\n\n const buffer = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return { ok: true, text: new TextDecoder().decode(buffer) };\n}\n\nfunction errorResponse(message: string, status: number, headers?: Record<string, string>): Response {\n // `batchEventErrorSchema`: a non-2xx is always a whole-batch fault, so the body carries a message and\n // nothing to attribute.\n return Response.json({ message }, { status, ...(headers ? { headers } : {}) });\n}\n\n/**\n * Whether ANY registered Event stream declares an identity field — i.e. whether ingest NEEDS verified claims.\n * The mutation path's posture, mirrored: it demands claims when the registry actually requires them (an RLS\n * policy or an `authClaim` managed field) rather than unconditionally. A registry whose streams declare no\n * identity at all stamps nothing from claims, so it does not force an auth adapter into existence.\n */\nexport function eventIngestRequiresClaims(streams: EventStreamRegistry): boolean {\n return Object.values(streams).some((entry) => Object.keys(entry.identity ?? {}).length > 0);\n}\n\nexport function createEventIngestHandler<TRegistry extends SyncTableRegistry>(\n db: EventIngestDb,\n registry: TRegistry,\n queue: EventQueue,\n options: CreateEventIngestHandlerOptions = {},\n): FetchHandler {\n const streams = getSyncRegistryStreams(registry) ?? {};\n const requiresClaims = eventIngestRequiresClaims(streams);\n const perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n const handle = async (request: Request): Promise<Response> => {\n const started = options.logTimings ? perfNow() : 0;\n let authMs = 0;\n let enqueueMs = 0;\n\n const finish = (response: Response, eventCount: number): Response => {\n if (options.logTimings) {\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route: \"events\",\n authMs: Math.round(authMs),\n enqueueMs: Math.round(enqueueMs),\n totalMs: Math.round(perfNow() - started),\n events: eventCount,\n status: response.status,\n }),\n );\n }\n return response;\n };\n\n // 1. Request-shape limits, BEFORE any parse — and the cap BOUNDS MEMORY, it does not merely report on it\n // afterwards. A truthful `Content-Length` is the cheap fast path (refused without reading a byte);\n // otherwise the body is read through a counting reader that aborts the moment it crosses the cap, so a\n // chunked or lying caller cannot make this public endpoint buffer an arbitrary upload.\n const declaredLength = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > MAX_EVENT_REQUEST_BYTES) {\n return finish(\n errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413),\n 0,\n );\n }\n\n const bodyRead = await readBodyWithinLimit(request, MAX_EVENT_REQUEST_BYTES);\n if (!bodyRead.ok) {\n return finish(\n bodyRead.status === 413\n ? errorResponse(`Event batch body exceeds the ${MAX_EVENT_REQUEST_BYTES}-byte request limit`, 413)\n : errorResponse(\"Invalid batch event request: the body could not be read\", 400),\n 0,\n );\n }\n const rawText = bodyRead.text;\n\n // 2. Strict framing. Unreachable through the library (appends are validated, envelopes are library-built)\n // — this layer exists for library bugs and non-library callers.\n let rawBody: unknown;\n try {\n rawBody = JSON.parse(rawText);\n } catch {\n return finish(errorResponse(\"Invalid batch event request: the body is not valid JSON\", 400), 0);\n }\n\n // Request-shape limits are 413, NOT 400 (ADR-0053 decision 3): an over-count is a LIMIT violation, and\n // the client must distinguish it from malformed framing. `batchEventRequestSchema` caps the array too, so\n // the count is checked here — after the JSON parse, before the strict parse — or the schema would answer\n // first with a 400. Only the count is read; every other malformation still falls through to the 400 below.\n if (isPlainObject(rawBody) && Array.isArray(rawBody[\"events\"]) && rawBody[\"events\"].length > MAX_EVENTS_PER_BATCH) {\n return finish(\n errorResponse(`Event batch carries more than the ${MAX_EVENTS_PER_BATCH}-event per-request limit`, 413),\n 0,\n );\n }\n\n const framing = batchEventRequestSchema.safeParse(rawBody);\n if (!framing.success) {\n return finish(errorResponse(`Invalid batch event request: ${framing.error.message}`, 400), 0);\n }\n const events = framing.data.events;\n\n // 3. Claims, resolved through the ONE adapter the read and write paths share, so an event's attribution\n // can never be authorized differently from a write.\n const authStart = options.logTimings ? perfNow() : 0;\n const resolvedClaims = await options.resolveAuthClaims?.(request);\n if (options.logTimings) authMs = perfNow() - authStart;\n\n if (requiresClaims && !isPlainObject(resolvedClaims)) {\n return finish(\n errorResponse(\"Event streams with claim-stamped identity require validated JWT claims\", 401),\n events.length,\n );\n }\n const claims: JwtClaims = isPlainObject(resolvedClaims) ? resolvedClaims : {};\n\n // 4. Per-event verdicts, in request order. Survivors are split by Event stream — insertion order gives\n // each stream's sub-batch the events in the order the client appended them (ADR-0053 decision 5).\n const acks: EventAck[] = [];\n const byStream = new Map<string, StampedEvent[]>();\n\n for (const event of events) {\n const entry = streams[event.stream];\n if (!entry) {\n // NOT terminal: a client rolled out ahead of its server is ordinary deployment skew, and deleting\n // its events would be data loss on a normal path.\n acks.push({\n eventId: event.eventId,\n status: \"deferred\",\n reason: `Unknown Event stream \"${event.stream}\" — this server registers none by that name`,\n });\n continue;\n }\n\n if (!isZodSchema(entry.payload)) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Event stream \"${event.stream}\" is registered without a usable payload schema`,\n });\n continue;\n }\n\n // THE authoritative parse: the one whose OUTPUT is taken. The JSON-NORMALIZED form of `parsed.data`\n // (never the raw envelope payload) is what gets stamped onto the queue and what the consumer callback\n // receives — the normalization is the JSON round-trip below, and it is part of the contract, not an\n // artefact: a transform producing a `Date` delivers that date's ISO STRING, and nested `undefined`\n // properties are dropped.\n //\n // The schema itself EXECUTES at both boundaries, and that is worth being exact about: `appendEvent`\n // already ran it on the client as pure validation — discarding the result and storing the caller's\n // original value — so what arrives here is the value that was appended, never a once-transformed one.\n // A transform CALLBACK therefore runs twice while its result is only ever taken once, which is exactly\n // why the lane requires transforms to be pure and deterministic: an effectful or environment-dependent\n // one is unsupported, because this server's run is the one that counts and nothing reconciles it\n // against the client's.\n const parsedPayload = entry.payload.safeParse(event.payload);\n if (!parsedPayload.success) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Payload failed the schema registered for Event stream \"${event.stream}\": ${parsedPayload.error.message}`,\n });\n continue;\n }\n\n // The authoritative parse's OUTPUT still has to reach the queue as JSON, and a schema is free to\n // produce something JSON cannot carry: `z.string().transform(BigInt)` makes `JSON.stringify` THROW,\n // and a transform returning `undefined` makes it RETURN `undefined`. Untrapped, the throw would fail\n // the WHOLE batch with a 500 — and the Outbox, having had no verdict, would resend that same event\n // forever, wedging every sibling behind it. So it is a TERMINAL per-event `rejected`, and deliberately\n // its own reason: labelling it \"exceeds the byte limit\" would send an author hunting a size problem\n // that does not exist. (The size check below stays exactly what it says.)\n //\n // This serialization is NOT merely a check — it IS the normalization the consumer contract names. A\n // successful `JSON.stringify` does not mean the value belongs to the JSON domain: a `Date` stringifies\n // to an ISO string, a nested `undefined` property vanishes, an `undefined` array member becomes `null`.\n // Enqueueing `parsedPayload.data` itself would hand an in-memory/fake queue the un-normalized value\n // while real pgmq (which serializes into `jsonb`) delivered the normalized one — the same event\n // observed as two different values depending on the backend. So these exact bytes are what is parsed\n // back and stamped below, and every backend, the fake and pgmq alike, sees the identical payload.\n let payloadJson: string | undefined;\n let serializationFailure: unknown;\n try {\n payloadJson = JSON.stringify(parsedPayload.data);\n } catch (error) {\n serializationFailure = error;\n }\n if (payloadJson === undefined) {\n const detail = serializationFailure instanceof Error ? serializationFailure.message : undefined;\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason:\n `The payload schema's parse for Event stream \"${event.stream}\" produced a value that cannot be ` +\n `serialized as JSON${detail != null ? `: ${detail}` : \"\"}`,\n });\n continue;\n }\n\n if (byteLengthOf(payloadJson) > MAX_EVENT_PAYLOAD_BYTES) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason: `Payload exceeds the ${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit`,\n });\n continue;\n }\n\n // Identity is resolved BEFORE the gate so the hook can consult the attribution it is gating; an\n // unresolvable identity is a rejection in its own right and never reaches the hook.\n const resolvedIdentity = resolveEventIdentity(claims, entry.identity ?? {});\n if (!resolvedIdentity.ok) {\n acks.push({\n eventId: event.eventId,\n status: \"rejected\",\n reason:\n `Identity field \"${resolvedIdentity.field}\" of Event stream \"${event.stream}\" could not be ` +\n `stamped from claim path ${JSON.stringify(resolvedIdentity.claimPath)}: ${resolvedIdentity.detail}`,\n });\n continue;\n }\n\n if (options.eventGate) {\n let decision: EventGateDecision;\n try {\n decision = await options.eventGate({\n stream: event.stream,\n event,\n claims,\n identity: resolvedIdentity.identity,\n });\n } catch (error) {\n // A gate that cannot decide must never be read as \"allow\". Fail the batch retryably: nothing is\n // enqueued, the Outbox keeps every row, and the client retries.\n console.error(\"[pgxsinkit] event gate threw; refusing the whole batch\", error);\n return finish(errorResponse(\"The event gate failed; nothing was enqueued\", 500), events.length);\n }\n\n const allowed = typeof decision === \"boolean\" ? decision : decision.allow;\n if (!allowed) {\n const reason = typeof decision === \"boolean\" ? undefined : decision.reason;\n acks.push({\n eventId: event.eventId,\n status: \"refused\",\n ...(reason ? { reason } : { reason: `Refused by the event gate for Event stream \"${event.stream}\"` }),\n });\n continue;\n }\n }\n\n // `payloadJson` is exactly the bytes the queue will carry, so parsing it back yields exactly the value\n // the consumer will observe — whatever backend is behind the seam. (`JSON.parse` of a string that\n // `JSON.stringify` just produced cannot throw.)\n const normalizedPayload: unknown = JSON.parse(payloadJson);\n\n const stamped: StampedEvent = {\n eventId: event.eventId,\n occurredAtUs: event.occurredAtUs,\n identity: resolvedIdentity.identity,\n payload: normalizedPayload,\n };\n const bucket = byStream.get(event.stream);\n if (bucket) {\n bucket.push(stamped);\n } else {\n byStream.set(event.stream, [stamped]);\n }\n acks.push({ eventId: event.eventId, status: \"acked\" });\n }\n\n // 5. One message per Event stream, all enqueued in ONE transaction. Atomic or nothing (ADR-0053\n // decision 4): the endpoint never partially enqueues and never buffers on the queue's behalf — the\n // Outbox is the buffer.\n const messages: EventQueueMessage[] = Array.from(byStream, ([stream, streamEvents]) => ({\n stream,\n events: streamEvents,\n }));\n\n if (messages.length > 0) {\n const enqueueStart = options.logTimings ? perfNow() : 0;\n try {\n await db.transaction(async (tx) => {\n await queue.enqueueBatch(messages, tx);\n });\n } catch (error) {\n // Deliberately generic to the client (the detail can name schema/queue internals); the operator gets\n // the full error on the server's own log.\n console.error(\"[pgxsinkit] event enqueue failed; nothing was enqueued\", error);\n return finish(\n errorResponse(\"The event queue is unavailable; nothing was enqueued\", 503, {\n \"Retry-After\": String(EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS),\n }),\n events.length,\n );\n }\n if (options.logTimings) enqueueMs = perfNow() - enqueueStart;\n\n // The nudge (ADR-0053 amendment): AFTER the commit, never awaited, never able to change the verdict\n // the client already earned. `byStream`'s keys are unique by construction, so the hook gets the\n // deduplicated stream names of this request in first-appearance order.\n if (options.onEventsEnqueued) {\n try {\n options.onEventsEnqueued({ streams: [...byStream.keys()] });\n } catch (error) {\n // A failed nudge costs latency, never delivery: the scheduled sweep is the guarantee.\n console.warn(\"[pgxsinkit] the `onEventsEnqueued` hook threw; the events are enqueued regardless\", error);\n }\n }\n }\n\n return finish(Response.json({ acks }), events.length);\n };\n\n return handle;\n}\n",
14
14
  "import type { EventStreamIdentityField, JwtClaims } from \"@pgxsinkit/contracts\";\n\n/**\n * Identity stamping (ADR-0053 decisions 1 and 5): resolve an Event stream's declared identity fields against\n * the **verified** claims of the ingesting request.\n *\n * This is the security-sensitive step of the lane — the point where a client-supplied event becomes an\n * attributed fact. The client's envelope carries no identity at all, so everything the consumer callback sees\n * under `identity` comes from here, and only from claims the server itself verified.\n */\n\n/** A resolved stamp, or the first field that could not be resolved (which makes the event `rejected`). */\nexport type IdentityResolution =\n | { ok: true; identity: Record<string, string> }\n | { ok: false; field: string; claimPath: readonly string[]; detail: string };\n\n/**\n * Walk a claim path the way the managed-field `authClaim` strategy does (`ManagedFieldSpec.claimPath`), so\n * the toolkit's two claim-stamping surfaces address claims identically: each segment is a plain key into a\n * plain object, `[\"sub\"]` for the auth subject, `[\"app_metadata\", \"person_id\"]` for an app-minted identity.\n *\n * Arrays are NOT indexed (the SQL twin's `#>> '{a,b}'` would, but an identity addressed by array position is\n * not a shape the registry validates or the toolkit wants to encourage), and the walk stops at the first\n * segment that is not a plain object.\n */\nfunction readClaimAtPath(claims: JwtClaims, claimPath: readonly string[]): unknown {\n let current: unknown = claims;\n for (const segment of claimPath) {\n if (typeof current !== \"object\" || current === null || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * Coerce a resolved claim to the stamped string value, or `null` when it is not stampable.\n *\n * A JSON scalar (number/boolean) is coerced to its text form deliberately: that is exactly what the SQL twin\n * (`current_setting('request.jwt.claims')::jsonb #>> '{…}'`) does for a managed `authClaim` field, so an\n * issuer that mints `person_id` as a JSON number stamps the same value on both surfaces. Anything else —\n * absent, null, an object, an array, or an empty/whitespace string — is NOT stampable: an empty identity must\n * never be stamped silently.\n */\nfunction toStampedValue(value: unknown): string | null {\n if (typeof value === \"string\") {\n return value.trim().length > 0 ? value : null;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n if (typeof value === \"boolean\") {\n return String(value);\n }\n return null;\n}\n\n/**\n * Resolve every declared identity field, or report the FIRST unresolvable one. Fail-closed by construction:\n * there is no partial stamp and no empty-string fallback — an event whose identity cannot be resolved gets a\n * `rejected` verdict naming the field and its claim path.\n */\nexport function resolveEventIdentity(\n claims: JwtClaims,\n identityFields: Record<string, EventStreamIdentityField>,\n): IdentityResolution {\n const identity: Record<string, string> = {};\n\n for (const [field, spec] of Object.entries(identityFields)) {\n const claimPath = spec.claimPath;\n const raw = readClaimAtPath(claims, claimPath);\n const stamped = toStampedValue(raw);\n if (stamped === null) {\n return {\n ok: false,\n field,\n claimPath,\n detail: raw === undefined ? \"the claim is absent\" : `the claim is not a stampable scalar (${typeof raw})`,\n };\n }\n identity[field] = stamped;\n }\n\n return { ok: true, identity };\n}\n",
15
- "import { and, eq, sql, type AnyRelations } from \"drizzle-orm\";\nimport { getTableConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\nimport type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\nimport { createSchemaFactory } from \"drizzle-orm/zod\";\n\nimport type {\n AuthoritativeWriteRequest,\n BatchMutationRequest,\n JwtClaims,\n ManagedFieldApplyOn,\n MutationAck,\n RegistryRelations,\n SyncTableEntry,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport {\n authoritativeWriteRequestSchema,\n batchMutationRequestSchema,\n getOmittedProjectedColumns as getOmittedProjectionColumns,\n getProjectedColumns,\n isManagedFieldGuarded,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport type { OperationsLogConfig } from \"../operations-log/types\";\nimport { logOperation, logOperationSafely } from \"../operations-log/writer\";\nimport type { FetchHandler } from \"../router\";\nimport { readSqlState } from \"../sql-state\";\nimport {\n executePlpgsqlBatch,\n expectedApplyFingerprint,\n resolveApplyFunctionSchema,\n type ApplyFunctionRenderOptions,\n type MutationConflict,\n verifyRlsAuthHelpers,\n} from \"./plpgsql-apply\";\nimport type { TransactionClient } from \"./types\";\n\n/**\n * How the write path handles its remaining startup query class — the RLS auth-helper verify (ADR-0030\n * decision 3). The apply-function drift guarantee moved into the call itself (self-verifying function),\n * so this now governs ONLY that helper check:\n * - `\"in-process\"` (default): keep today's boot-time `verifyRlsAuthHelpers` and its clear startup error.\n * - `\"deploy-time\"`: skip it — the migration pipeline owns that guarantee, so a fresh (serverless)\n * worker sends ZERO queries before the mutation transaction itself.\n */\nexport type StartupVerificationMode = \"in-process\" | \"deploy-time\";\n\nconst { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({\n // Mutation payloads cross a JSON boundary, so bigint-mode Drizzle columns arrive as decimal strings.\n // Coerce only while validating; the original JSON payload remains string-valued for the SQL apply path.\n coerce: { date: true, bigint: true },\n});\n\ntype RouteReadQueryClient = Pick<PgAsyncDatabase<PgQueryResultHKT, AnyRelations>, \"select\">;\n\nexport const batchMutationPaths = [\"/api/mutations\"] as const;\n/** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */\nexport const authoritativeMutationPaths = [\"/api/mutations/unit\"] as const;\n\nexport function createMutationHandler<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n operationsLogConfig: OperationsLogConfig,\n operationsLogReady: Promise<void>,\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null,\n startupVerification: StartupVerificationMode = \"in-process\",\n logTimings = false,\n // ADR-0054: the roles the installed artifact was generated with. The ACL is INSIDE the fingerprinted\n // body, so the expected fingerprint below is only reproducible when this matches the generate flags.\n applyFunctionGrantExecuteTo: readonly string[] = [],\n // The schema the installed artifact was generated into (`pgxsinkit-generate --function-schema`).\n // It is BOTH a fingerprint input (the body embeds the qualified name) and the name this server must\n // CALL, so one value drives both — a server that knows the fingerprint but calls the function\n // unqualified would resolve through `search_path` and, in the usual case, find nothing.\n applyFunctionSchema?: string,\n): { batch: FetchHandler; authoritative: FetchHandler } {\n let startupReadyPromise: Promise<void> | undefined;\n\n const applyFunctionRenderOptions: ApplyFunctionRenderOptions = {\n ...(applyFunctionGrantExecuteTo.length > 0 ? { grantExecuteTo: applyFunctionGrantExecuteTo } : {}),\n ...(applyFunctionSchema ? { functionSchema: applyFunctionSchema } : {}),\n };\n // Validated once here (the same rule the renderer applies) rather than per request, so a bad schema\n // name fails at server construction instead of on the first write.\n const resolvedApplyFunctionSchema = resolveApplyFunctionSchema(applyFunctionRenderOptions.functionSchema);\n const applyInvocationOptions = resolvedApplyFunctionSchema ? { functionSchema: resolvedApplyFunctionSchema } : {};\n\n // ADR-0030: the fingerprint this server expects for its registry + applier codegen, computed ONCE per\n // server instance. Every `executePlpgsqlBatch` passes it so the installed apply function can verify\n // itself in-body (SQLSTATE 'PXS01' on drift) — this replaces the deleted startup verify.\n const expectedFingerprint = expectedApplyFingerprint(registry, applyFunctionRenderOptions);\n\n // Per-request timing scratch (opt-in). authMs/applyMs are filled at the narrow phase call sites inside\n // the handler; totalMs + status are measured by `withTiming` wrapping the returned handler. A fresh\n // object per request keeps this concurrency-safe without threading state through the handler internals.\n const perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n interface RequestTiming {\n handlerStart: number;\n preTxMs: number;\n txOpenMs: number;\n authMs: number;\n applyMs: number;\n mutations: number;\n }\n const withTiming = (route: string, handler: (request: Request, timing?: RequestTiming) => Promise<Response>) => {\n if (!logTimings) {\n return (request: Request) => handler(request);\n }\n return async (request: Request): Promise<Response> => {\n const start = perfNow();\n const timing: RequestTiming = {\n handlerStart: start,\n preTxMs: 0,\n txOpenMs: 0,\n authMs: 0,\n applyMs: 0,\n mutations: 0,\n };\n const response = await handler(request, timing);\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route,\n preTxMs: Math.round(timing.preTxMs),\n txOpenMs: Math.round(timing.txOpenMs),\n authMs: Math.round(timing.authMs),\n applyMs: Math.round(timing.applyMs),\n totalMs: Math.round(perfNow() - start),\n mutations: timing.mutations,\n status: response.status,\n }),\n );\n return response;\n };\n };\n // Stamp the two spans the phase timers cannot see: preTxMs = handler entry → transaction call\n // (parse + zod validation), txOpenMs = transaction call → callback entry (the driver's LAZY\n // connection establishment + BEGIN — on serverless this is where a fresh worker's pooler\n // TLS/DNS cost lands, invisible to authMs/applyMs).\n const stampPreTx = (timing: RequestTiming | undefined) => {\n if (timing) timing.preTxMs = perfNow() - timing.handlerStart;\n return timing ? perfNow() : 0;\n };\n const stampTxOpen = (timing: RequestTiming | undefined, txCallAt: number) => {\n if (timing) timing.txOpenMs = perfNow() - txCallAt;\n };\n\n const startupReady = () => {\n if (!startupReadyPromise) {\n // ADR-0030: \"deploy-time\" skips the boot-time RLS auth-helper verify (the migration pipeline owns\n // that guarantee), so a fresh worker sends no query here — combined with a declared operations-log\n // posture, the first statement a serverless worker sends is the mutation transaction itself.\n startupReadyPromise = startupVerification === \"in-process\" ? installStartupDdl(db, registry) : Promise.resolve();\n }\n\n return startupReadyPromise;\n };\n\n // Per-mutation payload validation shared by the batch and authoritative endpoints (security: both must\n // reject client-omitted projection fields, server-managed fields, and malformed payloads before apply).\n // Logs each offender and returns the attributable 400 Response, or null when every mutation is valid.\n const validateMutationsOrRespond = async (\n mutations: BatchMutationRequest[\"mutations\"],\n requestPath: string,\n ): Promise<Response | null> => {\n const validationErrors: string[] = [];\n const invalidMutations: Array<{\n mutation: BatchMutationRequest[\"mutations\"][number];\n message: string;\n }> = [];\n\n for (const mutation of mutations) {\n if (!(mutation.tableName in registry)) {\n const message = `Unknown table: ${mutation.tableName}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const entry = registry[mutation.tableName as keyof TRegistry]!;\n const syncEntry = entry as SyncTableEntry;\n const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);\n // Surface (once per table+key) only a payload key the apply path would SILENTLY drop — a truly\n // unknown key, never a projected-away/server-only column (those are 400-rejected just below, so\n // the helper excludes them; warning \"the write succeeds\" then rejecting was the misleading overlap).\n warnOnSilentlyDroppedPayloadKeys(syncEntry, mutation.tableName, mutation.kind, normalizedPayload);\n const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (projectedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (managedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n try {\n if (mutation.kind === \"update\") {\n const payloadKeys =\n typeof normalizedPayload === \"object\" && normalizedPayload !== null\n ? Object.keys(normalizedPayload as object)\n : [];\n if (payloadKeys.length === 0) {\n throw new Error(\"At least one field must be provided\");\n }\n buildUpdateValidationSchema(syncEntry).parse(normalizedPayload);\n } else if (mutation.kind === \"create\") {\n buildCreateValidationSchema(syncEntry).parse(normalizedPayload);\n }\n // delete has no payload to validate\n } catch (error) {\n const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : \"\";\n const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n }\n }\n\n if (validationErrors.length > 0) {\n for (const invalidMutation of invalidMutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: invalidMutation.mutation.tableName,\n operationKind: invalidMutation.mutation.kind,\n entityKey: invalidMutation.mutation.entityKey,\n payload: invalidMutation.mutation.payload,\n status: \"validation_failed\",\n errorMessage: invalidMutation.message,\n httpStatus: 400,\n mutationId: invalidMutation.mutation.mutationId,\n mutationSeq: invalidMutation.mutation.mutationSeq,\n clientTimestampUs: invalidMutation.mutation.clientTimestampUs,\n requestPath: requestPath,\n });\n }\n\n // Attribute the rejection to the specific offending mutations. The batch is atomic\n // (nothing was applied), so the client can quarantine exactly these and keep the\n // innocent siblings retryable — one bad mutation never poisons the whole offline queue.\n return Response.json(\n {\n message: `Payload validation failed: ${validationErrors.join(\"; \")}`,\n rejections: invalidMutations.map(({ mutation, message }) => ({\n tableName: mutation.tableName,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n reason: message,\n })),\n },\n { status: 400 },\n );\n }\n\n return null;\n };\n\n const handleBatchMutation = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: [],\n },\n { status: 400 },\n );\n }\n\n let body: BatchMutationRequest;\n\n try {\n body = batchMutationRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid batch mutation request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const acks: MutationAck[] = [];\n let actorUserId: string | null = null;\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const batchRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n batchRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n applyInvocationOptions,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n // ADR-0015: a reject-if-stale stale write was NOT applied — the applier returned it here.\n // Surface a `conflicted` ack (distinct from a failure) carrying the row's current Server\n // version, so the client keeps the optimistic overlay and resolves it as a new write.\n const conflictByMutationId = new Map(conflicts.map((conflict) => [conflict.mutationId, conflict]));\n\n for (const mutation of batchRequest.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n\n if (conflict) {\n // #6: a null currentServerVersion means the target row no longer exists (an UPDATE whose\n // row was deleted by another writer), distinct from a stale write over a row that moved.\n const conflictReason =\n conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no ` +\n `longer exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`;\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n continue;\n }\n\n const serverUpdatedAtUs = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n const errorMessage = formatBatchExecutionError(error);\n\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage,\n httpStatus: 500,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n }\n\n return Response.json({ message: errorMessage }, { status: 500 });\n }\n\n return Response.json({ acks });\n };\n\n // ADR-0022 §3 (mechanism c): the authoritative (pessimistic) write endpoint. One write-**unit** per POST,\n // applied in its OWN isolated transaction, atomically — so a constraint/trigger exception becomes a clean\n // per-mutation `rejected` ack (the whole unit rolls back, overlays auto-discard) instead of the batch\n // path's whole-batch 500, and a stale member surfaces `conflicted` (overlays kept) without partial apply.\n const handleAuthoritativeWrite = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json({ message: \"Invalid authoritative write request\", issues: [] }, { status: 400 });\n }\n\n let body: AuthoritativeWriteRequest;\n\n try {\n body = authoritativeWriteRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid authoritative write request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json(\n {\n message: \"Invalid authoritative write request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n let actorUserId: string | null = null;\n // The unit's outcome, decided inside its OWN transaction: applied (Server versions per member) or\n // conflicted (a stale member → rolled back, overlays kept). An execution exception is handled in catch.\n let appliedServerVersions: Map<string, string | null> | null = null;\n let unitConflicts: MutationConflict[] | null = null;\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const unitRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n unitRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n applyInvocationOptions,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n if (conflicts.length > 0) {\n // The unit is atomic — a stale member means none of it applies. Roll back; report all members as\n // conflicted (overlays kept, re-resolve the unit) below.\n unitConflicts = conflicts;\n throw new UnitNotCommittedError();\n }\n\n // Applied cleanly. Read each member's resulting Server version INSIDE the txn, before it commits.\n const versions = new Map<string, string | null>();\n for (const mutation of unitRequest.mutations) {\n const version = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n versions.set(mutation.mutationId, version ?? null);\n }\n appliedServerVersions = versions;\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n if (!(error instanceof UnitNotCommittedError)) {\n // A DB-enforced invariant (capacity/quota/uniqueness constraint or trigger) declined the unit. The\n // whole unit rolled back; surface a per-mutation `rejected` ack so the client auto-discards the\n // unit's optimistic overlay (ADR-0022 §4). The ack carries a SANITISED reason — the raw DB error\n // (constraint names, offending values/PII, schema, hints) stays in the operations log only.\n const internalDetail = formatBatchExecutionError(error);\n const publicReason = toPublicRejectionReason(error);\n const rejectedAcks: MutationAck[] = [];\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage: internalDetail,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n rejectedAcks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"rejected\",\n rejectionReason: publicReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks: rejectedAcks });\n }\n // UnitNotCommittedError — `unitConflicts` is set; fall through to conflicted-ack building.\n }\n\n const acks: MutationAck[] = [];\n\n if (unitConflicts) {\n const conflictByMutationId = new Map(\n (unitConflicts as MutationConflict[]).map((conflict) => [conflict.mutationId, conflict]),\n );\n for (const mutation of body.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n const conflictReason = conflict\n ? conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no longer ` +\n `exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`\n : `Atomic write-unit not committed (ADR-0022): a sibling write in the same unit was rejected as ` +\n `stale, so this write rolled back too. Re-resolve the unit.`;\n\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict?.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks });\n }\n\n // Applied: ack every member, carrying the Server version each converged to.\n const serverVersions = appliedServerVersions ?? new Map<string, string | null>();\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n const serverUpdatedAtUs = serverVersions.get(mutation.mutationId) ?? undefined;\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n\n return Response.json({ acks });\n };\n\n return {\n batch: withTiming(\"mutations\", handleBatchMutation),\n authoritative: withTiming(\"mutations\", handleAuthoritativeWrite),\n };\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatBatchExecutionError(error: unknown): string {\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return \"Batch mutation failed\";\n }\n\n const details = [rootCause.message];\n const errorCode = getErrorStringProperty(rootCause, \"code\");\n const errorDetail = getErrorStringProperty(rootCause, \"detail\");\n const errorHint = getErrorStringProperty(rootCause, \"hint\");\n\n if (errorCode) {\n details.push(`code: ${errorCode}`);\n }\n\n if (errorDetail) {\n details.push(`detail: ${errorDetail}`);\n }\n\n if (errorHint) {\n details.push(`hint: ${errorHint}`);\n }\n\n return details.join(\" | \");\n}\n\n/**\n * Map a DB exception to a **client-safe** rejection reason for an authoritative `rejected` ack (ADR-0022 §4).\n * The raw error text (`formatBatchExecutionError`) leaks constraint names, schema/table, the offending\n * VALUES (potential PII), and trigger hints — and a `rejected` ack is success-path copy the app surfaces to\n * users, so it must not echo that. Two cases:\n *\n * - **App-authored `RAISE`** (PL/pgSQL `RAISE EXCEPTION 'cohort is full'`, SQLSTATE `P0001` / a custom `P0…`\n * class): the message IS the consumer's own user-facing copy — pass it through. This is the intended way\n * to give a friendly capacity/quota message.\n * - **Built-in integrity violations** (SQLSTATE class `23`) and everything else: return a stable generic\n * message keyed by SQLSTATE — never the raw message/detail/hint. Full detail stays in the operations log.\n */\nexport function toPublicRejectionReason(error: unknown): string {\n const fallback = \"The write was rejected by a server rule.\";\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return fallback;\n }\n\n // Resolve the SQLSTATE with the driver-agnostic helper (bun-sql — this project's runtime driver —\n // carries it on `errno`, not `code`; postgres.js / pg on `code`). Reading `error.code` directly, as\n // this did, returned bun's generic \"ERR_POSTGRES_SERVER_ERROR\" and dropped every app-authored `P0…`\n // and constraint code into the generic fallback, breaking ADR-0022's friendly rejection channel.\n // `readSqlState` walks the cause chain itself, so it runs on the ORIGINAL error; the app-authored\n // RAISE MESSAGE below still comes from the root cause.\n const code = readSqlState(error);\n\n // ADR-0030: the self-verifying apply function raises SQLSTATE 'PXS01' when its installed fingerprint\n // does not match this server's registry/codegen — the drift the deleted startup verify used to catch.\n // Surface the same actionable operator guidance the old startup error gave (it carries no PII, only the\n // regenerate-and-apply instruction), rather than the generic rejection fallback.\n if (code === \"PXS01\") {\n return (\n \"The server's apply function is out of date: its installed fingerprint does not match this \" +\n \"server's registry/codegen. Regenerate the sync-function migration (pgxsinkit-generate) and apply \" +\n \"it before serving writes.\"\n );\n }\n\n // App-authored RAISE — the message is the consumer's own copy, safe to surface.\n if (code && (code === \"P0001\" || code.startsWith(\"P0\"))) {\n return rootCause.message.trim() || fallback;\n }\n\n // Built-in integrity violations: generic, code-keyed messages only (no raw constraint names / values).\n const genericByCode: Record<string, string> = {\n \"23505\": \"This conflicts with an existing record (a uniqueness rule was violated).\",\n \"23514\": \"A validation rule rejected this write.\",\n \"23503\": \"A referenced record is missing (a relationship rule was violated).\",\n \"23502\": \"A required value was missing.\",\n \"23P01\": \"An exclusion rule rejected this write.\",\n };\n\n if (code && genericByCode[code]) {\n return genericByCode[code]!;\n }\n\n if (code && code.startsWith(\"23\")) {\n return \"A data-integrity rule rejected this write.\";\n }\n\n return fallback;\n}\n\nfunction getRootCauseError(error: unknown): Error | null {\n let current = error;\n let lastError: Error | null = null;\n const seen = new Set<unknown>();\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n lastError = current;\n current = current.cause;\n }\n\n return lastError;\n}\n\nfunction getErrorStringProperty(error: Error, key: string): string | null {\n if (!(key in error)) {\n return null;\n }\n\n const value = (error as unknown as Record<string, unknown>)[key];\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction isRlsAuthContextRequired(registry: SyncTableRegistry): boolean {\n return Object.values(registry).some(\n (entry) =>\n getTableConfig(entry.table as AnyPgTable).policies.length > 0 ||\n (entry.governance?.managedFields ?? []).some((field) => field.strategy === \"authClaim\"),\n );\n}\n\nclass UnauthorizedBatchMutationError extends Error {}\n\n/**\n * Thrown inside the authoritative write's transaction to roll the whole unit back when a member is a stale\n * write (ADR-0015) — distinct from an execution exception (a capacity/constraint rejection). The handler\n * catches it and reports every member `conflicted` (overlays kept), having committed nothing.\n */\nclass UnitNotCommittedError extends Error {}\n\nfunction getUuidClaim(claims: JwtClaims, key: string): string | null {\n const value = claims[key];\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;\n}\n\n/**\n * The server-managed payload keys a mutation must not carry — the 400 guard (see\n * {@link getGuardedManagedFields} for what counts as managed per operation, notably that a create-only\n * managed field is guarded on update too). Exported for direct unit coverage.\n */\nexport function findManagedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const managedFields = getGuardedManagedFields(entry, mutationKind);\n if (managedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);\n}\n\n// One structured warning per (table, dropped-key) per process. The apply path is hot; a memoized set\n// keeps a recurring silent-drop from spamming the log while still surfacing it once. The keys are\n// client-controlled (a malicious/buggy client can send unbounded junk keys), so the set is capped: past\n// the cap we stop memoizing AND stop warning, so the process can never accumulate unbounded entries.\nconst warnedDroppedPayloadKeys = new Set<string>();\nconst MAX_WARNED_DROPPED_KEYS = 10_000;\n// Set true after the one-time \"warnings suppressed\" notice fires, so the cap notice logs exactly once.\nlet droppedKeyWarningSuppressed = false;\n\n/**\n * Warn — **once** per (table, key) per process — when a mutation payload carries a key the apply path\n * will **silently drop**: a key that is neither a writable (projected) column, a server-managed field,\n * nor a projected-away column that request validation already 400-rejects. The generated apply function\n * reads only the table's PROJECTED columns from the payload jsonb, so such a key never lands — were it\n * \"applied\" the write would collapse to a bare server-version (`updated_at_us`) bump. This is the clean\n * two-case split (ADR-0022 posture docs):\n *\n * - **Projected-away / server-only columns** (`clientProjection.omitColumns`) sent explicitly are\n * **400-rejected** by {@link findProjectedFieldViolations} — they are NOT silently dropped, so this\n * helper deliberately does **not** warn for them (warning \"the write still succeeds\" and then\n * rejecting was the misleading overlap the review flagged).\n * - **Unknown non-column keys** (a typo, a stale field) are what the apply path silently ignores — those\n * are exactly the keys this warns about, once, as a debugging aid. It is NOT an error and changes no\n * semantics.\n *\n * Exported for direct unit coverage.\n */\nexport function warnOnSilentlyDroppedPayloadKeys(\n entry: SyncTableEntry,\n tableName: string,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): void {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return;\n }\n\n // The keys the apply path will actually write: the projected columns (what it reads from payload) plus\n // the managed fields for this operation (server-stamped, legitimately present). Both property key and\n // DB column name are accepted, so a payload keyed either way is not falsely flagged.\n const writable = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedColumns(entry)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n for (const { propertyKey, columnName } of getManagedFieldsForOperation(entry, mutationKind)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n\n // Keys request validation will 400-REJECT (an explicitly-sent projected-away / server-only column):\n // those never reach apply, so they are NOT a silent drop — exclude them so the warning is reserved for\n // truly-unknown keys the apply path drops without validation rejecting.\n const rejectedAtValidation = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedAwayFields(entry)) {\n rejectedAtValidation.add(propertyKey);\n rejectedAtValidation.add(columnName);\n }\n\n for (const key of Object.keys(payload)) {\n if (writable.has(key) || rejectedAtValidation.has(key)) {\n continue;\n }\n const memoKey = `${tableName}::${key}`;\n if (warnedDroppedPayloadKeys.has(memoKey)) {\n continue;\n }\n // Cap the memo set against client-controlled key spray: once full, emit one final suppression notice\n // and stop both memoizing and warning — the set never grows past the cap.\n if (warnedDroppedPayloadKeys.size >= MAX_WARNED_DROPPED_KEYS) {\n if (!droppedKeyWarningSuppressed) {\n droppedKeyWarningSuppressed = true;\n console.warn(\n `[pgxsinkit] Dropped-key warnings suppressed: more than ${MAX_WARNED_DROPPED_KEYS} distinct ` +\n `(table, key) pairs have been reported this process. Further dropped payload keys will not be logged.`,\n );\n }\n return;\n }\n warnedDroppedPayloadKeys.add(memoKey);\n console.warn(\n `[pgxsinkit] Payload for table \"${tableName}\" carries key \"${key}\", which is not a column of that ` +\n `table — the apply path silently ignores it (a write that reached apply would collapse to a bare ` +\n `server-version bump). This is almost always a typo or a stale field: check the spelling against ` +\n `the table's columns, or remove \"${key}\" if the schema no longer has it. (A projected-away/` +\n `server-only column would instead be 400-rejected, not dropped, so it is not what this warns about.) ` +\n `(Logged once per table+key per process.)`,\n { table: tableName, droppedKey: key, hint: \"unknown-non-column-key\" },\n );\n }\n}\n\nfunction findProjectedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const projectedFields = getProjectedAwayFields(entry);\n if (projectedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n\n return [\n ...new Set(\n projectedFields\n .filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName))\n .map((field) => field.propertyKey),\n ),\n ];\n}\n\n/**\n * Defense in depth behind the 400 guard: strip every server-owned key from each payload before apply, so\n * a caller that reaches this code path without the request-level check (or a key spelled as the DB column\n * name rather than the property key) still cannot set a managed or projected-away column. Exported for\n * direct unit coverage.\n */\nexport function sanitizeRestrictedFields(\n batch: BatchMutationRequest,\n registry: SyncTableRegistry,\n): BatchMutationRequest {\n return {\n mutations: batch.mutations.map((mutation) => {\n if (mutation.kind === \"delete\") {\n return mutation;\n }\n\n const entry = registry[mutation.tableName];\n\n if (!entry) {\n return mutation;\n }\n\n const managedFields = getGuardedManagedFields(entry as SyncTableEntry, mutation.kind);\n const projectedFields = getProjectedAwayFields(entry as SyncTableEntry);\n\n if (managedFields.length === 0 && projectedFields.length === 0) {\n return mutation;\n }\n\n const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};\n\n for (const field of managedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n for (const field of projectedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n return {\n ...mutation,\n payload,\n };\n }),\n };\n}\n\n/**\n * The zod schema used to validate a `create` payload. Managed-on-create fields (`authUid` /\n * `nowMicroseconds`) are stamped by the server AFTER validation, so the client correctly omits them —\n * and {@link findManagedFieldViolations} already rejects a payload that includes them. They are\n * omitted from the insert schema so a NOT NULL managed column without a SQL DEFAULT (e.g. an `authUid`\n * author/owner/created_by) is not falsely required. (A column carrying a DEFAULT is already optional\n * in the drizzle insert schema; this also covers a managed column that has none.)\n */\nexport function buildCreateValidationSchema(entry: SyncTableEntry) {\n const createSchema = createMutationInsertSchema(entry.table as AnyPgTable);\n const managedCreateKeys = getGuardedManagedFields(entry, \"create\").map((field) => field.propertyKey);\n if (managedCreateKeys.length === 0) {\n return createSchema;\n }\n // The omit-mask keys are derived from governance at runtime, so they cannot be narrowed to the\n // schema's literal-key mask type — cast through the parameter type.\n const omitMask = Object.fromEntries(managedCreateKeys.map((key) => [key, true as const])) as Parameters<\n typeof createSchema.omit\n >[0];\n return createSchema.omit(omitMask);\n}\n\n/**\n * The zod schema used to validate an `update` payload: the insert schema made `partial()` (an update is a\n * patch — only the sent keys are validated), minus every server-managed key. This is the update-side\n * counterpart of {@link buildCreateValidationSchema}: a field managed on update is stamped by the server,\n * and a **create-only** managed field is inert on update (the generated apply function omits it from the\n * UPDATE SET candidates), so neither is a settable key of an update payload. Both are already\n * 400-rejected by {@link findManagedFieldViolations}; omitting them keeps the schema an accurate\n * statement of what an update may carry.\n */\nexport function buildUpdateValidationSchema(\n entry: SyncTableEntry,\n): ReturnType<ReturnType<typeof createMutationInsertSchema<AnyPgTable>>[\"partial\"]> {\n const updateSchema = createMutationInsertSchema(entry.table as AnyPgTable).partial();\n const managedKeys = getGuardedManagedFields(entry, \"update\").map((field) => field.propertyKey);\n if (managedKeys.length === 0) {\n return updateSchema;\n }\n const omitMask = Object.fromEntries(managedKeys.map((key) => [key, true as const])) as Parameters<\n typeof updateSchema.omit\n >[0];\n return updateSchema.omit(omitMask);\n}\n\nfunction getManagedFields(\n entry: SyncTableEntry,\n matches: (field: { applyOn: readonly ManagedFieldApplyOn[] }) => boolean,\n) {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? [])\n .filter((field) => matches(field))\n .map((field) => ({\n propertyKey: field.column,\n columnName: columnMap.get(field.column) ?? field.column,\n strategy: field.strategy,\n }));\n}\n\nfunction getManagedFieldsForOperation(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n if (mutationKind === \"delete\") {\n return [];\n }\n\n return getManagedFields(entry, (field) => field.applyOn.includes(mutationKind));\n}\n\n/**\n * The fields the request-path guards treat as **server-owned** for `mutationKind` — the one set the\n * violation check flags, the sanitizer strips, and the validation schema omits. This resolves the\n * governance specs to `{ propertyKey, columnName, strategy }`; WHICH of them are server-owned is not\n * decided here but by contracts' {@link isManagedFieldGuarded}, the single definition of the guard rule\n * (shared with the client's `stripManagedFields` and the apply-function generator).\n */\nfunction getGuardedManagedFields(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n return getManagedFields(entry, (field) => isManagedFieldGuarded(field, mutationKind));\n}\n\nfunction getProjectedAwayFields(entry: SyncTableEntry) {\n return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({\n propertyKey,\n columnName,\n }));\n}\n\nfunction toSchemaPayload(entry: SyncTableEntry, payload: unknown): unknown {\n if (!isPlainObject(payload)) {\n return payload;\n }\n\n const columns = getColumns(entry.table as AnyPgTable);\n const keyMap = new Map<string, string>();\n\n for (const [propertyKey, column] of Object.entries(columns)) {\n keyMap.set(propertyKey, propertyKey);\n keyMap.set(column.name, propertyKey);\n }\n\n return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));\n}\n\nfunction resolveServerUpdatedAtColumnName(entry: SyncTableEntry): string {\n // The single source for the Server version column (ADR-0010 / ADR-0004): resolves the\n // managed field's property key to its column name. Falls back to the conventional name for\n // resilience, though registry validation now guarantees a writable table declares one.\n return resolveServerVersionColumnName(entry) ?? \"updated_at_us\";\n}\n\nasync function readServerUpdatedAtUs(\n tx: RouteReadQueryClient,\n entry: SyncTableEntry,\n entityKey: Record<string, string>,\n): Promise<string | undefined> {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnName = resolveServerUpdatedAtColumnName(entry);\n const updatedAtColumn = Object.values(columns).find((column) => column.name === columnName);\n\n if (!updatedAtColumn) {\n return undefined;\n }\n\n const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {\n const rawValue = entityKey[primaryKeyColumn];\n\n if (rawValue === undefined) {\n throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);\n }\n\n const primaryKeyTableColumn = Object.values(columns).find((column) => column.name === primaryKeyColumn);\n\n if (!primaryKeyTableColumn) {\n throw new Error(`Missing table column metadata for primary key column ${primaryKeyColumn}`);\n }\n\n return eq(primaryKeyTableColumn, rawValue);\n });\n\n const whereClause = conditions.length === 1 ? conditions[0]! : and(...conditions);\n const rows = await tx\n .select({ updatedAtUs: sql<string>`${updatedAtColumn}::text` })\n .from(entry.table as AnyPgTable)\n .where(whereClause)\n .limit(1);\n\n return rows[0]?.updatedAtUs ?? undefined;\n}\n\n// ADR-0030: the apply-function drift verify is gone from startup — the function verifies itself in-body\n// (SQLSTATE 'PXS01'). The only remaining boot-time check is the RLS auth-helper presence, and only when\n// the registry actually needs it. Reached only under `startupVerification: \"in-process\"`.\nasync function installStartupDdl<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n): Promise<void> {\n if (isRlsAuthContextRequired(registry)) {\n await verifyRlsAuthHelpers(db);\n }\n}\n",
15
+ "import { and, type AnyRelations, eq, sql } from \"drizzle-orm\";\nimport { type AnyPgTable, getTableConfig } from \"drizzle-orm/pg-core\";\nimport type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\nimport { createSchemaFactory } from \"drizzle-orm/zod\";\n\nimport type {\n AuthoritativeWriteRequest,\n BatchMutationRequest,\n JwtClaims,\n ManagedFieldApplyOn,\n MutationAck,\n RegistryRelations,\n SyncTableEntry,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport {\n authoritativeWriteRequestSchema,\n batchMutationRequestSchema,\n getOmittedProjectedColumns as getOmittedProjectionColumns,\n getProjectedColumns,\n isManagedFieldGuarded,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport type { OperationsLogConfig } from \"../operations-log/types\";\nimport { logOperation, logOperationSafely } from \"../operations-log/writer\";\nimport type { FetchHandler } from \"../router\";\nimport { readSqlState } from \"../sql-state\";\nimport {\n type ApplyFunctionRenderOptions,\n executePlpgsqlBatch,\n expectedApplyFingerprint,\n type MutationConflict,\n resolveApplyFunctionSchema,\n verifyRlsAuthHelpers,\n} from \"./plpgsql-apply\";\nimport type { TransactionClient } from \"./types\";\n\n/**\n * How the write path handles its remaining startup query class — the RLS auth-helper verify (ADR-0030\n * decision 3). The apply-function drift guarantee moved into the call itself (self-verifying function),\n * so this now governs ONLY that helper check:\n * - `\"in-process\"` (default): keep today's boot-time `verifyRlsAuthHelpers` and its clear startup error.\n * - `\"deploy-time\"`: skip it — the migration pipeline owns that guarantee, so a fresh (serverless)\n * worker sends ZERO queries before the mutation transaction itself.\n */\nexport type StartupVerificationMode = \"in-process\" | \"deploy-time\";\n\nconst { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({\n // Mutation payloads cross a JSON boundary, so bigint-mode Drizzle columns arrive as decimal strings.\n // Coerce only while validating; the original JSON payload remains string-valued for the SQL apply path.\n coerce: { date: true, bigint: true },\n});\n\ntype RouteReadQueryClient = Pick<PgAsyncDatabase<PgQueryResultHKT, AnyRelations>, \"select\">;\n\nexport const batchMutationPaths = [\"/api/mutations\"] as const;\n/** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */\nexport const authoritativeMutationPaths = [\"/api/mutations/unit\"] as const;\n\nexport function createMutationHandler<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n operationsLogConfig: OperationsLogConfig,\n operationsLogReady: Promise<void>,\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null,\n startupVerification: StartupVerificationMode = \"in-process\",\n logTimings = false,\n // ADR-0054: the roles the installed artifact was generated with. The ACL is INSIDE the fingerprinted\n // body, so the expected fingerprint below is only reproducible when this matches the generate flags.\n applyFunctionGrantExecuteTo: readonly string[] = [],\n // The schema the installed artifact was generated into (`pgxsinkit-generate --function-schema`).\n // It is BOTH a fingerprint input (the body embeds the qualified name) and the name this server must\n // CALL, so one value drives both — a server that knows the fingerprint but calls the function\n // unqualified would resolve through `search_path` and, in the usual case, find nothing.\n applyFunctionSchema?: string,\n): { batch: FetchHandler; authoritative: FetchHandler } {\n let startupReadyPromise: Promise<void> | undefined;\n\n const applyFunctionRenderOptions: ApplyFunctionRenderOptions = {\n ...(applyFunctionGrantExecuteTo.length > 0 ? { grantExecuteTo: applyFunctionGrantExecuteTo } : {}),\n ...(applyFunctionSchema ? { functionSchema: applyFunctionSchema } : {}),\n };\n // Validated once here (the same rule the renderer applies) rather than per request, so a bad schema\n // name fails at server construction instead of on the first write.\n const resolvedApplyFunctionSchema = resolveApplyFunctionSchema(applyFunctionRenderOptions.functionSchema);\n const applyInvocationOptions = resolvedApplyFunctionSchema ? { functionSchema: resolvedApplyFunctionSchema } : {};\n\n // ADR-0030: the fingerprint this server expects for its registry + applier codegen, computed ONCE per\n // server instance. Every `executePlpgsqlBatch` passes it so the installed apply function can verify\n // itself in-body (SQLSTATE 'PXS01' on drift) — this replaces the deleted startup verify.\n const expectedFingerprint = expectedApplyFingerprint(registry, applyFunctionRenderOptions);\n\n // Per-request timing scratch (opt-in). authMs/applyMs are filled at the narrow phase call sites inside\n // the handler; totalMs + status are measured by `withTiming` wrapping the returned handler. A fresh\n // object per request keeps this concurrency-safe without threading state through the handler internals.\n const perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n interface RequestTiming {\n handlerStart: number;\n preTxMs: number;\n txOpenMs: number;\n authMs: number;\n applyMs: number;\n mutations: number;\n }\n const withTiming = (route: string, handler: (request: Request, timing?: RequestTiming) => Promise<Response>) => {\n if (!logTimings) {\n return (request: Request) => handler(request);\n }\n return async (request: Request): Promise<Response> => {\n const start = perfNow();\n const timing: RequestTiming = {\n handlerStart: start,\n preTxMs: 0,\n txOpenMs: 0,\n authMs: 0,\n applyMs: 0,\n mutations: 0,\n };\n const response = await handler(request, timing);\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route,\n preTxMs: Math.round(timing.preTxMs),\n txOpenMs: Math.round(timing.txOpenMs),\n authMs: Math.round(timing.authMs),\n applyMs: Math.round(timing.applyMs),\n totalMs: Math.round(perfNow() - start),\n mutations: timing.mutations,\n status: response.status,\n }),\n );\n return response;\n };\n };\n // Stamp the two spans the phase timers cannot see: preTxMs = handler entry → transaction call\n // (parse + zod validation), txOpenMs = transaction call → callback entry (the driver's LAZY\n // connection establishment + BEGIN — on serverless this is where a fresh worker's pooler\n // TLS/DNS cost lands, invisible to authMs/applyMs).\n const stampPreTx = (timing: RequestTiming | undefined) => {\n if (timing) timing.preTxMs = perfNow() - timing.handlerStart;\n return timing ? perfNow() : 0;\n };\n const stampTxOpen = (timing: RequestTiming | undefined, txCallAt: number) => {\n if (timing) timing.txOpenMs = perfNow() - txCallAt;\n };\n\n const startupReady = () => {\n if (!startupReadyPromise) {\n // ADR-0030: \"deploy-time\" skips the boot-time RLS auth-helper verify (the migration pipeline owns\n // that guarantee), so a fresh worker sends no query here — combined with a declared operations-log\n // posture, the first statement a serverless worker sends is the mutation transaction itself.\n startupReadyPromise = startupVerification === \"in-process\" ? installStartupDdl(db, registry) : Promise.resolve();\n }\n\n return startupReadyPromise;\n };\n\n // Per-mutation payload validation shared by the batch and authoritative endpoints (security: both must\n // reject client-omitted projection fields, server-managed fields, and malformed payloads before apply).\n // Logs each offender and returns the attributable 400 Response, or null when every mutation is valid.\n const validateMutationsOrRespond = async (\n mutations: BatchMutationRequest[\"mutations\"],\n requestPath: string,\n ): Promise<Response | null> => {\n const validationErrors: string[] = [];\n const invalidMutations: Array<{\n mutation: BatchMutationRequest[\"mutations\"][number];\n message: string;\n }> = [];\n\n for (const mutation of mutations) {\n if (!(mutation.tableName in registry)) {\n const message = `Unknown table: ${mutation.tableName}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const entry = registry[mutation.tableName as keyof TRegistry]!;\n const syncEntry = entry as SyncTableEntry;\n const normalizedPayload = toSchemaPayload(syncEntry, mutation.payload);\n // Surface (once per table+key) only a payload key the apply path would SILENTLY drop — a truly\n // unknown key, never a projected-away/server-only column (those are 400-rejected just below, so\n // the helper excludes them; warning \"the write succeeds\" then rejecting was the misleading overlap).\n warnOnSilentlyDroppedPayloadKeys(syncEntry, mutation.tableName, mutation.kind, normalizedPayload);\n const projectedFieldViolations = findProjectedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (projectedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes client-omitted fields: ${projectedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n const managedFieldViolations = findManagedFieldViolations(syncEntry, mutation.kind, normalizedPayload);\n\n if (managedFieldViolations.length > 0) {\n const message = `${mutation.tableName}/${mutation.mutationId} includes server-managed fields: ${managedFieldViolations.join(\", \")}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n continue;\n }\n\n try {\n if (mutation.kind === \"update\") {\n const payloadKeys =\n typeof normalizedPayload === \"object\" && normalizedPayload !== null\n ? Object.keys(normalizedPayload as object)\n : [];\n if (payloadKeys.length === 0) {\n throw new Error(\"At least one field must be provided\");\n }\n buildUpdateValidationSchema(syncEntry).parse(normalizedPayload);\n } else if (mutation.kind === \"create\") {\n buildCreateValidationSchema(syncEntry).parse(normalizedPayload);\n }\n // delete has no payload to validate\n } catch (error) {\n const suffix = isValidationError(error) ? ` (${JSON.stringify(error.issues)})` : \"\";\n const message = `${mutation.tableName}/${mutation.mutationId}${suffix}`;\n validationErrors.push(message);\n invalidMutations.push({ mutation, message });\n }\n }\n\n if (validationErrors.length > 0) {\n for (const invalidMutation of invalidMutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: invalidMutation.mutation.tableName,\n operationKind: invalidMutation.mutation.kind,\n entityKey: invalidMutation.mutation.entityKey,\n payload: invalidMutation.mutation.payload,\n status: \"validation_failed\",\n errorMessage: invalidMutation.message,\n httpStatus: 400,\n mutationId: invalidMutation.mutation.mutationId,\n mutationSeq: invalidMutation.mutation.mutationSeq,\n clientTimestampUs: invalidMutation.mutation.clientTimestampUs,\n requestPath: requestPath,\n });\n }\n\n // Attribute the rejection to the specific offending mutations. The batch is atomic\n // (nothing was applied), so the client can quarantine exactly these and keep the\n // innocent siblings retryable — one bad mutation never poisons the whole offline queue.\n return Response.json(\n {\n message: `Payload validation failed: ${validationErrors.join(\"; \")}`,\n rejections: invalidMutations.map(({ mutation, message }) => ({\n tableName: mutation.tableName,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n reason: message,\n })),\n },\n { status: 400 },\n );\n }\n\n return null;\n };\n\n const handleBatchMutation = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: [],\n },\n { status: 400 },\n );\n }\n\n let body: BatchMutationRequest;\n\n try {\n body = batchMutationRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid batch mutation request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n\n return Response.json(\n {\n message: \"Invalid batch mutation request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const acks: MutationAck[] = [];\n let actorUserId: string | null = null;\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const batchRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n batchRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n applyInvocationOptions,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n // ADR-0015: a reject-if-stale stale write was NOT applied — the applier returned it here.\n // Surface a `conflicted` ack (distinct from a failure) carrying the row's current Server\n // version, so the client keeps the optimistic overlay and resolves it as a new write.\n const conflictByMutationId = new Map(conflicts.map((conflict) => [conflict.mutationId, conflict]));\n\n for (const mutation of batchRequest.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n\n if (conflict) {\n // #6: a null currentServerVersion means the target row no longer exists (an UPDATE whose\n // row was deleted by another writer), distinct from a stale write over a row that moved.\n const conflictReason =\n conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no ` +\n `longer exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`;\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n continue;\n }\n\n const serverUpdatedAtUs = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n\n await logOperation(tx, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n const errorMessage = formatBatchExecutionError(error);\n\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage,\n httpStatus: 500,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n }\n\n return Response.json({ message: errorMessage }, { status: 500 });\n }\n\n return Response.json({ acks });\n };\n\n // ADR-0022 §3 (mechanism c): the authoritative (pessimistic) write endpoint. One write-**unit** per POST,\n // applied in its OWN isolated transaction, atomically — so a constraint/trigger exception becomes a clean\n // per-mutation `rejected` ack (the whole unit rolls back, overlays auto-discard) instead of the batch\n // path's whole-batch 500, and a stale member surfaces `conflicted` (overlays kept) without partial apply.\n const handleAuthoritativeWrite = async (request: Request, timing?: RequestTiming): Promise<Response> => {\n await Promise.all([startupReady(), operationsLogReady]);\n\n const requestPath = new URL(request.url).pathname;\n let rawBody: unknown;\n\n try {\n rawBody = await request.json();\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: null,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid JSON request body\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json({ message: \"Invalid authoritative write request\", issues: [] }, { status: 400 });\n }\n\n let body: AuthoritativeWriteRequest;\n\n try {\n body = authoritativeWriteRequestSchema.parse(rawBody);\n } catch (error) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: error instanceof Error ? error.message : \"Invalid authoritative write request\",\n httpStatus: 400,\n requestPath: requestPath,\n });\n return Response.json(\n {\n message: \"Invalid authoritative write request\",\n issues: isValidationError(error) ? error.issues : [],\n },\n { status: 400 },\n );\n }\n\n const invalidResponse = await validateMutationsOrRespond(body.mutations, requestPath);\n if (invalidResponse) {\n return invalidResponse;\n }\n\n if (timing) timing.mutations = body.mutations.length;\n\n const rlsAuthContextRequired = isRlsAuthContextRequired(registry);\n let actorUserId: string | null = null;\n // The unit's outcome, decided inside its OWN transaction: applied (Server versions per member) or\n // conflicted (a stale member → rolled back, overlays kept). An execution exception is handled in catch.\n let appliedServerVersions: Map<string, string | null> | null = null;\n let unitConflicts: MutationConflict[] | null = null;\n\n try {\n const txCallAt = stampPreTx(timing);\n await db.transaction(async (tx) => {\n stampTxOpen(timing, txCallAt);\n const shouldApplyRlsContext = rlsAuthContextRequired;\n let userClaims: Record<string, unknown> = {};\n\n if (shouldApplyRlsContext) {\n const authStart = timing ? perfNow() : 0;\n const resolvedClaims = await resolveAuthClaims?.(request);\n if (timing) timing.authMs = perfNow() - authStart;\n\n if (!isPlainObject(resolvedClaims)) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: null,\n operationKind: null,\n entityKey: null,\n payload: rawBody,\n status: \"validation_failed\",\n errorMessage: \"Missing validated JWT claims for RLS-enabled tables\",\n httpStatus: 401,\n requestPath: requestPath,\n });\n\n throw new UnauthorizedBatchMutationError(\n \"RLS-enabled tables require validated JWT claims in request context\",\n );\n }\n\n userClaims = resolvedClaims;\n actorUserId = getUuidClaim(userClaims, \"sub\");\n }\n\n const unitRequest = sanitizeRestrictedFields(body, registry);\n await tx.execute(sql`SET CONSTRAINTS ALL DEFERRED`);\n\n const applyStart = timing ? perfNow() : 0;\n const conflicts = await executePlpgsqlBatch(\n tx as unknown as TransactionClient,\n unitRequest,\n requestPath,\n false,\n shouldApplyRlsContext,\n userClaims,\n expectedFingerprint,\n applyInvocationOptions,\n );\n if (timing) timing.applyMs = perfNow() - applyStart;\n\n if (shouldApplyRlsContext) {\n await tx.execute(sql`RESET ROLE`);\n }\n\n if (conflicts.length > 0) {\n // The unit is atomic — a stale member means none of it applies. Roll back; report all members as\n // conflicted (overlays kept, re-resolve the unit) below.\n unitConflicts = conflicts;\n throw new UnitNotCommittedError();\n }\n\n // Applied cleanly. Read each member's resulting Server version INSIDE the txn, before it commits.\n const versions = new Map<string, string | null>();\n for (const mutation of unitRequest.mutations) {\n const version = await readServerUpdatedAtUs(\n tx,\n registry[mutation.tableName as keyof TRegistry] as SyncTableEntry,\n mutation.entityKey,\n );\n versions.set(mutation.mutationId, version ?? null);\n }\n appliedServerVersions = versions;\n });\n } catch (error) {\n if (error instanceof UnauthorizedBatchMutationError) {\n return Response.json({ message: error.message }, { status: 401 });\n }\n\n if (!(error instanceof UnitNotCommittedError)) {\n // A DB-enforced invariant (capacity/quota/uniqueness constraint or trigger) declined the unit. The\n // whole unit rolled back; surface a per-mutation `rejected` ack so the client auto-discards the\n // unit's optimistic overlay (ADR-0022 §4). The ack carries a SANITISED reason — the raw DB error\n // (constraint names, offending values/PII, schema, hints) stays in the operations log only.\n const internalDetail = formatBatchExecutionError(error);\n const publicReason = toPublicRejectionReason(error);\n const rejectedAcks: MutationAck[] = [];\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"execution_failed\",\n errorMessage: internalDetail,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n rejectedAcks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"rejected\",\n rejectionReason: publicReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks: rejectedAcks });\n }\n // UnitNotCommittedError — `unitConflicts` is set; fall through to conflicted-ack building.\n }\n\n const acks: MutationAck[] = [];\n\n if (unitConflicts) {\n const conflictByMutationId = new Map(\n (unitConflicts as MutationConflict[]).map((conflict) => [conflict.mutationId, conflict]),\n );\n for (const mutation of body.mutations) {\n const conflict = conflictByMutationId.get(mutation.mutationId);\n const conflictReason = conflict\n ? conflict.currentServerVersion == null\n ? `Update rejected by the reject-if-stale conflict policy (ADR-0015): the target row no longer ` +\n `exists on the server (deleted by another writer after this write was authored).`\n : `Stale write rejected by the reject-if-stale conflict policy (ADR-0015): the row's current ` +\n `server version ${conflict.currentServerVersion} is ahead of the base ` +\n `${mutation.baseServerVersion ?? \"(unknown)\"} this write was authored against.`\n : `Atomic write-unit not committed (ADR-0022): a sibling write in the same unit was rejected as ` +\n `stale, so this write rolled back too. Re-resolve the unit.`;\n\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"conflicted\",\n errorMessage: conflictReason,\n httpStatus: 409,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"conflicted\",\n ...(conflict?.currentServerVersion ? { serverUpdatedAtUs: conflict.currentServerVersion } : {}),\n conflictReason,\n httpStatus: 409,\n });\n }\n return Response.json({ acks });\n }\n\n // Applied: ack every member, carrying the Server version each converged to.\n const serverVersions = appliedServerVersions ?? new Map<string, string | null>();\n for (const mutation of body.mutations) {\n await logOperationSafely(db, operationsLogConfig, {\n tableName: mutation.tableName,\n operationKind: mutation.kind,\n entityKey: mutation.entityKey,\n payload: mutation.payload,\n status: \"succeeded\",\n httpStatus: 200,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n clientTimestampUs: mutation.clientTimestampUs,\n requestPath: requestPath,\n userId: actorUserId,\n });\n const serverUpdatedAtUs = serverVersions.get(mutation.mutationId) ?? undefined;\n acks.push({\n tableName: mutation.tableName,\n entityKey: mutation.entityKey,\n mutationId: mutation.mutationId,\n mutationSeq: mutation.mutationSeq,\n status: \"acked\",\n ...(serverUpdatedAtUs ? { serverUpdatedAtUs } : {}),\n });\n }\n\n return Response.json({ acks });\n };\n\n return {\n batch: withTiming(\"mutations\", handleBatchMutation),\n authoritative: withTiming(\"mutations\", handleAuthoritativeWrite),\n };\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatBatchExecutionError(error: unknown): string {\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return \"Batch mutation failed\";\n }\n\n const details = [rootCause.message];\n const errorCode = getErrorStringProperty(rootCause, \"code\");\n const errorDetail = getErrorStringProperty(rootCause, \"detail\");\n const errorHint = getErrorStringProperty(rootCause, \"hint\");\n\n if (errorCode) {\n details.push(`code: ${errorCode}`);\n }\n\n if (errorDetail) {\n details.push(`detail: ${errorDetail}`);\n }\n\n if (errorHint) {\n details.push(`hint: ${errorHint}`);\n }\n\n return details.join(\" | \");\n}\n\n/**\n * Map a DB exception to a **client-safe** rejection reason for an authoritative `rejected` ack (ADR-0022 §4).\n * The raw error text (`formatBatchExecutionError`) leaks constraint names, schema/table, the offending\n * VALUES (potential PII), and trigger hints — and a `rejected` ack is success-path copy the app surfaces to\n * users, so it must not echo that. Two cases:\n *\n * - **App-authored `RAISE`** (PL/pgSQL `RAISE EXCEPTION 'cohort is full'`, SQLSTATE `P0001` / a custom `P0…`\n * class): the message IS the consumer's own user-facing copy — pass it through. This is the intended way\n * to give a friendly capacity/quota message.\n * - **Built-in integrity violations** (SQLSTATE class `23`) and everything else: return a stable generic\n * message keyed by SQLSTATE — never the raw message/detail/hint. Full detail stays in the operations log.\n */\nexport function toPublicRejectionReason(error: unknown): string {\n const fallback = \"The write was rejected by a server rule.\";\n const rootCause = getRootCauseError(error);\n\n if (!rootCause) {\n return fallback;\n }\n\n // Resolve the SQLSTATE with the driver-agnostic helper (bun-sql — this project's runtime driver —\n // carries it on `errno`, not `code`; postgres.js / pg on `code`). Reading `error.code` directly, as\n // this did, returned bun's generic \"ERR_POSTGRES_SERVER_ERROR\" and dropped every app-authored `P0…`\n // and constraint code into the generic fallback, breaking ADR-0022's friendly rejection channel.\n // `readSqlState` walks the cause chain itself, so it runs on the ORIGINAL error; the app-authored\n // RAISE MESSAGE below still comes from the root cause.\n const code = readSqlState(error);\n\n // ADR-0030: the self-verifying apply function raises SQLSTATE 'PXS01' when its installed fingerprint\n // does not match this server's registry/codegen — the drift the deleted startup verify used to catch.\n // Surface the same actionable operator guidance the old startup error gave (it carries no PII, only the\n // regenerate-and-apply instruction), rather than the generic rejection fallback.\n if (code === \"PXS01\") {\n return (\n \"The server's apply function is out of date: its installed fingerprint does not match this \" +\n \"server's registry/codegen. Regenerate the sync-function migration (pgxsinkit-generate) and apply \" +\n \"it before serving writes.\"\n );\n }\n\n // App-authored RAISE — the message is the consumer's own copy, safe to surface.\n if (code && (code === \"P0001\" || code.startsWith(\"P0\"))) {\n return rootCause.message.trim() || fallback;\n }\n\n // Built-in integrity violations: generic, code-keyed messages only (no raw constraint names / values).\n const genericByCode: Record<string, string> = {\n \"23505\": \"This conflicts with an existing record (a uniqueness rule was violated).\",\n \"23514\": \"A validation rule rejected this write.\",\n \"23503\": \"A referenced record is missing (a relationship rule was violated).\",\n \"23502\": \"A required value was missing.\",\n \"23P01\": \"An exclusion rule rejected this write.\",\n };\n\n if (code && genericByCode[code]) {\n return genericByCode[code]!;\n }\n\n if (code && code.startsWith(\"23\")) {\n return \"A data-integrity rule rejected this write.\";\n }\n\n return fallback;\n}\n\nfunction getRootCauseError(error: unknown): Error | null {\n let current = error;\n let lastError: Error | null = null;\n const seen = new Set<unknown>();\n\n while (current instanceof Error && !seen.has(current)) {\n seen.add(current);\n lastError = current;\n current = current.cause;\n }\n\n return lastError;\n}\n\nfunction getErrorStringProperty(error: Error, key: string): string | null {\n if (!(key in error)) {\n return null;\n }\n\n const value = (error as unknown as Record<string, unknown>)[key];\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction isRlsAuthContextRequired(registry: SyncTableRegistry): boolean {\n return Object.values(registry).some(\n (entry) =>\n getTableConfig(entry.table as AnyPgTable).policies.length > 0 ||\n (entry.governance?.managedFields ?? []).some((field) => field.strategy === \"authClaim\"),\n );\n}\n\nclass UnauthorizedBatchMutationError extends Error {}\n\n/**\n * Thrown inside the authoritative write's transaction to roll the whole unit back when a member is a stale\n * write (ADR-0015) — distinct from an execution exception (a capacity/constraint rejection). The handler\n * catches it and reports every member `conflicted` (overlays kept), having committed nothing.\n */\nclass UnitNotCommittedError extends Error {}\n\nfunction getUuidClaim(claims: JwtClaims, key: string): string | null {\n const value = claims[key];\n\n if (typeof value !== \"string\") {\n return null;\n }\n\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;\n}\n\n/**\n * The server-managed payload keys a mutation must not carry — the 400 guard (see\n * {@link getGuardedManagedFields} for what counts as managed per operation, notably that a create-only\n * managed field is guarded on update too). Exported for direct unit coverage.\n */\nexport function findManagedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const managedFields = getGuardedManagedFields(entry, mutationKind);\n if (managedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n return managedFields.filter((field) => payloadKeys.has(field.propertyKey)).map((field) => field.propertyKey);\n}\n\n// One structured warning per (table, dropped-key) per process. The apply path is hot; a memoized set\n// keeps a recurring silent-drop from spamming the log while still surfacing it once. The keys are\n// client-controlled (a malicious/buggy client can send unbounded junk keys), so the set is capped: past\n// the cap we stop memoizing AND stop warning, so the process can never accumulate unbounded entries.\nconst warnedDroppedPayloadKeys = new Set<string>();\nconst MAX_WARNED_DROPPED_KEYS = 10_000;\n// Set true after the one-time \"warnings suppressed\" notice fires, so the cap notice logs exactly once.\nlet droppedKeyWarningSuppressed = false;\n\n/**\n * Warn — **once** per (table, key) per process — when a mutation payload carries a key the apply path\n * will **silently drop**: a key that is neither a writable (projected) column, a server-managed field,\n * nor a projected-away column that request validation already 400-rejects. The generated apply function\n * reads only the table's PROJECTED columns from the payload jsonb, so such a key never lands — were it\n * \"applied\" the write would collapse to a bare server-version (`updated_at_us`) bump. This is the clean\n * two-case split (ADR-0022 posture docs):\n *\n * - **Projected-away / server-only columns** (`clientProjection.omitColumns`) sent explicitly are\n * **400-rejected** by {@link findProjectedFieldViolations} — they are NOT silently dropped, so this\n * helper deliberately does **not** warn for them (warning \"the write still succeeds\" and then\n * rejecting was the misleading overlap the review flagged).\n * - **Unknown non-column keys** (a typo, a stale field) are what the apply path silently ignores — those\n * are exactly the keys this warns about, once, as a debugging aid. It is NOT an error and changes no\n * semantics.\n *\n * Exported for direct unit coverage.\n */\nexport function warnOnSilentlyDroppedPayloadKeys(\n entry: SyncTableEntry,\n tableName: string,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): void {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return;\n }\n\n // The keys the apply path will actually write: the projected columns (what it reads from payload) plus\n // the managed fields for this operation (server-stamped, legitimately present). Both property key and\n // DB column name are accepted, so a payload keyed either way is not falsely flagged.\n const writable = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedColumns(entry)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n for (const { propertyKey, columnName } of getManagedFieldsForOperation(entry, mutationKind)) {\n writable.add(propertyKey);\n writable.add(columnName);\n }\n\n // Keys request validation will 400-REJECT (an explicitly-sent projected-away / server-only column):\n // those never reach apply, so they are NOT a silent drop — exclude them so the warning is reserved for\n // truly-unknown keys the apply path drops without validation rejecting.\n const rejectedAtValidation = new Set<string>();\n for (const { propertyKey, columnName } of getProjectedAwayFields(entry)) {\n rejectedAtValidation.add(propertyKey);\n rejectedAtValidation.add(columnName);\n }\n\n for (const key of Object.keys(payload)) {\n if (writable.has(key) || rejectedAtValidation.has(key)) {\n continue;\n }\n const memoKey = `${tableName}::${key}`;\n if (warnedDroppedPayloadKeys.has(memoKey)) {\n continue;\n }\n // Cap the memo set against client-controlled key spray: once full, emit one final suppression notice\n // and stop both memoizing and warning — the set never grows past the cap.\n if (warnedDroppedPayloadKeys.size >= MAX_WARNED_DROPPED_KEYS) {\n if (!droppedKeyWarningSuppressed) {\n droppedKeyWarningSuppressed = true;\n console.warn(\n `[pgxsinkit] Dropped-key warnings suppressed: more than ${MAX_WARNED_DROPPED_KEYS} distinct ` +\n `(table, key) pairs have been reported this process. Further dropped payload keys will not be logged.`,\n );\n }\n return;\n }\n warnedDroppedPayloadKeys.add(memoKey);\n console.warn(\n `[pgxsinkit] Payload for table \"${tableName}\" carries key \"${key}\", which is not a column of that ` +\n `table — the apply path silently ignores it (a write that reached apply would collapse to a bare ` +\n `server-version bump). This is almost always a typo or a stale field: check the spelling against ` +\n `the table's columns, or remove \"${key}\" if the schema no longer has it. (A projected-away/` +\n `server-only column would instead be 400-rejected, not dropped, so it is not what this warns about.) ` +\n `(Logged once per table+key per process.)`,\n { table: tableName, droppedKey: key, hint: \"unknown-non-column-key\" },\n );\n }\n}\n\nfunction findProjectedFieldViolations(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n payload: unknown,\n): string[] {\n if (mutationKind === \"delete\" || !isPlainObject(payload)) {\n return [];\n }\n\n const projectedFields = getProjectedAwayFields(entry);\n if (projectedFields.length === 0) {\n return [];\n }\n\n const payloadKeys = new Set(Object.keys(payload));\n\n return [\n ...new Set(\n projectedFields\n .filter((field) => payloadKeys.has(field.propertyKey) || payloadKeys.has(field.columnName))\n .map((field) => field.propertyKey),\n ),\n ];\n}\n\n/**\n * Defense in depth behind the 400 guard: strip every server-owned key from each payload before apply, so\n * a caller that reaches this code path without the request-level check (or a key spelled as the DB column\n * name rather than the property key) still cannot set a managed or projected-away column. Exported for\n * direct unit coverage.\n */\nexport function sanitizeRestrictedFields(\n batch: BatchMutationRequest,\n registry: SyncTableRegistry,\n): BatchMutationRequest {\n return {\n mutations: batch.mutations.map((mutation) => {\n if (mutation.kind === \"delete\") {\n return mutation;\n }\n\n const entry = registry[mutation.tableName];\n\n if (!entry) {\n return mutation;\n }\n\n const managedFields = getGuardedManagedFields(entry as SyncTableEntry, mutation.kind);\n const projectedFields = getProjectedAwayFields(entry as SyncTableEntry);\n\n if (managedFields.length === 0 && projectedFields.length === 0) {\n return mutation;\n }\n\n const payload = isPlainObject(mutation.payload) ? { ...mutation.payload } : {};\n\n for (const field of managedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n for (const field of projectedFields) {\n delete payload[field.propertyKey];\n delete payload[field.columnName];\n }\n\n return {\n ...mutation,\n payload,\n };\n }),\n };\n}\n\n/**\n * The zod schema used to validate a `create` payload. Managed-on-create fields (`authUid` /\n * `nowMicroseconds`) are stamped by the server AFTER validation, so the client correctly omits them —\n * and {@link findManagedFieldViolations} already rejects a payload that includes them. They are\n * omitted from the insert schema so a NOT NULL managed column without a SQL DEFAULT (e.g. an `authUid`\n * author/owner/created_by) is not falsely required. (A column carrying a DEFAULT is already optional\n * in the drizzle insert schema; this also covers a managed column that has none.)\n */\nexport function buildCreateValidationSchema(entry: SyncTableEntry) {\n const createSchema = createMutationInsertSchema(entry.table as AnyPgTable);\n const managedCreateKeys = getGuardedManagedFields(entry, \"create\").map((field) => field.propertyKey);\n if (managedCreateKeys.length === 0) {\n return createSchema;\n }\n // The omit-mask keys are derived from governance at runtime, so they cannot be narrowed to the\n // schema's literal-key mask type — cast through the parameter type.\n const omitMask = Object.fromEntries(managedCreateKeys.map((key) => [key, true as const])) as Parameters<\n typeof createSchema.omit\n >[0];\n return createSchema.omit(omitMask);\n}\n\n/**\n * The zod schema used to validate an `update` payload: the insert schema made `partial()` (an update is a\n * patch — only the sent keys are validated), minus every server-managed key. This is the update-side\n * counterpart of {@link buildCreateValidationSchema}: a field managed on update is stamped by the server,\n * and a **create-only** managed field is inert on update (the generated apply function omits it from the\n * UPDATE SET candidates), so neither is a settable key of an update payload. Both are already\n * 400-rejected by {@link findManagedFieldViolations}; omitting them keeps the schema an accurate\n * statement of what an update may carry.\n */\nexport function buildUpdateValidationSchema(\n entry: SyncTableEntry,\n): ReturnType<ReturnType<typeof createMutationInsertSchema<AnyPgTable>>[\"partial\"]> {\n const updateSchema = createMutationInsertSchema(entry.table as AnyPgTable).partial();\n const managedKeys = getGuardedManagedFields(entry, \"update\").map((field) => field.propertyKey);\n if (managedKeys.length === 0) {\n return updateSchema;\n }\n const omitMask = Object.fromEntries(managedKeys.map((key) => [key, true as const])) as Parameters<\n typeof updateSchema.omit\n >[0];\n return updateSchema.omit(omitMask);\n}\n\nfunction getManagedFields(\n entry: SyncTableEntry,\n matches: (field: { applyOn: readonly ManagedFieldApplyOn[] }) => boolean,\n) {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? [])\n .filter((field) => matches(field))\n .map((field) => ({\n propertyKey: field.column,\n columnName: columnMap.get(field.column) ?? field.column,\n strategy: field.strategy,\n }));\n}\n\nfunction getManagedFieldsForOperation(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n if (mutationKind === \"delete\") {\n return [];\n }\n\n return getManagedFields(entry, (field) => field.applyOn.includes(mutationKind));\n}\n\n/**\n * The fields the request-path guards treat as **server-owned** for `mutationKind` — the one set the\n * violation check flags, the sanitizer strips, and the validation schema omits. This resolves the\n * governance specs to `{ propertyKey, columnName, strategy }`; WHICH of them are server-owned is not\n * decided here but by contracts' {@link isManagedFieldGuarded}, the single definition of the guard rule\n * (shared with the client's `stripManagedFields` and the apply-function generator).\n */\nfunction getGuardedManagedFields(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n return getManagedFields(entry, (field) => isManagedFieldGuarded(field, mutationKind));\n}\n\nfunction getProjectedAwayFields(entry: SyncTableEntry) {\n return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({\n propertyKey,\n columnName,\n }));\n}\n\nfunction toSchemaPayload(entry: SyncTableEntry, payload: unknown): unknown {\n if (!isPlainObject(payload)) {\n return payload;\n }\n\n const columns = getColumns(entry.table as AnyPgTable);\n const keyMap = new Map<string, string>();\n\n for (const [propertyKey, column] of Object.entries(columns)) {\n keyMap.set(propertyKey, propertyKey);\n keyMap.set(column.name, propertyKey);\n }\n\n return Object.fromEntries(Object.entries(payload).map(([key, value]) => [keyMap.get(key) ?? key, value]));\n}\n\nfunction resolveServerUpdatedAtColumnName(entry: SyncTableEntry): string {\n // The single source for the Server version column (ADR-0010 / ADR-0004): resolves the\n // managed field's property key to its column name. Falls back to the conventional name for\n // resilience, though registry validation now guarantees a writable table declares one.\n return resolveServerVersionColumnName(entry) ?? \"updated_at_us\";\n}\n\nasync function readServerUpdatedAtUs(\n tx: RouteReadQueryClient,\n entry: SyncTableEntry,\n entityKey: Record<string, string>,\n): Promise<string | undefined> {\n const columns = getColumns(entry.table as AnyPgTable);\n const columnName = resolveServerUpdatedAtColumnName(entry);\n const updatedAtColumn = Object.values(columns).find((column) => column.name === columnName);\n\n if (!updatedAtColumn) {\n return undefined;\n }\n\n const conditions = entry.primaryKey.columns.map((primaryKeyColumn) => {\n const rawValue = entityKey[primaryKeyColumn];\n\n if (rawValue === undefined) {\n throw new Error(`Missing entity key value for primary key column ${primaryKeyColumn}`);\n }\n\n const primaryKeyTableColumn = Object.values(columns).find((column) => column.name === primaryKeyColumn);\n\n if (!primaryKeyTableColumn) {\n throw new Error(`Missing table column metadata for primary key column ${primaryKeyColumn}`);\n }\n\n return eq(primaryKeyTableColumn, rawValue);\n });\n\n const whereClause = conditions.length === 1 ? conditions[0]! : and(...conditions);\n const rows = await tx\n .select({ updatedAtUs: sql<string>`${updatedAtColumn}::text` })\n .from(entry.table as AnyPgTable)\n .where(whereClause)\n .limit(1);\n\n return rows[0]?.updatedAtUs ?? undefined;\n}\n\n// ADR-0030: the apply-function drift verify is gone from startup — the function verifies itself in-body\n// (SQLSTATE 'PXS01'). The only remaining boot-time check is the RLS auth-helper presence, and only when\n// the registry actually needs it. Reached only under `startupVerification: \"in-process\"`.\nasync function installStartupDdl<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n): Promise<void> {\n if (isRlsAuthContextRequired(registry)) {\n await verifyRlsAuthHelpers(db);\n }\n}\n",
16
16
  "import { bigint, bigserial, index, integer, jsonb, pgTable, text, timestamp, uuid, varchar } from \"drizzle-orm/pg-core\";\n\nimport { clockMicrosecondsSql } from \"@pgxsinkit/contracts\";\n\nexport const operationsLogTable = pgTable(\n \"operations_log\",\n {\n id: bigserial(\"id\", { mode: \"number\" }).primaryKey(),\n tableName: varchar(\"table_name\", { length: 255 }),\n operationKind: varchar(\"operation_kind\", { length: 24 }),\n userId: uuid(\"user_id\"),\n entityKeyJson: jsonb(\"entity_key_json\"),\n payloadJson: jsonb(\"payload_json\"),\n status: varchar(\"status\", { length: 32 }).notNull(),\n errorMessage: text(\"error_message\"),\n httpStatus: integer(\"http_status\"),\n // Text, NOT uuid: derived child envelopes (the expander tier) carry composite non-UUID ids of the\n // form `${parentMutationId}:<tag>:<n>`, so the log column must accept any string the apply path may\n // record. This is the server-side tier of the two-tier mutation-id invariant (see plpgsql-apply.ts\n // and packages/contracts/src/mutation.ts): the apply function + this log accept opaque text for a\n // direct caller deriving children, while pgxsinkit's public surface (route schemas, client journal)\n // stays UUID-only. (The ::uuid casts on this id were dropped for the same reason.)\n mutationId: text(\"mutation_id\"),\n mutationSeq: integer(\"mutation_seq\"),\n clientTimestampUs: bigint(\"client_timestamp_us\", { mode: \"bigint\" }),\n requestPath: text(\"request_path\"),\n serverTimestampUs: bigint(\"server_timestamp_us\", { mode: \"bigint\" }).notNull().default(clockMicrosecondsSql),\n createdAt: timestamp(\"created_at\", { mode: \"date\", withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index(\"operations_log_created_at_idx\").on(table.createdAt.desc()),\n index(\"operations_log_table_name_idx\").on(table.tableName),\n index(\"operations_log_user_id_idx\").on(table.userId),\n index(\"operations_log_status_idx\").on(table.status),\n index(\"operations_log_mutation_id_idx\").on(table.mutationId),\n ],\n);\n\nexport type OperationsLogRow = typeof operationsLogTable.$inferSelect;\nexport type NewOperationsLogRow = typeof operationsLogTable.$inferInsert;\n",
17
- "import { operationsLogTable } from \"./schema\";\nimport type { OpsLogEntry, OperationsLogConfig, SqlExecutor } from \"./types\";\n\nfunction toJsonValue(value: unknown): unknown {\n if (value === undefined) {\n return null;\n }\n\n return value;\n}\n\nfunction toBigIntValue(value: string | null | undefined): bigint | null {\n if (value === undefined || value === null) {\n return null;\n }\n\n return BigInt(value);\n}\n\nexport async function logOperation(\n executor: SqlExecutor,\n config: OperationsLogConfig,\n entry: OpsLogEntry,\n): Promise<void> {\n if (!config.enabled) {\n return;\n }\n\n await executor.insert(operationsLogTable).values({\n tableName: entry.tableName ?? null,\n operationKind: entry.operationKind ?? null,\n userId: entry.userId ?? null,\n entityKeyJson: toJsonValue(entry.entityKey ?? null),\n payloadJson: toJsonValue(entry.payload),\n status: entry.status,\n errorMessage: entry.errorMessage ?? null,\n httpStatus: entry.httpStatus ?? null,\n mutationId: entry.mutationId ?? null,\n mutationSeq: entry.mutationSeq ?? null,\n clientTimestampUs: toBigIntValue(entry.clientTimestampUs),\n requestPath: entry.requestPath ?? null,\n });\n}\n\nexport async function logOperationSafely(\n executor: SqlExecutor,\n config: OperationsLogConfig,\n entry: OpsLogEntry,\n): Promise<void> {\n try {\n await logOperation(executor, config, entry);\n } catch {\n // Failure-path logging must not hide the original route response/error.\n }\n}\n",
17
+ "import { operationsLogTable } from \"./schema\";\nimport type { OperationsLogConfig, OpsLogEntry, SqlExecutor } from \"./types\";\n\nfunction toJsonValue(value: unknown): unknown {\n if (value === undefined) {\n return null;\n }\n\n return value;\n}\n\nfunction toBigIntValue(value: string | null | undefined): bigint | null {\n if (value === undefined || value === null) {\n return null;\n }\n\n return BigInt(value);\n}\n\nexport async function logOperation(\n executor: SqlExecutor,\n config: OperationsLogConfig,\n entry: OpsLogEntry,\n): Promise<void> {\n if (!config.enabled) {\n return;\n }\n\n await executor.insert(operationsLogTable).values({\n tableName: entry.tableName ?? null,\n operationKind: entry.operationKind ?? null,\n userId: entry.userId ?? null,\n entityKeyJson: toJsonValue(entry.entityKey ?? null),\n payloadJson: toJsonValue(entry.payload),\n status: entry.status,\n errorMessage: entry.errorMessage ?? null,\n httpStatus: entry.httpStatus ?? null,\n mutationId: entry.mutationId ?? null,\n mutationSeq: entry.mutationSeq ?? null,\n clientTimestampUs: toBigIntValue(entry.clientTimestampUs),\n requestPath: entry.requestPath ?? null,\n });\n}\n\nexport async function logOperationSafely(\n executor: SqlExecutor,\n config: OperationsLogConfig,\n entry: OpsLogEntry,\n): Promise<void> {\n try {\n await logOperation(executor, config, entry);\n } catch {\n // Failure-path logging must not hide the original route response/error.\n }\n}\n",
18
18
  "/**\n * Read the Postgres `SQLSTATE` (the five-character error class, e.g. `\"23505\"` unique_violation) off a\n * thrown database error.\n *\n * **Why this helper exists — the bun-sql gotcha.** Bun's built-in `SQL`/`sql` driver (what pgxsinkit and\n * its consumers run against Postgres) surfaces the server's SQLSTATE on the error's **`errno`** property.\n * Its **`code`** property is bun's own generic string (`\"ERR_POSTGRES_SERVER_ERROR\"`), NOT the SQLSTATE —\n * so the intuitive `error.code` read (which worked under `postgres.js` / `pg`, where `code` carried the\n * SQLSTATE) silently returns the wrong thing under bun-sql. Consumers reaching for a stable, driver-agnostic\n * SQLSTATE (to map `23505`→\"already exists\", `P0001`→a raised app rule, etc.) kept re-deriving this by hand;\n * this is the one canonical extraction.\n *\n * Resolution order, returning the first well-formed SQLSTATE found:\n * 1. `errno` on the error (bun-sql),\n * 2. `code` on the error (postgres.js / node-postgres, and any driver that follows that convention),\n * 3. the same two properties walked down the `cause` chain (a wrapped/re-thrown error).\n *\n * A \"well-formed\" SQLSTATE is exactly five characters of `[0-9A-Z]` — this is what rejects bun's generic\n * `code` string, an `errno` that is a numeric OS errno, and any other non-SQLSTATE noise. A non-object\n * error (string, number, `null`, `undefined`) yields `undefined`.\n */\nexport function readSqlState(error: unknown): string | undefined {\n // Guard against a self-referential (or pathologically deep) `cause` chain — walk a bounded number of\n // links, never a `while (true)`.\n const MAX_CAUSE_DEPTH = 16;\n\n let current: unknown = error;\n for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth++) {\n if (!current || typeof current !== \"object\") {\n return undefined;\n }\n\n const candidate = current as { errno?: unknown; code?: unknown; cause?: unknown };\n\n // bun-sql: SQLSTATE on `errno`. postgres.js / pg: SQLSTATE on `code`. Prefer `errno`, fall back to\n // `code`, and accept only a value that is actually shaped like a SQLSTATE.\n const fromErrno = asSqlState(candidate.errno);\n if (fromErrno !== undefined) {\n return fromErrno;\n }\n const fromCode = asSqlState(candidate.code);\n if (fromCode !== undefined) {\n return fromCode;\n }\n\n // Not on this error — descend into a wrapped cause (Error.cause / a driver's nested original error).\n if (candidate.cause === current) {\n return undefined;\n }\n current = candidate.cause;\n }\n\n return undefined;\n}\n\n/** A value is a SQLSTATE only if it is a string of exactly five `[0-9A-Z]` characters. */\nfunction asSqlState(value: unknown): string | undefined {\n return typeof value === \"string\" && /^[0-9A-Z]{5}$/u.test(value) ? value : undefined;\n}\n",
19
- "import { getTableName, sql } from \"drizzle-orm\";\nimport { getTableConfig, type AnyPgTable, type PgAsyncDatabase, type PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\n\nimport {\n buildRoleGuardedStatement,\n CLOCK_US_CALL_SQL_TEXT,\n escapeSqlLiteral as toSqlLiteral,\n getProjectedColumns,\n hashString,\n isManagedFieldGuarded,\n quoteIdentifier as quoteIdent,\n resolveServerVersionColumnName,\n type BatchMutationRequest,\n type ManagedFieldApplyOn,\n type RegistryRelations,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { TransactionClient } from \"./types\";\n\nfunction qualifyIdent(schemaName: string | undefined, name: string): string {\n if (!schemaName) {\n return quoteIdent(name);\n }\n\n return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;\n}\n\nfunction toSqlTextOrNull(value: string): string {\n return value.length > 0 ? `'${toSqlLiteral(value)}'` : \"NULL\";\n}\n\n/**\n * The array dimensionality Drizzle records for a column (0 = scalar). It is carried SEPARATELY from\n * `getSQLType()`, which returns the ELEMENT type for an array column (`uuid` for a `uuid[]`) — reading\n * only the type string is what silently emitted a scalar cast for an array column and killed every\n * non-null array write with 22P02.\n */\nfunction columnDimensions(column: { dimensions?: number }): number {\n return column.dimensions ?? 0;\n}\n\n/**\n * The SQL expression that reads one writable column out of a mutation's payload (`x.p`), by column\n * name and Drizzle type. It is embedded in the branch's `(col_name, col_value)` candidate list and\n * substituted verbatim into the INSERT/UPDATE `format()` template at runtime.\n *\n * Scalars keep the long-standing `(x.p->>'col')::type` form. A one-dimensional array column expands\n * the JSON array element-wise and applies the terminal `::<element>[]` cast, which IS the type check\n * (no element-type allowlist: an element the target type cannot accept raises, exactly as a scalar\n * cast does). The three payload shapes match the scalar semantics exactly:\n *\n * - **absent key** — never reaches here (the branch intersects the candidate list with the group's\n * payload signature, so an unsent column is not in the statement at all);\n * - **JSON null** — `jsonb_typeof` is `'null'`, the CASE has no ELSE ⇒ SQL NULL, mirroring\n * `(x.p->>'col')::type` on a JSON null;\n * - **`[]`** — an empty typed array, NOT NULL (an empty list is a value the client meant to write).\n *\n * Element order is pinned with `WITH ORDINALITY … ORDER BY`, so the stored array order is the\n * client's array order by construction rather than by set-returning-function evaluation order.\n * A JSON null ELEMENT becomes a SQL NULL element (`jsonb_array_elements_text` semantics) — except for\n * the JSON element types, see below.\n *\n * The one branch inside the array branch is the ELEMENT type: `json`/`jsonb` elements expand with\n * `jsonb_array_elements` (the JSON-valued expansion), never `jsonb_array_elements_text`. Text expansion\n * of a JSON element STRIPS its JSON quoting, which is silent type corruption for a `jsonb[]`: the element\n * `\"123\"` (a JSON string) re-parses as the JSON NUMBER `123`, and `\"hi\"` fails the cast outright with\n * `invalid input syntax for type json`. `jsonb_array_elements` preserves each element VERBATIM, so a JSON\n * null element stays a JSON null value (`jsonb_typeof(e) = 'null'`, not SQL NULL) — the faithful reading\n * for a JSON-typed element, and what round-trips back to the client unchanged. The column-level shapes\n * (absent key / JSON null / `[]`) are identical to the text branch.\n */\nfunction buildPayloadValueExpression(\n tableName: string,\n column: { name: string; getSQLType: () => string; dimensions?: number },\n): string {\n const columnLiteral = `'${toSqlLiteral(column.name)}'`;\n const dimensions = columnDimensions(column);\n const sqlType = column.getSQLType();\n\n if (dimensions === 0) {\n return `(x.p->>${columnLiteral})::${sqlType}`;\n }\n\n if (dimensions > 1) {\n // Loud at GENERATE time, never a silently wrong cast: a multi-dimensional array cannot be\n // reconstructed from a flat element expansion, and Postgres additionally requires every\n // sub-array to be the same length — a validity rule this renderer cannot express.\n throw new Error(\n `plpgsql apply generator: column ${tableName}.${column.name} is a ${dimensions}-dimensional array; ` +\n `multi-dimensional arrays are not supported by the apply function (use a single-dimension array, ` +\n `or a jsonb column)`,\n );\n }\n\n // A `json`/`jsonb` ELEMENT type must keep its JSON value (quoting included); every other element type\n // is reconstructed from the element's TEXT rendering, which is what the terminal `::<type>[]` cast reads.\n const elementExpansion = isJsonElementType(sqlType) ? \"jsonb_array_elements\" : \"jsonb_array_elements_text\";\n\n return (\n `CASE WHEN jsonb_typeof(x.p->${columnLiteral}) = 'array' THEN ` +\n `ARRAY(SELECT e FROM ${elementExpansion}(x.p->${columnLiteral}) WITH ORDINALITY AS a(e, ord) ORDER BY ord)` +\n `::${sqlType}[] END`\n );\n}\n\n/** `json` / `jsonb` — the element types whose VALUE (not text rendering) must survive the expansion. */\nfunction isJsonElementType(sqlType: string): boolean {\n const normalized = sqlType.trim().toLowerCase();\n return normalized === \"json\" || normalized === \"jsonb\";\n}\n\n/** One `(column name, payload value expression)` row of a branch's runtime candidate list. */\nfunction toColumnCandidateRow(tableName: string, column: { name: string; getSQLType: () => string }): string {\n return `('${toSqlLiteral(column.name)}', '${toSqlLiteral(buildPayloadValueExpression(tableName, column))}')`;\n}\n\ninterface ResolvedManagedField {\n propertyKey: string;\n columnName: string;\n applyOn: readonly ManagedFieldApplyOn[];\n strategy: \"nowMicroseconds\" | \"authClaim\";\n claimPath?: string[];\n cast?: string;\n columnSqlType: string;\n}\n\n// The single claim-stamping strategy (ADR-0026): `authClaim` reads the verified request claim at its JSON\n// path — `auth.uid()` is just `{ claimPath: [\"sub\"], cast: \"uuid\" }`, so there is one mechanism. The path\n// segments are validated plain identifiers at registry build, so the `'{a,b}'` text-array literal is\n// injection-safe; `current_setting('request.jwt.claims', …)` is set by this function before the apply DML\n// (it is what RLS reads), NULLIF guards an unset GUC (an absent claim stamps NULL, never errors), and the\n// cast defaults to the target column's own SQL type so a `uuid` column needs no explicit cast.\nfunction buildManagedFieldExpression(field: ResolvedManagedField): string {\n if (field.strategy === \"authClaim\") {\n const path = (field.claimPath ?? []).join(\",\");\n const castType = field.cast ?? field.columnSqlType;\n return `(NULLIF(current_setting('request.jwt.claims', true), '')::jsonb #>> '{${path}}')::${castType}`;\n }\n\n // Call the canonical microsecond-clock DB function, never inline the expression. The rendered\n // artifact therefore DEPENDS on the utilities function (public.pgxsinkit_clock_us()): the utilities\n // migration (renderPgxsinkitUtilitiesMigration) must precede this artifact in any consumer's chain.\n // The ADR-0030 fingerprint recomputes from this rendered text, so a change to the call form is\n // coordinated through the normal regenerate-and-commit flow.\n return CLOCK_US_CALL_SQL_TEXT;\n}\n\n// Every managed field of the entry, resolved to its SQL column name and type. The two consumers slice it\n// differently and the distinction is load-bearing: STAMPING is operation-scoped (`applyOn.includes(op)`)\n// and decides what the applier writes, while GUARDING (contracts' `isManagedFieldGuarded`) decides which\n// columns a client payload may never move, and so which are excluded from the candidate lists below.\nfunction resolveManagedFields(entry: SyncTableEntry): ResolvedManagedField[] {\n const tableName = getTableName(entry.table as AnyPgTable);\n const columns = getColumns(entry.table as AnyPgTable);\n const columnNameMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? []).flatMap((field) => {\n const columnName = columnNameMap.get(field.column);\n if (!columnName) {\n return [];\n }\n\n const column =\n (columns as Record<string, { getSQLType: () => string; dimensions?: number } | undefined>)[field.column] ??\n Object.values(columns).find((candidate) => candidate.name === field.column);\n\n if (column && columnDimensions(column) > 0) {\n // Both stamping strategies produce a SCALAR (a microsecond clock read, or one claim at a JSON\n // path), so an array-typed managed column could only ever be assigned a scalar — a type error at\n // every write. Refuse at generate time instead.\n throw new Error(\n `plpgsql apply generator: managed field ${tableName}.${columnName} is an array column; ` +\n `managed fields stamp a single scalar value and are not supported on array columns`,\n );\n }\n\n return [\n {\n propertyKey: field.column,\n columnName,\n applyOn: field.applyOn,\n strategy: field.strategy,\n ...(field.claimPath ? { claimPath: field.claimPath } : {}),\n ...(field.cast ? { cast: field.cast } : {}),\n columnSqlType: column?.getSQLType() ?? \"text\",\n },\n ];\n });\n}\n\nfunction buildTableBranch(entry: SyncTableEntry): string {\n const tableName = getTableName(entry.table as AnyPgTable);\n const { schema } = getTableConfig(entry.table as AnyPgTable);\n const qualifiedTableName = qualifyIdent(schema, tableName);\n const columns = getColumns(entry.table as AnyPgTable);\n const projectedColumns = getProjectedColumns(entry);\n // The canonical Entity identity is the full server primary-key tuple, by column name with\n // typed values (ADR-0012): the applier matches update/delete over EVERY pk column. Keying on\n // only the first column (the old `columns[0]`) matched too many rows on a composite-PK table.\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const columnObject = Object.values(columns).find((column) => column.name === columnName);\n if (!columnObject) {\n // Hard error, not a silent `text` fallback: an unmatched PK column means the primaryKey spec\n // has drifted from the table (e.g. a rename) — a generated applier keyed on a mistyped tuple\n // would mis-match rows at apply time.\n throw new Error(\n `plpgsql apply generator: primary key column ${columnName} not found on table ${tableName}; ` +\n `the entry's primaryKey spec has drifted from its Drizzle table`,\n );\n }\n if (columnDimensions(columnObject) > 0) {\n // The canonical identity is carried as typed recordset columns and as `(x.k->>'col')::type`\n // join predicates — both scalar forms. An array PK would need array equality semantics the\n // entity-key wire shape (a JSON object of scalar strings) cannot express, so refuse it here\n // rather than emit a cast that would raise 22P02 on the first update/delete.\n throw new Error(\n `plpgsql apply generator: primary key column ${tableName}.${columnName} is an array column; ` +\n `array columns are not supported as primary keys by the apply function`,\n );\n }\n return { name: columnName, type: columnObject.getSQLType() };\n });\n const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));\n\n const managedFields = resolveManagedFields(entry);\n // STAMPING sets — operation-scoped: what the applier itself writes (the INSERT column/value fragments\n // and the UPDATE managed-assignment fragment below).\n const createManagedFields = managedFields.filter((field) => field.applyOn.includes(\"create\"));\n const updateManagedFields = managedFields.filter((field) => field.applyOn.includes(\"update\"));\n // EXCLUSION sets — the guard rule, from contracts' single definition: a column that is server-owned for\n // the operation is not a candidate a client payload key can move. On create that is the create-managed\n // columns (the applier stamps them itself); on update it is EVERY managed column, so a create-only\n // field (`applyOn: [\"create\"]`, e.g. an `authClaim` owner) is inert thereafter, and an update-managed\n // one is assigned by the static managed-assignment fragment instead.\n const createGuardedColumnNames = new Set(\n managedFields.filter((field) => isManagedFieldGuarded(field, \"create\")).map((field) => field.columnName),\n );\n const updateGuardedColumnNames = new Set(\n managedFields.filter((field) => isManagedFieldGuarded(field, \"update\")).map((field) => field.columnName),\n );\n\n // Each candidate row carries the column's NAME and its fully-rendered payload value EXPRESSION.\n // The expression is precomputed here (rather than `format()`-ed from a type at runtime) because it\n // is no longer uniform: an array column needs an element-wise expansion, not a `->>` cast.\n const allColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !createGuardedColumnNames.has(column.name))\n .map((column) => toColumnCandidateRow(tableName, column))\n .join(\",\\n \");\n\n const nonPrimaryKeyColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !primaryKeyColumnNames.has(column.name) && !updateGuardedColumnNames.has(column.name))\n .map((column) => toColumnCandidateRow(tableName, column))\n .join(\",\\n \");\n\n const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(\", \");\n const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field)).join(\", \");\n // ADR-0010: the Server version (the nowMicroseconds-on-update managed field) must be strictly\n // monotonic per row, so its on-update stamp is floored at the previous value + 1 — it can never\n // repeat or step backwards under wall-clock (NTP) skew, which would let a stale echo clear an\n // optimistic write early. The bare column on the RHS of an UPDATE SET is the pre-update value.\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n const updateManagedAssignmentsSql = updateManagedFields\n .map((field) => {\n const expression =\n field.strategy === \"nowMicroseconds\" && field.columnName === serverVersionColumn\n ? `GREATEST(${buildManagedFieldExpression(field)}, ${quoteIdent(field.columnName)} + 1)`\n : buildManagedFieldExpression(field);\n return `${quoteIdent(field.columnName)} = ${expression}`;\n })\n .join(\", \");\n\n // Set-based apply (ADR-0014 Phase 4): one statement per (table, kind, payload column-set) group,\n // over the group's rows materialised by jsonb_to_recordset. The PK match spans the full tuple\n // (ADR-0012): DELETE matches the recordset's typed PK columns directly; UPDATE matches each row's\n // entity key carried as `x.k` jsonb. Safe from the same-PK `UPDATE … FROM` join hazard because the\n // Per-entity flush serialization invariant leaves at most one mutation per entity in a batch.\n const pkRecordDef = primaryKeyColumns.map((pk) => `${quoteIdent(pk.name)} ${pk.type}`).join(\", \");\n const pkDeleteJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = x.${quoteIdent(pk.name)}`)\n .join(\" AND \");\n const pkUpdateJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = (x.k->>'${toSqlLiteral(pk.name)}')::${pk.type}`)\n .join(\" AND \");\n\n // Templates the runtime format() fills with the per-group column list. Single quotes are doubled\n // because these are embedded as PL/pgSQL string literals.\n const insertTemplate =\n `INSERT INTO ${qualifiedTableName} (%s) SELECT %s FROM jsonb_to_recordset($1) AS x(p jsonb)`.replace(/'/g, \"''\");\n const updateTemplate =\n `UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb) WHERE ${pkUpdateJoin}`.replace(\n /'/g,\n \"''\",\n );\n const deleteSql =\n `DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}) WHERE ${pkDeleteJoin}`.replace(\n /'/g,\n \"''\",\n );\n\n // The create/update column fragments come from the group signature (∩ writable columns) plus the\n // static managed fields. An empty intersection ⇒ NULL fragment ⇒ a managed-only statement (the\n // Server version still bumps on a PK-only update, exactly as the per-mutation path did).\n const createColumnSelect = allColumnPairs.length\n ? `SELECT\n string_agg(quote_ident(col_name), ', ' ORDER BY col_name),\n string_agg(col_value, ', ' ORDER BY col_name)\n INTO v_cols, v_vals\n FROM (VALUES\n ${allColumnPairs}\n ) AS col_types(col_name, col_value)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_cols := NULL; v_vals := NULL;`;\n\n const updateSetSelect = nonPrimaryKeyColumnPairs.length\n ? `SELECT string_agg(format('%I = %s', col_name, col_value), ', ' ORDER BY col_name)\n INTO v_set\n FROM (VALUES\n ${nonPrimaryKeyColumnPairs}\n ) AS col_types(col_name, col_value)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_set := NULL;`;\n\n const createBranch = `\n ${createColumnSelect}\n\n dml_sql := format(\n '${insertTemplate}',\n concat_ws(', ', nullif(v_cols, ''), ${toSqlTextOrNull(createManagedColumnsSql)}),\n concat_ws(', ', nullif(v_vals, ''), ${toSqlTextOrNull(createManagedValuesSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n // ADR-0015: a `reject-if-stale` table compares each targeted row's current Server version to the\n // mutation's Base server version (`x.b`). `current > base` ⇒ stale (an external write interleaved):\n // the row is NOT applied, and the conflict (mutation id + the row's current Server version) is\n // collected for the handler to turn into a `conflicted` ack. `last-write-wins` keeps today's apply\n // (now a named choice). The policy is known here at DDL-generation time, so each table emits the SQL\n // its policy needs; a create has no base (its conflict is a PK collision), so it is unchanged.\n // #6: an UPDATE whose target row is MISSING (deleted by another writer after authoring) is also a\n // conflict ('target row no longer exists', `currentServerVersion` NULL) — otherwise the edit would\n // silently no-op and ack as success. A DELETE of a missing row stays idempotent success (the user\n // wanted it gone), so the delete branch keeps its inner join and does not report missing targets.\n const serverVersionRef = serverVersionColumn ? quoteIdent(serverVersionColumn) : null;\n const rejectIfStale = entry.conflictPolicy === \"reject-if-stale\" && serverVersionRef != null;\n // For the missing-target conflict (ADR-0015 #6): a LEFT JOIN whose right side is absent leaves the\n // first PK column NULL. The Server version is NOT NULL on any existing writable row, so a NULL\n // `currentServerVersion` in a returned conflict means exactly \"the target row no longer exists\".\n const firstPkRef = quoteIdent(primaryKeyColumns[0]!.name);\n\n // The conflict-collect SELECT and the staleness guard need the base + mutation id alongside each\n // row, so reject-if-stale carries them in the recordset (`b bigint, m text`). The mutation id is\n // `text` (not `uuid`): a derived child envelope's id is a composite non-UUID string, and a `m uuid`\n // recordset column would raise 22P02 the moment such a write is stale.\n const conflictObjectSql = (alias: string) =>\n `jsonb_build_object('mutationId', ${alias}.m, 'tableName', '${toSqlLiteral(tableName)}', 'currentServerVersion', t.${serverVersionRef})`;\n\n const updateBranch = rejectIfStale\n ? `\n ${updateSetSelect}\n\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) LEFT JOIN ${qualifiedTableName} AS t ON ${pkUpdateJoin} WHERE t.${firstPkRef} IS NULL OR (x.b IS NOT NULL AND t.${serverVersionRef} > x.b)`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n dml_sql := format(\n '${`UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) WHERE ${pkUpdateJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n ${updateSetSelect}\n\n dml_sql := format(\n '${updateTemplate}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n const deleteBranch = rejectIfStale\n ? `\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) JOIN ${qualifiedTableName} AS t ON ${pkDeleteJoin} WHERE x.b IS NOT NULL AND t.${serverVersionRef} > x.b`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n EXECUTE '${`DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) WHERE ${pkDeleteJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}' USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n EXECUTE '${deleteSql}' USING (\n SELECT COALESCE(jsonb_agg(elem->'entityKey'), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n return `\n ELSIF v_table = '${toSqlLiteral(tableName)}' THEN\n IF v_kind = 'create' THEN\n ${createBranch}\n ELSIF v_kind = 'update' THEN\n ${updateBranch}\n ELSIF v_kind = 'delete' THEN\n ${deleteBranch}\n ELSE\n RAISE EXCEPTION 'Unsupported mutation kind \"%\" for table \"%\"', v_kind, v_table;\n END IF;\n `.trim();\n}\n\nconst APPLY_FUNCTION_NAME = \"pgxsinkit_apply_mutations\";\n// ADR-0030: the trailing `text` is `p_expected_fingerprint` — the running server passes the fingerprint\n// it expects for its registry + codegen, and the function verifies itself against its stamped comment\n// before touching any table.\nconst APPLY_FUNCTION_ARG_TYPES = \"jsonb, text, boolean, boolean, jsonb, text\";\n// ADR-0018: the prefix namespaces the strict fingerprint format. Any absent or different prefix is\n// an identity mismatch and the apply function refuses the write.\nconst APPLY_FINGERPRINT_PREFIX = \"pgxsinkit:fp1:\";\n\n/**\n * The roles Supabase's `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS` re-grants at every CREATE\n * (ADR-0054). The artifact's `DROP FUNCTION` makes each install a fresh creation, so these grants come\n * BACK on every regenerate — hence an unconditional revoke per install, not a one-off hardening.\n */\nconst SUPABASE_DEFAULT_PRIVILEGE_ROLES = [\"anon\", \"authenticated\", \"service_role\"] as const;\n\n/**\n * How the generated apply function is rendered. Both fields are part of the artifact's IDENTITY: they\n * change the fingerprinted body, so a change to either forces the regenerate-and-commit flow, and the\n * SERVER must be configured with the same values (it recomputes the expected fingerprint at runtime).\n */\nexport interface ApplyFunctionRenderOptions {\n /** Schema to qualify the function with. Default: unqualified (resolved through `search_path`). */\n functionSchema?: string;\n /**\n * Roles that receive `GRANT EXECUTE` on the apply function (ADR-0054 decision 2). Default `[]` —\n * **owner-only**, which is right whenever the server connects as the function's owner or a\n * superuser. Name ONLY server roles: the function trusts the `p_user_claims` it is handed, so a\n * granted role can pass any claims it likes. The grant list IS the write path's trust boundary.\n */\n grantExecuteTo?: readonly string[];\n}\n\n/** An unquoted-safe SQL role name: what `GRANT … TO <role>` may name without surprises. */\nconst GRANT_ROLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * Validate a `functionSchema` — the ONE definition, shared by the renderer (which qualifies the emitted\n * DDL with it) and by the running server (`applyFunctionSchema`, which must qualify its invocation the\n * same way and recompute the same fingerprint). A schema name reaches SQL as a quoted identifier, so the\n * rule is the same plain-identifier rule role names get: an unusable name is refused loudly at generate\n * / server-construction time rather than producing an artifact nobody can call.\n *\n * Returns `undefined` for an absent schema — the default, an unqualified name resolved through\n * `search_path`.\n */\nexport function resolveApplyFunctionSchema(functionSchema: string | undefined): string | undefined {\n if (functionSchema === undefined) {\n return undefined;\n }\n if (typeof functionSchema !== \"string\" || functionSchema.trim().length === 0) {\n throw new Error(\"plpgsql apply generator: functionSchema is empty\");\n }\n if (!GRANT_ROLE_NAME_PATTERN.test(functionSchema)) {\n throw new Error(\n `plpgsql apply generator: functionSchema '${functionSchema}' is not a plain SQL identifier ` +\n `(letters, digits, '_' and '$', not starting with a digit)`,\n );\n }\n if (functionSchema.length > 63) {\n throw new Error(\n `plpgsql apply generator: functionSchema '${functionSchema}' exceeds PostgreSQL's 63-byte name limit`,\n );\n }\n return functionSchema;\n}\n\n/**\n * Validate `grantExecuteTo` at GENERATE time, fail-closed. A role name is emitted into DDL (as a\n * quoted identifier and as a `pg_roles` literal), and the whole point of ADR-0054 is that who may\n * execute is named explicitly — so an unusable name is refused loudly here rather than silently\n * producing an artifact whose ACL does not say what its author meant.\n */\nfunction resolveGrantExecuteRoles(grantExecuteTo: readonly string[] | undefined): readonly string[] {\n const roles = grantExecuteTo ?? [];\n const seen = new Set<string>();\n\n for (const role of roles) {\n if (typeof role !== \"string\" || role.trim().length === 0) {\n throw new Error(\"plpgsql apply generator: grantExecuteTo contains an empty role name\");\n }\n if (!GRANT_ROLE_NAME_PATTERN.test(role)) {\n throw new Error(\n `plpgsql apply generator: grantExecuteTo role '${role}' is not a plain SQL identifier ` +\n `(letters, digits, '_' and '$', not starting with a digit)`,\n );\n }\n if (role.length > 63) {\n throw new Error(`plpgsql apply generator: grantExecuteTo role '${role}' exceeds PostgreSQL's 63-byte name limit`);\n }\n if (seen.has(role)) {\n throw new Error(`plpgsql apply generator: grantExecuteTo lists role '${role}' more than once`);\n }\n seen.add(role);\n }\n\n // Canonical (byte) order, so an equivalent SET of roles is one artifact whatever order the caller\n // listed them in. The list is emitted into the FINGERPRINTED body, so without this\n // `[\"a\",\"b\"]` and `[\"b\",\"a\"]` — the same authorization posture — would be two different artifacts,\n // and a server configured with one ordering would fail `PXS01` against the other's install. Role names\n // are validated plain identifiers (ASCII only), so JS's default code-unit sort IS byte order.\n return [...roles].sort();\n}\n\n/**\n * The GUARANTEE behind the readable revokes: converge the installed function's ACL to\n * `owner + grantExecuteTo`, whatever it actually contains.\n *\n * The named revokes above close the two exposures we can NAME (Postgres's PUBLIC default, Supabase's\n * default-privilege trio). They cannot close a grant to a role we cannot name — and a consumer's own\n * `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS TO <their role>` re-grants at every `CREATE`\n * exactly like Supabase's does, so a deployment-specific grantee would survive every install and keep a\n * forged-claims caller on the write path indefinitely. So the artifact ENUMERATES the installed\n * function's real grantees (`aclexplode(pg_proc.proacl)`) and revokes EXECUTE from each one that is\n * neither the function's OWNER (`proowner` — revoking the owner is meaningless, they can re-grant at\n * will) nor in the explicit allowlist.\n *\n * Two details make it total:\n * - **A default (NULL) `proacl` explodes to nothing.** That is why the unconditional\n * `REVOKE ALL … FROM PUBLIC` is emitted FIRST: revoking materializes the previously-implicit ACL\n * (`NULL` → `{owner=X/owner}`), so by the time this block runs the catalog states the truth. Pinned by\n * the pgwasm unit lane, and by the integration lane against a real cluster.\n * - **Grantee `0` is PUBLIC**, which has no role name (`pg_get_userbyid(0)` returns a placeholder\n * string), so it is revoked by the `FROM PUBLIC` spelling rather than by name.\n *\n * The grantee list is snapshotted into an array BEFORE any revoke runs, so the loop never revokes while\n * scanning the catalog it is mutating. Identifiers go through `format('%I', …)` (= `quote_ident`), and\n * the function is named by `oid::regprocedure::text`, which schema-qualifies and quotes as required.\n */\nfunction buildApplyFunctionAclConvergerSql(signature: string, grantExecuteTo: readonly string[]): string {\n const keepList =\n grantExecuteTo.length > 0\n ? `ARRAY[${grantExecuteTo.map((role) => `'${toSqlLiteral(role)}'`).join(\", \")}]::text[]`\n : `ARRAY[]::text[]`;\n\n return `DO $$\nDECLARE\n _fn oid := '${toSqlLiteral(signature)}'::regprocedure;\n _owner oid;\n _keep text[] := ${keepList};\n _grantees oid[];\n _grantee oid;\n _grantee_name text;\nBEGIN\n SELECT p.proowner INTO _owner FROM pg_proc AS p WHERE p.oid = _fn;\n SELECT array_agg(DISTINCT acl.grantee) INTO _grantees\n FROM pg_proc AS p, aclexplode(p.proacl) AS acl\n WHERE p.oid = _fn;\n\n FOREACH _grantee IN ARRAY COALESCE(_grantees, ARRAY[]::oid[]) LOOP\n IF _grantee = _owner THEN\n CONTINUE;\n END IF;\n IF _grantee = 0 THEN\n EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', _fn::regprocedure::text);\n CONTINUE;\n END IF;\n _grantee_name := pg_get_userbyid(_grantee);\n IF _grantee_name = ANY (_keep) THEN\n CONTINUE;\n END IF;\n EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM %I', _fn::regprocedure::text, _grantee_name);\n END LOOP;\nEND;\n$$;`;\n}\n\n/**\n * ADR-0054: the apply function is DENY-BY-DEFAULT, and converges on every install.\n *\n * The function trusts `p_user_claims` — it copies them into `request.jwt.claims` and switches `role`\n * before running RLS-governed DML — which is correct for the consumer server (it passes claims it\n * VERIFIED) and catastrophic for anyone else, who would simply choose their own. Postgres grants\n * EXECUTE to PUBLIC on every new function and Supabase-shaped clusters additionally re-grant the\n * `anon`/`authenticated`/`service_role` trio via default privileges; because the artifact begins with\n * `DROP FUNCTION`, EVERY install recreates that exposure. So the revokes are emitted unconditionally\n * (convergence must not depend on install history), the Supabase-trio ones through the shared\n * role-existence guard so the artifact stays portable to pgwasm and plain-Postgres lanes.\n *\n * Those named revokes are the READABLE fast path — a reviewer sees the two known exposures closed in\n * plain SQL. The guarantee is {@link buildApplyFunctionAclConvergerSql}, which then revokes EVERY\n * remaining grantee outside `owner + grantExecuteTo`, including ones this renderer cannot name.\n *\n * Grants come last, so naming a revoked role in `grantExecuteTo` is a deliberate, explicit grant.\n */\nfunction buildApplyFunctionAclSql(functionName: string, grantExecuteTo: readonly string[]): string {\n const signature = `${functionName}(${APPLY_FUNCTION_ARG_TYPES})`;\n\n return [\n `REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC;`,\n ...SUPABASE_DEFAULT_PRIVILEGE_ROLES.map((role) =>\n buildRoleGuardedStatement(role, `REVOKE ALL ON FUNCTION ${signature} FROM ${quoteIdent(role)}`),\n ),\n buildApplyFunctionAclConvergerSql(signature, grantExecuteTo),\n ...grantExecuteTo.map((role) =>\n buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${signature} TO ${quoteIdent(role)}`),\n ),\n ].join(\"\\n\\n\");\n}\n\nfunction buildApplyFunctionBody(registry: SyncTableRegistry, options: ApplyFunctionRenderOptions = {}): string {\n const tableBranches = Object.values(registry)\n // A read projection (ADR-0027) owns no writable table — its `table` IS the owner's, so the owner's\n // branch already handles that physical table. Emitting a branch for the projection too would\n // DUPLICATE the owner's table branch (same table name). Read projections are readonly and never\n // reach the write path, so exclude them from the apply function entirely.\n .filter((entry) => !(entry as SyncTableEntry).readProjection)\n .map((entry) => buildTableBranch(entry as SyncTableEntry))\n .join(\"\\n\");\n const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);\n // ADR-0054 decision 3: the ACL is rendered INSIDE the fingerprinted body (unlike the COMMENT, which\n // is appended around it) — an install without the revokes IS a different fingerprint and is refused\n // at call time, so a stale PUBLIC-executable install cannot run while `--check` stays green.\n const aclSql = buildApplyFunctionAclSql(functionName, resolveGrantExecuteRoles(options.grantExecuteTo));\n\n return `\n-- Install idempotently by dropping the current signature first. PostgreSQL cannot change a function's\n-- return type through CREATE OR REPLACE, while a generated artifact must install its complete definition.\n--\n-- TWO-TIER MUTATION-ID INVARIANT. \\`mutation_id\\` is TEXT here (RETURNS TABLE + operations_log), not\n-- uuid, so this apply function can serve a DIRECT server-side caller that derives child envelopes with\n-- composite non-UUID ids (\\`\\${parentId}:<tag>:<n>\\`). That is the ONLY non-UUID path. pgxsinkit's public\n-- surface — the HTTP route's request/ack schemas and the client's \\`mutation_id UUID\\` journal — stays\n-- UUID-only (see packages/contracts/src/mutation.ts): the route validates every request id as a UUID and\n-- builds every ack from that request id, never from the TEXT conflict rows this returns. A non-UUID id\n-- therefore never crosses into the UUID-typed surface.\n--\nDROP FUNCTION IF EXISTS ${functionName}(${APPLY_FUNCTION_ARG_TYPES});\n\nCREATE OR REPLACE FUNCTION ${functionName}(\n p_batch jsonb,\n p_request_path text,\n p_log_enabled boolean,\n p_rls_enabled boolean,\n p_user_claims jsonb,\n p_expected_fingerprint text\n) RETURNS TABLE(mutation_id text, table_name text, current_server_version bigint) LANGUAGE plpgsql AS $$\nDECLARE\n dml_sql text;\n v_table text;\n v_kind text;\n v_sig text;\n v_rows jsonb;\n v_cols text;\n v_vals text;\n v_set text;\n -- ADR-0015: stale-write conflicts collected across the batch (mutationId + the row's current\n -- Server version), returned to the handler which turns them into 'conflicted' acks.\n v_conflicts jsonb := '[]'::jsonb;\n v_group_conflicts jsonb;\n -- ADR-0030: the fingerprint this installed function was stamped with (its own ADR-0018 comment),\n -- read back once for the self-verification gate below.\n _installed_fingerprint text;\n _claims jsonb;\n _target_role text;\n _previous_role text;\n _previous_claims text;\n _previous_claim_sub text;\nBEGIN\n -- ADR-0030: the apply function verifies ITSELF against its ADR-0018 fingerprint comment before it\n -- touches any table. p_expected_fingerprint is what the running server expects for its registry +\n -- codegen; obj_description(...) is the fingerprint this installed function was stamped with, atomically,\n -- by the same migration. A mismatch — INCLUDING an absent comment (an unstamped hand-installed\n -- function ⇒ NULL, refused per ADR-0030) — means the installed function is stale relative to the caller,\n -- so raise SQLSTATE 'PXS01' and apply nothing. The check IS the call (no read-then-call TOCTOU) and\n -- costs no extra round trip (the argument rides the existing invocation; the comparison is one text\n -- equality). The signature literal is embedded, never the fingerprint hash itself — baking the hash\n -- into the body would be circular with the hash-of-body the fingerprint is.\n _installed_fingerprint := obj_description('${functionName}(${APPLY_FUNCTION_ARG_TYPES})'::regprocedure, 'pg_proc');\n IF p_expected_fingerprint IS DISTINCT FROM _installed_fingerprint THEN\n RAISE EXCEPTION 'pgxsinkit_apply_mutations is stale: the installed apply-function fingerprint (%) does not match the fingerprint this server expects (%). Regenerate the sync-function migration (pgxsinkit-generate) and apply it before serving writes.', COALESCE(_installed_fingerprint, '(none)'), p_expected_fingerprint\n USING ERRCODE = 'PXS01';\n END IF;\n\n IF p_rls_enabled THEN\n -- Capture the caller's role/claims before switching into the RLS actor context, so the\n -- batch does not leak that context into the rest of the caller's transaction. The HTTP\n -- route RESET ROLEs after calling this function, but in-transaction callers cannot —\n -- restoring here leaves every caller exactly as it was found.\n _previous_role := current_setting('role', true);\n _previous_claims := current_setting('request.jwt.claims', true);\n _previous_claim_sub := current_setting('request.jwt.claim.sub', true);\n _claims := COALESCE(p_user_claims, '{}'::jsonb);\n _target_role := COALESCE(NULLIF(_claims ->> 'role', ''), 'authenticated');\n BEGIN\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = _target_role) THEN\n PERFORM set_config('role', _target_role, true);\n ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN\n PERFORM set_config('role', 'authenticated', true);\n END IF;\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', _claims::text, true);\n IF _claims ? 'sub' THEN\n PERFORM set_config('request.jwt.claim.sub', _claims ->> 'sub', true);\n END IF;\n END IF;\n\n IF jsonb_typeof(p_batch) <> 'object' THEN\n RAISE EXCEPTION 'Batch payload must be a JSON object';\n END IF;\n\n IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN\n RAISE EXCEPTION 'Batch payload mutations must be a JSON array';\n END IF;\n\n -- Group the batch by (table, kind, payload column-set) and apply each group with one statement\n -- (ADR-0014 Phase 4). mutationSeq is table-local, so it cannot order groups across tables: parent\n -- and child journals can both start at 1. WITH ORDINALITY preserves the submitted JSON array order\n -- across tables (FK-safe; the batch transaction also runs SET CONSTRAINTS ALL DEFERRED).\n FOR v_table, v_kind, v_sig, v_rows IN\n SELECT\n grouped.table_name,\n grouped.kind,\n grouped.sig,\n jsonb_agg(grouped.mutation ORDER BY grouped.batch_position)\n FROM (\n SELECT\n entries.m->>'tableName' AS table_name,\n entries.m->>'kind' AS kind,\n COALESCE((\n SELECT string_agg(payload_key, ',' ORDER BY payload_key)\n FROM jsonb_object_keys(COALESCE(entries.m->'payload', '{}'::jsonb)) AS payload_key\n ), '') AS sig,\n entries.m AS mutation,\n entries.batch_position\n FROM jsonb_array_elements(p_batch->'mutations') WITH ORDINALITY AS entries(m, batch_position)\n ) AS grouped\n GROUP BY grouped.table_name, grouped.kind, grouped.sig\n ORDER BY MIN(grouped.batch_position)\n LOOP\n dml_sql := NULL;\n v_cols := NULL;\n v_vals := NULL;\n v_set := NULL;\n\n IF FALSE THEN\n NULL;\n ${tableBranches}\n ELSE\n RAISE EXCEPTION 'Unknown table \"%\" in batch mutation', v_table;\n END IF;\n END LOOP;\n\n IF p_log_enabled THEN\n -- One batched log insert (the whole batch is a single transaction, so a per-mutation loop\n -- bought nothing): a runtime apply failure above rolls the whole transaction back, log rows\n -- included, preserving the existing whole-batch-failure semantics.\n INSERT INTO operations_log (\n table_name,\n operation_kind,\n entity_key_json,\n payload_json,\n status,\n http_status,\n mutation_id,\n mutation_seq,\n client_timestamp_us,\n request_path,\n server_timestamp_us\n )\n SELECT\n m->>'tableName',\n m->>'kind',\n COALESCE(m->'entityKey', '{}'::jsonb),\n COALESCE(m->'payload', '{}'::jsonb),\n 'succeeded',\n 200,\n -- mutation_id is text: a derived child envelope carries a composite non-UUID id\n -- (parent-id + tag + index), so no ::uuid cast (it would raise 22P02 on such an id).\n m->>'mutationId',\n (m->>'mutationSeq')::integer,\n NULLIF(m->>'clientTimestampUs', '')::bigint,\n p_request_path,\n -- The canonical microsecond clock (utilities migration); never the inline expression.\n ${CLOCK_US_CALL_SQL_TEXT}\n FROM jsonb_array_elements(p_batch->'mutations') AS m;\n END IF;\n\n IF p_rls_enabled THEN\n -- Restore the caller's prior role/claims captured above, so the RLS context applied for\n -- the batch does not persist into subsequent statements of the caller's transaction.\n BEGIN\n PERFORM set_config('role', COALESCE(NULLIF(_previous_role, ''), 'none'), true);\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', COALESCE(_previous_claims, ''), true);\n PERFORM set_config('request.jwt.claim.sub', COALESCE(_previous_claim_sub, ''), true);\n END IF;\n\n -- ADR-0015: return the collected stale-write conflicts. Empty under last-write-wins (or when no\n -- write was stale), so the handler simply acks everything as today.\n RETURN QUERY\n SELECT\n -- mutation_id is text (see RETURNS TABLE): a stale derived child envelope's id is a composite\n -- non-UUID string, so return it verbatim — a ::uuid cast here would raise 22P02 and abort the batch.\n c->>'mutationId',\n c->>'tableName',\n (c->>'currentServerVersion')::bigint\n FROM jsonb_array_elements(v_conflicts) AS c;\nEND;\n$$;\n\n-- ADR-0054: deny by default. Emitted on EVERY install because the DROP above resets the ACL to\n-- Postgres's PUBLIC default (plus Supabase's default-privilege grants), so convergence cannot depend\n-- on install history. EXECUTE is owner-only unless the artifact was generated with an explicit\n-- --grant-execute-to; the grant list is the write path's ENTIRE trust boundary, because this function\n-- trusts the claims it is handed.\n${aclSql}\n`.trim();\n}\n\n/**\n * The fingerprint the installed apply function should carry for this registry + applier codegen\n * (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape\n * change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the\n * two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /\n * customPredicate logic, which never enters the apply function (that shapes reads, not writes).\n */\nexport function expectedApplyFingerprint(\n registry: SyncTableRegistry,\n options: ApplyFunctionRenderOptions = {},\n): string {\n return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));\n}\n\nexport function buildPlpgsqlBatchFunctionDdl(\n registry: SyncTableRegistry,\n options: ApplyFunctionRenderOptions = {},\n): string {\n const body = buildApplyFunctionBody(registry, options);\n const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);\n const fingerprint = APPLY_FINGERPRINT_PREFIX + hashString(body);\n\n // ADR-0018: stamp the function with the fingerprint of this exact DDL body. Stored as a COMMENT\n // because it is function-scoped, replaced atomically with the function, and read back in one line\n // via obj_description — so the server (startup) and CI (pre-deploy) can both detect a function\n // that is stale relative to the registry + codegen it is meant to serve.\n return `${body}\\n\\nCOMMENT ON FUNCTION ${functionName}(${APPLY_FUNCTION_ARG_TYPES}) IS '${fingerprint}';`;\n}\n\nexport async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n options: ApplyFunctionRenderOptions = {},\n): Promise<void> {\n const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);\n await db.execute(sql.raw(ddl));\n}\n\ntype AuthHelperPresenceRow = {\n authUid: string | null;\n};\n\nexport async function verifyRlsAuthHelpers<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n): Promise<void> {\n const result = await db.execute<AuthHelperPresenceRow>(sql`\n SELECT\n to_regprocedure('auth.uid()')::text AS \"authUid\"\n `);\n\n const row = Array.from(result as Iterable<unknown>, (entry) => entry as AuthHelperPresenceRow)[0];\n const missingHelpers = [row?.authUid ? null : \"auth.uid()\"].filter((value): value is string => value !== null);\n\n if (missingHelpers.length > 0) {\n throw new Error(\n `The write path requires Supabase auth helpers. Missing: ${missingHelpers.join(\", \")}. ` +\n \"Ensure auth.uid() is available (standard on Supabase-managed databases).\",\n );\n }\n}\n\n/**\n * A conflict the applier rejected under `reject-if-stale` (ADR-0015): either a **stale** write (the\n * Base server version the row has since advanced past — `currentServerVersion` is the row's current\n * version) or an UPDATE whose **target row is missing** (deleted by another writer —\n * `currentServerVersion` is `null`, the #6 discriminator). The handler surfaces it on the\n * `conflicted` ack.\n */\nexport interface MutationConflict {\n mutationId: string;\n tableName: string;\n currentServerVersion: string | null;\n}\n\ninterface MutationConflictRow {\n mutationId: string | null;\n tableName: string | null;\n currentServerVersion: string | null;\n}\n\nexport async function executePlpgsqlBatch(\n tx: TransactionClient,\n batch: BatchMutationRequest,\n requestPath: string,\n logEnabled: boolean,\n rlsEnabled: boolean,\n userClaims: Record<string, unknown>,\n // ADR-0030: the fingerprint the running server expects for its registry + codegen\n // (`expectedApplyFingerprint(registry)`, computed once per server instance). The installed apply\n // function compares it against its own stamped comment and raises SQLSTATE 'PXS01' on a mismatch —\n // in-body, atomic with the call, before it touches any table.\n expectedFingerprint: string,\n options: {\n functionSchema?: string;\n } = {},\n): Promise<MutationConflict[]> {\n const normalizedClaims = userClaims ?? {};\n // Typed identifier interpolation (never `sql.raw` of a hand-quoted name); the OUT-column aliases\n // are the generated function's fixed names. The schema goes through the SAME validator the renderer\n // uses, so a server configured with `applyFunctionSchema` names exactly what the artifact installed.\n const functionSchema = resolveApplyFunctionSchema(options.functionSchema);\n const functionRef = functionSchema\n ? sql`${sql.identifier(functionSchema)}.${sql.identifier(\"pgxsinkit_apply_mutations\")}`\n : sql`${sql.identifier(\"pgxsinkit_apply_mutations\")}`;\n\n // The applier RETURNS the stale-write conflicts (ADR-0015). Read them from the function's result\n // set; an empty set (the last-write-wins case, or nothing stale) means every mutation applied.\n const result = await tx.execute(\n sql`SELECT \"mutation_id\"::text AS \"mutationId\", \"table_name\" AS \"tableName\", \"current_server_version\"::text AS \"currentServerVersion\" FROM ${functionRef}(${JSON.stringify(batch)}::text::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::text::jsonb, ${expectedFingerprint})`,\n );\n\n const rows = Array.from(result as Iterable<unknown>, (row) => row as MutationConflictRow);\n return rows.flatMap((row) =>\n row.mutationId != null\n ? [\n {\n mutationId: row.mutationId,\n tableName: row.tableName ?? \"\",\n currentServerVersion: row.currentServerVersion,\n } satisfies MutationConflict,\n ]\n : [],\n );\n}\n",
19
+ "import { getTableName, sql } from \"drizzle-orm\";\nimport { type AnyPgTable, getTableConfig, type PgAsyncDatabase, type PgQueryResultHKT } from \"drizzle-orm/pg-core\";\nimport { getColumns } from \"drizzle-orm/utils\";\n\nimport {\n type BatchMutationRequest,\n buildRoleGuardedStatement,\n CLOCK_US_CALL_SQL_TEXT,\n escapeSqlLiteral as toSqlLiteral,\n getProjectedColumns,\n hashString,\n isManagedFieldGuarded,\n type ManagedFieldApplyOn,\n quoteIdentifier as quoteIdent,\n type RegistryRelations,\n resolveServerVersionColumnName,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { TransactionClient } from \"./types\";\n\nfunction qualifyIdent(schemaName: string | undefined, name: string): string {\n if (!schemaName) {\n return quoteIdent(name);\n }\n\n return `${quoteIdent(schemaName)}.${quoteIdent(name)}`;\n}\n\nfunction toSqlTextOrNull(value: string): string {\n return value.length > 0 ? `'${toSqlLiteral(value)}'` : \"NULL\";\n}\n\n/**\n * The array dimensionality Drizzle records for a column (0 = scalar). It is carried SEPARATELY from\n * `getSQLType()`, which returns the ELEMENT type for an array column (`uuid` for a `uuid[]`) — reading\n * only the type string is what silently emitted a scalar cast for an array column and killed every\n * non-null array write with 22P02.\n */\nfunction columnDimensions(column: { dimensions?: number }): number {\n return column.dimensions ?? 0;\n}\n\n/**\n * The SQL expression that reads one writable column out of a mutation's payload (`x.p`), by column\n * name and Drizzle type. It is embedded in the branch's `(col_name, col_value)` candidate list and\n * substituted verbatim into the INSERT/UPDATE `format()` template at runtime.\n *\n * Scalars keep the long-standing `(x.p->>'col')::type` form. A one-dimensional array column expands\n * the JSON array element-wise and applies the terminal `::<element>[]` cast, which IS the type check\n * (no element-type allowlist: an element the target type cannot accept raises, exactly as a scalar\n * cast does). The three payload shapes match the scalar semantics exactly:\n *\n * - **absent key** — never reaches here (the branch intersects the candidate list with the group's\n * payload signature, so an unsent column is not in the statement at all);\n * - **JSON null** — `jsonb_typeof` is `'null'`, the CASE has no ELSE ⇒ SQL NULL, mirroring\n * `(x.p->>'col')::type` on a JSON null;\n * - **`[]`** — an empty typed array, NOT NULL (an empty list is a value the client meant to write).\n *\n * Element order is pinned with `WITH ORDINALITY … ORDER BY`, so the stored array order is the\n * client's array order by construction rather than by set-returning-function evaluation order.\n * A JSON null ELEMENT becomes a SQL NULL element (`jsonb_array_elements_text` semantics) — except for\n * the JSON element types, see below.\n *\n * The one branch inside the array branch is the ELEMENT type: `json`/`jsonb` elements expand with\n * `jsonb_array_elements` (the JSON-valued expansion), never `jsonb_array_elements_text`. Text expansion\n * of a JSON element STRIPS its JSON quoting, which is silent type corruption for a `jsonb[]`: the element\n * `\"123\"` (a JSON string) re-parses as the JSON NUMBER `123`, and `\"hi\"` fails the cast outright with\n * `invalid input syntax for type json`. `jsonb_array_elements` preserves each element VERBATIM, so a JSON\n * null element stays a JSON null value (`jsonb_typeof(e) = 'null'`, not SQL NULL) — the faithful reading\n * for a JSON-typed element, and what round-trips back to the client unchanged. The column-level shapes\n * (absent key / JSON null / `[]`) are identical to the text branch.\n */\nfunction buildPayloadValueExpression(\n tableName: string,\n column: { name: string; getSQLType: () => string; dimensions?: number },\n): string {\n const columnLiteral = `'${toSqlLiteral(column.name)}'`;\n const dimensions = columnDimensions(column);\n const sqlType = column.getSQLType();\n\n if (dimensions === 0) {\n return `(x.p->>${columnLiteral})::${sqlType}`;\n }\n\n if (dimensions > 1) {\n // Loud at GENERATE time, never a silently wrong cast: a multi-dimensional array cannot be\n // reconstructed from a flat element expansion, and Postgres additionally requires every\n // sub-array to be the same length — a validity rule this renderer cannot express.\n throw new Error(\n `plpgsql apply generator: column ${tableName}.${column.name} is a ${dimensions}-dimensional array; ` +\n `multi-dimensional arrays are not supported by the apply function (use a single-dimension array, ` +\n `or a jsonb column)`,\n );\n }\n\n // A `json`/`jsonb` ELEMENT type must keep its JSON value (quoting included); every other element type\n // is reconstructed from the element's TEXT rendering, which is what the terminal `::<type>[]` cast reads.\n const elementExpansion = isJsonElementType(sqlType) ? \"jsonb_array_elements\" : \"jsonb_array_elements_text\";\n\n return (\n `CASE WHEN jsonb_typeof(x.p->${columnLiteral}) = 'array' THEN ` +\n `ARRAY(SELECT e FROM ${elementExpansion}(x.p->${columnLiteral}) WITH ORDINALITY AS a(e, ord) ORDER BY ord)` +\n `::${sqlType}[] END`\n );\n}\n\n/** `json` / `jsonb` — the element types whose VALUE (not text rendering) must survive the expansion. */\nfunction isJsonElementType(sqlType: string): boolean {\n const normalized = sqlType.trim().toLowerCase();\n return normalized === \"json\" || normalized === \"jsonb\";\n}\n\n/** One `(column name, payload value expression)` row of a branch's runtime candidate list. */\nfunction toColumnCandidateRow(tableName: string, column: { name: string; getSQLType: () => string }): string {\n return `('${toSqlLiteral(column.name)}', '${toSqlLiteral(buildPayloadValueExpression(tableName, column))}')`;\n}\n\ninterface ResolvedManagedField {\n propertyKey: string;\n columnName: string;\n applyOn: readonly ManagedFieldApplyOn[];\n strategy: \"nowMicroseconds\" | \"authClaim\";\n claimPath?: string[];\n cast?: string;\n columnSqlType: string;\n}\n\n// The single claim-stamping strategy (ADR-0026): `authClaim` reads the verified request claim at its JSON\n// path — `auth.uid()` is just `{ claimPath: [\"sub\"], cast: \"uuid\" }`, so there is one mechanism. The path\n// segments are validated plain identifiers at registry build, so the `'{a,b}'` text-array literal is\n// injection-safe; `current_setting('request.jwt.claims', …)` is set by this function before the apply DML\n// (it is what RLS reads), NULLIF guards an unset GUC (an absent claim stamps NULL, never errors), and the\n// cast defaults to the target column's own SQL type so a `uuid` column needs no explicit cast.\nfunction buildManagedFieldExpression(field: ResolvedManagedField): string {\n if (field.strategy === \"authClaim\") {\n const path = (field.claimPath ?? []).join(\",\");\n const castType = field.cast ?? field.columnSqlType;\n return `(NULLIF(current_setting('request.jwt.claims', true), '')::jsonb #>> '{${path}}')::${castType}`;\n }\n\n // Call the canonical microsecond-clock DB function, never inline the expression. The rendered\n // artifact therefore DEPENDS on the utilities function (public.pgxsinkit_clock_us()): the utilities\n // migration (renderPgxsinkitUtilitiesMigration) must precede this artifact in any consumer's chain.\n // The ADR-0030 fingerprint recomputes from this rendered text, so a change to the call form is\n // coordinated through the normal regenerate-and-commit flow.\n return CLOCK_US_CALL_SQL_TEXT;\n}\n\n// Every managed field of the entry, resolved to its SQL column name and type. The two consumers slice it\n// differently and the distinction is load-bearing: STAMPING is operation-scoped (`applyOn.includes(op)`)\n// and decides what the applier writes, while GUARDING (contracts' `isManagedFieldGuarded`) decides which\n// columns a client payload may never move, and so which are excluded from the candidate lists below.\nfunction resolveManagedFields(entry: SyncTableEntry): ResolvedManagedField[] {\n const tableName = getTableName(entry.table as AnyPgTable);\n const columns = getColumns(entry.table as AnyPgTable);\n const columnNameMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));\n\n return (entry.governance?.managedFields ?? []).flatMap((field) => {\n const columnName = columnNameMap.get(field.column);\n if (!columnName) {\n return [];\n }\n\n const column =\n (columns as Record<string, { getSQLType: () => string; dimensions?: number } | undefined>)[field.column] ??\n Object.values(columns).find((candidate) => candidate.name === field.column);\n\n if (column && columnDimensions(column) > 0) {\n // Both stamping strategies produce a SCALAR (a microsecond clock read, or one claim at a JSON\n // path), so an array-typed managed column could only ever be assigned a scalar — a type error at\n // every write. Refuse at generate time instead.\n throw new Error(\n `plpgsql apply generator: managed field ${tableName}.${columnName} is an array column; ` +\n `managed fields stamp a single scalar value and are not supported on array columns`,\n );\n }\n\n return [\n {\n propertyKey: field.column,\n columnName,\n applyOn: field.applyOn,\n strategy: field.strategy,\n ...(field.claimPath ? { claimPath: field.claimPath } : {}),\n ...(field.cast ? { cast: field.cast } : {}),\n columnSqlType: column?.getSQLType() ?? \"text\",\n },\n ];\n });\n}\n\nfunction buildTableBranch(entry: SyncTableEntry): string {\n const tableName = getTableName(entry.table as AnyPgTable);\n const { schema } = getTableConfig(entry.table as AnyPgTable);\n const qualifiedTableName = qualifyIdent(schema, tableName);\n const columns = getColumns(entry.table as AnyPgTable);\n const projectedColumns = getProjectedColumns(entry);\n // The canonical Entity identity is the full server primary-key tuple, by column name with\n // typed values (ADR-0012): the applier matches update/delete over EVERY pk column. Keying on\n // only the first column (the old `columns[0]`) matched too many rows on a composite-PK table.\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const columnObject = Object.values(columns).find((column) => column.name === columnName);\n if (!columnObject) {\n // Hard error, not a silent `text` fallback: an unmatched PK column means the primaryKey spec\n // has drifted from the table (e.g. a rename) — a generated applier keyed on a mistyped tuple\n // would mis-match rows at apply time.\n throw new Error(\n `plpgsql apply generator: primary key column ${columnName} not found on table ${tableName}; ` +\n `the entry's primaryKey spec has drifted from its Drizzle table`,\n );\n }\n if (columnDimensions(columnObject) > 0) {\n // The canonical identity is carried as typed recordset columns and as `(x.k->>'col')::type`\n // join predicates — both scalar forms. An array PK would need array equality semantics the\n // entity-key wire shape (a JSON object of scalar strings) cannot express, so refuse it here\n // rather than emit a cast that would raise 22P02 on the first update/delete.\n throw new Error(\n `plpgsql apply generator: primary key column ${tableName}.${columnName} is an array column; ` +\n `array columns are not supported as primary keys by the apply function`,\n );\n }\n return { name: columnName, type: columnObject.getSQLType() };\n });\n const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));\n\n const managedFields = resolveManagedFields(entry);\n // STAMPING sets — operation-scoped: what the applier itself writes (the INSERT column/value fragments\n // and the UPDATE managed-assignment fragment below).\n const createManagedFields = managedFields.filter((field) => field.applyOn.includes(\"create\"));\n const updateManagedFields = managedFields.filter((field) => field.applyOn.includes(\"update\"));\n // EXCLUSION sets — the guard rule, from contracts' single definition: a column that is server-owned for\n // the operation is not a candidate a client payload key can move. On create that is the create-managed\n // columns (the applier stamps them itself); on update it is EVERY managed column, so a create-only\n // field (`applyOn: [\"create\"]`, e.g. an `authClaim` owner) is inert thereafter, and an update-managed\n // one is assigned by the static managed-assignment fragment instead.\n const createGuardedColumnNames = new Set(\n managedFields.filter((field) => isManagedFieldGuarded(field, \"create\")).map((field) => field.columnName),\n );\n const updateGuardedColumnNames = new Set(\n managedFields.filter((field) => isManagedFieldGuarded(field, \"update\")).map((field) => field.columnName),\n );\n\n // Each candidate row carries the column's NAME and its fully-rendered payload value EXPRESSION.\n // The expression is precomputed here (rather than `format()`-ed from a type at runtime) because it\n // is no longer uniform: an array column needs an element-wise expansion, not a `->>` cast.\n const allColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !createGuardedColumnNames.has(column.name))\n .map((column) => toColumnCandidateRow(tableName, column))\n .join(\",\\n \");\n\n const nonPrimaryKeyColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !primaryKeyColumnNames.has(column.name) && !updateGuardedColumnNames.has(column.name))\n .map((column) => toColumnCandidateRow(tableName, column))\n .join(\",\\n \");\n\n const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(\", \");\n const createManagedValuesSql = createManagedFields.map((field) => buildManagedFieldExpression(field)).join(\", \");\n // ADR-0010: the Server version (the nowMicroseconds-on-update managed field) must be strictly\n // monotonic per row, so its on-update stamp is floored at the previous value + 1 — it can never\n // repeat or step backwards under wall-clock (NTP) skew, which would let a stale echo clear an\n // optimistic write early. The bare column on the RHS of an UPDATE SET is the pre-update value.\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n const updateManagedAssignmentsSql = updateManagedFields\n .map((field) => {\n const expression =\n field.strategy === \"nowMicroseconds\" && field.columnName === serverVersionColumn\n ? `GREATEST(${buildManagedFieldExpression(field)}, ${quoteIdent(field.columnName)} + 1)`\n : buildManagedFieldExpression(field);\n return `${quoteIdent(field.columnName)} = ${expression}`;\n })\n .join(\", \");\n\n // Set-based apply (ADR-0014 Phase 4): one statement per (table, kind, payload column-set) group,\n // over the group's rows materialised by jsonb_to_recordset. The PK match spans the full tuple\n // (ADR-0012): DELETE matches the recordset's typed PK columns directly; UPDATE matches each row's\n // entity key carried as `x.k` jsonb. Safe from the same-PK `UPDATE … FROM` join hazard because the\n // Per-entity flush serialization invariant leaves at most one mutation per entity in a batch.\n const pkRecordDef = primaryKeyColumns.map((pk) => `${quoteIdent(pk.name)} ${pk.type}`).join(\", \");\n const pkDeleteJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = x.${quoteIdent(pk.name)}`)\n .join(\" AND \");\n const pkUpdateJoin = primaryKeyColumns\n .map((pk) => `t.${quoteIdent(pk.name)} = (x.k->>'${toSqlLiteral(pk.name)}')::${pk.type}`)\n .join(\" AND \");\n\n // Templates the runtime format() fills with the per-group column list. Single quotes are doubled\n // because these are embedded as PL/pgSQL string literals.\n const insertTemplate =\n `INSERT INTO ${qualifiedTableName} (%s) SELECT %s FROM jsonb_to_recordset($1) AS x(p jsonb)`.replace(/'/g, \"''\");\n const updateTemplate =\n `UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb) WHERE ${pkUpdateJoin}`.replace(\n /'/g,\n \"''\",\n );\n const deleteSql =\n `DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}) WHERE ${pkDeleteJoin}`.replace(\n /'/g,\n \"''\",\n );\n\n // The create/update column fragments come from the group signature (∩ writable columns) plus the\n // static managed fields. An empty intersection ⇒ NULL fragment ⇒ a managed-only statement (the\n // Server version still bumps on a PK-only update, exactly as the per-mutation path did).\n const createColumnSelect = allColumnPairs.length\n ? `SELECT\n string_agg(quote_ident(col_name), ', ' ORDER BY col_name),\n string_agg(col_value, ', ' ORDER BY col_name)\n INTO v_cols, v_vals\n FROM (VALUES\n ${allColumnPairs}\n ) AS col_types(col_name, col_value)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_cols := NULL; v_vals := NULL;`;\n\n const updateSetSelect = nonPrimaryKeyColumnPairs.length\n ? `SELECT string_agg(format('%I = %s', col_name, col_value), ', ' ORDER BY col_name)\n INTO v_set\n FROM (VALUES\n ${nonPrimaryKeyColumnPairs}\n ) AS col_types(col_name, col_value)\n WHERE col_name = ANY(string_to_array(v_sig, ','));`\n : `v_set := NULL;`;\n\n const createBranch = `\n ${createColumnSelect}\n\n dml_sql := format(\n '${insertTemplate}',\n concat_ws(', ', nullif(v_cols, ''), ${toSqlTextOrNull(createManagedColumnsSql)}),\n concat_ws(', ', nullif(v_vals, ''), ${toSqlTextOrNull(createManagedValuesSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n // ADR-0015: a `reject-if-stale` table compares each targeted row's current Server version to the\n // mutation's Base server version (`x.b`). `current > base` ⇒ stale (an external write interleaved):\n // the row is NOT applied, and the conflict (mutation id + the row's current Server version) is\n // collected for the handler to turn into a `conflicted` ack. `last-write-wins` keeps today's apply\n // (now a named choice). The policy is known here at DDL-generation time, so each table emits the SQL\n // its policy needs; a create has no base (its conflict is a PK collision), so it is unchanged.\n // #6: an UPDATE whose target row is MISSING (deleted by another writer after authoring) is also a\n // conflict ('target row no longer exists', `currentServerVersion` NULL) — otherwise the edit would\n // silently no-op and ack as success. A DELETE of a missing row stays idempotent success (the user\n // wanted it gone), so the delete branch keeps its inner join and does not report missing targets.\n const serverVersionRef = serverVersionColumn ? quoteIdent(serverVersionColumn) : null;\n const rejectIfStale = entry.conflictPolicy === \"reject-if-stale\" && serverVersionRef != null;\n // For the missing-target conflict (ADR-0015 #6): a LEFT JOIN whose right side is absent leaves the\n // first PK column NULL. The Server version is NOT NULL on any existing writable row, so a NULL\n // `currentServerVersion` in a returned conflict means exactly \"the target row no longer exists\".\n const firstPkRef = quoteIdent(primaryKeyColumns[0]!.name);\n\n // The conflict-collect SELECT and the staleness guard need the base + mutation id alongside each\n // row, so reject-if-stale carries them in the recordset (`b bigint, m text`). The mutation id is\n // `text` (not `uuid`): a derived child envelope's id is a composite non-UUID string, and a `m uuid`\n // recordset column would raise 22P02 the moment such a write is stale.\n const conflictObjectSql = (alias: string) =>\n `jsonb_build_object('mutationId', ${alias}.m, 'tableName', '${toSqlLiteral(tableName)}', 'currentServerVersion', t.${serverVersionRef})`;\n\n const updateBranch = rejectIfStale\n ? `\n ${updateSetSelect}\n\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) LEFT JOIN ${qualifiedTableName} AS t ON ${pkUpdateJoin} WHERE t.${firstPkRef} IS NULL OR (x.b IS NOT NULL AND t.${serverVersionRef} > x.b)`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n dml_sql := format(\n '${`UPDATE ${qualifiedTableName} AS t SET %s FROM jsonb_to_recordset($1) AS x(p jsonb, k jsonb, b bigint, m text) WHERE ${pkUpdateJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb), 'b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n ${updateSetSelect}\n\n dml_sql := format(\n '${updateTemplate}',\n concat_ws(', ', nullif(v_set, ''), ${toSqlTextOrNull(updateManagedAssignmentsSql)})\n );\n EXECUTE dml_sql USING (\n SELECT COALESCE(jsonb_agg(jsonb_build_object('p', COALESCE(elem->'payload', '{}'::jsonb), 'k', COALESCE(elem->'entityKey', '{}'::jsonb))), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n const deleteBranch = rejectIfStale\n ? `\n EXECUTE '${`SELECT COALESCE(jsonb_agg(${conflictObjectSql(\"x\")}), '[]'::jsonb) FROM jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) JOIN ${qualifiedTableName} AS t ON ${pkDeleteJoin} WHERE x.b IS NOT NULL AND t.${serverVersionRef} > x.b`.replace(/'/g, \"''\")}'\n INTO v_group_conflicts\n USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n v_conflicts := v_conflicts || v_group_conflicts;\n\n EXECUTE '${`DELETE FROM ${qualifiedTableName} AS t USING jsonb_to_recordset($1) AS x(${pkRecordDef}, b bigint, m text) WHERE ${pkDeleteJoin} AND (x.b IS NULL OR t.${serverVersionRef} <= x.b)`.replace(/'/g, \"''\")}' USING (\n SELECT COALESCE(jsonb_agg(COALESCE(elem->'entityKey', '{}'::jsonb) || jsonb_build_object('b', (elem->>'baseServerVersion')::bigint, 'm', elem->>'mutationId')), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim()\n : `\n EXECUTE '${deleteSql}' USING (\n SELECT COALESCE(jsonb_agg(elem->'entityKey'), '[]'::jsonb)\n FROM jsonb_array_elements(v_rows) AS elem\n );\n `.trim();\n\n return `\n ELSIF v_table = '${toSqlLiteral(tableName)}' THEN\n IF v_kind = 'create' THEN\n ${createBranch}\n ELSIF v_kind = 'update' THEN\n ${updateBranch}\n ELSIF v_kind = 'delete' THEN\n ${deleteBranch}\n ELSE\n RAISE EXCEPTION 'Unsupported mutation kind \"%\" for table \"%\"', v_kind, v_table;\n END IF;\n `.trim();\n}\n\nconst APPLY_FUNCTION_NAME = \"pgxsinkit_apply_mutations\";\n// ADR-0030: the trailing `text` is `p_expected_fingerprint` — the running server passes the fingerprint\n// it expects for its registry + codegen, and the function verifies itself against its stamped comment\n// before touching any table.\nconst APPLY_FUNCTION_ARG_TYPES = \"jsonb, text, boolean, boolean, jsonb, text\";\n// ADR-0018: the prefix namespaces the strict fingerprint format. Any absent or different prefix is\n// an identity mismatch and the apply function refuses the write.\nconst APPLY_FINGERPRINT_PREFIX = \"pgxsinkit:fp1:\";\n\n/**\n * The roles Supabase's `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS` re-grants at every CREATE\n * (ADR-0054). The artifact's `DROP FUNCTION` makes each install a fresh creation, so these grants come\n * BACK on every regenerate — hence an unconditional revoke per install, not a one-off hardening.\n */\nconst SUPABASE_DEFAULT_PRIVILEGE_ROLES = [\"anon\", \"authenticated\", \"service_role\"] as const;\n\n/**\n * How the generated apply function is rendered. Both fields are part of the artifact's IDENTITY: they\n * change the fingerprinted body, so a change to either forces the regenerate-and-commit flow, and the\n * SERVER must be configured with the same values (it recomputes the expected fingerprint at runtime).\n */\nexport interface ApplyFunctionRenderOptions {\n /** Schema to qualify the function with. Default: unqualified (resolved through `search_path`). */\n functionSchema?: string;\n /**\n * Roles that receive `GRANT EXECUTE` on the apply function (ADR-0054 decision 2). Default `[]` —\n * **owner-only**, which is right whenever the server connects as the function's owner or a\n * superuser. Name ONLY server roles: the function trusts the `p_user_claims` it is handed, so a\n * granted role can pass any claims it likes. The grant list IS the write path's trust boundary.\n */\n grantExecuteTo?: readonly string[];\n}\n\n/** An unquoted-safe SQL role name: what `GRANT … TO <role>` may name without surprises. */\nconst GRANT_ROLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * Validate a `functionSchema` — the ONE definition, shared by the renderer (which qualifies the emitted\n * DDL with it) and by the running server (`applyFunctionSchema`, which must qualify its invocation the\n * same way and recompute the same fingerprint). A schema name reaches SQL as a quoted identifier, so the\n * rule is the same plain-identifier rule role names get: an unusable name is refused loudly at generate\n * / server-construction time rather than producing an artifact nobody can call.\n *\n * Returns `undefined` for an absent schema — the default, an unqualified name resolved through\n * `search_path`.\n */\nexport function resolveApplyFunctionSchema(functionSchema: string | undefined): string | undefined {\n if (functionSchema === undefined) {\n return undefined;\n }\n if (typeof functionSchema !== \"string\" || functionSchema.trim().length === 0) {\n throw new Error(\"plpgsql apply generator: functionSchema is empty\");\n }\n if (!GRANT_ROLE_NAME_PATTERN.test(functionSchema)) {\n throw new Error(\n `plpgsql apply generator: functionSchema '${functionSchema}' is not a plain SQL identifier ` +\n `(letters, digits, '_' and '$', not starting with a digit)`,\n );\n }\n if (functionSchema.length > 63) {\n throw new Error(\n `plpgsql apply generator: functionSchema '${functionSchema}' exceeds PostgreSQL's 63-byte name limit`,\n );\n }\n return functionSchema;\n}\n\n/**\n * Validate `grantExecuteTo` at GENERATE time, fail-closed. A role name is emitted into DDL (as a\n * quoted identifier and as a `pg_roles` literal), and the whole point of ADR-0054 is that who may\n * execute is named explicitly — so an unusable name is refused loudly here rather than silently\n * producing an artifact whose ACL does not say what its author meant.\n */\nfunction resolveGrantExecuteRoles(grantExecuteTo: readonly string[] | undefined): readonly string[] {\n const roles = grantExecuteTo ?? [];\n const seen = new Set<string>();\n\n for (const role of roles) {\n if (typeof role !== \"string\" || role.trim().length === 0) {\n throw new Error(\"plpgsql apply generator: grantExecuteTo contains an empty role name\");\n }\n if (!GRANT_ROLE_NAME_PATTERN.test(role)) {\n throw new Error(\n `plpgsql apply generator: grantExecuteTo role '${role}' is not a plain SQL identifier ` +\n `(letters, digits, '_' and '$', not starting with a digit)`,\n );\n }\n if (role.length > 63) {\n throw new Error(`plpgsql apply generator: grantExecuteTo role '${role}' exceeds PostgreSQL's 63-byte name limit`);\n }\n if (seen.has(role)) {\n throw new Error(`plpgsql apply generator: grantExecuteTo lists role '${role}' more than once`);\n }\n seen.add(role);\n }\n\n // Canonical (byte) order, so an equivalent SET of roles is one artifact whatever order the caller\n // listed them in. The list is emitted into the FINGERPRINTED body, so without this\n // `[\"a\",\"b\"]` and `[\"b\",\"a\"]` — the same authorization posture — would be two different artifacts,\n // and a server configured with one ordering would fail `PXS01` against the other's install. Role names\n // are validated plain identifiers (ASCII only), so JS's default code-unit sort IS byte order.\n return [...roles].sort();\n}\n\n/**\n * The GUARANTEE behind the readable revokes: converge the installed function's ACL to\n * `owner + grantExecuteTo`, whatever it actually contains.\n *\n * The named revokes above close the two exposures we can NAME (Postgres's PUBLIC default, Supabase's\n * default-privilege trio). They cannot close a grant to a role we cannot name — and a consumer's own\n * `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS TO <their role>` re-grants at every `CREATE`\n * exactly like Supabase's does, so a deployment-specific grantee would survive every install and keep a\n * forged-claims caller on the write path indefinitely. So the artifact ENUMERATES the installed\n * function's real grantees (`aclexplode(pg_proc.proacl)`) and revokes EXECUTE from each one that is\n * neither the function's OWNER (`proowner` — revoking the owner is meaningless, they can re-grant at\n * will) nor in the explicit allowlist.\n *\n * Two details make it total:\n * - **A default (NULL) `proacl` explodes to nothing.** That is why the unconditional\n * `REVOKE ALL … FROM PUBLIC` is emitted FIRST: revoking materializes the previously-implicit ACL\n * (`NULL` → `{owner=X/owner}`), so by the time this block runs the catalog states the truth. Pinned by\n * the pgwasm unit lane, and by the integration lane against a real cluster.\n * - **Grantee `0` is PUBLIC**, which has no role name (`pg_get_userbyid(0)` returns a placeholder\n * string), so it is revoked by the `FROM PUBLIC` spelling rather than by name.\n *\n * The grantee list is snapshotted into an array BEFORE any revoke runs, so the loop never revokes while\n * scanning the catalog it is mutating. Identifiers go through `format('%I', …)` (= `quote_ident`), and\n * the function is named by `oid::regprocedure::text`, which schema-qualifies and quotes as required.\n */\nfunction buildApplyFunctionAclConvergerSql(signature: string, grantExecuteTo: readonly string[]): string {\n const keepList =\n grantExecuteTo.length > 0\n ? `ARRAY[${grantExecuteTo.map((role) => `'${toSqlLiteral(role)}'`).join(\", \")}]::text[]`\n : `ARRAY[]::text[]`;\n\n return `DO $$\nDECLARE\n _fn oid := '${toSqlLiteral(signature)}'::regprocedure;\n _owner oid;\n _keep text[] := ${keepList};\n _grantees oid[];\n _grantee oid;\n _grantee_name text;\nBEGIN\n SELECT p.proowner INTO _owner FROM pg_proc AS p WHERE p.oid = _fn;\n SELECT array_agg(DISTINCT acl.grantee) INTO _grantees\n FROM pg_proc AS p, aclexplode(p.proacl) AS acl\n WHERE p.oid = _fn;\n\n FOREACH _grantee IN ARRAY COALESCE(_grantees, ARRAY[]::oid[]) LOOP\n IF _grantee = _owner THEN\n CONTINUE;\n END IF;\n IF _grantee = 0 THEN\n EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', _fn::regprocedure::text);\n CONTINUE;\n END IF;\n _grantee_name := pg_get_userbyid(_grantee);\n IF _grantee_name = ANY (_keep) THEN\n CONTINUE;\n END IF;\n EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM %I', _fn::regprocedure::text, _grantee_name);\n END LOOP;\nEND;\n$$;`;\n}\n\n/**\n * ADR-0054: the apply function is DENY-BY-DEFAULT, and converges on every install.\n *\n * The function trusts `p_user_claims` — it copies them into `request.jwt.claims` and switches `role`\n * before running RLS-governed DML — which is correct for the consumer server (it passes claims it\n * VERIFIED) and catastrophic for anyone else, who would simply choose their own. Postgres grants\n * EXECUTE to PUBLIC on every new function and Supabase-shaped clusters additionally re-grant the\n * `anon`/`authenticated`/`service_role` trio via default privileges; because the artifact begins with\n * `DROP FUNCTION`, EVERY install recreates that exposure. So the revokes are emitted unconditionally\n * (convergence must not depend on install history), the Supabase-trio ones through the shared\n * role-existence guard so the artifact stays portable to pgwasm and plain-Postgres lanes.\n *\n * Those named revokes are the READABLE fast path — a reviewer sees the two known exposures closed in\n * plain SQL. The guarantee is {@link buildApplyFunctionAclConvergerSql}, which then revokes EVERY\n * remaining grantee outside `owner + grantExecuteTo`, including ones this renderer cannot name.\n *\n * Grants come last, so naming a revoked role in `grantExecuteTo` is a deliberate, explicit grant.\n */\nfunction buildApplyFunctionAclSql(functionName: string, grantExecuteTo: readonly string[]): string {\n const signature = `${functionName}(${APPLY_FUNCTION_ARG_TYPES})`;\n\n return [\n `REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC;`,\n ...SUPABASE_DEFAULT_PRIVILEGE_ROLES.map((role) =>\n buildRoleGuardedStatement(role, `REVOKE ALL ON FUNCTION ${signature} FROM ${quoteIdent(role)}`),\n ),\n buildApplyFunctionAclConvergerSql(signature, grantExecuteTo),\n ...grantExecuteTo.map((role) =>\n buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${signature} TO ${quoteIdent(role)}`),\n ),\n ].join(\"\\n\\n\");\n}\n\nfunction buildApplyFunctionBody(registry: SyncTableRegistry, options: ApplyFunctionRenderOptions = {}): string {\n const tableBranches = Object.values(registry)\n // A read projection (ADR-0027) owns no writable table — its `table` IS the owner's, so the owner's\n // branch already handles that physical table. Emitting a branch for the projection too would\n // DUPLICATE the owner's table branch (same table name). Read projections are readonly and never\n // reach the write path, so exclude them from the apply function entirely.\n .filter((entry) => !(entry as SyncTableEntry).readProjection)\n .map((entry) => buildTableBranch(entry as SyncTableEntry))\n .join(\"\\n\");\n const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);\n // ADR-0054 decision 3: the ACL is rendered INSIDE the fingerprinted body (unlike the COMMENT, which\n // is appended around it) — an install without the revokes IS a different fingerprint and is refused\n // at call time, so a stale PUBLIC-executable install cannot run while `--check` stays green.\n const aclSql = buildApplyFunctionAclSql(functionName, resolveGrantExecuteRoles(options.grantExecuteTo));\n\n return `\n-- Install idempotently by dropping the current signature first. PostgreSQL cannot change a function's\n-- return type through CREATE OR REPLACE, while a generated artifact must install its complete definition.\n--\n-- TWO-TIER MUTATION-ID INVARIANT. \\`mutation_id\\` is TEXT here (RETURNS TABLE + operations_log), not\n-- uuid, so this apply function can serve a DIRECT server-side caller that derives child envelopes with\n-- composite non-UUID ids (\\`\\${parentId}:<tag>:<n>\\`). That is the ONLY non-UUID path. pgxsinkit's public\n-- surface — the HTTP route's request/ack schemas and the client's \\`mutation_id UUID\\` journal — stays\n-- UUID-only (see packages/contracts/src/mutation.ts): the route validates every request id as a UUID and\n-- builds every ack from that request id, never from the TEXT conflict rows this returns. A non-UUID id\n-- therefore never crosses into the UUID-typed surface.\n--\nDROP FUNCTION IF EXISTS ${functionName}(${APPLY_FUNCTION_ARG_TYPES});\n\nCREATE OR REPLACE FUNCTION ${functionName}(\n p_batch jsonb,\n p_request_path text,\n p_log_enabled boolean,\n p_rls_enabled boolean,\n p_user_claims jsonb,\n p_expected_fingerprint text\n) RETURNS TABLE(mutation_id text, table_name text, current_server_version bigint) LANGUAGE plpgsql AS $$\nDECLARE\n dml_sql text;\n v_table text;\n v_kind text;\n v_sig text;\n v_rows jsonb;\n v_cols text;\n v_vals text;\n v_set text;\n -- ADR-0015: stale-write conflicts collected across the batch (mutationId + the row's current\n -- Server version), returned to the handler which turns them into 'conflicted' acks.\n v_conflicts jsonb := '[]'::jsonb;\n v_group_conflicts jsonb;\n -- ADR-0030: the fingerprint this installed function was stamped with (its own ADR-0018 comment),\n -- read back once for the self-verification gate below.\n _installed_fingerprint text;\n _claims jsonb;\n _target_role text;\n _previous_role text;\n _previous_claims text;\n _previous_claim_sub text;\nBEGIN\n -- ADR-0030: the apply function verifies ITSELF against its ADR-0018 fingerprint comment before it\n -- touches any table. p_expected_fingerprint is what the running server expects for its registry +\n -- codegen; obj_description(...) is the fingerprint this installed function was stamped with, atomically,\n -- by the same migration. A mismatch — INCLUDING an absent comment (an unstamped hand-installed\n -- function ⇒ NULL, refused per ADR-0030) — means the installed function is stale relative to the caller,\n -- so raise SQLSTATE 'PXS01' and apply nothing. The check IS the call (no read-then-call TOCTOU) and\n -- costs no extra round trip (the argument rides the existing invocation; the comparison is one text\n -- equality). The signature literal is embedded, never the fingerprint hash itself — baking the hash\n -- into the body would be circular with the hash-of-body the fingerprint is.\n _installed_fingerprint := obj_description('${functionName}(${APPLY_FUNCTION_ARG_TYPES})'::regprocedure, 'pg_proc');\n IF p_expected_fingerprint IS DISTINCT FROM _installed_fingerprint THEN\n RAISE EXCEPTION 'pgxsinkit_apply_mutations is stale: the installed apply-function fingerprint (%) does not match the fingerprint this server expects (%). Regenerate the sync-function migration (pgxsinkit-generate) and apply it before serving writes.', COALESCE(_installed_fingerprint, '(none)'), p_expected_fingerprint\n USING ERRCODE = 'PXS01';\n END IF;\n\n IF p_rls_enabled THEN\n -- Capture the caller's role/claims before switching into the RLS actor context, so the\n -- batch does not leak that context into the rest of the caller's transaction. The HTTP\n -- route RESET ROLEs after calling this function, but in-transaction callers cannot —\n -- restoring here leaves every caller exactly as it was found.\n _previous_role := current_setting('role', true);\n _previous_claims := current_setting('request.jwt.claims', true);\n _previous_claim_sub := current_setting('request.jwt.claim.sub', true);\n _claims := COALESCE(p_user_claims, '{}'::jsonb);\n _target_role := COALESCE(NULLIF(_claims ->> 'role', ''), 'authenticated');\n BEGIN\n IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = _target_role) THEN\n PERFORM set_config('role', _target_role, true);\n ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN\n PERFORM set_config('role', 'authenticated', true);\n END IF;\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', _claims::text, true);\n IF _claims ? 'sub' THEN\n PERFORM set_config('request.jwt.claim.sub', _claims ->> 'sub', true);\n END IF;\n END IF;\n\n IF jsonb_typeof(p_batch) <> 'object' THEN\n RAISE EXCEPTION 'Batch payload must be a JSON object';\n END IF;\n\n IF jsonb_typeof(p_batch->'mutations') <> 'array' THEN\n RAISE EXCEPTION 'Batch payload mutations must be a JSON array';\n END IF;\n\n -- Group the batch by (table, kind, payload column-set) and apply each group with one statement\n -- (ADR-0014 Phase 4). mutationSeq is table-local, so it cannot order groups across tables: parent\n -- and child journals can both start at 1. WITH ORDINALITY preserves the submitted JSON array order\n -- across tables (FK-safe; the batch transaction also runs SET CONSTRAINTS ALL DEFERRED).\n FOR v_table, v_kind, v_sig, v_rows IN\n SELECT\n grouped.table_name,\n grouped.kind,\n grouped.sig,\n jsonb_agg(grouped.mutation ORDER BY grouped.batch_position)\n FROM (\n SELECT\n entries.m->>'tableName' AS table_name,\n entries.m->>'kind' AS kind,\n COALESCE((\n SELECT string_agg(payload_key, ',' ORDER BY payload_key)\n FROM jsonb_object_keys(COALESCE(entries.m->'payload', '{}'::jsonb)) AS payload_key\n ), '') AS sig,\n entries.m AS mutation,\n entries.batch_position\n FROM jsonb_array_elements(p_batch->'mutations') WITH ORDINALITY AS entries(m, batch_position)\n ) AS grouped\n GROUP BY grouped.table_name, grouped.kind, grouped.sig\n ORDER BY MIN(grouped.batch_position)\n LOOP\n dml_sql := NULL;\n v_cols := NULL;\n v_vals := NULL;\n v_set := NULL;\n\n IF FALSE THEN\n NULL;\n ${tableBranches}\n ELSE\n RAISE EXCEPTION 'Unknown table \"%\" in batch mutation', v_table;\n END IF;\n END LOOP;\n\n IF p_log_enabled THEN\n -- One batched log insert (the whole batch is a single transaction, so a per-mutation loop\n -- bought nothing): a runtime apply failure above rolls the whole transaction back, log rows\n -- included, preserving the existing whole-batch-failure semantics.\n INSERT INTO operations_log (\n table_name,\n operation_kind,\n entity_key_json,\n payload_json,\n status,\n http_status,\n mutation_id,\n mutation_seq,\n client_timestamp_us,\n request_path,\n server_timestamp_us\n )\n SELECT\n m->>'tableName',\n m->>'kind',\n COALESCE(m->'entityKey', '{}'::jsonb),\n COALESCE(m->'payload', '{}'::jsonb),\n 'succeeded',\n 200,\n -- mutation_id is text: a derived child envelope carries a composite non-UUID id\n -- (parent-id + tag + index), so no ::uuid cast (it would raise 22P02 on such an id).\n m->>'mutationId',\n (m->>'mutationSeq')::integer,\n NULLIF(m->>'clientTimestampUs', '')::bigint,\n p_request_path,\n -- The canonical microsecond clock (utilities migration); never the inline expression.\n ${CLOCK_US_CALL_SQL_TEXT}\n FROM jsonb_array_elements(p_batch->'mutations') AS m;\n END IF;\n\n IF p_rls_enabled THEN\n -- Restore the caller's prior role/claims captured above, so the RLS context applied for\n -- the batch does not persist into subsequent statements of the caller's transaction.\n BEGIN\n PERFORM set_config('role', COALESCE(NULLIF(_previous_role, ''), 'none'), true);\n EXCEPTION WHEN insufficient_privilege THEN NULL;\n END;\n PERFORM set_config('request.jwt.claims', COALESCE(_previous_claims, ''), true);\n PERFORM set_config('request.jwt.claim.sub', COALESCE(_previous_claim_sub, ''), true);\n END IF;\n\n -- ADR-0015: return the collected stale-write conflicts. Empty under last-write-wins (or when no\n -- write was stale), so the handler simply acks everything as today.\n RETURN QUERY\n SELECT\n -- mutation_id is text (see RETURNS TABLE): a stale derived child envelope's id is a composite\n -- non-UUID string, so return it verbatim — a ::uuid cast here would raise 22P02 and abort the batch.\n c->>'mutationId',\n c->>'tableName',\n (c->>'currentServerVersion')::bigint\n FROM jsonb_array_elements(v_conflicts) AS c;\nEND;\n$$;\n\n-- ADR-0054: deny by default. Emitted on EVERY install because the DROP above resets the ACL to\n-- Postgres's PUBLIC default (plus Supabase's default-privilege grants), so convergence cannot depend\n-- on install history. EXECUTE is owner-only unless the artifact was generated with an explicit\n-- --grant-execute-to; the grant list is the write path's ENTIRE trust boundary, because this function\n-- trusts the claims it is handed.\n${aclSql}\n`.trim();\n}\n\n/**\n * The fingerprint the installed apply function should carry for this registry + applier codegen\n * (ADR-0018). It is a hash of the exact generated DDL body, so it shifts on any registry-shape\n * change AND on any change to how the applier emits SQL (e.g. a @pgxsinkit/server upgrade) — the\n * two drift classes a bare signature check cannot see. It does NOT depend on TS-side row-filter /\n * customPredicate logic, which never enters the apply function (that shapes reads, not writes).\n */\nexport function expectedApplyFingerprint(\n registry: SyncTableRegistry,\n options: ApplyFunctionRenderOptions = {},\n): string {\n return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));\n}\n\nexport function buildPlpgsqlBatchFunctionDdl(\n registry: SyncTableRegistry,\n options: ApplyFunctionRenderOptions = {},\n): string {\n const body = buildApplyFunctionBody(registry, options);\n const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);\n const fingerprint = APPLY_FINGERPRINT_PREFIX + hashString(body);\n\n // ADR-0018: stamp the function with the fingerprint of this exact DDL body. Stored as a COMMENT\n // because it is function-scoped, replaced atomically with the function, and read back in one line\n // via obj_description — so the server (startup) and CI (pre-deploy) can both detect a function\n // that is stale relative to the registry + codegen it is meant to serve.\n return `${body}\\n\\nCOMMENT ON FUNCTION ${functionName}(${APPLY_FUNCTION_ARG_TYPES}) IS '${fingerprint}';`;\n}\n\nexport async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n registry: TRegistry,\n options: ApplyFunctionRenderOptions = {},\n): Promise<void> {\n const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);\n await db.execute(sql.raw(ddl));\n}\n\ntype AuthHelperPresenceRow = {\n authUid: string | null;\n};\n\nexport async function verifyRlsAuthHelpers<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n): Promise<void> {\n const result = await db.execute<AuthHelperPresenceRow>(sql`\n SELECT\n to_regprocedure('auth.uid()')::text AS \"authUid\"\n `);\n\n const row = Array.from(result as Iterable<unknown>, (entry) => entry as AuthHelperPresenceRow)[0];\n const missingHelpers = [row?.authUid ? null : \"auth.uid()\"].filter((value): value is string => value !== null);\n\n if (missingHelpers.length > 0) {\n throw new Error(\n `The write path requires Supabase auth helpers. Missing: ${missingHelpers.join(\", \")}. ` +\n \"Ensure auth.uid() is available (standard on Supabase-managed databases).\",\n );\n }\n}\n\n/**\n * A conflict the applier rejected under `reject-if-stale` (ADR-0015): either a **stale** write (the\n * Base server version the row has since advanced past — `currentServerVersion` is the row's current\n * version) or an UPDATE whose **target row is missing** (deleted by another writer —\n * `currentServerVersion` is `null`, the #6 discriminator). The handler surfaces it on the\n * `conflicted` ack.\n */\nexport interface MutationConflict {\n mutationId: string;\n tableName: string;\n currentServerVersion: string | null;\n}\n\ninterface MutationConflictRow {\n mutationId: string | null;\n tableName: string | null;\n currentServerVersion: string | null;\n}\n\nexport async function executePlpgsqlBatch(\n tx: TransactionClient,\n batch: BatchMutationRequest,\n requestPath: string,\n logEnabled: boolean,\n rlsEnabled: boolean,\n userClaims: Record<string, unknown>,\n // ADR-0030: the fingerprint the running server expects for its registry + codegen\n // (`expectedApplyFingerprint(registry)`, computed once per server instance). The installed apply\n // function compares it against its own stamped comment and raises SQLSTATE 'PXS01' on a mismatch —\n // in-body, atomic with the call, before it touches any table.\n expectedFingerprint: string,\n options: {\n functionSchema?: string;\n } = {},\n): Promise<MutationConflict[]> {\n const normalizedClaims = userClaims ?? {};\n // Typed identifier interpolation (never `sql.raw` of a hand-quoted name); the OUT-column aliases\n // are the generated function's fixed names. The schema goes through the SAME validator the renderer\n // uses, so a server configured with `applyFunctionSchema` names exactly what the artifact installed.\n const functionSchema = resolveApplyFunctionSchema(options.functionSchema);\n const functionRef = functionSchema\n ? sql`${sql.identifier(functionSchema)}.${sql.identifier(\"pgxsinkit_apply_mutations\")}`\n : sql`${sql.identifier(\"pgxsinkit_apply_mutations\")}`;\n\n // The applier RETURNS the stale-write conflicts (ADR-0015). Read them from the function's result\n // set; an empty set (the last-write-wins case, or nothing stale) means every mutation applied.\n const result = await tx.execute(\n sql`SELECT \"mutation_id\"::text AS \"mutationId\", \"table_name\" AS \"tableName\", \"current_server_version\"::text AS \"currentServerVersion\" FROM ${functionRef}(${JSON.stringify(batch)}::text::jsonb, ${requestPath}, ${logEnabled}, ${rlsEnabled}, ${JSON.stringify(normalizedClaims)}::text::jsonb, ${expectedFingerprint})`,\n );\n\n const rows = Array.from(result as Iterable<unknown>, (row) => row as MutationConflictRow);\n return rows.flatMap((row) =>\n row.mutationId != null\n ? [\n {\n mutationId: row.mutationId,\n tableName: row.tableName ?? \"\",\n currentServerVersion: row.currentServerVersion,\n } satisfies MutationConflict,\n ]\n : [],\n );\n}\n",
20
20
  "import { getTableName, sql } from \"drizzle-orm\";\nimport type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport type { RegistryRelations, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { operationsLogTable } from \"./schema\";\nimport type { OperationsLogConfig } from \"./types\";\n\ntype OperationsLogPresenceRow = {\n tableName: string | null;\n};\n\n/**\n * The `to_regclass` presence-probe target, derived from the real pgTable so the probe (and the\n * warning below) track a rename of `operationsLogTable`. Exported for the integration suite that\n * asserts the degraded no-log path against the same identity.\n */\nexport function operationsLogRegclassTarget(): string {\n return `public.${getTableName(operationsLogTable)}`;\n}\n\n/**\n * Ensures the operations_log table exists in the database.\n *\n * Returns `true` if the table is present, `false` if missing.\n * Consumers should include `operationsLogTable` from `@pgxsinkit/server`\n * in their Drizzle schema so `drizzle-kit generate`/`push` creates it.\n */\nexport async function ensureOperationsLogSchema<TRegistry extends SyncTableRegistry>(\n db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,\n config: OperationsLogConfig,\n): Promise<boolean> {\n if (!config.enabled) {\n return false;\n }\n\n try {\n const result = await db.execute<OperationsLogPresenceRow>(sql`\n SELECT to_regclass(${operationsLogRegclassTarget()})::text AS \"tableName\"\n `);\n\n const row = Array.from(result as Iterable<unknown>, (entry) => entry as OperationsLogPresenceRow)[0];\n\n if (!row?.tableName) {\n console.warn(\n `${getTableName(operationsLogTable)} table is missing. Add operationsLogTable from @pgxsinkit/server ` +\n \"to your Drizzle schema and run drizzle-kit generate/push to create it. \" +\n \"Operation logging will be disabled until the table exists.\",\n );\n return false;\n }\n\n return true;\n } catch (error) {\n console.warn(\"Unable to verify operations_log table:\", (error as Error)?.message ?? error);\n return false;\n }\n}\n",
21
21
  "/**\n * Resolve which origin (if any) a response's CORS headers should allow for this request.\n *\n * Entries are exact scheme+host[+port] strings (`https://app.example.com`, `http://localhost:5660`),\n * plus one special form: a literal `\"*\"` entry allows EVERY origin by reflecting the request's\n * `Origin` header back — never a literal `*` header value, which the Fetch spec rejects for\n * credentialed requests (the toolkit's requests carry `Authorization`). Reflection is sound here\n * because auth is a per-request bearer token, not ambient cookies: a hostile page cannot mint the\n * header, so the origin list is deployment hygiene rather than the security boundary. Use `\"*\"` for\n * dev/demo backends serving many local origins; enumerate exact origins for production.\n *\n * Returns `null` when the request has no `Origin` or it is not allowed — callers then omit CORS\n * headers entirely, and the browser blocks the read.\n */\nexport function resolveCorsOrigin(request: Request, origins: readonly string[]): string | null {\n const origin = request.headers.get(\"origin\");\n if (!origin) {\n return null;\n }\n return origins.includes(\"*\") || origins.includes(origin) ? origin : null;\n}\n",
22
22
  "// A tiny web-standard `fetch` router for the pgxsinkit server (ADR-0017). The server needs only\n// exact-path GET/POST routing, a small CORS layer, and an error boundary, so a focused router keeps\n// `@pgxsinkit/server` dependency-light and runnable on any `fetch` runtime — no web framework required.\n// The mutation handler, the control-plane routes, and the stream edge are all plain\n// `(Request) => Response` functions, so they can equally be mounted in someone else's framework.\n\nimport { resolveCorsOrigin } from \"./cors-origin\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nexport interface CorsConfig {\n /** Exact origins, or a `\"*\"` entry to allow every origin by reflection (see {@link resolveCorsOrigin}). */\n origins: string[];\n allowMethods: string[];\n allowHeaders: string[];\n}\n\n/** A CORS scope is matched either by exact pathname or by pathname prefix (e.g. `/api/`). */\nexport type CorsScope = { exact: string } | { prefix: string };\n\nexport type RouterErrorHandler = (error: unknown, request: Request) => Response | Promise<Response>;\n\nexport class FetchRouter {\n readonly #routes = new Map<string, FetchHandler>();\n #cors: CorsConfig | undefined;\n #corsMatchers: Array<(pathname: string) => boolean> = [];\n #onError: RouterErrorHandler | undefined;\n\n get(path: string, handler: FetchHandler): void {\n this.#routes.set(`GET ${path}`, handler);\n }\n\n post(path: string, handler: FetchHandler): void {\n this.#routes.set(`POST ${path}`, handler);\n }\n\n setCors(config: CorsConfig, scopes: CorsScope[]): void {\n this.#cors = config;\n this.#corsMatchers = scopes.map((scope) =>\n \"exact\" in scope\n ? (pathname: string) => pathname === scope.exact\n : (pathname: string) => pathname.startsWith(scope.prefix),\n );\n }\n\n setErrorHandler(handler: RouterErrorHandler): void {\n this.#onError = handler;\n }\n\n readonly fetch = async (request: Request): Promise<Response> => {\n const pathname = new URL(request.url).pathname;\n const corsApplies = this.#cors !== undefined && this.#corsMatchers.some((matches) => matches(pathname));\n\n // A preflight short-circuits before routing, exactly as a CORS middleware mounted on the scope would.\n if (request.method === \"OPTIONS\" && corsApplies) {\n return this.#preflight(request);\n }\n\n let response: Response;\n const handler = this.#routes.get(`${request.method} ${pathname}`);\n if (handler) {\n try {\n response = await handler(request);\n } catch (error) {\n if (!this.#onError) {\n throw error;\n }\n response = await this.#onError(error, request);\n }\n } else {\n response = new Response(\"Not Found\", { status: 404 });\n }\n\n return corsApplies ? this.#withCorsHeaders(request, response) : response;\n };\n\n #allowedOrigin(request: Request): string | null {\n return this.#cors ? resolveCorsOrigin(request, this.#cors.origins) : null;\n }\n\n #preflight(request: Request): Response {\n const headers = new Headers();\n const origin = this.#allowedOrigin(request);\n if (origin) {\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n }\n if (this.#cors) {\n headers.set(\"Access-Control-Allow-Methods\", this.#cors.allowMethods.join(\",\"));\n // Echo what the browser asks to send (e.g. a deployment gateway's `apikey` alongside the\n // toolkit's `Authorization`), falling back to the declared list — so a client header the app\n // legitimately sets is never rejected just because it wasn't enumerated here.\n headers.set(\n \"Access-Control-Allow-Headers\",\n request.headers.get(\"access-control-request-headers\") ?? this.#cors.allowHeaders.join(\",\"),\n );\n }\n return new Response(null, { status: 204, headers });\n }\n\n #withCorsHeaders(request: Request, response: Response): Response {\n const origin = this.#allowedOrigin(request);\n if (!origin) {\n return response;\n }\n const headers = new Headers(response.headers);\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n }\n}\n",
23
23
  "import { buildRoleGuardedStatement, NOW_MICROSECONDS_SQL_TEXT, quoteIdentifier } from \"@pgxsinkit/contracts\";\n\n/**\n * ADR-0054 decision 5: `pgxsinkit_clock_us()` is hardened in the same pass as the apply function — no\n * pgxsinkit-emitted function relies on default privileges. Unlike the apply function it is a harmless\n * monotonic-clock read whose legitimate callers INCLUDE RLS-context sessions (a column DEFAULT\n * evaluates as whatever role is writing the row), so PUBLIC is revoked and the Supabase trio is\n * granted back explicitly, through the shared role-existence guard so the migration stays portable.\n */\nconst CLOCK_US_SIGNATURE = \"public.pgxsinkit_clock_us()\";\nconst CLOCK_US_GRANTEES = [\"anon\", \"authenticated\", \"service_role\"] as const;\n\n/**\n * The canonical microsecond-clock DB function `public.pgxsinkit_clock_us()` — the ONE home for the\n * `clock_timestamp()`-epoch-microseconds semantics. Every surface (column DEFAULTs, the generated\n * apply function's managed `nowMicroseconds` fields, the operations-log server stamp) CALLS this\n * function; nothing inlines the expression. This migration installs it, and — because the generated\n * apply function calls it — it MUST be the FIRST folder in any consumer's migration chain (before the\n * schema and the sync-artifact folder).\n *\n * The body is composed from the single source {@link NOW_MICROSECONDS_SQL_TEXT} in @pgxsinkit/contracts\n * (CREATE FUNCTION is the sanctioned raw-SQL case — Drizzle cannot express a PL/pgSQL/SQL function body).\n */\nexport function renderPgxsinkitUtilitiesMigration(): string {\n return `-- The pgxsinkit canonical microsecond clock. Deliberately clock_timestamp() (advances WITHIN a\n-- transaction — LWW/audit ordering of multi-row applies depends on it), never now()/transaction_timestamp()\n-- (frozen at tx start). FLOOR + BIGINT: whole microseconds since epoch.\nCREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()\n RETURNS bigint\n LANGUAGE sql\n VOLATILE\nAS $$\n SELECT ${NOW_MICROSECONDS_SQL_TEXT}\n$$;\n\n-- Deny by default, then grant back deliberately (ADR-0054 decision 5). Stated on every install: a\n-- first install on a Supabase-shaped cluster otherwise picks up ALTER DEFAULT PRIVILEGES ... GRANT ALL\n-- ON FUNCTIONS TO anon, authenticated, service_role, so the posture is declared here, never inherited.\n-- The grants are real: a column DEFAULT calling this clock is evaluated as whatever role writes the row.\nREVOKE ALL ON FUNCTION ${CLOCK_US_SIGNATURE} FROM PUBLIC;\n\n${CLOCK_US_GRANTEES.map((role) =>\n buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${CLOCK_US_SIGNATURE} TO ${quoteIdentifier(role)}`),\n).join(\"\\n\\n\")}`;\n}\n",
24
- "import {\n getSyncRegistryStreams,\n type EventQueueMessage,\n type StampedEvent,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n MalformedEventQueueMessageError,\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueReceipt,\n} from \"./queue\";\n\n/**\n * The **Event lane**'s consumer runner (ADR-0053 decisions 6 and 7): the library defines it, the app hosts it.\n *\n * `defineEventConsumer` returns a `start()`/`stop()` handle the app runs in its OWN long-lived Bun process —\n * the toolkit's first long-lived server artifact, deliberately separate from `createSyncServer`'s\n * zero-startup-query serverless posture. There is no supervisor, no CLI entrypoint, no daemon and no signal\n * handling here: the app owns its process lifecycle and calls `stop()` from wherever it already handles\n * shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside\n * `start()`.\n *\n * Because the app owns the process, it also owns the health endpoint — so the runner reports the one thing\n * that endpoint cannot see from outside: {@link DefineEventConsumerOptions.onPoll} fires after EVERY read,\n * productive or empty, in both pacing modes. Beat a liveness probe from that, never from `callback`, which\n * by design says nothing at all while the queue is idle.\n *\n * One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in\n * one stream must never head-of-line-block another), so small deployments run one process and large ones split\n * `streams` across processes.\n *\n * **Pacing is adaptive interval polling, and it is INTERNAL** (ADR-0053 decision 7 — out of consumer-app design\n * space by ratified requirement; only the floor/ceiling/factor are exposed as tuning, never as contract):\n *\n * - a NON-EMPTY read is followed by an immediate re-read, so a backlog drains back-to-back;\n * - consecutive EMPTY reads grow the wait from a floor ({@link DEFAULT_EVENT_POLL_FLOOR_MS}) toward an idle\n * ceiling ({@link DEFAULT_EVENT_POLL_CEILING_MS}) by {@link DEFAULT_EVENT_POLL_FACTOR};\n * - one non-empty read resets the wait to the floor.\n *\n * LISTEN/NOTIFY and `pgmq.read_with_poll` long-polling are REJECTED as wake mechanisms (ADR-0053, maintainer\n * decision): Bun's native `SQL` — the sanctioned Postgres driver — has no LISTEN/NOTIFY, and both mechanisms\n * hold a connection per stream through the transaction poolers the consumers' stacks run behind. Because\n * pacing is internal, the mechanism can change later without any contract change.\n *\n * **Leases are RENEWED while a read is being worked through; a thrown sub-batch's lease is deliberately left\n * to lapse** (ADR-0053 decision 7: visibility renewal is internal). One read makes up to `batchSize` messages\n * invisible at once, so the timeout cannot be \"the processing budget\": ten ordinary ten-second callbacks\n * would outlive a 60-second window for the later messages, and in a documented multi-runner deployment\n * another process would pick them up while the first is still working toward them. So for as long as a read\n * is in flight the runner extends EVERY not-yet-settled receipt of that read — the one running plus the ones\n * still queued behind it — every `visibilityTimeoutSeconds / 2`. Renewal is best-effort: a failure is\n * warn-logged and the loop carries on, because redelivery is the safety net it would fall back on anyway.\n *\n * `visibilityTimeoutSeconds` therefore means two retry-shaped things, never a budget:\n *\n * - **the redelivery delay of a FAILED sub-batch.** A callback that throws is not acked AND is dropped from\n * renewal immediately, so its lease lapses and the queue redelivers it with an incremented `deliveryCount`.\n * That lapse IS the retry pacing — the runner never sleeps \"on behalf of\" a failed message, and if a\n * backend ever wants exponential redelivery backoff it belongs INSIDE that backend, behind the\n * {@link EventQueue} seam, so the runner stays backend-agnostic;\n * - **the crash-recovery bound.** A runner that dies takes its renewals with it, so everything it held comes\n * back one timeout later.\n *\n * **A graceful stop does not cancel renewal — it narrows it.** `stop()` starts no further read and no further\n * callback, but the callbacks already in flight are AWAITED and then acked, so their receipts must stay\n * invisible until they settle: cancelling renewal at `stop()` would hand a second runner the very message\n * this one is deliberately finishing, on every ordinary SIGTERM/rollout. What IS released at `stop()` is the\n * rest of that read — the messages no callback has started — which drop out of the renewal set so their\n * leases lapse and the queue redelivers them promptly. `stop()` therefore resolves only once every in-flight\n * callback has settled AND its renewal task has shut down.\n *\n * **The SECOND pacing mode: `drainOnce()`, for hosts that cannot hold a process** (ADR-0053 amendment,\n * 2026-08-02). Everything above describes the primary mode. A serverless-only deployment — managed\n * Supabase, whose edge functions are the only compute — has nowhere to put a `start()`; its queue would\n * simply never drain. So the SAME handle also answers `drainOnce({ budgetMs })`: one bounded pass that\n * reads/delivers/acks through the identical internals until every stream reads empty or the wall-clock\n * budget runs out. Nothing about the delivery contract moves — at-least-once, batch-internal order only,\n * dead-lettering to the backend's archive are all the same code — because pacing was internal from the\n * start (decision 7), which is exactly what makes this a HOSTING addition rather than a contract change.\n * The long-lived runner remains the primary mode; `drainOnce` is what a scheduled invocation calls.\n */\n\n/** Max messages (each ONE single-stream sub-batch) a single read delivers, when the app sets nothing. */\nexport const DEFAULT_EVENT_CONSUMER_BATCH_SIZE = 10;\n/**\n * How long a delivered sub-batch stays invisible, when the app sets nothing — and how long the runner extends\n * it by on each renewal (it renews at half this). Healthy long processing is covered by renewal, so this is\n * the REDELIVERY DELAY of a sub-batch whose callback threw and the crash-recovery bound, not a budget: it\n * wants to sit above a single callback's worst case (too short redelivers a callback that is merely slower\n * than one renewal interval), never above the whole batch's.\n */\nexport const DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS = 60;\n/** Deliveries a sub-batch gets before a further callback failure dead-letters it, when the app sets nothing. */\nexport const DEFAULT_EVENT_MAX_ATTEMPTS = 5;\n/** The adaptive poll's floor — the wait after the FIRST empty read (ADR-0053 decision 7: ~250 ms). */\nexport const DEFAULT_EVENT_POLL_FLOOR_MS = 250;\n/** The adaptive poll's idle ceiling — the longest an idle stream ever waits between reads. */\nexport const DEFAULT_EVENT_POLL_CEILING_MS = 5_000;\n/** How fast consecutive empty reads grow the wait from the floor toward the ceiling. */\nexport const DEFAULT_EVENT_POLL_FACTOR = 2;\n/**\n * The wall-clock budget one {@link EventConsumer.drainOnce} pass gets, when the caller sets nothing.\n *\n * **Set it under your platform's invocation wall-clock cap**, with head-room for one callback: the budget is\n * only ever checked BETWEEN sub-batches, so a pass can overrun it by however long the callback that was\n * already running takes. 25 s suits the common serverless caps (Supabase Edge, Vercel, Cloud Run jobs); a\n * platform with a tighter cap wants a tighter budget, and a generous one (a cron container) can raise it.\n */\nexport const DEFAULT_EVENT_DRAIN_BUDGET_MS = 25_000;\n\n/**\n * Adaptive-poll tuning. Defaults are the ADR's; they are TUNING, not contract — the pacing mechanism itself is\n * internal and may change.\n */\nexport interface EventConsumerPollOptions {\n /** The wait after the first empty read. Defaults to {@link DEFAULT_EVENT_POLL_FLOOR_MS}. */\n floorMs?: number;\n /** The longest wait an idle stream reaches. Defaults to {@link DEFAULT_EVENT_POLL_CEILING_MS}. */\n ceilingMs?: number;\n /** The growth factor per consecutive empty read. Defaults to {@link DEFAULT_EVENT_POLL_FACTOR}. */\n factor?: number;\n}\n\n/** One callback invocation: exactly ONE delivered queue message, i.e. one single-stream sub-batch. */\nexport interface EventConsumerBatch {\n /** The Event stream these events were appended under. */\n stream: string;\n /**\n * The stamped envelopes, EXACTLY as the ingestion endpoint enqueued them (ADR-0053 decision 5) — in append\n * order within this sub-batch. Across sub-batches there is no ordering promise (decision 6).\n */\n events: readonly StampedEvent[];\n}\n\n/**\n * The consumer callback. Returning (resolving) ACKS the sub-batch; THROWING retries it — the message stays\n * invisible until its visibility timeout lapses and the queue redelivers it.\n *\n * It MUST be idempotent (ADR-0053 decision 6, at-least-once): the blessed pattern is deduping on `eventId`\n * against the app's own durable store, which composes to effectively-exactly-once.\n */\nexport type EventConsumerCallback = (batch: EventConsumerBatch) => void | Promise<void>;\n\n/** What {@link DefineEventConsumerOptions.onDeadLetter} is told about a sub-batch the runner gave up on. */\nexport interface EventDeadLetterReport {\n stream: string;\n /** Why it was dead-lettered — the same reason recorded in the backend's dead-letter storage. */\n reason: string;\n /** Deliveries this message had received. `0` when the body was unreadable (nothing was ever delivered from it). */\n attempts: number;\n /** The receipt it was dead-lettered under — always present, including for an unparseable body. */\n receipt: EventQueueReceipt;\n /** The message, when it was readable. Absent for a malformed body (that is exactly what could not be parsed). */\n message?: EventQueueMessage;\n /** The error behind it: the callback's throw, or the {@link MalformedEventQueueMessageError}. */\n cause?: unknown;\n}\n\n/**\n * What {@link DefineEventConsumerOptions.onPoll} is told after each read — the host's liveness heartbeat.\n *\n * One report per read the runner performs, productive or not, in BOTH pacing modes. `delivered` counts the\n * sub-batches that read returned (the queue's unit: one message, one callback invocation), and `empty` is\n * exactly `delivered === 0` — including on a faulted read, which is why `fault` is a separate flag rather\n * than something to infer from the counts.\n */\nexport interface EventPollReport {\n /** The Event stream that was read. Each stream has its own loop, so each beats on its own cadence. */\n readonly stream: string;\n /** Sub-batches this read returned. `0` on an empty or faulted read. */\n readonly delivered: number;\n /** `delivered === 0` — nothing came back from this read. */\n readonly empty: boolean;\n /**\n * The read itself FAILED: a queue/database fault, or a message body that could not be parsed (which fails\n * the whole read). The runner backs off and carries on either way — a fault never ends a loop — so a host\n * watching the heartbeat still sees it turning, and this is what tells it the queue is unhealthy.\n */\n readonly fault: boolean;\n /** When the read settled, from the runner's own clock (`Date.now` unless one is injected). */\n readonly at: number;\n}\n\n/**\n * The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never\n * lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.\n */\nexport type EventConsumerSleep = (ms: number, signal: AbortSignal) => Promise<void>;\n\n/** What {@link EventConsumer.drainOnce} is tuned with. */\nexport interface EventDrainOptions {\n /**\n * The pass's wall-clock budget. Defaults to {@link DEFAULT_EVENT_DRAIN_BUDGET_MS}. Checked between\n * sub-batches only, never inside a callback — so size it under the invocation's cap with head-room for\n * one callback's worst case.\n */\n budgetMs?: number;\n}\n\n/** What one {@link EventConsumer.drainOnce} pass reports back. Counts are SUB-BATCHES (one queue message,\n * one callback invocation), the unit the queue and the dead-letter archive both work in. */\nexport interface EventDrainSummary {\n /**\n * Sub-batches whose callback completed during this pass. An ack that then failed still counts — the work\n * was delivered, and at-least-once means it may be delivered again later (the callback is idempotent).\n */\n delivered: number;\n /** Sub-batches this pass moved to the backend's dead-letter storage. */\n deadLettered: number;\n /**\n * `true` when every configured Event stream read empty before the budget ran out — the queue is drained\n * as far as this pass can see.\n *\n * `false` means the pass ended with work possibly still queued: the budget cut it short, or a stream's\n * read faulted. It is the caller's signal that another tick has something to do — a scheduler that\n * chains passes should invoke again promptly rather than waiting out its full period.\n */\n empty: boolean;\n}\n\nexport interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry> {\n /** The sync registry whose `streams` this runner consumes. */\n registry: TRegistry;\n /**\n * The queue to consume from — REQUIRED, and the reason the runner is backend-agnostic by construction. The\n * ordinary wiring is `createPgmqEventQueue({ db })` with the app's own drizzle handle; constructing it here\n * from a `db` option would bake the shipped backend into the runner for one line of ergonomics.\n */\n queue: EventQueue;\n callback: EventConsumerCallback;\n /**\n * Narrow to a subset of the registered Event streams — the knob that splits streams across processes.\n * Defaults to ALL registered streams. An unknown name is a definition-time throw (fail-closed): a runner\n * that silently consumed nothing is the failure mode this forbids.\n */\n streams?: readonly string[];\n /** Max messages per read. Defaults to {@link DEFAULT_EVENT_CONSUMER_BATCH_SIZE}. */\n batchSize?: number;\n /**\n * The delivered-message invisibility window, renewed at half of it while the runner is still working\n * through a read. Defaults to {@link DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS}. Size it above ONE\n * callback's worst case (renewal covers the rest of the batch), not above the whole batch's.\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Max CONCURRENT callback invocations per Event stream. Defaults to `1` (strictly sequential). Values above 1\n * are safe for the idempotent callback the lane already requires: ADR-0053 decision 6 disclaims any ordering\n * across sub-batches precisely so concurrency is available. Reads stay serial — only the callbacks of one\n * delivered read run in parallel.\n */\n concurrency?: number;\n /**\n * Deliveries a sub-batch gets before a further callback failure dead-letters it. Defaults to\n * {@link DEFAULT_EVENT_MAX_ATTEMPTS}. A malformed body never gets attempts — it dead-letters on sight.\n */\n maxAttempts?: number;\n /** Adaptive-poll tuning. See {@link EventConsumerPollOptions}. */\n poll?: EventConsumerPollOptions;\n /**\n * Notified for every dead-lettered sub-batch. The runner ALSO warn-logs each one unconditionally: loudness is\n * the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.\n */\n onDeadLetter?: (report: EventDeadLetterReport) => void;\n /**\n * Notified after EVERY read the runner performs — productive or empty, in both pacing modes — which makes it\n * the host's **liveness heartbeat**. The {@link DefineEventConsumerOptions.callback} fires only on delivered\n * batches, so on an idle queue it goes quiet and a liveness/readiness probe answering from it would report a\n * healthy runner as dead; beat from this instead and treat `fault` as the queue-health signal.\n *\n * It fires on the READ, before the batch is delivered, so a slow callback cannot delay the heartbeat. A hook\n * that THROWS can never take a loop down: the throw is caught, warn-logged ONCE per runner (a hook that\n * throws every poll must not drown the log), and the loop carries on.\n */\n onPoll?: (report: EventPollReport) => void;\n /** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */\n sleep?: EventConsumerSleep;\n /** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */\n now?: () => number;\n /**\n * @internal The injectable RENEWAL wait, deliberately a second seam rather than `sleep`: the two cadences\n * are independent (one paces reads, one paces lease renewal) and sharing one would make every pacing\n * assertion depend on renewal timing. Defaults to `setTimeout`.\n */\n renewalSleep?: EventConsumerSleep;\n}\n\nexport interface EventConsumer {\n /**\n * Begin every stream's loop. Idempotent; a no-op after {@link EventConsumer.stop}. Throws while a\n * {@link EventConsumer.drainOnce} pass is in flight — one handle drives one pacing mode at a time.\n */\n start: () => void;\n /**\n * Graceful stop: no new reads, no new callbacks, in-flight callbacks are awaited (and their leases KEPT\n * renewed until they ack or dead-letter), and the promise resolves when every loop — and every renewal\n * task it still owned — is quiet. Safe to call twice (the second call awaits the first). Messages of an\n * in-progress read whose callback had not started are released at once: they stop being renewed and are\n * left unacked, so at-least-once redelivers them as soon as their lease lapses.\n *\n * A `drainOnce` pass in flight is treated the same way: it starts no further read, finishes the callback\n * it is on, and `stop()` resolves once it has.\n */\n stop: () => Promise<void>;\n /**\n * One bounded drain pass — the pacing mode for a host that cannot hold a process (ADR-0053 amendment,\n * 2026-08-02).\n *\n * It walks every configured Event stream, read → deliver → ack, and keeps going until EITHER every stream\n * has returned an empty read OR the wall-clock budget is spent. Same internals as the loop mode\n * throughout: the same read/deliver/ack path, the same lease renewal while a callback runs, the same\n * per-sub-batch retry-by-lapsing-lease, the same dead-lettering after `maxAttempts` with the same\n * `onDeadLetter` hook and unconditional warn log. It never sleeps: a stream that reads empty is finished\n * for this pass, and there is no adaptive interval to wait out.\n *\n * **The budget is checked BETWEEN sub-batches, never inside one.** A callback already running is awaited\n * and acked exactly as the runner would (its lease stays renewed throughout), and no new read starts once\n * the budget is gone — so a pass can overrun its budget by one callback, and `budgetMs` must leave\n * head-room for that under the platform's invocation cap. A sub-batch whose callback THROWS near the\n * budget edge is not special-cased: it is left unacked and dropped from renewal, its lease lapses, and the\n * queue redelivers it on a later pass with an incremented delivery count. That is at-least-once working as\n * designed, not a lost event — and it is why the callback must be idempotent.\n *\n * **Hosting it.** Wire a SCHEDULED invocation (a platform cron, e.g. every 10 s) that calls `drainOnce`\n * and, optionally, an ingest-side nudge (`createSyncServer({ onEventsEnqueued })` firing a\n * fetch-and-forget at the same endpoint) so an interactive append is drained in milliseconds instead of\n * waiting for the next tick. The **schedule is the delivery guarantee; the nudge is only latency** — a\n * lost nudge costs nothing but time. Overlapping invocations are SAFE: two processes reading the same\n * queue are arbitrated by the visibility timeout, exactly as two long-lived runners would be. (Two passes\n * on ONE handle are not — that is a bug, and throws; see below.)\n *\n * **One handle, one pacing mode.** Throws if `start()` is live, if another `drainOnce` is already in\n * flight on this handle, or if the handle has been stopped — the lifecycle is one-way, so the next drain\n * builds a fresh `defineEventConsumer` (construction is query-free, so that costs nothing).\n */\n drainOnce: (options?: EventDrainOptions) => Promise<EventDrainSummary>;\n}\n\n/**\n * The adaptive wait for `idleCount` CONSECUTIVE unproductive reads (an empty read or a queue fault), clamped to\n * the ceiling. `idleCount` is 1 for the first one; a productive read resets it to 0 and re-reads immediately.\n */\nexport function computeEventPollWaitMs(idleCount: number, options: EventConsumerPollOptions = {}): number {\n const floorMs = options.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS;\n const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS;\n const factor = options.factor ?? DEFAULT_EVENT_POLL_FACTOR;\n const exponent = Math.max(idleCount - 1, 0);\n return Math.min(Math.round(floorMs * factor ** exponent), ceilingMs);\n}\n\n/** The production wait: a `setTimeout` that is CLEARED on abort, so `stop()` never leaves a timer holding the process open. */\nconst abortableSleep: EventConsumerSleep = (ms, signal) =>\n new Promise<void>((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n let handle: ReturnType<typeof setTimeout> | undefined;\n const finish = (): void => {\n if (handle !== undefined) {\n clearTimeout(handle);\n }\n signal.removeEventListener(\"abort\", finish);\n resolve();\n };\n handle = setTimeout(finish, ms);\n signal.addEventListener(\"abort\", finish, { once: true });\n });\n\nfunction assertPositive(label: string, value: number, minimum: number): number {\n if (!Number.isFinite(value) || value < minimum) {\n throw new Error(\n `pgxsinkit: defineEventConsumer's \\`${label}\\` must be a finite number >= ${minimum} (got ${value}).`,\n );\n }\n return value;\n}\n\nexport function defineEventConsumer<TRegistry extends SyncTableRegistry>(\n options: DefineEventConsumerOptions<TRegistry>,\n): EventConsumer {\n // ─── Definition-time resolution (fail-closed, and query-free) ────────────────────────────────────────\n const registered = getSyncRegistryStreams(options.registry) ?? {};\n const registeredNames = Object.keys(registered);\n if (registeredNames.length === 0) {\n throw new Error(\n \"pgxsinkit: this registry registers no Event streams, so there is nothing for a consumer runner to \" +\n \"consume. Register one with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.\",\n );\n }\n\n let streams: string[];\n if (options.streams) {\n const unknown = options.streams.filter((stream) => !Object.hasOwn(registered, stream));\n if (unknown.length > 0) {\n // Every offender is named: a typo'd stream on a runner would otherwise present as \"the events never\n // arrive\", which is the most expensive shape of silence in the lane.\n throw new Error(\n `pgxsinkit: defineEventConsumer was asked for Event stream(s) [${unknown.join(\", \")}] this registry ` +\n `does not register — it registers [${registeredNames.join(\", \")}].`,\n );\n }\n streams = [...new Set(options.streams)];\n if (streams.length === 0) {\n throw new Error(\n \"pgxsinkit: defineEventConsumer was given an empty `streams` list. Omit it to consume every registered \" +\n \"Event stream, or name at least one.\",\n );\n }\n } else {\n streams = registeredNames;\n }\n\n const batchSize = assertPositive(\"batchSize\", options.batchSize ?? DEFAULT_EVENT_CONSUMER_BATCH_SIZE, 1);\n const visibilityTimeoutSeconds = assertPositive(\n \"visibilityTimeoutSeconds\",\n options.visibilityTimeoutSeconds ?? DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n 1,\n );\n const concurrency = assertPositive(\"concurrency\", options.concurrency ?? 1, 1);\n const maxAttempts = assertPositive(\"maxAttempts\", options.maxAttempts ?? DEFAULT_EVENT_MAX_ATTEMPTS, 1);\n const poll = options.poll ?? {};\n const floorMs = assertPositive(\"poll.floorMs\", poll.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS, 0);\n const ceilingMs = assertPositive(\"poll.ceilingMs\", poll.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS, floorMs);\n const factor = assertPositive(\"poll.factor\", poll.factor ?? DEFAULT_EVENT_POLL_FACTOR, 1);\n const pollOptions: EventConsumerPollOptions = { floorMs, ceilingMs, factor };\n\n const queue = options.queue;\n const sleep = options.sleep ?? abortableSleep;\n const renewalSleep = options.renewalSleep ?? abortableSleep;\n const now = options.now ?? Date.now;\n /** Renew at HALF the window: one missed renewal still leaves a full half-window of head-room. */\n const renewalIntervalMs = Math.max(1, Math.floor((visibilityTimeoutSeconds * 1000) / 2));\n\n // ─── Lifecycle state ─────────────────────────────────────────────────────────────────────────────────\n const stopController = new AbortController();\n let started = false;\n let stopping = false;\n let loops: Promise<void>[] = [];\n let stopPromise: Promise<void> | null = null;\n /** The in-flight bounded drain, if any — the second pacing mode's whole lifecycle state. */\n let activeDrain: Promise<EventDrainSummary> | null = null;\n /**\n * The counters of the drain pass in flight, or `null` in loop mode. The settle points below feed it\n * rather than returning counts, so `drainOnce` reports on the SAME delivery path the runner uses instead\n * of a parallel one. Exactly one pass can be in flight (the mode is mutually exclusive), so one slot is\n * all this needs.\n */\n let drainStats: { delivered: number; deadLettered: number } | null = null;\n\n // ─── The per-read heartbeat ──────────────────────────────────────────────────────────────────────────\n /** Latched once the `onPoll` hook has thrown: the warn is per RUNNER, not per poll (see the option's doc). */\n let pollHookFailed = false;\n /**\n * Beat once for one completed read. Called from BOTH pacing modes and from the fault paths, so a host\n * watching this sees every turn of every loop; `empty` is derived here so the two modes cannot disagree\n * about what an empty read is.\n */\n const reportPoll = (stream: string, delivered: number, fault: boolean): void => {\n if (!options.onPoll) {\n return;\n }\n try {\n options.onPoll({ stream, delivered, empty: delivered === 0, fault, at: now() });\n } catch (error) {\n // A liveness hook that throws must never be able to stop the loop it is observing — that would turn a\n // reporting bug into an outage. Loud once, then silent: it typically throws on EVERY poll.\n if (!pollHookFailed) {\n pollHookFailed = true;\n console.warn(\n \"pgxsinkit: the `onPoll` hook threw; the event consumer carries on regardless (this is warned once \" +\n \"per runner, not once per poll)\",\n error,\n );\n }\n }\n };\n\n // ─── Dead-lettering (ADR-0053 decision 7: the loudness lives HERE) ───────────────────────────────────\n const reportDeadLetter = (report: EventDeadLetterReport): void => {\n // Unconditional, and deliberately not the client report surface's \"warn only when nobody subscribed\"\n // rule: a dead letter is rare and terminal, so it is worth a line in the operator's log even when the\n // app also handles it.\n console.warn(\n `pgxsinkit: dead-lettered an event sub-batch on Event stream \"${report.stream}\" (receipt ${report.receipt}, ` +\n `${report.attempts} delivery attempt(s)) — ${report.reason}. It is in the queue's dead-letter storage; ` +\n \"requeue it deliberately with `requeueDeadLetter` once the cause is fixed.\",\n report.cause,\n );\n if (!options.onDeadLetter) {\n return;\n }\n try {\n options.onDeadLetter(report);\n } catch (error) {\n console.error(\"pgxsinkit: the `onDeadLetter` hook threw; the message is dead-lettered regardless\", error);\n }\n };\n\n /** Move one message to dead-letter storage and report it. Resolves `false` when the QUEUE refused the move. */\n const deadLetter = async (\n stream: string,\n receipt: EventQueueReceipt,\n attempts: number,\n reason: string,\n cause: unknown,\n message?: EventQueueMessage,\n ): Promise<boolean> => {\n try {\n await queue.deadLetter(stream, [receipt], reason);\n } catch (error) {\n // The message is still queued and still invisible; it redelivers and dead-letters on a later pass.\n console.warn(\n `pgxsinkit: could not dead-letter message ${receipt} on Event stream \"${stream}\"; it stays queued and ` +\n \"will be retried\",\n error,\n );\n return false;\n }\n if (drainStats) {\n drainStats.deadLettered += 1;\n }\n reportDeadLetter({ stream, reason, attempts, receipt, ...(message ? { message } : {}), cause });\n return true;\n };\n\n // ─── Lease renewal (ADR-0053 decision 7: internal, and not optional) ─────────────────────────────────\n /**\n * Keep every UNSETTLED receipt of one read invisible for as long as that read is being worked through.\n * Returns the stopper, which the caller awaits so no renewal outlives its read (a stray timer would hold\n * the app's process open, and a stray extension would delay a redelivery the runner no longer wants).\n *\n * Its lifetime is the READ's, deliberately NOT the runner's: this task is wired to its OWN controller and\n * never to `stopController`. A graceful stop still awaits the callbacks already in flight, so aborting\n * renewal there would let their leases lapse mid-callback and let another runner take the work this one is\n * finishing. `stop()` instead shrinks `unsettled` (see `processDelivered`), and the loop below exits on its\n * own the moment that set drains.\n */\n const startRenewal = (stream: string, unsettled: Set<EventQueueReceipt>): (() => Promise<void>) => {\n const controller = new AbortController();\n\n const task = (async () => {\n while (!controller.signal.aborted && unsettled.size > 0) {\n await renewalSleep(renewalIntervalMs, controller.signal);\n if (controller.signal.aborted || unsettled.size === 0) {\n return;\n }\n try {\n await queue.extendVisibility(stream, [...unsettled], visibilityTimeoutSeconds);\n } catch (error) {\n // Best-effort by design: the worst case of a failed renewal is the behaviour there would be with\n // no renewal at all — the lease lapses and the sub-batch is redelivered to an idempotent callback.\n console.warn(\n `pgxsinkit: could not renew the visibility lease on Event stream \"${stream}\" (receipts ` +\n `${[...unsettled].join(\", \")}); the sub-batch may be redelivered while it is still being processed`,\n error,\n );\n }\n }\n })();\n\n return async () => {\n controller.abort();\n await task;\n };\n };\n\n // ─── One delivered message ───────────────────────────────────────────────────────────────────────────\n const processMessage = async (\n stream: string,\n delivered: DeliveredEventMessage,\n /** Drop this message from the read's renewal set — it is settled, one way or the other. */\n settle: () => void,\n ): Promise<void> => {\n try {\n await options.callback({ stream, events: delivered.message.events });\n } catch (error) {\n // Settled the moment it throws, and settled FIRST: a failed sub-batch's lease is deliberately allowed\n // to lapse, because that lapse IS the retry pacing. Renewing it would postpone its own redelivery.\n settle();\n const detail = error instanceof Error ? error.message : String(error);\n if (delivered.deliveryCount >= maxAttempts) {\n await deadLetter(\n stream,\n delivered.receipt,\n delivered.deliveryCount,\n `the consumer callback failed on delivery ${delivered.deliveryCount} of ${maxAttempts}: ${detail}`,\n error,\n delivered.message,\n );\n return;\n }\n // NOT acked, and no longer renewed: the lapsing lease IS the retry pacing (see the module note).\n console.warn(\n `pgxsinkit: the event consumer callback failed for Event stream \"${stream}\" (receipt ${delivered.receipt}, ` +\n `delivery ${delivered.deliveryCount} of ${maxAttempts}); the sub-batch will be redelivered after its ` +\n `${visibilityTimeoutSeconds}s visibility timeout`,\n error,\n );\n return;\n }\n\n if (drainStats) {\n // Counted on the callback's success, before the ack: the work was delivered either way, and an ack\n // that fails only means at-least-once will deliver it again to an idempotent callback.\n drainStats.delivered += 1;\n }\n\n try {\n await queue.ack(stream, [delivered.receipt]);\n } catch (error) {\n // At-least-once's honest failure mode: the work succeeded but the ack did not, so the sub-batch will be\n // redelivered. The idempotent callback the lane requires is exactly what makes that harmless.\n console.warn(\n `pgxsinkit: could not ack message ${delivered.receipt} on Event stream \"${stream}\"; it will be ` +\n \"redelivered (the callback must be idempotent)\",\n error,\n );\n }\n // Settled either way: an acked message is gone, and one whose ack failed is meant to be redelivered.\n settle();\n };\n\n /**\n * Process one read's messages, at most `concurrency` callbacks at a time. Never throws.\n *\n * The renewal task spans the WHOLE read, not one callback: the messages queued behind the one in flight are\n * just as invisible, and they are precisely the ones a long first callback would otherwise let lapse.\n *\n * `halted` is the \"enter no further callback\" predicate — a graceful stop in loop mode, and additionally\n * the spent wall-clock budget under {@link EventConsumer.drainOnce}. It is consulted BETWEEN sub-batches\n * only, so whatever is already running is always awaited and settled first; the messages of this read no\n * callback ever entered are then released from renewal so their leases lapse and they redeliver at once,\n * rather than staying invisible behind work this pass will not do.\n */\n const processDelivered = async (\n stream: string,\n messages: readonly DeliveredEventMessage[],\n halted: () => boolean,\n ): Promise<void> => {\n const unsettled = new Set(messages.map((delivered) => delivered.receipt));\n const settleOf = (delivered: DeliveredEventMessage) => () => unsettled.delete(delivered.receipt);\n /** Receipts a callback has actually been entered for — the ones a graceful stop must keep renewing. */\n const startedReceipts = new Set<EventQueueReceipt>();\n /**\n * A graceful stop enters no further callback, so every message of this read the workers never reached is\n * released HERE: dropping it from the renewal set lets its lease lapse and the queue redeliver it at once,\n * instead of holding it invisible for as long as the in-flight callbacks still take. The started ones stay\n * in the set and keep being renewed until `processMessage` settles them.\n */\n const releaseUnstarted = (): void => {\n for (const delivered of messages) {\n if (!startedReceipts.has(delivered.receipt)) {\n unsettled.delete(delivered.receipt);\n }\n }\n };\n if (stopController.signal.aborted) {\n releaseUnstarted();\n } else {\n stopController.signal.addEventListener(\"abort\", releaseUnstarted, { once: true });\n }\n const stopRenewal = startRenewal(stream, unsettled);\n\n // The `halted` check and this call are one synchronous step, so a stop (or an expiring budget) can never\n // land between \"we decided to run it\" and \"it counts as started\".\n const runOne = async (delivered: DeliveredEventMessage): Promise<void> => {\n startedReceipts.add(delivered.receipt);\n await processMessage(stream, delivered, settleOf(delivered));\n };\n\n try {\n if (concurrency <= 1) {\n for (const delivered of messages) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n await runOne(delivered);\n }\n return;\n }\n\n let cursor = 0;\n const worker = async (): Promise<void> => {\n for (;;) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n const delivered = messages[cursor++];\n if (!delivered) {\n return;\n }\n await runOne(delivered);\n }\n };\n await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, worker));\n } finally {\n // Every callback of this read has settled by now (the workers await theirs), so the renewal task has\n // nothing left to protect — and `stop()`, which awaits this loop, therefore awaits the shutdown too.\n stopController.signal.removeEventListener(\"abort\", releaseUnstarted);\n await stopRenewal();\n }\n };\n\n // ─── One stream's loop ───────────────────────────────────────────────────────────────────────────────\n const runStream = async (stream: string): Promise<void> => {\n let idleCount = 0;\n\n while (!stopping) {\n let productive = false;\n try {\n const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n // Beat on the READ, before delivery, so a slow callback cannot delay the heartbeat. `processDelivered`\n // never throws, so this iteration can produce exactly one report: this one, or the fault one below.\n reportPoll(stream, messages.length, false);\n if (messages.length > 0) {\n productive = true;\n await processDelivered(stream, messages, () => stopping);\n }\n } catch (error) {\n // The read did not complete. An unparseable body fails the WHOLE read exactly as a queue fault does,\n // so both beat the same way: nothing delivered, `fault: true`, and the loop carries on.\n reportPoll(stream, 0, true);\n if (error instanceof MalformedEventQueueMessageError) {\n // The endpoint is the only writer of these queues and it writes contract-shaped bodies, so this is a\n // hand-inserted or corrupted message. It fails the WHOLE read, so it must go on sight or it wedges\n // the stream: dead-letter exactly the named receipt, then re-read for the rest of the batch.\n productive = await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n } else {\n // A queue/database fault. A runner NEVER exits on a transient one — it backs off exactly like an\n // idle stream and keeps trying.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\"; backing off and retrying`,\n error,\n );\n }\n }\n\n if (productive) {\n // A backlog drains back-to-back: read again immediately, at the floor again once it runs dry.\n idleCount = 0;\n continue;\n }\n\n idleCount += 1;\n if (stopping) {\n break;\n }\n await sleep(computeEventPollWaitMs(idleCount, pollOptions), stopController.signal);\n }\n };\n\n // ─── One bounded drain pass (the serverless pacing mode) ─────────────────────────────────────────────\n /**\n * Read → deliver → ack across every stream until they all read empty or the budget is spent. Deliberately\n * built out of `processDelivered` and `deadLetter` — the loop mode's own path — so retry, renewal and\n * dead-lettering cannot drift between the two modes.\n */\n const runDrain = async (budgetMs: number): Promise<EventDrainSummary> => {\n const stats = { delivered: 0, deadLettered: 0 };\n drainStats = stats;\n const deadline = now() + budgetMs;\n /** Streams not yet known to be empty. A stream leaves the set on an empty read, or on a read fault. */\n const pending = new Set(streams);\n /** Anything that ended the pass with work possibly still queued — the `empty: false` reasons. */\n let unfinished = false;\n // Budget AND stop: a `stop()` during a pass must wind it down just as it winds down a loop.\n const halted = (): boolean => stopping || now() >= deadline;\n\n try {\n while (pending.size > 0) {\n if (halted()) {\n unfinished = true;\n break;\n }\n for (const stream of [...pending]) {\n if (halted()) {\n unfinished = true;\n break;\n }\n\n let messages: readonly DeliveredEventMessage[];\n try {\n messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n // The heartbeat covers this pacing mode too — a scheduled drain is exactly the deployment whose\n // host most wants to know a pass actually reached the queue.\n reportPoll(stream, messages.length, false);\n } catch (error) {\n reportPoll(stream, 0, true);\n if (error instanceof MalformedEventQueueMessageError) {\n // Same policy as the loop: it fails the WHOLE read, so it goes on sight and the stream stays\n // pending for the re-read that fetches the rest of the batch.\n await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n continue;\n }\n // A queue/database fault. The loop mode backs off and retries; a bounded pass has nothing to\n // back off INTO (it must not busy-spin against a broken queue for the whole budget), so the\n // stream is left for the next invocation and the pass reports itself unfinished.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\" during a bounded drain; ` +\n \"leaving it for the next pass\",\n error,\n );\n pending.delete(stream);\n unfinished = true;\n continue;\n }\n\n if (messages.length === 0) {\n pending.delete(stream);\n continue;\n }\n await processDelivered(stream, messages, halted);\n }\n }\n } finally {\n drainStats = null;\n }\n\n return { delivered: stats.delivered, deadLettered: stats.deadLettered, empty: !unfinished };\n };\n\n return {\n start: () => {\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: this event consumer is running a bounded `drainOnce()` pass, so `start()` cannot also \" +\n \"run its polling loops — one handle drives one pacing mode at a time. Await the pass first.\",\n );\n }\n if (started || stopping) {\n // Idempotent, and a no-op after `stop()` — the handle's lifecycle is one-way, matching the client's\n // flush driver. A restart is a new `defineEventConsumer`.\n return;\n }\n started = true;\n loops = streams.map((stream) =>\n // The catch is attached HERE, at creation: a loop is only awaited by `stop()`, so an unexpected\n // rejection must never be able to surface as an unhandled promise in the app's process.\n runStream(stream).catch((error: unknown) => {\n console.error(`pgxsinkit: the event consumer loop for Event stream \"${stream}\" ended unexpectedly`, error);\n }),\n );\n },\n\n stop: () => {\n stopping = true;\n stopController.abort();\n stopPromise ??= (async () => {\n await Promise.all(loops);\n loops = [];\n // A bounded pass is stopped like a loop: `halted()` already saw `stopping`, so it enters no further\n // callback — this just makes `stop()` resolve only once the one it was on has settled.\n await activeDrain?.catch(() => undefined);\n })();\n return stopPromise;\n },\n\n // Deliberately `async`, so every refusal below is a REJECTION rather than a synchronous throw from a\n // promise-returning function — a caller that only wired `.catch()` must not lose one.\n drainOnce: async (drainOptions = {}) => {\n if (started) {\n throw new Error(\n \"pgxsinkit: `drainOnce()` cannot run while this consumer's polling loops are live — one handle \" +\n \"drives one pacing mode at a time. Use the long-lived runner OR bounded drains, not both on one \" +\n \"handle. (Two separate PROCESSES draining the same queues concurrently is safe: the visibility \" +\n \"timeout arbitrates them.)\",\n );\n }\n if (stopping) {\n throw new Error(\n \"pgxsinkit: this event consumer handle is stopped — its lifecycle is one-way. Build a fresh \" +\n \"`defineEventConsumer` for the next drain pass; construction is query-free, so that costs nothing.\",\n );\n }\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: a `drainOnce()` pass is already in flight on this handle. Two SEPARATE PROCESSES \" +\n \"draining concurrently is safe (the queue's visibility timeouts arbitrate); two passes on one \" +\n \"handle would share its internal state, so it is refused. Await the first pass.\",\n );\n }\n\n const budgetMs = drainOptions.budgetMs ?? DEFAULT_EVENT_DRAIN_BUDGET_MS;\n if (!Number.isFinite(budgetMs) || budgetMs < 0) {\n throw new Error(`pgxsinkit: drainOnce's \\`budgetMs\\` must be a finite number >= 0 (got ${budgetMs}).`);\n }\n const pass = runDrain(budgetMs).finally(() => {\n activeDrain = null;\n });\n activeDrain = pass;\n return pass;\n },\n };\n}\n",
24
+ "import {\n type EventQueueMessage,\n getSyncRegistryStreams,\n type StampedEvent,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueReceipt,\n MalformedEventQueueMessageError,\n} from \"./queue\";\n\n/**\n * The **Event lane**'s consumer runner (ADR-0053 decisions 6 and 7): the library defines it, the app hosts it.\n *\n * `defineEventConsumer` returns a `start()`/`stop()` handle the app runs in its OWN long-lived Bun process —\n * the toolkit's first long-lived server artifact, deliberately separate from `createSyncServer`'s\n * zero-startup-query serverless posture. There is no supervisor, no CLI entrypoint, no daemon and no signal\n * handling here: the app owns its process lifecycle and calls `stop()` from wherever it already handles\n * shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside\n * `start()`.\n *\n * Because the app owns the process, it also owns the health endpoint — so the runner reports the one thing\n * that endpoint cannot see from outside: {@link DefineEventConsumerOptions.onPoll} fires after EVERY read,\n * productive or empty, in both pacing modes. Beat a liveness probe from that, never from `callback`, which\n * by design says nothing at all while the queue is idle.\n *\n * One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in\n * one stream must never head-of-line-block another), so small deployments run one process and large ones split\n * `streams` across processes.\n *\n * **Pacing is adaptive interval polling, and it is INTERNAL** (ADR-0053 decision 7 — out of consumer-app design\n * space by ratified requirement; only the floor/ceiling/factor are exposed as tuning, never as contract):\n *\n * - a NON-EMPTY read is followed by an immediate re-read, so a backlog drains back-to-back;\n * - consecutive EMPTY reads grow the wait from a floor ({@link DEFAULT_EVENT_POLL_FLOOR_MS}) toward an idle\n * ceiling ({@link DEFAULT_EVENT_POLL_CEILING_MS}) by {@link DEFAULT_EVENT_POLL_FACTOR};\n * - one non-empty read resets the wait to the floor.\n *\n * LISTEN/NOTIFY and `pgmq.read_with_poll` long-polling are REJECTED as wake mechanisms (ADR-0053, maintainer\n * decision): Bun's native `SQL` — the sanctioned Postgres driver — has no LISTEN/NOTIFY, and both mechanisms\n * hold a connection per stream through the transaction poolers the consumers' stacks run behind. Because\n * pacing is internal, the mechanism can change later without any contract change.\n *\n * **Leases are RENEWED while a read is being worked through; a thrown sub-batch's lease is deliberately left\n * to lapse** (ADR-0053 decision 7: visibility renewal is internal). One read makes up to `batchSize` messages\n * invisible at once, so the timeout cannot be \"the processing budget\": ten ordinary ten-second callbacks\n * would outlive a 60-second window for the later messages, and in a documented multi-runner deployment\n * another process would pick them up while the first is still working toward them. So for as long as a read\n * is in flight the runner extends EVERY not-yet-settled receipt of that read — the one running plus the ones\n * still queued behind it — every `visibilityTimeoutSeconds / 2`. Renewal is best-effort: a failure is\n * warn-logged and the loop carries on, because redelivery is the safety net it would fall back on anyway.\n *\n * `visibilityTimeoutSeconds` therefore means two retry-shaped things, never a budget:\n *\n * - **the redelivery delay of a FAILED sub-batch.** A callback that throws is not acked AND is dropped from\n * renewal immediately, so its lease lapses and the queue redelivers it with an incremented `deliveryCount`.\n * That lapse IS the retry pacing — the runner never sleeps \"on behalf of\" a failed message, and if a\n * backend ever wants exponential redelivery backoff it belongs INSIDE that backend, behind the\n * {@link EventQueue} seam, so the runner stays backend-agnostic;\n * - **the crash-recovery bound.** A runner that dies takes its renewals with it, so everything it held comes\n * back one timeout later.\n *\n * **A graceful stop does not cancel renewal — it narrows it.** `stop()` starts no further read and no further\n * callback, but the callbacks already in flight are AWAITED and then acked, so their receipts must stay\n * invisible until they settle: cancelling renewal at `stop()` would hand a second runner the very message\n * this one is deliberately finishing, on every ordinary SIGTERM/rollout. What IS released at `stop()` is the\n * rest of that read — the messages no callback has started — which drop out of the renewal set so their\n * leases lapse and the queue redelivers them promptly. `stop()` therefore resolves only once every in-flight\n * callback has settled AND its renewal task has shut down.\n *\n * **The SECOND pacing mode: `drainOnce()`, for hosts that cannot hold a process** (ADR-0053 amendment,\n * 2026-08-02). Everything above describes the primary mode. A serverless-only deployment — managed\n * Supabase, whose edge functions are the only compute — has nowhere to put a `start()`; its queue would\n * simply never drain. So the SAME handle also answers `drainOnce({ budgetMs })`: one bounded pass that\n * reads/delivers/acks through the identical internals until every stream reads empty or the wall-clock\n * budget runs out. Nothing about the delivery contract moves — at-least-once, batch-internal order only,\n * dead-lettering to the backend's archive are all the same code — because pacing was internal from the\n * start (decision 7), which is exactly what makes this a HOSTING addition rather than a contract change.\n * The long-lived runner remains the primary mode; `drainOnce` is what a scheduled invocation calls.\n */\n\n/** Max messages (each ONE single-stream sub-batch) a single read delivers, when the app sets nothing. */\nexport const DEFAULT_EVENT_CONSUMER_BATCH_SIZE = 10;\n/**\n * How long a delivered sub-batch stays invisible, when the app sets nothing — and how long the runner extends\n * it by on each renewal (it renews at half this). Healthy long processing is covered by renewal, so this is\n * the REDELIVERY DELAY of a sub-batch whose callback threw and the crash-recovery bound, not a budget: it\n * wants to sit above a single callback's worst case (too short redelivers a callback that is merely slower\n * than one renewal interval), never above the whole batch's.\n */\nexport const DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS = 60;\n/** Deliveries a sub-batch gets before a further callback failure dead-letters it, when the app sets nothing. */\nexport const DEFAULT_EVENT_MAX_ATTEMPTS = 5;\n/** The adaptive poll's floor — the wait after the FIRST empty read (ADR-0053 decision 7: ~250 ms). */\nexport const DEFAULT_EVENT_POLL_FLOOR_MS = 250;\n/** The adaptive poll's idle ceiling — the longest an idle stream ever waits between reads. */\nexport const DEFAULT_EVENT_POLL_CEILING_MS = 5_000;\n/** How fast consecutive empty reads grow the wait from the floor toward the ceiling. */\nexport const DEFAULT_EVENT_POLL_FACTOR = 2;\n/**\n * The wall-clock budget one {@link EventConsumer.drainOnce} pass gets, when the caller sets nothing.\n *\n * **Set it under your platform's invocation wall-clock cap**, with head-room for one callback: the budget is\n * only ever checked BETWEEN sub-batches, so a pass can overrun it by however long the callback that was\n * already running takes. 25 s suits the common serverless caps (Supabase Edge, Vercel, Cloud Run jobs); a\n * platform with a tighter cap wants a tighter budget, and a generous one (a cron container) can raise it.\n */\nexport const DEFAULT_EVENT_DRAIN_BUDGET_MS = 25_000;\n\n/**\n * Adaptive-poll tuning. Defaults are the ADR's; they are TUNING, not contract — the pacing mechanism itself is\n * internal and may change.\n */\nexport interface EventConsumerPollOptions {\n /** The wait after the first empty read. Defaults to {@link DEFAULT_EVENT_POLL_FLOOR_MS}. */\n floorMs?: number;\n /** The longest wait an idle stream reaches. Defaults to {@link DEFAULT_EVENT_POLL_CEILING_MS}. */\n ceilingMs?: number;\n /** The growth factor per consecutive empty read. Defaults to {@link DEFAULT_EVENT_POLL_FACTOR}. */\n factor?: number;\n}\n\n/** One callback invocation: exactly ONE delivered queue message, i.e. one single-stream sub-batch. */\nexport interface EventConsumerBatch {\n /** The Event stream these events were appended under. */\n stream: string;\n /**\n * The stamped envelopes, EXACTLY as the ingestion endpoint enqueued them (ADR-0053 decision 5) — in append\n * order within this sub-batch. Across sub-batches there is no ordering promise (decision 6).\n */\n events: readonly StampedEvent[];\n}\n\n/**\n * The consumer callback. Returning (resolving) ACKS the sub-batch; THROWING retries it — the message stays\n * invisible until its visibility timeout lapses and the queue redelivers it.\n *\n * It MUST be idempotent (ADR-0053 decision 6, at-least-once): the blessed pattern is deduping on `eventId`\n * against the app's own durable store, which composes to effectively-exactly-once.\n */\nexport type EventConsumerCallback = (batch: EventConsumerBatch) => void | Promise<void>;\n\n/** What {@link DefineEventConsumerOptions.onDeadLetter} is told about a sub-batch the runner gave up on. */\nexport interface EventDeadLetterReport {\n stream: string;\n /** Why it was dead-lettered — the same reason recorded in the backend's dead-letter storage. */\n reason: string;\n /** Deliveries this message had received. `0` when the body was unreadable (nothing was ever delivered from it). */\n attempts: number;\n /** The receipt it was dead-lettered under — always present, including for an unparseable body. */\n receipt: EventQueueReceipt;\n /** The message, when it was readable. Absent for a malformed body (that is exactly what could not be parsed). */\n message?: EventQueueMessage;\n /** The error behind it: the callback's throw, or the {@link MalformedEventQueueMessageError}. */\n cause?: unknown;\n}\n\n/**\n * What {@link DefineEventConsumerOptions.onPoll} is told after each read — the host's liveness heartbeat.\n *\n * One report per read the runner performs, productive or not, in BOTH pacing modes. `delivered` counts the\n * sub-batches that read returned (the queue's unit: one message, one callback invocation), and `empty` is\n * exactly `delivered === 0` — including on a faulted read, which is why `fault` is a separate flag rather\n * than something to infer from the counts.\n */\nexport interface EventPollReport {\n /** The Event stream that was read. Each stream has its own loop, so each beats on its own cadence. */\n readonly stream: string;\n /** Sub-batches this read returned. `0` on an empty or faulted read. */\n readonly delivered: number;\n /** `delivered === 0` — nothing came back from this read. */\n readonly empty: boolean;\n /**\n * The read itself FAILED: a queue/database fault, or a message body that could not be parsed (which fails\n * the whole read). The runner backs off and carries on either way — a fault never ends a loop — so a host\n * watching the heartbeat still sees it turning, and this is what tells it the queue is unhealthy.\n */\n readonly fault: boolean;\n /** When the read settled, from the runner's own clock (`Date.now` unless one is injected). */\n readonly at: number;\n}\n\n/**\n * The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never\n * lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.\n */\nexport type EventConsumerSleep = (ms: number, signal: AbortSignal) => Promise<void>;\n\n/** What {@link EventConsumer.drainOnce} is tuned with. */\nexport interface EventDrainOptions {\n /**\n * The pass's wall-clock budget. Defaults to {@link DEFAULT_EVENT_DRAIN_BUDGET_MS}. Checked between\n * sub-batches only, never inside a callback — so size it under the invocation's cap with head-room for\n * one callback's worst case.\n */\n budgetMs?: number;\n}\n\n/** What one {@link EventConsumer.drainOnce} pass reports back. Counts are SUB-BATCHES (one queue message,\n * one callback invocation), the unit the queue and the dead-letter archive both work in. */\nexport interface EventDrainSummary {\n /**\n * Sub-batches whose callback completed during this pass. An ack that then failed still counts — the work\n * was delivered, and at-least-once means it may be delivered again later (the callback is idempotent).\n */\n delivered: number;\n /** Sub-batches this pass moved to the backend's dead-letter storage. */\n deadLettered: number;\n /**\n * `true` when every configured Event stream read empty before the budget ran out — the queue is drained\n * as far as this pass can see.\n *\n * `false` means the pass ended with work possibly still queued: the budget cut it short, or a stream's\n * read faulted. It is the caller's signal that another tick has something to do — a scheduler that\n * chains passes should invoke again promptly rather than waiting out its full period.\n */\n empty: boolean;\n}\n\nexport interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry> {\n /** The sync registry whose `streams` this runner consumes. */\n registry: TRegistry;\n /**\n * The queue to consume from — REQUIRED, and the reason the runner is backend-agnostic by construction. The\n * ordinary wiring is `createPgmqEventQueue({ db })` with the app's own drizzle handle; constructing it here\n * from a `db` option would bake the shipped backend into the runner for one line of ergonomics.\n */\n queue: EventQueue;\n callback: EventConsumerCallback;\n /**\n * Narrow to a subset of the registered Event streams — the knob that splits streams across processes.\n * Defaults to ALL registered streams. An unknown name is a definition-time throw (fail-closed): a runner\n * that silently consumed nothing is the failure mode this forbids.\n */\n streams?: readonly string[];\n /** Max messages per read. Defaults to {@link DEFAULT_EVENT_CONSUMER_BATCH_SIZE}. */\n batchSize?: number;\n /**\n * The delivered-message invisibility window, renewed at half of it while the runner is still working\n * through a read. Defaults to {@link DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS}. Size it above ONE\n * callback's worst case (renewal covers the rest of the batch), not above the whole batch's.\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Max CONCURRENT callback invocations per Event stream. Defaults to `1` (strictly sequential). Values above 1\n * are safe for the idempotent callback the lane already requires: ADR-0053 decision 6 disclaims any ordering\n * across sub-batches precisely so concurrency is available. Reads stay serial — only the callbacks of one\n * delivered read run in parallel.\n */\n concurrency?: number;\n /**\n * Deliveries a sub-batch gets before a further callback failure dead-letters it. Defaults to\n * {@link DEFAULT_EVENT_MAX_ATTEMPTS}. A malformed body never gets attempts — it dead-letters on sight.\n */\n maxAttempts?: number;\n /** Adaptive-poll tuning. See {@link EventConsumerPollOptions}. */\n poll?: EventConsumerPollOptions;\n /**\n * Notified for every dead-lettered sub-batch. The runner ALSO warn-logs each one unconditionally: loudness is\n * the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.\n */\n onDeadLetter?: (report: EventDeadLetterReport) => void;\n /**\n * Notified after EVERY read the runner performs — productive or empty, in both pacing modes — which makes it\n * the host's **liveness heartbeat**. The {@link DefineEventConsumerOptions.callback} fires only on delivered\n * batches, so on an idle queue it goes quiet and a liveness/readiness probe answering from it would report a\n * healthy runner as dead; beat from this instead and treat `fault` as the queue-health signal.\n *\n * It fires on the READ, before the batch is delivered, so a slow callback cannot delay the heartbeat. A hook\n * that THROWS can never take a loop down: the throw is caught, warn-logged ONCE per runner (a hook that\n * throws every poll must not drown the log), and the loop carries on.\n */\n onPoll?: (report: EventPollReport) => void;\n /** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */\n sleep?: EventConsumerSleep;\n /** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */\n now?: () => number;\n /**\n * @internal The injectable RENEWAL wait, deliberately a second seam rather than `sleep`: the two cadences\n * are independent (one paces reads, one paces lease renewal) and sharing one would make every pacing\n * assertion depend on renewal timing. Defaults to `setTimeout`.\n */\n renewalSleep?: EventConsumerSleep;\n}\n\nexport interface EventConsumer {\n /**\n * Begin every stream's loop. Idempotent; a no-op after {@link EventConsumer.stop}. Throws while a\n * {@link EventConsumer.drainOnce} pass is in flight — one handle drives one pacing mode at a time.\n */\n start: () => void;\n /**\n * Graceful stop: no new reads, no new callbacks, in-flight callbacks are awaited (and their leases KEPT\n * renewed until they ack or dead-letter), and the promise resolves when every loop — and every renewal\n * task it still owned — is quiet. Safe to call twice (the second call awaits the first). Messages of an\n * in-progress read whose callback had not started are released at once: they stop being renewed and are\n * left unacked, so at-least-once redelivers them as soon as their lease lapses.\n *\n * A `drainOnce` pass in flight is treated the same way: it starts no further read, finishes the callback\n * it is on, and `stop()` resolves once it has.\n */\n stop: () => Promise<void>;\n /**\n * One bounded drain pass — the pacing mode for a host that cannot hold a process (ADR-0053 amendment,\n * 2026-08-02).\n *\n * It walks every configured Event stream, read → deliver → ack, and keeps going until EITHER every stream\n * has returned an empty read OR the wall-clock budget is spent. Same internals as the loop mode\n * throughout: the same read/deliver/ack path, the same lease renewal while a callback runs, the same\n * per-sub-batch retry-by-lapsing-lease, the same dead-lettering after `maxAttempts` with the same\n * `onDeadLetter` hook and unconditional warn log. It never sleeps: a stream that reads empty is finished\n * for this pass, and there is no adaptive interval to wait out.\n *\n * **The budget is checked BETWEEN sub-batches, never inside one.** A callback already running is awaited\n * and acked exactly as the runner would (its lease stays renewed throughout), and no new read starts once\n * the budget is gone — so a pass can overrun its budget by one callback, and `budgetMs` must leave\n * head-room for that under the platform's invocation cap. A sub-batch whose callback THROWS near the\n * budget edge is not special-cased: it is left unacked and dropped from renewal, its lease lapses, and the\n * queue redelivers it on a later pass with an incremented delivery count. That is at-least-once working as\n * designed, not a lost event — and it is why the callback must be idempotent.\n *\n * **Hosting it.** Wire a SCHEDULED invocation (a platform cron, e.g. every 10 s) that calls `drainOnce`\n * and, optionally, an ingest-side nudge (`createSyncServer({ onEventsEnqueued })` firing a\n * fetch-and-forget at the same endpoint) so an interactive append is drained in milliseconds instead of\n * waiting for the next tick. The **schedule is the delivery guarantee; the nudge is only latency** — a\n * lost nudge costs nothing but time. Overlapping invocations are SAFE: two processes reading the same\n * queue are arbitrated by the visibility timeout, exactly as two long-lived runners would be. (Two passes\n * on ONE handle are not — that is a bug, and throws; see below.)\n *\n * **One handle, one pacing mode.** Throws if `start()` is live, if another `drainOnce` is already in\n * flight on this handle, or if the handle has been stopped — the lifecycle is one-way, so the next drain\n * builds a fresh `defineEventConsumer` (construction is query-free, so that costs nothing).\n */\n drainOnce: (options?: EventDrainOptions) => Promise<EventDrainSummary>;\n}\n\n/**\n * The adaptive wait for `idleCount` CONSECUTIVE unproductive reads (an empty read or a queue fault), clamped to\n * the ceiling. `idleCount` is 1 for the first one; a productive read resets it to 0 and re-reads immediately.\n */\nexport function computeEventPollWaitMs(idleCount: number, options: EventConsumerPollOptions = {}): number {\n const floorMs = options.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS;\n const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS;\n const factor = options.factor ?? DEFAULT_EVENT_POLL_FACTOR;\n const exponent = Math.max(idleCount - 1, 0);\n return Math.min(Math.round(floorMs * factor ** exponent), ceilingMs);\n}\n\n/** The production wait: a `setTimeout` that is CLEARED on abort, so `stop()` never leaves a timer holding the process open. */\nconst abortableSleep: EventConsumerSleep = (ms, signal) =>\n new Promise<void>((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n let handle: ReturnType<typeof setTimeout> | undefined;\n const finish = (): void => {\n if (handle !== undefined) {\n clearTimeout(handle);\n }\n signal.removeEventListener(\"abort\", finish);\n resolve();\n };\n handle = setTimeout(finish, ms);\n signal.addEventListener(\"abort\", finish, { once: true });\n });\n\nfunction assertPositive(label: string, value: number, minimum: number): number {\n if (!Number.isFinite(value) || value < minimum) {\n throw new Error(\n `pgxsinkit: defineEventConsumer's \\`${label}\\` must be a finite number >= ${minimum} (got ${value}).`,\n );\n }\n return value;\n}\n\nexport function defineEventConsumer<TRegistry extends SyncTableRegistry>(\n options: DefineEventConsumerOptions<TRegistry>,\n): EventConsumer {\n // ─── Definition-time resolution (fail-closed, and query-free) ────────────────────────────────────────\n const registered = getSyncRegistryStreams(options.registry) ?? {};\n const registeredNames = Object.keys(registered);\n if (registeredNames.length === 0) {\n throw new Error(\n \"pgxsinkit: this registry registers no Event streams, so there is nothing for a consumer runner to \" +\n \"consume. Register one with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.\",\n );\n }\n\n let streams: string[];\n if (options.streams) {\n const unknown = options.streams.filter((stream) => !Object.hasOwn(registered, stream));\n if (unknown.length > 0) {\n // Every offender is named: a typo'd stream on a runner would otherwise present as \"the events never\n // arrive\", which is the most expensive shape of silence in the lane.\n throw new Error(\n `pgxsinkit: defineEventConsumer was asked for Event stream(s) [${unknown.join(\", \")}] this registry ` +\n `does not register — it registers [${registeredNames.join(\", \")}].`,\n );\n }\n streams = [...new Set(options.streams)];\n if (streams.length === 0) {\n throw new Error(\n \"pgxsinkit: defineEventConsumer was given an empty `streams` list. Omit it to consume every registered \" +\n \"Event stream, or name at least one.\",\n );\n }\n } else {\n streams = registeredNames;\n }\n\n const batchSize = assertPositive(\"batchSize\", options.batchSize ?? DEFAULT_EVENT_CONSUMER_BATCH_SIZE, 1);\n const visibilityTimeoutSeconds = assertPositive(\n \"visibilityTimeoutSeconds\",\n options.visibilityTimeoutSeconds ?? DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n 1,\n );\n const concurrency = assertPositive(\"concurrency\", options.concurrency ?? 1, 1);\n const maxAttempts = assertPositive(\"maxAttempts\", options.maxAttempts ?? DEFAULT_EVENT_MAX_ATTEMPTS, 1);\n const poll = options.poll ?? {};\n const floorMs = assertPositive(\"poll.floorMs\", poll.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS, 0);\n const ceilingMs = assertPositive(\"poll.ceilingMs\", poll.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS, floorMs);\n const factor = assertPositive(\"poll.factor\", poll.factor ?? DEFAULT_EVENT_POLL_FACTOR, 1);\n const pollOptions: EventConsumerPollOptions = { floorMs, ceilingMs, factor };\n\n const queue = options.queue;\n const sleep = options.sleep ?? abortableSleep;\n const renewalSleep = options.renewalSleep ?? abortableSleep;\n const now = options.now ?? Date.now;\n /** Renew at HALF the window: one missed renewal still leaves a full half-window of head-room. */\n const renewalIntervalMs = Math.max(1, Math.floor((visibilityTimeoutSeconds * 1000) / 2));\n\n // ─── Lifecycle state ─────────────────────────────────────────────────────────────────────────────────\n const stopController = new AbortController();\n let started = false;\n let stopping = false;\n let loops: Promise<void>[] = [];\n let stopPromise: Promise<void> | null = null;\n /** The in-flight bounded drain, if any — the second pacing mode's whole lifecycle state. */\n let activeDrain: Promise<EventDrainSummary> | null = null;\n /**\n * The counters of the drain pass in flight, or `null` in loop mode. The settle points below feed it\n * rather than returning counts, so `drainOnce` reports on the SAME delivery path the runner uses instead\n * of a parallel one. Exactly one pass can be in flight (the mode is mutually exclusive), so one slot is\n * all this needs.\n */\n let drainStats: { delivered: number; deadLettered: number } | null = null;\n\n // ─── The per-read heartbeat ──────────────────────────────────────────────────────────────────────────\n /** Latched once the `onPoll` hook has thrown: the warn is per RUNNER, not per poll (see the option's doc). */\n let pollHookFailed = false;\n /**\n * Beat once for one completed read. Called from BOTH pacing modes and from the fault paths, so a host\n * watching this sees every turn of every loop; `empty` is derived here so the two modes cannot disagree\n * about what an empty read is.\n */\n const reportPoll = (stream: string, delivered: number, fault: boolean): void => {\n if (!options.onPoll) {\n return;\n }\n try {\n options.onPoll({ stream, delivered, empty: delivered === 0, fault, at: now() });\n } catch (error) {\n // A liveness hook that throws must never be able to stop the loop it is observing — that would turn a\n // reporting bug into an outage. Loud once, then silent: it typically throws on EVERY poll.\n if (!pollHookFailed) {\n pollHookFailed = true;\n console.warn(\n \"pgxsinkit: the `onPoll` hook threw; the event consumer carries on regardless (this is warned once \" +\n \"per runner, not once per poll)\",\n error,\n );\n }\n }\n };\n\n // ─── Dead-lettering (ADR-0053 decision 7: the loudness lives HERE) ───────────────────────────────────\n const reportDeadLetter = (report: EventDeadLetterReport): void => {\n // Unconditional, and deliberately not the client report surface's \"warn only when nobody subscribed\"\n // rule: a dead letter is rare and terminal, so it is worth a line in the operator's log even when the\n // app also handles it.\n console.warn(\n `pgxsinkit: dead-lettered an event sub-batch on Event stream \"${report.stream}\" (receipt ${report.receipt}, ` +\n `${report.attempts} delivery attempt(s)) — ${report.reason}. It is in the queue's dead-letter storage; ` +\n \"requeue it deliberately with `requeueDeadLetter` once the cause is fixed.\",\n report.cause,\n );\n if (!options.onDeadLetter) {\n return;\n }\n try {\n options.onDeadLetter(report);\n } catch (error) {\n console.error(\"pgxsinkit: the `onDeadLetter` hook threw; the message is dead-lettered regardless\", error);\n }\n };\n\n /** Move one message to dead-letter storage and report it. Resolves `false` when the QUEUE refused the move. */\n const deadLetter = async (\n stream: string,\n receipt: EventQueueReceipt,\n attempts: number,\n reason: string,\n cause: unknown,\n message?: EventQueueMessage,\n ): Promise<boolean> => {\n try {\n await queue.deadLetter(stream, [receipt], reason);\n } catch (error) {\n // The message is still queued and still invisible; it redelivers and dead-letters on a later pass.\n console.warn(\n `pgxsinkit: could not dead-letter message ${receipt} on Event stream \"${stream}\"; it stays queued and ` +\n \"will be retried\",\n error,\n );\n return false;\n }\n if (drainStats) {\n drainStats.deadLettered += 1;\n }\n reportDeadLetter({ stream, reason, attempts, receipt, ...(message ? { message } : {}), cause });\n return true;\n };\n\n // ─── Lease renewal (ADR-0053 decision 7: internal, and not optional) ─────────────────────────────────\n /**\n * Keep every UNSETTLED receipt of one read invisible for as long as that read is being worked through.\n * Returns the stopper, which the caller awaits so no renewal outlives its read (a stray timer would hold\n * the app's process open, and a stray extension would delay a redelivery the runner no longer wants).\n *\n * Its lifetime is the READ's, deliberately NOT the runner's: this task is wired to its OWN controller and\n * never to `stopController`. A graceful stop still awaits the callbacks already in flight, so aborting\n * renewal there would let their leases lapse mid-callback and let another runner take the work this one is\n * finishing. `stop()` instead shrinks `unsettled` (see `processDelivered`), and the loop below exits on its\n * own the moment that set drains.\n */\n const startRenewal = (stream: string, unsettled: Set<EventQueueReceipt>): (() => Promise<void>) => {\n const controller = new AbortController();\n\n const task = (async () => {\n while (!controller.signal.aborted && unsettled.size > 0) {\n await renewalSleep(renewalIntervalMs, controller.signal);\n if (controller.signal.aborted || unsettled.size === 0) {\n return;\n }\n try {\n await queue.extendVisibility(stream, [...unsettled], visibilityTimeoutSeconds);\n } catch (error) {\n // Best-effort by design: the worst case of a failed renewal is the behaviour there would be with\n // no renewal at all — the lease lapses and the sub-batch is redelivered to an idempotent callback.\n console.warn(\n `pgxsinkit: could not renew the visibility lease on Event stream \"${stream}\" (receipts ` +\n `${[...unsettled].join(\", \")}); the sub-batch may be redelivered while it is still being processed`,\n error,\n );\n }\n }\n })();\n\n return async () => {\n controller.abort();\n await task;\n };\n };\n\n // ─── One delivered message ───────────────────────────────────────────────────────────────────────────\n const processMessage = async (\n stream: string,\n delivered: DeliveredEventMessage,\n /** Drop this message from the read's renewal set — it is settled, one way or the other. */\n settle: () => void,\n ): Promise<void> => {\n try {\n await options.callback({ stream, events: delivered.message.events });\n } catch (error) {\n // Settled the moment it throws, and settled FIRST: a failed sub-batch's lease is deliberately allowed\n // to lapse, because that lapse IS the retry pacing. Renewing it would postpone its own redelivery.\n settle();\n const detail = error instanceof Error ? error.message : String(error);\n if (delivered.deliveryCount >= maxAttempts) {\n await deadLetter(\n stream,\n delivered.receipt,\n delivered.deliveryCount,\n `the consumer callback failed on delivery ${delivered.deliveryCount} of ${maxAttempts}: ${detail}`,\n error,\n delivered.message,\n );\n return;\n }\n // NOT acked, and no longer renewed: the lapsing lease IS the retry pacing (see the module note).\n console.warn(\n `pgxsinkit: the event consumer callback failed for Event stream \"${stream}\" (receipt ${delivered.receipt}, ` +\n `delivery ${delivered.deliveryCount} of ${maxAttempts}); the sub-batch will be redelivered after its ` +\n `${visibilityTimeoutSeconds}s visibility timeout`,\n error,\n );\n return;\n }\n\n if (drainStats) {\n // Counted on the callback's success, before the ack: the work was delivered either way, and an ack\n // that fails only means at-least-once will deliver it again to an idempotent callback.\n drainStats.delivered += 1;\n }\n\n try {\n await queue.ack(stream, [delivered.receipt]);\n } catch (error) {\n // At-least-once's honest failure mode: the work succeeded but the ack did not, so the sub-batch will be\n // redelivered. The idempotent callback the lane requires is exactly what makes that harmless.\n console.warn(\n `pgxsinkit: could not ack message ${delivered.receipt} on Event stream \"${stream}\"; it will be ` +\n \"redelivered (the callback must be idempotent)\",\n error,\n );\n }\n // Settled either way: an acked message is gone, and one whose ack failed is meant to be redelivered.\n settle();\n };\n\n /**\n * Process one read's messages, at most `concurrency` callbacks at a time. Never throws.\n *\n * The renewal task spans the WHOLE read, not one callback: the messages queued behind the one in flight are\n * just as invisible, and they are precisely the ones a long first callback would otherwise let lapse.\n *\n * `halted` is the \"enter no further callback\" predicate — a graceful stop in loop mode, and additionally\n * the spent wall-clock budget under {@link EventConsumer.drainOnce}. It is consulted BETWEEN sub-batches\n * only, so whatever is already running is always awaited and settled first; the messages of this read no\n * callback ever entered are then released from renewal so their leases lapse and they redeliver at once,\n * rather than staying invisible behind work this pass will not do.\n */\n const processDelivered = async (\n stream: string,\n messages: readonly DeliveredEventMessage[],\n halted: () => boolean,\n ): Promise<void> => {\n const unsettled = new Set(messages.map((delivered) => delivered.receipt));\n const settleOf = (delivered: DeliveredEventMessage) => () => unsettled.delete(delivered.receipt);\n /** Receipts a callback has actually been entered for — the ones a graceful stop must keep renewing. */\n const startedReceipts = new Set<EventQueueReceipt>();\n /**\n * A graceful stop enters no further callback, so every message of this read the workers never reached is\n * released HERE: dropping it from the renewal set lets its lease lapse and the queue redeliver it at once,\n * instead of holding it invisible for as long as the in-flight callbacks still take. The started ones stay\n * in the set and keep being renewed until `processMessage` settles them.\n */\n const releaseUnstarted = (): void => {\n for (const delivered of messages) {\n if (!startedReceipts.has(delivered.receipt)) {\n unsettled.delete(delivered.receipt);\n }\n }\n };\n if (stopController.signal.aborted) {\n releaseUnstarted();\n } else {\n stopController.signal.addEventListener(\"abort\", releaseUnstarted, { once: true });\n }\n const stopRenewal = startRenewal(stream, unsettled);\n\n // The `halted` check and this call are one synchronous step, so a stop (or an expiring budget) can never\n // land between \"we decided to run it\" and \"it counts as started\".\n const runOne = async (delivered: DeliveredEventMessage): Promise<void> => {\n startedReceipts.add(delivered.receipt);\n await processMessage(stream, delivered, settleOf(delivered));\n };\n\n try {\n if (concurrency <= 1) {\n for (const delivered of messages) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n await runOne(delivered);\n }\n return;\n }\n\n let cursor = 0;\n const worker = async (): Promise<void> => {\n for (;;) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n const delivered = messages[cursor++];\n if (!delivered) {\n return;\n }\n await runOne(delivered);\n }\n };\n await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, worker));\n } finally {\n // Every callback of this read has settled by now (the workers await theirs), so the renewal task has\n // nothing left to protect — and `stop()`, which awaits this loop, therefore awaits the shutdown too.\n stopController.signal.removeEventListener(\"abort\", releaseUnstarted);\n await stopRenewal();\n }\n };\n\n // ─── One stream's loop ───────────────────────────────────────────────────────────────────────────────\n const runStream = async (stream: string): Promise<void> => {\n let idleCount = 0;\n\n while (!stopping) {\n let productive = false;\n try {\n const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n // Beat on the READ, before delivery, so a slow callback cannot delay the heartbeat. `processDelivered`\n // never throws, so this iteration can produce exactly one report: this one, or the fault one below.\n reportPoll(stream, messages.length, false);\n if (messages.length > 0) {\n productive = true;\n await processDelivered(stream, messages, () => stopping);\n }\n } catch (error) {\n // The read did not complete. An unparseable body fails the WHOLE read exactly as a queue fault does,\n // so both beat the same way: nothing delivered, `fault: true`, and the loop carries on.\n reportPoll(stream, 0, true);\n if (error instanceof MalformedEventQueueMessageError) {\n // The endpoint is the only writer of these queues and it writes contract-shaped bodies, so this is a\n // hand-inserted or corrupted message. It fails the WHOLE read, so it must go on sight or it wedges\n // the stream: dead-letter exactly the named receipt, then re-read for the rest of the batch.\n productive = await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n } else {\n // A queue/database fault. A runner NEVER exits on a transient one — it backs off exactly like an\n // idle stream and keeps trying.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\"; backing off and retrying`,\n error,\n );\n }\n }\n\n if (productive) {\n // A backlog drains back-to-back: read again immediately, at the floor again once it runs dry.\n idleCount = 0;\n continue;\n }\n\n idleCount += 1;\n if (stopping) {\n break;\n }\n await sleep(computeEventPollWaitMs(idleCount, pollOptions), stopController.signal);\n }\n };\n\n // ─── One bounded drain pass (the serverless pacing mode) ─────────────────────────────────────────────\n /**\n * Read → deliver → ack across every stream until they all read empty or the budget is spent. Deliberately\n * built out of `processDelivered` and `deadLetter` — the loop mode's own path — so retry, renewal and\n * dead-lettering cannot drift between the two modes.\n */\n const runDrain = async (budgetMs: number): Promise<EventDrainSummary> => {\n const stats = { delivered: 0, deadLettered: 0 };\n drainStats = stats;\n const deadline = now() + budgetMs;\n /** Streams not yet known to be empty. A stream leaves the set on an empty read, or on a read fault. */\n const pending = new Set(streams);\n /** Anything that ended the pass with work possibly still queued — the `empty: false` reasons. */\n let unfinished = false;\n // Budget AND stop: a `stop()` during a pass must wind it down just as it winds down a loop.\n const halted = (): boolean => stopping || now() >= deadline;\n\n try {\n while (pending.size > 0) {\n if (halted()) {\n unfinished = true;\n break;\n }\n for (const stream of [...pending]) {\n if (halted()) {\n unfinished = true;\n break;\n }\n\n let messages: readonly DeliveredEventMessage[];\n try {\n messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n // The heartbeat covers this pacing mode too — a scheduled drain is exactly the deployment whose\n // host most wants to know a pass actually reached the queue.\n reportPoll(stream, messages.length, false);\n } catch (error) {\n reportPoll(stream, 0, true);\n if (error instanceof MalformedEventQueueMessageError) {\n // Same policy as the loop: it fails the WHOLE read, so it goes on sight and the stream stays\n // pending for the re-read that fetches the rest of the batch.\n await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n continue;\n }\n // A queue/database fault. The loop mode backs off and retries; a bounded pass has nothing to\n // back off INTO (it must not busy-spin against a broken queue for the whole budget), so the\n // stream is left for the next invocation and the pass reports itself unfinished.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\" during a bounded drain; ` +\n \"leaving it for the next pass\",\n error,\n );\n pending.delete(stream);\n unfinished = true;\n continue;\n }\n\n if (messages.length === 0) {\n pending.delete(stream);\n continue;\n }\n await processDelivered(stream, messages, halted);\n }\n }\n } finally {\n drainStats = null;\n }\n\n return { delivered: stats.delivered, deadLettered: stats.deadLettered, empty: !unfinished };\n };\n\n return {\n start: () => {\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: this event consumer is running a bounded `drainOnce()` pass, so `start()` cannot also \" +\n \"run its polling loops — one handle drives one pacing mode at a time. Await the pass first.\",\n );\n }\n if (started || stopping) {\n // Idempotent, and a no-op after `stop()` — the handle's lifecycle is one-way, matching the client's\n // flush driver. A restart is a new `defineEventConsumer`.\n return;\n }\n started = true;\n loops = streams.map((stream) =>\n // The catch is attached HERE, at creation: a loop is only awaited by `stop()`, so an unexpected\n // rejection must never be able to surface as an unhandled promise in the app's process.\n runStream(stream).catch((error: unknown) => {\n console.error(`pgxsinkit: the event consumer loop for Event stream \"${stream}\" ended unexpectedly`, error);\n }),\n );\n },\n\n stop: () => {\n stopping = true;\n stopController.abort();\n stopPromise ??= (async () => {\n await Promise.all(loops);\n loops = [];\n // A bounded pass is stopped like a loop: `halted()` already saw `stopping`, so it enters no further\n // callback — this just makes `stop()` resolve only once the one it was on has settled.\n await activeDrain?.catch(() => undefined);\n })();\n return stopPromise;\n },\n\n // Deliberately `async`, so every refusal below is a REJECTION rather than a synchronous throw from a\n // promise-returning function — a caller that only wired `.catch()` must not lose one.\n drainOnce: async (drainOptions = {}) => {\n if (started) {\n throw new Error(\n \"pgxsinkit: `drainOnce()` cannot run while this consumer's polling loops are live — one handle \" +\n \"drives one pacing mode at a time. Use the long-lived runner OR bounded drains, not both on one \" +\n \"handle. (Two separate PROCESSES draining the same queues concurrently is safe: the visibility \" +\n \"timeout arbitrates them.)\",\n );\n }\n if (stopping) {\n throw new Error(\n \"pgxsinkit: this event consumer handle is stopped — its lifecycle is one-way. Build a fresh \" +\n \"`defineEventConsumer` for the next drain pass; construction is query-free, so that costs nothing.\",\n );\n }\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: a `drainOnce()` pass is already in flight on this handle. Two SEPARATE PROCESSES \" +\n \"draining concurrently is safe (the queue's visibility timeouts arbitrate); two passes on one \" +\n \"handle would share its internal state, so it is refused. Await the first pass.\",\n );\n }\n\n const budgetMs = drainOptions.budgetMs ?? DEFAULT_EVENT_DRAIN_BUDGET_MS;\n if (!Number.isFinite(budgetMs) || budgetMs < 0) {\n throw new Error(`pgxsinkit: drainOnce's \\`budgetMs\\` must be a finite number >= 0 (got ${budgetMs}).`);\n }\n const pass = runDrain(budgetMs).finally(() => {\n activeDrain = null;\n });\n activeDrain = pass;\n return pass;\n },\n };\n}\n",
25
25
  "import { getSyncRegistryStreams, hashString, quoteSqlLiteral, type SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { eventStreamQueueName } from \"./queue\";\n\n/**\n * The Event lane's **deploy-time** DDL (ADR-0053 decision 5): the pgmq extension plus one queue per registered\n * Event stream, derived from the registry.\n *\n * Provisioning is deploy-time and never runtime create-if-missing — the ingestion endpoint may enqueue long\n * before any consumer runner first starts, and a create-if-missing probe would put a query back in front of\n * the server's zero-startup-query posture.\n *\n * **pgmq assumptions** (read off pgmq's own extension SQL, and pinned by the integration lane):\n * - `CREATE EXTENSION IF NOT EXISTS pgmq` needs **no `CASCADE`**: pgmq's control file declares no `requires`.\n * (pg_partman is needed only for PARTITIONED queues, which this DDL never creates.) `CASCADE` would be\n * harmless but would also silently install whatever a future control file starts requiring.\n * - **No schema qualification is configurable**: the control file is `relocatable = false` with\n * `schema = 'pgmq'`, so the extension always lives in `pgmq` and every call is `pgmq.`-qualified.\n * - `pgmq.create()` is **idempotent**: it delegates to `create_non_partitioned`, whose tables and indexes are\n * `IF NOT EXISTS` and whose `pgmq.meta` insert is `ON CONFLICT DO NOTHING`. So the emitted statements need\n * no guard block and re-applying the migration is a no-op.\n *\n * The artifact is a MIGRATION body (raw SQL text) — `CREATE EXTENSION` and a SQL function call are outside\n * anything Drizzle's builders can express, which is the sanctioned raw-SQL case. Every interpolated queue\n * name is a registry-validated `[a-z][a-z0-9_]*` name, emitted through `quoteSqlLiteral`.\n */\n\n/** Stamped into the emitted DDL so `--check` can detect drift between the registry and a committed migration. */\nexport const EVENT_LANE_FINGERPRINT_PREFIX = \"pgxsinkit:events:fp1:\";\n\n/** The registered Event-stream names, SORTED — so the artifact and its fingerprint are registry-order-independent. */\nexport function eventLaneStreamNames(registry: SyncTableRegistry): string[] {\n return Object.keys(getSyncRegistryStreams(registry) ?? {}).sort();\n}\n\nfunction buildEventLaneDdlBody(streamNames: readonly string[]): string {\n const header =\n \"-- The pgxsinkit event lane's queues (ADR-0053 decision 5): one pgmq queue per registered Event stream.\\n\" +\n \"-- Provisioning is DEPLOY-TIME: the ingestion endpoint may enqueue long before any consumer runner starts.\\n\" +\n \"-- No CASCADE: pgmq's control file declares no `requires`. pgmq is non-relocatable (schema = 'pgmq').\\n\" +\n \"-- pgmq.create() is idempotent (IF NOT EXISTS tables/indexes + ON CONFLICT DO NOTHING meta), so\\n\" +\n \"-- re-applying this migration is a no-op and adding a stream only appends a line.\";\n\n const statements = streamNames.map(\n (stream) => `SELECT pgmq.create(${quoteSqlLiteral(eventStreamQueueName(stream))});`,\n );\n\n return `${header}\\nCREATE EXTENSION IF NOT EXISTS pgmq;\\n${statements.join(\"\\n\")}`;\n}\n\nfunction assertHasStreams(registry: SyncTableRegistry): string[] {\n const streamNames = eventLaneStreamNames(registry);\n if (streamNames.length === 0) {\n throw new Error(\n \"pgxsinkit: this registry registers no Event streams, so there is no event-lane DDL to emit. Register one \" +\n \"with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.\",\n );\n }\n return streamNames;\n}\n\n/**\n * The fingerprint the event-lane artifact carries for this registry. Derived from the emitted DDL body, so it\n * moves when a stream is added or removed (and when this generator's output changes) — and does NOT move for a\n * payload-schema change, which provisions nothing.\n */\nexport function eventLaneDdlFingerprint(registry: SyncTableRegistry): string {\n return EVENT_LANE_FINGERPRINT_PREFIX + hashString(buildEventLaneDdlBody(assertHasStreams(registry)));\n}\n\n/**\n * The full migration body: the DDL plus its fingerprint as a SQL comment. The comment is what\n * `pgxsinkit-generate --events --check` scans committed migrations for — the same pre-deploy drift detection\n * the apply-function artifact gets, minus the in-database stamp (there is no function here to comment on).\n */\nexport function renderEventLaneMigration(registry: SyncTableRegistry): string {\n const body = buildEventLaneDdlBody(assertHasStreams(registry));\n return `-- ${EVENT_LANE_FINGERPRINT_PREFIX + hashString(body)}\\n${body}`;\n}\n"
26
26
  ],
27
- "mappings": ";;AAUA,oDAA0B;;;ACV1B;AAAA,mBACE;AAAA;;;ACDF;AAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDO,SAAS,sBAAsB,CAAC,UAA6B,UAA8C;AAAA,EAChH,OAAO,OAAO,OAAO,QAAQ,EAAE,KAAK,CAAC,UAAU,OAAO,OAAO,aAAa,QAAQ;AAAA;AAWpF,SAAS,kBAAkB,CAAC,OAA2D;AAAA,EACrF,MAAM,SAAS,MAAM,iBAAiB,MAAM;AAAA,EAC5C,IAAI,CAAC,OAAO,SAAS,GAAG;AAAA,IAAG,OAAO,EAAE,OAAO,OAAO;AAAA,EAClD,OAAO,UAAU,OAAO,MAAM,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