@pgxsinkit/server 0.1.51 → 0.2.0

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,19 +2,19 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/electric-proxy.ts", "../src/cors-origin.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/router.ts", "../src/migrations/utilities.ts", "../src/index.ts"],
4
4
  "sourcesContent": [
5
- "import {\n buildRowFilterShape,\n getOmittedProjectedColumnNames,\n type JwtClaims,\n type RowTransform,\n type RowTransformContext,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { resolveCorsOrigin } from \"./cors-origin\";\n\nexport interface ElectricProxyCors {\n /**\n * Browser origins allowed to read this shape: exact strings (e.g. a hosted SPA + localhost dev),\n * or a `\"*\"` entry to allow every origin by reflection (see {@link resolveCorsOrigin}).\n */\n origins: string[];\n}\n\nexport interface ElectricProxyOptions {\n registry: SyncTableRegistry;\n electricUrl: string;\n /** Extra params passed to customWhere functions (e.g. fromLang, toLang). */\n extraParams?: Record<string, unknown>;\n /**\n * CORS for a browser-facing deployment with **no CORS-adding gateway in front** — e.g. a Supabase\n * Cloud edge function, which the platform routes to directly. When set, OPTIONS preflights are\n * answered here and the response carries the allowed origin plus the Electric headers the client\n * must read off each shape. Omit it where a gateway already handles CORS (the local stack's Envoy).\n */\n cors?: ElectricProxyCors;\n /**\n * Opt-in per-request timing log (default off). When on, each forwarded shape request emits one compact\n * `[pgxsinkit-timing]` line (route `\"shape\"`) with the request's table/live/offset and the upstream\n * Electric fetch duration + status, for attributing read-path latency. Additive; no behaviour change.\n */\n logTimings?: boolean;\n /**\n * Append a unique `cache-buster` to every `live=true` request forwarded upstream (default ON; set\n * `false` to restore upstream CDN collapse of live long-polls). Stopgap for Electric Cloud serving\n * live long-polls from a layer blind to fresh commits: consecutive full-hold (~41s) `up-to-date`\n * responses at an unmoved offset despite an advancing `cursor`, measured cross-client propagation\n * of 40–89s (backlog 0001, 2026-07-04; upstream report alongside it). Only the live tail is busted —\n * catch-up responses keep their CDN cold-fanout sharing, and per-user-filtered live polls share\n * ~nothing across clients anyway. Remove when Electric fixes the live path (backlog 0001's close).\n */\n bustLiveUpstreamCache?: boolean;\n}\n\nconst perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/** Per-request shape-proxy timing scratch: the upstream Electric fetch duration + its HTTP status. */\ninterface ShapeProxyTiming {\n upstreamMs: number;\n upstreamStatus: number;\n}\n\n// Electric response headers the browser client reads off each shape response (offset/handle drive\n// resumption, schema/cursor drive parsing, up-to-date ends the initial sync). They must be exposed via\n// CORS or the client cannot resume — the classic Electric \"MissingHeadersError\".\nconst ELECTRIC_EXPOSED_HEADERS = \"electric-offset,electric-handle,electric-schema,electric-cursor,electric-up-to-date\";\n\n/**\n * Proxies an Electric shape request, applying registry-driven row filters and stripping omitted\n * columns from JSON shape-log payloads. Optionally answers CORS preflights and adds CORS headers\n * ({@link ElectricProxyOptions.cors}) for gateway-less browser deployments.\n *\n * The caller is responsible for resolving auth claims from the request.\n * Pass `claims` as `null` for unauthenticated requests (all rows blocked).\n */\nexport async function proxyElectricShapeRequest(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n): Promise<Response> {\n if (options.cors && request.method === \"OPTIONS\") {\n return corsPreflightResponse(request, options.cors);\n }\n const timing: ShapeProxyTiming | undefined = options.logTimings ? { upstreamMs: 0, upstreamStatus: 0 } : undefined;\n const start = timing ? perfNow() : 0;\n const response = await forwardShapeRequest(request, claims, options, timing);\n const finalResponse = options.cors ? withCorsResponseHeaders(request, response, options.cors) : response;\n if (timing) {\n logShapeTiming(request, timing, perfNow() - start);\n }\n return finalResponse;\n}\n\n/** Emit the one-line shape-proxy timing log: table/live/offset from the request, upstream + total ms. */\nfunction logShapeTiming(request: Request, timing: ShapeProxyTiming, totalMs: number): void {\n const params = new URL(request.url).searchParams;\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route: \"shape\",\n table: params.get(\"table\") ?? undefined,\n live: params.get(\"live\") === \"true\",\n offset: params.get(\"offset\") ?? undefined,\n upstreamMs: Math.round(timing.upstreamMs),\n upstreamStatus: timing.upstreamStatus,\n totalMs: Math.round(totalMs),\n }),\n );\n}\n\nasync function forwardShapeRequest(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n timing?: ShapeProxyTiming,\n): Promise<Response> {\n const decision = decideProxyTarget(request, claims, options);\n\n if (decision.kind === \"reject\") {\n // Fail closed: never forward, so the upstream Electric credentials in\n // `electricUrl` are not lent to a request the registry does not govern.\n return new Response(JSON.stringify({ message: decision.message }), {\n status: decision.status,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n const upstreamStart = timing ? perfNow() : 0;\n const response = await fetch(decision.targetUrl, {\n method: \"GET\",\n signal: request.signal,\n }).catch((error: unknown) => {\n // Client disconnected — no meaningful response can be sent.\n // Return a 499 (client closed request) to avoid a 500 in logs.\n // Keyed on the signal's aborted state first: Bun can reject an aborted fetch with a\n // literal `null` (no AbortError to pattern-match), and once the caller aborted there is\n // nobody to answer regardless of what the rejection value looks like.\n if (request.signal.aborted || isAbortError(error)) {\n return new Response(null, { status: 499, statusText: \"Client Closed Request\" });\n }\n throw error;\n });\n if (timing) {\n timing.upstreamMs = perfNow() - upstreamStart;\n timing.upstreamStatus = response.status;\n }\n\n const responseHeaders = new Headers(response.headers);\n // Strip encoding/length since the response body may be re-serialized\n // (column omission path) or streamed through a new Response object.\n responseHeaders.delete(\"content-encoding\");\n responseHeaders.delete(\"content-length\");\n\n // The ingress `table` param carries the shape's unique `shapeKey` (the client identifies the shape;\n // the proxy maps it to the physical Electric table on egress). Resolve the entry by it.\n const shapeKey = new URL(request.url).searchParams.get(\"table\");\n const omittedColumns = shapeKey ? getOmittedProjectedColumnsForTable(options.registry, shapeKey) : [];\n const rowTransform = shapeKey ? getRowTransformForTable(options.registry, shapeKey) : undefined;\n const contentType = responseHeaders.get(\"content-type\") ?? \"\";\n\n // Re-serialize the shape log when this table needs any row-level rewriting: column\n // omission and/or a registry-declared row transform. The transform runs first so it can\n // read a column (e.g. a control flag) that omission then strips from the client row.\n if ((omittedColumns.length > 0 || rowTransform) && contentType.includes(\"application/json\")) {\n const payload = await response\n .clone()\n .json()\n .catch(() => undefined);\n\n if (Array.isArray(payload)) {\n const context: RowTransformContext = { claims, ...(options.extraParams ? { params: options.extraParams } : {}) };\n const rewritten = rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context);\n return new Response(JSON.stringify(rewritten), {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n }\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n}\n\ntype ProxyTargetDecision = { kind: \"forward\"; targetUrl: string } | { kind: \"reject\"; status: number; message: string };\n\n/**\n * Decide whether a shape request may be forwarded. The proxy serves only\n * registry-governed shapes (ADR-0003): a request with no `table`, or one whose `table`\n * (the shape's `shapeKey`) does not match a declared shape **exactly**, is rejected and never\n * reaches Electric. A shape that is in the registry but declares no `rowFilter` still\n * forwards — the gate is registry membership, not the presence of a filter.\n */\nfunction decideProxyTarget(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n): ProxyTargetDecision {\n const requestedShapeKey = new URL(request.url).searchParams.get(\"table\");\n\n if (!requestedShapeKey) {\n return { kind: \"reject\", status: 400, message: \"Shape request must specify a table\" };\n }\n\n if (!resolveEntryByShapeKey(options.registry, requestedShapeKey)) {\n return { kind: \"reject\", status: 403, message: `Shape is not in the sync registry: ${requestedShapeKey}` };\n }\n\n return { kind: \"forward\", targetUrl: buildProxyTargetUrl(request, claims, options) };\n}\n\n/**\n * Electric protocol resume/control query params a client may legitimately set on a shape request.\n * These drive resumption and long-poll; they do **not** define the shape's data. Every\n * shape-DEFINING param (`table`, `where`, `columns`, and any shape option such as `replica`) is\n * derived from the registry below, never forwarded from the client (ADR-0003 ISS-08).\n *\n * Kept as an explicit local allowlist — mirroring the `*_QUERY_PARAM` constants in\n * `@electric-sql/client` (1.5.x) — so the proxy fails **closed** on any unknown or future param\n * rather than lending it upstream Electric authority. `@electric-sql/client` exposes no aggregate\n * \"protocol params\" export to import, and `@pgxsinkit/server` deliberately takes no client-package\n * dependency, so the set is enumerated here with each Electric param it maps to.\n */\nconst ELECTRIC_CONTROL_QUERY_PARAMS: ReadonlySet<string> = new Set([\n \"offset\", // OFFSET_QUERY_PARAM — resume position\n \"handle\", // SHAPE_HANDLE_QUERY_PARAM — shape handle\n \"live\", // LIVE_QUERY_PARAM — long-poll mode\n \"cursor\", // LIVE_CACHE_BUSTER_QUERY_PARAM — live cursor\n \"cache-buster\", // CACHE_BUSTER_QUERY_PARAM\n \"expired_handle\", // EXPIRED_HANDLE_QUERY_PARAM — resume after a handle expires\n \"experimental_live_sse\", // EXPERIMENTAL_LIVE_SSE_QUERY_PARAM\n \"live_sse\", // LIVE_SSE_QUERY_PARAM\n \"log\", // LOG_MODE_QUERY_PARAM\n]);\n\nfunction buildProxyTargetUrl(request: Request, claims: JwtClaims | null, options: ElectricProxyOptions): string {\n const requestUrl = new URL(request.url);\n const targetUrl = new URL(options.electricUrl);\n\n // The registry entry — resolved by the request's `shapeKey` — is the sole shape authority\n // (ADR-0003). Strip any shape-defining param riding on `electricUrl` and re-derive `table`,\n // `where`, and `columns` from the registry. The client-supplied `where` never reaches here\n // either: authorization must never depend on client-controlled SQL — there is no safe way to\n // merge untrusted raw SQL into the ownership predicate (`1=1) OR (1=1` escapes any wrapping and\n // precedence-reduces to all-rows), so the registry row filter is the only `where`.\n targetUrl.searchParams.delete(\"where\");\n targetUrl.searchParams.delete(\"columns\");\n\n // Resolve by the ingress shapeKey, then set the EGRESS `table` to the entry's physical Electric\n // target (a read projection's owning table differs from its shapeKey).\n const entry = resolveEntryByShapeKey(options.registry, requestUrl.searchParams.get(\"table\") ?? \"\");\n const electricTarget = electricTargetForEntry(entry);\n\n if (!electricTarget) {\n // Defensive only: decideProxyTarget already validated the shapeKey against the registry before we\n // get here. Without a registry-resolved target there is no governed shape to serve.\n return targetUrl.toString();\n }\n\n targetUrl.searchParams.set(\"table\", electricTarget);\n\n // Forward ONLY Electric protocol resume/control params from the client. A client-supplied\n // `columns`, `replica`, or any unknown/future param is never lent upstream authority — it cannot\n // alter the shape beyond what the registry authorized.\n requestUrl.searchParams.forEach((value, key) => {\n if (ELECTRIC_CONTROL_QUERY_PARAMS.has(key)) {\n targetUrl.searchParams.set(key, value);\n }\n });\n\n // Live-tail cache bust ({@link ElectricProxyOptions.bustLiveUpstreamCache}): a unique\n // Electric-recognized `cache-buster` per live long-poll keeps any upstream CDN from answering the\n // poll out of a collapsed/cached entry that cannot see fresh commits (backlog 0001). Catch-up\n // requests are left untouched so cold-fanout CDN sharing keeps working. Set AFTER the forward loop\n // so a client-sent buster (the stale-cache ladder rides catch-up, not live) is never clobbered on\n // non-live requests and a live request always gets a fresh one.\n if (options.bustLiveUpstreamCache !== false && targetUrl.searchParams.get(\"live\") === \"true\") {\n targetUrl.searchParams.set(\"cache-buster\", crypto.randomUUID());\n }\n\n const rowFilter = entry?.shape?.rowFilter;\n\n if (!rowFilter) {\n return targetUrl.toString();\n }\n\n // A `customWhere` that returns a Drizzle `SQL` fragment is emitted as a *parameterized* Electric\n // where — `where=… $1 …` plus `params[1]=…` — so no request-derived value is ever inlined/escaped by\n // hand (Drizzle owns identifiers + structure, Electric binds the leaves). `ownership`/`shared` and a\n // string `customWhere` stay inline; `buildRowFilterShape` composes both forms.\n const shape = buildRowFilterShape(rowFilter, claims, options.extraParams);\n\n if (shape) {\n targetUrl.searchParams.set(\"where\", shape.where);\n shape.params.forEach((param, index) => {\n targetUrl.searchParams.set(`params[${index + 1}]`, param);\n });\n }\n\n // Registry-declared column projection (an explicit opt-in). Per-row `omitColumns` is enforced\n // separately by post-hoc JSON stripping (below), so an omitted column never reaches the client\n // even when no projection is set here.\n if (rowFilter.columns && rowFilter.columns.length > 0) {\n targetUrl.searchParams.set(\"columns\", rowFilter.columns.join(\",\"));\n }\n\n return targetUrl.toString();\n}\n\n/**\n * The physical Electric table an entry reads — `electricTable` (a read projection's owning table) if\n * set, otherwise the shape's own table name. This is the value the proxy sends UPSTREAM in the egress\n * `table` param; several shapes may share it (a projection and its owner), which is exactly why an\n * incoming request is resolved by `shapeKey` (below), not by this.\n */\nfunction electricTargetForEntry(entry: SyncTableEntry | undefined): string | null {\n const shape = entry?.shape;\n if (!shape) {\n return null;\n }\n return shape.electricTable ?? shape.tableName;\n}\n\n/**\n * Resolve the registry entry a request selects by its **`shapeKey`** — the unique per-shape identity a\n * client puts in the ingress `table` param. Resolving by shapeKey (not by physical Electric target) is\n * what lets several shapes read ONE physical table: a read projection and its owner share an Electric\n * target but carry distinct shapeKeys. Schema qualification is significant (`authors` ≠\n * `private.authors`). Returns undefined when no entry declares that shapeKey — the caller fails closed.\n */\nfunction resolveEntryByShapeKey(registry: SyncTableRegistry, requestedShapeKey: string): SyncTableEntry | undefined {\n for (const key of Object.keys(registry)) {\n const entry = registry[key as keyof typeof registry] as SyncTableEntry | undefined;\n if (entry?.shape?.shapeKey === requestedShapeKey) {\n return entry;\n }\n }\n return undefined;\n}\n\nfunction getOmittedProjectedColumnsForTable(registry: SyncTableRegistry, shapeKey: string): readonly string[] {\n const entry = resolveEntryByShapeKey(registry, shapeKey);\n return entry ? getOmittedProjectedColumnNames(entry) : [];\n}\n\nfunction getRowTransformForTable(registry: SyncTableRegistry, shapeKey: string): RowTransform | undefined {\n return resolveEntryByShapeKey(registry, shapeKey)?.serverProjection?.rowTransform;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Subset of an Electric shape-log entry the proxy rewrites: `value` carries the\n * row, `old_value` the prior row on updates. Runtime guards still validate both\n * before use; the declared shape is the wire-protocol expectation.\n */\ninterface ShapeLogEntry {\n value?: Record<string, unknown>;\n old_value?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nfunction isShapeLogEntry(value: unknown): value is ShapeLogEntry {\n return isObjectRecord(value);\n}\n\n/**\n * Rewrite each shape-log row: apply the registry row transform (if any), then strip\n * omitted columns. Both passes preserve object identity when nothing changes, so an\n * untouched entry flows through unmodified.\n */\nfunction rewriteRow(\n row: Record<string, unknown>,\n omittedColumns: readonly string[],\n rowTransform: RowTransform | undefined,\n context: RowTransformContext,\n): Record<string, unknown> {\n const transformed = rowTransform ? rowTransform(row, context) : row;\n return omittedColumns.length > 0 ? omitColumnsFromRow(transformed, omittedColumns) : transformed;\n}\n\nfunction rewriteShapeLogEntries(\n payload: unknown[],\n omittedColumns: readonly string[],\n rowTransform: RowTransform | undefined,\n context: RowTransformContext,\n): unknown[] {\n return payload.map((entry) => {\n if (!isShapeLogEntry(entry)) {\n return entry;\n }\n\n let currentEntry: ShapeLogEntry = entry;\n\n if (isObjectRecord(entry.value)) {\n const nextValue = rewriteRow(entry.value, omittedColumns, rowTransform, context);\n if (nextValue !== entry.value) {\n currentEntry = { ...currentEntry, value: nextValue };\n }\n }\n\n if (isObjectRecord(currentEntry.old_value)) {\n const nextOldValue = rewriteRow(currentEntry.old_value, omittedColumns, rowTransform, context);\n if (nextOldValue !== currentEntry.old_value) {\n currentEntry = { ...currentEntry, old_value: nextOldValue };\n }\n }\n\n return currentEntry;\n });\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"AbortError\" ||\n // Bun wraps aborted fetch as DOMException with numeric code\n (typeof (error as unknown as { code?: unknown }).code === \"number\" &&\n (error as unknown as { code: number }).code === 20))\n );\n}\n\n/** The request's `Origin` if it is on the allow-list, else `null` (so a disallowed origin gets no CORS). */\nfunction allowedCorsOrigin(request: Request, cors: ElectricProxyCors): string | null {\n return resolveCorsOrigin(request, cors.origins);\n}\n\n/** Answer a browser preflight: allowed origin, GET-only, the requested headers, cached for an hour. */\nfunction corsPreflightResponse(request: Request, cors: ElectricProxyCors): Response {\n const headers = new Headers();\n const origin = allowedCorsOrigin(request, cors);\n if (origin) {\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n }\n headers.set(\"Access-Control-Allow-Methods\", \"GET,OPTIONS\");\n // Echo what the browser asks to send (authorization + apikey for a Supabase function), falling back\n // to the standard set — so any client header is permitted without enumerating every one here.\n headers.set(\n \"Access-Control-Allow-Headers\",\n request.headers.get(\"access-control-request-headers\") ?? \"authorization,apikey,content-type\",\n );\n headers.set(\"Access-Control-Max-Age\", \"3600\");\n return new Response(null, { status: 204, headers });\n}\n\n/** Add the allowed origin + the exposed Electric headers to a real shape response (no-op off-list). */\nfunction withCorsResponseHeaders(request: Request, response: Response, cors: ElectricProxyCors): Response {\n const origin = allowedCorsOrigin(request, cors);\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 headers.set(\"Access-Control-Expose-Headers\", ELECTRIC_EXPOSED_HEADERS);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n}\n\nfunction omitColumnsFromRow(row: Record<string, unknown>, omittedColumns: readonly string[]): Record<string, unknown> {\n let changed = false;\n const nextRow = { ...row };\n\n for (const column of omittedColumns) {\n if (Object.prototype.hasOwnProperty.call(nextRow, column)) {\n delete nextRow[column];\n changed = true;\n }\n }\n\n return changed ? nextRow : row;\n}\n",
5
+ "import {\n buildRowFilterShape,\n getOmittedProjectedColumnNames,\n type JwtClaims,\n type RowTransform,\n type RowTransformContext,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { resolveCorsOrigin } from \"./cors-origin\";\n\nexport interface ElectricProxyCors {\n /**\n * Browser origins allowed to read this shape: exact strings (e.g. a hosted SPA + localhost dev),\n * or a `\"*\"` entry to allow every origin by reflection (see {@link resolveCorsOrigin}).\n */\n origins: string[];\n}\n\nexport interface ElectricProxyOptions {\n registry: SyncTableRegistry;\n electricUrl: string;\n /** Extra params passed to customWhere functions (e.g. fromLang, toLang). */\n extraParams?: Record<string, unknown>;\n /**\n * CORS for a browser-facing deployment with **no CORS-adding gateway in front** — e.g. a Supabase\n * Cloud edge function, which the platform routes to directly. When set, OPTIONS preflights are\n * answered here and the response carries the allowed origin plus the Electric headers the client\n * must read off each shape. Omit it where a gateway already handles CORS (the local stack's Envoy).\n */\n cors?: ElectricProxyCors;\n /**\n * Opt-in per-request timing log (default off). When on, each forwarded shape request emits one compact\n * `[pgxsinkit-timing]` line (route `\"shape\"`) with the request's table/live/offset and the upstream\n * Electric fetch duration + status, for attributing read-path latency. Off by default — a pure\n * diagnostic surface that adds no standing query or latency when unset.\n */\n logTimings?: boolean;\n /**\n * Append a unique `cache-buster` to every `live=true` request forwarded upstream (default ON; set\n * `false` to restore upstream CDN collapse of live long-polls). Stopgap for Electric Cloud serving\n * live long-polls from a layer blind to fresh commits: consecutive full-hold (~41s) `up-to-date`\n * responses at an unmoved offset despite an advancing `cursor`, measured cross-client propagation\n * of 40–89s (backlog 0001, 2026-07-04; upstream report alongside it). Only the live tail is busted —\n * catch-up responses keep their CDN cold-fanout sharing, and per-user-filtered live polls share\n * ~nothing across clients anyway. Remove when Electric fixes the live path (backlog 0001's close).\n */\n bustLiveUpstreamCache?: boolean;\n}\n\nconst perfNow = () => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/** Per-request shape-proxy timing scratch: the upstream Electric fetch duration + its HTTP status. */\ninterface ShapeProxyTiming {\n upstreamMs: number;\n upstreamStatus: number;\n}\n\n// Electric response headers the browser client reads off each shape response (offset/handle drive\n// resumption, schema/cursor drive parsing, up-to-date ends the initial sync). They must be exposed via\n// CORS or the client cannot resume — the classic Electric \"MissingHeadersError\".\nconst ELECTRIC_EXPOSED_HEADERS = \"electric-offset,electric-handle,electric-schema,electric-cursor,electric-up-to-date\";\n\n/**\n * Proxies an Electric shape request, applying registry-driven row filters and stripping omitted\n * columns from JSON shape-log payloads. Optionally answers CORS preflights and adds CORS headers\n * ({@link ElectricProxyOptions.cors}) for gateway-less browser deployments.\n *\n * The caller is responsible for resolving auth claims from the request.\n * Pass `claims` as `null` for unauthenticated requests (all rows blocked).\n */\nexport async function proxyElectricShapeRequest(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n): Promise<Response> {\n if (options.cors && request.method === \"OPTIONS\") {\n return corsPreflightResponse(request, options.cors);\n }\n const timing: ShapeProxyTiming | undefined = options.logTimings ? { upstreamMs: 0, upstreamStatus: 0 } : undefined;\n const start = timing ? perfNow() : 0;\n const response = await forwardShapeRequest(request, claims, options, timing);\n const finalResponse = options.cors ? withCorsResponseHeaders(request, response, options.cors) : response;\n if (timing) {\n logShapeTiming(request, timing, perfNow() - start);\n }\n return finalResponse;\n}\n\n/** Emit the one-line shape-proxy timing log: table/live/offset from the request, upstream + total ms. */\nfunction logShapeTiming(request: Request, timing: ShapeProxyTiming, totalMs: number): void {\n const params = new URL(request.url).searchParams;\n console.log(\n \"[pgxsinkit-timing]\",\n JSON.stringify({\n route: \"shape\",\n table: params.get(\"table\") ?? undefined,\n live: params.get(\"live\") === \"true\",\n offset: params.get(\"offset\") ?? undefined,\n upstreamMs: Math.round(timing.upstreamMs),\n upstreamStatus: timing.upstreamStatus,\n totalMs: Math.round(totalMs),\n }),\n );\n}\n\nasync function forwardShapeRequest(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n timing?: ShapeProxyTiming,\n): Promise<Response> {\n const decision = decideProxyTarget(request, claims, options);\n\n if (decision.kind === \"reject\") {\n // Fail closed: never forward, so the upstream Electric credentials in\n // `electricUrl` are not lent to a request the registry does not govern.\n return new Response(JSON.stringify({ message: decision.message }), {\n status: decision.status,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n const upstreamStart = timing ? perfNow() : 0;\n const response = await fetch(decision.targetUrl, {\n method: \"GET\",\n signal: request.signal,\n }).catch((error: unknown) => {\n // Client disconnected — no meaningful response can be sent.\n // Return a 499 (client closed request) to avoid a 500 in logs.\n // Keyed on the signal's aborted state first: Bun can reject an aborted fetch with a\n // literal `null` (no AbortError to pattern-match), and once the caller aborted there is\n // nobody to answer regardless of what the rejection value looks like.\n if (request.signal.aborted || isAbortError(error)) {\n return new Response(null, { status: 499, statusText: \"Client Closed Request\" });\n }\n throw error;\n });\n if (timing) {\n timing.upstreamMs = perfNow() - upstreamStart;\n timing.upstreamStatus = response.status;\n }\n\n const responseHeaders = new Headers(response.headers);\n // Strip encoding/length since the response body may be re-serialized\n // (column omission path) or streamed through a new Response object.\n responseHeaders.delete(\"content-encoding\");\n responseHeaders.delete(\"content-length\");\n\n // The ingress `table` param carries the shape's unique `shapeKey` (the client identifies the shape;\n // the proxy maps it to the physical Electric table on egress). Resolve the entry by it.\n const shapeKey = new URL(request.url).searchParams.get(\"table\");\n const omittedColumns = shapeKey ? getOmittedProjectedColumnsForTable(options.registry, shapeKey) : [];\n const rowTransform = shapeKey ? getRowTransformForTable(options.registry, shapeKey) : undefined;\n const contentType = responseHeaders.get(\"content-type\") ?? \"\";\n\n // Re-serialize the shape log when this table needs any row-level rewriting: column\n // omission and/or a registry-declared row transform. The transform runs first so it can\n // read a column (e.g. a control flag) that omission then strips from the client row.\n if ((omittedColumns.length > 0 || rowTransform) && contentType.includes(\"application/json\")) {\n const payload = await response\n .clone()\n .json()\n .catch(() => undefined);\n\n if (Array.isArray(payload)) {\n const context: RowTransformContext = { claims, ...(options.extraParams ? { params: options.extraParams } : {}) };\n const rewritten = rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context);\n return new Response(JSON.stringify(rewritten), {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n }\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n}\n\ntype ProxyTargetDecision = { kind: \"forward\"; targetUrl: string } | { kind: \"reject\"; status: number; message: string };\n\n/**\n * Decide whether a shape request may be forwarded. The proxy serves only\n * registry-governed shapes (ADR-0003): a request with no `table`, or one whose `table`\n * (the shape's `shapeKey`) does not match a declared shape **exactly**, is rejected and never\n * reaches Electric. A shape that is in the registry but declares no `rowFilter` still\n * forwards — the gate is registry membership, not the presence of a filter.\n */\nfunction decideProxyTarget(\n request: Request,\n claims: JwtClaims | null,\n options: ElectricProxyOptions,\n): ProxyTargetDecision {\n const requestedShapeKey = new URL(request.url).searchParams.get(\"table\");\n\n if (!requestedShapeKey) {\n return { kind: \"reject\", status: 400, message: \"Shape request must specify a table\" };\n }\n\n if (!resolveEntryByShapeKey(options.registry, requestedShapeKey)) {\n return { kind: \"reject\", status: 403, message: `Shape is not in the sync registry: ${requestedShapeKey}` };\n }\n\n return { kind: \"forward\", targetUrl: buildProxyTargetUrl(request, claims, options) };\n}\n\n/**\n * Electric protocol resume/control query params a client may legitimately set on a shape request.\n * These drive resumption and long-poll; they do **not** define the shape's data. Every\n * shape-DEFINING param (`table`, `where`, `columns`, and any shape option such as `replica`) is\n * derived from the registry below, never forwarded from the client (ADR-0003 ISS-08).\n *\n * Kept as an explicit local allowlist — mirroring the `*_QUERY_PARAM` constants in\n * `@electric-sql/client` (1.5.x) — so the proxy fails **closed** on any unknown or future param\n * rather than lending it upstream Electric authority. `@electric-sql/client` exposes no aggregate\n * \"protocol params\" export to import, and `@pgxsinkit/server` deliberately takes no client-package\n * dependency, so the set is enumerated here with each Electric param it maps to.\n */\nconst ELECTRIC_CONTROL_QUERY_PARAMS: ReadonlySet<string> = new Set([\n \"offset\", // OFFSET_QUERY_PARAM — resume position\n \"handle\", // SHAPE_HANDLE_QUERY_PARAM — shape handle\n \"live\", // LIVE_QUERY_PARAM — long-poll mode\n \"cursor\", // LIVE_CACHE_BUSTER_QUERY_PARAM — live cursor\n \"cache-buster\", // CACHE_BUSTER_QUERY_PARAM\n \"expired_handle\", // EXPIRED_HANDLE_QUERY_PARAM — resume after a handle expires\n \"experimental_live_sse\", // EXPERIMENTAL_LIVE_SSE_QUERY_PARAM\n \"live_sse\", // LIVE_SSE_QUERY_PARAM\n \"log\", // LOG_MODE_QUERY_PARAM\n]);\n\nfunction buildProxyTargetUrl(request: Request, claims: JwtClaims | null, options: ElectricProxyOptions): string {\n const requestUrl = new URL(request.url);\n const targetUrl = new URL(options.electricUrl);\n\n // The registry entry — resolved by the request's `shapeKey` — is the sole shape authority\n // (ADR-0003). Strip any shape-defining param riding on `electricUrl` and re-derive `table`,\n // `where`, and `columns` from the registry. The client-supplied `where` never reaches here\n // either: authorization must never depend on client-controlled SQL — there is no safe way to\n // merge untrusted raw SQL into the ownership predicate (`1=1) OR (1=1` escapes any wrapping and\n // precedence-reduces to all-rows), so the registry row filter is the only `where`.\n targetUrl.searchParams.delete(\"where\");\n targetUrl.searchParams.delete(\"columns\");\n\n // Resolve by the ingress shapeKey, then set the EGRESS `table` to the entry's physical Electric\n // target (a read projection's owning table differs from its shapeKey).\n const entry = resolveEntryByShapeKey(options.registry, requestUrl.searchParams.get(\"table\") ?? \"\");\n const electricTarget = electricTargetForEntry(entry);\n\n if (!electricTarget) {\n // Defensive only: decideProxyTarget already validated the shapeKey against the registry before we\n // get here. Without a registry-resolved target there is no governed shape to serve.\n return targetUrl.toString();\n }\n\n targetUrl.searchParams.set(\"table\", electricTarget);\n\n // Forward ONLY Electric protocol resume/control params from the client. A client-supplied\n // `columns`, `replica`, or any unknown/future param is never lent upstream authority — it cannot\n // alter the shape beyond what the registry authorized.\n requestUrl.searchParams.forEach((value, key) => {\n if (ELECTRIC_CONTROL_QUERY_PARAMS.has(key)) {\n targetUrl.searchParams.set(key, value);\n }\n });\n\n // Live-tail cache bust ({@link ElectricProxyOptions.bustLiveUpstreamCache}): a unique\n // Electric-recognized `cache-buster` per live long-poll keeps any upstream CDN from answering the\n // poll out of a collapsed/cached entry that cannot see fresh commits (backlog 0001). Catch-up\n // requests are left untouched so cold-fanout CDN sharing keeps working. Set AFTER the forward loop\n // so a client-sent buster (the stale-cache ladder rides catch-up, not live) is never clobbered on\n // non-live requests and a live request always gets a fresh one.\n if (options.bustLiveUpstreamCache !== false && targetUrl.searchParams.get(\"live\") === \"true\") {\n targetUrl.searchParams.set(\"cache-buster\", crypto.randomUUID());\n }\n\n const rowFilter = entry?.shape?.rowFilter;\n\n if (!rowFilter) {\n return targetUrl.toString();\n }\n\n // A `customWhere` that returns a Drizzle `SQL` fragment is emitted as a *parameterized* Electric\n // where — `where=… $1 …` plus `params[1]=…` — so no request-derived value is ever inlined/escaped by\n // hand (Drizzle owns identifiers + structure, Electric binds the leaves). `ownership`/`shared` and a\n // string `customWhere` stay inline; `buildRowFilterShape` composes both forms.\n const shape = buildRowFilterShape(rowFilter, claims, options.extraParams);\n\n if (shape) {\n targetUrl.searchParams.set(\"where\", shape.where);\n shape.params.forEach((param, index) => {\n targetUrl.searchParams.set(`params[${index + 1}]`, param);\n });\n }\n\n // Registry-declared column projection (an explicit opt-in). Per-row `omitColumns` is enforced\n // separately by post-hoc JSON stripping (below), so an omitted column never reaches the client\n // even when no projection is set here.\n if (rowFilter.columns && rowFilter.columns.length > 0) {\n targetUrl.searchParams.set(\"columns\", rowFilter.columns.join(\",\"));\n }\n\n return targetUrl.toString();\n}\n\n/**\n * The physical Electric table an entry reads — `electricTable` (a read projection's owning table) if\n * set, otherwise the shape's own table name. This is the value the proxy sends UPSTREAM in the egress\n * `table` param; several shapes may share it (a projection and its owner), which is exactly why an\n * incoming request is resolved by `shapeKey` (below), not by this.\n */\nfunction electricTargetForEntry(entry: SyncTableEntry | undefined): string | null {\n const shape = entry?.shape;\n if (!shape) {\n return null;\n }\n return shape.electricTable ?? shape.tableName;\n}\n\n/**\n * Resolve the registry entry a request selects by its **`shapeKey`** — the unique per-shape identity a\n * client puts in the ingress `table` param. Resolving by shapeKey (not by physical Electric target) is\n * what lets several shapes read ONE physical table: a read projection and its owner share an Electric\n * target but carry distinct shapeKeys. Schema qualification is significant (`authors` ≠\n * `private.authors`). Returns undefined when no entry declares that shapeKey — the caller fails closed.\n */\nfunction resolveEntryByShapeKey(registry: SyncTableRegistry, requestedShapeKey: string): SyncTableEntry | undefined {\n for (const key of Object.keys(registry)) {\n const entry = registry[key as keyof typeof registry] as SyncTableEntry | undefined;\n if (entry?.shape?.shapeKey === requestedShapeKey) {\n return entry;\n }\n }\n return undefined;\n}\n\nfunction getOmittedProjectedColumnsForTable(registry: SyncTableRegistry, shapeKey: string): readonly string[] {\n const entry = resolveEntryByShapeKey(registry, shapeKey);\n return entry ? getOmittedProjectedColumnNames(entry) : [];\n}\n\nfunction getRowTransformForTable(registry: SyncTableRegistry, shapeKey: string): RowTransform | undefined {\n return resolveEntryByShapeKey(registry, shapeKey)?.serverProjection?.rowTransform;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Subset of an Electric shape-log entry the proxy rewrites: `value` carries the\n * row, `old_value` the prior row on updates. Runtime guards still validate both\n * before use; the declared shape is the wire-protocol expectation.\n */\ninterface ShapeLogEntry {\n value?: Record<string, unknown>;\n old_value?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nfunction isShapeLogEntry(value: unknown): value is ShapeLogEntry {\n return isObjectRecord(value);\n}\n\n/**\n * Rewrite each shape-log row: apply the registry row transform (if any), then strip\n * omitted columns. Both passes preserve object identity when nothing changes, so an\n * untouched entry flows through unmodified.\n */\nfunction rewriteRow(\n row: Record<string, unknown>,\n omittedColumns: readonly string[],\n rowTransform: RowTransform | undefined,\n context: RowTransformContext,\n): Record<string, unknown> {\n const transformed = rowTransform ? rowTransform(row, context) : row;\n return omittedColumns.length > 0 ? omitColumnsFromRow(transformed, omittedColumns) : transformed;\n}\n\nfunction rewriteShapeLogEntries(\n payload: unknown[],\n omittedColumns: readonly string[],\n rowTransform: RowTransform | undefined,\n context: RowTransformContext,\n): unknown[] {\n return payload.map((entry) => {\n if (!isShapeLogEntry(entry)) {\n return entry;\n }\n\n let currentEntry: ShapeLogEntry = entry;\n\n if (isObjectRecord(entry.value)) {\n const nextValue = rewriteRow(entry.value, omittedColumns, rowTransform, context);\n if (nextValue !== entry.value) {\n currentEntry = { ...currentEntry, value: nextValue };\n }\n }\n\n if (isObjectRecord(currentEntry.old_value)) {\n const nextOldValue = rewriteRow(currentEntry.old_value, omittedColumns, rowTransform, context);\n if (nextOldValue !== currentEntry.old_value) {\n currentEntry = { ...currentEntry, old_value: nextOldValue };\n }\n }\n\n return currentEntry;\n });\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"AbortError\" ||\n // Bun wraps aborted fetch as DOMException with numeric code\n (typeof (error as unknown as { code?: unknown }).code === \"number\" &&\n (error as unknown as { code: number }).code === 20))\n );\n}\n\n/** The request's `Origin` if it is on the allow-list, else `null` (so a disallowed origin gets no CORS). */\nfunction allowedCorsOrigin(request: Request, cors: ElectricProxyCors): string | null {\n return resolveCorsOrigin(request, cors.origins);\n}\n\n/** Answer a browser preflight: allowed origin, GET-only, the requested headers, cached for an hour. */\nfunction corsPreflightResponse(request: Request, cors: ElectricProxyCors): Response {\n const headers = new Headers();\n const origin = allowedCorsOrigin(request, cors);\n if (origin) {\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.append(\"Vary\", \"Origin\");\n }\n headers.set(\"Access-Control-Allow-Methods\", \"GET,OPTIONS\");\n // Echo what the browser asks to send (authorization + apikey for a Supabase function), falling back\n // to the standard set — so any client header is permitted without enumerating every one here.\n headers.set(\n \"Access-Control-Allow-Headers\",\n request.headers.get(\"access-control-request-headers\") ?? \"authorization,apikey,content-type\",\n );\n headers.set(\"Access-Control-Max-Age\", \"3600\");\n return new Response(null, { status: 204, headers });\n}\n\n/** Add the allowed origin + the exposed Electric headers to a real shape response (no-op off-list). */\nfunction withCorsResponseHeaders(request: Request, response: Response, cors: ElectricProxyCors): Response {\n const origin = allowedCorsOrigin(request, cors);\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 headers.set(\"Access-Control-Expose-Headers\", ELECTRIC_EXPOSED_HEADERS);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n}\n\nfunction omitColumnsFromRow(row: Record<string, unknown>, omittedColumns: readonly string[]): Record<string, unknown> {\n let changed = false;\n const nextRow = { ...row };\n\n for (const column of omittedColumns) {\n if (Object.prototype.hasOwnProperty.call(nextRow, column)) {\n delete nextRow[column];\n changed = true;\n }\n }\n\n return changed ? nextRow : row;\n}\n",
6
6
  "/**\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",
7
- "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 MutationAck,\n RegistryRelations,\n SyncTableEntry,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport {\n authoritativeWriteRequestSchema,\n batchMutationRequestSchema,\n getOmittedProjectedColumns as getOmittedProjectionColumns,\n getProjectedColumns,\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 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 coerce: { date: true },\n});\n\ntype RouteReadQueryClient = Pick<PgAsyncDatabase<PgQueryResultHKT, AnyRelations>, \"select\">;\n\nexport const batchMutationPaths = [\"/api/mutations\", \"/mutations\"] as const;\n/** The authoritative (pessimistic) write endpoint (ADR-0022 §3): one atomic write-unit per POST. */\nexport const authoritativeMutationPaths = [\"/api/mutations/unit\", \"/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): { batch: FetchHandler; authoritative: FetchHandler } {\n let startupReadyPromise: Promise<void> | undefined;\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);\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 createMutationInsertSchema(syncEntry.table as AnyPgTable)\n .partial()\n .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 );\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 );\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\nfunction 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 = getManagedFieldsForOperation(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\nfunction sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTableRegistry): 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 = getManagedFieldsForOperation(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 = getManagedFieldsForOperation(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\nfunction getManagedFieldsForOperation(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n if (mutationKind === \"delete\") {\n return [];\n }\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) => field.applyOn.includes(mutationKind))\n .map((field) => ({\n propertyKey: field.column,\n columnName: columnMap.get(field.column) ?? field.column,\n strategy: field.strategy,\n }));\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",
7
+ "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 MutationAck,\n RegistryRelations,\n SyncTableEntry,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport {\n authoritativeWriteRequestSchema,\n batchMutationRequestSchema,\n getOmittedProjectedColumns as getOmittedProjectionColumns,\n getProjectedColumns,\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 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 coerce: { date: 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): { batch: FetchHandler; authoritative: FetchHandler } {\n let startupReadyPromise: Promise<void> | undefined;\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);\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 createMutationInsertSchema(syncEntry.table as AnyPgTable)\n .partial()\n .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 );\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 );\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\nfunction 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 = getManagedFieldsForOperation(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\nfunction sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTableRegistry): 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 = getManagedFieldsForOperation(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 = getManagedFieldsForOperation(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\nfunction getManagedFieldsForOperation(\n entry: SyncTableEntry,\n mutationKind: BatchMutationRequest[\"mutations\"][number][\"kind\"],\n) {\n if (mutationKind === \"delete\") {\n return [];\n }\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) => field.applyOn.includes(mutationKind))\n .map((field) => ({\n propertyKey: field.column,\n columnName: columnMap.get(field.column) ?? field.column,\n strategy: field.strategy,\n }));\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",
8
8
  "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",
9
9
  "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",
10
10
  "/**\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",
11
- "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 CLOCK_US_CALL_SQL_TEXT,\n escapeSqlLiteral as toSqlLiteral,\n getProjectedColumns,\n hashString,\n quoteIdentifier as quoteIdent,\n resolveServerVersionColumnName,\n type BatchMutationRequest,\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\ninterface ResolvedManagedField {\n propertyKey: string;\n columnName: string;\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\nfunction getManagedFieldsForOperation(entry: SyncTableEntry, operation: \"create\" | \"update\"): ResolvedManagedField[] {\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 if (!field.applyOn.includes(operation)) {\n return [];\n }\n\n const columnName = columnNameMap.get(field.column);\n if (!columnName) {\n return [];\n }\n\n const column =\n (columns as Record<string, { getSQLType: () => string } | undefined>)[field.column] ??\n Object.values(columns).find((candidate) => candidate.name === field.column);\n\n return [\n {\n propertyKey: field.column,\n columnName,\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 return { name: columnName, type: columnObject.getSQLType() };\n });\n const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));\n\n const createManagedFields = getManagedFieldsForOperation(entry, \"create\");\n const updateManagedFields = getManagedFieldsForOperation(entry, \"update\");\n const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));\n const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));\n\n const allColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !createManagedFieldNames.has(column.name))\n .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)\n .join(\",\\n \");\n\n const nonPrimaryKeyColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !primaryKeyColumnNames.has(column.name) && !updateManagedFieldNames.has(column.name))\n .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)\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(format('(x.p->>%L)::%s', col_name, col_type), ', ' ORDER BY col_name)\n INTO v_cols, v_vals\n FROM (VALUES\n ${allColumnPairs}\n ) AS col_types(col_name, col_type)\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 = (x.p->>%L)::%s', col_name, col_name, col_type), ', ' ORDER BY col_name)\n INTO v_set\n FROM (VALUES\n ${nonPrimaryKeyColumnPairs}\n ) AS col_types(col_name, col_type)\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. The previous (pre-ADR-0030) signature dropped the trailing `text`.\nconst APPLY_FUNCTION_ARG_TYPES = \"jsonb, text, boolean, boolean, jsonb, text\";\nconst APPLY_FUNCTION_ARG_TYPES_LEGACY = \"jsonb, text, boolean, boolean, jsonb\";\n// ADR-0018: version-prefixed so the stored format can evolve; the reader parses the prefix and\n// treats an unknown prefix as \"can't compare\" (warn) rather than a mismatch (error).\nconst APPLY_FINGERPRINT_PREFIX = \"pgxsinkit:fp1:\";\n\nfunction buildApplyFunctionBody(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): 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(options.functionSchema, APPLY_FUNCTION_NAME);\n\n return `\n-- ADR-0015: the function now RETURNS the per-mutation conflicts (a reject-if-stale stale write). A\n-- return-type change cannot be a bare CREATE OR REPLACE, so drop the prior (void-returning) signature\n-- first. Idempotent: re-running installs the same 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--\n-- ADR-0030: the signature gained a trailing p_expected_fingerprint text, so the prior (pre-ADR-0030,\n-- 5-arg) function is a DIFFERENT overload — drop it too, else a CREATE of the 6-arg form would leave a\n-- stale 5-arg beside it. The runtime only ever calls the 6-arg form; dropping the legacy one keeps an\n-- in-place upgrade clean.\nDROP FUNCTION IF EXISTS ${functionName}(${APPLY_FUNCTION_ARG_TYPES_LEGACY});\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 (a hand-installed / pre-fingerprint\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`.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 * customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).\n */\nexport function expectedApplyFingerprint(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): string {\n return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));\n}\n\nexport function buildPlpgsqlBatchFunctionDdl(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): string {\n const body = buildApplyFunctionBody(registry, options);\n const functionName = qualifyIdent(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: {\n functionSchema?: string;\n } = {},\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.\n const functionRef = options.functionSchema\n ? sql`${sql.identifier(options.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",
11
+ "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 CLOCK_US_CALL_SQL_TEXT,\n escapeSqlLiteral as toSqlLiteral,\n getProjectedColumns,\n hashString,\n quoteIdentifier as quoteIdent,\n resolveServerVersionColumnName,\n type BatchMutationRequest,\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\ninterface ResolvedManagedField {\n propertyKey: string;\n columnName: string;\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\nfunction getManagedFieldsForOperation(entry: SyncTableEntry, operation: \"create\" | \"update\"): ResolvedManagedField[] {\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 if (!field.applyOn.includes(operation)) {\n return [];\n }\n\n const columnName = columnNameMap.get(field.column);\n if (!columnName) {\n return [];\n }\n\n const column =\n (columns as Record<string, { getSQLType: () => string } | undefined>)[field.column] ??\n Object.values(columns).find((candidate) => candidate.name === field.column);\n\n return [\n {\n propertyKey: field.column,\n columnName,\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 return { name: columnName, type: columnObject.getSQLType() };\n });\n const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));\n\n const createManagedFields = getManagedFieldsForOperation(entry, \"create\");\n const updateManagedFields = getManagedFieldsForOperation(entry, \"update\");\n const createManagedFieldNames = new Set(createManagedFields.map((field) => field.columnName));\n const updateManagedFieldNames = new Set(updateManagedFields.map((field) => field.columnName));\n\n const allColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !createManagedFieldNames.has(column.name))\n .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)\n .join(\",\\n \");\n\n const nonPrimaryKeyColumnPairs = projectedColumns\n .map(({ column }) => column)\n .filter((column) => !primaryKeyColumnNames.has(column.name) && !updateManagedFieldNames.has(column.name))\n .map((column) => `('${toSqlLiteral(column.name)}', '${toSqlLiteral(column.getSQLType())}')`)\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(format('(x.p->>%L)::%s', col_name, col_type), ', ' ORDER BY col_name)\n INTO v_cols, v_vals\n FROM (VALUES\n ${allColumnPairs}\n ) AS col_types(col_name, col_type)\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 = (x.p->>%L)::%s', col_name, col_name, col_type), ', ' ORDER BY col_name)\n INTO v_set\n FROM (VALUES\n ${nonPrimaryKeyColumnPairs}\n ) AS col_types(col_name, col_type)\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\nfunction buildApplyFunctionBody(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): 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(options.functionSchema, APPLY_FUNCTION_NAME);\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`.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 * customWhere logic, which never enters the apply function (that shapes the read proxy, not writes).\n */\nexport function expectedApplyFingerprint(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): string {\n return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));\n}\n\nexport function buildPlpgsqlBatchFunctionDdl(\n registry: SyncTableRegistry,\n options: {\n functionSchema?: string;\n } = {},\n): string {\n const body = buildApplyFunctionBody(registry, options);\n const functionName = qualifyIdent(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: {\n functionSchema?: string;\n } = {},\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.\n const functionRef = options.functionSchema\n ? sql`${sql.identifier(options.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",
12
12
  "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",
13
13
  "// 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// `proxyElectricShapeRequest` and the mutation handler are plain `(Request) => Response` functions, so\n// 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",
14
14
  "import { NOW_MICROSECONDS_SQL_TEXT } from \"@pgxsinkit/contracts\";\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",
15
- "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\";\n\nimport { proxyElectricShapeRequest } from \"./electric-proxy\";\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): today's behavior — one query ensures/confirms the table, and logging is\n * disabled at runtime (with a warning) if it is absent. Preserves the documented degradation.\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 * preserve today's behavior exactly, so long-lived hosts need not set it; serverless / per-request\n * workers set `{ 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 a read-path Electric shape proxy that shares the\n * single `resolveAuthClaims` adapter with the write path (ADR-0003). Without it,\n * no shape proxy is registered.\n */\n electricUrl?: string;\n /** Path for the shape proxy route. Defaults to `/api/shape`. */\n shapeProxyPath?: string;\n /** Optional per-request extra params passed to customWhere/shared filters. */\n resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;\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 * preserve today's behavior. See {@link DeploymentProfile}.\n */\n deployment?: DeploymentProfile;\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. Additive; no behaviour change.\n */\n logTimings?: boolean;\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 const shapeProxyPath = options.shapeProxyPath ?? \"/api/shape\";\n\n // CORS mirrors the previous middleware scopes: everything under /api/*, the /mutations alias, and\n // the shape proxy path (which may be relocated outside /api/).\n const corsScopes: CorsScope[] = [{ prefix: \"/api/\" }, { exact: \"/mutations\" }];\n if (options.electricUrl) {\n corsScopes.push({ exact: shapeProxyPath });\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 (and the /mutations alias).\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 );\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 read-path shape proxy shares the same resolveAuthClaims adapter, so read and\n // write authorization can never diverge (ADR-0003).\n if (options.electricUrl) {\n const electricUrl = options.electricUrl;\n const resolveAuthClaims = options.resolveAuthClaims;\n const resolveShapeParams = options.resolveShapeParams;\n router.get(shapeProxyPath, async (request) => {\n const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;\n const extraParams = resolveShapeParams?.(request);\n return proxyElectricShapeRequest(request, claims, {\n registry: options.registry,\n electricUrl,\n ...(extraParams ? { extraParams } : {}),\n ...(options.logTimings ? { logTimings: true } : {}),\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 { renderPgxsinkitUtilitiesMigration } from \"./migrations/utilities\";\nexport { ensureOperationsLogSchema, operationsLogRegclassTarget } from \"./operations-log/ddl\";\nexport { operationsLogTable } from \"./operations-log/schema\";\nexport { proxyElectricShapeRequest } from \"./electric-proxy\";\nexport type { ElectricProxyOptions } from \"./electric-proxy\";\nexport { readSqlState } from \"./sql-state\";\n"
15
+ "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\";\n\nimport { proxyElectricShapeRequest } from \"./electric-proxy\";\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 a read-path Electric shape proxy that shares the\n * single `resolveAuthClaims` adapter with the write path (ADR-0003). Without it,\n * no shape proxy is registered.\n */\n electricUrl?: string;\n /** Path for the shape proxy route. Defaults to `/api/shape`. */\n shapeProxyPath?: string;\n /** Optional per-request extra params passed to customWhere/shared filters. */\n resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;\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 * 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\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 const shapeProxyPath = options.shapeProxyPath ?? \"/api/shape\";\n\n // CORS covers the canonical /api/* routes and the shape proxy path when it is relocated outside /api/.\n const corsScopes: CorsScope[] = [{ prefix: \"/api/\" }];\n if (options.electricUrl) {\n corsScopes.push({ exact: shapeProxyPath });\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 );\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 read-path shape proxy shares the same resolveAuthClaims adapter, so read and\n // write authorization can never diverge (ADR-0003).\n if (options.electricUrl) {\n const electricUrl = options.electricUrl;\n const resolveAuthClaims = options.resolveAuthClaims;\n const resolveShapeParams = options.resolveShapeParams;\n router.get(shapeProxyPath, async (request) => {\n const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;\n const extraParams = resolveShapeParams?.(request);\n return proxyElectricShapeRequest(request, claims, {\n registry: options.registry,\n electricUrl,\n ...(extraParams ? { extraParams } : {}),\n ...(options.logTimings ? { logTimings: true } : {}),\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 { renderPgxsinkitUtilitiesMigration } from \"./migrations/utilities\";\nexport { ensureOperationsLogSchema, operationsLogRegclassTarget } from \"./operations-log/ddl\";\nexport { operationsLogTable } from \"./operations-log/schema\";\nexport { proxyElectricShapeRequest } from \"./electric-proxy\";\nexport type { ElectricProxyOptions } from \"./electric-proxy\";\nexport { readSqlState } from \"./sql-state\";\n"
16
16
  ],
17
- "mappings": ";;AAAA;AAAA;AAAA;AAAA;;;ACcO,SAAS,iBAAiB,CAAC,SAAkB,SAA2C;AAAA,EAC7F,MAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ;AAAA,EAC3C,IAAI,CAAC,QAAQ;AAAA,IACX,OAAO;AAAA,EACT;AAAA,EACA,OAAO,QAAQ,SAAS,GAAG,KAAK,QAAQ,SAAS,MAAM,IAAI,SAAS;AAAA;;;AD+BtE,IAAM,UAAU,MAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAWzF,IAAM,2BAA2B;AAUjC,eAAsB,yBAAyB,CAC7C,SACA,QACA,SACmB;AAAA,EACnB,IAAI,QAAQ,QAAQ,QAAQ,WAAW,WAAW;AAAA,IAChD,OAAO,sBAAsB,SAAS,QAAQ,IAAI;AAAA,EACpD;AAAA,EACA,MAAM,SAAuC,QAAQ,aAAa,EAAE,YAAY,GAAG,gBAAgB,EAAE,IAAI;AAAA,EACzG,MAAM,QAAQ,SAAS,QAAQ,IAAI;AAAA,EACnC,MAAM,WAAW,MAAM,oBAAoB,SAAS,QAAQ,SAAS,MAAM;AAAA,EAC3E,MAAM,gBAAgB,QAAQ,OAAO,wBAAwB,SAAS,UAAU,QAAQ,IAAI,IAAI;AAAA,EAChG,IAAI,QAAQ;AAAA,IACV,eAAe,SAAS,QAAQ,QAAQ,IAAI,KAAK;AAAA,EACnD;AAAA,EACA,OAAO;AAAA;AAIT,SAAS,cAAc,CAAC,SAAkB,QAA0B,SAAuB;AAAA,EACzF,MAAM,SAAS,IAAI,IAAI,QAAQ,G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