@pgxsinkit/contracts 0.2.6 → 0.3.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
@@ -1,25 +1,27 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/apply-strategy.ts", "../src/common.ts", "../src/config.ts", "../src/convergence-model.ts", "../src/registry.ts", "../src/event-stream.ts", "../src/sql-identifier.ts", "../src/events.ts", "../src/fingerprint.ts", "../src/registry-diff.ts", "../src/registry-invariant.ts", "../src/mutation.ts", "../src/projection.ts", "../src/sql-defaults.ts", "../src/sql-role-guard.ts", "../src/supabase-rls.ts"],
3
+ "sources": ["../src/apply-strategy.ts", "../src/common.ts", "../src/config.ts", "../src/predicate.ts", "../src/convergence-model.ts", "../src/registry.ts", "../src/event-stream.ts", "../src/sql-identifier.ts", "../src/events.ts", "../src/fingerprint.ts", "../src/registry-diff.ts", "../src/registry-invariant.ts", "../src/mutation.ts", "../src/projection.ts", "../src/sql-defaults.ts", "../src/stream-envelope.ts", "../src/sql-role-guard.ts", "../src/supabase-rls.ts"],
4
4
  "sourcesContent": [
5
5
  "/**\n * Static, type-driven read-path apply ladder (ADR-0009 decision 3).\n *\n * We own the registry's column types ahead of time and only ever target the latest PGlite, so the\n * bulk-insert strategy for a synced table is chosen **once, statically** from its column types —\n * never by probing `information_schema` at runtime. This module is the pure, dependency-free core\n * (no registry, no Drizzle import) so it stays in the fast unit lane; {@link deriveSyncColumnTypes}\n * in `registry.ts` bridges a `SyncTableEntry`'s Drizzle columns into {@link SyncColumnType}s.\n */\n\n/** The bulk-insert path the engine uses for a fresh subscription's initial backfill. */\nexport type ApplyStrategy = \"copy\" | \"json\" | \"insert\";\n\n/** Resolved column type descriptor for the apply ladder — derived from the registry, not the DB. */\nexport interface SyncColumnType {\n /** SQL column name (not the Drizzle property key). */\n name: string;\n /**\n * The column's base SQL type from Drizzle's `getSQLType()` (e.g. `\"uuid\"`, `\"text\"`, `\"jsonb\"`,\n * `\"bigint\"`, `\"timestamp with time zone\"`). Array-ness is carried separately in {@link isArray};\n * this string is the element/base type and is usable verbatim as a `json_to_recordset` cast type\n * (with `[]` appended when `isArray`).\n */\n sqlType: string;\n /** True when the column is an array of any dimension. */\n isArray: boolean;\n /**\n * True when the column is a Drizzle `pgEnum` column. An enum's {@link sqlType} is its custom type NAME\n * (not a base type), so it is not in {@link COPY_SAFE_BASE_TYPES} — but enum labels round-trip\n * losslessly through both the COPY text format and a `json_to_recordset` cast (whose cast type is the\n * enum type name), so an enum column is COPY-safe / JSON-safe. This flag carries that positively rather\n * than trying to whitelist every enum type name. When true, {@link sqlType} is the enum type name,\n * usable as a cast type once the applier identifier-quotes (and schema-qualifies) it.\n */\n isEnum: boolean;\n}\n\n/**\n * Postgres scalar types whose JS→CSV-text rendering is unambiguous, so PGlite `COPY ... FROM`\n * round-trips them losslessly. Deliberately **conservative** (ADR-0009 decision 3): never add a\n * type here unless `COPY` truly handles it. Notably EXCLUDES timestamps/dates (format nuances),\n * `numeric` (precision/format), `bytea`, `interval`, `json`/`jsonb`, and arrays — those route to the\n * `json` tier (if json-representable) or the always-correct `insert` floor. Enums are NOT listed by\n * type name (each is a distinct custom type) but ARE COPY-safe — carried via {@link SyncColumnType.isEnum}\n * rather than this base-type set, since their labels round-trip through COPY text losslessly.\n */\nconst COPY_SAFE_BASE_TYPES = new Set<string>([\n \"text\",\n \"varchar\",\n \"character varying\",\n \"char\",\n \"character\",\n \"bpchar\",\n \"uuid\",\n \"boolean\",\n \"bool\",\n \"smallint\",\n \"int2\",\n \"integer\",\n \"int\",\n \"int4\",\n \"bigint\",\n \"int8\",\n \"real\",\n \"float4\",\n \"double precision\",\n \"float8\",\n]);\n\n/**\n * Normalises a Drizzle `getSQLType()` string to a bare base type for whitelist comparison: strips\n * array markers and type arguments (`varchar(255)` → `varchar`, `numeric(10, 2)` → `numeric`),\n * collapses whitespace, and lowercases.\n */\nfunction normalizeBaseType(sqlType: string): string {\n return sqlType\n .replace(/\\[\\]/g, \"\")\n .replace(/\\(.*\\)/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .toLowerCase();\n}\n\nfunction isCopySafe(column: SyncColumnType): boolean {\n if (column.isArray) {\n return false;\n }\n // Enum labels are plain text on the COPY wire; PGlite's COPY input casts them into the enum type\n // losslessly, so an enum column is COPY-safe even though its `sqlType` (the enum name) is not a base type.\n if (column.isEnum) {\n return true;\n }\n return COPY_SAFE_BASE_TYPES.has(normalizeBaseType(column.sqlType));\n}\n\n/**\n * `json_to_recordset` extends the COPY-safe set with arrays, `json`, and `jsonb` — viable now that\n * the latest PGlite round-trips bigint and bigint[] correctly (ADR-0009 decision 3).\n */\nfunction isJsonSafe(column: SyncColumnType): boolean {\n if (isCopySafe(column)) {\n return true;\n }\n if (column.isArray) {\n return true;\n }\n const base = normalizeBaseType(column.sqlType);\n return base === \"json\" || base === \"jsonb\";\n}\n\n/**\n * Chooses the bulk-insert strategy for a table from its column types (ADR-0009 decision 3):\n * - every column COPY-safe → `copy`;\n * - else every column COPY-safe ∪ array/json/jsonb → `json`;\n * - else → `insert` (the always-correct floor for anything not positively whitelisted).\n *\n * Pure and total: an empty column list falls to `insert`.\n */\nexport function classifyApplyStrategy(columns: readonly SyncColumnType[]): ApplyStrategy {\n if (columns.length === 0) {\n return \"insert\";\n }\n\n let allCopySafe = true;\n let allJsonSafe = true;\n\n for (const column of columns) {\n if (!isCopySafe(column)) {\n allCopySafe = false;\n }\n if (!isJsonSafe(column)) {\n allJsonSafe = false;\n }\n }\n\n if (allCopySafe) {\n return \"copy\";\n }\n if (allJsonSafe) {\n return \"json\";\n }\n return \"insert\";\n}\n",
6
6
  "import { z } from \"zod\";\n\nexport const unixMicrosecondsSchema = z.string().regex(/^[0-9]+$/);\n",
7
- "import { sql, type AnyColumn, type SQL } from \"drizzle-orm\";\nimport { PgDialect } from \"drizzle-orm/pg-core\";\nimport { z } from \"zod\";\n\nconst pgDialect = new PgDialect();\n\nexport type TableMode = \"readonly\" | \"writeonly\" | \"readwrite\";\n\n/**\n * The per-writable-table Conflict policy (ADR-0015): what happens to a **stale** write — one whose\n * Base server version is behind the row's current Server version at apply (an external write\n * interleaved). It is a **required** declaration on every writable table; there is no silent default\n * (registry validation rejects an undeclared writable table — the third hard-require). v1:\n *\n * - `last-write-wins` — apply the stale write anyway. A required, named declaration: the toolkit never\n * silently clobbers under an unspecified default, so choosing this is an explicit acceptance of the\n * stale-overwrite semantics.\n * - `reject-if-stale` — do not apply; surface the conflict so the user's edit is kept (the optimistic\n * Overlay stays, marked conflicted) and resolved as a new write.\n *\n * `field-merge` (apply only the changed fields over the current row) and `custom-resolver` (a client\n * re-resolution protocol) are reserved values for future policies — declared here so the policy surface\n * names its full intended range.\n */\nexport type ConflictPolicy = \"last-write-wins\" | \"reject-if-stale\";\n\n/** The Conflict policy values accepted in v1 (ADR-0015). Source of truth for registry validation. */\nexport const CONFLICT_POLICIES = [\"last-write-wins\", \"reject-if-stale\"] as const satisfies readonly ConflictPolicy[];\n\n/** Type guard: is `value` one of the v1 {@link ConflictPolicy} values? */\nexport function isConflictPolicy(value: unknown): value is ConflictPolicy {\n return typeof value === \"string\" && (CONFLICT_POLICIES as readonly string[]).includes(value);\n}\n\n/**\n * Subscription timing for a synced table (ADR-0021): **when** its Electric shape subscribes.\n *\n * - `eager` (default) — subscribed in the boot set, as today.\n * - `lazy` — excluded from boot; subscribed on first query-reference. With `persistent` retention,\n * first use is a one-time ignition that promotes the table to a normal eager table for subsequent\n * sessions; with `ephemeral` retention it is session-scoped.\n *\n * A property of the **consistency group**: every table sharing a `consistencyGroup` must agree, since\n * a group commits atomically on one `MultiShapeStream` and cannot be partly lazy (ADR-0021 §4).\n */\nexport type SubscriptionTiming = \"eager\" | \"lazy\";\n\n/** The {@link SubscriptionTiming} values. Source of truth for registry validation. */\nexport const SUBSCRIPTION_TIMINGS = [\"eager\", \"lazy\"] as const satisfies readonly SubscriptionTiming[];\n\n/** Type guard: is `value` a {@link SubscriptionTiming}? */\nexport function isSubscriptionTiming(value: unknown): value is SubscriptionTiming {\n return typeof value === \"string\" && (SUBSCRIPTION_TIMINGS as readonly string[]).includes(value);\n}\n\n/**\n * Retention for a synced table (ADR-0021): **whether** its local copy is durable.\n *\n * - `persistent` (default) — the durable PGlite backend with a resumable subscription-state.\n * - `ephemeral` — the table's whole per-table local cluster (read cache, overlay, journal, sequence,\n * views, reconcile trigger/function) is emitted as `TEMP`, so reads **and** writes leave no durable\n * trace. Consequence: no durable offline write queue — pair a must-not-lose write with a pessimistic\n * flush (ADR-0022).\n *\n * Like {@link SubscriptionTiming}, a property of the consistency group: every table in a group agrees.\n */\nexport type Retention = \"persistent\" | \"ephemeral\";\n\n/** The {@link Retention} values. Source of truth for registry validation. */\nexport const RETENTIONS = [\"persistent\", \"ephemeral\"] as const satisfies readonly Retention[];\n\n/** Type guard: is `value` a {@link Retention}? */\nexport function isRetention(value: unknown): value is Retention {\n return typeof value === \"string\" && (RETENTIONS as readonly string[]).includes(value);\n}\n\n/**\n * Write-mode (ADR-0022): **how** a write reaches the server — the write-side twin of {@link Retention}.\n *\n * - `optimistic` (default) — the write enters the local journal with an optimistic overlay, the UI updates\n * immediately, and the convergence loop flushes the journal as one all-or-nothing batch; the canonical\n * row returns via the sync echo. The path that has always existed.\n * - `pessimistic` — the write is **server-authoritative**: it flush-routes to an authoritative endpoint that\n * applies it in its own isolated, serialised transaction and returns a per-mutation result (accepted, or\n * rejected-with-typed-reason) **before** the UI shows success. For invariants the client cannot evaluate\n * locally — a capacity/quota/uniqueness gate enforced by a server-side rule.\n *\n * Write-mode is a property of an atomic **write-unit**, not a single table (ADR-0022 §1): a unit is uniformly\n * one mode. The *static* write-unit is the **consistency group** — so, like {@link SubscriptionTiming} and\n * {@link Retention}, every table sharing a `consistencyGroup` must agree (validated). A *dynamic* override is\n * the imperative `transaction({ mode })` block, which scopes a mode to an ad-hoc set of mutations.\n */\nexport type WriteMode = \"optimistic\" | \"pessimistic\";\n\n/** The {@link WriteMode} values. Source of truth for registry validation. */\nexport const WRITE_MODES = [\"optimistic\", \"pessimistic\"] as const satisfies readonly WriteMode[];\n\n/** Type guard: is `value` a {@link WriteMode}? */\nexport function isWriteMode(value: unknown): value is WriteMode {\n return typeof value === \"string\" && (WRITE_MODES as readonly string[]).includes(value);\n}\n\n/**\n * The registry-declared BROWSER storage backend (ADR-0049 decision 1). `opfs` (default) is the store's\n * normal boot on every platform — the capability machinery selects the `opfs-repacked` VFS where a home\n * can hold sync-access handles, and falls back to in-SharedWorker `idbfs` when no home can. `idbfs` is the\n * one way to opt out of that machinery entirely: no probe, no election, the engine boots on idb.\n *\n * Scopes the BROWSER store only. Environment resolution is orthogonal and unchanged (ADR-0049 decision 14):\n * a Node mint stays `file://` and the export clone stays memory regardless of this declaration.\n */\nexport type StorageBackend = \"opfs\" | \"idbfs\";\n\n/** The {@link StorageBackend} values. Source of truth for {@link SyncStorageDeclaration} validation. */\nexport const STORAGE_BACKENDS = [\"opfs\", \"idbfs\"] as const satisfies readonly StorageBackend[];\n\n/** Type guard: is `value` a {@link StorageBackend}? */\nexport function isStorageBackend(value: unknown): value is StorageBackend {\n return typeof value === \"string\" && (STORAGE_BACKENDS as readonly string[]).includes(value);\n}\n\n/**\n * The registry-declared durability mode (ADR-0047; ADR-0049 decision 9). `relaxed` (default) returns a\n * write before its durable flush and schedules the flush asynchronously — the local-first \"instant write\"\n * the toolkit exists to deliver. `strict` reinstates the synchronous flush boundary (a ~50ms+ per-statement\n * floor on idb; cheap on `opfs-repacked`). It binds EVERY open of EVERY store minted from the registry, so\n * no minting/open site takes a durability option to contradict it, and an opfs→idbfs capability fallback\n * keeps the declared mode.\n */\nexport type StorageDurability = \"relaxed\" | \"strict\";\n\n/** The {@link StorageDurability} values. Source of truth for {@link SyncStorageDeclaration} validation. */\nexport const STORAGE_DURABILITIES = [\"relaxed\", \"strict\"] as const satisfies readonly StorageDurability[];\n\n/** Type guard: is `value` a {@link StorageDurability}? */\nexport function isStorageDurability(value: unknown): value is StorageDurability {\n return typeof value === \"string\" && (STORAGE_DURABILITIES as readonly string[]).includes(value);\n}\n\n/**\n * The registry's storage contract (ADR-0049 decision 1, ADR-0047). Storage is PART OF THE DATA CONTRACT:\n * whether losing the last not-yet-flushed action is acceptable, and whether OPFS may be used at all, is\n * decided by what the data IS — so it is declared once on the registry, not at any minting/open site.\n *\n * - {@link StorageDurability durability} defaults to `\"relaxed\"` and binds every toolkit-minted open of\n * every store the registry mints (its own boot AND the provision/spare path). No open-site option exists\n * to contradict it; a capability fallback keeps the declared mode. A no-op on `memory` clones.\n * - {@link StorageBackend backend} defaults to `\"opfs\"` and scopes the BROWSER store only; Node/`file` and\n * `memory` clones are unaffected. `\"idbfs\"` opts the store out of the capability/election machinery.\n */\nexport interface SyncStorageDeclaration {\n backend?: StorageBackend;\n durability?: StorageDurability;\n}\n\n/**\n * A {@link SyncStorageDeclaration} with every field resolved (ADR-0050) — the store's BOUND declaration.\n * Produced once per store by {@link resolveStorageDeclaration} and immutable for the store's lifetime: a\n * preference change mints a fresh store under a fresh path, never rebinds an existing one.\n */\nexport interface ResolvedStorageDeclaration {\n backend: StorageBackend;\n durability: StorageDurability;\n}\n\n/**\n * A storage declaration was refused (ADR-0050): two sources explicitly disagree on a field, or a later\n * declaration explicitly contradicts the store's bound declaration. Never resolved silently — the store's\n * storage contract has exactly one value per field, and a disagreement means one side is wrong. The stable\n * `name` survives bridge serialization (`BridgeErrorWire.name`), so a tab can detect the refusal typed.\n */\nexport class StorageDeclarationRefusedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StorageDeclarationRefusedError\";\n }\n}\n\n/** One field's resolution: explicit-vs-explicit disagreement refuses; otherwise the explicit value, else the default. */\nfunction resolveDeclarationField<TValue>(\n field: keyof SyncStorageDeclaration,\n staticValue: TValue | undefined,\n wireValue: TValue | undefined,\n defaultValue: TValue,\n): TValue {\n if (staticValue !== undefined && wireValue !== undefined && staticValue !== wireValue) {\n throw new StorageDeclarationRefusedError(\n `storage declaration disagreement on \"${field}\": the registry-attached declaration says ` +\n `\"${String(staticValue)}\" but the wire declaration says \"${String(wireValue)}\" — a store's storage ` +\n `contract has one value per field; fix the declaring side (a preference change mints a fresh store, ` +\n `it never redeclares an existing one)`,\n );\n }\n return staticValue ?? wireValue ?? defaultValue;\n}\n\n/**\n * Resolve a store's storage declaration from its two sources (ADR-0050): the registry-attached STATIC\n * declaration (authoritative) and the tab's WIRE declaration (honoured only where the registry is silent).\n * Per field: an unset field is \"no opinion\" and can never conflict; both explicit and disagreeing is a\n * {@link StorageDeclarationRefusedError}; unresolved fields take the capability defaults\n * (`backend: \"opfs\"`, `durability: \"relaxed\"`).\n */\nexport function resolveStorageDeclaration(\n staticDeclaration: SyncStorageDeclaration | undefined,\n wireDeclaration: SyncStorageDeclaration | undefined,\n): ResolvedStorageDeclaration {\n return {\n backend: resolveDeclarationField(\"backend\", staticDeclaration?.backend, wireDeclaration?.backend, \"opfs\"),\n durability: resolveDeclarationField(\n \"durability\",\n staticDeclaration?.durability,\n wireDeclaration?.durability,\n \"relaxed\",\n ),\n };\n}\n\n/**\n * Check a LATER declaration against a store's bound resolution (ADR-0050): an unset or equal field is\n * idempotent; an explicit field disagreeing with the bound value is a {@link StorageDeclarationRefusedError}.\n * The bound declaration is immutable — first arrival binds, later arrivals only confirm.\n */\nexport function assertStorageDeclarationCompatible(\n bound: ResolvedStorageDeclaration,\n incoming: SyncStorageDeclaration | undefined,\n): void {\n if (incoming === undefined) return;\n for (const field of [\"backend\", \"durability\"] as const) {\n const value = incoming[field];\n if (value !== undefined && value !== bound[field]) {\n throw new StorageDeclarationRefusedError(\n `storage declaration disagreement on \"${field}\": the store is bound to \"${bound[field]}\" but a later ` +\n `declaration says \"${value}\" — a store's declaration is immutable; a preference change mints a ` +\n `fresh store under a fresh path`,\n );\n }\n }\n}\n\n/**\n * Minimal verified-JWT claim shape the sync layer understands. Providers may\n * attach arbitrary extra claims; those stay reachable through index access and\n * ownership claim paths (e.g. \"app_metadata.person_id\"). Parse decoded JWT\n * payloads with this schema at the auth boundary so the static type is honest.\n */\nexport const jwtClaimsSchema = z.looseObject({\n sub: z.string().optional(),\n app_metadata: z\n .looseObject({\n roles: z.array(z.string()).optional(),\n })\n .optional(),\n});\n\nexport type JwtClaims = z.infer<typeof jwtClaimsSchema>;\n\nexport interface PrimaryKeySpec {\n columns: string[];\n}\n\nexport interface ShapeSpec {\n tableName: string;\n shapeKey: string;\n /**\n * INTERNAL / resolved — the physical Postgres table this shape reads, when it differs from the\n * shape's own `tableName`. A read PROJECTION (`defineReadProjection`) sets it to the OWNING table's\n * name so several shapes can read one physical table under distinct `shapeKey`s; the engine resolves\n * an incoming request by `shapeKey` and consults this only on egress, to build the upstream Electric\n * `table` param. `attachSyncRegistrySchema` also fills/qualifies it for schema-bound registries.\n *\n * Not a consumer input — there is no valid reason to hand-set it (it can only be redundant with, or\n * wrong about, the table you are reading), so it is omitted from {@link ShapeSpecInput}. The\n * combinator derives it from the owner; `defineSyncTable` never sets it from input.\n */\n electricTable?: string;\n rowFilter?: RowFilterSpec;\n}\n\n/** Input variant of {@link ShapeSpec} where `tableName` and `shapeKey` are optional.\n * When omitted, both default to the top-level `tableName` of the `defineSyncTable` call.\n * `electricTable` is deliberately absent — it is a resolved/internal field, never a consumer input\n * (see {@link ShapeSpec.electricTable}); a read projection over an existing table is authored with\n * `defineReadProjection`, which derives it from the owner. */\nexport type ShapeSpecInput = Omit<ShapeSpec, \"tableName\" | \"shapeKey\" | \"electricTable\"> & {\n tableName?: string;\n shapeKey?: string;\n};\n\n/** Context available to a {@link RowTransform}: the verified claims and any extra runtime params. */\nexport interface RowTransformContext {\n claims: JwtClaims | null;\n params?: Record<string, unknown>;\n}\n\n/**\n * Per-row rewrite applied in the proxy response path (after the row filter, before\n * column omission). Receives a shape-log row's column map (keys are wire/column names)\n * and returns a possibly-rewritten one — letting the server strip a *sub-document* of a\n * jsonb column, or otherwise rewrite a value, *conditionally on row data*. This expresses\n * what a static, whole-column `omitColumns` cannot.\n *\n * It runs only in the proxy's per-response path: it never alters the local PGlite schema,\n * never changes the Electric shape URL, and so never pollutes Electric's shared shape\n * cache. Return the same `row` reference to signal \"no change\".\n */\nexport type RowTransform = (row: Record<string, unknown>, context: RowTransformContext) => Record<string, unknown>;\n\nexport interface ClientProjectionSpec {\n syncedTable?: string;\n overlayTable?: string;\n journalTable?: string;\n omitColumns?: readonly string[];\n localPrimaryKey?: PrimaryKeySpec;\n}\n\n/**\n * Server-side projection applied in the proxy response path. This is server\n * authority, not client shape — it never alters the local PGlite schema or the\n * Electric shape URL — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).\n */\nexport interface ServerProjectionSpec {\n /**\n * Optional per-row rewrite applied in the proxy response path. Runs before column\n * omission, so it may read a column (e.g. a control flag) that\n * `clientProjection.omitColumns` then removes from the client-visible row. See\n * {@link RowTransform}.\n */\n rowTransform?: RowTransform;\n}\n\nexport interface DeferrableConstraintSpec {\n constraintName: string;\n columns: string[];\n initiallyDeferred?: boolean;\n}\n\nexport type ManagedFieldApplyOn = \"create\" | \"update\";\n\n/**\n * How the applier stamps a server-managed column (it overrides any client-sent value — the client write\n * payload omits managed fields, and the apply function re-derives them under the verified request claims):\n *\n * - `nowMicroseconds` — `clock_timestamp()` microseconds, stamped via the canonical `pgxsinkit_clock_us()`\n * DB function (installed by the utilities migration). The audit/version columns (`created_at_us`,\n * `updated_at_us`); the `updated_at_us`-on-update field is the strictly-monotonic Server version (ADR-0010).\n * - `authClaim` — a value read from the **verified JWT claims** at a JSON {@link ManagedFieldSpec.claimPath}\n * (e.g. `[\"sub\"]` for the auth subject, or `[\"app_metadata\",\"person_id\"]` for an app-minted identity). This\n * is the single claim-stamping strategy: the old `authUid` is exactly `{ claimPath: [\"sub\"], cast: \"uuid\" }`,\n * so there is one mechanism, not a `sub`-only special case beside a general one.\n */\nexport type ManagedFieldStrategy = \"nowMicroseconds\" | \"authClaim\";\n\nexport interface ManagedFieldSpec {\n column: string;\n applyOn: ManagedFieldApplyOn[];\n strategy: ManagedFieldStrategy;\n /**\n * For `strategy: \"authClaim\"` only (required there, forbidden otherwise): the JSON path into the verified\n * request claims to stamp from — `[\"sub\"]`, `[\"app_metadata\", \"person_id\"]`, etc. Each segment must be a\n * plain identifier (`[A-Za-z_][A-Za-z0-9_]*`); it is emitted into the apply-function DDL as a `jsonb #>>`\n * text-array path, so it is never a value-injection surface.\n */\n claimPath?: string[];\n /**\n * Optional SQL cast for an `authClaim` value (`jsonb #>>` yields text). Defaults to the **target column's\n * own SQL type** (so a `uuid` column casts to `uuid` with no declaration needed). Override only to force a\n * different cast; must be a plain SQL type name.\n */\n cast?: string;\n}\n\nexport interface TableGovernanceSpec {\n deferrableConstraints?: DeferrableConstraintSpec[];\n managedFields?: ManagedFieldSpec[];\n}\n\nexport interface TableSpecInput {\n mode: TableMode;\n primaryKey: PrimaryKeySpec;\n shape?: ShapeSpec;\n clientProjection?: ClientProjectionSpec;\n governance?: TableGovernanceSpec;\n /**\n * Consistency group (ADR-0009 decision 2): tables sharing a group sync on one `MultiShapeStream`\n * and commit atomically at a shared LSN frontier. Absent → the table is its own singleton group.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` table is excluded from the boot\n * subscription set and subscribed on first query-reference. See {@link SubscriptionTiming}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021). Absent → `persistent`. An `ephemeral` table's whole local cluster is emitted\n * as `TEMP` — no durable trace. See {@link Retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022). Absent → `optimistic`. A `pessimistic` consistency group is a standing\n * server-authoritative write-unit whose writes flush-route to the authoritative endpoint. See\n * {@link WriteMode}.\n */\n writeMode?: WriteMode;\n}\n\nexport interface SyncConfigInput<TTables extends Record<string, TableSpecInput> = Record<string, TableSpecInput>> {\n electricUrl: string;\n localSchema?: string;\n tables: TTables;\n}\n\nexport function getLocalSyncPrimaryKey(source: {\n primaryKey: PrimaryKeySpec;\n clientProjection?: Pick<ClientProjectionSpec, \"localPrimaryKey\">;\n}) {\n return source.clientProjection?.localPrimaryKey ?? source.primaryKey;\n}\n\nexport function getLocalSyncPrimaryKeyColumns(source: {\n primaryKey: PrimaryKeySpec;\n clientProjection?: Pick<ClientProjectionSpec, \"localPrimaryKey\">;\n}) {\n return [...getLocalSyncPrimaryKey(source).columns];\n}\n\nexport interface RowFilterSpec {\n /**\n * The row filter: returns the Electric shape `where` for this request, or `null` to bypass\n * filtering (e.g. admin access). **Prefer returning a Drizzle `SQL` fragment** built from the\n * table's columns: reference each column through {@link c} (a bare, rename-safe identifier) and\n * embed request-derived values directly — they become **bound `$n` params**, never hand-escaped\n * literals. Enum columns must be cast to text (`${c(col)}::text = 'x'`) for Electric's grammar,\n * and subqueries must be self-contained (not correlated), since Electric needs plain column refs.\n *\n * Returning a raw **string** is the escape hatch for a predicate Drizzle can't express. SECURITY:\n * a string is interpolated verbatim into the `where` — it is NOT escaped, so any request-derived\n * value you embed must be escaped/validated (`escapeSqlLiteral`) inside this function, or it is a\n * SQL-injection vector. Reach for the string form only when the Drizzle fragment cannot express it.\n *\n * **Must be pure.** The proxy already calls this fresh on every shape request; the client also\n * *probes* it with empty claims (`{}`) to detect claims-dependence (ADR-0039 —\n * {@link isClaimsDependentRowFilter}). Do not memoize, mutate external state, or assume it runs once.\n */\n customWhere?: (claims: JwtClaims, params?: Record<string, unknown>) => string | SQL | null;\n /** Column projection for the shape URL (e.g. [\"id\", \"source_text\"]). */\n columns?: string[];\n /**\n * An opaque version tag for the part of this filter the fingerprint cannot see — the `customWhere`\n * body (you cannot hash a closure; only its *presence* is fingerprinted). Bump this (any new\n * string/number) whenever you change that logic so the fingerprint shifts and the local read cache\n * rebuilds + the shape subscription resets. Leaving it unchanged after a `customWhere`\n * authorization change would silently serve the stale shape.\n */\n revision?: string | number;\n}\n\n/**\n * A **bare** (table-unqualified) quoted identifier for a Drizzle column — `\"workspace_id\"`, never\n * `\"work_items\".\"workspace_id\"`. Electric's shape `where` grammar requires *plain* column references\n * (it rejects a qualified one with \"Expected a plain column reference\"), and Drizzle qualifies columns\n * by default — so reference columns through `c()` when authoring a `customWhere` Drizzle fragment. The\n * column object keeps the reference rename-safe and existence-checked at compile time; only the bare\n * name reaches the wire. Subqueries must stay self-contained (not correlated), since bare names then\n * resolve unambiguously to each FROM — a correlated subquery would need qualification Electric rejects.\n */\nexport function c(column: AnyColumn): SQL {\n return sql`${sql.identifier(column.name)}`;\n}\n\n/**\n * The deny-all row filter: a `customWhere` returns this to make **no** rows visible (e.g. an\n * unauthenticated request), the counterpart to returning `null` (which bypasses filtering — all rows\n * visible). It is a Drizzle `SQL` fragment (`false`), so it stays on the typed/parameterized path\n * with the rest of the filter rather than being a hand-written `\"1 = 0\"` string. `WHERE false`\n * matches nothing; Electric accepts it (verified) exactly as it accepts `1 = 0`.\n */\nexport const DENY_ALL: SQL = sql`false`;\n\n/**\n * Whether a row filter denies (or cannot serve) an unauthenticated caller — a *claims-dependent*\n * filter (ADR-0039). The client probes this at lazy-group activation: a group whose members probe\n * claims-dependent, activated with no auth token, opens an empty subscription by construction, so\n * the client warns.\n *\n * A filter is claims-dependent when its `customWhere`, evaluated with **empty claims** (`{}` —\n * exactly what the proxy passes for an unauthenticated request) and no params, either **throws** or\n * returns the {@link DENY_ALL} sentinel by **reference identity** (which every contracts helper —\n * {@link buildOwnershipShapeWhere} and friends — returns for a missing subject, and which is already\n * the documented deny-anonymous pattern). Any other result — `null` (no filtering), a string, or a\n * different `SQL` fragment — is not claims-dependent as far as this probe can tell.\n *\n * Requires `customWhere` to be pure (its contract; see {@link RowFilterSpec.customWhere}).\n */\nexport function isClaimsDependentRowFilter(filter: RowFilterSpec | undefined): boolean {\n if (!filter?.customWhere) {\n return false;\n }\n\n try {\n return filter.customWhere({}, undefined) === DENY_ALL;\n } catch {\n return true;\n }\n}\n\n/**\n * The ownership shape `where` — the read-path mirror of an owner-column RLS policy: rows whose owner\n * column equals the caller's subject, {@link DENY_ALL} for an unauthenticated caller. Takes the real\n * Drizzle owner column (bare via {@link c}, rename-safe); the subject rides as a typed interpolation —\n * a bound param through `buildRowFilterShape`, or a drizzle-escaped literal when a proxy renders it\n * inline for a shape URL.\n */\nexport function buildOwnershipShapeWhere(ownerColumn: AnyColumn, subject: string | null | undefined): SQL {\n return subject == null || subject === \"\" ? DENY_ALL : sql`${c(ownerColumn)} = ${subject}`;\n}\n\n/** The parameterized shape filter the proxy sends to Electric: a `where` and its positional params. */\nexport interface RowFilterShape {\n where: string;\n params: string[];\n}\n\n/**\n * The shape filter the proxy sends to Electric: the `where` plus its positional `params` (`$1`, `$2`,\n * …). A `customWhere` returning a Drizzle `SQL` fragment is serialized here, so request-derived values\n * become **bound params** — never hand-escaped literals; a string `customWhere` is the raw escape\n * hatch (no params). Returns `null` when there is no filter (all rows visible).\n */\nexport function buildRowFilterShape(\n filter: RowFilterSpec,\n claims: JwtClaims | null,\n params?: Record<string, unknown>,\n): RowFilterShape | null {\n const custom = filter.customWhere?.(claims ?? {}, params);\n\n if (custom == null) {\n return null;\n }\n\n if (typeof custom === \"string\") {\n return custom ? { where: custom, params: [] } : null;\n }\n\n const compiled = pgDialect.sqlToQuery(custom);\n return { where: compiled.sql, params: compiled.params.map((value) => String(value)) };\n}\n",
8
- "import { type AnyPgTable, getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { resolveServerVersionColumnName, type SyncTableEntry } from \"./registry\";\nimport { quoteIdentifier } from \"./sql-identifier\";\n\n/**\n * The Convergence model (ADR-0011): the single owner of *how* local optimistic state converges to\n * server state. It owns the shared barrier predicate, the per-table sync-state **view** generator,\n * and the event-model spec below. Read sync (the Sync applier) and write sync (the mutation runtime)\n * remain the two edges with their own transaction paths, but neither independently decides whether an\n * entity is resolved — this module is the one resolution authority.\n *\n * Distinct from the convergence *driver* (`convergence.ts`, ADR-0005), which schedules *when* to\n * converge. This module defines *how* an entity resolves.\n */\n\n/**\n * The Convergence barrier predicate (ADR-0010): an acked create/update is resolved only once the\n * synced echo's Server version has reached the write's acked version. Emitted identically by the\n * reconcile trigger (schema.ts), `reconcileTable` (mutation.ts), **and** the per-table sync-state\n * view (decision 4) — one rule, three consumers, no drift (ADR-0004).\n *\n * `syncedAlias` is the synced-side reference (a table alias, or `NEW` inside the trigger);\n * `journalAlias` qualifies the journal's `server_updated_at_us` (omit it where the journal is the\n * unaliased target of the `DELETE`).\n */\nexport function buildOverlayResolutionBarrier<TTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable>,\n options: { syncedAlias: string; journalAlias?: string },\n): string {\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n\n if (!serverVersionColumn) {\n throw new Error(\n `writable table ${getTableConfig(entry.table).name} has no Server version; cannot build the convergence barrier (ADR-0010)`,\n );\n }\n\n const journalRef = options.journalAlias ? `${options.journalAlias}.server_updated_at_us` : \"server_updated_at_us\";\n return `${journalRef} <= ${options.syncedAlias}.${quoteIdentifier(serverVersionColumn)}`;\n}\n\n/**\n * The qualified object names the sync-state view is generated over. The synced read cache is\n * droppable (ADR-0006); overlay + journal are the authority. The view joins all three but stores\n * nothing — it is a derived projection (ADR-0011 decision 2).\n */\nexport interface SyncStateViewProjection {\n /** Qualified synced read-cache table. */\n syncedTable: string;\n /** Qualified overlay (optimistic intent) table. */\n overlayTable: string;\n /** Qualified mutation-journal table. */\n journalTable: string;\n}\n\n/**\n * Generate the per-writable-table `<table>_sync_state` **view** (ADR-0011 decision 2): a derived\n * projection — never a stored copy — over synced + overlay + journal that answers \"what is this\n * entity's convergence state?\" with one authoritative, queryable row per entity that has local\n * activity (an overlay or journal row). Keyed on the **real PK columns**, never a generic\n * `entity_key_json` (decision 2).\n *\n * Columns:\n * - `observed_server_version` — the synced row's Server version (NULL when no echo has landed).\n * - `acked_server_version` — the highest Server version the server assigned to our acked writes.\n * - `pending_count` — journal rows still owed to the server (pending/sending/failed).\n * - `has_acked_unobserved_write` — an acked create/update whose echo has not yet caught up. Derived\n * from the **same** {@link buildOverlayResolutionBarrier} predicate the resolver uses (decision 4),\n * so what the UI shows can never drift from what the resolver does.\n * - `local_delete_pending` — an optimistic delete is staged in the overlay.\n * - `conflict_state` — the reason a `conflicted` (stale, reject-if-stale) write was declined, or NULL\n * when the entity has no conflicted mutation (ADR-0015). Surfaced from the journal's\n * `conflict_reason`, scoped to `status = 'conflicted'` so a stale failure reason never leaks in.\n * - `quarantined_count` — terminal local writes the server permanently rejected (ADR-0006): a poison\n * mutation named in a batch rejection, or one that exhausted the attempt cap. Quarantine blocks\n * sync and *keeps* the optimistic overlay, so without this the view would show an entity with\n * `pending_count = 0` and `conflict_state = NULL` yet still carrying un-converged local intent.\n * - `quarantine_state` — the `last_error` of a quarantined write (the rejection reason), or NULL when\n * the entity has none. The reason counterpart to `quarantined_count`, mirroring `conflict_state`.\n *\n * Note `pending_count` is the *retryable* owed set (pending/sending/failed); a quarantined write is\n * terminal, counted separately so a blocked write is never mistaken for one still in flight.\n *\n * The Read model stays lean (it already carries `overlay_kind`); an app that wants per-row\n * convergence status joins this view on the PK.\n */\nexport function buildSyncStateView<TTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable>,\n projection: SyncStateViewProjection,\n): string {\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n\n if (!serverVersionColumn) {\n throw new Error(\n `writable table ${getTableConfig(entry.table).name} has no Server version; cannot build the sync-state view (ADR-0011)`,\n );\n }\n\n const pkColumns = [...entry.primaryKey.columns];\n const quotedVersion = quoteIdentifier(serverVersionColumn);\n const keyColumnList = pkColumns.map((column) => quoteIdentifier(column)).join(\", \");\n const keySelectList = pkColumns.map((column) => `k.${quoteIdentifier(column)}`).join(\",\\n \");\n\n const pkEquality = (left: string, right: string) =>\n pkColumns.map((column) => `${left}.${quoteIdentifier(column)} = ${right}.${quoteIdentifier(column)}`).join(\" AND \");\n\n // Decision 4: the SAME barrier the resolver's journal-clear DELETE uses. The view asks whether an\n // acked write is *not yet* resolved (`(barrier) IS NOT TRUE`) — NULL (no synced row) counts as\n // unobserved, exactly the create-with-no-echo case. One predicate string, two consumers.\n const barrier = buildOverlayResolutionBarrier(entry, { syncedAlias: \"synced\", journalAlias: \"journal\" });\n\n return [\n `SELECT`,\n ` ${keySelectList},`,\n ` synced.${quotedVersion} AS observed_server_version,`,\n ` j.acked_server_version,`,\n ` COALESCE(j.pending_count, 0) AS pending_count,`,\n ` COALESCE(j.has_acked_unobserved_write, FALSE) AS has_acked_unobserved_write,`,\n ` COALESCE(o.local_delete_pending, FALSE) AS local_delete_pending,`,\n ` j.conflict_state,`,\n ` COALESCE(j.quarantined_count, 0) AS quarantined_count,`,\n ` j.quarantine_state`,\n `FROM (`,\n ` SELECT DISTINCT ${keyColumnList} FROM ${projection.journalTable}`,\n ` UNION`,\n ` SELECT DISTINCT ${keyColumnList} FROM ${projection.overlayTable}`,\n `) AS k`,\n `LEFT JOIN ${projection.syncedTable} AS synced ON ${pkEquality(\"synced\", \"k\")}`,\n `LEFT JOIN LATERAL (`,\n ` SELECT`,\n ` MAX(journal.server_updated_at_us) FILTER (WHERE journal.status = 'acked') AS acked_server_version,`,\n ` COUNT(*) FILTER (WHERE journal.status IN ('pending', 'sending', 'failed')) AS pending_count,`,\n ` COALESCE(bool_or(`,\n ` journal.status = 'acked'`,\n ` AND journal.mutation_kind <> 'delete'`,\n ` AND journal.server_updated_at_us IS NOT NULL`,\n ` AND (${barrier}) IS NOT TRUE`,\n ` ), FALSE) AS has_acked_unobserved_write,`,\n ` MAX(journal.conflict_reason) FILTER (WHERE journal.status = 'conflicted') AS conflict_state,`,\n ` COUNT(*) FILTER (WHERE journal.status = 'quarantined') AS quarantined_count,`,\n ` MAX(journal.last_error) FILTER (WHERE journal.status = 'quarantined') AS quarantine_state`,\n ` FROM ${projection.journalTable} AS journal`,\n ` WHERE ${pkEquality(\"journal\", \"k\")}`,\n `) AS j ON TRUE`,\n `LEFT JOIN LATERAL (`,\n ` SELECT bool_or(overlay.overlay_kind = 'pending_delete') AS local_delete_pending`,\n ` FROM ${projection.overlayTable} AS overlay`,\n ` WHERE ${pkEquality(\"overlay\", \"k\")}`,\n `) AS o ON TRUE`,\n ].join(\"\\n\");\n}\n\n/**\n * The event model the Convergence model implements (ADR-0011). The per-entity convergence state is\n * **derived** from synced + overlay + journal — never a mutated row — so this table is the spec the\n * derivation answers to, not a state machine that is stepped. Exported so a test can assert the\n * implemented derivation covers every event.\n */\nexport const CONVERGENCE_EVENTS = [\n {\n event: \"local create/update/delete enqueued\",\n effect: \"overlay upserted; a journal mutation appended (records base server version for ADR-0015)\",\n },\n { event: \"mutation sent\", effect: \"journal row → sending\" },\n {\n event: \"mutation acked\",\n effect:\n \"journal row → acked, server_updated_at_us stamped; entity shows acked_unobserved until the echo catches up\",\n },\n {\n event: \"Electric insert/update observed\",\n effect: \"synced row applied; the barrier predicate runs; resolved entities clear overlay + acked journal\",\n },\n {\n event: \"Electric delete observed\",\n effect: \"resolved by synced-row absence (deletes carry no Server version — ADR-0010)\",\n },\n { event: \"resolution\", effect: \"clear overlay/journal only through the shared barrier predicate (decision 4)\" },\n { event: \"conflict detected\", effect: \"conflict_state recorded on the journal row (ADR-0015); surfaced in the view\" },\n {\n event: \"mutation quarantined\",\n effect:\n \"journal row → quarantined (terminal, ADR-0006), overlay kept; surfaced as quarantined_count/quarantine_state\",\n },\n {\n event: \"shape must-refetch\",\n effect: \"subscription reset + re-stream; affected entity state re-derives from the fresh synced rows\",\n },\n] as const;\n",
9
- "import type { ColumnBuilderBase, InferInsertModel, InferSelectModel } from \"drizzle-orm\";\nimport {\n bigint,\n getTableConfig,\n pgTable,\n pgView,\n primaryKey as pgPrimaryKey,\n PrimaryKeyBuilder,\n type AnyPgColumn,\n type AnyPgTable,\n type PgBigInt64Builder,\n type PgBuildColumns,\n type PgBuildExtraConfigColumns,\n type PgPolicy,\n type PgTableExtraConfigValue,\n type PgTableWithColumns,\n type PgVarcharBuilder,\n type PgView,\n type PgViewWithSelection,\n type SetNotNull,\n} from \"drizzle-orm/pg-core\";\nimport type { pgSchema } from \"drizzle-orm/pg-core\";\nimport { varchar } from \"drizzle-orm/pg-core\";\nimport type { ExtractTablesWithRelations } from \"drizzle-orm/relations\";\nimport { getColumns } from \"drizzle-orm/utils\";\n\nimport { type ApplyStrategy, classifyApplyStrategy, type SyncColumnType } from \"./apply-strategy\";\nimport {\n CONFLICT_POLICIES,\n isConflictPolicy,\n isRetention,\n isStorageBackend,\n isStorageDurability,\n isSubscriptionTiming,\n isWriteMode,\n RETENTIONS,\n STORAGE_BACKENDS,\n STORAGE_DURABILITIES,\n SUBSCRIPTION_TIMINGS,\n WRITE_MODES,\n type ClientProjectionSpec,\n type ConflictPolicy,\n type DeferrableConstraintSpec,\n type ManagedFieldApplyOn,\n type ManagedFieldSpec,\n type ManagedFieldStrategy,\n type PrimaryKeySpec,\n type Retention,\n type RowFilterSpec,\n type ServerProjectionSpec,\n type ShapeSpec,\n type ShapeSpecInput,\n type SubscriptionTiming,\n type SyncStorageDeclaration,\n type TableGovernanceSpec as TableGovernanceSpecBase,\n type TableMode,\n type WriteMode,\n} from \"./config\";\nimport {\n EVENT_STREAM_NAME_MAX_LENGTH,\n EVENT_STREAM_NAME_PATTERN,\n EVENT_STREAM_QUEUE_PREFIX,\n hasNonStrictObjectRoot,\n isZodSchema,\n type EventStreamRegistry,\n} from \"./event-stream\";\n\ntype PgSchemaType = ReturnType<typeof pgSchema>;\n\n// PgView's parameters all default to their upper bounds, so the bare name\n// covers any pg view instance.\ntype AnyPgView = PgView;\n\ntype TableColumnsShape<TTable extends AnyPgTable> = TTable extends {\n _: {\n columns: infer TColumns;\n };\n}\n ? TColumns\n : never;\n\nexport type TableColumnKey<TTable extends AnyPgTable> = Extract<keyof TableColumnsShape<TTable>, string>;\n\nexport type DeferrableConstraintSpecForTable<TTable extends AnyPgTable> = Omit<DeferrableConstraintSpec, \"columns\"> & {\n columns: Array<TableColumnKey<TTable>>;\n};\n\nexport type ManagedFieldSpecForTable<TTable extends AnyPgTable> = Omit<ManagedFieldSpec, \"column\"> & {\n column: TableColumnKey<TTable>;\n};\n\nexport interface ResolvedManagedFieldSpecForTable<TTable extends AnyPgTable> {\n column: TableColumnKey<TTable>;\n applyOn: ManagedFieldApplyOn[];\n strategy: ManagedFieldStrategy;\n}\n\nexport type ClientProjectionSpecForTable<TTable extends AnyPgTable> = Omit<ClientProjectionSpec, \"omitColumns\"> & {\n omitColumns?: readonly TableColumnKey<TTable>[];\n};\n\nexport interface ProjectedTableColumn<TTable extends AnyPgTable = AnyPgTable> {\n propertyKey: TableColumnKey<TTable>;\n columnName: string;\n column: ReturnType<typeof getColumns<AnyPgTable>>[string];\n}\n\nexport type TableGovernanceSpecForTable<TTable extends AnyPgTable> = Omit<\n TableGovernanceSpecBase,\n \"deferrableConstraints\" | \"managedFields\"\n> & {\n deferrableConstraints?: Array<DeferrableConstraintSpecForTable<TTable>>;\n managedFields?: Array<ManagedFieldSpecForTable<TTable>>;\n};\n\ndeclare const syncTableInputGovernanceSymbol: unique symbol;\n\ntype SyncTableInputGovernanceMarker<TGovernance> = {\n [syncTableInputGovernanceSymbol]?: TGovernance;\n};\n\nexport interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTable extends AnyPgTable = TTable> {\n table: TTable;\n /**\n * Projected client-side table for PGlite use. Columns listed in\n * `clientProjection.omitColumns` (e.g. `created_by_id`) are absent from\n * both the runtime table definition and the TypeScript shape of this table.\n */\n localTable: TLocalTable;\n // `| undefined` (with exactOptionalPropertyTypes) admits `defineSyncTable`'s ALWAYS-PRESENT `view`\n // key, whose value is undefined for entries without a read model — see the entry construction.\n view?: AnyPgView | undefined;\n mode: TableMode;\n primaryKey: PrimaryKeySpec;\n /**\n * CDC insert-apply policy (ADR-0045). Default `\"insert\"`: a server CDC `insert` is applied as a plain\n * INSERT, so a genuine primary-key collision surfaces (the ADR-0014 collision-surfacing invariant).\n * `\"upsert\"`: this table legitimately receives locally-derived provisional rows (e.g. written by a\n * local trigger from another synced table), so server CDC inserts are applied idempotently as\n * `INSERT … ON CONFLICT (pk) DO UPDATE` — the authoritative server row overwrites the provisional\n * local row instead of failing the commit. Resolved to `\"insert\"` when omitted.\n */\n applyMode: \"insert\" | \"upsert\";\n /**\n * Consumer-defined ROW CLASSIFICATION (ADR-0052) — documentation-as-code for what KIND of rows this\n * entry carries. The vocabulary is entirely the CONSUMER's: pgxsinkit defines no values and attaches no\n * behaviour to any of them. Its two jobs:\n *\n * - **Fail-closed enumeration.** When the registry declares its vocabulary\n * ({@link SyncRegistryDefinition.rowClasses}), EVERY entry must carry a `rowClass` drawn from that set —\n * validated at `defineSyncRegistry`, i.e. at module eval. A new entry therefore cannot join the registry\n * without its author classifying it, which is what stops a privacy/visibility obligation from being\n * silently inherited by tables nobody remembered to enumerate.\n * - **The binding key for {@link assertRegistryInvariant}.** An invariant binds to `rowClass` values\n * rather than to a hand-maintained table list, so coverage grows with the registry instead of drifting\n * behind it.\n *\n * When the registry declares no `rowClasses`, this field is unconstrained (any string, or none). It is\n * authoring metadata only: it is deliberately absent from the registry fingerprint and the read-contract\n * fingerprint, so classifying a table never shifts a persisted cache key (ADR-0052).\n */\n rowClass?: string;\n shape?: ShapeSpec;\n clientProjection?: ClientProjectionSpecForTable<TTable>;\n serverProjection?: ServerProjectionSpec;\n governance?: TableGovernanceSpecForTable<TTable>;\n /**\n * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable\n * tables** (registry validation rejects an undeclared one — the third hard-require); ignored for\n * `readonly` tables (they have no write path). See {@link ConflictPolicy}.\n */\n conflictPolicy?: ConflictPolicy;\n /**\n * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced on one\n * `MultiShapeStream` and committed atomically at a shared LSN frontier, so a local reader never\n * sees one grouped table advanced past another for the same server transaction. Omitted → the\n * table is its own singleton group (independent frontier, no cross-table atomicity — the resolution\n * for a table that declares no group). The latency cost (a group advances only as fast as its\n * slowest shape) is contained to the tables that opt in.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021): `eager` (default) | `lazy`. A `lazy` table is excluded from the\n * boot subscription set and subscribed on first query-reference. A property of the **consistency\n * group** — every table sharing a `consistencyGroup` must agree (validated). See\n * {@link SubscriptionTiming}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021): `persistent` (default) | `ephemeral`. An `ephemeral` table's whole local\n * cluster is emitted as `TEMP` — no durable trace, no durable offline write queue. A property of the\n * consistency group — every table sharing a `consistencyGroup` must agree (validated). See\n * {@link Retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. A `pessimistic` consistency group is a\n * standing server-authoritative write-unit — its writes flush-route to the authoritative endpoint and\n * the UI shows success only after the server confirms. Write-mode is a property of the **write-unit**;\n * the static write-unit is the consistency group, so every table sharing a `consistencyGroup` must agree\n * (validated). See {@link WriteMode}.\n */\n writeMode?: WriteMode;\n /**\n * True when this entry is a read PROJECTION over a table OWNED by another entry (built by\n * {@link defineReadProjection}). Such an entry owns no physical table — its `table` is the owner's,\n * and only its `localTable` + `shape` are its own — so migration/apply/RLS generation skips it and a\n * consumer's schema barrel must never export a fresh table for it. Absent → the entry owns its table.\n */\n readProjection?: boolean;\n /**\n * The column-builder factory that produced this entry's table (set by {@link defineSyncTable}).\n * Retained so {@link defineReadProjection} can reuse the owner's column definitions to build a typed\n * column subset without restating them, AND — since ADR-0029 P1 — so the client can derive every\n * synced-table object (the local synced read cache, overlay, journal) via\n * `getSyncedLocalTable` → `projectedColumnBuilders`. It is therefore read-derivation machinery, not a\n * write handle: it is carried through every projection ({@link asReadonly}, `withRetention`,\n * `defineReadProjection`), NOT fingerprinted (functions are invisible to the read-contract hash), and\n * required on every registered entry — `defineSyncRegistry`/`validateSyncTableEntry` reject a\n * hand-assembled entry that lacks it, since the client hard-requires it at boot.\n */\n makeColumns?: () => Record<string, ColumnBuilderBase>;\n}\n\n/** Column property key names from a `makeColumns` factory function. */\ntype ColumnKeys<TColumns extends Record<string, ColumnBuilderBase>> = keyof TColumns & string;\n\ntype ProjectedColumnsShape<\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = ColumnKeys<TColumns> extends TOmittedColumns[number] ? TColumns : Omit<TColumns, TOmittedColumns[number]>;\n\n// Explicit shapes for the projected local table and the read-model view.\n// Their drizzle-inferred types cannot survive declaration emit: the printer\n// reproduces pgTable/pgView internals as `PgBuildColumn<TTableName, ...>` with\n// drizzle's own out-of-scope generic, breaking the published .d.ts. The\n// constructed values are cast to these equivalent, printable types instead.\ntype ProjectedLocalTable<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = PgTableWithColumns<{\n name: TName;\n schema: string | undefined;\n columns: PgBuildColumns<TName, ProjectedColumnsShape<TColumns, TOmittedColumns>>;\n dialect: \"pg\";\n}>;\n\n/**\n * The local table TYPE for a {@link defineReadProjection} entry: the OWNER's already-built columns\n * (`TableColumnsShape<TOwnerTable>`) restricted to the kept keys (`TKeptKey`), under the projection's own\n * local name (`TAs`).\n *\n * Why this exists rather than reusing the inner `defineSyncTable`'s `localTable` type: a projection\n * rebuilds its columns from the owner's stashed `makeColumns`, but {@link SyncTableEntry.makeColumns} is\n * type-erased to `() => Record<string, ColumnBuilderBase>`, so a `localTable` inferred through it collapses\n * to an open index signature — forcing bracket-access + `!` in consumers. Picking directly off\n * `TOwnerTable`'s real column types restores rename-safe, per-column typing.\n *\n * Sound by construction — never an over-claim: the runtime keeps `columns ∪ primaryKey`, a SUPERSET of\n * `TKeptKey`, so every typed column exists at runtime. A primary-key column not listed in `columns` is\n * kept at runtime but omitted from the type (a safe under-claim; include it in `columns` to type it).\n */\ntype ProjectionLocalTable<\n TOwnerTable extends AnyPgTable,\n TAs extends string,\n TKeptKey extends string,\n> = PgTableWithColumns<{\n name: TAs;\n schema: string | undefined;\n columns: Pick<TableColumnsShape<TOwnerTable>, TKeptKey & keyof TableColumnsShape<TOwnerTable>>;\n dialect: \"pg\";\n}>;\n\ntype ReadModelView<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = PgViewWithSelection<\n `${TName}_read_model`,\n true,\n PgBuildColumns<\n `${TName}_read_model`,\n ProjectedColumnsShape<TColumns, TOmittedColumns> & {\n overlay_kind: SetNotNull<PgVarcharBuilder<[string, ...string[]]>>;\n local_updated_at_us: SetNotNull<PgBigInt64Builder>;\n }\n >\n>;\n\n/** Governance spec for `defineSyncTable` — columns are typed from `makeColumns`. */\nexport type SyncTableInputGovernance<TColumns extends Record<string, ColumnBuilderBase>> = Omit<\n TableGovernanceSpecBase,\n \"deferrableConstraints\" | \"managedFields\"\n> & {\n deferrableConstraints?: Array<Omit<DeferrableConstraintSpec, \"columns\"> & { columns: Array<ColumnKeys<TColumns>> }>;\n managedFields?: Array<Omit<ManagedFieldSpec, \"column\"> & { column: ColumnKeys<TColumns> }>;\n};\n\n/** Projection spec for `defineSyncTable` — omitColumns typed from `makeColumns`. */\nexport type SyncTableInputProjection<\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n> = Omit<ClientProjectionSpec, \"omitColumns\"> & {\n omitColumns?: TOmittedColumns;\n};\n\n/**\n * A row filter for {@link defineSyncTable}'s `shape`, authored from the table's built, typed columns.\n * Reference columns through `c(columns.x)` exactly as `extras` does with its `self` argument, so\n * `customWhere` builds parameterized Electric `where`s from real, rename-safe column objects instead\n * of hand-written column-name strings.\n */\nexport type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> = (\n columns: PgBuildExtraConfigColumns<TColumns>,\n) => RowFilterSpec;\n\n/** {@link ShapeSpecInput} whose `rowFilter` is authored from the built columns (typed by `TColumns`). */\nexport type ShapeSpecInputFor<TColumns extends Record<string, ColumnBuilderBase>> = Omit<\n ShapeSpecInput,\n \"rowFilter\"\n> & {\n rowFilter?: RowFilterInput<TColumns>;\n};\n\n/**\n * Input for `defineSyncTable`. Supply `tableName + makeColumns` — the Drizzle table\n * (and, for `readwrite` mode, the read-model view) are created internally.\n *\n * Access the built objects via `.table` and `.view` on the returned entry.\n */\nexport type SyncTableInput<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n> = {\n tableName: TName;\n makeColumns: () => TColumns;\n /** RLS policies (or other table extras) attached to the Postgres table. */\n policies?: PgPolicy[];\n /**\n * Extra constraints or indexes on the server-side Postgres table (unique, index, etc.).\n * Receives the built column map — same signature as `pgTable`'s third argument.\n * Not applied to `localTable`.\n */\n extras?: (self: PgBuildExtraConfigColumns<TColumns>) => PgTableExtraConfigValue[];\n /** Place the table in this schema (e.g. for perf-lab schemed tables). */\n schema?: PgSchemaType;\n /** @default \"readonly\" */\n mode?: TableMode;\n /**\n * THE primary key of the server table — the single source of truth for its physical\n * `PRIMARY KEY` constraint. `defineSyncTable` emits it as the constraint, named\n * `` `${tableName}_pkey` `` (matching Postgres's inline-PK default, so existing consumer\n * databases see no rename churn) unless the object form overrides `name`.\n *\n * Defaults to `[\"id\"]`. Use an array with multiple entries for composite keys, or the object\n * form `{ name, columns }` to name the constraint.\n *\n * A single-column key MAY equivalently be declared via the column's own `.primaryKey()`\n * (idiomatic drizzle); it must match this spec, and emission is then skipped because the\n * column already carries the constraint. A table-level `primaryKey(...)` in `extras`/`policies`\n * is REJECTED — declare the key here instead.\n */\n primaryKey?: string[] | { name: string; columns: string[] };\n /**\n * CDC insert-apply policy (ADR-0045). **Default `\"insert\"`** — a CDC insert is a plain INSERT, so a\n * genuine PK collision must surface (the ADR-0014 collision-surfacing invariant; a synced cache table\n * is server-authoritative and a duplicate insert is a real bug). Set `\"upsert\"` **only** when this\n * table legitimately receives locally-DERIVED provisional rows — e.g. a local trigger on another\n * synced table inserts a provisional row here, and the server independently creates the same row so\n * its CDC insert would collide (23505). With `\"upsert\"`, server CDC inserts are applied idempotently\n * as `INSERT … ON CONFLICT (pk) DO UPDATE`; the authoritative server row overwrites the provisional\n * local row. Declare the exception here, where it lives — do not weaken the invariant repo-wide.\n */\n applyMode?: \"insert\" | \"upsert\";\n /**\n * Consumer-defined row classification (ADR-0052) — see {@link SyncTableEntry.rowClass}. Required (and\n * checked against the declared set) when the registry declares {@link SyncRegistryDefinition.rowClasses};\n * unconstrained otherwise.\n */\n rowClass?: string;\n shape?: ShapeSpecInputFor<TColumns>;\n clientProjection?: SyncTableInputProjection<TColumns, TOmittedColumns>;\n /** Server-side response-path projection (e.g. `rowTransform`). Server authority, not client shape. */\n serverProjection?: ServerProjectionSpec;\n governance?: SyncTableInputGovernance<TColumns>;\n /**\n * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable\n * tables** — `defineSyncTable`/`defineSyncRegistry` reject a writable table without one. See\n * {@link ConflictPolicy}.\n */\n conflictPolicy?: ConflictPolicy;\n /**\n * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync on one\n * `MultiShapeStream` and commit atomically. Omit for the default singleton group. See\n * {@link SyncTableEntry.consistencyGroup}.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021): `eager` (default) | `lazy`. See\n * {@link SyncTableEntry.subscription}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021): `persistent` (default) | `ephemeral`. See {@link SyncTableEntry.retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. See {@link SyncTableEntry.writeMode}.\n */\n writeMode?: WriteMode;\n};\n\nexport type SyncTableRegistry = Record<string, SyncTableEntry>;\n\nexport interface SyncRegistryDefinition<TRegistry extends SyncTableRegistry> {\n schema?: string;\n tables: TRegistry;\n /**\n * The storage contract for every store this registry mints (ADR-0049 decision 1, ADR-0047). Part of the\n * DATA contract, not a per-open knob: `durability` binds every toolkit-minted open (relaxed default),\n * and `backend` scopes the BROWSER store only (`opfs` default; Node/`file` and `memory` clones\n * unaffected). Validated at {@link defineSyncRegistry} (fail-closed at module-eval); carried through on\n * the returned registry and read back with {@link getSyncRegistryStorage}. See {@link SyncStorageDeclaration}.\n */\n storage?: SyncStorageDeclaration;\n /**\n * The registry's CLOSED row-classification vocabulary (ADR-0052) — the consumer's own set of\n * {@link SyncTableEntry.rowClass} values (pgxsinkit defines none). Declaring it turns classification into\n * a fail-closed obligation: EVERY entry must then carry a `rowClass` drawn from this exact set, validated\n * at {@link defineSyncRegistry} (module eval), so a newly added entry cannot join the registry\n * unclassified and silently escape whatever invariants its class enrols it in. The declared set is carried\n * on the returned registry and read back with {@link getSyncRegistryRowClasses}, which\n * {@link assertRegistryInvariant} uses to reject a misspelled class in an invariant's `appliesTo`.\n *\n * Omit it and `rowClass` is unconstrained (the bare-registry-map overload has nowhere to declare a set, so\n * it is always unconstrained). Purely authoring metadata: it never enters the registry fingerprint.\n */\n rowClasses?: readonly string[];\n /**\n * The registry's **Event streams** (ADR-0053 decision 1) — the Event lane's registration surface, keyed by\n * Event-stream NAME (the record key IS the name; {@link defineEventStream} declares the entry). Registration\n * lives here rather than in a parallel artifact so there is ONE contract to lock, diff and thread through\n * `createSyncServer` and `defineSyncWorker`.\n *\n * Validated fail-closed at {@link defineSyncRegistry} (module eval, every offender named at once): the name\n * must match `[a-z][a-z0-9_]*` and fit the pgmq queue-name budget, the payload must be a zod schema, and each\n * identity field must name a non-empty claim path. Carried on the returned registry and read back with\n * {@link getSyncRegistryStreams}.\n *\n * Streams follow the `rowClasses` precedent: they ride the registry LOCK as a sibling (added → `compatible`,\n * removed → `breaking`, payload/identity changed → `risky`) and stay OUT of the canonical fingerprint — an\n * Event stream touches no synced table, no local schema and no apply function, so registering one must never\n * wipe a store's read cache. The bare-registry-map overload has nowhere to declare streams.\n */\n streams?: EventStreamRegistry;\n}\n\nexport const syncRegistrySchemaSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistrySchema\");\n\nexport const syncRegistryStorageSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistryStorage\");\n\nexport const syncRegistryRowClassesSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistryRowClasses\");\n\nexport const syncRegistryStreamsSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistryStreams\");\n\nexport type RegistryTables<TRegistry extends SyncTableRegistry> = {\n [TKey in keyof TRegistry]: TRegistry[TKey][\"table\"];\n};\n\nexport type RegistryViews<TRegistry extends SyncTableRegistry> = {\n [TKey in keyof TRegistry as TRegistry[TKey] extends { view: AnyPgView } ? TKey : never]: NonNullable<\n TRegistry[TKey][\"view\"]\n >;\n};\n\nexport type RegistryRelations<TRegistry extends SyncTableRegistry> = ExtractTablesWithRelations<\n {},\n RegistryTables<TRegistry>\n>;\n\nexport type SyncTableName<TRegistry extends SyncTableRegistry> = keyof TRegistry & string;\n\ntype GovernanceShapeForEntry<TEntry> =\n TEntry extends SyncTableInputGovernanceMarker<infer TGovernance>\n ? TGovernance\n : TEntry extends { governance?: infer TGovernance }\n ? TGovernance\n : never;\n\ntype ManagedFieldColumnKeysForOperation<TEntry, TOperation extends ManagedFieldApplyOn> =\n GovernanceShapeForEntry<TEntry> extends {\n managedFields?: ReadonlyArray<infer TField>;\n }\n ? TField extends {\n column: infer TColumn extends string;\n applyOn: ReadonlyArray<ManagedFieldApplyOn>;\n }\n ? TOperation extends TField[\"applyOn\"][number]\n ? TColumn\n : never\n : never\n : never;\n\n/**\n * EVERY managed column key, whatever its `applyOn` — the omit set for {@link SyncTableUpdateInput}.\n * `ManagedFieldApplyOn` is a union and the operation parameter is naked, so the conditional distributes\n * and a field managed on either operation contributes its key.\n *\n * The **type-level twin** of {@link isManagedFieldGuarded} at `\"update\"`: same rule, stated where the\n * compiler can enforce it. Change one only by changing the rule in {@link isManagedFieldGuarded}.\n */\ntype ManagedFieldColumnKeys<TEntry> = ManagedFieldColumnKeysForOperation<TEntry, ManagedFieldApplyOn>;\n\n/**\n * Whether a managed field is **SERVER-OWNED** for an operation — the ONE definition of the guard rule,\n * so the surfaces that enforce it cannot drift apart:\n *\n * - **create** ⇒ the field is guarded when its `applyOn` includes `\"create\"`. The server stamps it after\n * validation, so a client value for it is never honoured.\n * - **update** ⇒ **every** managed field is guarded, a **create-only** one included. An update-managed\n * field is stamped by the server on every write; a `applyOn: [\"create\"]` field is stamped at birth and\n * **inert** on update (the generated apply function offers no UPDATE SET candidate for it). Neither is\n * ever a settable update key, so both are flagged, stripped, and omitted rather than left for consumer\n * RLS to neutralise.\n * - **delete** ⇒ none. A delete carries no payload, so nothing can be owned.\n *\n * \"Guarded\" is NOT \"stamped\": stamping is operation-scoped (`applyOn.includes(operation)`) and decides\n * what the applier writes; guarding decides what a client may not send. They coincide on create and\n * deliberately diverge on update.\n *\n * The consuming surfaces, all of which must go through this predicate:\n * - the write route's `getGuardedManagedFields` (`packages/server/src/mutations/route.ts`) — the 400\n * violation check, the sanitizer, and the create/update validation schemas;\n * - the client's `stripManagedFields` (`packages/client/src/mutation.ts`) — the outgoing-payload strip;\n * - the apply-function generator's `buildTableBranch` (`packages/server/src/mutations/plpgsql-apply.ts`) —\n * the INSERT/UPDATE candidate-column exclusions;\n * - {@link ManagedFieldColumnKeys} / `ManagedFieldColumnKeysForOperation` — the type-level twin behind\n * {@link SyncTableCreateInput} / {@link SyncTableUpdateInput}.\n */\nexport function isManagedFieldGuarded(\n field: { applyOn: readonly ManagedFieldApplyOn[] },\n operation: \"create\" | \"update\" | \"delete\",\n): boolean {\n switch (operation) {\n case \"create\":\n return field.applyOn.includes(\"create\");\n case \"update\":\n return true;\n case \"delete\":\n return false;\n }\n}\n\nexport type SyncTableCreateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>\n ? Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], \"create\">>\n : never;\n\n/**\n * The patch type for an update: the insert model made partial, minus **every** managed key — including\n * a **create-only** one. A field declared `applyOn: [\"create\"]` is stamped at birth and inert on update\n * (the generated apply function offers no UPDATE SET candidate for it), so it is never a settable update\n * key; the write route 400-rejects an update payload that carries one. This omit set is the type-level\n * statement of {@link isManagedFieldGuarded} at `\"update\"` — that predicate is the single definition of\n * the rule, and every runtime surface derives from it.\n */\nexport type SyncTableUpdateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>\n ? Partial<Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeys<TRegistry[TKey]>>>\n : never;\n\nexport type SyncTableRecord<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<infer TTable extends AnyPgTable, AnyPgTable>\n ? InferSelectModel<TTable>\n : never;\n\n/**\n * Filters a columns object, omitting keys in `omitSet`, while preserving TypeScript column types.\n * When `omitSet` is empty the original object is returned unchanged (no copy, no type loss).\n */\nfunction viewColumnsForProjection<\n TColumns extends Record<string, ColumnBuilderBase>,\n const TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n>(columns: TColumns, omittedColumns: TOmittedColumns): ProjectedColumnsShape<TColumns, TOmittedColumns> {\n if (omittedColumns.length === 0) {\n return columns as ProjectedColumnsShape<TColumns, TOmittedColumns>;\n }\n\n const omitSet = new Set<string>(omittedColumns);\n return Object.fromEntries(Object.entries(columns).filter(([key]) => !omitSet.has(key))) as ProjectedColumnsShape<\n TColumns,\n TOmittedColumns\n >;\n}\n\n/**\n * Defines a sync table entry. Provide `tableName` and `makeColumns` — the Drizzle\n * `pgTable` (and, for `readwrite` mode, the `_read_model` view) are created here.\n *\n * Access the built objects via `.table` and `.view` on the returned entry.\n */\nexport function defineSyncTable<\n const TName extends string,\n const TColumns extends Record<string, ColumnBuilderBase>,\n const TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n const TGovernance extends SyncTableInputGovernance<TColumns> | undefined = undefined,\n // The mode LITERAL, so the entry's `view` type can be conditional on it: readwrite entries carry a\n // typed ReadModelView, everything else carries undefined — which is what lets `RegistryViews`\n // (and so `client.views`) keep exactly the read-model entries at the type level.\n const TMode extends TableMode = \"readonly\",\n>(\n input: Omit<SyncTableInput<TName, TColumns, TOmittedColumns>, \"governance\" | \"mode\"> & {\n governance?: TGovernance;\n /** @default \"readonly\" */\n mode?: TMode;\n },\n) {\n const {\n tableName,\n makeColumns,\n policies,\n extras,\n schema,\n mode,\n primaryKey,\n applyMode,\n governance,\n clientProjection,\n serverProjection,\n shape,\n ...otherRest\n } = input;\n\n const resolvedMode: TableMode = mode ?? \"readonly\";\n\n // The `primaryKey` spec is the SINGLE SOURCE OF TRUTH for the server table's physical PRIMARY KEY.\n // It was runtime-only metadata until a consumer (transcrobes) had drizzle-kit DROP a composite PK\n // from a live DB because nothing re-declared it in DDL — so `defineSyncTable` now emits the\n // constraint itself. The default constraint name `${tableName}_pkey` matches Postgres's inline-PK\n // naming, so existing consumer databases see no rename churn; the object form overrides it.\n const primaryKeyColumns = Array.isArray(primaryKey) ? primaryKey : (primaryKey?.columns ?? [\"id\"]);\n const resolvedPrimaryKey: PrimaryKeySpec = { columns: primaryKeyColumns };\n\n // ADR-0045: default to the strict `\"insert\"` policy (a CDC insert is a plain INSERT — a genuine PK\n // collision must surface). Only tables that legitimately receive locally-derived provisional rows opt\n // into idempotent `\"upsert\"` apply of server CDC inserts.\n const resolvedApplyMode: \"insert\" | \"upsert\" = applyMode ?? \"insert\";\n const customPrimaryKeyName = !Array.isArray(primaryKey) ? primaryKey?.name : undefined;\n const primaryKeyConstraintName = customPrimaryKeyName ?? `${tableName}_pkey`;\n\n // Probe the columns (no extras — cheap) to detect idiomatic column-level `.primaryKey()` flags and\n // to resolve each spec column to its PROPERTY KEY (spec entries may be given as the SQL column name\n // or the property key, matching the omitColumns precedent below).\n const probeColumns = getColumns(pgTable(tableName, makeColumns())) as Record<string, AnyPgColumn>;\n const columnLevelPkKeys = Object.entries(probeColumns)\n .filter(([, col]) => col.primary === true)\n .map(([key]) => key);\n const specPropertyKeys = primaryKeyColumns.map((key) => {\n if (probeColumns[key]) return key;\n const byColumnName = Object.entries(probeColumns).find(([, col]) => col.name === key);\n if (byColumnName) return byColumnName[0];\n throw new Error(`[pgxsinkit] ${tableName}: primaryKey column \"${key}\" not found among the table's columns`);\n });\n\n if (columnLevelPkKeys.length > 1) {\n throw new Error(\n `[pgxsinkit] ${tableName}: multiple columns declare .primaryKey() (${columnLevelPkKeys.join(\", \")}) — declare a composite key via the primaryKey option ({ name?, columns }) and remove the column-level .primaryKey() flags; the spec is the single source of truth`,\n );\n }\n if (columnLevelPkKeys.length === 1) {\n const columnLevelPkKey = columnLevelPkKeys[0]!;\n if (specPropertyKeys.length !== 1 || specPropertyKeys[0] !== columnLevelPkKey) {\n throw new Error(\n `[pgxsinkit] ${tableName}: column \"${columnLevelPkKey}\" declares .primaryKey() but the primaryKey spec is [${resolvedPrimaryKey.columns.join(\", \")}] — they must match; the spec is the single source of truth`,\n );\n }\n if (customPrimaryKeyName != null && customPrimaryKeyName !== `${tableName}_pkey`) {\n throw new Error(\n `[pgxsinkit] ${tableName}: a custom primary-key name (\"${customPrimaryKeyName}\") requires defineSyncTable to emit the constraint — remove .primaryKey() from column \"${columnLevelPkKey}\" so the named constraint can be emitted`,\n );\n }\n }\n const emitPrimaryKey = columnLevelPkKeys.length === 0;\n\n const resolvedClientProjection =\n resolvedMode !== \"writeonly\" || clientProjection != null\n ? {\n ...(clientProjection ?? {}),\n syncedTable: clientProjection?.syncedTable ?? tableName,\n ...(resolvedMode === \"readwrite\"\n ? {\n overlayTable: clientProjection?.overlayTable ?? `${tableName}_overlay`,\n journalTable: clientProjection?.journalTable ?? `${tableName}_mutations`,\n }\n : {}),\n }\n : undefined;\n\n const extrasFn =\n policies || extras || emitPrimaryKey\n ? (self: PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>) => {\n const consumerExtras = [...(policies ?? []), ...(extras ? extras(self) : [])];\n for (const extra of consumerExtras) {\n if (extra instanceof PrimaryKeyBuilder) {\n throw new Error(\n `[pgxsinkit] ${tableName}: declare the primary key via the primaryKey option (string[] or { name, columns }), not a primaryKey(...) extra — the spec is the single source of truth and defineSyncTable emits the constraint`,\n );\n }\n }\n if (!emitPrimaryKey) return consumerExtras;\n const selfCols = self as unknown as Record<string, AnyPgColumn>;\n const pkColumns = specPropertyKeys.map((k) => selfCols[k]!) as [AnyPgColumn, ...AnyPgColumn[]];\n return [...consumerExtras, pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];\n }\n : undefined;\n const table = schema ? schema.table(tableName, makeColumns(), extrasFn) : pgTable(tableName, makeColumns(), extrasFn);\n\n // Resolve `shape.rowFilter` against the built typed columns so all authoring uses rename-safe\n // Drizzle column objects rather than hand-written column-name strings.\n const resolvedRowFilter = shape?.rowFilter?.(\n getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>,\n );\n const resolvedShape: ShapeSpec | undefined =\n resolvedMode !== \"writeonly\" || shape != null\n ? {\n tableName: shape?.tableName ?? tableName,\n shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,\n // `electricTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its\n // own table. It is filled by `attachSyncRegistrySchema` (schema qualification) or by\n // `defineReadProjection` (which points a projection at the owning physical table).\n ...(resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {}),\n }\n : undefined;\n\n const omittedColumns = (clientProjection?.omitColumns ?? []) as TOmittedColumns;\n const projectedCols = viewColumnsForProjection(makeColumns(), omittedColumns);\n const localTable = (\n schema ? schema.table(tableName, projectedCols) : pgTable(tableName, projectedCols)\n ) as ProjectedLocalTable<TName, TColumns, TOmittedColumns>;\n\n const viewColumns = viewColumnsForProjection(makeColumns(), omittedColumns);\n const view =\n resolvedMode === \"readwrite\"\n ? (pgView(`${tableName}_read_model`, {\n ...viewColumns,\n overlay_kind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n local_updated_at_us: bigint(\"local_updated_at_us\", { mode: \"bigint\" }).notNull(),\n }).existing() as ReadModelView<TName, TColumns, TOmittedColumns>)\n : undefined;\n\n const entry = {\n ...otherRest,\n mode: resolvedMode,\n primaryKey: resolvedPrimaryKey,\n applyMode: resolvedApplyMode,\n ...(resolvedShape != null ? { shape: resolvedShape } : {}),\n // The input specs are typed over the builder columns map (keys of\n // TColumns); the entry fields demand specs typed over the built table.\n // The key sets are equal by construction (BuildColumns preserves keys),\n // but that equality is unprovable while TColumns is an open generic.\n ...(governance != null ? { governance: governance as TableGovernanceSpecForTable<typeof table> } : {}),\n ...(resolvedClientProjection != null\n ? { clientProjection: resolvedClientProjection as unknown as ClientProjectionSpecForTable<typeof table> }\n : {}),\n ...(serverProjection != null ? { serverProjection } : {}),\n table,\n localTable,\n // ALWAYS a present key, typed by the mode literal. A conditional spread here would infer `view`\n // as an OPTIONAL property, and RegistryViews' `extends { view: AnyPgView }` filter would then\n // reject every entry — `client.views` typed as `{}` for all consumers while runtime worked\n // (caught by the packed fixture's consumer typecheck, ADR-0037 §4). Runtime `entry.view != null`\n // checks are unaffected by a present-undefined key, and the registry fingerprint canonicalizes\n // named fields, never raw entry keys.\n view: view as TMode extends \"readwrite\" ? ReadModelView<TName, TColumns, TOmittedColumns> : undefined,\n // Retained so `defineReadProjection` can reuse these column definitions for a typed subset.\n makeColumns: makeColumns as () => Record<string, ColumnBuilderBase>,\n };\n validateSyncTableEntry(entry as unknown as SyncTableEntry<AnyPgTable>);\n return entry as typeof entry & SyncTableInputGovernanceMarker<TGovernance>;\n}\n\n/**\n * Define a **read projection**: a second client shape over a table an `owner` entry already owns. The\n * projection reads the SAME physical rows under a DISTINCT local identity (`as`) and its own narrower\n * shape — a typed column subset and/or an admin/role-scoped `rowFilter` — without owning, migrating, or\n * RLS-guarding any new table. The first use is a light admin view of a heavy authoring table (titles,\n * not the jsonb), while the learner keeps reading the full table through the owner's shape.\n *\n * It is the *obvious, DRY* way to express \"another shape over this table\", versus the bare\n * `shape.electricTable` string it replaces (a footgun — config that silently un-asserts table\n * ownership):\n *\n * - **Owns nothing.** The returned entry's `table` IS `owner.table` (the same object), so there is no\n * new `pgTable` to migrate or to leak into a drizzle-kit schema barrel. Only `localTable` (named `as`)\n * and `shape` are its own. `readProjection` is set so generators skip it.\n * - **DRY columns.** `columns` is a typed subset of the owner's column keys; the local table is built by\n * filtering the owner's own column definitions (never restated), and the same subset becomes the\n * Electric `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The\n * primary key is always kept. Omit `columns` to sync every column.\n * - **Source is derived, never named.** The physical Electric target is taken from the owner — there is\n * no consumer-facing source field to get wrong (see {@link ShapeSpec.electricTable}).\n * - **Readonly.** A projection has no write path; the engine resolves an incoming shape request by its\n * unique `shapeKey` (= `as`) and consults the derived physical target only on egress.\n *\n * The `rowFilter` callback receives the OWNER's full columns — `customWhere` runs in Electric against\n * the physical table, so it may reference a column the local subset omits. RLS for the projection's\n * reads lives on the OWNER's table (a projection adds no DDL to a table it does not own); its\n * `customWhere` must be a subset of what that RLS allows.\n *\n * The `owner` may be a `defineSyncTable` entry OR an `asReadonly` of one — an `asReadonly` projection\n * preserves the full read contract (physical table, columns, primary key) and only drops the write path,\n * so projecting off it is equivalent to projecting off its writable source. A CHAINED read projection\n * (an owner that is itself a `defineReadProjection`) is rejected, because it composes wrongly — see below.\n *\n * ### Server-side egress redaction (`serverProjection` + `serverOnlyColumns`)\n *\n * A projection may carry its own `serverProjection` (a {@link ServerProjectionSpec}, typically a\n * `rowTransform`) — resolved by the projection's `shapeKey` and run on the proxy egress path for this\n * shape only. The order on egress is **transform first, then omission**: the transform runs against the\n * fetched row, then column omission strips this projection's omitted columns (the client keep-set is\n * `columns ∪ primaryKey`) before the row reaches the client wire. This lets a \"secure window\" over a\n * keyed table stream the body while stripping the keys per row.\n *\n * `serverOnlyColumns` are owner column keys the transform must READ but that are NOT in the client shape\n * (e.g. a `keysWithheld` control flag). Such a key stays omitted from the client keep-set, yet is ADDED\n * to the Electric fetch allow-list — so it is fetched from Electric, visible to the transform, and then\n * stripped on egress by the same omission pass, never reaching the client. It requires a\n * `serverProjection.rowTransform` (a fetch no transform reads is dead weight) AND `columns` (with\n * `columns` omitted every column is already kept, so \"server-only\" is a contradiction), and must be\n * disjoint from `columns` and the primary key.\n *\n * **No inheritance — ENFORCED.** A projection does NOT inherit its owner's `serverProjection`. That is\n * deliberate: an inherited transform whose input column is absent from the projection's fetch list would\n * read `undefined` and silently fail OPEN (serving the un-redacted body) — half-protection worse than\n * none. Because a bare projection over a redacting owner would therefore egress RAW owner rows, the\n * registry no longer merely warns: when `owner.serverProjection?.rowTransform` exists, this function\n * THROWS at definition time unless the projection declares a posture. You must either declare your own\n * `serverProjection` on the projection (typically the same transform fn, plus `serverOnlyColumns` for its\n * control-flag inputs), or — only after confirming the projection's kept columns leak nothing — opt out\n * explicitly with the literal `serverProjection: \"unredacted\"`, which attaches no transform (egress raw)\n * but records that as a visible, reviewed decision at the definition site. The opt-out is meaningful only\n * where it applies: `\"unredacted\"` over an owner with NO egress `rowTransform` is itself rejected, so a\n * stale opt-out cannot silently pre-authorize a leak the day the owner grows one.\n */\nexport function defineReadProjection<\n const TOwnerTable extends AnyPgTable,\n const TOwnerLocal extends AnyPgTable,\n const TAs extends string,\n // Captures `opts.columns` as a literal tuple so the projection's local table can carry the OWNER's real\n // per-column types restricted to the kept keys. Defaults to \"all owner keys\" (its `[number]` is the full\n // key union), which is exactly the shape when `columns` is omitted — one uniform kept-key expression.\n const TColumns extends readonly TableColumnKey<TOwnerTable>[] = readonly TableColumnKey<TOwnerTable>[],\n>(\n // Two table params so an owner that uses `omitColumns` (its `table` and `localTable` types differ) is\n // accepted — `TOwnerTable` (the physical table) is what `columns`/`rowFilter` are typed against.\n owner: SyncTableEntry<TOwnerTable, TOwnerLocal>,\n opts: {\n /** The projection's distinct local identity — its PGlite table name AND its `shapeKey`. */\n as: TAs;\n /** Column keys (of the owner) to sync locally + fetch from Electric. The PK is always kept. Omit → all. */\n columns?: TColumns;\n /** Row filter for this shape; the callback form receives the owner's full (physical) columns. */\n rowFilter?: (columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec;\n /**\n * Server-side egress projection (ADR-0004) for THIS shape — typically a `rowTransform` that redacts a\n * sub-document of a kept column conditionally on row data. A projection does NOT inherit its owner's\n * `serverProjection` (see the docblock's no-inheritance caution): an inherited transform whose input\n * column is unfetched would fail OPEN, so inheritance is refused, not silent. When the OWNER declares\n * an egress `rowTransform`, this is therefore **required** — the registry throws at definition time\n * unless you either declare your own spec here (typically the same transform fn, plus\n * `serverOnlyColumns` for its control-flag inputs) OR opt out with the literal `\"unredacted\"`. Use\n * `\"unredacted\"` only after confirming this projection's kept columns leak nothing; it attaches NO\n * egress transform (the shape streams raw owner rows), but records that as a visible, reviewed\n * decision at the definition site. `\"unredacted\"` over a transform-less owner is itself rejected — a\n * stale opt-out would silently pre-authorize a leak the day the owner grows a transform.\n */\n serverProjection?: ServerProjectionSpec | \"unredacted\";\n /**\n * Owner column keys the `serverProjection.rowTransform` must READ but which are NOT part of the client\n * shape (e.g. a `keysWithheld` control flag). They are added to the Electric fetch allow-list so the\n * transform can see them, then stripped on egress before the client wire. Requires\n * `serverProjection.rowTransform` and `columns`; must be disjoint from `columns` and the primary key.\n */\n serverOnlyColumns?: readonly TableColumnKey<TOwnerTable>[];\n /**\n * Row classification (ADR-0052) for THIS projection. Defaults to the OWNER's `rowClass` — a projection\n * reads the owner's rows, so it carries the owner's classification (and the invariants bound to it)\n * unless you say otherwise. Override when the narrower shape genuinely changes the KIND of row the\n * client receives (e.g. a redacting window over private rows that egresses only public fields).\n */\n rowClass?: string;\n consistencyGroup?: string;\n subscription?: SubscriptionTiming;\n retention?: Retention;\n },\n) {\n // A read projection composes off the OWNER's physical table + full columns. A chained projection (an\n // owner that is itself a read projection) would silently discard the intermediate's OWN column subset\n // and rowFilter — this derivation reads the intermediate's `table`/`makeColumns` (the physical table,\n // full columns), not its narrowed shape — so it cannot mean \"project the projection\". Reject it and\n // point at the owning defineSyncTable entry, which is the only sound base. (An `asReadonly` owner is\n // NOT a read projection and IS accepted — see the docblock.)\n if (owner.readProjection) {\n throw new Error(\n `defineReadProjection: owner \"${opts.as}\" is itself a read projection — chained projections compose ` +\n `wrongly (this derives off the owner's physical table + full columns, so the intermediate's own ` +\n `column subset and rowFilter would be silently discarded). Project off the owning defineSyncTable ` +\n `entry instead.`,\n );\n }\n\n // Defensive: every registrable entry (defineSyncTable + every transform — asReadonly / asEphemeral /\n // withRetention) now carries the column factory, so its absence means a hand-assembled owner, which\n // cannot be projected (there is nothing to derive columns from).\n const ownerMakeColumns = owner.makeColumns;\n if (!ownerMakeColumns) {\n throw new Error(\n `defineReadProjection: owner \"${getTableConfig(owner.table).name}\" has no column factory — pass an ` +\n `entry built by defineSyncTable (or an asReadonly of one), not a hand-assembled entry.`,\n );\n }\n\n const physicalTable = getTableConfig(owner.table).name;\n const allKeys = Object.keys(ownerMakeColumns());\n const pkKeys = owner.primaryKey.columns;\n const keep = opts.columns ? new Set<string>([...opts.columns, ...pkKeys]) : new Set(allKeys);\n // The subset is expressed as `omitColumns` over the OWNER's full columns, so every column-derivation\n // helper (deriveSyncColumnTypes / classifyTableApplyStrategy / getProjectedColumnNames) — which read\n // `entry.table` minus `omitColumns` — yields the right subset for the client, with `entry.table`\n // staying the owner's physical table (nothing new to migrate). The primary key is always kept.\n const omittedKeys = allKeys.filter((key) => !keep.has(key));\n\n // serverOnlyColumns — owner keys the egress rowTransform must READ but that are NOT in the client\n // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND the proxy strips them on\n // egress), yet are added to the Electric fetch allow-list below so the transform can see them. Each\n // guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.\n // Fail-closed posture guard. A projection does NOT inherit its owner's egress `serverProjection`\n // (see the docblock's no-inheritance caution: an inherited transform whose input column is unfetched\n // reads `undefined` and fails OPEN — half-protection worse than none). So if the OWNER redacts on\n // egress via `serverProjection.rowTransform`, this projection would silently egress RAW owner rows\n // unless it declares a posture. We REFUSE that silence: the projection must either declare its own\n // `serverProjection` (an object spec) or opt out with the literal `serverProjection: \"unredacted\"`.\n const optServerProjection = opts.serverProjection;\n const ownerHasEgressTransform = owner.serverProjection?.rowTransform != null;\n if (optServerProjection === \"unredacted\" && !ownerHasEgressTransform) {\n // A stale \"unredacted\" over a transform-less owner would silently pre-authorize a leak if the owner\n // later grew a transform. Keep the opt-out meaningful exactly where it applies.\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverProjection: \"unredacted\", but owner ` +\n `\"${physicalTable}\" declares no egress rowTransform — the opt-out masks nothing here and would ` +\n `silently pre-authorize a leak if the owner later gains one. Remove the opt-out so it cannot mask ` +\n `a future one.`,\n );\n }\n if (ownerHasEgressTransform && optServerProjection == null) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" projects over owner \"${physicalTable}\", which declares ` +\n `an egress rowTransform — a projection does NOT inherit it, so this shape would egress RAW owner ` +\n `rows. Declare your own serverProjection (typically the same transform fn, plus serverOnlyColumns ` +\n `for its control-flag inputs) or — only after confirming the projection's kept columns leak nothing ` +\n `— opt out with serverProjection: \"unredacted\".`,\n );\n }\n // Only an object spec attaches to the entry; \"unredacted\" attaches NOTHING (egress raw, but now a\n // visible, reviewed decision at the definition site).\n const serverProjection = typeof optServerProjection === \"object\" ? optServerProjection : undefined;\n const serverOnlyColumns = opts.serverOnlyColumns ?? [];\n if (serverOnlyColumns.length > 0) {\n if (optServerProjection === \"unredacted\") {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverProjection: \"unredacted\" together ` +\n `with serverOnlyColumns — the opt-out runs no transform, so there is nothing to read them. Drop ` +\n `serverOnlyColumns, or declare a serverProjection.rowTransform that reads them.`,\n );\n }\n if (!serverProjection?.rowTransform) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverOnlyColumns but no ` +\n `serverProjection.rowTransform — a server-only fetch that no transform reads is dead weight. ` +\n `Add the rowTransform that reads them, or drop serverOnlyColumns.`,\n );\n }\n if (!opts.columns) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverOnlyColumns without columns — with ` +\n `columns omitted every column is already kept client-side, so a \"server-only\" column is a ` +\n `contradiction. Declare columns (the client subset) so some columns can be genuinely server-only.`,\n );\n }\n const clientKept = new Set<string>([...opts.columns, ...pkKeys]);\n for (const key of serverOnlyColumns) {\n if (!allKeys.includes(key)) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" serverOnlyColumns names \"${key}\", which is not a ` +\n `column of owner \"${physicalTable}\". It feeds the Electric fetch allow-list, so a typo would ` +\n `silently mis-fetch — name an existing owner column key.`,\n );\n }\n if (clientKept.has(key)) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" lists \"${key}\" in BOTH serverOnlyColumns and the ` +\n `client shape (columns or primary key) — it is already fetched and kept client-side, so ` +\n `declaring it server-only is contradictory. Remove it from serverOnlyColumns.`,\n );\n }\n }\n }\n\n // The local table (subset) + base shape (tableName/shapeKey = `as`) + readonly validation come from the\n // normal constructor — reusing the OWNER's column definitions, never restating them. Below we override\n // only what a projection differs in (it owns no table; it reads the owner's physical table).\n const built = defineSyncTable({\n tableName: opts.as,\n makeColumns: ownerMakeColumns,\n mode: \"readonly\",\n primaryKey: [...pkKeys],\n ...(omittedKeys.length > 0\n ? { clientProjection: { omitColumns: omittedKeys as unknown as readonly never[] } }\n : {}),\n ...(opts.consistencyGroup != null ? { consistencyGroup: opts.consistencyGroup } : {}),\n ...(opts.subscription != null ? { subscription: opts.subscription } : {}),\n ...(opts.retention != null ? { retention: opts.retention } : {}),\n });\n\n // Resolve the row filter against the OWNER's full columns (the customWhere runs in Electric on the\n // physical table, so it may reference a column the subset omits).\n const resolvedRowFilter = opts.rowFilter?.(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>);\n\n // When a subset is requested, set the Electric `columns` allow-list to the KEPT physical column names\n // so an omitted (e.g. heavy jsonb) column is never fetched over the wire — not merely stripped after.\n // serverOnlyColumns are added ON TOP of the kept names: a server-only column must be FETCHED (so the\n // egress rowTransform can read it) even though it is omitted from the client keep-set — proxy omission\n // then strips it after the transform runs. Resolve key -> physical name the same way getProjectedColumns\n // does (the drizzle column's `.name`), never a hand-map. A full-width projection (no omitted keys, hence\n // no serverOnlyColumns — validated above) declares no allow-list at all.\n const ownerColumns = getColumns(owner.table) as Record<string, { name: string }>;\n const serverOnlyColumnNames = serverOnlyColumns.map((key) => ownerColumns[key]!.name);\n const allowListColumns =\n omittedKeys.length > 0 ? [...getProjectedColumnNames(built), ...serverOnlyColumnNames] : undefined;\n\n const rowFilter: RowFilterSpec | undefined =\n resolvedRowFilter != null || allowListColumns != null\n ? {\n ...(resolvedRowFilter ?? {}),\n ...(allowListColumns != null ? { columns: allowListColumns } : {}),\n }\n : undefined;\n\n const shape: ShapeSpec = {\n tableName: opts.as,\n shapeKey: opts.as,\n electricTable: physicalTable,\n ...(rowFilter != null ? { rowFilter } : {}),\n };\n\n // Point `table` at the owner's physical table and flag `readProjection` — that flag (not the absence of\n // a column factory) is what generators/appliers key on to skip owning-table work (see plpgsql-apply's\n // `!entry.readProjection` filter). The owner's `makeColumns` is KEPT (it rode in via `built`): since\n // ADR-0029 P1 the client derives a projection's OWN local synced object from it too\n // (`getSyncedLocalTable` → `projectedColumnBuilders`, with this entry's `omitColumns` applied), so a\n // subscribed read projection that dropped it would fail to boot exactly as an `asReadonly` entry did.\n // `built` was validated by defineSyncTable and only its `table` is replaced (with the owner's,\n // structurally identical role), so the result is a sound SyncTableEntry — cast past the spread's\n // exactOptional friction to a clean entry type that keeps the projected local-table shape.\n // `serverProjection` is attached HERE on the outer object (mirroring `shape`), NOT threaded through the\n // inner `defineSyncTable` call — that alone makes the proxy's shapeKey resolution find and run the\n // projection's egress transform (getRowTransformForTable → resolveEntryByShapeKey(…)?.serverProjection).\n // Row classification (ADR-0052) is INHERITED from the owner by default — a projection streams the owner's\n // rows, so it belongs to the owner's class (and to every invariant bound to it) unless the projection's\n // narrower shape genuinely changes the kind of row a client receives, which `opts.rowClass` overrides.\n const rowClass = opts.rowClass ?? owner.rowClass;\n const projection = {\n ...built,\n table: owner.table,\n shape,\n readProjection: true as const,\n ...(rowClass != null ? { rowClass } : {}),\n ...(serverProjection != null ? { serverProjection } : {}),\n };\n // The local table carries the OWNER's real column types restricted to the kept keys (`TColumns[number]`\n // — the full owner key union when `columns` was omitted), NOT the type-erased `built.localTable` (which\n // collapses to an open index signature because it is rebuilt through the stashed `makeColumns`).\n return projection as unknown as SyncTableEntry<\n TOwnerTable,\n ProjectionLocalTable<TOwnerTable, TAs, TColumns[number]>\n > & { readProjection: true };\n}\n\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n registry: TRegistry,\n): TRegistry;\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n definition: SyncRegistryDefinition<TRegistry>,\n): TRegistry;\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n input: TRegistry | SyncRegistryDefinition<TRegistry>,\n) {\n if (isSyncRegistryDefinition(input)) {\n for (const entry of getRegistryEntries(input.tables)) {\n validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);\n }\n validateRegistryTableUniqueness(input.tables);\n validateRegistryLifecycleGroups(input.tables);\n validateStorageDeclaration(input.storage);\n validateRowClassification(input.tables, input.rowClasses);\n validateEventStreams(input.streams);\n\n // Schema first (it may return the same tables object), then stamp the storage declaration on the\n // returned registry as a non-enumerable symbol — the same carrier pattern as the schema symbol — so\n // client code reads the data-contract storage back off the registry value (getSyncRegistrySchema's\n // twin, getSyncRegistryStorage). The bare-registry-map overload carries no storage and reads back\n // `undefined`, which resolves to the ADR-0047 defaults at the mint seam. The declared row-class\n // vocabulary rides the same way (ADR-0052), for getSyncRegistryRowClasses, and so do the registered\n // Event streams (ADR-0053), for getSyncRegistryStreams.\n return attachSyncRegistryStreams(\n attachSyncRegistryRowClasses(\n attachSyncRegistryStorage(attachSyncRegistrySchema(input.tables, input.schema), input.storage),\n input.rowClasses,\n ),\n input.streams,\n );\n }\n\n for (const entry of getRegistryEntries(input)) {\n validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);\n }\n validateRegistryTableUniqueness(input);\n validateRegistryLifecycleGroups(input);\n\n return input;\n}\n\n/** The local/shape identity an entry resolves to: its `shape.tableName` (the unique shape key a client\n * requests and the local PGlite table), falling back to the Drizzle table name when an entry has no\n * shape (a write-only table). A read projection carries a distinct `shape.tableName` (`as`) even though\n * its `table` is the owner's, so it is identified here by `as`, never by the shared physical table. */\nfunction localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {\n return entry.shape?.tableName ?? getTableConfig(entry.table).name;\n}\n\n/**\n * A registry must not declare the same local table twice. Every entry resolves to one local identity\n * ({@link localShapeIdentity}) — the PGlite table a client reads and the `shapeKey` the proxy resolves a\n * request by — so two entries sharing it would collide locally (one shadows the other) and make the\n * shape unresolvable. A read PROJECTION over a shared physical table does NOT trip this: it carries a\n * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.electricTable`,\n * so several shapes read one physical table while their local identities stay unique. Fails closed at\n * module-eval, for every consumer.\n */\nfunction validateRegistryTableUniqueness(registry: SyncTableRegistry) {\n const declaredBy = new Map<string, string>();\n\n for (const [key, entry] of Object.entries(registry)) {\n const identity = localShapeIdentity(entry as SyncTableEntry<AnyPgTable>);\n const firstKey = declaredBy.get(identity);\n\n if (firstKey !== undefined) {\n throw new Error(\n `local table \"${identity}\" is declared by two registry entries (\"${firstKey}\" and \"${key}\"): ` +\n `each entry must map to a unique local table. A second shape over an existing physical table ` +\n `must use defineReadProjection (a distinct \"as\") rather than a second owning entry.`,\n );\n }\n\n declaredBy.set(identity, key);\n }\n}\n\n/**\n * ADR-0021 §4 / ADR-0022 §1–2: subscription timing, retention, and write-mode are properties of a\n * **consistency group**, not a single table — a group commits atomically on one `MultiShapeStream`\n * (so it cannot be partly lazy or partly ephemeral) and a consistency group *is* the static\n * write-unit (so it cannot be partly pessimistic). Reject a registry whose grouped tables disagree on\n * any of the three. Tables without a `consistencyGroup` are their own singleton group and are\n * unconstrained.\n */\nfunction validateRegistryLifecycleGroups(registry: SyncTableRegistry) {\n const groups = new Map<\n string,\n Array<{ tableName: string; subscription: SubscriptionTiming; retention: Retention; writeMode: WriteMode }>\n >();\n\n for (const entry of getRegistryEntries(registry)) {\n if (!entry.consistencyGroup) {\n continue;\n }\n\n const members = groups.get(entry.consistencyGroup) ?? [];\n members.push({\n tableName: getTableConfig(entry.table).name,\n subscription: entry.subscription ?? \"eager\",\n retention: entry.retention ?? \"persistent\",\n writeMode: entry.writeMode ?? \"optimistic\",\n });\n groups.set(entry.consistencyGroup, members);\n }\n\n for (const [group, members] of groups) {\n const subscriptions = new Set(members.map((member) => member.subscription));\n const retentions = new Set(members.map((member) => member.retention));\n const writeModes = new Set(members.map((member) => member.writeMode));\n\n if (subscriptions.size > 1 || retentions.size > 1 || writeModes.size > 1) {\n throw new Error(\n `consistency group \"${group}\" mixes lifecycle (ADR-0021 §4 / ADR-0022 §1): every table in a ` +\n `group must share one subscription, one retention, and one write-mode; got ` +\n members\n .map((member) => `${member.tableName}=${member.subscription}/${member.retention}/${member.writeMode}`)\n .join(\", \"),\n );\n }\n }\n}\n\nexport function getProjectedColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n const omittedColumns = new Set(entry.clientProjection?.omitColumns ?? []);\n\n return Object.entries(getColumns(entry.table)).flatMap(([propertyKey, column]) => {\n if (omittedColumns.has(propertyKey as TableColumnKey<TTable>)) {\n return [];\n }\n\n return [\n {\n propertyKey: propertyKey as TableColumnKey<TTable>,\n columnName: column.name,\n column,\n } satisfies ProjectedTableColumn<TTable>,\n ];\n });\n}\n\nexport function getOmittedProjectedColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n const omittedColumns = new Set(entry.clientProjection?.omitColumns ?? []);\n\n return Object.entries(getColumns(entry.table)).flatMap(([propertyKey, column]) => {\n if (!omittedColumns.has(propertyKey as TableColumnKey<TTable>)) {\n return [];\n }\n\n return [\n {\n propertyKey: propertyKey as TableColumnKey<TTable>,\n columnName: column.name,\n column,\n } satisfies ProjectedTableColumn<TTable>,\n ];\n });\n}\n\nexport function getProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return getProjectedColumns(entry).map(({ columnName }) => columnName);\n}\n\n/**\n * Resolves the {@link SyncColumnType}s of a synced table's client-projected columns from its Drizzle\n * definition (ADR-0009 decision 3) — the same `getSQLType()`/`dimensions` introspection the local\n * schema generator uses, so the apply ladder and the generated DDL can never disagree about a\n * column's type. Drives both {@link classifyTableApplyStrategy} and the engine's `json` apply cast,\n * removing the runtime `information_schema` round-trip.\n */\nexport function deriveSyncColumnTypes<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): SyncColumnType[] {\n return getProjectedColumns(entry).map(({ column, columnName }) => {\n const typedColumn = column as { getSQLType?: () => string; dimensions?: number; columnType?: string };\n const sqlType = normalizeCastPositionType(typedColumn.getSQLType?.() ?? \"\");\n return {\n name: columnName,\n sqlType,\n isArray: (typedColumn.dimensions ?? 0) > 0,\n // A real Postgres enum column brands as `PgEnumColumn`. `enumValues` is NOT the discriminator:\n // `text(\"c\", { enum: […] })` / varchar variants expose `enumValues` too but their `getSQLType()` is\n // a BASE type (`text`, `varchar(255)`) — identifier-quoting that as a cast type would be wrong (and\n // broken for parameterised types). For a true enum, `getSQLType()` returns the enum TYPE NAME\n // (usable as a cast type once quoted) — the flag lets the ladder classify it as COPY/JSON-safe\n // instead of falling to the `insert` floor on the unrecognised type name.\n isEnum: typedColumn.columnType?.startsWith(\"PgEnum\") === true,\n } satisfies SyncColumnType;\n });\n}\n\n/**\n * `serial`/`bigserial`/`smallserial` are DDL-position conveniences (an integer column plus a sequence\n * default), NOT real cast-position types: `json_to_recordset(… AS x(id serial))` and `value::serial`\n * are both invalid SQL. {@link SyncColumnType.sqlType} is contracted to be usable verbatim as a cast\n * type, so we normalise the serial family to its underlying integer type here — the single derivation\n * point — which also lets the column classify as COPY-safe rather than falling to the `insert` floor.\n *\n * Exported so any code deriving a {@link SyncColumnType} from a bare Drizzle column (e.g. test-support\n * `makeApplyTarget`, which cannot go through {@link deriveSyncColumnTypes} without a registry entry)\n * stays byte-faithful to this single normalisation rather than re-`getSQLType()`ing without it.\n */\nexport function normalizeCastPositionType(sqlType: string): string {\n switch (sqlType.trim().toLowerCase()) {\n case \"serial\":\n return \"integer\";\n case \"bigserial\":\n return \"bigint\";\n case \"smallserial\":\n return \"smallint\";\n default:\n return sqlType;\n }\n}\n\n/** The statically-chosen bulk-insert strategy for a synced table (ADR-0009 decision 3). */\nexport function classifyTableApplyStrategy<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): ApplyStrategy {\n return classifyApplyStrategy(deriveSyncColumnTypes(entry));\n}\n\nexport function getOmittedProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return getOmittedProjectedColumns(entry).map(({ columnName }) => columnName);\n}\n\nexport function getLocalSyncedTablePrimaryKeyColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return [...(entry.clientProjection?.localPrimaryKey?.columns ?? entry.primaryKey.columns)];\n}\n\n/**\n * The Server version column (ADR-0010): the `nowMicroseconds`-on-update managed field a writable\n * table stamps on every write (conventionally `updated_at_us`), made strictly monotonic by the\n * applier. Returns its **column name**, resolving the managed field's drizzle property key. Returns\n * `undefined` when none is declared — registry validation rejects that for writable tables, so the\n * convergence barrier never has to degrade.\n */\nexport function resolveServerVersionColumnName<TTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable>,\n): string | undefined {\n const field = (entry.governance?.managedFields ?? []).find(\n (managed) => managed.strategy === \"nowMicroseconds\" && managed.applyOn.includes(\"update\"),\n );\n\n if (!field) {\n return undefined;\n }\n\n // `field.column` is the drizzle property key (registry validation rejects a column-name declaration —\n // ADR-0012); resolve it to the underlying SQL column name.\n const columns = getColumns(entry.table);\n return (columns as Record<string, { name: string } | undefined>)[field.column as string]?.name;\n}\n\nexport function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry, schema?: string) {\n const normalizedSchema = normalizeSchemaName(schema);\n\n if (!normalizedSchema) {\n return registry;\n }\n\n for (const entry of Object.values(registry)) {\n const tableSchema = getTableConfig(entry.table).schema ?? \"public\";\n\n if (tableSchema !== normalizedSchema) {\n throw new Error(\n `Registry schema ${normalizedSchema} does not match table schema ${tableSchema} for ${getTableConfig(entry.table).name}`,\n );\n }\n\n if (!entry.shape) {\n continue;\n }\n\n const qualify = (name: string) => (name.includes(\".\") ? name : `${normalizedSchema}.${name}`);\n const qualifiedTableName = `${normalizedSchema}.${entry.shape.tableName}`;\n entry.shape = {\n ...entry.shape,\n // A read projection sets electricTable to the owner's (bare) physical name; qualify it the same\n // way the owner's own target is qualified, so both shapes hit one schema-qualified table on egress.\n // An owner (no electricTable) qualifies its own tableName. An already-qualified value is left as-is.\n electricTable: entry.shape.electricTable ? qualify(entry.shape.electricTable) : qualifiedTableName,\n ...(entry.shape.shapeKey === entry.shape.tableName ? { shapeKey: qualifiedTableName } : {}),\n };\n }\n\n Object.defineProperty(registry, syncRegistrySchemaSymbol, {\n value: normalizedSchema,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return registry;\n}\n\nexport function getSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const schema = Reflect.get(registry, syncRegistrySchemaSymbol) as unknown;\n return typeof schema === \"string\" && schema.length > 0 ? schema : \"public\";\n}\n\n/**\n * Stamp the registry's storage declaration (ADR-0049 decision 1, ADR-0047) onto the registry value as a\n * non-enumerable symbol — the storage twin of {@link attachSyncRegistrySchema}. Carries the data-contract\n * storage through {@link defineSyncRegistry} so client code reads it back via {@link getSyncRegistryStorage}.\n * A `null`/`undefined` declaration attaches nothing (the bare-registry-map overload), leaving the reader to\n * resolve the ADR-0047 defaults at the mint seam.\n */\nexport function attachSyncRegistryStorage<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n storage: SyncStorageDeclaration | undefined,\n) {\n if (storage == null) {\n return registry;\n }\n // Idempotent for an EQUAL declaration (a registry value reused across constructions may be re-stamped with\n // the same contract) but fail-closed on a CONFLICT — two different storage contracts over one registry is a\n // definition error, never silently resolved. `backend`/`durability` are the only fields, so a shallow\n // compare is exhaustive.\n const existing = getSyncRegistryStorage(registry);\n if (existing != null) {\n if (existing.backend !== storage.backend || existing.durability !== storage.durability) {\n throw new Error(\n `conflicting storage declaration for registry: already ${JSON.stringify(existing)}, cannot re-declare ` +\n `${JSON.stringify(storage)}`,\n );\n }\n return registry;\n }\n Object.defineProperty(registry, syncRegistryStorageSymbol, {\n value: storage,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return registry;\n}\n\n/**\n * Read the storage declaration (ADR-0049 decision 1, ADR-0047) a registry was built with, or `undefined`\n * when none was declared (a bare registry map, or a definition with no `storage`). The client resolves the\n * effective mint durability as `getSyncRegistryStorage(registry)?.durability ?? \"relaxed\"` at its single\n * mint seam — the storage twin of {@link getSyncRegistrySchema}.\n */\nexport function getSyncRegistryStorage<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): SyncStorageDeclaration | undefined {\n const storage = Reflect.get(registry, syncRegistryStorageSymbol) as unknown;\n return storage != null && typeof storage === \"object\" ? (storage as SyncStorageDeclaration) : undefined;\n}\n\n/**\n * Stamp the registry's declared row-class vocabulary (ADR-0052) onto the registry value as a non-enumerable\n * symbol — the classification twin of {@link attachSyncRegistryStorage}. An absent/empty declaration attaches\n * nothing (the bare-registry-map overload, and any definition that declares no vocabulary), so\n * {@link getSyncRegistryRowClasses} reads back `undefined` and classification stays unconstrained.\n */\nexport function attachSyncRegistryRowClasses<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n rowClasses: readonly string[] | undefined,\n) {\n if (rowClasses == null) {\n return registry;\n }\n // Idempotent for an EQUAL vocabulary (a registry value reused across constructions may be re-stamped with\n // the same set) but fail-closed on a CONFLICT — two different vocabularies over one registry is a\n // definition error, never silently resolved.\n const existing = getSyncRegistryRowClasses(registry);\n if (existing != null) {\n if (existing.length !== rowClasses.length || existing.some((value, index) => value !== rowClasses[index])) {\n throw new Error(\n `conflicting rowClasses declaration for registry: already [${existing.join(\", \")}], cannot re-declare ` +\n `[${rowClasses.join(\", \")}]`,\n );\n }\n return registry;\n }\n Object.defineProperty(registry, syncRegistryRowClassesSymbol, {\n value: Object.freeze([...rowClasses]),\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return registry;\n}\n\n/**\n * Read the row-class vocabulary (ADR-0052) a registry was built with, or `undefined` when none was declared\n * (a bare registry map, or a definition with no `rowClasses`) — the classification twin of\n * {@link getSyncRegistryStorage}. {@link assertRegistryInvariant} consults it to reject an invariant whose\n * `appliesTo` names a class this registry does not define (a typo that would otherwise bind nothing).\n */\nexport function getSyncRegistryRowClasses<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): readonly string[] | undefined {\n const rowClasses = Reflect.get(registry, syncRegistryRowClassesSymbol) as unknown;\n return Array.isArray(rowClasses) ? (rowClasses as readonly string[]) : undefined;\n}\n\n/**\n * Stamp the registry's registered Event streams (ADR-0053 decision 1) onto the registry value as a\n * non-enumerable symbol — the Event-lane twin of {@link attachSyncRegistryRowClasses}. An absent declaration\n * attaches nothing (the bare-registry-map overload, and any definition that registers no Event stream), so\n * {@link getSyncRegistryStreams} reads back `undefined` and the registry simply has no Event lane.\n *\n * Non-enumerable is load-bearing beyond tidiness: `canonicalizeRegistry` walks the registry's own enumerable\n * keys, so riding a symbol is what keeps Event streams OUT of the persisted fingerprint.\n */\nexport function attachSyncRegistryStreams<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n streams: EventStreamRegistry | undefined,\n) {\n if (streams == null) {\n return registry;\n }\n // Idempotent for the SAME registration (one tables object may be reused across per-client registries built\n // from one definition) but fail-closed on a CONFLICT — two different Event-lane contracts over one registry\n // is a definition error, never silently resolved. Entries are compared by identity: a payload schema is an\n // opaque object, so structural equality here would be a worse promise than none.\n const existing = getSyncRegistryStreams(registry);\n if (existing != null) {\n const existingNames = Object.keys(existing).sort();\n const nextNames = Object.keys(streams).sort();\n const same =\n existingNames.length === nextNames.length &&\n existingNames.every((name, index) => name === nextNames[index] && existing[name] === streams[name]);\n if (!same) {\n throw new Error(\n `conflicting streams declaration for registry: already [${existingNames.join(\", \")}], cannot re-declare ` +\n `[${nextNames.join(\", \")}]`,\n );\n }\n return registry;\n }\n Object.defineProperty(registry, syncRegistryStreamsSymbol, {\n value: Object.freeze({ ...streams }),\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return registry;\n}\n\n/**\n * Read the Event streams (ADR-0053 decision 1) a registry was built with, or `undefined` when none were\n * registered — the Event-lane twin of {@link getSyncRegistryRowClasses}. The server mounts the ingestion route\n * and provisions one pgmq queue per entry from this; the client resolves an `appendEvent` payload schema\n * through it.\n */\nexport function getSyncRegistryStreams<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): EventStreamRegistry | undefined {\n const streams = Reflect.get(registry, syncRegistryStreamsSymbol) as unknown;\n return streams != null && typeof streams === \"object\" ? (streams as EventStreamRegistry) : undefined;\n}\n\n/**\n * Fail-closed at module-eval (ADR-0053 decision 1): every registered Event stream must be nameable as a pgmq\n * queue and must declare a usable payload contract and identity-stamping rule. A bad Event-stream name has to\n * fail at DEFINITION — failing at deployment DDL, when `pgxsinkit-generate` emits the per-stream queues, is\n * far too late.\n *\n * Rejection-only, and it names EVERY offender in one error (same posture as {@link validateRowClassification}:\n * an author fixing a batch of streams should not have to re-run the build once per stream).\n */\nfunction validateEventStreams(streams: EventStreamRegistry | undefined) {\n if (streams == null) {\n return;\n }\n\n const problems: string[] = [];\n\n for (const [name, entry] of Object.entries(streams)) {\n if (!EVENT_STREAM_NAME_PATTERN.test(name)) {\n problems.push(\n `\"${name}\": invalid Event-stream name — must match ${EVENT_STREAM_NAME_PATTERN.source} ` +\n `(lowercase letters, digits and underscores, starting with a letter)`,\n );\n } else if (name.length > EVENT_STREAM_NAME_MAX_LENGTH) {\n problems.push(\n `\"${name}\": Event-stream name is ${name.length} characters — at most ${EVENT_STREAM_NAME_MAX_LENGTH} ` +\n `are allowed, because each stream is provisioned as the pgmq queue ` +\n `\"${EVENT_STREAM_QUEUE_PREFIX}${name}\" and pgmq's queue-name limit is 47 characters, of which the ` +\n `\"${EVENT_STREAM_QUEUE_PREFIX}\" prefix consumes ${EVENT_STREAM_QUEUE_PREFIX.length}`,\n );\n }\n\n if (entry == null || typeof entry !== \"object\") {\n problems.push(`\"${name}\": not an Event-stream entry — declare it with defineEventStream({ payload, identity })`);\n continue;\n }\n\n if (!isZodSchema(entry.payload)) {\n problems.push(`\"${name}\": payload is not a zod schema — declare a strict zod schema for the event payload`);\n } else if (hasNonStrictObjectRoot(entry.payload)) {\n // The strict promise is ENFORCED, not advertised. A stripping `z.object({…})` would drop a misspelled\n // or newly-added key between the caller and the consumer with no verdict anywhere — the exact silence\n // the lane's \"everything in the Outbox is well-formed\" invariant exists to prevent. Non-object roots\n // (string, array, record, transform pipelines) are untouched by this rule.\n problems.push(\n `\"${name}\": the payload's object schema is not strict — declare it with \\`.strict()\\` or ` +\n `\\`z.strictObject()\\` (every object inside a union payload too), so an unknown key is REJECTED at ` +\n `\\`appendEvent\\` instead of being silently stripped on the way to the consumer`,\n );\n }\n\n if (entry.revision != null && (!Number.isInteger(entry.revision) || entry.revision <= 0)) {\n problems.push(\n `\"${name}\": revision must be a positive integer (it is the opaque counter you bump when acceptance ` +\n `logic the JSON-Schema hash cannot see — a refinement threshold, a transform — changes)`,\n );\n }\n\n if (entry.identity == null || typeof entry.identity !== \"object\") {\n problems.push(`\"${name}\": identity must be a record of field name -> { claimPath }`);\n continue;\n }\n\n for (const [field, spec] of Object.entries(entry.identity)) {\n if (field.trim().length === 0) {\n problems.push(`\"${name}\": an identity field name is empty`);\n continue;\n }\n const claimPath = spec?.claimPath;\n if (!Array.isArray(claimPath) || claimPath.length === 0) {\n problems.push(\n `\"${name}\".identity.${field}: claimPath must be a non-empty JSON path into the verified claims ` +\n `(e.g. [\"sub\"] or [\"app_metadata\", \"person_id\"])`,\n );\n continue;\n }\n if (claimPath.some((segment) => typeof segment !== \"string\" || segment.trim().length === 0)) {\n problems.push(`\"${name}\".identity.${field}: every claimPath segment must be a non-empty string`);\n }\n }\n }\n\n if (problems.length === 0) {\n return;\n }\n\n throw new Error(\n `invalid Event-stream registration (ADR-0053). The record key IS the Event-stream name, and each entry ` +\n `must be a defineEventStream({ payload, identity }) — ${problems.join(\"; \")}.`,\n );\n}\n\n/**\n * Fail-closed at module-eval (ADR-0052): when a registry declares a `rowClasses` vocabulary, EVERY entry\n * must carry a {@link SyncTableEntry.rowClass} drawn from it. This is the whole point of the field — a new\n * entry added tomorrow cannot join the registry without its author classifying it, so an invariant that\n * binds by class can never quietly under-enumerate the tables it is supposed to cover.\n *\n * Rejection-only, and it names EVERY offender in one error (an author fixing a batch of entries should not\n * have to re-run the build once per entry). An undeclared vocabulary constrains nothing — the entries may\n * carry any `rowClass`, or none.\n */\nfunction validateRowClassification(registry: SyncTableRegistry, rowClasses: readonly string[] | undefined) {\n if (rowClasses == null) {\n return;\n }\n\n if (rowClasses.length === 0) {\n throw new Error(\n `rowClasses is declared but empty: a declared vocabulary makes classification mandatory, so an empty ` +\n `set can never be satisfied. Declare the classes this registry uses, or omit rowClasses entirely.`,\n );\n }\n\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n for (const rowClass of rowClasses) {\n if (typeof rowClass !== \"string\" || rowClass.length === 0) {\n throw new Error(\n `rowClasses contains an invalid value ${JSON.stringify(rowClass)}: each class must be a non-empty string`,\n );\n }\n if (seen.has(rowClass)) {\n duplicates.add(rowClass);\n }\n seen.add(rowClass);\n }\n if (duplicates.size > 0) {\n throw new Error(`rowClasses declares duplicate classes: ${[...duplicates].join(\", \")}`);\n }\n\n const unclassified: string[] = [];\n const unknown: string[] = [];\n for (const [key, entry] of Object.entries(registry)) {\n const rowClass = (entry as SyncTableEntry<AnyPgTable>).rowClass;\n if (rowClass == null) {\n unclassified.push(key);\n continue;\n }\n if (!seen.has(rowClass)) {\n unknown.push(`${key} (rowClass \"${rowClass}\")`);\n }\n }\n\n if (unclassified.length === 0 && unknown.length === 0) {\n return;\n }\n\n const problems = [\n ...(unclassified.length > 0 ? [`unclassified entries: ${unclassified.join(\", \")}`] : []),\n ...(unknown.length > 0 ? [`entries with an undeclared class: ${unknown.join(\", \")}`] : []),\n ];\n throw new Error(\n `row classification is incomplete (ADR-0052). This registry declares rowClasses ` +\n `[${rowClasses.join(\", \")}], so every entry must carry a rowClass from that set — ${problems.join(\"; \")}. ` +\n `Classify each entry (or widen rowClasses if a genuinely new kind of row has arrived).`,\n );\n}\n\n/**\n * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` must\n * be a known value, matching how the other registry axes reject bad input at `defineSyncRegistry`. An absent\n * declaration or absent field is fine — it resolves to the ADR-0047 defaults (`opfs` / `relaxed`).\n */\nfunction validateStorageDeclaration(storage: SyncStorageDeclaration | undefined) {\n if (storage == null) {\n return;\n }\n if (storage.backend !== undefined && !isStorageBackend(storage.backend)) {\n throw new Error(\n `invalid storage.backend \"${String(storage.backend)}\": must be one of ${STORAGE_BACKENDS.join(\", \")}`,\n );\n }\n if (storage.durability !== undefined && !isStorageDurability(storage.durability)) {\n throw new Error(\n `invalid storage.durability \"${String(storage.durability)}\": must be one of ${STORAGE_DURABILITIES.join(\", \")}`,\n );\n }\n}\n\nfunction isSyncRegistryDefinition<TRegistry extends SyncTableRegistry>(\n input: TRegistry | SyncRegistryDefinition<TRegistry>,\n): input is SyncRegistryDefinition<TRegistry> {\n return (\n typeof input === \"object\" &&\n input !== null &&\n \"tables\" in input &&\n typeof input.tables === \"object\" &&\n input.tables !== null\n );\n}\n\nfunction normalizeSchemaName(schema: string | undefined) {\n const trimmed = schema?.trim();\n return trimmed && trimmed !== \"public\" ? trimmed : undefined;\n}\n\nfunction getRegistryEntries<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.values(registry) as Array<SyncTableEntry<AnyPgTable>>;\n}\n\nfunction validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {\n const tableName = getTableConfig(entry.table).name;\n\n // ADR-0029 P1: the client derives every synced-table object (the local synced read cache, and — for a\n // writable table — the overlay/journal) from this column-builder factory (getSyncedLocalTable →\n // projectedColumnBuilders), so it is hard-required at client boot. Promote the check to registry-build\n // time (better DX than an opaque engine-boot throw): defineSyncTable always stashes it, and every\n // projection (asReadonly / withRetention / defineReadProjection) carries it through — only a\n // hand-assembled entry can lack it, and such an entry cannot be synced.\n if (typeof entry.makeColumns !== \"function\") {\n throw new Error(\n `sync table ${tableName} has no makeColumns factory: every registered entry must be built by ` +\n `defineSyncTable (or a projection of one — asReadonly / asEphemeral / defineReadProjection), which ` +\n `stashes the column-builder factory the client requires (ADR-0029 P1) to derive its local ` +\n `synced/overlay/journal objects. Hand-assembled entries are unsupported.`,\n );\n }\n\n // ADR-0010: a writable synced table must declare a Server version — a nowMicroseconds-on-update\n // managed field (conventionally updated_at_us) the applier stamps and keeps strictly monotonic.\n // Optimistic convergence is unsound without a per-row version (the barrier would degenerate to a\n // flicker-prone key-match), so this is a hard requirement, not a silent degraded fallback.\n if (entry.mode !== \"readonly\" && resolveServerVersionColumnName(entry) === undefined) {\n throw new Error(\n `writable table ${tableName} must declare a Server version: a managed field with strategy ` +\n `\"nowMicroseconds\" and applyOn including \"update\" (conventionally updated_at_us) — ADR-0010`,\n );\n }\n\n // ADR-0015: every writable table must declare a Conflict policy — what happens to a stale write.\n // There is no silent default: silent last-write-wins is exactly the data loss the policy exists to\n // turn into a conscious per-table decision. This is the third hard-require (after the Server version\n // above and the server-PK-in-projection rule below), accepted as consistent with the footgun-averse\n // stance.\n if (entry.mode !== \"readonly\" && !isConflictPolicy(entry.conflictPolicy)) {\n throw new Error(\n `writable table ${tableName} must declare a Conflict policy (ADR-0015): conflictPolicy must be ` +\n `one of ${CONFLICT_POLICIES.join(\", \")}` +\n (entry.conflictPolicy === undefined ? \" (none was declared)\" : ` (got ${String(entry.conflictPolicy)})`),\n );\n }\n\n // ADR-0021: the lifecycle axes are optional (default eager/persistent), but a declared value must be\n // valid. Group-level uniformity (every table in a consistency group agrees) is checked at the\n // registry level in defineSyncRegistry, where the whole table set is visible.\n if (entry.subscription !== undefined && !isSubscriptionTiming(entry.subscription)) {\n throw new Error(\n `table ${tableName} has an invalid subscription (ADR-0021): must be one of ` +\n `${SUBSCRIPTION_TIMINGS.join(\", \")} (got ${String(entry.subscription)})`,\n );\n }\n if (entry.retention !== undefined && !isRetention(entry.retention)) {\n throw new Error(\n `table ${tableName} has an invalid retention (ADR-0021): must be one of ` +\n `${RETENTIONS.join(\", \")} (got ${String(entry.retention)})`,\n );\n }\n\n // ADR-0022: write-mode is optional (default optimistic), but a declared value must be valid and\n // meaningful. `pessimistic` governs the write path, which a `readonly` table does not have, so reject\n // it there. Group-level uniformity is checked at the registry level alongside the lifecycle axes.\n if (entry.writeMode !== undefined && !isWriteMode(entry.writeMode)) {\n throw new Error(\n `table ${tableName} has an invalid writeMode (ADR-0022): must be one of ` +\n `${WRITE_MODES.join(\", \")} (got ${String(entry.writeMode)})`,\n );\n }\n if (entry.writeMode === \"pessimistic\" && entry.mode === \"readonly\") {\n throw new Error(\n `readonly table ${tableName} cannot be pessimistic (ADR-0022): write-mode governs the write path, ` +\n `which a readonly table does not have. Declare writeMode only on a writable table.`,\n );\n }\n\n // A managed field's `column` is the drizzle PROPERTY KEY of the target column, never its SQL column\n // name — ADR-0012 keeps the two distinct. Both consumers resolve by property key and canonicalise to\n // it (the client stamp in mutation.ts, the Server-version resolve in resolveServerVersionColumnName);\n // neither tolerates a column-name spelling. So a declaration that names the SQL column instead of the\n // property must fail HERE, at the boundary where declarations enter, rather than silently\n // half-resolving downstream.\n const managedFieldPropertyKeys = new Set(Object.keys(getColumns(entry.table)));\n\n // The single claim-stamping strategy (ADR-0026): an `authClaim` managed field reads a value from the\n // verified request claims at a JSON path, emitted into the apply-function DDL — so the path segments\n // must be plain identifiers and any cast a plain type name (never a value-injection surface). A\n // non-authClaim field carrying claimPath/cast is an authoring slip; reject it rather than ignore it.\n for (const field of entry.governance?.managedFields ?? []) {\n if (!managedFieldPropertyKeys.has(field.column as string)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} names an unknown column: field.column must be the ` +\n `drizzle PROPERTY KEY of the target column, not its SQL column name (ADR-0012)`,\n );\n }\n if (field.strategy === \"authClaim\") {\n if (!Array.isArray(field.claimPath) || field.claimPath.length === 0) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} (strategy \"authClaim\") must declare a non-empty ` +\n `claimPath (e.g. [\"sub\"] or [\"app_metadata\",\"person_id\"]) — ADR-0026`,\n );\n }\n for (const segment of field.claimPath) {\n if (typeof segment !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} has an invalid claimPath segment ` +\n `${JSON.stringify(segment)}: each segment must match [A-Za-z_][A-Za-z0-9_]* (it is emitted into ` +\n `the apply-function DDL)`,\n );\n }\n }\n if (field.cast !== undefined && !/^[A-Za-z_][A-Za-z0-9_ ]*$/.test(field.cast)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} has an invalid cast ${JSON.stringify(field.cast)}: ` +\n `must be a plain SQL type name (e.g. \"uuid\", \"text\")`,\n );\n }\n } else if (field.claimPath !== undefined || field.cast !== undefined) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} declares claimPath/cast but its strategy is ` +\n `\"${field.strategy}\" — those apply only to \"authClaim\"`,\n );\n }\n }\n\n const columns = Object.entries(getColumns(entry.table)).map(([propertyKey, column]) => ({\n propertyKey,\n columnName: column.name,\n column,\n }));\n const columnsByPropertyKey = new Map(columns.map((column) => [column.propertyKey, column]));\n const columnsByColumnName = new Map(columns.map((column) => [column.columnName, column]));\n const omitColumns = entry.clientProjection?.omitColumns ?? [];\n const localPrimaryKeyColumns = entry.clientProjection?.localPrimaryKey?.columns ?? [];\n\n if (omitColumns.length === 0 && localPrimaryKeyColumns.length === 0) {\n return;\n }\n\n const unknownColumns = omitColumns.filter((propertyKey) => !columnsByPropertyKey.has(propertyKey));\n\n if (unknownColumns.length > 0) {\n throw new Error(\n `clientProjection.omitColumns contains unknown columns for ${tableName}: ${unknownColumns.join(\", \")}`,\n );\n }\n\n const unknownLocalPrimaryKeyColumns = localPrimaryKeyColumns.filter(\n (columnName) => !columnsByColumnName.has(columnName),\n );\n\n if (unknownLocalPrimaryKeyColumns.length > 0) {\n throw new Error(\n `clientProjection.localPrimaryKey contains unknown columns for ${tableName}: ${unknownLocalPrimaryKeyColumns.join(\", \")}`,\n );\n }\n\n if (entry.mode !== \"readonly\" && localPrimaryKeyColumns.length > 0) {\n throw new Error(`clientProjection.localPrimaryKey is only supported for readonly table ${tableName}`);\n }\n\n const omittedColumnsSet = new Set(omitColumns);\n const omittedLocalPrimaryKeyColumns = localPrimaryKeyColumns.filter((columnName) =>\n omittedColumnsSet.has(columnName),\n );\n\n if (omittedLocalPrimaryKeyColumns.length > 0) {\n throw new Error(\n `clientProjection.localPrimaryKey must not include omitted columns for ${tableName}: ${omittedLocalPrimaryKeyColumns.join(\", \")}`,\n );\n }\n\n const primaryKeyOmissions = omitColumns.filter((propertyKey) => {\n const column = columnsByPropertyKey.get(propertyKey);\n return column\n ? entry.primaryKey.columns.includes(column.columnName) || entry.primaryKey.columns.includes(propertyKey)\n : false;\n });\n\n if (primaryKeyOmissions.length > 0) {\n if (entry.mode === \"readonly\" && localPrimaryKeyColumns.length > 0) {\n return;\n }\n\n throw new Error(\n `clientProjection.omitColumns must not omit primary-key columns for ${tableName}: ${primaryKeyOmissions.join(\", \")}`,\n );\n }\n\n if (entry.mode === \"readonly\") {\n return;\n }\n\n const createManagedColumns = new Set(\n (entry.governance?.managedFields ?? [])\n .filter((field) => field.applyOn.includes(\"create\"))\n .map((field) => field.column),\n );\n\n const createRequiredOmissions = omitColumns.filter((propertyKey) => {\n const column = columnsByPropertyKey.get(propertyKey);\n\n if (!column) {\n return false;\n }\n\n return column.column.notNull && !column.column.hasDefault && !createManagedColumns.has(propertyKey);\n });\n\n if (createRequiredOmissions.length > 0) {\n throw new Error(\n `clientProjection.omitColumns must only omit create-safe columns for writable table ${tableName}: ${createRequiredOmissions.join(\", \")}`,\n );\n }\n}\n",
10
- "import type { z } from \"zod\";\n\n/**\n * Event-stream registration (ADR-0053 decision 1) — the contract half of the **Event lane**, the toolkit's\n * second lane beside the sync rail.\n *\n * An **Event stream** is a named, registered category of append-only client events sharing one payload\n * schema and one consumer-side handling. It is registered on the sync registry\n * (`SyncRegistryDefinition.streams`), where the record KEY is the Event-stream name, so there is one\n * contract artifact rather than a second one to lock, diff and thread through the server and the worker.\n *\n * The registration stays **declarative data only** — no functions. The gating hook (consent/entitlement\n * refusal before enqueue) is a function on `CreateSyncServerOptions`, keyed by Event-stream name, never a\n * field here.\n */\n\n/**\n * One claim-derived identity field of an Event stream: the JSON path into the **verified** request claims\n * the value is stamped from at ingest.\n *\n * The same addressing as a managed field's `authClaim` strategy (`ManagedFieldSpec.claimPath`) — `[\"sub\"]`\n * for the auth subject, `[\"app_metadata\", \"person_id\"]` for an app-minted identity — so the two\n * claim-stamping surfaces of the toolkit read identically. Identity is **server-stamped**, never\n * client-trusted: the client's envelope carries no identity at all (see `eventEnvelopeSchema`), and the\n * stamped value reaches the consumer callback on the queue envelope (`stampedEventSchema`).\n */\nexport interface EventStreamIdentityField {\n /** JSON path into the verified claims; each segment a plain identifier. Must be non-empty. */\n claimPath: readonly string[];\n}\n\n/**\n * A registered Event stream: its payload contract and its claim→identity stamping rule.\n *\n * `payload` is a **strict** zod schema, and strictness is ENFORCED, not merely advertised: an object-rooted\n * payload (including every object inside a union or discriminated union) must carry a `never` catchall —\n * `.strict()` or `z.strictObject()` — or `defineSyncRegistry` rejects the registration. A stripping object\n * would let a misspelled or newly-added key vanish between the caller and the consumer with no verdict\n * anywhere, which is exactly the silence the Event lane's \"everything in the Outbox is well-formed\"\n * invariant exists to prevent. A NON-object root (a string, array, record, a transform pipeline, …) is\n * accepted unchanged and follows ordinary parse-contract semantics: what the schema ACCEPTS is what\n * `appendEvent` validates, and the JSON-NORMALIZED form of what the schema PRODUCES is what the consumer\n * receives.\n *\n * **The schema EXECUTES at both boundaries; only ONE execution's output is taken.** `appendEvent` runs it as\n * pure validation — the result is discarded and the Outbox stores the value the caller supplied — and the\n * ingestion endpoint runs it again as the one AUTHORITATIVE parse, whose output is what is enqueued and what\n * the consumer callback receives. A transform callback therefore runs twice, so **transforms must be pure\n * and deterministic**: an effectful or environment-dependent one is unsupported, because the server's run is\n * the one that counts and nothing reconciles it against the client's. Parse output the JSON value domain\n * cannot carry (a `BigInt`, `undefined`) is a terminal per-event `rejected` at ingest, never a batch fault.\n *\n * **What is enqueued is the JSON-NORMALIZED parse output, not the parse output itself.** Ingest serializes\n * the authoritative parse's result and enqueues the round-trip, so every queue backend — the in-memory fake\n * and real pgmq's `jsonb` alike — delivers the identical value. The consequence is worth designing against:\n * a transform producing a `Date` reaches the consumer as that date's ISO STRING, and a nested `undefined`\n * property is dropped (an `undefined` array member becomes `null`). A transform that must round-trip as a\n * rich type has to encode it itself.\n *\n * **Schema evolution is compatibility-bound** (ADR-0053 decision 1): a payload schema may evolve only\n * backward-compatibly — it must keep accepting every previously-valid payload, because events written\n * offline under the old schema are still in flight. An incompatible change requires a NEW Event-stream\n * name. The registry lock records a hash of this entry so a change is a reviewable `risky` diff; the hash\n * DETECTS change, it cannot judge compatibility (see `registryEventStreams`).\n */\nexport interface EventStreamEntry<TPayload extends z.ZodType = z.ZodType> {\n payload: TPayload;\n /**\n * The identity fields stamped server-side from verified claims, keyed by field name. The stamped record\n * (field name → value) is what the consumer callback receives on every event.\n */\n identity: Record<string, EventStreamIdentityField>;\n /**\n * An opaque version counter for the part of this payload contract the lock's hash cannot see — the same\n * role `RowFilterSpec.revision` plays for a `customWhere` closure. The lock hashes the payload schema as\n * a **JSON Schema**, and refinements/transforms are simply not representable there: a reviewer\n * demonstrated that `z.string().refine(v => v.length >= 3)` and the INCOMPATIBLE `>= 10` version produce\n * the identical stream hash, so the `risky` diff the ADR relies on never fires.\n *\n * So: whenever you change acceptance logic a JSON Schema cannot express (any `.refine`/`.superRefine`\n * threshold, a cross-field check, a transform), you MUST bump `revision` (positive integer). That is\n * what surfaces the change in the lock diff, where the compatibility rule can actually be reviewed.\n * Leaving it unchanged after a refinement change silently bypasses the gate.\n */\n revision?: number;\n}\n\n/** A registry's Event streams, keyed by Event-stream name (the key IS the name). */\nexport type EventStreamRegistry = Record<string, EventStreamEntry>;\n\n/** The payload TYPE of a registered Event stream — what `appendEvent` accepts for it. */\nexport type EventStreamPayload<TEntry extends EventStreamEntry> =\n TEntry extends EventStreamEntry<infer TPayload> ? z.infer<TPayload> : never;\n\n/**\n * The queue-name prefix each Event stream's pgmq queue is provisioned under (`pgxsinkit_events_<stream>`,\n * ADR-0053 decision 5). Its length is what bounds {@link EVENT_STREAM_NAME_MAX_LENGTH}.\n */\nexport const EVENT_STREAM_QUEUE_PREFIX = \"pgxsinkit_events_\";\n\n/**\n * The maximum length of an Event-stream name: **30**. pgmq's queue-name limit is 47 characters and\n * {@link EVENT_STREAM_QUEUE_PREFIX} consumes 17 of them, so a longer name could not be provisioned. The\n * bound is enforced at `defineSyncRegistry` (module eval) rather than at deployment DDL, because a name\n * that fails only when the queue is created fails far too late.\n */\nexport const EVENT_STREAM_NAME_MAX_LENGTH = 47 - EVENT_STREAM_QUEUE_PREFIX.length;\n\n/**\n * Event-stream names are lowercase `[a-z][a-z0-9_]*` — the intersection of what pgmq accepts unquoted and\n * what stays legible as a queue/table suffix.\n */\nexport const EVENT_STREAM_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;\n\n/**\n * Declare one Event stream for a registry's `streams` map.\n *\n * The Event-stream NAME is the record key it is registered under, so it is not named here — the name (and\n * this entry's payload/identity shape) is validated fail-closed at `defineSyncRegistry`, which sees the\n * whole map and reports EVERY offender in one error rather than one per build.\n *\n * ```ts\n * import { z } from \"zod\";\n *\n * export const registry = defineSyncRegistry({\n * tables: { issue },\n * streams: {\n * board_issue_viewed: defineEventStream({\n * payload: z.object({ issueId: z.uuid() }).strict(),\n * identity: { viewerId: { claimPath: [\"sub\"] } },\n * }),\n * },\n * });\n * ```\n */\nexport function defineEventStream<const TPayload extends z.ZodType>(input: {\n payload: TPayload;\n identity: Record<string, EventStreamIdentityField>;\n /** Bump on every change the JSON-Schema hash cannot see. See {@link EventStreamEntry.revision}. */\n revision?: number;\n}): EventStreamEntry<TPayload> {\n return {\n payload: input.payload,\n identity: input.identity,\n ...(input.revision != null ? { revision: input.revision } : {}),\n };\n}\n\n/**\n * Whether a value walks and quacks like a zod schema.\n *\n * Duck-typed on `safeParse` (the capability `appendEvent` and the ingest endpoint actually use) rather\n * than `instanceof z.ZodType`: zod is a PEER dependency, so a consumer with a duplicated zod install would\n * fail an `instanceof` against a schema that is perfectly usable.\n */\nexport function isZodSchema(value: unknown): value is z.ZodType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === \"function\" &&\n typeof (value as { parse?: unknown }).parse === \"function\"\n );\n}\n\n/** The bits of zod v4's internal `_zod.def` this module reads. Kept structural — zod is a PEER dependency. */\ninterface ZodDefLike {\n type?: unknown;\n catchall?: unknown;\n options?: unknown;\n}\n\nfunction zodDefOf(schema: unknown): ZodDefLike | undefined {\n const def = (schema as { _zod?: { def?: unknown } } | null | undefined)?._zod?.def;\n return def != null && typeof def === \"object\" ? (def as ZodDefLike) : undefined;\n}\n\n/**\n * Whether an Event stream's payload schema has a NON-strict object at its root — the one shape\n * `validateEventStreams` refuses (ADR-0053 decision 1: the payload contract is strict, and the promise is\n * enforced rather than advertised).\n *\n * zod v4 models strictness as the object's **catchall**: `.strict()` / `z.strictObject()` set it to\n * `ZodNever`, a bare `z.object()` leaves it unset (unknown keys are silently STRIPPED), and\n * `z.looseObject()` / `.catchall(…)` set something else. So the rule is exactly \"an object root's catchall\n * must be `never`\", read off `_zod.def` — the same duck-typed posture as {@link isZodSchema}, never an\n * `instanceof` a peer-installed class.\n *\n * A union (or discriminated union) is walked recursively, because each member is equally a root the client\n * may append against. Every other root — string, array, record, a `.transform()` pipeline — is NOT an\n * object and is accepted unchanged. A schema whose internals cannot be read at all (a duplicated zod\n * install, a hand-rolled duck-typed schema) is likewise accepted: this check can only refuse what it can\n * actually see.\n */\nexport function hasNonStrictObjectRoot(schema: unknown): boolean {\n const seen = new Set<unknown>();\n const walk = (candidate: unknown): boolean => {\n if (candidate == null || seen.has(candidate)) {\n return false;\n }\n seen.add(candidate);\n const def = zodDefOf(candidate);\n if (!def) {\n return false;\n }\n if (def.type === \"object\") {\n return zodDefOf(def.catchall)?.type !== \"never\";\n }\n if (def.type === \"union\" && Array.isArray(def.options)) {\n return def.options.some(walk);\n }\n return false;\n };\n return walk(schema);\n}\n",
7
+ "import type { AnyColumn } from \"drizzle-orm\";\nimport { z } from \"zod\";\n\nimport { p, type Predicate } from \"./predicate\";\n\nexport type TableMode = \"readonly\" | \"writeonly\" | \"readwrite\";\n\n/**\n * The per-writable-table Conflict policy (ADR-0015): what happens to a **stale** write — one whose\n * Base server version is behind the row's current Server version at apply (an external write\n * interleaved). It is a **required** declaration on every writable table; there is no silent default\n * (registry validation rejects an undeclared writable table — the third hard-require). v1:\n *\n * - `last-write-wins` — apply the stale write anyway. A required, named declaration: the toolkit never\n * silently clobbers under an unspecified default, so choosing this is an explicit acceptance of the\n * stale-overwrite semantics.\n * - `reject-if-stale` — do not apply; surface the conflict so the user's edit is kept (the optimistic\n * Overlay stays, marked conflicted) and resolved as a new write.\n *\n * `field-merge` (apply only the changed fields over the current row) and `custom-resolver` (a client\n * re-resolution protocol) are reserved values for future policies — declared here so the policy surface\n * names its full intended range.\n */\nexport type ConflictPolicy = \"last-write-wins\" | \"reject-if-stale\";\n\n/** The Conflict policy values accepted in v1 (ADR-0015). Source of truth for registry validation. */\nexport const CONFLICT_POLICIES = [\"last-write-wins\", \"reject-if-stale\"] as const satisfies readonly ConflictPolicy[];\n\n/** Type guard: is `value` one of the v1 {@link ConflictPolicy} values? */\nexport function isConflictPolicy(value: unknown): value is ConflictPolicy {\n return typeof value === \"string\" && (CONFLICT_POLICIES as readonly string[]).includes(value);\n}\n\n/**\n * Subscription timing for a synced table (ADR-0021): **when** its read-path shape subscribes.\n *\n * - `eager` (default) — subscribed in the boot set, as today.\n * - `lazy` — excluded from boot; subscribed on first query-reference. With `persistent` retention,\n * first use is a one-time ignition that promotes the table to a normal eager table for subsequent\n * sessions; with `ephemeral` retention it is session-scoped.\n *\n * A property of the **consistency group**: every table sharing a `consistencyGroup` must agree, since\n * a group's streams commit atomically together — all up-to-date, then one transaction (ADR-0056) — so\n * it cannot be partly lazy (ADR-0021 §4).\n */\nexport type SubscriptionTiming = \"eager\" | \"lazy\";\n\n/** The {@link SubscriptionTiming} values. Source of truth for registry validation. */\nexport const SUBSCRIPTION_TIMINGS = [\"eager\", \"lazy\"] as const satisfies readonly SubscriptionTiming[];\n\n/** Type guard: is `value` a {@link SubscriptionTiming}? */\nexport function isSubscriptionTiming(value: unknown): value is SubscriptionTiming {\n return typeof value === \"string\" && (SUBSCRIPTION_TIMINGS as readonly string[]).includes(value);\n}\n\n/**\n * Retention for a synced table (ADR-0021): **whether** its local copy is durable.\n *\n * - `persistent` (default) — the durable PGlite backend with a resumable subscription-state.\n * - `ephemeral` — the table's whole per-table local cluster (read cache, overlay, journal, sequence,\n * views, reconcile trigger/function) is emitted as `TEMP`, so reads **and** writes leave no durable\n * trace. Consequence: no durable offline write queue — pair a must-not-lose write with a pessimistic\n * flush (ADR-0022).\n *\n * Like {@link SubscriptionTiming}, a property of the consistency group: every table in a group agrees.\n */\nexport type Retention = \"persistent\" | \"ephemeral\";\n\n/** The {@link Retention} values. Source of truth for registry validation. */\nexport const RETENTIONS = [\"persistent\", \"ephemeral\"] as const satisfies readonly Retention[];\n\n/** Type guard: is `value` a {@link Retention}? */\nexport function isRetention(value: unknown): value is Retention {\n return typeof value === \"string\" && (RETENTIONS as readonly string[]).includes(value);\n}\n\n/**\n * Write-mode (ADR-0022): **how** a write reaches the server — the write-side twin of {@link Retention}.\n *\n * - `optimistic` (default) — the write enters the local journal with an optimistic overlay, the UI updates\n * immediately, and the convergence loop flushes the journal as one all-or-nothing batch; the canonical\n * row returns via the sync echo. The path that has always existed.\n * - `pessimistic` — the write is **server-authoritative**: it flush-routes to an authoritative endpoint that\n * applies it in its own isolated, serialised transaction and returns a per-mutation result (accepted, or\n * rejected-with-typed-reason) **before** the UI shows success. For invariants the client cannot evaluate\n * locally — a capacity/quota/uniqueness gate enforced by a server-side rule.\n *\n * Write-mode is a property of an atomic **write-unit**, not a single table (ADR-0022 §1): a unit is uniformly\n * one mode. The *static* write-unit is the **consistency group** — so, like {@link SubscriptionTiming} and\n * {@link Retention}, every table sharing a `consistencyGroup` must agree (validated). A *dynamic* override is\n * the imperative `transaction({ mode })` block, which scopes a mode to an ad-hoc set of mutations.\n */\nexport type WriteMode = \"optimistic\" | \"pessimistic\";\n\n/** The {@link WriteMode} values. Source of truth for registry validation. */\nexport const WRITE_MODES = [\"optimistic\", \"pessimistic\"] as const satisfies readonly WriteMode[];\n\n/** Type guard: is `value` a {@link WriteMode}? */\nexport function isWriteMode(value: unknown): value is WriteMode {\n return typeof value === \"string\" && (WRITE_MODES as readonly string[]).includes(value);\n}\n\n/**\n * The registry-declared BROWSER storage backend (ADR-0049 decision 1). `opfs` (default) is the store's\n * normal boot on every platform — the capability machinery selects the `opfs-repacked` VFS where a home\n * can hold sync-access handles, and falls back to in-SharedWorker `idbfs` when no home can. `idbfs` is the\n * one way to opt out of that machinery entirely: no probe, no election, the engine boots on idb.\n *\n * Scopes the BROWSER store only. Environment resolution is orthogonal and unchanged (ADR-0049 decision 14):\n * a Node mint stays `file://` and the export clone stays memory regardless of this declaration.\n */\nexport type StorageBackend = \"opfs\" | \"idbfs\";\n\n/** The {@link StorageBackend} values. Source of truth for {@link SyncStorageDeclaration} validation. */\nexport const STORAGE_BACKENDS = [\"opfs\", \"idbfs\"] as const satisfies readonly StorageBackend[];\n\n/** Type guard: is `value` a {@link StorageBackend}? */\nexport function isStorageBackend(value: unknown): value is StorageBackend {\n return typeof value === \"string\" && (STORAGE_BACKENDS as readonly string[]).includes(value);\n}\n\n/**\n * The registry-declared durability mode (ADR-0047; ADR-0049 decision 9). `relaxed` (default) returns a\n * write before its durable flush and schedules the flush asynchronously — the local-first \"instant write\"\n * the toolkit exists to deliver. `strict` reinstates the synchronous flush boundary (a ~50ms+ per-statement\n * floor on idb; cheap on `opfs-repacked`). It binds EVERY open of EVERY store minted from the registry, so\n * no minting/open site takes a durability option to contradict it, and an opfs→idbfs capability fallback\n * keeps the declared mode.\n */\nexport type StorageDurability = \"relaxed\" | \"strict\";\n\n/** The {@link StorageDurability} values. Source of truth for {@link SyncStorageDeclaration} validation. */\nexport const STORAGE_DURABILITIES = [\"relaxed\", \"strict\"] as const satisfies readonly StorageDurability[];\n\n/** Type guard: is `value` a {@link StorageDurability}? */\nexport function isStorageDurability(value: unknown): value is StorageDurability {\n return typeof value === \"string\" && (STORAGE_DURABILITIES as readonly string[]).includes(value);\n}\n\n/**\n * The registry's storage contract (ADR-0049 decision 1, ADR-0047). Storage is PART OF THE DATA CONTRACT:\n * whether losing the last not-yet-flushed action is acceptable, and whether OPFS may be used at all, is\n * decided by what the data IS — so it is declared once on the registry, not at any minting/open site.\n *\n * - {@link StorageDurability durability} defaults to `\"relaxed\"` and binds every toolkit-minted open of\n * every store the registry mints (its own boot AND the provision/spare path). No open-site option exists\n * to contradict it; a capability fallback keeps the declared mode. A no-op on `memory` clones.\n * - {@link StorageBackend backend} defaults to `\"opfs\"` and scopes the BROWSER store only; Node/`file` and\n * `memory` clones are unaffected. `\"idbfs\"` opts the store out of the capability/election machinery.\n */\nexport interface SyncStorageDeclaration {\n backend?: StorageBackend;\n durability?: StorageDurability;\n}\n\n/**\n * A {@link SyncStorageDeclaration} with every field resolved (ADR-0050) — the store's BOUND declaration.\n * Produced once per store by {@link resolveStorageDeclaration} and immutable for the store's lifetime: a\n * preference change mints a fresh store under a fresh path, never rebinds an existing one.\n */\nexport interface ResolvedStorageDeclaration {\n backend: StorageBackend;\n durability: StorageDurability;\n}\n\n/**\n * A storage declaration was refused (ADR-0050): two sources explicitly disagree on a field, or a later\n * declaration explicitly contradicts the store's bound declaration. Never resolved silently — the store's\n * storage contract has exactly one value per field, and a disagreement means one side is wrong. The stable\n * `name` survives bridge serialization (`BridgeErrorWire.name`), so a tab can detect the refusal typed.\n */\nexport class StorageDeclarationRefusedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StorageDeclarationRefusedError\";\n }\n}\n\n/** One field's resolution: explicit-vs-explicit disagreement refuses; otherwise the explicit value, else the default. */\nfunction resolveDeclarationField<TValue>(\n field: keyof SyncStorageDeclaration,\n staticValue: TValue | undefined,\n wireValue: TValue | undefined,\n defaultValue: TValue,\n): TValue {\n if (staticValue !== undefined && wireValue !== undefined && staticValue !== wireValue) {\n throw new StorageDeclarationRefusedError(\n `storage declaration disagreement on \"${field}\": the registry-attached declaration says ` +\n `\"${String(staticValue)}\" but the wire declaration says \"${String(wireValue)}\" — a store's storage ` +\n `contract has one value per field; fix the declaring side (a preference change mints a fresh store, ` +\n `it never redeclares an existing one)`,\n );\n }\n return staticValue ?? wireValue ?? defaultValue;\n}\n\n/**\n * Resolve a store's storage declaration from its two sources (ADR-0050): the registry-attached STATIC\n * declaration (authoritative) and the tab's WIRE declaration (honoured only where the registry is silent).\n * Per field: an unset field is \"no opinion\" and can never conflict; both explicit and disagreeing is a\n * {@link StorageDeclarationRefusedError}; unresolved fields take the capability defaults\n * (`backend: \"opfs\"`, `durability: \"relaxed\"`).\n */\nexport function resolveStorageDeclaration(\n staticDeclaration: SyncStorageDeclaration | undefined,\n wireDeclaration: SyncStorageDeclaration | undefined,\n): ResolvedStorageDeclaration {\n return {\n backend: resolveDeclarationField(\"backend\", staticDeclaration?.backend, wireDeclaration?.backend, \"opfs\"),\n durability: resolveDeclarationField(\n \"durability\",\n staticDeclaration?.durability,\n wireDeclaration?.durability,\n \"relaxed\",\n ),\n };\n}\n\n/**\n * Check a LATER declaration against a store's bound resolution (ADR-0050): an unset or equal field is\n * idempotent; an explicit field disagreeing with the bound value is a {@link StorageDeclarationRefusedError}.\n * The bound declaration is immutable — first arrival binds, later arrivals only confirm.\n */\nexport function assertStorageDeclarationCompatible(\n bound: ResolvedStorageDeclaration,\n incoming: SyncStorageDeclaration | undefined,\n): void {\n if (incoming === undefined) return;\n for (const field of [\"backend\", \"durability\"] as const) {\n const value = incoming[field];\n if (value !== undefined && value !== bound[field]) {\n throw new StorageDeclarationRefusedError(\n `storage declaration disagreement on \"${field}\": the store is bound to \"${bound[field]}\" but a later ` +\n `declaration says \"${value}\" — a store's declaration is immutable; a preference change mints a ` +\n `fresh store under a fresh path`,\n );\n }\n }\n}\n\n/**\n * Minimal verified-JWT claim shape the sync layer understands. Providers may\n * attach arbitrary extra claims; those stay reachable through index access and\n * ownership claim paths (e.g. \"app_metadata.person_id\"). Parse decoded JWT\n * payloads with this schema at the auth boundary so the static type is honest.\n */\nexport const jwtClaimsSchema = z.looseObject({\n sub: z.string().optional(),\n app_metadata: z\n .looseObject({\n roles: z.array(z.string()).optional(),\n })\n .optional(),\n});\n\nexport type JwtClaims = z.infer<typeof jwtClaimsSchema>;\n\nexport interface PrimaryKeySpec {\n columns: string[];\n}\n\nexport interface ShapeSpec {\n tableName: string;\n shapeKey: string;\n /**\n * INTERNAL / resolved — the physical Postgres table this shape reads, when it differs from the\n * shape's own `tableName`. A read PROJECTION (`defineReadProjection`) sets it to the OWNING table's\n * name so several shapes can read one physical table under distinct `shapeKey`s; the control plane\n * resolves an incoming subscription by `shapeKey` and consults this only when it creates the shape, as\n * the source `table` it hands the engine. `attachSyncRegistrySchema` also fills/qualifies it for\n * schema-bound registries.\n *\n * Not a consumer input — there is no valid reason to hand-set it (it can only be redundant with, or\n * wrong about, the table you are reading), so it is omitted from {@link ShapeSpecInput}. The\n * combinator derives it from the owner; `defineSyncTable` never sets it from input.\n */\n physicalTable?: string;\n rowFilter?: RowFilterSpec;\n /**\n * SHARED TIER (ADR-0055) — the scope columns, resolved to column names, whose values key this\n * shape family. The predicate is *generated* as an `AND` of equalities over them, so disjointness\n * is a property of the construction rather than something a checker has to enforce: a row carries\n * exactly one value per scope column, so it falls in exactly one shape of the family, and an\n * overlapping pair is not expressible at all.\n *\n * `NULL` is a legal scope value and compiles to `IS NULL` — which is how an offering-wide row gets\n * its own scope `(O, null)` rather than appearing in every group's shape. The tempting\n * `group_id IS NULL OR group_id = $G` form is not merely disallowed here; it is wrong, because it\n * places one row in every group shape at once.\n *\n * Its presence is what makes this a shared-tier shape. Declaring it alongside `rowFilter` is\n * refused at definition time — see {@link readShapeTier}.\n */\n scope?: readonly string[];\n /**\n * The **static** half of the shape's predicate: subscriber-independent, identical for every\n * reader, and therefore safe in either tier. On the shared tier it is conjoined with the generated\n * scope equalities; on the private tier, with whatever `rowFilter` resolves to for the subject.\n *\n * Native AST, not SQL text — see {@link Predicate}.\n */\n where?: Predicate;\n}\n\n/** Which read tier a shape belongs to (ADR-0055 decision 2). */\nexport type ShapeTier = \"shared\" | \"private\";\n\n/**\n * The tier a shape declares, or a refusal.\n *\n * The tier is not configured; it is *read off* which field the author declared — `scope` for shared,\n * `rowFilter` for private. That makes a shape's tier evident from its authoring and impossible to\n * leave ambiguous, which matters because the two differ in whether their bytes are user-independent,\n * and so in whether they may be shared and cached at all.\n *\n * Declaring both is refused rather than resolved by precedence. A `rowFilter` fuses the subject into\n * the predicate, which is exactly what makes a stream unshareable; silently letting it ride along on\n * a shape declared as shared would produce a stream that is cached under a scope key while carrying\n * subject-dependent bytes — a disclosure, not a stale row.\n */\nexport function readShapeTier(shape: ShapeSpec): ShapeTier {\n if (shape.scope != null && shape.rowFilter != null) {\n throw new Error(\n `[pgxsinkit] shape \"${shape.shapeKey}\" declares both scope and rowFilter — a shape is shared ` +\n `(scope: the predicate is a function of scope values only) or private (rowFilter: the subject ` +\n `is fused into the predicate), never both. A rowFilter makes the stream's bytes ` +\n `subject-dependent, so it cannot be served from a scope-keyed shared stream. Move the ` +\n `subject-dependent part into the entitlement rule, or drop scope and keep this private.`,\n );\n }\n return shape.scope != null ? \"shared\" : \"private\";\n}\n\n/**\n * Refuse a shape whose `rowFilter` cannot actually filter.\n *\n * The control plane compiles a private-tier shape from `customPredicate` alone, so a filter that does\n * not supply one is created with no subject test and streams **every** row to whoever subscribed. That\n * is the precise shape of a silent authorization bypass: the registry says \"filtered\", the wire says\n * \"all rows\", and nothing anywhere reports a discrepancy.\n *\n * The way to land there is a `rowFilter` that filters nothing at all — no predicate and no column\n * allow-list — so it asserts a restriction it does not carry. (A filter holding *only* `columns` is\n * legitimate: that is how `defineReadProjection` narrows a projection's wire columns without\n * restricting its rows.)\n *\n * Refused at DEFINITION time, not at the first subscribe: declaring a `rowFilter` asserts that these\n * rows are not for everyone, and there is no input for which a filter that cannot run could later turn\n * out to be fine. A shape that genuinely serves every row omits `rowFilter` entirely — the difference\n * between \"no filter\" and \"a filter that does nothing\" is exactly what this keeps expressible.\n */\nexport function assertShapeFilterIsEnforceable(shape: ShapeSpec): void {\n const filter = shape.rowFilter;\n if (filter == null || filter.customPredicate != null) return;\n\n if (filter.columns == null) {\n throw new Error(\n `[pgxsinkit] shape \"${shape.shapeKey}\" declares a rowFilter that restricts nothing — no ` +\n `customPredicate and no column allow-list. Declare customPredicate, or drop the rowFilter if ` +\n `the rows really are for everyone (an absent rowFilter is how a shape says so).`,\n );\n }\n}\n\n/** Input variant of {@link ShapeSpec} where `tableName` and `shapeKey` are optional.\n * When omitted, both default to the top-level `tableName` of the `defineSyncTable` call.\n * `physicalTable` is deliberately absent — it is a resolved/internal field, never a consumer input\n * (see {@link ShapeSpec.physicalTable}); a read projection over an existing table is authored with\n * `defineReadProjection`, which derives it from the owner. */\nexport type ShapeSpecInput = Omit<ShapeSpec, \"tableName\" | \"shapeKey\" | \"physicalTable\"> & {\n tableName?: string;\n shapeKey?: string;\n};\n\n/** Context available to a {@link RowTransform}: the verified claims and any extra runtime params. */\nexport interface RowTransformContext {\n claims: JwtClaims | null;\n params?: Record<string, unknown>;\n}\n\n/**\n * Per-row rewrite applied on the server's read egress path (after the row filter, before\n * column omission). Receives a streamed row's column map (keys are wire/column names)\n * and returns a possibly-rewritten one — letting the server strip a *sub-document* of a\n * jsonb column, or otherwise rewrite a value, *conditionally on row data*. This expresses\n * what a static, whole-column `omitColumns` cannot.\n *\n * Server authority only: it never alters the local PGlite schema and never alters the shape\n * definition — the engine ref-counts shapes by definition (ADR-0055), so a transform can\n * neither change which stream a subject reads nor split one that would otherwise be shared.\n * Return the same `row` reference to signal \"no change\".\n */\nexport type RowTransform = (row: Record<string, unknown>, context: RowTransformContext) => Record<string, unknown>;\n\nexport interface ClientProjectionSpec {\n syncedTable?: string;\n overlayTable?: string;\n journalTable?: string;\n omitColumns?: readonly string[];\n localPrimaryKey?: PrimaryKeySpec;\n}\n\n/**\n * Server-side projection applied on the read egress path. This is server\n * authority, not client shape — it never alters the local PGlite schema or the\n * shape definition — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).\n */\nexport interface ServerProjectionSpec {\n /**\n * Optional per-row rewrite applied on the read egress path. Runs before column\n * omission, so it may read a column (e.g. a control flag) that\n * `clientProjection.omitColumns` then removes from the client-visible row. See\n * {@link RowTransform}.\n */\n rowTransform?: RowTransform;\n}\n\nexport interface DeferrableConstraintSpec {\n constraintName: string;\n columns: string[];\n initiallyDeferred?: boolean;\n}\n\nexport type ManagedFieldApplyOn = \"create\" | \"update\";\n\n/**\n * How the applier stamps a server-managed column (it overrides any client-sent value — the client write\n * payload omits managed fields, and the apply function re-derives them under the verified request claims):\n *\n * - `nowMicroseconds` — `clock_timestamp()` microseconds, stamped via the canonical `pgxsinkit_clock_us()`\n * DB function (installed by the utilities migration). The audit/version columns (`created_at_us`,\n * `updated_at_us`); the `updated_at_us`-on-update field is the strictly-monotonic Server version (ADR-0010).\n * - `authClaim` — a value read from the **verified JWT claims** at a JSON {@link ManagedFieldSpec.claimPath}\n * (e.g. `[\"sub\"]` for the auth subject, or `[\"app_metadata\",\"person_id\"]` for an app-minted identity). This\n * is the single claim-stamping strategy: the old `authUid` is exactly `{ claimPath: [\"sub\"], cast: \"uuid\" }`,\n * so there is one mechanism, not a `sub`-only special case beside a general one.\n */\nexport type ManagedFieldStrategy = \"nowMicroseconds\" | \"authClaim\";\n\nexport interface ManagedFieldSpec {\n column: string;\n applyOn: ManagedFieldApplyOn[];\n strategy: ManagedFieldStrategy;\n /**\n * For `strategy: \"authClaim\"` only (required there, forbidden otherwise): the JSON path into the verified\n * request claims to stamp from — `[\"sub\"]`, `[\"app_metadata\", \"person_id\"]`, etc. Each segment must be a\n * plain identifier (`[A-Za-z_][A-Za-z0-9_]*`); it is emitted into the apply-function DDL as a `jsonb #>>`\n * text-array path, so it is never a value-injection surface.\n */\n claimPath?: string[];\n /**\n * Optional SQL cast for an `authClaim` value (`jsonb #>>` yields text). Defaults to the **target column's\n * own SQL type** (so a `uuid` column casts to `uuid` with no declaration needed). Override only to force a\n * different cast; must be a plain SQL type name.\n */\n cast?: string;\n}\n\nexport interface TableGovernanceSpec {\n deferrableConstraints?: DeferrableConstraintSpec[];\n managedFields?: ManagedFieldSpec[];\n}\n\nexport interface TableSpecInput {\n mode: TableMode;\n primaryKey: PrimaryKeySpec;\n shape?: ShapeSpec;\n clientProjection?: ClientProjectionSpec;\n governance?: TableGovernanceSpec;\n /**\n * Consistency group (ADR-0009 decision 2): tables sharing a group sync on one set of streams and\n * commit atomically — every stream up-to-date, then one transaction (ADR-0056). Absent → the table is\n * its own singleton group.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` table is excluded from the boot\n * subscription set and subscribed on first query-reference. See {@link SubscriptionTiming}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021). Absent → `persistent`. An `ephemeral` table's whole local cluster is emitted\n * as `TEMP` — no durable trace. See {@link Retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022). Absent → `optimistic`. A `pessimistic` consistency group is a standing\n * server-authoritative write-unit whose writes flush-route to the authoritative endpoint. See\n * {@link WriteMode}.\n */\n writeMode?: WriteMode;\n}\n\nexport function getLocalSyncPrimaryKey(source: {\n primaryKey: PrimaryKeySpec;\n clientProjection?: Pick<ClientProjectionSpec, \"localPrimaryKey\">;\n}) {\n return source.clientProjection?.localPrimaryKey ?? source.primaryKey;\n}\n\nexport function getLocalSyncPrimaryKeyColumns(source: {\n primaryKey: PrimaryKeySpec;\n clientProjection?: Pick<ClientProjectionSpec, \"localPrimaryKey\">;\n}) {\n return [...getLocalSyncPrimaryKey(source).columns];\n}\n\nexport interface RowFilterSpec {\n /**\n * The PRIVATE-TIER row filter (ADR-0055): the predicate fused with the caller's claims, compiled\n * into the shape at subscribe. `null` bypasses filtering (all rows); {@link DENY_ALL_PREDICATE}\n * denies.\n *\n * Authored with the `p.*` builders over real Drizzle column objects, so a comparison is checked\n * against the column's own TypeScript type — a mistyped enum label, a `null` against a NOT NULL\n * column, or a `jsonb`/`Date` column with no scalar wire form are all compile errors rather than\n * silently-wrong filters.\n *\n * **Must be pure**: it is called fresh per shape creation, and probed with empty claims to detect\n * claims-dependence (ADR-0039 — {@link isClaimsDependentRowFilter}).\n */\n customPredicate?: (claims: JwtClaims, params?: Record<string, unknown>) => Predicate | null;\n /** Column projection for the shape URL (e.g. [\"id\", \"source_text\"]). */\n columns?: string[];\n /**\n * An opaque version tag for the part of this filter the fingerprint cannot see — the\n * `customPredicate` body (you cannot hash a closure; only its *presence* is fingerprinted). Bump\n * this (any new string/number) whenever you change that logic so the fingerprint shifts and the\n * local read cache rebuilds + the shape subscription resets. Leaving it unchanged after a\n * `customPredicate` authorization change would silently serve the stale shape.\n */\n revision?: string | number;\n}\n\n/**\n * The deny-all predicate: a `customPredicate` returns this to make **no** rows visible (e.g. an\n * unauthenticated request), the counterpart to returning `null` (which bypasses filtering — all rows\n * visible).\n *\n * An empty `OR` rather than a synthetic always-false comparison: the engine evaluates it as FALSE by\n * construction (`Or` starts at FALSE and only TRUE dominates), it needs no column to name, and it\n * cannot be made accidentally true by a NULL cell the way `col <> col` can.\n *\n * The control plane recognises it **by reference identity** and declines to create the shape at all,\n * so a denied subject holds no handle and no stream is materialised — a stronger outcome than an\n * empty stream, and the reason this is a frozen singleton rather than a shape a caller might\n * reconstruct. A structurally equal but distinct `{ or: [] }` is still correct on the wire; it just\n * costs an empty shape instead of a refusal.\n */\nexport const DENY_ALL_PREDICATE: Predicate = Object.freeze({ or: [] as Predicate[] });\n\n/**\n * Whether a row filter denies (or cannot serve) an unauthenticated caller — a *claims-dependent*\n * filter (ADR-0039). The client probes this at lazy-group activation: a group whose members probe\n * claims-dependent, activated with no auth token, opens an empty subscription by construction, so\n * the client warns.\n *\n * A filter is claims-dependent when its `customPredicate`, evaluated with **empty claims** (`{}` —\n * exactly what the control plane passes for an unauthenticated request) and no params, either\n * **throws** or returns the {@link DENY_ALL_PREDICATE} sentinel by **reference identity** (which every\n * contracts helper — {@link buildOwnershipShapePredicate} and friends — returns for a missing subject,\n * and which is already the documented deny-anonymous pattern). Any other result — `null` (no\n * filtering) or a different predicate — is not claims-dependent as far as this probe can tell.\n *\n * Requires `customPredicate` to be pure (its contract; see {@link RowFilterSpec.customPredicate}).\n */\nexport function isClaimsDependentRowFilter(filter: RowFilterSpec | undefined): boolean {\n if (!filter?.customPredicate) {\n return false;\n }\n\n try {\n return filter.customPredicate({}, undefined) === DENY_ALL_PREDICATE;\n } catch {\n return true;\n }\n}\n\n/**\n * The ownership **predicate** the read path filters on: rows whose owner column equals the caller's\n * subject, {@link DENY_ALL_PREDICATE} for an unauthenticated caller (by reference, so a\n * `customPredicate` built on it probes claims-dependent).\n *\n * Takes the real Drizzle owner column, so the reference is rename-safe, and the subject rides as a\n * typed JSON scalar rather than text that has to be escaped and re-parsed.\n */\nexport function buildOwnershipShapePredicate(ownerColumn: AnyColumn, subject: string | null | undefined): Predicate {\n return subject == null || subject === \"\" ? DENY_ALL_PREDICATE : p.eq(ownerColumn, subject);\n}\n",
8
+ "import { getColumnTable, getTableName, type AnyColumn } from \"drizzle-orm\";\n\n/**\n * The **native predicate AST** — the wire form a shape's `where` takes on the Circuits-native read\n * path (ADR-0055), replacing the Electric path's SQL `where` **text**.\n *\n * This matters beyond serialization. The Electric path compiled a Drizzle `SQL` fragment down to a\n * string that the engine then re-lexed (`where_sql.rs`); the native path never produces text at all,\n * so there is no lexer on our path and no grammar to keep two implementations agreeing on. It is\n * also what makes the repo's SQL-tier rule reachable at tier ① here: authoring is real column\n * objects and typed values end to end, with no string to escape and nothing to interpolate.\n *\n * These types mirror `@electric-circuits/protocol`'s `Predicate` union exactly. They are restated\n * rather than imported: this is the wire contract pgxsinkit commits to, the protocol package is\n * alpha, and a published library should not put an alpha peer in its public types. Any divergence\n * is a bug here — the engine's serde definitions are authoritative.\n */\nexport type PredicateValue = string | number | boolean | null;\n\n/**\n * Comparison operators for a leaf predicate.\n *\n * `like` is SQL `LIKE`: case-sensitive, `%` = any sequence, `_` = any single char. There is no\n * `notLike` op — the engine models it as `Not(Like)`, which is what {@link p.notLike} builds.\n */\nexport type PredicateLeafOp = \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\" | \"like\";\n\n/** `col <op> value`. Three-valued: never TRUE on a NULL cell — use {@link IsNullPredicate} for that. */\nexport interface LeafPredicate {\n col: string;\n op: PredicateLeafOp;\n value: PredicateValue;\n}\n\n/**\n * `col IS NULL` / `col IS NOT NULL`. A separate leaf because it is the one test that is TRUE on a\n * NULL cell, and the only two-valued one — so it is also the only leaf that composes soundly under\n * {@link NotPredicate}.\n */\nexport interface IsNullPredicate {\n col: string;\n isNull: boolean;\n}\n\nexport interface AndPredicate {\n and: Predicate[];\n}\n\nexport interface OrPredicate {\n or: Predicate[];\n}\n\nexport interface NotPredicate {\n not: Predicate;\n}\n\n/**\n * The inner half of an `IN` test: the set of `project` values over `table`'s rows matching `where`.\n * `where` may itself contain subquery leaves. Single column only — the engine has no composite\n * `(a, b) IN (…)`. Subqueries must stay **uncorrelated**: the inner `where` references the inner\n * table's columns only, never the outer row's.\n */\nexport interface SubqueryRef<TValue extends PredicateValue = PredicateValue> {\n table: string;\n project: string;\n where?: Predicate;\n /**\n * Phantom: the projected column's value type, carried so {@link p.in} can require the OUTER column\n * to be comparable with what the subquery actually projects. Never serialized — it is a type-level\n * marker only, which is why it is optional and never read.\n */\n readonly __value?: TValue;\n}\n\n/**\n * `outer.col IN (SELECT project FROM table WHERE …)`, or `NOT IN` when `negated`. The engine\n * maintains the inner set incrementally and shares it across every shape referencing the same\n * subquery, which is why an entitlement-shaped subquery costs one index rather than one per shape.\n */\nexport interface InSubqueryPredicate {\n col: string;\n in: SubqueryRef;\n negated?: boolean;\n}\n\n/** A restricted boolean predicate over one table's columns, plus single-column `IN`/`NOT IN`. */\nexport type Predicate =\n | LeafPredicate\n | IsNullPredicate\n | AndPredicate\n | OrPredicate\n | NotPredicate\n | InSubqueryPredicate;\n\nexport function isLeafPredicate(node: Predicate): node is LeafPredicate {\n return \"col\" in node && \"op\" in node;\n}\nexport function isIsNullPredicate(node: Predicate): node is IsNullPredicate {\n return \"col\" in node && \"isNull\" in node;\n}\nexport function isAndPredicate(node: Predicate): node is AndPredicate {\n return \"and\" in node;\n}\nexport function isOrPredicate(node: Predicate): node is OrPredicate {\n return \"or\" in node;\n}\nexport function isNotPredicate(node: Predicate): node is NotPredicate {\n return \"not\" in node;\n}\nexport function isInSubqueryPredicate(node: Predicate): node is InSubqueryPredicate {\n return \"in\" in node && \"col\" in node;\n}\n\n/**\n * Values reach the engine as JSON scalars, so a Drizzle column whose TS type is richer than the\n * four Circuits column types (`int`/`text`/`bool`/`float`) has no automatic rendering here.\n *\n * `Date` is the case that actually turns up, and it is deliberately **not** coerced: a timestamp\n * column syncs as `text`, and JS's ISO rendering is not Postgres's, so a silent `toISOString()`\n * would produce a predicate that compares unequal to every row it was meant to match. Render it the\n * way the column does and pass the string.\n */\nfunction assertPredicateValue(column: AnyColumn, value: unknown): asserts value is PredicateValue {\n if (value === null) return;\n const kind = typeof value;\n if (kind === \"string\" || kind === \"number\" || kind === \"boolean\") return;\n\n const shown = value instanceof Date ? \"Date\" : kind === \"object\" ? \"object\" : kind;\n throw new Error(\n `[pgxsinkit] predicate on \"${column.name}\": ${shown} is not a predicate value — the wire form ` +\n `carries JSON scalars (string | number | boolean | null). Render it to the text form the ` +\n `column itself stores and pass that, rather than relying on a coercion that may not match.`,\n );\n}\n\n/**\n * What a builder accepts, versus {@link PredicateValue} (what goes on the wire).\n *\n * `bigint` is admitted because the toolkit's own timestamp convention is a **microsecond BIGINT**, so\n * comparing against one is ordinary rather than exotic. It is narrowed to a number by `toWireValue`\n * rather than widening the wire type: Postgres `bigint` is `ColumnType::Int` to the engine, which reads\n * the JSON scalar as an `i64` — a decimal *string* would be rejected against an int column.\n */\nexport type PredicateValueInput = PredicateValue | bigint;\n\n/** A column's TypeScript value type, as Drizzle carries it on the column object. */\ntype ColumnData<TCol extends AnyColumn> = TCol[\"_\"][\"data\"];\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\n/**\n * Whether a column's value type is statically unknowable — `any`, or the `unknown` that Drizzle's\n * erased column paths (`getColumns`, `PgBuildExtraConfigColumns`) yield. Those must stay PERMISSIVE:\n * narrowing an unknowable type through `Extract` collapses it to `never`, which would refuse every\n * comparison on a column the author cannot re-type.\n */\ntype IsUnknownData<T> = IsAny<T> extends true ? true : unknown extends T ? true : false;\n\n/**\n * What may be compared against `TCol` — the column's OWN value type, narrowed to what this wire can\n * carry, plus `null` when the column is nullable.\n *\n * `Extract` is what refuses a column whose values have no scalar form at all: a `jsonb` column typed\n * as an object, or a `timestamp` column typed as `Date`, resolves to `never` here, so the comparison\n * is a compile error rather than the runtime throw it used to be. And because a `pgEnum` column's\n * data type is the literal union of its labels, a mistyped label is caught too — something the SQL\n * text form could never see.\n */\nexport type ColumnValue<TCol extends AnyColumn> =\n IsUnknownData<ColumnData<TCol>> extends true\n ? PredicateValueInput\n : Extract<ColumnData<TCol>, PredicateValueInput> | (TCol[\"_\"][\"notNull\"] extends true ? never : null);\n\n/**\n * Narrow a builder input to its wire form, refusing the one conversion that would be silently wrong.\n *\n * A `bigint` past `Number.MAX_SAFE_INTEGER` cannot survive the trip: JSON's only integer carrier here\n * is a JS `number` (an IEEE double), so serializing it would round to a nearby value and the predicate\n * would compare unequal to the row it was written for. Microsecond timestamps sit comfortably inside\n * the safe range, so this throws only for a value that genuinely cannot be expressed.\n */\nfunction toWireValue(column: AnyColumn, value: PredicateValueInput): PredicateValue {\n if (typeof value !== \"bigint\") {\n assertPredicateValue(column, value);\n return value;\n }\n\n if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {\n throw new Error(\n `[pgxsinkit] predicate on \"${column.name}\": ${value}n is outside the exactly-representable ` +\n `integer range, so serializing it would silently round to a different value. Compare against ` +\n `a value inside the safe-integer range, or split the test.`,\n );\n }\n return Number(value);\n}\n\nfunction leaf<TCol extends AnyColumn>(column: TCol, op: PredicateLeafOp, value: ColumnValue<TCol>): LeafPredicate {\n return { col: column.name, op, value: toWireValue(column, value as PredicateValueInput) };\n}\n\n/**\n * The predicate builder — the tier-① authoring surface for a native `where`.\n *\n * Deliberately namespaced rather than exported as bare `eq`/`and`/`or`/`not`, which would collide\n * with `drizzle-orm`'s operators of the same names in exactly the files that use both (a registry\n * authoring RLS policies with Drizzle's `eq` and a shape `where` with this one). The shapes are\n * intentionally the same so the two read alike; only the AST-versus-`SQL` return type differs.\n *\n * ```ts\n * where: (c) => p.and(p.eq(c.published, true), p.isNotNull(c.releasedAt))\n * ```\n */\nexport const p = {\n eq: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, \"eq\", value),\n ne: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, \"neq\", value),\n lt: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, \"lt\", value),\n lte: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, \"lte\", value),\n gt: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, \"gt\", value),\n gte: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, \"gte\", value),\n\n /** SQL `LIKE` (case-sensitive; `%` = any sequence, `_` = any single char). Text columns only. */\n like: <TCol extends AnyColumn<{ data: string }>>(column: TCol, pattern: string): LeafPredicate =>\n leaf(column, \"like\", pattern as ColumnValue<TCol>),\n /** SQL `NOT LIKE`. The engine has no negated-like op; it models it as `Not(Like)`, so this does too. */\n notLike: <TCol extends AnyColumn<{ data: string }>>(column: TCol, pattern: string): NotPredicate => ({\n not: leaf(column, \"like\", pattern as ColumnValue<TCol>),\n }),\n\n isNull: (column: AnyColumn): IsNullPredicate => ({ col: column.name, isNull: true }),\n isNotNull: (column: AnyColumn): IsNullPredicate => ({ col: column.name, isNull: false }),\n\n and: (...nodes: Predicate[]): AndPredicate => ({ and: nodes }),\n or: (...nodes: Predicate[]): OrPredicate => ({ or: nodes }),\n not: (node: Predicate): NotPredicate => ({ not: node }),\n\n /**\n * The inner set for an `IN` test, named by the column it projects — the table is read off that\n * column, so there is no table name to get wrong and no way to project a column the named table\n * does not have.\n */\n subquery: <TCol extends AnyColumn>(\n projected: TCol,\n where?: Predicate,\n ): SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>> => ({\n table: getTableName(getColumnTable(projected)),\n project: projected.name,\n ...(where !== undefined ? { where } : {}),\n }),\n\n in: <TCol extends AnyColumn>(\n column: TCol,\n ref: SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>>,\n ): InSubqueryPredicate => ({ col: column.name, in: ref }),\n notIn: <TCol extends AnyColumn>(\n column: TCol,\n ref: SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>>,\n ): InSubqueryPredicate => ({\n col: column.name,\n in: ref,\n negated: true,\n }),\n} as const;\n\n/**\n * Conjoin, dropping absent branches and collapsing the trivial cases. `undefined` when nothing is\n * left, which is the AST's own spelling of \"all rows\" (an omitted `where`) — so a caller never has\n * to invent an always-true leaf to stand in for one.\n */\nexport function conjoinPredicates(...nodes: (Predicate | undefined)[]): Predicate | undefined {\n const present = nodes.filter((node): node is Predicate => node !== undefined);\n if (present.length === 0) return undefined;\n if (present.length === 1) return present[0];\n return { and: present };\n}\n",
9
+ "import { type AnyPgTable, getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { resolveServerVersionColumnName, type SyncTableEntry } from \"./registry\";\nimport { quoteIdentifier } from \"./sql-identifier\";\n\n/**\n * The Convergence model (ADR-0011): the single owner of *how* local optimistic state converges to\n * server state. It owns the shared barrier predicate, the per-table sync-state **view** generator,\n * and the event-model spec below. Read sync (the Sync applier) and write sync (the mutation runtime)\n * remain the two edges with their own transaction paths, but neither independently decides whether an\n * entity is resolved — this module is the one resolution authority.\n *\n * Distinct from the convergence *driver* (`convergence.ts`, ADR-0005), which schedules *when* to\n * converge. This module defines *how* an entity resolves.\n */\n\n/**\n * The Convergence barrier predicate (ADR-0010): an acked create/update is resolved only once the\n * synced echo's Server version has reached the write's acked version. Emitted identically by the\n * reconcile trigger (schema.ts), `reconcileTable` (mutation.ts), **and** the per-table sync-state\n * view (decision 4) — one rule, three consumers, no drift (ADR-0004).\n *\n * `syncedAlias` is the synced-side reference (a table alias, or `NEW` inside the trigger);\n * `journalAlias` qualifies the journal's `server_updated_at_us` (omit it where the journal is the\n * unaliased target of the `DELETE`).\n */\nexport function buildOverlayResolutionBarrier<TTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable>,\n options: { syncedAlias: string; journalAlias?: string },\n): string {\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n\n if (!serverVersionColumn) {\n throw new Error(\n `writable table ${getTableConfig(entry.table).name} has no Server version; cannot build the convergence barrier (ADR-0010)`,\n );\n }\n\n const journalRef = options.journalAlias ? `${options.journalAlias}.server_updated_at_us` : \"server_updated_at_us\";\n return `${journalRef} <= ${options.syncedAlias}.${quoteIdentifier(serverVersionColumn)}`;\n}\n\n/**\n * The qualified object names the sync-state view is generated over. The synced read cache is\n * droppable (ADR-0006); overlay + journal are the authority. The view joins all three but stores\n * nothing — it is a derived projection (ADR-0011 decision 2).\n */\nexport interface SyncStateViewProjection {\n /** Qualified synced read-cache table. */\n syncedTable: string;\n /** Qualified overlay (optimistic intent) table. */\n overlayTable: string;\n /** Qualified mutation-journal table. */\n journalTable: string;\n}\n\n/**\n * Generate the per-writable-table `<table>_sync_state` **view** (ADR-0011 decision 2): a derived\n * projection — never a stored copy — over synced + overlay + journal that answers \"what is this\n * entity's convergence state?\" with one authoritative, queryable row per entity that has local\n * activity (an overlay or journal row). Keyed on the **real PK columns**, never a generic\n * `entity_key_json` (decision 2).\n *\n * Columns:\n * - `observed_server_version` — the synced row's Server version (NULL when no echo has landed).\n * - `acked_server_version` — the highest Server version the server assigned to our acked writes.\n * - `pending_count` — journal rows still owed to the server (pending/sending/failed).\n * - `has_acked_unobserved_write` — an acked create/update whose echo has not yet caught up. Derived\n * from the **same** {@link buildOverlayResolutionBarrier} predicate the resolver uses (decision 4),\n * so what the UI shows can never drift from what the resolver does.\n * - `local_delete_pending` — an optimistic delete is staged in the overlay.\n * - `conflict_state` — the reason a `conflicted` (stale, reject-if-stale) write was declined, or NULL\n * when the entity has no conflicted mutation (ADR-0015). Surfaced from the journal's\n * `conflict_reason`, scoped to `status = 'conflicted'` so a stale failure reason never leaks in.\n * - `quarantined_count` — terminal local writes the server permanently rejected (ADR-0006): a poison\n * mutation named in a batch rejection, or one that exhausted the attempt cap. Quarantine blocks\n * sync and *keeps* the optimistic overlay, so without this the view would show an entity with\n * `pending_count = 0` and `conflict_state = NULL` yet still carrying un-converged local intent.\n * - `quarantine_state` — the `last_error` of a quarantined write (the rejection reason), or NULL when\n * the entity has none. The reason counterpart to `quarantined_count`, mirroring `conflict_state`.\n *\n * Note `pending_count` is the *retryable* owed set (pending/sending/failed); a quarantined write is\n * terminal, counted separately so a blocked write is never mistaken for one still in flight.\n *\n * The Read model stays lean (it already carries `overlay_kind`); an app that wants per-row\n * convergence status joins this view on the PK.\n */\nexport function buildSyncStateView<TTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable>,\n projection: SyncStateViewProjection,\n): string {\n const serverVersionColumn = resolveServerVersionColumnName(entry);\n\n if (!serverVersionColumn) {\n throw new Error(\n `writable table ${getTableConfig(entry.table).name} has no Server version; cannot build the sync-state view (ADR-0011)`,\n );\n }\n\n const pkColumns = [...entry.primaryKey.columns];\n const quotedVersion = quoteIdentifier(serverVersionColumn);\n const keyColumnList = pkColumns.map((column) => quoteIdentifier(column)).join(\", \");\n const keySelectList = pkColumns.map((column) => `k.${quoteIdentifier(column)}`).join(\",\\n \");\n\n const pkEquality = (left: string, right: string) =>\n pkColumns.map((column) => `${left}.${quoteIdentifier(column)} = ${right}.${quoteIdentifier(column)}`).join(\" AND \");\n\n // Decision 4: the SAME barrier the resolver's journal-clear DELETE uses. The view asks whether an\n // acked write is *not yet* resolved (`(barrier) IS NOT TRUE`) — NULL (no synced row) counts as\n // unobserved, exactly the create-with-no-echo case. One predicate string, two consumers.\n const barrier = buildOverlayResolutionBarrier(entry, { syncedAlias: \"synced\", journalAlias: \"journal\" });\n\n return [\n `SELECT`,\n ` ${keySelectList},`,\n ` synced.${quotedVersion} AS observed_server_version,`,\n ` j.acked_server_version,`,\n ` COALESCE(j.pending_count, 0) AS pending_count,`,\n ` COALESCE(j.has_acked_unobserved_write, FALSE) AS has_acked_unobserved_write,`,\n ` COALESCE(o.local_delete_pending, FALSE) AS local_delete_pending,`,\n ` j.conflict_state,`,\n ` COALESCE(j.quarantined_count, 0) AS quarantined_count,`,\n ` j.quarantine_state`,\n `FROM (`,\n ` SELECT DISTINCT ${keyColumnList} FROM ${projection.journalTable}`,\n ` UNION`,\n ` SELECT DISTINCT ${keyColumnList} FROM ${projection.overlayTable}`,\n `) AS k`,\n `LEFT JOIN ${projection.syncedTable} AS synced ON ${pkEquality(\"synced\", \"k\")}`,\n `LEFT JOIN LATERAL (`,\n ` SELECT`,\n ` MAX(journal.server_updated_at_us) FILTER (WHERE journal.status = 'acked') AS acked_server_version,`,\n ` COUNT(*) FILTER (WHERE journal.status IN ('pending', 'sending', 'failed')) AS pending_count,`,\n ` COALESCE(bool_or(`,\n ` journal.status = 'acked'`,\n ` AND journal.mutation_kind <> 'delete'`,\n ` AND journal.server_updated_at_us IS NOT NULL`,\n ` AND (${barrier}) IS NOT TRUE`,\n ` ), FALSE) AS has_acked_unobserved_write,`,\n ` MAX(journal.conflict_reason) FILTER (WHERE journal.status = 'conflicted') AS conflict_state,`,\n ` COUNT(*) FILTER (WHERE journal.status = 'quarantined') AS quarantined_count,`,\n ` MAX(journal.last_error) FILTER (WHERE journal.status = 'quarantined') AS quarantine_state`,\n ` FROM ${projection.journalTable} AS journal`,\n ` WHERE ${pkEquality(\"journal\", \"k\")}`,\n `) AS j ON TRUE`,\n `LEFT JOIN LATERAL (`,\n ` SELECT bool_or(overlay.overlay_kind = 'pending_delete') AS local_delete_pending`,\n ` FROM ${projection.overlayTable} AS overlay`,\n ` WHERE ${pkEquality(\"overlay\", \"k\")}`,\n `) AS o ON TRUE`,\n ].join(\"\\n\");\n}\n\n/**\n * The event model the Convergence model implements (ADR-0011). The per-entity convergence state is\n * **derived** from synced + overlay + journal — never a mutated row — so this table is the spec the\n * derivation answers to, not a state machine that is stepped. Exported so a test can assert the\n * implemented derivation covers every event.\n */\nexport const CONVERGENCE_EVENTS = [\n {\n event: \"local create/update/delete enqueued\",\n effect: \"overlay upserted; a journal mutation appended (records base server version for ADR-0015)\",\n },\n { event: \"mutation sent\", effect: \"journal row → sending\" },\n {\n event: \"mutation acked\",\n effect:\n \"journal row → acked, server_updated_at_us stamped; entity shows acked_unobserved until the echo catches up\",\n },\n {\n event: \"synced upsert observed\",\n effect: \"synced row applied; the barrier predicate runs; resolved entities clear overlay + acked journal\",\n },\n {\n event: \"synced delete observed\",\n effect: \"resolved by synced-row absence (deletes carry no Server version — ADR-0010)\",\n },\n { event: \"resolution\", effect: \"clear overlay/journal only through the shared barrier predicate (decision 4)\" },\n { event: \"conflict detected\", effect: \"conflict_state recorded on the journal row (ADR-0015); surfaced in the view\" },\n {\n event: \"mutation quarantined\",\n effect:\n \"journal row → quarantined (terminal, ADR-0006), overlay kept; surfaced as quarantined_count/quarantine_state\",\n },\n {\n event: \"shape must-refetch\",\n effect: \"subscription reset + re-stream; affected entity state re-derives from the fresh synced rows\",\n },\n] as const;\n",
10
+ "import type { AnyColumn, ColumnBuilderBase, InferInsertModel, InferSelectModel } from \"drizzle-orm\";\nimport {\n bigint,\n getTableConfig,\n pgTable,\n pgView,\n primaryKey as pgPrimaryKey,\n PrimaryKeyBuilder,\n type AnyPgColumn,\n type AnyPgTable,\n type PgBigInt64Builder,\n type PgBuildColumns,\n type PgBuildExtraConfigColumns,\n type PgPolicy,\n type PgTableExtraConfigValue,\n type PgTableWithColumns,\n type PgVarcharBuilder,\n type PgView,\n type PgViewWithSelection,\n type SetNotNull,\n} from \"drizzle-orm/pg-core\";\nimport type { pgSchema } from \"drizzle-orm/pg-core\";\nimport { varchar } from \"drizzle-orm/pg-core\";\nimport type { ExtractTablesWithRelations } from \"drizzle-orm/relations\";\nimport { getColumns } from \"drizzle-orm/utils\";\n\nimport { type ApplyStrategy, classifyApplyStrategy, type SyncColumnType } from \"./apply-strategy\";\nimport {\n CONFLICT_POLICIES,\n isConflictPolicy,\n isRetention,\n isStorageBackend,\n isStorageDurability,\n isSubscriptionTiming,\n isWriteMode,\n assertShapeFilterIsEnforceable,\n readShapeTier,\n RETENTIONS,\n STORAGE_BACKENDS,\n STORAGE_DURABILITIES,\n SUBSCRIPTION_TIMINGS,\n WRITE_MODES,\n type ClientProjectionSpec,\n type ConflictPolicy,\n type DeferrableConstraintSpec,\n type ManagedFieldApplyOn,\n type ManagedFieldSpec,\n type ManagedFieldStrategy,\n type PrimaryKeySpec,\n type Retention,\n type RowFilterSpec,\n type ServerProjectionSpec,\n type ShapeSpec,\n type ShapeSpecInput,\n type SubscriptionTiming,\n type SyncStorageDeclaration,\n type TableGovernanceSpec as TableGovernanceSpecBase,\n type TableMode,\n type WriteMode,\n} from \"./config\";\nimport {\n EVENT_STREAM_NAME_MAX_LENGTH,\n EVENT_STREAM_NAME_PATTERN,\n EVENT_STREAM_QUEUE_PREFIX,\n hasNonStrictObjectRoot,\n isZodSchema,\n type EventStreamRegistry,\n} from \"./event-stream\";\nimport type { Predicate } from \"./predicate\";\n\ntype PgSchemaType = ReturnType<typeof pgSchema>;\n\n// PgView's parameters all default to their upper bounds, so the bare name\n// covers any pg view instance.\ntype AnyPgView = PgView;\n\ntype TableColumnsShape<TTable extends AnyPgTable> = TTable extends {\n _: {\n columns: infer TColumns;\n };\n}\n ? TColumns\n : never;\n\nexport type TableColumnKey<TTable extends AnyPgTable> = Extract<keyof TableColumnsShape<TTable>, string>;\n\nexport type DeferrableConstraintSpecForTable<TTable extends AnyPgTable> = Omit<DeferrableConstraintSpec, \"columns\"> & {\n columns: Array<TableColumnKey<TTable>>;\n};\n\nexport type ManagedFieldSpecForTable<TTable extends AnyPgTable> = Omit<ManagedFieldSpec, \"column\"> & {\n column: TableColumnKey<TTable>;\n};\n\nexport interface ResolvedManagedFieldSpecForTable<TTable extends AnyPgTable> {\n column: TableColumnKey<TTable>;\n applyOn: ManagedFieldApplyOn[];\n strategy: ManagedFieldStrategy;\n}\n\nexport type ClientProjectionSpecForTable<TTable extends AnyPgTable> = Omit<ClientProjectionSpec, \"omitColumns\"> & {\n omitColumns?: readonly TableColumnKey<TTable>[];\n};\n\nexport interface ProjectedTableColumn<TTable extends AnyPgTable = AnyPgTable> {\n propertyKey: TableColumnKey<TTable>;\n columnName: string;\n column: ReturnType<typeof getColumns<AnyPgTable>>[string];\n}\n\nexport type TableGovernanceSpecForTable<TTable extends AnyPgTable> = Omit<\n TableGovernanceSpecBase,\n \"deferrableConstraints\" | \"managedFields\"\n> & {\n deferrableConstraints?: Array<DeferrableConstraintSpecForTable<TTable>>;\n managedFields?: Array<ManagedFieldSpecForTable<TTable>>;\n};\n\ndeclare const syncTableInputGovernanceSymbol: unique symbol;\n\ntype SyncTableInputGovernanceMarker<TGovernance> = {\n [syncTableInputGovernanceSymbol]?: TGovernance;\n};\n\nexport interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTable extends AnyPgTable = TTable> {\n table: TTable;\n /**\n * Projected client-side table for PGlite use. Columns listed in\n * `clientProjection.omitColumns` (e.g. `created_by_id`) are absent from\n * both the runtime table definition and the TypeScript shape of this table.\n */\n localTable: TLocalTable;\n // `| undefined` (with exactOptionalPropertyTypes) admits `defineSyncTable`'s ALWAYS-PRESENT `view`\n // key, whose value is undefined for entries without a read model — see the entry construction.\n view?: AnyPgView | undefined;\n mode: TableMode;\n primaryKey: PrimaryKeySpec;\n /**\n * **Backfill** conflict policy (ADR-0045). Resolved to `\"insert\"` when omitted.\n *\n * This no longer selects how steady-state changes apply. The engine emits `upsert`, which states a\n * row's value without claiming it is new, so every streamed change now applies as `INSERT … ON\n * CONFLICT (pk) DO UPDATE` regardless of this setting. ADR-0014's plain-INSERT collision surfacing\n * went with the `insert` verb it depended on.\n *\n * What survives is the **initial load**, which is a different question: a fresh subscription or a\n * post-must-refetch re-snapshot lands on a table assumed empty, which is what lets it use COPY or a\n * plain multi-row INSERT — neither of which can express `ON CONFLICT`. Set `\"upsert\"` when that\n * assumption does not hold for this table, i.e. it legitimately receives locally-DERIVED provisional\n * rows (e.g. a local trigger on another synced table inserts one here) that a backfill could meet.\n * The backfill then takes the conflict-tolerant applier instead, at the cost of the faster path.\n */\n applyMode: \"insert\" | \"upsert\";\n /**\n * Consumer-defined ROW CLASSIFICATION (ADR-0052) — documentation-as-code for what KIND of rows this\n * entry carries. The vocabulary is entirely the CONSUMER's: pgxsinkit defines no values and attaches no\n * behaviour to any of them. Its two jobs:\n *\n * - **Fail-closed enumeration.** When the registry declares its vocabulary\n * ({@link SyncRegistryDefinition.rowClasses}), EVERY entry must carry a `rowClass` drawn from that set —\n * validated at `defineSyncRegistry`, i.e. at module eval. A new entry therefore cannot join the registry\n * without its author classifying it, which is what stops a privacy/visibility obligation from being\n * silently inherited by tables nobody remembered to enumerate.\n * - **The binding key for {@link assertRegistryInvariant}.** An invariant binds to `rowClass` values\n * rather than to a hand-maintained table list, so coverage grows with the registry instead of drifting\n * behind it.\n *\n * When the registry declares no `rowClasses`, this field is unconstrained (any string, or none). It is\n * authoring metadata only: it is deliberately absent from the registry fingerprint and the read-contract\n * fingerprint, so classifying a table never shifts a persisted cache key (ADR-0052).\n */\n rowClass?: string;\n shape?: ShapeSpec;\n clientProjection?: ClientProjectionSpecForTable<TTable>;\n serverProjection?: ServerProjectionSpec;\n governance?: TableGovernanceSpecForTable<TTable>;\n /**\n * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable\n * tables** (registry validation rejects an undeclared one — the third hard-require); ignored for\n * `readonly` tables (they have no write path). See {@link ConflictPolicy}.\n */\n conflictPolicy?: ConflictPolicy;\n /**\n * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced as one set\n * of streams and committed atomically — held until every stream reports up-to-date, then applied in\n * one transaction (ADR-0056) — so a local reader never sees one grouped table advanced past another\n * for the same server transaction. Omitted → the table is its own singleton group (its own stream, no\n * cross-table atomicity — the resolution for a table that declares no group). The latency cost (a\n * group advances only as fast as its slowest shape) is contained to the tables that opt in.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021): `eager` (default) | `lazy`. A `lazy` table is excluded from the\n * boot subscription set and subscribed on first query-reference. A property of the **consistency\n * group** — every table sharing a `consistencyGroup` must agree (validated). See\n * {@link SubscriptionTiming}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021): `persistent` (default) | `ephemeral`. An `ephemeral` table's whole local\n * cluster is emitted as `TEMP` — no durable trace, no durable offline write queue. A property of the\n * consistency group — every table sharing a `consistencyGroup` must agree (validated). See\n * {@link Retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. A `pessimistic` consistency group is a\n * standing server-authoritative write-unit — its writes flush-route to the authoritative endpoint and\n * the UI shows success only after the server confirms. Write-mode is a property of the **write-unit**;\n * the static write-unit is the consistency group, so every table sharing a `consistencyGroup` must agree\n * (validated). See {@link WriteMode}.\n */\n writeMode?: WriteMode;\n /**\n * True when this entry is a read PROJECTION over a table OWNED by another entry (built by\n * {@link defineReadProjection}). Such an entry owns no physical table — its `table` is the owner's,\n * and only its `localTable` + `shape` are its own — so migration/apply/RLS generation skips it and a\n * consumer's schema barrel must never export a fresh table for it. Absent → the entry owns its table.\n */\n readProjection?: boolean;\n /**\n * The column-builder factory that produced this entry's table (set by {@link defineSyncTable}).\n * Retained so {@link defineReadProjection} can reuse the owner's column definitions to build a typed\n * column subset without restating them, AND — since ADR-0029 P1 — so the client can derive every\n * synced-table object (the local synced read cache, overlay, journal) via\n * `getSyncedLocalTable` → `projectedColumnBuilders`. It is therefore read-derivation machinery, not a\n * write handle: it is carried through every projection ({@link asReadonly}, `withRetention`,\n * `defineReadProjection`), NOT fingerprinted (functions are invisible to the read-contract hash), and\n * required on every registered entry — `defineSyncRegistry`/`validateSyncTableEntry` reject a\n * hand-assembled entry that lacks it, since the client hard-requires it at boot.\n */\n makeColumns?: () => Record<string, ColumnBuilderBase>;\n}\n\n/** Column property key names from a `makeColumns` factory function. */\ntype ColumnKeys<TColumns extends Record<string, ColumnBuilderBase>> = keyof TColumns & string;\n\ntype ProjectedColumnsShape<\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = ColumnKeys<TColumns> extends TOmittedColumns[number] ? TColumns : Omit<TColumns, TOmittedColumns[number]>;\n\n// Explicit shapes for the projected local table and the read-model view.\n// Their drizzle-inferred types cannot survive declaration emit: the printer\n// reproduces pgTable/pgView internals as `PgBuildColumn<TTableName, ...>` with\n// drizzle's own out-of-scope generic, breaking the published .d.ts. The\n// constructed values are cast to these equivalent, printable types instead.\ntype ProjectedLocalTable<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = PgTableWithColumns<{\n name: TName;\n schema: string | undefined;\n columns: PgBuildColumns<TName, ProjectedColumnsShape<TColumns, TOmittedColumns>>;\n dialect: \"pg\";\n}>;\n\n/**\n * The local table TYPE for a {@link defineReadProjection} entry: the OWNER's already-built columns\n * (`TableColumnsShape<TOwnerTable>`) restricted to the kept keys (`TKeptKey`), under the projection's own\n * local name (`TAs`).\n *\n * Why this exists rather than reusing the inner `defineSyncTable`'s `localTable` type: a projection\n * rebuilds its columns from the owner's stashed `makeColumns`, but {@link SyncTableEntry.makeColumns} is\n * type-erased to `() => Record<string, ColumnBuilderBase>`, so a `localTable` inferred through it collapses\n * to an open index signature — forcing bracket-access + `!` in consumers. Picking directly off\n * `TOwnerTable`'s real column types restores rename-safe, per-column typing.\n *\n * Sound by construction — never an over-claim: the runtime keeps `columns ∪ primaryKey`, a SUPERSET of\n * `TKeptKey`, so every typed column exists at runtime. A primary-key column not listed in `columns` is\n * kept at runtime but omitted from the type (a safe under-claim; include it in `columns` to type it).\n */\ntype ProjectionLocalTable<\n TOwnerTable extends AnyPgTable,\n TAs extends string,\n TKeptKey extends string,\n> = PgTableWithColumns<{\n name: TAs;\n schema: string | undefined;\n columns: Pick<TableColumnsShape<TOwnerTable>, TKeptKey & keyof TableColumnsShape<TOwnerTable>>;\n dialect: \"pg\";\n}>;\n\ntype ReadModelView<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = PgViewWithSelection<\n `${TName}_read_model`,\n true,\n PgBuildColumns<\n `${TName}_read_model`,\n ProjectedColumnsShape<TColumns, TOmittedColumns> & {\n overlay_kind: SetNotNull<PgVarcharBuilder<[string, ...string[]]>>;\n local_updated_at_us: SetNotNull<PgBigInt64Builder>;\n }\n >\n>;\n\n/** Governance spec for `defineSyncTable` — columns are typed from `makeColumns`. */\nexport type SyncTableInputGovernance<TColumns extends Record<string, ColumnBuilderBase>> = Omit<\n TableGovernanceSpecBase,\n \"deferrableConstraints\" | \"managedFields\"\n> & {\n deferrableConstraints?: Array<Omit<DeferrableConstraintSpec, \"columns\"> & { columns: Array<ColumnKeys<TColumns>> }>;\n managedFields?: Array<Omit<ManagedFieldSpec, \"column\"> & { column: ColumnKeys<TColumns> }>;\n};\n\n/** Projection spec for `defineSyncTable` — omitColumns typed from `makeColumns`. */\nexport type SyncTableInputProjection<\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n> = Omit<ClientProjectionSpec, \"omitColumns\"> & {\n omitColumns?: TOmittedColumns;\n};\n\n/**\n * A row filter for {@link defineSyncTable}'s `shape`, authored from the table's built, typed columns.\n * Reference columns through `c(columns.x)` exactly as `extras` does with its `self` argument, so\n * `customPredicate` builds the shape's predicate from real, rename-safe column objects instead\n * of hand-written column-name strings.\n */\nexport type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> = (\n columns: PgBuildExtraConfigColumns<TColumns>,\n) => RowFilterSpec;\n\n/**\n * The scope declaration for a SHARED-tier shape (ADR-0055), authored from the built, typed columns —\n * the columns whose values key the shape family, in the order they parameterize it.\n *\n * Returning real column objects rather than names is what makes the family rename-safe: a renamed\n * column moves the scope with it, where a string would have gone on naming a column that no longer\n * exists and silently produced a predicate over nothing.\n */\nexport type ScopeInput<TColumns extends Record<string, ColumnBuilderBase>> = (\n columns: PgBuildExtraConfigColumns<TColumns>,\n) => readonly AnyColumn[];\n\n/**\n * The static, subscriber-independent half of a shape's native predicate, authored from the built,\n * typed columns. Build it with {@link p} — `(c) => p.eq(c.published, true)`.\n */\nexport type ShapeWhereInput<TColumns extends Record<string, ColumnBuilderBase>> = (\n columns: PgBuildExtraConfigColumns<TColumns>,\n) => Predicate;\n\n/** {@link ShapeSpecInput} whose callbacks are authored from the built columns (typed by `TColumns`). */\nexport type ShapeSpecInputFor<TColumns extends Record<string, ColumnBuilderBase>> = Omit<\n ShapeSpecInput,\n \"rowFilter\" | \"scope\" | \"where\"\n> & {\n rowFilter?: RowFilterInput<TColumns>;\n scope?: ScopeInput<TColumns>;\n where?: ShapeWhereInput<TColumns>;\n};\n\n/**\n * Input for `defineSyncTable`. Supply `tableName + makeColumns` — the Drizzle table\n * (and, for `readwrite` mode, the read-model view) are created internally.\n *\n * Access the built objects via `.table` and `.view` on the returned entry.\n */\nexport type SyncTableInput<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n> = {\n tableName: TName;\n makeColumns: () => TColumns;\n /** RLS policies (or other table extras) attached to the Postgres table. */\n policies?: PgPolicy[];\n /**\n * Extra constraints or indexes on the server-side Postgres table (unique, index, etc.).\n * Receives the built column map — same signature as `pgTable`'s third argument.\n * Not applied to `localTable`.\n */\n extras?: (self: PgBuildExtraConfigColumns<TColumns>) => PgTableExtraConfigValue[];\n /** Place the table in this schema (e.g. for perf-lab schemed tables). */\n schema?: PgSchemaType;\n /** @default \"readonly\" */\n mode?: TableMode;\n /**\n * THE primary key of the server table — the single source of truth for its physical\n * `PRIMARY KEY` constraint. `defineSyncTable` emits it as the constraint, named\n * `` `${tableName}_pkey` `` (matching Postgres's inline-PK default, so existing consumer\n * databases see no rename churn) unless the object form overrides `name`.\n *\n * Defaults to `[\"id\"]`. Use an array with multiple entries for composite keys, or the object\n * form `{ name, columns }` to name the constraint.\n *\n * A single-column key MAY equivalently be declared via the column's own `.primaryKey()`\n * (idiomatic drizzle); it must match this spec, and emission is then skipped because the\n * column already carries the constraint. A table-level `primaryKey(...)` in `extras`/`policies`\n * is REJECTED — declare the key here instead.\n */\n primaryKey?: string[] | { name: string; columns: string[] };\n /**\n * **Backfill** conflict policy (ADR-0045). **Default `\"insert\"`** — the initial load assumes an empty\n * table (fresh subscription or post-must-refetch re-snapshot) and takes the fast path, COPY or a plain\n * multi-row INSERT, neither of which can express `ON CONFLICT`. Set `\"upsert\"` **only** when this table\n * legitimately receives locally-DERIVED provisional rows a backfill could land on top of — e.g. a local\n * trigger on another synced table inserts a provisional row here, and the server independently creates\n * the same row (23505). Steady-state changes are unaffected: the engine emits `upsert`, so they apply\n * as `INSERT … ON CONFLICT (pk) DO UPDATE` for every table. See {@link SyncTableEntry.applyMode}.\n */\n applyMode?: \"insert\" | \"upsert\";\n /**\n * Consumer-defined row classification (ADR-0052) — see {@link SyncTableEntry.rowClass}. Required (and\n * checked against the declared set) when the registry declares {@link SyncRegistryDefinition.rowClasses};\n * unconstrained otherwise.\n */\n rowClass?: string;\n shape?: ShapeSpecInputFor<TColumns>;\n clientProjection?: SyncTableInputProjection<TColumns, TOmittedColumns>;\n /** Server-side response-path projection (e.g. `rowTransform`). Server authority, not client shape. */\n serverProjection?: ServerProjectionSpec;\n governance?: SyncTableInputGovernance<TColumns>;\n /**\n * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable\n * tables** — `defineSyncTable`/`defineSyncRegistry` reject a writable table without one. See\n * {@link ConflictPolicy}.\n */\n conflictPolicy?: ConflictPolicy;\n /**\n * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync as one set of\n * streams and commit atomically. Omit for the default singleton group. See\n * {@link SyncTableEntry.consistencyGroup}.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021): `eager` (default) | `lazy`. See\n * {@link SyncTableEntry.subscription}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021): `persistent` (default) | `ephemeral`. See {@link SyncTableEntry.retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. See {@link SyncTableEntry.writeMode}.\n */\n writeMode?: WriteMode;\n};\n\nexport type SyncTableRegistry = Record<string, SyncTableEntry>;\n\nexport interface SyncRegistryDefinition<TRegistry extends SyncTableRegistry> {\n schema?: string;\n tables: TRegistry;\n /**\n * The storage contract for every store this registry mints (ADR-0049 decision 1, ADR-0047). Part of the\n * DATA contract, not a per-open knob: `durability` binds every toolkit-minted open (relaxed default),\n * and `backend` scopes the BROWSER store only (`opfs` default; Node/`file` and `memory` clones\n * unaffected). Validated at {@link defineSyncRegistry} (fail-closed at module-eval); carried through on\n * the returned registry and read back with {@link getSyncRegistryStorage}. See {@link SyncStorageDeclaration}.\n */\n storage?: SyncStorageDeclaration;\n /**\n * The registry's CLOSED row-classification vocabulary (ADR-0052) — the consumer's own set of\n * {@link SyncTableEntry.rowClass} values (pgxsinkit defines none). Declaring it turns classification into\n * a fail-closed obligation: EVERY entry must then carry a `rowClass` drawn from this exact set, validated\n * at {@link defineSyncRegistry} (module eval), so a newly added entry cannot join the registry\n * unclassified and silently escape whatever invariants its class enrols it in. The declared set is carried\n * on the returned registry and read back with {@link getSyncRegistryRowClasses}, which\n * {@link assertRegistryInvariant} uses to reject a misspelled class in an invariant's `appliesTo`.\n *\n * Omit it and `rowClass` is unconstrained (the bare-registry-map overload has nowhere to declare a set, so\n * it is always unconstrained). Purely authoring metadata: it never enters the registry fingerprint.\n */\n rowClasses?: readonly string[];\n /**\n * The registry's **Event streams** (ADR-0053 decision 1) — the Event lane's registration surface, keyed by\n * Event-stream NAME (the record key IS the name; {@link defineEventStream} declares the entry). Registration\n * lives here rather than in a parallel artifact so there is ONE contract to lock, diff and thread through\n * `createSyncServer` and `defineSyncWorker`.\n *\n * Validated fail-closed at {@link defineSyncRegistry} (module eval, every offender named at once): the name\n * must match `[a-z][a-z0-9_]*` and fit the pgmq queue-name budget, the payload must be a zod schema, and each\n * identity field must name a non-empty claim path. Carried on the returned registry and read back with\n * {@link getSyncRegistryStreams}.\n *\n * Streams follow the `rowClasses` precedent: they ride the registry LOCK as a sibling (added → `compatible`,\n * removed → `breaking`, payload/identity changed → `risky`) and stay OUT of the canonical fingerprint — an\n * Event stream touches no synced table, no local schema and no apply function, so registering one must never\n * wipe a store's read cache. The bare-registry-map overload has nowhere to declare streams.\n */\n streams?: EventStreamRegistry;\n}\n\nexport const syncRegistrySchemaSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistrySchema\");\n\nexport const syncRegistryStorageSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistryStorage\");\n\nexport const syncRegistryRowClassesSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistryRowClasses\");\n\nexport const syncRegistryStreamsSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistryStreams\");\n\nexport type RegistryTables<TRegistry extends SyncTableRegistry> = {\n [TKey in keyof TRegistry]: TRegistry[TKey][\"table\"];\n};\n\nexport type RegistryViews<TRegistry extends SyncTableRegistry> = {\n [TKey in keyof TRegistry as TRegistry[TKey] extends { view: AnyPgView } ? TKey : never]: NonNullable<\n TRegistry[TKey][\"view\"]\n >;\n};\n\nexport type RegistryRelations<TRegistry extends SyncTableRegistry> = ExtractTablesWithRelations<\n {},\n RegistryTables<TRegistry>\n>;\n\nexport type SyncTableName<TRegistry extends SyncTableRegistry> = keyof TRegistry & string;\n\ntype GovernanceShapeForEntry<TEntry> =\n TEntry extends SyncTableInputGovernanceMarker<infer TGovernance>\n ? TGovernance\n : TEntry extends { governance?: infer TGovernance }\n ? TGovernance\n : never;\n\ntype ManagedFieldColumnKeysForOperation<TEntry, TOperation extends ManagedFieldApplyOn> =\n GovernanceShapeForEntry<TEntry> extends {\n managedFields?: ReadonlyArray<infer TField>;\n }\n ? TField extends {\n column: infer TColumn extends string;\n applyOn: ReadonlyArray<ManagedFieldApplyOn>;\n }\n ? TOperation extends TField[\"applyOn\"][number]\n ? TColumn\n : never\n : never\n : never;\n\n/**\n * EVERY managed column key, whatever its `applyOn` — the omit set for {@link SyncTableUpdateInput}.\n * `ManagedFieldApplyOn` is a union and the operation parameter is naked, so the conditional distributes\n * and a field managed on either operation contributes its key.\n *\n * The **type-level twin** of {@link isManagedFieldGuarded} at `\"update\"`: same rule, stated where the\n * compiler can enforce it. Change one only by changing the rule in {@link isManagedFieldGuarded}.\n */\ntype ManagedFieldColumnKeys<TEntry> = ManagedFieldColumnKeysForOperation<TEntry, ManagedFieldApplyOn>;\n\n/**\n * Whether a managed field is **SERVER-OWNED** for an operation — the ONE definition of the guard rule,\n * so the surfaces that enforce it cannot drift apart:\n *\n * - **create** ⇒ the field is guarded when its `applyOn` includes `\"create\"`. The server stamps it after\n * validation, so a client value for it is never honoured.\n * - **update** ⇒ **every** managed field is guarded, a **create-only** one included. An update-managed\n * field is stamped by the server on every write; a `applyOn: [\"create\"]` field is stamped at birth and\n * **inert** on update (the generated apply function offers no UPDATE SET candidate for it). Neither is\n * ever a settable update key, so both are flagged, stripped, and omitted rather than left for consumer\n * RLS to neutralise.\n * - **delete** ⇒ none. A delete carries no payload, so nothing can be owned.\n *\n * \"Guarded\" is NOT \"stamped\": stamping is operation-scoped (`applyOn.includes(operation)`) and decides\n * what the applier writes; guarding decides what a client may not send. They coincide on create and\n * deliberately diverge on update.\n *\n * The consuming surfaces, all of which must go through this predicate:\n * - the write route's `getGuardedManagedFields` (`packages/server/src/mutations/route.ts`) — the 400\n * violation check, the sanitizer, and the create/update validation schemas;\n * - the client's `stripManagedFields` (`packages/client/src/mutation.ts`) — the outgoing-payload strip;\n * - the apply-function generator's `buildTableBranch` (`packages/server/src/mutations/plpgsql-apply.ts`) —\n * the INSERT/UPDATE candidate-column exclusions;\n * - {@link ManagedFieldColumnKeys} / `ManagedFieldColumnKeysForOperation` — the type-level twin behind\n * {@link SyncTableCreateInput} / {@link SyncTableUpdateInput}.\n */\nexport function isManagedFieldGuarded(\n field: { applyOn: readonly ManagedFieldApplyOn[] },\n operation: \"create\" | \"update\" | \"delete\",\n): boolean {\n switch (operation) {\n case \"create\":\n return field.applyOn.includes(\"create\");\n case \"update\":\n return true;\n case \"delete\":\n return false;\n }\n}\n\nexport type SyncTableCreateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>\n ? Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], \"create\">>\n : never;\n\n/**\n * The patch type for an update: the insert model made partial, minus **every** managed key — including\n * a **create-only** one. A field declared `applyOn: [\"create\"]` is stamped at birth and inert on update\n * (the generated apply function offers no UPDATE SET candidate for it), so it is never a settable update\n * key; the write route 400-rejects an update payload that carries one. This omit set is the type-level\n * statement of {@link isManagedFieldGuarded} at `\"update\"` — that predicate is the single definition of\n * the rule, and every runtime surface derives from it.\n */\nexport type SyncTableUpdateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>\n ? Partial<Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeys<TRegistry[TKey]>>>\n : never;\n\nexport type SyncTableRecord<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<infer TTable extends AnyPgTable, AnyPgTable>\n ? InferSelectModel<TTable>\n : never;\n\n/**\n * Filters a columns object, omitting keys in `omitSet`, while preserving TypeScript column types.\n * When `omitSet` is empty the original object is returned unchanged (no copy, no type loss).\n */\nfunction viewColumnsForProjection<\n TColumns extends Record<string, ColumnBuilderBase>,\n const TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n>(columns: TColumns, omittedColumns: TOmittedColumns): ProjectedColumnsShape<TColumns, TOmittedColumns> {\n if (omittedColumns.length === 0) {\n return columns as ProjectedColumnsShape<TColumns, TOmittedColumns>;\n }\n\n const omitSet = new Set<string>(omittedColumns);\n return Object.fromEntries(Object.entries(columns).filter(([key]) => !omitSet.has(key))) as ProjectedColumnsShape<\n TColumns,\n TOmittedColumns\n >;\n}\n\n/**\n * Defines a sync table entry. Provide `tableName` and `makeColumns` — the Drizzle\n * `pgTable` (and, for `readwrite` mode, the `_read_model` view) are created here.\n *\n * Access the built objects via `.table` and `.view` on the returned entry.\n */\nexport function defineSyncTable<\n const TName extends string,\n const TColumns extends Record<string, ColumnBuilderBase>,\n const TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n const TGovernance extends SyncTableInputGovernance<TColumns> | undefined = undefined,\n // The mode LITERAL, so the entry's `view` type can be conditional on it: readwrite entries carry a\n // typed ReadModelView, everything else carries undefined — which is what lets `RegistryViews`\n // (and so `client.views`) keep exactly the read-model entries at the type level.\n const TMode extends TableMode = \"readonly\",\n>(\n input: Omit<SyncTableInput<TName, TColumns, TOmittedColumns>, \"governance\" | \"mode\"> & {\n governance?: TGovernance;\n /** @default \"readonly\" */\n mode?: TMode;\n },\n) {\n const {\n tableName,\n makeColumns,\n policies,\n extras,\n schema,\n mode,\n primaryKey,\n applyMode,\n governance,\n clientProjection,\n serverProjection,\n shape,\n ...otherRest\n } = input;\n\n const resolvedMode: TableMode = mode ?? \"readonly\";\n\n // The `primaryKey` spec is the SINGLE SOURCE OF TRUTH for the server table's physical PRIMARY KEY.\n // It was runtime-only metadata until a consumer (transcrobes) had drizzle-kit DROP a composite PK\n // from a live DB because nothing re-declared it in DDL — so `defineSyncTable` now emits the\n // constraint itself. The default constraint name `${tableName}_pkey` matches Postgres's inline-PK\n // naming, so existing consumer databases see no rename churn; the object form overrides it.\n const primaryKeyColumns = Array.isArray(primaryKey) ? primaryKey : (primaryKey?.columns ?? [\"id\"]);\n const resolvedPrimaryKey: PrimaryKeySpec = { columns: primaryKeyColumns };\n\n // ADR-0045: default to the strict `\"insert\"` policy (a CDC insert is a plain INSERT — a genuine PK\n // collision must surface). Only tables that legitimately receive locally-derived provisional rows opt\n // into idempotent `\"upsert\"` apply of server CDC inserts.\n const resolvedApplyMode: \"insert\" | \"upsert\" = applyMode ?? \"insert\";\n const customPrimaryKeyName = !Array.isArray(primaryKey) ? primaryKey?.name : undefined;\n const primaryKeyConstraintName = customPrimaryKeyName ?? `${tableName}_pkey`;\n\n // Probe the columns (no extras — cheap) to detect idiomatic column-level `.primaryKey()` flags and\n // to resolve each spec column to its PROPERTY KEY (spec entries may be given as the SQL column name\n // or the property key, matching the omitColumns precedent below).\n const probeColumns = getColumns(pgTable(tableName, makeColumns())) as Record<string, AnyPgColumn>;\n const columnLevelPkKeys = Object.entries(probeColumns)\n .filter(([, col]) => col.primary === true)\n .map(([key]) => key);\n const toPropertyKey = (key: string, label: string) => {\n if (probeColumns[key]) return key;\n const byColumnName = Object.entries(probeColumns).find(([, col]) => col.name === key);\n if (byColumnName) return byColumnName[0];\n throw new Error(`[pgxsinkit] ${tableName}: ${label} column \"${key}\" not found among the table's columns`);\n };\n const specPropertyKeys = primaryKeyColumns.map((key) => toPropertyKey(key, \"primaryKey\"));\n\n if (columnLevelPkKeys.length > 1) {\n throw new Error(\n `[pgxsinkit] ${tableName}: multiple columns declare .primaryKey() (${columnLevelPkKeys.join(\", \")}) — declare a composite key via the primaryKey option ({ name?, columns }) and remove the column-level .primaryKey() flags; the spec is the single source of truth`,\n );\n }\n if (columnLevelPkKeys.length === 1) {\n const columnLevelPkKey = columnLevelPkKeys[0]!;\n if (specPropertyKeys.length !== 1 || specPropertyKeys[0] !== columnLevelPkKey) {\n throw new Error(\n `[pgxsinkit] ${tableName}: column \"${columnLevelPkKey}\" declares .primaryKey() but the primaryKey spec is [${resolvedPrimaryKey.columns.join(\", \")}] — they must match; the spec is the single source of truth`,\n );\n }\n if (customPrimaryKeyName != null && customPrimaryKeyName !== `${tableName}_pkey`) {\n throw new Error(\n `[pgxsinkit] ${tableName}: a custom primary-key name (\"${customPrimaryKeyName}\") requires defineSyncTable to emit the constraint — remove .primaryKey() from column \"${columnLevelPkKey}\" so the named constraint can be emitted`,\n );\n }\n }\n const emitPrimaryKey = columnLevelPkKeys.length === 0;\n\n const resolvedClientProjection =\n resolvedMode !== \"writeonly\" || clientProjection != null\n ? {\n ...(clientProjection ?? {}),\n syncedTable: clientProjection?.syncedTable ?? tableName,\n ...(resolvedMode === \"readwrite\"\n ? {\n overlayTable: clientProjection?.overlayTable ?? `${tableName}_overlay`,\n journalTable: clientProjection?.journalTable ?? `${tableName}_mutations`,\n }\n : {}),\n }\n : undefined;\n\n const extrasFn =\n policies || extras || emitPrimaryKey\n ? (self: PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>) => {\n const consumerExtras = [...(policies ?? []), ...(extras ? extras(self) : [])];\n for (const extra of consumerExtras) {\n if (extra instanceof PrimaryKeyBuilder) {\n throw new Error(\n `[pgxsinkit] ${tableName}: declare the primary key via the primaryKey option (string[] or { name, columns }), not a primaryKey(...) extra — the spec is the single source of truth and defineSyncTable emits the constraint`,\n );\n }\n }\n if (!emitPrimaryKey) return consumerExtras;\n const selfCols = self as unknown as Record<string, AnyPgColumn>;\n const pkColumns = specPropertyKeys.map((k) => selfCols[k]!) as [AnyPgColumn, ...AnyPgColumn[]];\n return [...consumerExtras, pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];\n }\n : undefined;\n const table = schema ? schema.table(tableName, makeColumns(), extrasFn) : pgTable(tableName, makeColumns(), extrasFn);\n\n // Resolve `shape.rowFilter` against the built typed columns so all authoring uses rename-safe\n // Drizzle column objects rather than hand-written column-name strings.\n const shapeColumns = getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>;\n const resolvedRowFilter = shape?.rowFilter?.(shapeColumns);\n const resolvedScope = shape?.scope?.(shapeColumns).map((column) => column.name);\n const resolvedWhere = shape?.where?.(shapeColumns);\n const resolvedShape: ShapeSpec | undefined =\n resolvedMode !== \"writeonly\" || shape != null\n ? {\n tableName: shape?.tableName ?? tableName,\n shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,\n // `physicalTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its\n // own table. It is filled by `attachSyncRegistrySchema` (schema qualification) or by\n // `defineReadProjection` (which points a projection at the owning physical table).\n ...(resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {}),\n ...(resolvedScope != null ? { scope: resolvedScope } : {}),\n ...(resolvedWhere != null ? { where: resolvedWhere } : {}),\n }\n : undefined;\n\n // Read the tier for its side effect: a shape declaring both `scope` and `rowFilter` is refused\n // HERE, at definition time, rather than at the first shape creation — the two are contradictory\n // by construction, so there is no input for which it could later turn out to be fine.\n if (resolvedShape != null) {\n readShapeTier(resolvedShape);\n assertShapeFilterIsEnforceable(resolvedShape);\n }\n\n const omittedColumns = (clientProjection?.omitColumns ?? []) as TOmittedColumns;\n const projectedCols = viewColumnsForProjection(makeColumns(), omittedColumns);\n\n // The local synced table carries its OWN primary key, mirroring exactly what the local-schema\n // generator emits for it (`getLocalSyncPrimaryKeyColumns` → `buildTableColumnSql`) — including a\n // `clientProjection.localPrimaryKey` narrowing, where the server's key columns may not even be\n // projected. Stating it here keeps the drizzle object and the physical table in agreement; a\n // localTable that claimed no key while its table had one stayed invisible only while the apply path\n // was a plain INSERT plus `UPDATE … WHERE pk`, and became a 42P10 the moment anything said\n // `ON CONFLICT (pk)` (ADR-0058 decision 3). Skipped when a single column already carries the flag\n // itself, since drizzle would then render two primary keys.\n const localPkPropertyKeys = (clientProjection?.localPrimaryKey?.columns ?? primaryKeyColumns).map((key) =>\n toPropertyKey(key, \"localPrimaryKey\"),\n );\n const localPkIsColumnLevel =\n localPkPropertyKeys.length === 1 && probeColumns[localPkPropertyKeys[0]!]?.primary === true;\n const localExtrasFn = localPkIsColumnLevel\n ? undefined\n : (self: PgBuildExtraConfigColumns<Record<string, ColumnBuilderBase>>) => {\n const selfCols = self as unknown as Record<string, AnyPgColumn>;\n const pkColumns = localPkPropertyKeys.map((k) => selfCols[k]!) as [AnyPgColumn, ...AnyPgColumn[]];\n return [pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];\n };\n const localTable = (\n schema\n ? schema.table(tableName, projectedCols, localExtrasFn as never)\n : pgTable(tableName, projectedCols, localExtrasFn as never)\n ) as ProjectedLocalTable<TName, TColumns, TOmittedColumns>;\n\n const viewColumns = viewColumnsForProjection(makeColumns(), omittedColumns);\n const view =\n resolvedMode === \"readwrite\"\n ? (pgView(`${tableName}_read_model`, {\n ...viewColumns,\n overlay_kind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n local_updated_at_us: bigint(\"local_updated_at_us\", { mode: \"bigint\" }).notNull(),\n }).existing() as ReadModelView<TName, TColumns, TOmittedColumns>)\n : undefined;\n\n const entry = {\n ...otherRest,\n mode: resolvedMode,\n primaryKey: resolvedPrimaryKey,\n applyMode: resolvedApplyMode,\n ...(resolvedShape != null ? { shape: resolvedShape } : {}),\n // The input specs are typed over the builder columns map (keys of\n // TColumns); the entry fields demand specs typed over the built table.\n // The key sets are equal by construction (BuildColumns preserves keys),\n // but that equality is unprovable while TColumns is an open generic.\n ...(governance != null ? { governance: governance as TableGovernanceSpecForTable<typeof table> } : {}),\n ...(resolvedClientProjection != null\n ? { clientProjection: resolvedClientProjection as unknown as ClientProjectionSpecForTable<typeof table> }\n : {}),\n ...(serverProjection != null ? { serverProjection } : {}),\n table,\n localTable,\n // ALWAYS a present key, typed by the mode literal. A conditional spread here would infer `view`\n // as an OPTIONAL property, and RegistryViews' `extends { view: AnyPgView }` filter would then\n // reject every entry — `client.views` typed as `{}` for all consumers while runtime worked\n // (caught by the packed fixture's consumer typecheck, ADR-0037 §4). Runtime `entry.view != null`\n // checks are unaffected by a present-undefined key, and the registry fingerprint canonicalizes\n // named fields, never raw entry keys.\n view: view as TMode extends \"readwrite\" ? ReadModelView<TName, TColumns, TOmittedColumns> : undefined,\n // Retained so `defineReadProjection` can reuse these column definitions for a typed subset.\n makeColumns: makeColumns as () => Record<string, ColumnBuilderBase>,\n };\n validateSyncTableEntry(entry as unknown as SyncTableEntry<AnyPgTable>);\n return entry as typeof entry & SyncTableInputGovernanceMarker<TGovernance>;\n}\n\n/**\n * Define a **read projection**: a second client shape over a table an `owner` entry already owns. The\n * projection reads the SAME physical rows under a DISTINCT local identity (`as`) and its own narrower\n * shape — a typed column subset and/or an admin/role-scoped `rowFilter` — without owning, migrating, or\n * RLS-guarding any new table. The first use is a light admin view of a heavy authoring table (titles,\n * not the jsonb), while the learner keeps reading the full table through the owner's shape.\n *\n * It is the *obvious, DRY* way to express \"another shape over this table\", versus the bare\n * `shape.physicalTable` string it replaces (a footgun — config that silently un-asserts table\n * ownership):\n *\n * - **Owns nothing.** The returned entry's `table` IS `owner.table` (the same object), so there is no\n * new `pgTable` to migrate or to leak into a drizzle-kit schema barrel. Only `localTable` (named `as`)\n * and `shape` are its own. `readProjection` is set so generators skip it.\n * - **DRY columns.** `columns` is a typed subset of the owner's column keys; the local table is built by\n * filtering the owner's own column definitions (never restated), and the same subset becomes the\n * shape's `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The\n * primary key is always kept. Omit `columns` to sync every column.\n * - **Source is derived, never named.** The physical source table is taken from the owner — there is\n * no consumer-facing source field to get wrong (see {@link ShapeSpec.physicalTable}).\n * - **Readonly.** A projection has no write path; the control plane resolves an incoming subscription by\n * its unique `shapeKey` (= `as`) and consults the derived physical target when it creates the shape.\n *\n * The `rowFilter` callback receives the OWNER's full columns — the predicate is evaluated against\n * the physical table, so it may reference a column the local subset omits. RLS for the projection's\n * reads lives on the OWNER's table (a projection adds no DDL to a table it does not own); its\n * `customPredicate` must be a subset of what that RLS allows.\n *\n * The `owner` may be a `defineSyncTable` entry OR an `asReadonly` of one — an `asReadonly` projection\n * preserves the full read contract (physical table, columns, primary key) and only drops the write path,\n * so projecting off it is equivalent to projecting off its writable source. A CHAINED read projection\n * (an owner that is itself a `defineReadProjection`) is rejected, because it composes wrongly — see below.\n *\n * ### Server-side egress redaction (`serverProjection` + `serverOnlyColumns`)\n *\n * A projection may carry its own `serverProjection` (a {@link ServerProjectionSpec}, typically a\n * `rowTransform`) — resolved by the projection's `shapeKey` and run at the STREAM EDGE, per request, for\n * this shape only (ADR-0055 decision 5). The order on egress is **transform first, then omission**: the\n * transform runs against the fetched row, then the edge strips the row to the client keep-set\n * (`columns ∪ primaryKey`) before it reaches the client wire. This lets a \"secure window\" over a keyed\n * table stream the body while stripping the keys per row. Such a shape is private-tier by construction\n * (its bytes depend on the reader) and is answered `cache-control: private, no-store`.\n *\n * `serverOnlyColumns` are owner column keys the transform must READ but that are NOT in the client shape\n * (e.g. a `keysWithheld` control flag). Such a key stays omitted from the client keep-set, yet is ADDED\n * to the shape's `columns` allow-list — so it is fetched, visible to the transform, and then\n * stripped on egress by the same omission pass, never reaching the client. It requires a\n * `serverProjection.rowTransform` (a fetch no transform reads is dead weight) AND `columns` (with\n * `columns` omitted every column is already kept, so \"server-only\" is a contradiction), and must be\n * disjoint from `columns` and the primary key.\n *\n * **No inheritance — ENFORCED.** A projection does NOT inherit its owner's `serverProjection`. That is\n * deliberate: an inherited transform whose input column is absent from the projection's fetch list would\n * read `undefined` and silently fail OPEN (serving the un-redacted body) — half-protection worse than\n * none. Because a bare projection over a redacting owner would therefore egress RAW owner rows, the\n * registry no longer merely warns: when `owner.serverProjection?.rowTransform` exists, this function\n * THROWS at definition time unless the projection declares a posture. You must either declare your own\n * `serverProjection` on the projection (typically the same transform fn, plus `serverOnlyColumns` for its\n * control-flag inputs), or — only after confirming the projection's kept columns leak nothing — opt out\n * explicitly with the literal `serverProjection: \"unredacted\"`, which attaches no transform (egress raw)\n * but records that as a visible, reviewed decision at the definition site. The opt-out is meaningful only\n * where it applies: `\"unredacted\"` over an owner with NO egress `rowTransform` is itself rejected, so a\n * stale opt-out cannot silently pre-authorize a leak the day the owner grows one.\n */\nexport function defineReadProjection<\n const TOwnerTable extends AnyPgTable,\n const TOwnerLocal extends AnyPgTable,\n const TAs extends string,\n // Captures `opts.columns` as a literal tuple so the projection's local table can carry the OWNER's real\n // per-column types restricted to the kept keys. Defaults to \"all owner keys\" (its `[number]` is the full\n // key union), which is exactly the shape when `columns` is omitted — one uniform kept-key expression.\n const TColumns extends readonly TableColumnKey<TOwnerTable>[] = readonly TableColumnKey<TOwnerTable>[],\n>(\n // Two table params so an owner that uses `omitColumns` (its `table` and `localTable` types differ) is\n // accepted — `TOwnerTable` (the physical table) is what `columns`/`rowFilter` are typed against.\n owner: SyncTableEntry<TOwnerTable, TOwnerLocal>,\n opts: {\n /** The projection's distinct local identity — its PGlite table name AND its `shapeKey`. */\n as: TAs;\n /** Column keys (of the owner) to sync locally + fetch on the shape. The PK is always kept. Omit → all. */\n columns?: TColumns;\n /** Row filter for this shape; the callback form receives the owner's full (physical) columns. */\n rowFilter?: (columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec;\n /**\n * Server-side egress projection (ADR-0004) for THIS shape — typically a `rowTransform` that redacts a\n * sub-document of a kept column conditionally on row data. A projection does NOT inherit its owner's\n * `serverProjection` (see the docblock's no-inheritance caution): an inherited transform whose input\n * column is unfetched would fail OPEN, so inheritance is refused, not silent. When the OWNER declares\n * an egress `rowTransform`, this is therefore **required** — the registry throws at definition time\n * unless you either declare your own spec here (typically the same transform fn, plus\n * `serverOnlyColumns` for its control-flag inputs) OR opt out with the literal `\"unredacted\"`. Use\n * `\"unredacted\"` only after confirming this projection's kept columns leak nothing; it attaches NO\n * egress transform (the shape streams raw owner rows), but records that as a visible, reviewed\n * decision at the definition site. `\"unredacted\"` over a transform-less owner is itself rejected — a\n * stale opt-out would silently pre-authorize a leak the day the owner grows a transform.\n */\n serverProjection?: ServerProjectionSpec | \"unredacted\";\n /**\n * Owner column keys the `serverProjection.rowTransform` must READ but which are NOT part of the client\n * shape (e.g. a `keysWithheld` control flag). They are added to the shape's `columns` allow-list so\n * the transform can see them, then stripped on egress before the client wire. Requires\n * `serverProjection.rowTransform` and `columns`; must be disjoint from `columns` and the primary key.\n */\n serverOnlyColumns?: readonly TableColumnKey<TOwnerTable>[];\n /**\n * Row classification (ADR-0052) for THIS projection. Defaults to the OWNER's `rowClass` — a projection\n * reads the owner's rows, so it carries the owner's classification (and the invariants bound to it)\n * unless you say otherwise. Override when the narrower shape genuinely changes the KIND of row the\n * client receives (e.g. a redacting window over private rows that egresses only public fields).\n */\n rowClass?: string;\n consistencyGroup?: string;\n subscription?: SubscriptionTiming;\n retention?: Retention;\n },\n) {\n // A read projection composes off the OWNER's physical table + full columns. A chained projection (an\n // owner that is itself a read projection) would silently discard the intermediate's OWN column subset\n // and rowFilter — this derivation reads the intermediate's `table`/`makeColumns` (the physical table,\n // full columns), not its narrowed shape — so it cannot mean \"project the projection\". Reject it and\n // point at the owning defineSyncTable entry, which is the only sound base. (An `asReadonly` owner is\n // NOT a read projection and IS accepted — see the docblock.)\n if (owner.readProjection) {\n throw new Error(\n `defineReadProjection: owner \"${opts.as}\" is itself a read projection — chained projections compose ` +\n `wrongly (this derives off the owner's physical table + full columns, so the intermediate's own ` +\n `column subset and rowFilter would be silently discarded). Project off the owning defineSyncTable ` +\n `entry instead.`,\n );\n }\n\n // Defensive: every registrable entry (defineSyncTable + every transform — asReadonly / asEphemeral /\n // withRetention) now carries the column factory, so its absence means a hand-assembled owner, which\n // cannot be projected (there is nothing to derive columns from).\n const ownerMakeColumns = owner.makeColumns;\n if (!ownerMakeColumns) {\n throw new Error(\n `defineReadProjection: owner \"${getTableConfig(owner.table).name}\" has no column factory — pass an ` +\n `entry built by defineSyncTable (or an asReadonly of one), not a hand-assembled entry.`,\n );\n }\n\n const physicalTable = getTableConfig(owner.table).name;\n const allKeys = Object.keys(ownerMakeColumns());\n const pkKeys = owner.primaryKey.columns;\n const keep = opts.columns ? new Set<string>([...opts.columns, ...pkKeys]) : new Set(allKeys);\n // The subset is expressed as `omitColumns` over the OWNER's full columns, so every column-derivation\n // helper (deriveSyncColumnTypes / classifyTableApplyStrategy / getProjectedColumnNames) — which read\n // `entry.table` minus `omitColumns` — yields the right subset for the client, with `entry.table`\n // staying the owner's physical table (nothing new to migrate). The primary key is always kept.\n const omittedKeys = allKeys.filter((key) => !keep.has(key));\n\n // serverOnlyColumns — owner keys the egress rowTransform must READ but that are NOT in the client\n // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND egress strips them on\n // the way out), yet are added to the shape's `columns` allow-list below so the transform can see them.\n // Each guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.\n // Fail-closed posture guard. A projection does NOT inherit its owner's egress `serverProjection`\n // (see the docblock's no-inheritance caution: an inherited transform whose input column is unfetched\n // reads `undefined` and fails OPEN — half-protection worse than none). So if the OWNER redacts on\n // egress via `serverProjection.rowTransform`, this projection would silently egress RAW owner rows\n // unless it declares a posture. We REFUSE that silence: the projection must either declare its own\n // `serverProjection` (an object spec) or opt out with the literal `serverProjection: \"unredacted\"`.\n const optServerProjection = opts.serverProjection;\n const ownerHasEgressTransform = owner.serverProjection?.rowTransform != null;\n if (optServerProjection === \"unredacted\" && !ownerHasEgressTransform) {\n // A stale \"unredacted\" over a transform-less owner would silently pre-authorize a leak if the owner\n // later grew a transform. Keep the opt-out meaningful exactly where it applies.\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverProjection: \"unredacted\", but owner ` +\n `\"${physicalTable}\" declares no egress rowTransform — the opt-out masks nothing here and would ` +\n `silently pre-authorize a leak if the owner later gains one. Remove the opt-out so it cannot mask ` +\n `a future one.`,\n );\n }\n if (ownerHasEgressTransform && optServerProjection == null) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" projects over owner \"${physicalTable}\", which declares ` +\n `an egress rowTransform — a projection does NOT inherit it, so this shape would egress RAW owner ` +\n `rows. Declare your own serverProjection (typically the same transform fn, plus serverOnlyColumns ` +\n `for its control-flag inputs) or — only after confirming the projection's kept columns leak nothing ` +\n `— opt out with serverProjection: \"unredacted\".`,\n );\n }\n // Only an object spec attaches to the entry; \"unredacted\" attaches NOTHING (egress raw, but now a\n // visible, reviewed decision at the definition site).\n const serverProjection = typeof optServerProjection === \"object\" ? optServerProjection : undefined;\n const serverOnlyColumns = opts.serverOnlyColumns ?? [];\n if (serverOnlyColumns.length > 0) {\n if (optServerProjection === \"unredacted\") {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverProjection: \"unredacted\" together ` +\n `with serverOnlyColumns — the opt-out runs no transform, so there is nothing to read them. Drop ` +\n `serverOnlyColumns, or declare a serverProjection.rowTransform that reads them.`,\n );\n }\n if (!serverProjection?.rowTransform) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverOnlyColumns but no ` +\n `serverProjection.rowTransform — a server-only fetch that no transform reads is dead weight. ` +\n `Add the rowTransform that reads them, or drop serverOnlyColumns.`,\n );\n }\n if (!opts.columns) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverOnlyColumns without columns — with ` +\n `columns omitted every column is already kept client-side, so a \"server-only\" column is a ` +\n `contradiction. Declare columns (the client subset) so some columns can be genuinely server-only.`,\n );\n }\n const clientKept = new Set<string>([...opts.columns, ...pkKeys]);\n for (const key of serverOnlyColumns) {\n if (!allKeys.includes(key)) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" serverOnlyColumns names \"${key}\", which is not a ` +\n `column of owner \"${physicalTable}\". It feeds the shape's \"columns\" allow-list, so a typo would ` +\n `silently mis-fetch — name an existing owner column key.`,\n );\n }\n if (clientKept.has(key)) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" lists \"${key}\" in BOTH serverOnlyColumns and the ` +\n `client shape (columns or primary key) — it is already fetched and kept client-side, so ` +\n `declaring it server-only is contradictory. Remove it from serverOnlyColumns.`,\n );\n }\n }\n }\n\n // The local table (subset) + base shape (tableName/shapeKey = `as`) + readonly validation come from the\n // normal constructor — reusing the OWNER's column definitions, never restating them. Below we override\n // only what a projection differs in (it owns no table; it reads the owner's physical table).\n const built = defineSyncTable({\n tableName: opts.as,\n makeColumns: ownerMakeColumns,\n mode: \"readonly\",\n primaryKey: [...pkKeys],\n ...(omittedKeys.length > 0\n ? { clientProjection: { omitColumns: omittedKeys as unknown as readonly never[] } }\n : {}),\n ...(opts.consistencyGroup != null ? { consistencyGroup: opts.consistencyGroup } : {}),\n ...(opts.subscription != null ? { subscription: opts.subscription } : {}),\n ...(opts.retention != null ? { retention: opts.retention } : {}),\n });\n\n // Resolve the row filter against the OWNER's full columns (the predicate is evaluated on the\n // physical table, so it may reference a column the subset omits).\n const resolvedRowFilter = opts.rowFilter?.(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>);\n\n // When a subset is requested, set the shape's `columns` allow-list to the KEPT physical column names\n // so an omitted (e.g. heavy jsonb) column is never fetched over the wire — not merely stripped after.\n // serverOnlyColumns are added ON TOP of the kept names: a server-only column must be FETCHED (so the\n // egress rowTransform can read it) even though it is omitted from the client keep-set. It is stripped\n // after the transform runs, at the STREAM EDGE — `createStreamGate` (packages/server/src/circuits/edge.ts)\n // rewrites each row of a transform shape's long-poll body and then narrows it to `entry.localTable`'s\n // columns, which is precisely this keep-set. So the column rides the engine's stream and comes off the\n // wire one hop before the client. Resolve key -> physical name the same way getProjectedColumns\n // does (the drizzle column's `.name`), never a hand-map. A full-width projection (no omitted keys, hence\n // no serverOnlyColumns — validated above) declares no allow-list at all.\n const ownerColumns = getColumns(owner.table) as Record<string, { name: string }>;\n const serverOnlyColumnNames = serverOnlyColumns.map((key) => ownerColumns[key]!.name);\n const allowListColumns =\n omittedKeys.length > 0 ? [...getProjectedColumnNames(built), ...serverOnlyColumnNames] : undefined;\n\n const rowFilter: RowFilterSpec | undefined =\n resolvedRowFilter != null || allowListColumns != null\n ? {\n ...(resolvedRowFilter ?? {}),\n ...(allowListColumns != null ? { columns: allowListColumns } : {}),\n }\n : undefined;\n\n const shape: ShapeSpec = {\n tableName: opts.as,\n shapeKey: opts.as,\n physicalTable: physicalTable,\n ...(rowFilter != null ? { rowFilter } : {}),\n };\n\n // Same definition-time refusal the owning `defineSyncTable` performs: a projection's filter is a\n // filter, and one that cannot run here is the same unfiltered stream it would be there.\n assertShapeFilterIsEnforceable(shape);\n\n // Point `table` at the owner's physical table and flag `readProjection` — that flag (not the absence of\n // a column factory) is what generators/appliers key on to skip owning-table work (see plpgsql-apply's\n // `!entry.readProjection` filter). The owner's `makeColumns` is KEPT (it rode in via `built`): since\n // ADR-0029 P1 the client derives a projection's OWN local synced object from it too\n // (`getSyncedLocalTable` → `projectedColumnBuilders`, with this entry's `omitColumns` applied), so a\n // subscribed read projection that dropped it would fail to boot exactly as an `asReadonly` entry did.\n // `built` was validated by defineSyncTable and only its `table` is replaced (with the owner's,\n // structurally identical role), so the result is a sound SyncTableEntry — cast past the spread's\n // exactOptional friction to a clean entry type that keeps the projected local-table shape.\n // `serverProjection` is attached HERE on the outer object (mirroring `shape`), NOT threaded through the\n // inner `defineSyncTable` call — that alone makes the proxy's shapeKey resolution find and run the\n // projection's egress transform (getRowTransformForTable → resolveEntryByShapeKey(…)?.serverProjection).\n // Row classification (ADR-0052) is INHERITED from the owner by default — a projection streams the owner's\n // rows, so it belongs to the owner's class (and to every invariant bound to it) unless the projection's\n // narrower shape genuinely changes the kind of row a client receives, which `opts.rowClass` overrides.\n const rowClass = opts.rowClass ?? owner.rowClass;\n const projection = {\n ...built,\n table: owner.table,\n shape,\n readProjection: true as const,\n ...(rowClass != null ? { rowClass } : {}),\n ...(serverProjection != null ? { serverProjection } : {}),\n };\n // The local table carries the OWNER's real column types restricted to the kept keys (`TColumns[number]`\n // — the full owner key union when `columns` was omitted), NOT the type-erased `built.localTable` (which\n // collapses to an open index signature because it is rebuilt through the stashed `makeColumns`).\n return projection as unknown as SyncTableEntry<\n TOwnerTable,\n ProjectionLocalTable<TOwnerTable, TAs, TColumns[number]>\n > & { readProjection: true };\n}\n\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n registry: TRegistry,\n): TRegistry;\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n definition: SyncRegistryDefinition<TRegistry>,\n): TRegistry;\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n input: TRegistry | SyncRegistryDefinition<TRegistry>,\n) {\n if (isSyncRegistryDefinition(input)) {\n for (const entry of getRegistryEntries(input.tables)) {\n validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);\n }\n validateRegistryTableUniqueness(input.tables);\n validateRegistryShapeKeyUniqueness(input.tables);\n validateRegistryLifecycleGroups(input.tables);\n validateStorageDeclaration(input.storage);\n validateRowClassification(input.tables, input.rowClasses);\n validateEventStreams(input.streams);\n\n // Schema first (it may return the same tables object), then stamp the storage declaration on the\n // returned registry as a non-enumerable symbol — the same carrier pattern as the schema symbol — so\n // client code reads the data-contract storage back off the registry value (getSyncRegistrySchema's\n // twin, getSyncRegistryStorage). The bare-registry-map overload carries no storage and reads back\n // `undefined`, which resolves to the ADR-0047 defaults at the mint seam. The declared row-class\n // vocabulary rides the same way (ADR-0052), for getSyncRegistryRowClasses, and so do the registered\n // Event streams (ADR-0053), for getSyncRegistryStreams.\n return attachSyncRegistryStreams(\n attachSyncRegistryRowClasses(\n attachSyncRegistryStorage(attachSyncRegistrySchema(input.tables, input.schema), input.storage),\n input.rowClasses,\n ),\n input.streams,\n );\n }\n\n for (const entry of getRegistryEntries(input)) {\n validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);\n }\n validateRegistryTableUniqueness(input);\n validateRegistryShapeKeyUniqueness(input);\n validateRegistryLifecycleGroups(input);\n\n return input;\n}\n\n/** The local/shape identity an entry resolves to: its `shape.tableName` (the unique shape key a client\n * requests and the local PGlite table), falling back to the Drizzle table name when an entry has no\n * shape (a write-only table). A read projection carries a distinct `shape.tableName` (`as`) even though\n * its `table` is the owner's, so it is identified here by `as`, never by the shared physical table. */\nfunction localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {\n return entry.shape?.tableName ?? getTableConfig(entry.table).name;\n}\n\n/**\n * A registry must not declare the same local table twice. Every entry resolves to one local identity\n * ({@link localShapeIdentity}) — the PGlite table a client reads and the `shapeKey` the proxy resolves a\n * request by — so two entries sharing it would collide locally (one shadows the other) and make the\n * shape unresolvable. A read PROJECTION over a shared physical table does NOT trip this: it carries a\n * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.physicalTable`,\n * so several shapes read one physical table while their local identities stay unique. Fails closed at\n * module-eval, for every consumer.\n */\nfunction validateRegistryTableUniqueness(registry: SyncTableRegistry) {\n const declaredBy = new Map<string, string>();\n\n for (const [key, entry] of Object.entries(registry)) {\n const identity = localShapeIdentity(entry as SyncTableEntry<AnyPgTable>);\n const firstKey = declaredBy.get(identity);\n\n if (firstKey !== undefined) {\n throw new Error(\n `local table \"${identity}\" is declared by two registry entries (\"${firstKey}\" and \"${key}\"): ` +\n `each entry must map to a unique local table. A second shape over an existing physical table ` +\n `must use defineReadProjection (a distinct \"as\") rather than a second owning entry.`,\n );\n }\n\n declaredBy.set(identity, key);\n }\n}\n\n/**\n * A registry must not expose the same PUBLIC `shapeKey` twice. This is a DISTINCT identity from the\n * local table checked by {@link validateRegistryTableUniqueness}: `shapeKey` is what a subscription\n * request names on the wire and what the control plane resolves an entry by (`resolveEntryByShapeKey`\n * is first-match), while the local identity is the PGlite table a client reads into. They coincide by\n * default (`shapeKey` falls back to `tableName`), so the local check already covers the common case,\n * and read projections over one physical table stay legal because `as` yields a distinct value for\n * BOTH identities. The only way to collide here is an EXPLICIT `shape.shapeKey` that diverges from the\n * table name: two such entries would leave the second permanently unreachable, silently served the\n * first's shape (and therefore the first's row filter). Write-only entries carry no shape and are\n * skipped — they are not publicly requestable. Fails closed at module-eval, for every consumer.\n */\nfunction validateRegistryShapeKeyUniqueness(registry: SyncTableRegistry) {\n const declaredBy = new Map<string, string>();\n\n for (const [key, entry] of Object.entries(registry)) {\n const shape = (entry as SyncTableEntry<AnyPgTable>).shape;\n if (shape === undefined) continue;\n\n const firstKey = declaredBy.get(shape.shapeKey);\n\n if (firstKey !== undefined) {\n throw new Error(\n `shapeKey \"${shape.shapeKey}\" is declared by two registry entries (\"${firstKey}\" and \"${key}\"): ` +\n `a duplicate shapeKey makes the second entry unreachable — the control plane resolves a ` +\n `subscription by shapeKey and would serve the first entry's shape. Give each entry a unique ` +\n `shape.shapeKey, or use defineReadProjection (a distinct \"as\") for a second shape over one table.`,\n );\n }\n\n declaredBy.set(shape.shapeKey, key);\n }\n}\n\n/**\n * ADR-0021 §4 / ADR-0022 §1–2: subscription timing, retention, and write-mode are properties of a\n * **consistency group**, not a single table — a group's streams commit atomically together\n * (so it cannot be partly lazy or partly ephemeral) and a consistency group *is* the static\n * write-unit (so it cannot be partly pessimistic). Reject a registry whose grouped tables disagree on\n * any of the three. Tables without a `consistencyGroup` are their own singleton group and are\n * unconstrained.\n */\nfunction validateRegistryLifecycleGroups(registry: SyncTableRegistry) {\n const groups = new Map<\n string,\n Array<{ tableName: string; subscription: SubscriptionTiming; retention: Retention; writeMode: WriteMode }>\n >();\n\n for (const entry of getRegistryEntries(registry)) {\n if (!entry.consistencyGroup) {\n continue;\n }\n\n const members = groups.get(entry.consistencyGroup) ?? [];\n members.push({\n tableName: getTableConfig(entry.table).name,\n subscription: entry.subscription ?? \"eager\",\n retention: entry.retention ?? \"persistent\",\n writeMode: entry.writeMode ?? \"optimistic\",\n });\n groups.set(entry.consistencyGroup, members);\n }\n\n for (const [group, members] of groups) {\n const subscriptions = new Set(members.map((member) => member.subscription));\n const retentions = new Set(members.map((member) => member.retention));\n const writeModes = new Set(members.map((member) => member.writeMode));\n\n if (subscriptions.size > 1 || retentions.size > 1 || writeModes.size > 1) {\n throw new Error(\n `consistency group \"${group}\" mixes lifecycle (ADR-0021 §4 / ADR-0022 §1): every table in a ` +\n `group must share one subscription, one retention, and one write-mode; got ` +\n members\n .map((member) => `${member.tableName}=${member.subscription}/${member.retention}/${member.writeMode}`)\n .join(\", \"),\n );\n }\n }\n}\n\nexport function getProjectedColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n const omittedColumns = new Set(entry.clientProjection?.omitColumns ?? []);\n\n return Object.entries(getColumns(entry.table)).flatMap(([propertyKey, column]) => {\n if (omittedColumns.has(propertyKey as TableColumnKey<TTable>)) {\n return [];\n }\n\n return [\n {\n propertyKey: propertyKey as TableColumnKey<TTable>,\n columnName: column.name,\n column,\n } satisfies ProjectedTableColumn<TTable>,\n ];\n });\n}\n\nexport function getOmittedProjectedColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n const omittedColumns = new Set(entry.clientProjection?.omitColumns ?? []);\n\n return Object.entries(getColumns(entry.table)).flatMap(([propertyKey, column]) => {\n if (!omittedColumns.has(propertyKey as TableColumnKey<TTable>)) {\n return [];\n }\n\n return [\n {\n propertyKey: propertyKey as TableColumnKey<TTable>,\n columnName: column.name,\n column,\n } satisfies ProjectedTableColumn<TTable>,\n ];\n });\n}\n\nexport function getProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return getProjectedColumns(entry).map(({ columnName }) => columnName);\n}\n\n/**\n * Resolves the {@link SyncColumnType}s of a synced table's client-projected columns from its Drizzle\n * definition (ADR-0009 decision 3) — the same `getSQLType()`/`dimensions` introspection the local\n * schema generator uses, so the apply ladder and the generated DDL can never disagree about a\n * column's type. Drives both {@link classifyTableApplyStrategy} and the engine's `json` apply cast,\n * removing the runtime `information_schema` round-trip.\n */\nexport function deriveSyncColumnTypes<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): SyncColumnType[] {\n return getProjectedColumns(entry).map(({ column, columnName }) => {\n const typedColumn = column as { getSQLType?: () => string; dimensions?: number; columnType?: string };\n const sqlType = normalizeCastPositionType(typedColumn.getSQLType?.() ?? \"\");\n return {\n name: columnName,\n sqlType,\n isArray: (typedColumn.dimensions ?? 0) > 0,\n // A real Postgres enum column brands as `PgEnumColumn`. `enumValues` is NOT the discriminator:\n // `text(\"c\", { enum: […] })` / varchar variants expose `enumValues` too but their `getSQLType()` is\n // a BASE type (`text`, `varchar(255)`) — identifier-quoting that as a cast type would be wrong (and\n // broken for parameterised types). For a true enum, `getSQLType()` returns the enum TYPE NAME\n // (usable as a cast type once quoted) — the flag lets the ladder classify it as COPY/JSON-safe\n // instead of falling to the `insert` floor on the unrecognised type name.\n isEnum: typedColumn.columnType?.startsWith(\"PgEnum\") === true,\n } satisfies SyncColumnType;\n });\n}\n\n/**\n * `serial`/`bigserial`/`smallserial` are DDL-position conveniences (an integer column plus a sequence\n * default), NOT real cast-position types: `json_to_recordset(… AS x(id serial))` and `value::serial`\n * are both invalid SQL. {@link SyncColumnType.sqlType} is contracted to be usable verbatim as a cast\n * type, so we normalise the serial family to its underlying integer type here — the single derivation\n * point — which also lets the column classify as COPY-safe rather than falling to the `insert` floor.\n *\n * Exported so any code deriving a {@link SyncColumnType} from a bare Drizzle column (e.g. test-support\n * `makeApplyTarget`, which cannot go through {@link deriveSyncColumnTypes} without a registry entry)\n * stays byte-faithful to this single normalisation rather than re-`getSQLType()`ing without it.\n */\nexport function normalizeCastPositionType(sqlType: string): string {\n switch (sqlType.trim().toLowerCase()) {\n case \"serial\":\n return \"integer\";\n case \"bigserial\":\n return \"bigint\";\n case \"smallserial\":\n return \"smallint\";\n default:\n return sqlType;\n }\n}\n\n/** The statically-chosen bulk-insert strategy for a synced table (ADR-0009 decision 3). */\nexport function classifyTableApplyStrategy<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): ApplyStrategy {\n return classifyApplyStrategy(deriveSyncColumnTypes(entry));\n}\n\nexport function getOmittedProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return getOmittedProjectedColumns(entry).map(({ columnName }) => columnName);\n}\n\nexport function getLocalSyncedTablePrimaryKeyColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return [...(entry.clientProjection?.localPrimaryKey?.columns ?? entry.primaryKey.columns)];\n}\n\n/**\n * The Server version column (ADR-0010): the `nowMicroseconds`-on-update managed field a writable\n * table stamps on every write (conventionally `updated_at_us`), made strictly monotonic by the\n * applier. Returns its **column name**, resolving the managed field's drizzle property key. Returns\n * `undefined` when none is declared — registry validation rejects that for writable tables, so the\n * convergence barrier never has to degrade.\n */\nexport function resolveServerVersionColumnName<TTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable>,\n): string | undefined {\n const field = (entry.governance?.managedFields ?? []).find(\n (managed) => managed.strategy === \"nowMicroseconds\" && managed.applyOn.includes(\"update\"),\n );\n\n if (!field) {\n return undefined;\n }\n\n // `field.column` is the drizzle property key (registry validation rejects a column-name declaration —\n // ADR-0012); resolve it to the underlying SQL column name.\n const columns = getColumns(entry.table);\n return (columns as Record<string, { name: string } | undefined>)[field.column as string]?.name;\n}\n\nexport function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry, schema?: string) {\n const normalizedSchema = normalizeSchemaName(schema);\n\n if (!normalizedSchema) {\n return registry;\n }\n\n for (const entry of Object.values(registry)) {\n const tableSchema = getTableConfig(entry.table).schema ?? \"public\";\n\n if (tableSchema !== normalizedSchema) {\n throw new Error(\n `Registry schema ${normalizedSchema} does not match table schema ${tableSchema} for ${getTableConfig(entry.table).name}`,\n );\n }\n\n if (!entry.shape) {\n continue;\n }\n\n const qualify = (name: string) => (name.includes(\".\") ? name : `${normalizedSchema}.${name}`);\n const qualifiedTableName = `${normalizedSchema}.${entry.shape.tableName}`;\n entry.shape = {\n ...entry.shape,\n // A read projection sets physicalTable to the owner's (bare) physical name; qualify it the same\n // way the owner's own target is qualified, so both shapes hit one schema-qualified table on egress.\n // An owner (no physicalTable) qualifies its own tableName. An already-qualified value is left as-is.\n physicalTable: entry.shape.physicalTable ? qualify(entry.shape.physicalTable) : qualifiedTableName,\n ...(entry.shape.shapeKey === entry.shape.tableName ? { shapeKey: qualifiedTableName } : {}),\n };\n }\n\n Object.defineProperty(registry, syncRegistrySchemaSymbol, {\n value: normalizedSchema,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return registry;\n}\n\nexport function getSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const schema = Reflect.get(registry, syncRegistrySchemaSymbol) as unknown;\n return typeof schema === \"string\" && schema.length > 0 ? schema : \"public\";\n}\n\n/**\n * Stamp the registry's storage declaration (ADR-0049 decision 1, ADR-0047) onto the registry value as a\n * non-enumerable symbol — the storage twin of {@link attachSyncRegistrySchema}. Carries the data-contract\n * storage through {@link defineSyncRegistry} so client code reads it back via {@link getSyncRegistryStorage}.\n * A `null`/`undefined` declaration attaches nothing (the bare-registry-map overload), leaving the reader to\n * resolve the ADR-0047 defaults at the mint seam.\n */\nexport function attachSyncRegistryStorage<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n storage: SyncStorageDeclaration | undefined,\n) {\n if (storage == null) {\n return registry;\n }\n // Idempotent for an EQUAL declaration (a registry value reused across constructions may be re-stamped with\n // the same contract) but fail-closed on a CONFLICT — two different storage contracts over one registry is a\n // definition error, never silently resolved. `backend`/`durability` are the only fields, so a shallow\n // compare is exhaustive.\n const existing = getSyncRegistryStorage(registry);\n if (existing != null) {\n if (existing.backend !== storage.backend || existing.durability !== storage.durability) {\n throw new Error(\n `conflicting storage declaration for registry: already ${JSON.stringify(existing)}, cannot re-declare ` +\n `${JSON.stringify(storage)}`,\n );\n }\n return registry;\n }\n Object.defineProperty(registry, syncRegistryStorageSymbol, {\n value: storage,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return registry;\n}\n\n/**\n * Read the storage declaration (ADR-0049 decision 1, ADR-0047) a registry was built with, or `undefined`\n * when none was declared (a bare registry map, or a definition with no `storage`). The client resolves the\n * effective mint durability as `getSyncRegistryStorage(registry)?.durability ?? \"relaxed\"` at its single\n * mint seam — the storage twin of {@link getSyncRegistrySchema}.\n */\nexport function getSyncRegistryStorage<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): SyncStorageDeclaration | undefined {\n const storage = Reflect.get(registry, syncRegistryStorageSymbol) as unknown;\n return storage != null && typeof storage === \"object\" ? (storage as SyncStorageDeclaration) : undefined;\n}\n\n/**\n * Stamp the registry's declared row-class vocabulary (ADR-0052) onto the registry value as a non-enumerable\n * symbol — the classification twin of {@link attachSyncRegistryStorage}. An absent/empty declaration attaches\n * nothing (the bare-registry-map overload, and any definition that declares no vocabulary), so\n * {@link getSyncRegistryRowClasses} reads back `undefined` and classification stays unconstrained.\n */\nexport function attachSyncRegistryRowClasses<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n rowClasses: readonly string[] | undefined,\n) {\n if (rowClasses == null) {\n return registry;\n }\n // Idempotent for an EQUAL vocabulary (a registry value reused across constructions may be re-stamped with\n // the same set) but fail-closed on a CONFLICT — two different vocabularies over one registry is a\n // definition error, never silently resolved.\n const existing = getSyncRegistryRowClasses(registry);\n if (existing != null) {\n if (existing.length !== rowClasses.length || existing.some((value, index) => value !== rowClasses[index])) {\n throw new Error(\n `conflicting rowClasses declaration for registry: already [${existing.join(\", \")}], cannot re-declare ` +\n `[${rowClasses.join(\", \")}]`,\n );\n }\n return registry;\n }\n Object.defineProperty(registry, syncRegistryRowClassesSymbol, {\n value: Object.freeze([...rowClasses]),\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return registry;\n}\n\n/**\n * Read the row-class vocabulary (ADR-0052) a registry was built with, or `undefined` when none was declared\n * (a bare registry map, or a definition with no `rowClasses`) — the classification twin of\n * {@link getSyncRegistryStorage}. {@link assertRegistryInvariant} consults it to reject an invariant whose\n * `appliesTo` names a class this registry does not define (a typo that would otherwise bind nothing).\n */\nexport function getSyncRegistryRowClasses<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): readonly string[] | undefined {\n const rowClasses = Reflect.get(registry, syncRegistryRowClassesSymbol) as unknown;\n return Array.isArray(rowClasses) ? (rowClasses as readonly string[]) : undefined;\n}\n\n/**\n * Stamp the registry's registered Event streams (ADR-0053 decision 1) onto the registry value as a\n * non-enumerable symbol — the Event-lane twin of {@link attachSyncRegistryRowClasses}. An absent declaration\n * attaches nothing (the bare-registry-map overload, and any definition that registers no Event stream), so\n * {@link getSyncRegistryStreams} reads back `undefined` and the registry simply has no Event lane.\n *\n * Non-enumerable is load-bearing beyond tidiness: `canonicalizeRegistry` walks the registry's own enumerable\n * keys, so riding a symbol is what keeps Event streams OUT of the persisted fingerprint.\n */\nexport function attachSyncRegistryStreams<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n streams: EventStreamRegistry | undefined,\n) {\n if (streams == null) {\n return registry;\n }\n // Idempotent for the SAME registration (one tables object may be reused across per-client registries built\n // from one definition) but fail-closed on a CONFLICT — two different Event-lane contracts over one registry\n // is a definition error, never silently resolved. Entries are compared by identity: a payload schema is an\n // opaque object, so structural equality here would be a worse promise than none.\n const existing = getSyncRegistryStreams(registry);\n if (existing != null) {\n const existingNames = Object.keys(existing).sort();\n const nextNames = Object.keys(streams).sort();\n const same =\n existingNames.length === nextNames.length &&\n existingNames.every((name, index) => name === nextNames[index] && existing[name] === streams[name]);\n if (!same) {\n throw new Error(\n `conflicting streams declaration for registry: already [${existingNames.join(\", \")}], cannot re-declare ` +\n `[${nextNames.join(\", \")}]`,\n );\n }\n return registry;\n }\n Object.defineProperty(registry, syncRegistryStreamsSymbol, {\n value: Object.freeze({ ...streams }),\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return registry;\n}\n\n/**\n * Read the Event streams (ADR-0053 decision 1) a registry was built with, or `undefined` when none were\n * registered — the Event-lane twin of {@link getSyncRegistryRowClasses}. The server mounts the ingestion route\n * and provisions one pgmq queue per entry from this; the client resolves an `appendEvent` payload schema\n * through it.\n */\nexport function getSyncRegistryStreams<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): EventStreamRegistry | undefined {\n const streams = Reflect.get(registry, syncRegistryStreamsSymbol) as unknown;\n return streams != null && typeof streams === \"object\" ? (streams as EventStreamRegistry) : undefined;\n}\n\n/**\n * Fail-closed at module-eval (ADR-0053 decision 1): every registered Event stream must be nameable as a pgmq\n * queue and must declare a usable payload contract and identity-stamping rule. A bad Event-stream name has to\n * fail at DEFINITION — failing at deployment DDL, when `pgxsinkit-generate` emits the per-stream queues, is\n * far too late.\n *\n * Rejection-only, and it names EVERY offender in one error (same posture as {@link validateRowClassification}:\n * an author fixing a batch of streams should not have to re-run the build once per stream).\n */\nfunction validateEventStreams(streams: EventStreamRegistry | undefined) {\n if (streams == null) {\n return;\n }\n\n const problems: string[] = [];\n\n for (const [name, entry] of Object.entries(streams)) {\n if (!EVENT_STREAM_NAME_PATTERN.test(name)) {\n problems.push(\n `\"${name}\": invalid Event-stream name — must match ${EVENT_STREAM_NAME_PATTERN.source} ` +\n `(lowercase letters, digits and underscores, starting with a letter)`,\n );\n } else if (name.length > EVENT_STREAM_NAME_MAX_LENGTH) {\n problems.push(\n `\"${name}\": Event-stream name is ${name.length} characters — at most ${EVENT_STREAM_NAME_MAX_LENGTH} ` +\n `are allowed, because each stream is provisioned as the pgmq queue ` +\n `\"${EVENT_STREAM_QUEUE_PREFIX}${name}\" and pgmq's queue-name limit is 47 characters, of which the ` +\n `\"${EVENT_STREAM_QUEUE_PREFIX}\" prefix consumes ${EVENT_STREAM_QUEUE_PREFIX.length}`,\n );\n }\n\n if (entry == null || typeof entry !== \"object\") {\n problems.push(`\"${name}\": not an Event-stream entry — declare it with defineEventStream({ payload, identity })`);\n continue;\n }\n\n if (!isZodSchema(entry.payload)) {\n problems.push(`\"${name}\": payload is not a zod schema — declare a strict zod schema for the event payload`);\n } else if (hasNonStrictObjectRoot(entry.payload)) {\n // The strict promise is ENFORCED, not advertised. A stripping `z.object({…})` would drop a misspelled\n // or newly-added key between the caller and the consumer with no verdict anywhere — the exact silence\n // the lane's \"everything in the Outbox is well-formed\" invariant exists to prevent. Non-object roots\n // (string, array, record, transform pipelines) are untouched by this rule.\n problems.push(\n `\"${name}\": the payload's object schema is not strict — declare it with \\`.strict()\\` or ` +\n `\\`z.strictObject()\\` (every object inside a union payload too), so an unknown key is REJECTED at ` +\n `\\`appendEvent\\` instead of being silently stripped on the way to the consumer`,\n );\n }\n\n if (entry.revision != null && (!Number.isInteger(entry.revision) || entry.revision <= 0)) {\n problems.push(\n `\"${name}\": revision must be a positive integer (it is the opaque counter you bump when acceptance ` +\n `logic the JSON-Schema hash cannot see — a refinement threshold, a transform — changes)`,\n );\n }\n\n if (entry.identity == null || typeof entry.identity !== \"object\") {\n problems.push(`\"${name}\": identity must be a record of field name -> { claimPath }`);\n continue;\n }\n\n for (const [field, spec] of Object.entries(entry.identity)) {\n if (field.trim().length === 0) {\n problems.push(`\"${name}\": an identity field name is empty`);\n continue;\n }\n const claimPath = spec?.claimPath;\n if (!Array.isArray(claimPath) || claimPath.length === 0) {\n problems.push(\n `\"${name}\".identity.${field}: claimPath must be a non-empty JSON path into the verified claims ` +\n `(e.g. [\"sub\"] or [\"app_metadata\", \"person_id\"])`,\n );\n continue;\n }\n if (claimPath.some((segment) => typeof segment !== \"string\" || segment.trim().length === 0)) {\n problems.push(`\"${name}\".identity.${field}: every claimPath segment must be a non-empty string`);\n }\n }\n }\n\n if (problems.length === 0) {\n return;\n }\n\n throw new Error(\n `invalid Event-stream registration (ADR-0053). The record key IS the Event-stream name, and each entry ` +\n `must be a defineEventStream({ payload, identity }) — ${problems.join(\"; \")}.`,\n );\n}\n\n/**\n * Fail-closed at module-eval (ADR-0052): when a registry declares a `rowClasses` vocabulary, EVERY entry\n * must carry a {@link SyncTableEntry.rowClass} drawn from it. This is the whole point of the field — a new\n * entry added tomorrow cannot join the registry without its author classifying it, so an invariant that\n * binds by class can never quietly under-enumerate the tables it is supposed to cover.\n *\n * Rejection-only, and it names EVERY offender in one error (an author fixing a batch of entries should not\n * have to re-run the build once per entry). An undeclared vocabulary constrains nothing — the entries may\n * carry any `rowClass`, or none.\n */\nfunction validateRowClassification(registry: SyncTableRegistry, rowClasses: readonly string[] | undefined) {\n if (rowClasses == null) {\n return;\n }\n\n if (rowClasses.length === 0) {\n throw new Error(\n `rowClasses is declared but empty: a declared vocabulary makes classification mandatory, so an empty ` +\n `set can never be satisfied. Declare the classes this registry uses, or omit rowClasses entirely.`,\n );\n }\n\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n for (const rowClass of rowClasses) {\n if (typeof rowClass !== \"string\" || rowClass.length === 0) {\n throw new Error(\n `rowClasses contains an invalid value ${JSON.stringify(rowClass)}: each class must be a non-empty string`,\n );\n }\n if (seen.has(rowClass)) {\n duplicates.add(rowClass);\n }\n seen.add(rowClass);\n }\n if (duplicates.size > 0) {\n throw new Error(`rowClasses declares duplicate classes: ${[...duplicates].join(\", \")}`);\n }\n\n const unclassified: string[] = [];\n const unknown: string[] = [];\n for (const [key, entry] of Object.entries(registry)) {\n const rowClass = (entry as SyncTableEntry<AnyPgTable>).rowClass;\n if (rowClass == null) {\n unclassified.push(key);\n continue;\n }\n if (!seen.has(rowClass)) {\n unknown.push(`${key} (rowClass \"${rowClass}\")`);\n }\n }\n\n if (unclassified.length === 0 && unknown.length === 0) {\n return;\n }\n\n const problems = [\n ...(unclassified.length > 0 ? [`unclassified entries: ${unclassified.join(\", \")}`] : []),\n ...(unknown.length > 0 ? [`entries with an undeclared class: ${unknown.join(\", \")}`] : []),\n ];\n throw new Error(\n `row classification is incomplete (ADR-0052). This registry declares rowClasses ` +\n `[${rowClasses.join(\", \")}], so every entry must carry a rowClass from that set — ${problems.join(\"; \")}. ` +\n `Classify each entry (or widen rowClasses if a genuinely new kind of row has arrived).`,\n );\n}\n\n/**\n * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` must\n * be a known value, matching how the other registry axes reject bad input at `defineSyncRegistry`. An absent\n * declaration or absent field is fine — it resolves to the ADR-0047 defaults (`opfs` / `relaxed`).\n */\nfunction validateStorageDeclaration(storage: SyncStorageDeclaration | undefined) {\n if (storage == null) {\n return;\n }\n if (storage.backend !== undefined && !isStorageBackend(storage.backend)) {\n throw new Error(\n `invalid storage.backend \"${String(storage.backend)}\": must be one of ${STORAGE_BACKENDS.join(\", \")}`,\n );\n }\n if (storage.durability !== undefined && !isStorageDurability(storage.durability)) {\n throw new Error(\n `invalid storage.durability \"${String(storage.durability)}\": must be one of ${STORAGE_DURABILITIES.join(\", \")}`,\n );\n }\n}\n\nfunction isSyncRegistryDefinition<TRegistry extends SyncTableRegistry>(\n input: TRegistry | SyncRegistryDefinition<TRegistry>,\n): input is SyncRegistryDefinition<TRegistry> {\n return (\n typeof input === \"object\" &&\n input !== null &&\n \"tables\" in input &&\n typeof input.tables === \"object\" &&\n input.tables !== null\n );\n}\n\nfunction normalizeSchemaName(schema: string | undefined) {\n const trimmed = schema?.trim();\n return trimmed && trimmed !== \"public\" ? trimmed : undefined;\n}\n\nfunction getRegistryEntries<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.values(registry) as Array<SyncTableEntry<AnyPgTable>>;\n}\n\nfunction validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {\n const tableName = getTableConfig(entry.table).name;\n\n // ADR-0029 P1: the client derives every synced-table object (the local synced read cache, and — for a\n // writable table — the overlay/journal) from this column-builder factory (getSyncedLocalTable →\n // projectedColumnBuilders), so it is hard-required at client boot. Promote the check to registry-build\n // time (better DX than an opaque engine-boot throw): defineSyncTable always stashes it, and every\n // projection (asReadonly / withRetention / defineReadProjection) carries it through — only a\n // hand-assembled entry can lack it, and such an entry cannot be synced.\n if (typeof entry.makeColumns !== \"function\") {\n throw new Error(\n `sync table ${tableName} has no makeColumns factory: every registered entry must be built by ` +\n `defineSyncTable (or a projection of one — asReadonly / asEphemeral / defineReadProjection), which ` +\n `stashes the column-builder factory the client requires (ADR-0029 P1) to derive its local ` +\n `synced/overlay/journal objects. Hand-assembled entries are unsupported.`,\n );\n }\n\n // ADR-0055 decision 5: an egress `serverProjection.rowTransform` makes the shape's bytes a function\n // of the SUBJECT — the stream edge rewrites them per request, with the subject from the stream\n // token — so the shape is private-tier BY CONSTRUCTION and cannot be served from a scope-keyed\n // shared stream. Letting the two ride together would produce exactly what `readShapeTier` refuses\n // for `scope` + `rowFilter`: a stream cached under a scope key while carrying subject-dependent\n // bytes, which is a disclosure rather than a stale row. Checked HERE rather than in `readShapeTier`\n // because the transform lives on the ENTRY (a projection attaches it after its shape is built), and\n // this is the one validation every registrable entry passes through, projections included.\n if (entry.serverProjection?.rowTransform != null && entry.shape?.scope != null) {\n throw new Error(\n `[pgxsinkit] shape \"${entry.shape.shapeKey}\" declares both scope and a serverProjection.rowTransform ` +\n `— an egress transform rewrites the stream's bytes per request with the reader's subject, so the ` +\n `shape is private-tier by construction (ADR-0055 decision 5) and cannot be served from a ` +\n `scope-keyed shared stream. Drop the transform and pre-compute the redaction into a column the ` +\n `shape projects, or drop scope and keep this shape private.`,\n );\n }\n\n // ADR-0010: a writable synced table must declare a Server version — a nowMicroseconds-on-update\n // managed field (conventionally updated_at_us) the applier stamps and keeps strictly monotonic.\n // Optimistic convergence is unsound without a per-row version (the barrier would degenerate to a\n // flicker-prone key-match), so this is a hard requirement, not a silent degraded fallback.\n if (entry.mode !== \"readonly\" && resolveServerVersionColumnName(entry) === undefined) {\n throw new Error(\n `writable table ${tableName} must declare a Server version: a managed field with strategy ` +\n `\"nowMicroseconds\" and applyOn including \"update\" (conventionally updated_at_us) — ADR-0010`,\n );\n }\n\n // ADR-0015: every writable table must declare a Conflict policy — what happens to a stale write.\n // There is no silent default: silent last-write-wins is exactly the data loss the policy exists to\n // turn into a conscious per-table decision. This is the third hard-require (after the Server version\n // above and the server-PK-in-projection rule below), accepted as consistent with the footgun-averse\n // stance.\n if (entry.mode !== \"readonly\" && !isConflictPolicy(entry.conflictPolicy)) {\n throw new Error(\n `writable table ${tableName} must declare a Conflict policy (ADR-0015): conflictPolicy must be ` +\n `one of ${CONFLICT_POLICIES.join(\", \")}` +\n (entry.conflictPolicy === undefined ? \" (none was declared)\" : ` (got ${String(entry.conflictPolicy)})`),\n );\n }\n\n // ADR-0021: the lifecycle axes are optional (default eager/persistent), but a declared value must be\n // valid. Group-level uniformity (every table in a consistency group agrees) is checked at the\n // registry level in defineSyncRegistry, where the whole table set is visible.\n if (entry.subscription !== undefined && !isSubscriptionTiming(entry.subscription)) {\n throw new Error(\n `table ${tableName} has an invalid subscription (ADR-0021): must be one of ` +\n `${SUBSCRIPTION_TIMINGS.join(\", \")} (got ${String(entry.subscription)})`,\n );\n }\n if (entry.retention !== undefined && !isRetention(entry.retention)) {\n throw new Error(\n `table ${tableName} has an invalid retention (ADR-0021): must be one of ` +\n `${RETENTIONS.join(\", \")} (got ${String(entry.retention)})`,\n );\n }\n\n // ADR-0022: write-mode is optional (default optimistic), but a declared value must be valid and\n // meaningful. `pessimistic` governs the write path, which a `readonly` table does not have, so reject\n // it there. Group-level uniformity is checked at the registry level alongside the lifecycle axes.\n if (entry.writeMode !== undefined && !isWriteMode(entry.writeMode)) {\n throw new Error(\n `table ${tableName} has an invalid writeMode (ADR-0022): must be one of ` +\n `${WRITE_MODES.join(\", \")} (got ${String(entry.writeMode)})`,\n );\n }\n if (entry.writeMode === \"pessimistic\" && entry.mode === \"readonly\") {\n throw new Error(\n `readonly table ${tableName} cannot be pessimistic (ADR-0022): write-mode governs the write path, ` +\n `which a readonly table does not have. Declare writeMode only on a writable table.`,\n );\n }\n\n // A managed field's `column` is the drizzle PROPERTY KEY of the target column, never its SQL column\n // name — ADR-0012 keeps the two distinct. Both consumers resolve by property key and canonicalise to\n // it (the client stamp in mutation.ts, the Server-version resolve in resolveServerVersionColumnName);\n // neither tolerates a column-name spelling. So a declaration that names the SQL column instead of the\n // property must fail HERE, at the boundary where declarations enter, rather than silently\n // half-resolving downstream.\n const managedFieldPropertyKeys = new Set(Object.keys(getColumns(entry.table)));\n\n // The single claim-stamping strategy (ADR-0026): an `authClaim` managed field reads a value from the\n // verified request claims at a JSON path, emitted into the apply-function DDL — so the path segments\n // must be plain identifiers and any cast a plain type name (never a value-injection surface). A\n // non-authClaim field carrying claimPath/cast is an authoring slip; reject it rather than ignore it.\n for (const field of entry.governance?.managedFields ?? []) {\n if (!managedFieldPropertyKeys.has(field.column as string)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} names an unknown column: field.column must be the ` +\n `drizzle PROPERTY KEY of the target column, not its SQL column name (ADR-0012)`,\n );\n }\n if (field.strategy === \"authClaim\") {\n if (!Array.isArray(field.claimPath) || field.claimPath.length === 0) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} (strategy \"authClaim\") must declare a non-empty ` +\n `claimPath (e.g. [\"sub\"] or [\"app_metadata\",\"person_id\"]) — ADR-0026`,\n );\n }\n for (const segment of field.claimPath) {\n if (typeof segment !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} has an invalid claimPath segment ` +\n `${JSON.stringify(segment)}: each segment must match [A-Za-z_][A-Za-z0-9_]* (it is emitted into ` +\n `the apply-function DDL)`,\n );\n }\n }\n if (field.cast !== undefined && !/^[A-Za-z_][A-Za-z0-9_ ]*$/.test(field.cast)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} has an invalid cast ${JSON.stringify(field.cast)}: ` +\n `must be a plain SQL type name (e.g. \"uuid\", \"text\")`,\n );\n }\n } else if (field.claimPath !== undefined || field.cast !== undefined) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} declares claimPath/cast but its strategy is ` +\n `\"${field.strategy}\" — those apply only to \"authClaim\"`,\n );\n }\n }\n\n const columns = Object.entries(getColumns(entry.table)).map(([propertyKey, column]) => ({\n propertyKey,\n columnName: column.name,\n column,\n }));\n const columnsByPropertyKey = new Map(columns.map((column) => [column.propertyKey, column]));\n const columnsByColumnName = new Map(columns.map((column) => [column.columnName, column]));\n const omitColumns = entry.clientProjection?.omitColumns ?? [];\n const localPrimaryKeyColumns = entry.clientProjection?.localPrimaryKey?.columns ?? [];\n\n if (omitColumns.length === 0 && localPrimaryKeyColumns.length === 0) {\n return;\n }\n\n const unknownColumns = omitColumns.filter((propertyKey) => !columnsByPropertyKey.has(propertyKey));\n\n if (unknownColumns.length > 0) {\n throw new Error(\n `clientProjection.omitColumns contains unknown columns for ${tableName}: ${unknownColumns.join(\", \")}`,\n );\n }\n\n const unknownLocalPrimaryKeyColumns = localPrimaryKeyColumns.filter(\n (columnName) => !columnsByColumnName.has(columnName),\n );\n\n if (unknownLocalPrimaryKeyColumns.length > 0) {\n throw new Error(\n `clientProjection.localPrimaryKey contains unknown columns for ${tableName}: ${unknownLocalPrimaryKeyColumns.join(\", \")}`,\n );\n }\n\n if (entry.mode !== \"readonly\" && localPrimaryKeyColumns.length > 0) {\n throw new Error(`clientProjection.localPrimaryKey is only supported for readonly table ${tableName}`);\n }\n\n const omittedColumnsSet = new Set(omitColumns);\n const omittedLocalPrimaryKeyColumns = localPrimaryKeyColumns.filter((columnName) =>\n omittedColumnsSet.has(columnName),\n );\n\n if (omittedLocalPrimaryKeyColumns.length > 0) {\n throw new Error(\n `clientProjection.localPrimaryKey must not include omitted columns for ${tableName}: ${omittedLocalPrimaryKeyColumns.join(\", \")}`,\n );\n }\n\n const primaryKeyOmissions = omitColumns.filter((propertyKey) => {\n const column = columnsByPropertyKey.get(propertyKey);\n return column\n ? entry.primaryKey.columns.includes(column.columnName) || entry.primaryKey.columns.includes(propertyKey)\n : false;\n });\n\n if (primaryKeyOmissions.length > 0) {\n if (entry.mode === \"readonly\" && localPrimaryKeyColumns.length > 0) {\n return;\n }\n\n throw new Error(\n `clientProjection.omitColumns must not omit primary-key columns for ${tableName}: ${primaryKeyOmissions.join(\", \")}`,\n );\n }\n\n if (entry.mode === \"readonly\") {\n return;\n }\n\n const createManagedColumns = new Set(\n (entry.governance?.managedFields ?? [])\n .filter((field) => field.applyOn.includes(\"create\"))\n .map((field) => field.column),\n );\n\n const createRequiredOmissions = omitColumns.filter((propertyKey) => {\n const column = columnsByPropertyKey.get(propertyKey);\n\n if (!column) {\n return false;\n }\n\n return column.column.notNull && !column.column.hasDefault && !createManagedColumns.has(propertyKey);\n });\n\n if (createRequiredOmissions.length > 0) {\n throw new Error(\n `clientProjection.omitColumns must only omit create-safe columns for writable table ${tableName}: ${createRequiredOmissions.join(\", \")}`,\n );\n }\n}\n",
11
+ "import type { z } from \"zod\";\n\n/**\n * Event-stream registration (ADR-0053 decision 1) — the contract half of the **Event lane**, the toolkit's\n * second lane beside the sync rail.\n *\n * An **Event stream** is a named, registered category of append-only client events sharing one payload\n * schema and one consumer-side handling. It is registered on the sync registry\n * (`SyncRegistryDefinition.streams`), where the record KEY is the Event-stream name, so there is one\n * contract artifact rather than a second one to lock, diff and thread through the server and the worker.\n *\n * The registration stays **declarative data only** — no functions. The gating hook (consent/entitlement\n * refusal before enqueue) is a function on `CreateSyncServerOptions`, keyed by Event-stream name, never a\n * field here.\n */\n\n/**\n * One claim-derived identity field of an Event stream: the JSON path into the **verified** request claims\n * the value is stamped from at ingest.\n *\n * The same addressing as a managed field's `authClaim` strategy (`ManagedFieldSpec.claimPath`) — `[\"sub\"]`\n * for the auth subject, `[\"app_metadata\", \"person_id\"]` for an app-minted identity — so the two\n * claim-stamping surfaces of the toolkit read identically. Identity is **server-stamped**, never\n * client-trusted: the client's envelope carries no identity at all (see `eventEnvelopeSchema`), and the\n * stamped value reaches the consumer callback on the queue envelope (`stampedEventSchema`).\n */\nexport interface EventStreamIdentityField {\n /** JSON path into the verified claims; each segment a plain identifier. Must be non-empty. */\n claimPath: readonly string[];\n}\n\n/**\n * A registered Event stream: its payload contract and its claim→identity stamping rule.\n *\n * `payload` is a **strict** zod schema, and strictness is ENFORCED, not merely advertised: an object-rooted\n * payload (including every object inside a union or discriminated union) must carry a `never` catchall —\n * `.strict()` or `z.strictObject()` — or `defineSyncRegistry` rejects the registration. A stripping object\n * would let a misspelled or newly-added key vanish between the caller and the consumer with no verdict\n * anywhere, which is exactly the silence the Event lane's \"everything in the Outbox is well-formed\"\n * invariant exists to prevent. A NON-object root (a string, array, record, a transform pipeline, …) is\n * accepted unchanged and follows ordinary parse-contract semantics: what the schema ACCEPTS is what\n * `appendEvent` validates, and the JSON-NORMALIZED form of what the schema PRODUCES is what the consumer\n * receives.\n *\n * **The schema EXECUTES at both boundaries; only ONE execution's output is taken.** `appendEvent` runs it as\n * pure validation — the result is discarded and the Outbox stores the value the caller supplied — and the\n * ingestion endpoint runs it again as the one AUTHORITATIVE parse, whose output is what is enqueued and what\n * the consumer callback receives. A transform callback therefore runs twice, so **transforms must be pure\n * and deterministic**: an effectful or environment-dependent one is unsupported, because the server's run is\n * the one that counts and nothing reconciles it against the client's. Parse output the JSON value domain\n * cannot carry (a `BigInt`, `undefined`) is a terminal per-event `rejected` at ingest, never a batch fault.\n *\n * **What is enqueued is the JSON-NORMALIZED parse output, not the parse output itself.** Ingest serializes\n * the authoritative parse's result and enqueues the round-trip, so every queue backend — the in-memory fake\n * and real pgmq's `jsonb` alike — delivers the identical value. The consequence is worth designing against:\n * a transform producing a `Date` reaches the consumer as that date's ISO STRING, and a nested `undefined`\n * property is dropped (an `undefined` array member becomes `null`). A transform that must round-trip as a\n * rich type has to encode it itself.\n *\n * **Schema evolution is compatibility-bound** (ADR-0053 decision 1): a payload schema may evolve only\n * backward-compatibly — it must keep accepting every previously-valid payload, because events written\n * offline under the old schema are still in flight. An incompatible change requires a NEW Event-stream\n * name. The registry lock records a hash of this entry so a change is a reviewable `risky` diff; the hash\n * DETECTS change, it cannot judge compatibility (see `registryEventStreams`).\n */\nexport interface EventStreamEntry<TPayload extends z.ZodType = z.ZodType> {\n payload: TPayload;\n /**\n * The identity fields stamped server-side from verified claims, keyed by field name. The stamped record\n * (field name → value) is what the consumer callback receives on every event.\n */\n identity: Record<string, EventStreamIdentityField>;\n /**\n * An opaque version counter for the part of this payload contract the lock's hash cannot see — the same\n * role `RowFilterSpec.revision` plays for a `customPredicate` closure. The lock hashes the payload schema as\n * a **JSON Schema**, and refinements/transforms are simply not representable there: a reviewer\n * demonstrated that `z.string().refine(v => v.length >= 3)` and the INCOMPATIBLE `>= 10` version produce\n * the identical stream hash, so the `risky` diff the ADR relies on never fires.\n *\n * So: whenever you change acceptance logic a JSON Schema cannot express (any `.refine`/`.superRefine`\n * threshold, a cross-field check, a transform), you MUST bump `revision` (positive integer). That is\n * what surfaces the change in the lock diff, where the compatibility rule can actually be reviewed.\n * Leaving it unchanged after a refinement change silently bypasses the gate.\n */\n revision?: number;\n}\n\n/** A registry's Event streams, keyed by Event-stream name (the key IS the name). */\nexport type EventStreamRegistry = Record<string, EventStreamEntry>;\n\n/** The payload TYPE of a registered Event stream — what `appendEvent` accepts for it. */\nexport type EventStreamPayload<TEntry extends EventStreamEntry> =\n TEntry extends EventStreamEntry<infer TPayload> ? z.infer<TPayload> : never;\n\n/**\n * The queue-name prefix each Event stream's pgmq queue is provisioned under (`pgxsinkit_events_<stream>`,\n * ADR-0053 decision 5). Its length is what bounds {@link EVENT_STREAM_NAME_MAX_LENGTH}.\n */\nexport const EVENT_STREAM_QUEUE_PREFIX = \"pgxsinkit_events_\";\n\n/**\n * The maximum length of an Event-stream name: **30**. pgmq's queue-name limit is 47 characters and\n * {@link EVENT_STREAM_QUEUE_PREFIX} consumes 17 of them, so a longer name could not be provisioned. The\n * bound is enforced at `defineSyncRegistry` (module eval) rather than at deployment DDL, because a name\n * that fails only when the queue is created fails far too late.\n */\nexport const EVENT_STREAM_NAME_MAX_LENGTH = 47 - EVENT_STREAM_QUEUE_PREFIX.length;\n\n/**\n * Event-stream names are lowercase `[a-z][a-z0-9_]*` — the intersection of what pgmq accepts unquoted and\n * what stays legible as a queue/table suffix.\n */\nexport const EVENT_STREAM_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;\n\n/**\n * Declare one Event stream for a registry's `streams` map.\n *\n * The Event-stream NAME is the record key it is registered under, so it is not named here — the name (and\n * this entry's payload/identity shape) is validated fail-closed at `defineSyncRegistry`, which sees the\n * whole map and reports EVERY offender in one error rather than one per build.\n *\n * ```ts\n * import { z } from \"zod\";\n *\n * export const registry = defineSyncRegistry({\n * tables: { issue },\n * streams: {\n * board_issue_viewed: defineEventStream({\n * payload: z.object({ issueId: z.uuid() }).strict(),\n * identity: { viewerId: { claimPath: [\"sub\"] } },\n * }),\n * },\n * });\n * ```\n */\nexport function defineEventStream<const TPayload extends z.ZodType>(input: {\n payload: TPayload;\n identity: Record<string, EventStreamIdentityField>;\n /** Bump on every change the JSON-Schema hash cannot see. See {@link EventStreamEntry.revision}. */\n revision?: number;\n}): EventStreamEntry<TPayload> {\n return {\n payload: input.payload,\n identity: input.identity,\n ...(input.revision != null ? { revision: input.revision } : {}),\n };\n}\n\n/**\n * Whether a value walks and quacks like a zod schema.\n *\n * Duck-typed on `safeParse` (the capability `appendEvent` and the ingest endpoint actually use) rather\n * than `instanceof z.ZodType`: zod is a PEER dependency, so a consumer with a duplicated zod install would\n * fail an `instanceof` against a schema that is perfectly usable.\n */\nexport function isZodSchema(value: unknown): value is z.ZodType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === \"function\" &&\n typeof (value as { parse?: unknown }).parse === \"function\"\n );\n}\n\n/** The bits of zod v4's internal `_zod.def` this module reads. Kept structural — zod is a PEER dependency. */\ninterface ZodDefLike {\n type?: unknown;\n catchall?: unknown;\n options?: unknown;\n}\n\nfunction zodDefOf(schema: unknown): ZodDefLike | undefined {\n const def = (schema as { _zod?: { def?: unknown } } | null | undefined)?._zod?.def;\n return def != null && typeof def === \"object\" ? (def as ZodDefLike) : undefined;\n}\n\n/**\n * Whether an Event stream's payload schema has a NON-strict object at its root — the one shape\n * `validateEventStreams` refuses (ADR-0053 decision 1: the payload contract is strict, and the promise is\n * enforced rather than advertised).\n *\n * zod v4 models strictness as the object's **catchall**: `.strict()` / `z.strictObject()` set it to\n * `ZodNever`, a bare `z.object()` leaves it unset (unknown keys are silently STRIPPED), and\n * `z.looseObject()` / `.catchall(…)` set something else. So the rule is exactly \"an object root's catchall\n * must be `never`\", read off `_zod.def` — the same duck-typed posture as {@link isZodSchema}, never an\n * `instanceof` a peer-installed class.\n *\n * A union (or discriminated union) is walked recursively, because each member is equally a root the client\n * may append against. Every other root — string, array, record, a `.transform()` pipeline — is NOT an\n * object and is accepted unchanged. A schema whose internals cannot be read at all (a duplicated zod\n * install, a hand-rolled duck-typed schema) is likewise accepted: this check can only refuse what it can\n * actually see.\n */\nexport function hasNonStrictObjectRoot(schema: unknown): boolean {\n const seen = new Set<unknown>();\n const walk = (candidate: unknown): boolean => {\n if (candidate == null || seen.has(candidate)) {\n return false;\n }\n seen.add(candidate);\n const def = zodDefOf(candidate);\n if (!def) {\n return false;\n }\n if (def.type === \"object\") {\n return zodDefOf(def.catchall)?.type !== \"never\";\n }\n if (def.type === \"union\" && Array.isArray(def.options)) {\n return def.options.some(walk);\n }\n return false;\n };\n return walk(schema);\n}\n",
11
12
  "/**\n * The single SQL identifier and literal resolver (ADR-0004).\n *\n * Every package routes identifier quoting and literal escaping through this module\n * so there is exactly one definition of \"what is a bare-safe identifier\", the\n * reserved-word set, quoting, and string-literal escaping. Previously five-plus\n * copies disagreed — one of them (the client mutation path) left reserved-word\n * table names unquoted, the same class of bug the local-schema generator had to fix.\n *\n * Note: this is the bare-quoting concern. Validation guards that merely assert a\n * value is a syntactically valid identifier (e.g. allowing uppercase, which is legal\n * but must be quoted) are a distinct concern and live with their callers.\n */\n\n// PostgreSQL fully-reserved keywords: cannot be used as a bare identifier.\nconst RESERVED_SQL_KEYWORDS = new Set([\n \"all\",\n \"analyse\",\n \"analyze\",\n \"and\",\n \"any\",\n \"array\",\n \"as\",\n \"asc\",\n \"asymmetric\",\n \"both\",\n \"case\",\n \"cast\",\n \"check\",\n \"collate\",\n \"column\",\n \"constraint\",\n \"create\",\n \"current_catalog\",\n \"current_date\",\n \"current_role\",\n \"current_time\",\n \"current_timestamp\",\n \"current_user\",\n \"default\",\n \"deferrable\",\n \"desc\",\n \"distinct\",\n \"do\",\n \"else\",\n \"end\",\n \"except\",\n \"false\",\n \"fetch\",\n \"for\",\n \"foreign\",\n \"from\",\n \"grant\",\n \"group\",\n \"having\",\n \"in\",\n \"initially\",\n \"intersect\",\n \"into\",\n \"lateral\",\n \"leading\",\n \"limit\",\n \"localtime\",\n \"localtimestamp\",\n \"not\",\n \"null\",\n \"offset\",\n \"on\",\n \"only\",\n \"or\",\n \"order\",\n \"placing\",\n \"primary\",\n \"references\",\n \"returning\",\n \"select\",\n \"session_user\",\n \"some\",\n \"symmetric\",\n \"table\",\n \"then\",\n \"to\",\n \"trailing\",\n \"true\",\n \"union\",\n \"unique\",\n \"user\",\n \"using\",\n \"variadic\",\n \"when\",\n \"where\",\n \"window\",\n \"with\",\n]);\n\n/** Always wrap an identifier in double quotes, escaping any embedded quote. */\nexport function quoteIdentifier(value: string): string {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** Escape a SQL string-literal body (`'` -> `''`); does not add the surrounding quotes. */\nexport function escapeSqlLiteral(value: string): string {\n return value.replace(/'/g, \"''\");\n}\n\n/** A SQL string literal, surrounding quotes included. */\nexport function quoteSqlLiteral(value: string): string {\n return `'${escapeSqlLiteral(value)}'`;\n}\n\n/**\n * A bare-safe identifier: a simple lowercase identifier Postgres will neither fold\n * nor misparse. Uppercase is excluded because Postgres folds an unquoted identifier\n * to lowercase, which would change its meaning. Internal to {@link maybeQuoteIdentifier}.\n */\nfunction isSimpleIdentifier(value: string): boolean {\n return /^[a-z_][a-z0-9_]*$/.test(value);\n}\n\n/**\n * Quote only when required: bare for a simple, non-reserved identifier; quoted\n * otherwise. Keeps generated SQL stable for the common case while never emitting a\n * reserved word or mixed-case name unquoted.\n */\nexport function maybeQuoteIdentifier(value: string): string {\n if (isSimpleIdentifier(value) && !RESERVED_SQL_KEYWORDS.has(value)) {\n return value;\n }\n return quoteIdentifier(value);\n}\n",
12
13
  "import { z } from \"zod\";\n\nimport { unixMicrosecondsSchema } from \"./common\";\n\n/**\n * The **Event lane**'s wire contracts (ADR-0053 decision 3 + decision 5): the flush endpoint's request and\n * verdict bodies, the request-shape limits both sides enforce, and the stamped envelope that travels the\n * queue to the consumer callback.\n *\n * The mutation endpoint's sibling, minus what events don't need — no `seq` (a batch's internal order is\n * its array order; the Outbox's local append ordinal stays local) and no base version (nothing to conflict\n * with). Same strictness discipline as `mutation.ts`.\n */\n\n/**\n * The batch ingestion endpoint. Deliberate constants, not tuning: the client flush loop clamps its\n * batching to them and the server enforces them independently of any client's configuration.\n *\n * **`MAX_EVENTS_PER_BATCH` (1000)** — one flush batch. Large enough that a device draining an offline\n * backlog makes real progress per round trip, small enough that one batch stays a modest request and one\n * queue transaction.\n *\n * **`MAX_EVENT_PAYLOAD_BYTES` (64 KiB)** — the serialized payload of ONE event. Events are facts, not\n * documents; a payload approaching this is a modelling smell. Enforced at `appendEvent` (so the library\n * caller fails at the call site) AND at ingest, where a single oversized payload is a per-event\n * `rejected` verdict rather than a batch fault.\n *\n * **`MAX_EVENT_REQUEST_BYTES` (4 MiB)** — the whole request body, the backstop for the two above (1000\n * events × 64 KiB would exceed it, deliberately: the body cap binds first). A violation is a batch-level\n * 413, reachable only under deployment skew or from a non-library caller.\n */\nexport const MAX_EVENTS_PER_BATCH = 1000;\n/** See {@link MAX_EVENTS_PER_BATCH}. Serialized bytes of one event's payload. */\nexport const MAX_EVENT_PAYLOAD_BYTES = 64 * 1024;\n/** See {@link MAX_EVENTS_PER_BATCH}. Bytes of the whole `POST /api/events` body. */\nexport const MAX_EVENT_REQUEST_BYTES = 4 * 1024 * 1024;\n\n/**\n * The batch event-ingestion endpoint path(s) — the Event lane's twin of the mutation route's\n * `batchMutationPaths`. It lives HERE, in contracts, rather than beside the server route: the same\n * constant is the client flush loop's target and the server's mount point, and the neighbouring\n * request-shape limits are already contracts-level toolkit constants both sides read.\n */\nexport const batchEventPaths = [\"/api/events\"] as const;\n\n/**\n * One client-produced event as it crosses the wire. The library builds it (`appendEvent` stamps `eventId`\n * and `occurredAtUs`); `stream` is the registered Event-stream name.\n *\n * It carries NO identity: identity is stamped server-side from verified claims per the stream's\n * registration (see `EventStreamIdentityField`), never client-trusted. `stream` is validated only as a\n * non-empty string here — an unregistered name is a per-event `deferred` verdict (ordinary rollout skew),\n * not a framing fault.\n */\nexport const eventEnvelopeSchema = z\n .object({\n stream: z.string().trim().min(1),\n eventId: z.uuid(),\n occurredAtUs: unixMicrosecondsSchema,\n payload: z.unknown(),\n })\n .strict();\n\n/**\n * The `POST /api/events` body. A request failing this parse — or exceeding the request-shape limits — is a\n * batch-level 400/413: a malformed item without a parseable `eventId` cannot receive a per-event verdict.\n * That layer is unreachable through the library (appends are validated, envelopes are library-built); it\n * exists for library bugs and non-library callers.\n */\nexport const batchEventRequestSchema = z\n .object({\n events: z.array(eventEnvelopeSchema).min(1).max(MAX_EVENTS_PER_BATCH),\n })\n .strict();\n\n/**\n * The per-event verdict. Three of the four are TERMINAL — the client deletes the Outbox row:\n *\n * - `acked` — enqueued.\n * - `refused` — the consent/entitlement gating hook said no.\n * - `rejected` — a schema-invalid payload for a KNOWN Event stream, or an oversized payload. Given\n * append-time validation and the backward-compatibility rule, this means a non-library caller or a\n * broken consumer deployment — a bug, not a rollout.\n *\n * `deferred` is NOT terminal: an Event stream the server does not (yet) know is ordinary deployment skew\n * (a client rolled out ahead of its server), and deleting those events would be data loss on a normal\n * path. Deferred rows stay in the Outbox, retry with backoff, and drain when the rollout completes.\n */\nexport const eventAckStatusSchema = z.enum([\"acked\", \"refused\", \"rejected\", \"deferred\"]);\n\nexport const eventAckSchema = z\n .object({\n eventId: z.uuid(),\n status: eventAckStatusSchema,\n reason: z.string().trim().min(1).optional(),\n })\n .strict();\n\n/** The 2xx body: one verdict per well-formed envelope in the request. */\nexport const batchEventAckSchema = z\n .object({\n acks: z.array(eventAckSchema),\n })\n .strict();\n\n/**\n * The body of a non-2xx batch-event response. Unlike the mutation path there is NO per-item rejection\n * field: a well-formed envelope always gets a per-event verdict in a 2xx `acks` array, so a non-2xx is\n * *always* a whole-batch fault (framing, limits, auth, queue unavailable) with nothing to attribute.\n * Unknown extra fields are stripped.\n */\nexport const batchEventErrorSchema = z.object({\n message: z.string().optional(),\n});\n\n/**\n * The **stamped** envelope (ADR-0053 decision 5): what the server produces at ingest, carries through the\n * queue, and delivers to the consumer callback as-is. `identity` is the record of claim-derived fields the\n * Event stream's registration declares, resolved from the VERIFIED claims of the ingesting request.\n *\n * This is the security-sensitive interface of the lane — the point where a client-supplied event becomes\n * an attributed fact — so its shape is contracts-defined, never implementation-defined. It carries no\n * `stream` (the queue message names it once, below) and no client-supplied identity of any kind.\n */\nexport const stampedEventSchema = z\n .object({\n eventId: z.uuid(),\n occurredAtUs: unixMicrosecondsSchema,\n identity: z.record(z.string().trim().min(1), z.string()),\n payload: z.unknown(),\n })\n .strict();\n\n/**\n * One queue message: a single-stream sub-batch. The endpoint splits a mixed flush batch by Event stream\n * (preserving array order) and enqueues each sub-batch as ONE message on that stream's queue — one\n * visibility timeout, one ack, one consumer transaction per message. Events arrive at the callback in\n * append order WITHIN a message; across messages there is no ordering promise (ADR-0053 decision 6).\n */\nexport const eventQueueMessageSchema = z\n .object({\n stream: z.string().trim().min(1),\n events: z.array(stampedEventSchema).min(1),\n })\n .strict();\n\nexport type EventEnvelope = z.infer<typeof eventEnvelopeSchema>;\nexport type BatchEventRequest = z.infer<typeof batchEventRequestSchema>;\nexport type EventAckStatus = z.infer<typeof eventAckStatusSchema>;\nexport type EventAck = z.infer<typeof eventAckSchema>;\nexport type BatchEventAck = z.infer<typeof batchEventAckSchema>;\nexport type BatchEventError = z.infer<typeof batchEventErrorSchema>;\nexport type StampedEvent = z.infer<typeof stampedEventSchema>;\nexport type EventQueueMessage = z.infer<typeof eventQueueMessageSchema>;\n",
13
- "import { getTableConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport type { RowFilterSpec } from \"./config\";\nimport type { SyncTableEntry, SyncTableRegistry } from \"./registry\";\n\n/**\n * The registry fingerprint (ADR-0004): a stable, order-independent description of\n * the shape-relevant registry metadata, plus a hash of it.\n *\n * This is the single source of \"has the shape changed\" — consumed as the local-DB\n * version key and as the basis of the registry-diff gate (ADR-0006). Function *bodies*\n * (`rowTransform`, `customWhere`) cannot be fingerprinted and are excluded — but their\n * *presence* and the surrounding **static** filter structure (the projected columns)\n * participate. For the invisible *logic* itself, a consumer-bumped `rowFilter.revision` is\n * folded in: changing it is how a `customWhere` authorization change is forced to shift the\n * fingerprint (and so rebuild the cache + reset the subscription).\n */\n\nexport interface CanonicalColumn {\n name: string;\n type: string;\n notNull: boolean;\n hasDefault: boolean;\n primary: boolean;\n}\n\nexport interface CanonicalTable {\n key: string;\n mode: string;\n primaryKey: string[];\n localPrimaryKey: string[] | null;\n columns: CanonicalColumn[];\n projection: {\n syncedTable: string | null;\n overlayTable: string | null;\n journalTable: string | null;\n omitColumns: string[];\n } | null;\n shape: {\n tableName: string;\n shapeKey: string;\n electricTable: string | null;\n rowFilter: CanonicalRowFilter | null;\n } | null;\n managedFields: Array<{ field: string; strategy: string; applyOn: string[] }>;\n /**\n * Consistency group (ADR-0009 decision 2). Part of the fingerprint because it decides which\n * subscription-state row a table persists under: moving a table between groups must shift the\n * fingerprint (forcing a cache rebuild + subscription reset) and surface in the diff gate. `null`\n * = the default singleton group.\n */\n consistencyGroup: string | null;\n /**\n * Retention (ADR-0021). Part of the fingerprint because it changes the cluster DDL — an `ephemeral`\n * table's whole cluster is emitted as `TEMP`/`pg_temp` — so flipping persistent↔ephemeral must force a\n * cache rebuild + subscription reset. (Subscription timing is NOT included: it is pure runtime\n * orchestration over identical tables and needs no rebuild.)\n */\n retention: string;\n}\n\n/**\n * The static, fingerprint-able structure of a row filter. A changed projection shifts the\n * fingerprint, so the local store rebuilds and the diff gate flags it. `customWhere`'s body is\n * invisible — only its presence (`hasCustomWhere`) is recorded — so a `customWhere` *logic* change\n * is surfaced only by bumping `revision`.\n */\nexport interface CanonicalRowFilter {\n hasCustomWhere: boolean;\n columns: string[] | null;\n /**\n * The consumer-supplied version tag for the non-fingerprintable filter logic (the `customWhere`\n * body). Changing it shifts the fingerprint, which is the only way a `customWhere` *logic* change\n * forces a cache + subscription reset.\n */\n revision: string | null;\n}\n\nconst byName = (a: { name: string }, b: { name: string }): number => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\nconst asString = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nfunction canonicalizeColumns(table: AnyPgTable): CanonicalColumn[] {\n return getTableConfig(table)\n .columns.map((column) => ({\n name: column.name,\n type: column.getSQLType(),\n notNull: column.notNull,\n hasDefault: column.hasDefault,\n primary: column.primary,\n }))\n .sort(byName);\n}\n\nfunction canonicalizeManagedFields(entry: SyncTableEntry): CanonicalTable[\"managedFields\"] {\n return (entry.governance?.managedFields ?? [])\n .map((field) => {\n const record = field as { propertyKey?: unknown; column?: unknown; strategy?: unknown; applyOn?: unknown };\n const name =\n typeof record.propertyKey === \"string\"\n ? record.propertyKey\n : typeof record.column === \"string\"\n ? record.column\n : \"\";\n const applyOn = Array.isArray(record.applyOn) ? [...record.applyOn].map(String).sort(asString) : [];\n const strategy = typeof record.strategy === \"string\" ? record.strategy : \"\";\n return { field: name, strategy, applyOn };\n })\n .sort((a, b) => asString(a.field, b.field));\n}\n\nfunction canonicalizeRowFilter(filter: RowFilterSpec | undefined): CanonicalRowFilter | null {\n if (!filter) {\n return null;\n }\n return {\n hasCustomWhere: filter.customWhere != null,\n columns: filter.columns ? [...filter.columns].sort(asString) : null,\n revision: filter.revision != null ? String(filter.revision) : null,\n };\n}\n\nfunction canonicalizeTable(key: string, entry: SyncTableEntry): CanonicalTable {\n const projection = entry.clientProjection\n ? {\n syncedTable: entry.clientProjection.syncedTable ?? null,\n overlayTable: entry.clientProjection.overlayTable ?? null,\n journalTable: entry.clientProjection.journalTable ?? null,\n omitColumns: [...(entry.clientProjection.omitColumns ?? [])].map(String).sort(asString),\n }\n : null;\n\n const shape = entry.shape\n ? {\n tableName: entry.shape.tableName,\n shapeKey: entry.shape.shapeKey,\n electricTable: entry.shape.electricTable ?? null,\n rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),\n }\n : null;\n\n return {\n key,\n mode: entry.mode,\n primaryKey: [...entry.primaryKey.columns].sort(asString),\n localPrimaryKey: entry.clientProjection?.localPrimaryKey\n ? [...entry.clientProjection.localPrimaryKey.columns].sort(asString)\n : null,\n columns: canonicalizeColumns(entry.table),\n projection,\n shape,\n managedFields: canonicalizeManagedFields(entry),\n consistencyGroup: entry.consistencyGroup ?? null,\n retention: entry.retention ?? \"persistent\",\n };\n}\n\n/**\n * The canonical, order-independent shape of a registry. Tables are sorted by key so\n * declaration order never affects the result.\n */\nexport function canonicalizeRegistry(registry: SyncTableRegistry): CanonicalTable[] {\n return Object.entries(registry)\n .map(([key, entry]) => canonicalizeTable(key, entry))\n .sort((a, b) => asString(a.key, b.key));\n}\n\n/** A stable string serialization of the canonical registry shape. */\nexport function canonicalRegistryString(registry: SyncTableRegistry): string {\n return JSON.stringify(canonicalizeRegistry(registry));\n}\n\n/**\n * Per-registry-object memo. The full canonicalize → JSON.stringify → hash chain is walked at least twice per\n * client boot over the SAME registry object (the boot report's `registryFingerprint` and the mutation\n * runtime's `registryVersion`), and its cost scales with registry width — so cache it on the object.\n *\n * There is deliberately no invalidation: a registry is a frozen-by-convention module constant built once by\n * `defineSyncRegistry` (mutating one after handing it to a client is already undefined behaviour — the shape\n * fingerprint is what the local store's DDL and subscription state are keyed by). A `WeakMap` keeps the entry\n * exactly as long as the registry itself, so a per-request/per-tenant registry object is collected normally.\n */\nconst registryFingerprintMemo = new WeakMap<SyncTableRegistry, string>();\n\n/**\n * A stable fingerprint (hex) of the registry's shape. Identical shapes — even with\n * tables declared in a different order — produce the same fingerprint; any\n * structural change produces a different one. Memoised per registry object (see\n * {@link registryFingerprintMemo}); two structurally equal registries still fingerprint equal, memo or not.\n */\nexport function fingerprintRegistry(registry: SyncTableRegistry): string {\n const memoised = registryFingerprintMemo.get(registry);\n if (memoised !== undefined) return memoised;\n const fingerprint = hashString(canonicalRegistryString(registry));\n registryFingerprintMemo.set(registry, fingerprint);\n return fingerprint;\n}\n\n/**\n * The **read contract** of a single sync table: the subset of its canonical shape that decides what\n * data streams down and how a row is identified and filtered — synced-table name, columns, primary key\n * (and any local-PK override), column omission, and the shape (electric table + row filter). It is the\n * stable identity a writable entry shares with its {@link asReadonly} projection.\n *\n * Deliberately EXCLUDES the two axes a per-client projection may legitimately differ on:\n * - **write capability** — `mode`, the overlay/journal projection, `managedFields`, `conflictPolicy`,\n * `writeMode` (one client writes the table, another only reads it);\n * - **lifecycle orchestration** — `consistencyGroup`, `subscription`, `retention` (a client may\n * eager- or lazy-load, or group differently, without changing the data it sees).\n *\n * What it pins is the data itself: two registries that present \"the same\" logical table to different\n * clients must agree here, or those clients are silently seeing different rows/columns. As with the\n * full registry fingerprint, the `customWhere` *body* is invisible — only its presence and the\n * consumer-bumped {@link RowFilterSpec.revision} participate, so bump `revision` to force a divergence\n * a logic-only change would otherwise hide.\n */\nexport interface CanonicalReadContract {\n syncedTable: string;\n primaryKey: string[];\n localPrimaryKey: string[] | null;\n columns: CanonicalColumn[];\n omitColumns: string[];\n shape: {\n tableName: string;\n shapeKey: string;\n electricTable: string | null;\n rowFilter: CanonicalRowFilter | null;\n } | null;\n}\n\n/** The canonical {@link CanonicalReadContract} of a sync table entry (see the interface for what it omits). */\nexport function canonicalizeReadContract(entry: SyncTableEntry): CanonicalReadContract {\n const shape = entry.shape\n ? {\n tableName: entry.shape.tableName,\n shapeKey: entry.shape.shapeKey,\n electricTable: entry.shape.electricTable ?? null,\n rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),\n }\n : null;\n\n return {\n syncedTable: entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,\n primaryKey: [...entry.primaryKey.columns].sort(asString),\n localPrimaryKey: entry.clientProjection?.localPrimaryKey\n ? [...entry.clientProjection.localPrimaryKey.columns].sort(asString)\n : null,\n columns: canonicalizeColumns(entry.table),\n omitColumns: [...(entry.clientProjection?.omitColumns ?? [])].map(String).sort(asString),\n shape,\n };\n}\n\n/** A stable string serialization of a table's {@link CanonicalReadContract}. */\nexport function canonicalReadContractString(entry: SyncTableEntry): string {\n return JSON.stringify(canonicalizeReadContract(entry));\n}\n\n/**\n * A stable fingerprint (hex) of a table's {@link CanonicalReadContract}. Equal for a writable entry and\n * its {@link asReadonly} projection; the basis of the projection-consistency invariant\n * (`assertReadContractPreserved`).\n */\nexport function fingerprintReadContract(entry: SyncTableEntry): string {\n return hashString(canonicalReadContractString(entry));\n}\n\n/**\n * FNV-1a over UTF-8 bytes, returned as 16 hex chars. Pure and dependency-free so it runs\n * identically in the browser and in Bun (no crypto import). A fingerprint, not a security\n * primitive — used both for the registry shape fingerprint (ADR-0004) and for the apply-function\n * DDL fingerprint embedded in the generated migration (ADR-0018).\n *\n * The 64-bit state is carried in TWO 32-bit Number lanes rather than a BigInt, because this runs over\n * multi-KB payloads on the boot critical path (the local-schema fingerprint hashes the whole generated\n * durable DDL) and a BigInt allocates per byte. The output is IDENTICAL — same algorithm, same offset\n * basis, same prime, same modulo-2^64 truncation — and it MUST stay that way: the values are PERSISTED\n * (`registry_fingerprint`, the `lsf1` local-schema fingerprint, the `apply` DDL fingerprint), so a\n * changed value would silently wipe every existing store's read cache. `tests/unit/registry-fingerprint`\n * pins goldens against the original BigInt implementation as the oracle.\n *\n * Why plain Numbers are exact here: the prime 0x100000001b3 splits into small halves (high 0x100, low\n * 0x1b3), so every partial product stays under 2^42 — far inside the 2^53 integer-exact range. The lane\n * arithmetic therefore needs no `Math.imul` truncation games; only the final `% 2^32` per lane.\n */\nexport function hashString(input: string): string {\n const bytes = new TextEncoder().encode(input);\n const TWO_32 = 4294967296;\n const PRIME_LOW = 0x1b3;\n const PRIME_HIGH = 0x100;\n // The FNV-1a 64-bit offset basis 0xcbf29ce484222325, split into its two 32-bit halves.\n let high = 0xcbf29ce4;\n let low = 0x84222325;\n for (let index = 0; index < bytes.length; index += 1) {\n // The byte only ever touches the bottom 8 bits, so the XOR is confined to the low lane.\n low = (low ^ bytes[index]!) >>> 0;\n // 64-bit multiply, mod 2^64: low·primeLow feeds the low lane and carries into the high lane, which\n // also takes high·primeLow + low·primeHigh (the primeHigh·high term overflows 2^64 and is dropped).\n const lowProduct = low * PRIME_LOW;\n const carry = Math.floor(lowProduct / TWO_32);\n const nextHigh = (high * PRIME_LOW + low * PRIME_HIGH + carry) % TWO_32;\n low = lowProduct - carry * TWO_32;\n high = nextHigh;\n }\n // Two zero-padded 32-bit halves are byte-identical to padStart(16) over the joined 64-bit value.\n return high.toString(16).padStart(8, \"0\") + low.toString(16).padStart(8, \"0\");\n}\n",
14
- "import { z } from \"zod\";\n\nimport type { EventStreamEntry } from \"./event-stream\";\nimport { canonicalizeRegistry, fingerprintRegistry, hashString, type CanonicalTable } from \"./fingerprint\";\nimport { getSyncRegistryStreams, type SyncTableEntry, type SyncTableRegistry } from \"./registry\";\n\n/**\n * The registry-diff gate (ADR-0006): classify a registry change as\n * `compatible | risky | breaking` so loss-detection happens at *authoring* time, not\n * as a runtime surprise. A breaking diff is a conscious release decision — rework to\n * expand/contract, or accept-and-notify. This catches the one case the runtime cannot:\n * silent column *repurposing* (a same-named column whose type/meaning changed).\n *\n * pgxsinkit ships this mechanism; enforcement (whether a non-zero check blocks CI) is\n * the consumer's, via a committed lock that makes a breaking change a reviewable diff.\n */\n\nexport type RegistryChangeSeverity = \"compatible\" | \"risky\" | \"breaking\";\n\nconst asString = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nexport interface RegistryChange {\n severity: RegistryChangeSeverity;\n table: string;\n detail: string;\n}\n\nexport interface RegistryDiff {\n severity: RegistryChangeSeverity;\n changes: RegistryChange[];\n}\n\n/** A committed baseline of a registry's shape — the enforcement surface for the gate. */\nexport interface RegistryLock {\n version: string;\n tables: CanonicalTable[];\n /**\n * Each entry's row classification (ADR-0052), keyed by registry key; `null` = unclassified. A SIBLING of\n * `tables`, deliberately not a field of {@link CanonicalTable}: the canonical table shape is what\n * `fingerprintRegistry` hashes, and that hash is PERSISTED as the local store's cache key — so folding\n * classification into it would make merely classifying a table wipe every store's read cache. The lock\n * still records it, so an un-enrolment (a class removed or changed) is a reviewable diff.\n *\n * Optional because a committed lock is JSON on disk: one written before this field existed simply has no\n * `rowClasses`, and the diff then reads the whole baseline as unclassified — so adopting classification\n * against an old lock is a set of `compatible` declarations, never spurious risk. {@link buildRegistryLock}\n * always populates it.\n */\n rowClasses?: RegistryRowClasses;\n /**\n * Each registered Event stream (ADR-0053 decision 1), keyed by Event-stream name → a canonical hash of its\n * payload schema AND its identity declaration. A SIBLING of `tables` for the same reason `rowClasses` is:\n * the canonical table shape is what `fingerprintRegistry` hashes and that hash is the local store's\n * PERSISTED cache key, so folding an Event stream into it would make registering one wipe every store's read\n * cache — for a lane that touches no synced table, no local schema and no apply function.\n *\n * Optional because a committed lock is JSON on disk: one written before this field existed simply has no\n * `streams`, and the diff then reads the whole baseline as having none — so adopting the Event lane against\n * an old lock is a set of `compatible` additions, never spurious risk. {@link buildRegistryLock} always\n * populates it.\n */\n streams?: RegistryEventStreams;\n}\n\n/** Registry key → row class (`null` = unclassified). See {@link RegistryLock.rowClasses}. */\nexport type RegistryRowClasses = Record<string, string | null>;\n\n/** Event-stream name → canonical contract hash. See {@link RegistryLock.streams}. */\nexport type RegistryEventStreams = Record<string, string>;\n\n/** The row classification of every entry, with sorted keys so a serialized lock is stable. */\nexport function registryRowClasses(registry: SyncTableRegistry): RegistryRowClasses {\n const classes: RegistryRowClasses = {};\n for (const key of Object.keys(registry).sort()) {\n classes[key] = (registry[key] as SyncTableEntry | undefined)?.rowClass ?? null;\n }\n return classes;\n}\n\n/**\n * A stable JSON serialization with recursively SORTED object keys, so two structurally equal values\n * serialize identically regardless of key insertion order (`z.toJSONSchema`'s property order follows the\n * schema's declaration order, which an author may reshuffle without changing the contract).\n */\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([a], [b]) => asString(a, b))\n .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`);\n return `{${entries.join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/**\n * The canonical string of ONE Event stream's contract: its payload schema (as a JSON Schema, stably\n * stringified), its identity declaration (field name → claim path, sorted), and its author-supplied\n * `revision`.\n *\n * The payload is converted with `io: \"input\"` because the schema is a PARSE contract (what a client may\n * append), and with `unrepresentable: \"any\"` so a schema using a type JSON Schema cannot express degrades to\n * a coarser canonical form instead of throwing at lock time — a lock build must never fail on a legal\n * registry. The cost of that choice is under-detection for such a type, which the next two paragraphs bound.\n *\n * **The blind spot is real and named.** JSON Schema cannot express a zod refinement or transform, so\n * `z.string().refine(v => v.length >= 3)` and the incompatible `>= 10` version canonicalize identically —\n * the hash sees no change and the review gate never fires. {@link EventStreamEntry.revision} is the fix and\n * it is the AUTHOR's obligation, exactly as `RowFilterSpec.revision` is for a `customWhere` closure: bump it\n * on any acceptance-logic change the JSON Schema cannot carry, and the stream's hash shifts.\n *\n * The hash exists to DETECT change, not to VALIDATE compatibility. ADR-0053 decision 1 binds a stream's\n * payload schema to backward-compatible evolution (events written offline under the old schema are still in\n * flight) and requires a NEW Event-stream name for an incompatible change — a rule no hash can check. All the\n * lock can do is force the change to be seen and reviewed, which is what the `risky` verdict is for.\n */\nfunction canonicalEventStreamString(entry: EventStreamEntry): string {\n let payload: string;\n try {\n payload = stableStringify(z.toJSONSchema(entry.payload, { io: \"input\", unrepresentable: \"any\" }));\n } catch {\n // Defensive: an exotic schema `toJSONSchema` still refuses. A constant canonical form under-detects\n // change for that one stream rather than breaking every consumer's lock build.\n payload = '\"<unrepresentable>\"';\n }\n const identity = Object.keys(entry.identity ?? {})\n .sort(asString)\n .map((field) => [field, [...(entry.identity[field]?.claimPath ?? [])]]);\n // Absent === 0, so adopting `revision` on an unchanged stream by declaring `revision: 1` IS a change (as it\n // should be: an author only reaches for it because the invisible logic moved).\n return stableStringify({ payload, identity, revision: entry.revision ?? 0 });\n}\n\n/** The canonical contract hash of every registered Event stream, with sorted keys so a lock is stable. */\nexport function registryEventStreams(registry: SyncTableRegistry): RegistryEventStreams {\n const streams = getSyncRegistryStreams(registry);\n const hashes: RegistryEventStreams = {};\n if (!streams) {\n return hashes;\n }\n for (const name of Object.keys(streams).sort(asString)) {\n const entry = streams[name];\n if (entry) {\n hashes[name] = hashString(canonicalEventStreamString(entry));\n }\n }\n return hashes;\n}\n\nconst SEVERITY_RANK: Record<RegistryChangeSeverity, number> = { compatible: 0, risky: 1, breaking: 2 };\n\nfunction maxSeverity(changes: readonly RegistryChange[]): RegistryChangeSeverity {\n return changes.reduce<RegistryChangeSeverity>(\n (worst, change) => (SEVERITY_RANK[change.severity] > SEVERITY_RANK[worst] ? change.severity : worst),\n \"compatible\",\n );\n}\n\n/**\n * Build the committed lock (fingerprint + canonical shape + row classification + Event streams) for a\n * registry.\n */\nexport function buildRegistryLock(registry: SyncTableRegistry): RegistryLock {\n return {\n version: fingerprintRegistry(registry),\n tables: canonicalizeRegistry(registry),\n rowClasses: registryRowClasses(registry),\n streams: registryEventStreams(registry),\n };\n}\n\nfunction diffTable(table: string, previous: CanonicalTable, next: CanonicalTable, changes: RegistryChange[]): void {\n const prevColumns = new Map(previous.columns.map((column) => [column.name, column]));\n const nextColumns = new Map(next.columns.map((column) => [column.name, column]));\n\n for (const [name, prevColumn] of prevColumns) {\n const nextColumn = nextColumns.get(name);\n if (!nextColumn) {\n // A rename appears as remove + add; both are breaking, which is the safe read.\n changes.push({ severity: \"breaking\", table, detail: `column removed: ${name}` });\n continue;\n }\n if (prevColumn.type !== nextColumn.type) {\n // Same name, different type: the silent-repurposing case the runtime cannot see.\n changes.push({\n severity: \"breaking\",\n table,\n detail: `column type changed: ${name} (${prevColumn.type} -> ${nextColumn.type})`,\n });\n }\n if (!prevColumn.notNull && nextColumn.notNull) {\n changes.push({ severity: \"breaking\", table, detail: `column became NOT NULL: ${name}` });\n } else if (prevColumn.notNull && !nextColumn.notNull) {\n changes.push({ severity: \"compatible\", table, detail: `column relaxed to nullable: ${name}` });\n }\n }\n\n for (const [name, nextColumn] of nextColumns) {\n if (prevColumns.has(name)) {\n continue;\n }\n const safe = !nextColumn.notNull || nextColumn.hasDefault;\n changes.push({\n severity: safe ? \"compatible\" : \"breaking\",\n table,\n detail: safe ? `column added: ${name}` : `NOT NULL column added without default: ${name}`,\n });\n }\n\n if (JSON.stringify(previous.primaryKey) !== JSON.stringify(next.primaryKey)) {\n changes.push({ severity: \"breaking\", table, detail: \"primary key changed\" });\n }\n if (JSON.stringify(previous.localPrimaryKey) !== JSON.stringify(next.localPrimaryKey)) {\n // The local identity the overlay + journal rows are keyed on; changing it orphans\n // any owed (un-acked) writes — the runtime cannot re-key them.\n changes.push({ severity: \"breaking\", table, detail: \"local primary key changed\" });\n }\n if (previous.mode !== next.mode) {\n changes.push({ severity: \"risky\", table, detail: `mode changed: ${previous.mode} -> ${next.mode}` });\n }\n diffProjection(table, previous.projection, next.projection, changes);\n diffShape(table, previous.shape, next.shape, changes);\n if ((previous.consistencyGroup ?? null) !== (next.consistencyGroup ?? null)) {\n // A group move re-keys the table's subscription-state row (ADR-0009 decision 2): the local cache\n // columns survive, but the subscription must reset so the table re-streams under its new group.\n changes.push({\n severity: \"risky\",\n table,\n detail: `consistency group changed: ${previous.consistencyGroup ?? \"(singleton)\"} -> ${next.consistencyGroup ?? \"(singleton)\"} (re-sync required)`,\n });\n }\n if (JSON.stringify(previous.managedFields) !== JSON.stringify(next.managedFields)) {\n // Managed-field governance changes how writes are constructed/owned; a returning client\n // with owed writes authored under the old governance needs a conscious re-sync.\n changes.push({ severity: \"risky\", table, detail: \"managed fields changed (re-sync required)\" });\n }\n}\n\n/**\n * Projection changes. Renaming the synced/overlay/journal tables orphans their\n * name-coupled local data (ADR-0006) → breaking; changing the omitted-column set changes\n * which columns exist locally → a re-sync (risky).\n */\nfunction diffProjection(\n table: string,\n previous: CanonicalTable[\"projection\"],\n next: CanonicalTable[\"projection\"],\n changes: RegistryChange[],\n): void {\n for (const key of [\"syncedTable\", \"overlayTable\", \"journalTable\"] as const) {\n if ((previous?.[key] ?? null) !== (next?.[key] ?? null)) {\n changes.push({ severity: \"breaking\", table, detail: `projection ${key} changed (orphans local data)` });\n }\n }\n if (JSON.stringify(previous?.omitColumns ?? null) !== JSON.stringify(next?.omitColumns ?? null)) {\n changes.push({ severity: \"risky\", table, detail: \"omitted columns changed (re-sync required)\" });\n }\n}\n\n/**\n * Shape changes. The Electric target (table/shapeKey/electricTable) and the row filter both\n * govern which rows stream; a change to either needs a re-sync so the local cache is not left\n * holding rows selected under the old definition (risky). The row filter's `customWhere` body\n * is invisible to the fingerprint, so a change confined to it is not detectable here.\n */\nfunction diffShape(\n table: string,\n previous: CanonicalTable[\"shape\"],\n next: CanonicalTable[\"shape\"],\n changes: RegistryChange[],\n): void {\n const target = (shape: CanonicalTable[\"shape\"]): string | null =>\n shape ? `${shape.tableName}|${shape.shapeKey}|${shape.electricTable ?? \"\"}` : null;\n\n if (target(previous) !== target(next)) {\n changes.push({ severity: \"risky\", table, detail: \"shape target changed (re-sync required)\" });\n }\n if (JSON.stringify(previous?.rowFilter ?? null) !== JSON.stringify(next?.rowFilter ?? null)) {\n changes.push({ severity: \"risky\", table, detail: \"row filter changed (re-sync required)\" });\n }\n}\n\n/**\n * Row-classification changes (ADR-0052). Classification is authoring metadata, invisible to the runtime and\n * to the fingerprint — but it decides which registry invariants an entry is ENROLLED in, so a change to it\n * is exactly the kind of quiet authoring drift the gate exists to surface.\n *\n * - class → different class: `risky` (the entry left one invariant's coverage and joined another's).\n * - unclassified → classified: `compatible` (pure adoption; nothing loses coverage).\n * - classified → unclassified: `risky` (the entry un-enrols from every invariant bound to that class).\n */\nfunction diffRowClass(table: string, previous: string | null, next: string | null, changes: RegistryChange[]): void {\n if (previous === next) {\n return;\n }\n if (previous == null) {\n changes.push({ severity: \"compatible\", table, detail: `row class declared: ${next}` });\n return;\n }\n if (next == null) {\n changes.push({\n severity: \"risky\",\n table,\n detail: `row class removed: ${previous} (un-enrols from registry invariants)`,\n });\n return;\n }\n changes.push({\n severity: \"risky\",\n table,\n detail: `row class changed: ${previous} -> ${next} (review invariant enrollment)`,\n });\n}\n\n/**\n * Event-stream changes (ADR-0053 decision 1). The Event lane is invisible to the fingerprint, so the lock is\n * the ONLY place a change to it can surface.\n *\n * - added → `compatible` (a new Event stream takes nothing away; a client that does not know it appends\n * nothing to it).\n * - removed → `breaking`. Events for it are already durable in some clients' Outboxes, and a server that no\n * longer knows the stream can only park them (`deferred`, retried forever) or refuse them — the removal is\n * a deliberate release decision, exactly what the gate exists to force.\n * - payload/identity hash changed → `risky`. The hash cannot judge compatibility (see\n * {@link canonicalEventStreamString}); the rule it enforces socially is the ADR's: evolve only\n * backward-compatibly, and take a NEW Event-stream name for anything else.\n */\nfunction diffEventStreams(previous: RegistryEventStreams, next: RegistryEventStreams, changes: RegistryChange[]): void {\n for (const name of Object.keys(previous).sort(asString)) {\n const nextHash = next[name];\n if (nextHash === undefined) {\n changes.push({\n severity: \"breaking\",\n table: name,\n detail: `event stream removed: ${name} (in-flight client events will be deferred/refused)`,\n });\n continue;\n }\n if (previous[name] !== nextHash) {\n changes.push({\n severity: \"risky\",\n table: name,\n detail:\n `event stream ${name} payload/identity changed (must remain backward-compatible; ` +\n `incompatible change requires a new Event-stream name)`,\n });\n }\n }\n\n for (const name of Object.keys(next).sort(asString)) {\n if (!(name in previous)) {\n changes.push({ severity: \"compatible\", table: name, detail: `event stream added: ${name}` });\n }\n }\n}\n\n/**\n * Classify the change from one canonical registry shape to another. `rowClasses` carries each side's row\n * classification (ADR-0052) and `streams` each side's Event-stream contract hashes (ADR-0053) — both siblings\n * of the canonical tables, never fields of them (see {@link RegistryLock.rowClasses} /\n * {@link RegistryLock.streams}). An omitted side reads as entirely unclassified / streamless, which is how a\n * lock predating either field diffs as adoption rather than as spurious risk.\n *\n * `RegistryChange.table` names the SUBJECT of the change, which for an Event-stream change is the\n * Event-stream name rather than a registry table key; each such `detail` says \"event stream …\" so the\n * summary line stays unambiguous.\n */\nexport function diffCanonicalRegistries(\n previous: readonly CanonicalTable[],\n next: readonly CanonicalTable[],\n rowClasses?: { previous?: RegistryRowClasses | undefined; next?: RegistryRowClasses | undefined },\n streams?: { previous?: RegistryEventStreams | undefined; next?: RegistryEventStreams | undefined },\n): RegistryDiff {\n const changes: RegistryChange[] = [];\n const prevByKey = new Map(previous.map((table) => [table.key, table]));\n const nextByKey = new Map(next.map((table) => [table.key, table]));\n const prevClasses = rowClasses?.previous ?? {};\n const nextClasses = rowClasses?.next ?? {};\n\n for (const [key, prevTable] of prevByKey) {\n const nextTable = nextByKey.get(key);\n if (!nextTable) {\n changes.push({ severity: \"breaking\", table: key, detail: \"table removed\" });\n continue;\n }\n diffTable(key, prevTable, nextTable, changes);\n diffRowClass(key, prevClasses[key] ?? null, nextClasses[key] ?? null, changes);\n }\n\n for (const key of nextByKey.keys()) {\n if (!prevByKey.has(key)) {\n changes.push({ severity: \"compatible\", table: key, detail: \"table added\" });\n }\n }\n\n diffEventStreams(streams?.previous ?? {}, streams?.next ?? {}, changes);\n\n return { changes, severity: maxSeverity(changes) };\n}\n\n/** Classify the change between two registries. */\nexport function compareRegistries(previous: SyncTableRegistry, next: SyncTableRegistry): RegistryDiff {\n return diffCanonicalRegistries(\n canonicalizeRegistry(previous),\n canonicalizeRegistry(next),\n { previous: registryRowClasses(previous), next: registryRowClasses(next) },\n { previous: registryEventStreams(previous), next: registryEventStreams(next) },\n );\n}\n\n/** Classify a registry against a committed lock baseline. */\nexport function diffRegistryAgainstLock(registry: SyncTableRegistry, lock: RegistryLock): RegistryDiff {\n return diffCanonicalRegistries(\n lock.tables,\n canonicalizeRegistry(registry),\n { previous: lock.rowClasses, next: registryRowClasses(registry) },\n { previous: lock.streams, next: registryEventStreams(registry) },\n );\n}\n\n/**\n * The consumer-facing check: `ok` is false on a breaking diff. The consumer wires the\n * exit code (e.g. `process.exit(result.ok ? 0 : 1)`) into their own CI — pgxsinkit does\n * not reach into anyone's pipeline.\n */\nexport function runRegistryCheck(input: { registry: SyncTableRegistry; lock: RegistryLock }): {\n ok: boolean;\n diff: RegistryDiff;\n} {\n const diff = diffRegistryAgainstLock(input.registry, input.lock);\n return { ok: diff.severity !== \"breaking\", diff };\n}\n\n/** A human-readable, stable summary of a diff (one line per change). */\nexport function summarizeRegistryDiff(diff: RegistryDiff): string {\n if (diff.changes.length === 0) {\n return \"no registry changes\";\n }\n return diff.changes.map((change) => `[${change.severity}] ${change.table}: ${change.detail}`).join(\"\\n\");\n}\n",
15
- "import type { SQL } from \"drizzle-orm\";\nimport { getTableConfig, PgDialect } from \"drizzle-orm/pg-core\";\n\nimport { buildRowFilterShape, type JwtClaims, type RowFilterShape } from \"./config\";\nimport { getSyncRegistryRowClasses, type SyncTableEntry, type SyncTableRegistry } from \"./registry\";\n\n/**\n * Registry invariants (ADR-0052): assert a claim about the RENDERED authorization artifacts of every entry\n * a classification binds, evaluated against named claims personas — the whole-registry counterpart to\n * `assertReadContractPreserved`'s per-table read-contract check.\n *\n * It exists because a privacy/visibility invariant spanning many entries drifts in two structural ways that\n * per-entry review cannot catch:\n *\n * 1. **Read/write asymmetry** — the Electric row filter and the Postgres RLS policies are two engines, so one\n * can be tightened (or loosened) without the other. The assertion audits BOTH surfaces of every bound\n * entry in one predicate, so \"readable but unwritable\" (or the reverse) is a test failure, not a bug report.\n * 2. **Under-enumeration** — an invariant expressed over a hand-maintained list of tables silently stops\n * covering the registry the moment someone adds an entry. Binding by {@link SyncTableEntry.rowClass}\n * inverts that: with a declared `rowClasses` vocabulary, a new entry cannot even be registered without\n * being classified, so it joins its class's invariants by construction.\n *\n * It audits RENDERED output, so it sees things the fingerprint structurally cannot (the `customWhere` BODY\n * is a closure — only its presence and `RowFilterSpec.revision` are hashed). The trade: it sees exactly the\n * claims fixtures you give it, and nothing else.\n */\n\n/** One rendered write policy on a bound entry's Postgres table, as the invariant predicate sees it. */\nexport interface RenderedPolicy {\n /** The policy name as declared (e.g. `widgets_select_owner_or_admin`). */\n name: string;\n /** The command the policy governs: `select` | `insert` | `update` | `delete`, or `all` when undeclared. */\n command: string;\n /** The `USING` predicate rendered to inline SQL text, or `null` when the policy declares none. */\n using: string | null;\n /** The `WITH CHECK` predicate rendered to inline SQL text, or `null` when the policy declares none. */\n withCheck: string | null;\n}\n\n/** One (entry × claims fixture) cell handed to a {@link RegistryInvariantSpec.holds} predicate. */\nexport interface RegistryInvariantCell {\n /** The entry's key in the registry. */\n key: string;\n entry: SyncTableEntry;\n /** The entry's classification, or `undefined` when it carries none (possible only for a `appliesTo` predicate). */\n rowClass: string | undefined;\n /** The fixture's name, as declared in {@link RegistryInvariantSpec.claimsFixtures}. */\n fixtureName: string;\n claims: JwtClaims;\n /**\n * The read filter this entry sends to Electric FOR THESE CLAIMS — the real read pipeline's output\n * (`buildRowFilterShape`, exactly what the proxy calls per shape request).\n *\n * `null` means **unfiltered**, and covers both ways that arises: the entry declares no shape/`rowFilter`\n * at all, or its `customWhere` returned `null` for these claims (the documented \"bypass filtering, every\n * row is visible\" answer — e.g. an admin persona). Both are the same statement about what the client\n * receives, which is what an invariant reasons about; distinguish them via `entry.shape?.rowFilter` if a\n * predicate genuinely needs to.\n */\n renderedWhere: RowFilterShape | null;\n /** Every RLS policy attached to the entry's Postgres table, rendered to inline SQL text. */\n renderedPolicies: RenderedPolicy[];\n}\n\nexport interface RegistryInvariantSpec {\n /** Human name for the invariant, used as the error header (e.g. \"private rows never leave their owner\"). */\n name: string;\n /**\n * Which entries the invariant binds: a list of {@link SyncTableEntry.rowClass} values (the normal form —\n * coverage then grows with the registry), or a predicate over the entry for the rare case a class cannot\n * express. When the registry declares its `rowClasses`, a class named here that is not in that vocabulary\n * throws immediately — a typo would otherwise bind nothing and pass vacuously.\n */\n appliesTo: readonly string[] | ((entry: SyncTableEntry, key: string) => boolean);\n /**\n * The claims personas the invariant is evaluated against, by name (`{ anonymous: {}, owner: {...} }`). Every\n * bound entry is checked against every fixture; the names appear in the failure report.\n */\n claimsFixtures: Record<string, JwtClaims>;\n /**\n * The invariant itself, over ONE (entry × fixture) cell's rendered artifacts. Return `true` when it holds,\n * `false` or a reason string when it does not — a reason string is reproduced verbatim in the error, so\n * prefer it.\n */\n holds: (cell: RegistryInvariantCell) => boolean | string;\n}\n\n// Policy predicates are rendered with values INLINED, matching how `CREATE POLICY` DDL carries them (and how\n// supabase-rls.ts's own text builders render): a `$n` bind would be meaningless to compare against.\nconst policyDialect = new PgDialect();\n\nfunction renderPolicyPredicate(fragment: SQL | undefined): string | null {\n return fragment == null ? null : policyDialect.sqlToQuery(fragment.inlineParams()).sql;\n}\n\n/**\n * The write policies attached to an entry's Postgres table, rendered to inline SQL text. Read straight off\n * drizzle's own table config, so it sees exactly what the migration will emit — including policies passed\n * through `defineSyncTable`'s `policies:`/`extras:` options, which are merged into the `pgTable` extras.\n *\n * A read PROJECTION's `table` IS its owner's, so a projection reports the OWNER's policies. That is correct:\n * a projection owns no table and adds no DDL, so the owner's policies are the ones governing its rows.\n */\nfunction renderPolicies(entry: SyncTableEntry): RenderedPolicy[] {\n return getTableConfig(entry.table).policies.map((policy) => ({\n name: policy.name,\n // drizzle leaves `for` undefined when the policy does not narrow the command, which is Postgres's `ALL`.\n command: policy.for ?? \"all\",\n using: renderPolicyPredicate(policy.using),\n withCheck: renderPolicyPredicate(policy.withCheck),\n }));\n}\n\n/** The read filter for these claims, through the real pipeline the proxy uses. */\nfunction renderWhere(entry: SyncTableEntry, claims: JwtClaims): RowFilterShape | null {\n const rowFilter = entry.shape?.rowFilter;\n return rowFilter == null ? null : buildRowFilterShape(rowFilter, claims);\n}\n\nfunction boundEntries(\n registry: SyncTableRegistry,\n appliesTo: RegistryInvariantSpec[\"appliesTo\"],\n): Array<[string, SyncTableEntry]> {\n const entries = Object.entries(registry) as Array<[string, SyncTableEntry]>;\n if (typeof appliesTo === \"function\") {\n return entries.filter(([key, entry]) => appliesTo(entry, key));\n }\n const classes = new Set(appliesTo);\n return entries.filter(([, entry]) => entry.rowClass != null && classes.has(entry.rowClass));\n}\n\n/**\n * Assert a {@link RegistryInvariantSpec} over a registry: for every entry the invariant binds, and every\n * claims fixture, evaluate `holds` against the entry's RENDERED read filter and write policies. Pure audit —\n * it renders through the production code paths but changes no runtime behaviour.\n *\n * Call it at module eval beside the registry (or in a test), the same way {@link assertReadContractPreserved}\n * is called, so a violation fails closed rather than shipping.\n *\n * ```ts\n * assertRegistryInvariant(registry, {\n * name: \"private rows are never visible to an anonymous caller\",\n * appliesTo: [\"private\"],\n * claimsFixtures: { anonymous: {}, member: { sub: \"u-1\" } },\n * holds: ({ fixtureName, renderedWhere }) =>\n * fixtureName !== \"anonymous\" || renderedWhere?.where === \"false\" || \"anonymous read is not denied\",\n * });\n * ```\n *\n * Two deliberate fail-closed behaviours:\n * - An `appliesTo` class the registry's declared vocabulary does not contain throws immediately (a typo must\n * not pass as \"nothing to check\").\n * - An invariant that binds ZERO entries throws. A spec that checks nothing is a bug in the spec — nearly\n * always a wrong class name or an invariant left behind after its class was renamed — and silently passing\n * is the exact failure mode this whole mechanism exists to remove.\n *\n * Every failing cell is collected and reported together: the header names the invariant, then one\n * `entry (fixture): reason` line per violation. Never first-failure-only — you fix a classification-wide\n * problem in one pass, not one re-run per entry.\n */\nexport function assertRegistryInvariant(registry: SyncTableRegistry, spec: RegistryInvariantSpec): void {\n const declaredClasses = getSyncRegistryRowClasses(registry);\n if (Array.isArray(spec.appliesTo) && declaredClasses != null) {\n const unknown = spec.appliesTo.filter((rowClass) => !declaredClasses.includes(rowClass));\n if (unknown.length > 0) {\n throw new Error(\n `registry invariant \"${spec.name}\" applies to unknown row class(es): ${unknown.join(\", \")}. This ` +\n `registry declares [${declaredClasses.join(\", \")}] — a misspelled class would bind no entries and ` +\n `pass vacuously, so it is rejected here.`,\n );\n }\n }\n\n const bound = boundEntries(registry, spec.appliesTo);\n if (bound.length === 0) {\n const binding = Array.isArray(spec.appliesTo) ? `row class(es) ${spec.appliesTo.join(\", \")}` : \"its predicate\";\n throw new Error(\n `registry invariant \"${spec.name}\" binds no entries (${binding}). An invariant that checks nothing ` +\n `passes vacuously, which defeats the point — check the class name(s) against the entries' rowClass, ` +\n `or drop the invariant if its rows are gone.`,\n );\n }\n\n const fixtures = Object.entries(spec.claimsFixtures);\n if (fixtures.length === 0) {\n throw new Error(\n `registry invariant \"${spec.name}\" declares no claims fixtures: the invariant is evaluated per persona, ` +\n `so with none it checks nothing. Declare at least one (e.g. { anonymous: {} }).`,\n );\n }\n\n const violations: string[] = [];\n for (const [key, entry] of bound) {\n const renderedPolicies = renderPolicies(entry);\n for (const [fixtureName, claims] of fixtures) {\n const verdict = spec.holds({\n key,\n entry,\n rowClass: entry.rowClass,\n fixtureName,\n claims,\n renderedWhere: renderWhere(entry, claims),\n renderedPolicies,\n });\n if (verdict === true) {\n continue;\n }\n violations.push(`${key} (${fixtureName}): ${typeof verdict === \"string\" ? verdict : \"invariant does not hold\"}`);\n }\n }\n\n if (violations.length > 0) {\n throw new Error(\n `registry invariant \"${spec.name}\" is violated by ${violations.length} of ${bound.length * fixtures.length} ` +\n `checked cells:\\n ${violations.join(\"\\n \")}`,\n );\n }\n}\n",
14
+ "import { getTableConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport type { RowFilterSpec } from \"./config\";\nimport {\n isAndPredicate,\n isInSubqueryPredicate,\n isIsNullPredicate,\n isNotPredicate,\n isOrPredicate,\n type Predicate,\n} from \"./predicate\";\nimport type { SyncTableEntry, SyncTableRegistry } from \"./registry\";\n\n/**\n * The registry fingerprint (ADR-0004): a stable, order-independent description of\n * the shape-relevant registry metadata, plus a hash of it.\n *\n * This is the single source of \"has the shape changed\" — consumed as the local-DB\n * version key and as the basis of the registry-diff gate (ADR-0006). Function *bodies*\n * (`rowTransform`, `customPredicate`) cannot be fingerprinted and are excluded — but their\n * *presence* and the surrounding **static** filter structure (the projected columns)\n * participate. For the invisible *logic* itself, a consumer-bumped `rowFilter.revision` is\n * folded in: changing it is how a `customPredicate` authorization change is forced to shift the\n * fingerprint (and so rebuild the cache + reset the subscription).\n */\n\nexport interface CanonicalColumn {\n name: string;\n type: string;\n notNull: boolean;\n hasDefault: boolean;\n primary: boolean;\n}\n\nexport interface CanonicalTable {\n key: string;\n mode: string;\n primaryKey: string[];\n localPrimaryKey: string[] | null;\n columns: CanonicalColumn[];\n projection: {\n syncedTable: string | null;\n overlayTable: string | null;\n journalTable: string | null;\n omitColumns: string[];\n } | null;\n shape: {\n tableName: string;\n shapeKey: string;\n physicalTable: string | null;\n rowFilter: CanonicalRowFilter | null;\n /** Shared-tier scope columns, in declaration order — the order parameterizes the family. */\n scope: string[] | null;\n /**\n * The native static predicate, canonicalized in full.\n *\n * Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only\n * ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing\n * a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.\n */\n where: string | null;\n } | null;\n managedFields: Array<{ field: string; strategy: string; applyOn: string[] }>;\n /**\n * Consistency group (ADR-0009 decision 2). Part of the fingerprint because it decides which\n * subscription-state row a table persists under: moving a table between groups must shift the\n * fingerprint (forcing a cache rebuild + subscription reset) and surface in the diff gate. `null`\n * = the default singleton group.\n */\n consistencyGroup: string | null;\n /**\n * Retention (ADR-0021). Part of the fingerprint because it changes the cluster DDL — an `ephemeral`\n * table's whole cluster is emitted as `TEMP`/`pg_temp` — so flipping persistent↔ephemeral must force a\n * cache rebuild + subscription reset. (Subscription timing is NOT included: it is pure runtime\n * orchestration over identical tables and needs no rebuild.)\n */\n retention: string;\n}\n\n/**\n * The static, fingerprint-able structure of a row filter. A changed projection shifts the\n * fingerprint, so the local store rebuilds and the diff gate flags it. `customPredicate`'s body is\n * invisible — only its presence (`hasCustomPredicate`) is recorded — so a `customPredicate` *logic* change\n * is surfaced only by bumping `revision`.\n */\nexport interface CanonicalRowFilter {\n hasCustomPredicate: boolean;\n columns: string[] | null;\n /**\n * The consumer-supplied version tag for the non-fingerprintable filter logic (the `customPredicate`\n * body). Changing it shifts the fingerprint, which is the only way a `customPredicate` *logic* change\n * forces a cache + subscription reset.\n */\n revision: string | null;\n}\n\nconst byName = (a: { name: string }, b: { name: string }): number => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\nconst asString = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nfunction canonicalizeColumns(table: AnyPgTable): CanonicalColumn[] {\n return getTableConfig(table)\n .columns.map((column) => ({\n name: column.name,\n type: column.getSQLType(),\n notNull: column.notNull,\n hasDefault: column.hasDefault,\n primary: column.primary,\n }))\n .sort(byName);\n}\n\nfunction canonicalizeManagedFields(entry: SyncTableEntry): CanonicalTable[\"managedFields\"] {\n return (entry.governance?.managedFields ?? [])\n .map((field) => {\n const record = field as { propertyKey?: unknown; column?: unknown; strategy?: unknown; applyOn?: unknown };\n const name =\n typeof record.propertyKey === \"string\"\n ? record.propertyKey\n : typeof record.column === \"string\"\n ? record.column\n : \"\";\n const applyOn = Array.isArray(record.applyOn) ? [...record.applyOn].map(String).sort(asString) : [];\n const strategy = typeof record.strategy === \"string\" ? record.strategy : \"\";\n return { field: name, strategy, applyOn };\n })\n .sort((a, b) => asString(a.field, b.field));\n}\n\n/**\n * A stable string form of a native predicate.\n *\n * Keys are emitted in a fixed order rather than serialized as authored, so two predicates that\n * differ only in how their object literals were written fingerprint identically — otherwise a\n * cosmetic edit would force every client to rebuild its local cache.\n */\nfunction canonicalizePredicate(node: Predicate | undefined): string | null {\n if (node === undefined) return null;\n const render = (current: Predicate): unknown => {\n if (isAndPredicate(current)) return { and: current.and.map(render) };\n if (isOrPredicate(current)) return { or: current.or.map(render) };\n if (isNotPredicate(current)) return { not: render(current.not) };\n if (isInSubqueryPredicate(current)) {\n return {\n col: current.col,\n in: {\n table: current.in.table,\n project: current.in.project,\n where: current.in.where ? render(current.in.where) : null,\n },\n negated: current.negated === true,\n };\n }\n if (isIsNullPredicate(current)) return { col: current.col, isNull: current.isNull };\n return { col: current.col, op: current.op, value: current.value };\n };\n return JSON.stringify(render(node));\n}\n\nfunction canonicalizeRowFilter(filter: RowFilterSpec | undefined): CanonicalRowFilter | null {\n if (!filter) {\n return null;\n }\n return {\n hasCustomPredicate: filter.customPredicate != null,\n columns: filter.columns ? [...filter.columns].sort(asString) : null,\n revision: filter.revision != null ? String(filter.revision) : null,\n };\n}\n\nfunction canonicalizeTable(key: string, entry: SyncTableEntry): CanonicalTable {\n const projection = entry.clientProjection\n ? {\n syncedTable: entry.clientProjection.syncedTable ?? null,\n overlayTable: entry.clientProjection.overlayTable ?? null,\n journalTable: entry.clientProjection.journalTable ?? null,\n omitColumns: [...(entry.clientProjection.omitColumns ?? [])].map(String).sort(asString),\n }\n : null;\n\n const shape = entry.shape\n ? {\n tableName: entry.shape.tableName,\n shapeKey: entry.shape.shapeKey,\n physicalTable: entry.shape.physicalTable ?? null,\n rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),\n scope: entry.shape.scope ? [...entry.shape.scope] : null,\n where: canonicalizePredicate(entry.shape.where),\n }\n : null;\n\n return {\n key,\n mode: entry.mode,\n primaryKey: [...entry.primaryKey.columns].sort(asString),\n localPrimaryKey: entry.clientProjection?.localPrimaryKey\n ? [...entry.clientProjection.localPrimaryKey.columns].sort(asString)\n : null,\n columns: canonicalizeColumns(entry.table),\n projection,\n shape,\n managedFields: canonicalizeManagedFields(entry),\n consistencyGroup: entry.consistencyGroup ?? null,\n retention: entry.retention ?? \"persistent\",\n };\n}\n\n/**\n * The canonical, order-independent shape of a registry. Tables are sorted by key so\n * declaration order never affects the result.\n */\nexport function canonicalizeRegistry(registry: SyncTableRegistry): CanonicalTable[] {\n return Object.entries(registry)\n .map(([key, entry]) => canonicalizeTable(key, entry))\n .sort((a, b) => asString(a.key, b.key));\n}\n\n/** A stable string serialization of the canonical registry shape. */\nexport function canonicalRegistryString(registry: SyncTableRegistry): string {\n return JSON.stringify(canonicalizeRegistry(registry));\n}\n\n/**\n * Per-registry-object memo. The full canonicalize → JSON.stringify → hash chain is walked at least twice per\n * client boot over the SAME registry object (the boot report's `registryFingerprint` and the mutation\n * runtime's `registryVersion`), and its cost scales with registry width — so cache it on the object.\n *\n * There is deliberately no invalidation: a registry is a frozen-by-convention module constant built once by\n * `defineSyncRegistry` (mutating one after handing it to a client is already undefined behaviour — the shape\n * fingerprint is what the local store's DDL and subscription state are keyed by). A `WeakMap` keeps the entry\n * exactly as long as the registry itself, so a per-request/per-tenant registry object is collected normally.\n */\nconst registryFingerprintMemo = new WeakMap<SyncTableRegistry, string>();\n\n/**\n * A stable fingerprint (hex) of the registry's shape. Identical shapes — even with\n * tables declared in a different order — produce the same fingerprint; any\n * structural change produces a different one. Memoised per registry object (see\n * {@link registryFingerprintMemo}); two structurally equal registries still fingerprint equal, memo or not.\n */\nexport function fingerprintRegistry(registry: SyncTableRegistry): string {\n const memoised = registryFingerprintMemo.get(registry);\n if (memoised !== undefined) return memoised;\n const fingerprint = hashString(canonicalRegistryString(registry));\n registryFingerprintMemo.set(registry, fingerprint);\n return fingerprint;\n}\n\n/**\n * The **read contract** of a single sync table: the subset of its canonical shape that decides what\n * data streams down and how a row is identified and filtered — synced-table name, columns, primary key\n * (and any local-PK override), column omission, and the shape (physical table + row filter). It is the\n * stable identity a writable entry shares with its {@link asReadonly} projection.\n *\n * Deliberately EXCLUDES the two axes a per-client projection may legitimately differ on:\n * - **write capability** — `mode`, the overlay/journal projection, `managedFields`, `conflictPolicy`,\n * `writeMode` (one client writes the table, another only reads it);\n * - **lifecycle orchestration** — `consistencyGroup`, `subscription`, `retention` (a client may\n * eager- or lazy-load, or group differently, without changing the data it sees).\n *\n * What it pins is the data itself: two registries that present \"the same\" logical table to different\n * clients must agree here, or those clients are silently seeing different rows/columns. As with the\n * full registry fingerprint, the `customPredicate` *body* is invisible — only its presence and the\n * consumer-bumped {@link RowFilterSpec.revision} participate, so bump `revision` to force a divergence\n * a logic-only change would otherwise hide.\n */\nexport interface CanonicalReadContract {\n syncedTable: string;\n primaryKey: string[];\n localPrimaryKey: string[] | null;\n columns: CanonicalColumn[];\n omitColumns: string[];\n shape: {\n tableName: string;\n shapeKey: string;\n physicalTable: string | null;\n rowFilter: CanonicalRowFilter | null;\n /** Shared-tier scope columns, in declaration order — the order parameterizes the family. */\n scope: string[] | null;\n /**\n * The native static predicate, canonicalized in full.\n *\n * Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only\n * ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing\n * a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.\n */\n where: string | null;\n } | null;\n}\n\n/** The canonical {@link CanonicalReadContract} of a sync table entry (see the interface for what it omits). */\nexport function canonicalizeReadContract(entry: SyncTableEntry): CanonicalReadContract {\n const shape = entry.shape\n ? {\n tableName: entry.shape.tableName,\n shapeKey: entry.shape.shapeKey,\n physicalTable: entry.shape.physicalTable ?? null,\n rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),\n scope: entry.shape.scope ? [...entry.shape.scope] : null,\n where: canonicalizePredicate(entry.shape.where),\n }\n : null;\n\n return {\n syncedTable: entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,\n primaryKey: [...entry.primaryKey.columns].sort(asString),\n localPrimaryKey: entry.clientProjection?.localPrimaryKey\n ? [...entry.clientProjection.localPrimaryKey.columns].sort(asString)\n : null,\n columns: canonicalizeColumns(entry.table),\n omitColumns: [...(entry.clientProjection?.omitColumns ?? [])].map(String).sort(asString),\n shape,\n };\n}\n\n/** A stable string serialization of a table's {@link CanonicalReadContract}. */\nexport function canonicalReadContractString(entry: SyncTableEntry): string {\n return JSON.stringify(canonicalizeReadContract(entry));\n}\n\n/**\n * A stable fingerprint (hex) of a table's {@link CanonicalReadContract}. Equal for a writable entry and\n * its {@link asReadonly} projection; the basis of the projection-consistency invariant\n * (`assertReadContractPreserved`).\n */\nexport function fingerprintReadContract(entry: SyncTableEntry): string {\n return hashString(canonicalReadContractString(entry));\n}\n\n/**\n * FNV-1a over UTF-8 bytes, returned as 16 hex chars. Pure and dependency-free so it runs\n * identically in the browser and in Bun (no crypto import). A fingerprint, not a security\n * primitive — used both for the registry shape fingerprint (ADR-0004) and for the apply-function\n * DDL fingerprint embedded in the generated migration (ADR-0018).\n *\n * The 64-bit state is carried in TWO 32-bit Number lanes rather than a BigInt, because this runs over\n * multi-KB payloads on the boot critical path (the local-schema fingerprint hashes the whole generated\n * durable DDL) and a BigInt allocates per byte. The output is IDENTICAL — same algorithm, same offset\n * basis, same prime, same modulo-2^64 truncation — and it MUST stay that way: the values are PERSISTED\n * (`registry_fingerprint`, the `lsf1` local-schema fingerprint, the `apply` DDL fingerprint), so a\n * changed value would silently wipe every existing store's read cache. `tests/unit/registry-fingerprint`\n * pins goldens against the original BigInt implementation as the oracle.\n *\n * Why plain Numbers are exact here: the prime 0x100000001b3 splits into small halves (high 0x100, low\n * 0x1b3), so every partial product stays under 2^42 — far inside the 2^53 integer-exact range. The lane\n * arithmetic therefore needs no `Math.imul` truncation games; only the final `% 2^32` per lane.\n */\nexport function hashString(input: string): string {\n const bytes = new TextEncoder().encode(input);\n const TWO_32 = 4294967296;\n const PRIME_LOW = 0x1b3;\n const PRIME_HIGH = 0x100;\n // The FNV-1a 64-bit offset basis 0xcbf29ce484222325, split into its two 32-bit halves.\n let high = 0xcbf29ce4;\n let low = 0x84222325;\n for (let index = 0; index < bytes.length; index += 1) {\n // The byte only ever touches the bottom 8 bits, so the XOR is confined to the low lane.\n low = (low ^ bytes[index]!) >>> 0;\n // 64-bit multiply, mod 2^64: low·primeLow feeds the low lane and carries into the high lane, which\n // also takes high·primeLow + low·primeHigh (the primeHigh·high term overflows 2^64 and is dropped).\n const lowProduct = low * PRIME_LOW;\n const carry = Math.floor(lowProduct / TWO_32);\n const nextHigh = (high * PRIME_LOW + low * PRIME_HIGH + carry) % TWO_32;\n low = lowProduct - carry * TWO_32;\n high = nextHigh;\n }\n // Two zero-padded 32-bit halves are byte-identical to padStart(16) over the joined 64-bit value.\n return high.toString(16).padStart(8, \"0\") + low.toString(16).padStart(8, \"0\");\n}\n",
15
+ "import { z } from \"zod\";\n\nimport type { EventStreamEntry } from \"./event-stream\";\nimport { canonicalizeRegistry, fingerprintRegistry, hashString, type CanonicalTable } from \"./fingerprint\";\nimport { getSyncRegistryStreams, type SyncTableEntry, type SyncTableRegistry } from \"./registry\";\n\n/**\n * The registry-diff gate (ADR-0006): classify a registry change as\n * `compatible | risky | breaking` so loss-detection happens at *authoring* time, not\n * as a runtime surprise. A breaking diff is a conscious release decision — rework to\n * expand/contract, or accept-and-notify. This catches the one case the runtime cannot:\n * silent column *repurposing* (a same-named column whose type/meaning changed).\n *\n * pgxsinkit ships this mechanism; enforcement (whether a non-zero check blocks CI) is\n * the consumer's, via a committed lock that makes a breaking change a reviewable diff.\n */\n\nexport type RegistryChangeSeverity = \"compatible\" | \"risky\" | \"breaking\";\n\nconst asString = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nexport interface RegistryChange {\n severity: RegistryChangeSeverity;\n table: string;\n detail: string;\n}\n\nexport interface RegistryDiff {\n severity: RegistryChangeSeverity;\n changes: RegistryChange[];\n}\n\n/** A committed baseline of a registry's shape — the enforcement surface for the gate. */\nexport interface RegistryLock {\n version: string;\n tables: CanonicalTable[];\n /**\n * Each entry's row classification (ADR-0052), keyed by registry key; `null` = unclassified. A SIBLING of\n * `tables`, deliberately not a field of {@link CanonicalTable}: the canonical table shape is what\n * `fingerprintRegistry` hashes, and that hash is PERSISTED as the local store's cache key — so folding\n * classification into it would make merely classifying a table wipe every store's read cache. The lock\n * still records it, so an un-enrolment (a class removed or changed) is a reviewable diff.\n *\n * Optional because a committed lock is JSON on disk: one written before this field existed simply has no\n * `rowClasses`, and the diff then reads the whole baseline as unclassified — so adopting classification\n * against an old lock is a set of `compatible` declarations, never spurious risk. {@link buildRegistryLock}\n * always populates it.\n */\n rowClasses?: RegistryRowClasses;\n /**\n * Each registered Event stream (ADR-0053 decision 1), keyed by Event-stream name → a canonical hash of its\n * payload schema AND its identity declaration. A SIBLING of `tables` for the same reason `rowClasses` is:\n * the canonical table shape is what `fingerprintRegistry` hashes and that hash is the local store's\n * PERSISTED cache key, so folding an Event stream into it would make registering one wipe every store's read\n * cache — for a lane that touches no synced table, no local schema and no apply function.\n *\n * Optional because a committed lock is JSON on disk: one written before this field existed simply has no\n * `streams`, and the diff then reads the whole baseline as having none — so adopting the Event lane against\n * an old lock is a set of `compatible` additions, never spurious risk. {@link buildRegistryLock} always\n * populates it.\n */\n streams?: RegistryEventStreams;\n}\n\n/** Registry key → row class (`null` = unclassified). See {@link RegistryLock.rowClasses}. */\nexport type RegistryRowClasses = Record<string, string | null>;\n\n/** Event-stream name → canonical contract hash. See {@link RegistryLock.streams}. */\nexport type RegistryEventStreams = Record<string, string>;\n\n/** The row classification of every entry, with sorted keys so a serialized lock is stable. */\nexport function registryRowClasses(registry: SyncTableRegistry): RegistryRowClasses {\n const classes: RegistryRowClasses = {};\n for (const key of Object.keys(registry).sort()) {\n classes[key] = (registry[key] as SyncTableEntry | undefined)?.rowClass ?? null;\n }\n return classes;\n}\n\n/**\n * A stable JSON serialization with recursively SORTED object keys, so two structurally equal values\n * serialize identically regardless of key insertion order (`z.toJSONSchema`'s property order follows the\n * schema's declaration order, which an author may reshuffle without changing the contract).\n */\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([a], [b]) => asString(a, b))\n .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`);\n return `{${entries.join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/**\n * The canonical string of ONE Event stream's contract: its payload schema (as a JSON Schema, stably\n * stringified), its identity declaration (field name → claim path, sorted), and its author-supplied\n * `revision`.\n *\n * The payload is converted with `io: \"input\"` because the schema is a PARSE contract (what a client may\n * append), and with `unrepresentable: \"any\"` so a schema using a type JSON Schema cannot express degrades to\n * a coarser canonical form instead of throwing at lock time — a lock build must never fail on a legal\n * registry. The cost of that choice is under-detection for such a type, which the next two paragraphs bound.\n *\n * **The blind spot is real and named.** JSON Schema cannot express a zod refinement or transform, so\n * `z.string().refine(v => v.length >= 3)` and the incompatible `>= 10` version canonicalize identically —\n * the hash sees no change and the review gate never fires. {@link EventStreamEntry.revision} is the fix and\n * it is the AUTHOR's obligation, exactly as `RowFilterSpec.revision` is for a `customPredicate` closure: bump it\n * on any acceptance-logic change the JSON Schema cannot carry, and the stream's hash shifts.\n *\n * The hash exists to DETECT change, not to VALIDATE compatibility. ADR-0053 decision 1 binds a stream's\n * payload schema to backward-compatible evolution (events written offline under the old schema are still in\n * flight) and requires a NEW Event-stream name for an incompatible change — a rule no hash can check. All the\n * lock can do is force the change to be seen and reviewed, which is what the `risky` verdict is for.\n */\nfunction canonicalEventStreamString(entry: EventStreamEntry): string {\n let payload: string;\n try {\n payload = stableStringify(z.toJSONSchema(entry.payload, { io: \"input\", unrepresentable: \"any\" }));\n } catch {\n // Defensive: an exotic schema `toJSONSchema` still refuses. A constant canonical form under-detects\n // change for that one stream rather than breaking every consumer's lock build.\n payload = '\"<unrepresentable>\"';\n }\n const identity = Object.keys(entry.identity ?? {})\n .sort(asString)\n .map((field) => [field, [...(entry.identity[field]?.claimPath ?? [])]]);\n // Absent === 0, so adopting `revision` on an unchanged stream by declaring `revision: 1` IS a change (as it\n // should be: an author only reaches for it because the invisible logic moved).\n return stableStringify({ payload, identity, revision: entry.revision ?? 0 });\n}\n\n/** The canonical contract hash of every registered Event stream, with sorted keys so a lock is stable. */\nexport function registryEventStreams(registry: SyncTableRegistry): RegistryEventStreams {\n const streams = getSyncRegistryStreams(registry);\n const hashes: RegistryEventStreams = {};\n if (!streams) {\n return hashes;\n }\n for (const name of Object.keys(streams).sort(asString)) {\n const entry = streams[name];\n if (entry) {\n hashes[name] = hashString(canonicalEventStreamString(entry));\n }\n }\n return hashes;\n}\n\nconst SEVERITY_RANK: Record<RegistryChangeSeverity, number> = { compatible: 0, risky: 1, breaking: 2 };\n\nfunction maxSeverity(changes: readonly RegistryChange[]): RegistryChangeSeverity {\n return changes.reduce<RegistryChangeSeverity>(\n (worst, change) => (SEVERITY_RANK[change.severity] > SEVERITY_RANK[worst] ? change.severity : worst),\n \"compatible\",\n );\n}\n\n/**\n * Build the committed lock (fingerprint + canonical shape + row classification + Event streams) for a\n * registry.\n */\nexport function buildRegistryLock(registry: SyncTableRegistry): RegistryLock {\n return {\n version: fingerprintRegistry(registry),\n tables: canonicalizeRegistry(registry),\n rowClasses: registryRowClasses(registry),\n streams: registryEventStreams(registry),\n };\n}\n\nfunction diffTable(table: string, previous: CanonicalTable, next: CanonicalTable, changes: RegistryChange[]): void {\n const prevColumns = new Map(previous.columns.map((column) => [column.name, column]));\n const nextColumns = new Map(next.columns.map((column) => [column.name, column]));\n\n for (const [name, prevColumn] of prevColumns) {\n const nextColumn = nextColumns.get(name);\n if (!nextColumn) {\n // A rename appears as remove + add; both are breaking, which is the safe read.\n changes.push({ severity: \"breaking\", table, detail: `column removed: ${name}` });\n continue;\n }\n if (prevColumn.type !== nextColumn.type) {\n // Same name, different type: the silent-repurposing case the runtime cannot see.\n changes.push({\n severity: \"breaking\",\n table,\n detail: `column type changed: ${name} (${prevColumn.type} -> ${nextColumn.type})`,\n });\n }\n if (!prevColumn.notNull && nextColumn.notNull) {\n changes.push({ severity: \"breaking\", table, detail: `column became NOT NULL: ${name}` });\n } else if (prevColumn.notNull && !nextColumn.notNull) {\n changes.push({ severity: \"compatible\", table, detail: `column relaxed to nullable: ${name}` });\n }\n }\n\n for (const [name, nextColumn] of nextColumns) {\n if (prevColumns.has(name)) {\n continue;\n }\n const safe = !nextColumn.notNull || nextColumn.hasDefault;\n changes.push({\n severity: safe ? \"compatible\" : \"breaking\",\n table,\n detail: safe ? `column added: ${name}` : `NOT NULL column added without default: ${name}`,\n });\n }\n\n if (JSON.stringify(previous.primaryKey) !== JSON.stringify(next.primaryKey)) {\n changes.push({ severity: \"breaking\", table, detail: \"primary key changed\" });\n }\n if (JSON.stringify(previous.localPrimaryKey) !== JSON.stringify(next.localPrimaryKey)) {\n // The local identity the overlay + journal rows are keyed on; changing it orphans\n // any owed (un-acked) writes — the runtime cannot re-key them.\n changes.push({ severity: \"breaking\", table, detail: \"local primary key changed\" });\n }\n if (previous.mode !== next.mode) {\n changes.push({ severity: \"risky\", table, detail: `mode changed: ${previous.mode} -> ${next.mode}` });\n }\n diffProjection(table, previous.projection, next.projection, changes);\n diffShape(table, previous.shape, next.shape, changes);\n if ((previous.consistencyGroup ?? null) !== (next.consistencyGroup ?? null)) {\n // A group move re-keys the table's subscription-state row (ADR-0009 decision 2): the local cache\n // columns survive, but the subscription must reset so the table re-streams under its new group.\n changes.push({\n severity: \"risky\",\n table,\n detail: `consistency group changed: ${previous.consistencyGroup ?? \"(singleton)\"} -> ${next.consistencyGroup ?? \"(singleton)\"} (re-sync required)`,\n });\n }\n if (JSON.stringify(previous.managedFields) !== JSON.stringify(next.managedFields)) {\n // Managed-field governance changes how writes are constructed/owned; a returning client\n // with owed writes authored under the old governance needs a conscious re-sync.\n changes.push({ severity: \"risky\", table, detail: \"managed fields changed (re-sync required)\" });\n }\n}\n\n/**\n * Projection changes. Renaming the synced/overlay/journal tables orphans their\n * name-coupled local data (ADR-0006) → breaking; changing the omitted-column set changes\n * which columns exist locally → a re-sync (risky).\n */\nfunction diffProjection(\n table: string,\n previous: CanonicalTable[\"projection\"],\n next: CanonicalTable[\"projection\"],\n changes: RegistryChange[],\n): void {\n for (const key of [\"syncedTable\", \"overlayTable\", \"journalTable\"] as const) {\n if ((previous?.[key] ?? null) !== (next?.[key] ?? null)) {\n changes.push({ severity: \"breaking\", table, detail: `projection ${key} changed (orphans local data)` });\n }\n }\n if (JSON.stringify(previous?.omitColumns ?? null) !== JSON.stringify(next?.omitColumns ?? null)) {\n changes.push({ severity: \"risky\", table, detail: \"omitted columns changed (re-sync required)\" });\n }\n}\n\n/**\n * Shape changes. The shape target (table/shapeKey/physicalTable) and the row filter both\n * govern which rows stream; a change to either needs a re-sync so the local cache is not left\n * holding rows selected under the old definition (risky). The row filter's `customPredicate` body\n * is invisible to the fingerprint, so a change confined to it is not detectable here.\n */\nfunction diffShape(\n table: string,\n previous: CanonicalTable[\"shape\"],\n next: CanonicalTable[\"shape\"],\n changes: RegistryChange[],\n): void {\n const target = (shape: CanonicalTable[\"shape\"]): string | null =>\n shape ? `${shape.tableName}|${shape.shapeKey}|${shape.physicalTable ?? \"\"}` : null;\n\n if (target(previous) !== target(next)) {\n changes.push({ severity: \"risky\", table, detail: \"shape target changed (re-sync required)\" });\n }\n if (JSON.stringify(previous?.rowFilter ?? null) !== JSON.stringify(next?.rowFilter ?? null)) {\n changes.push({ severity: \"risky\", table, detail: \"row filter changed (re-sync required)\" });\n }\n\n // A change of scope columns re-partitions the whole family: rows that were in one shape land in\n // another, and a client holding the old partition cannot reconcile itself to the new one.\n if (JSON.stringify(previous?.scope ?? null) !== JSON.stringify(next?.scope ?? null)) {\n changes.push({ severity: \"risky\", table, detail: \"shape scope changed (re-sync required)\" });\n }\n // Unlike `customPredicate`, this one IS visible — so a change confined to the static predicate is\n // caught here rather than needing a consumer to remember to bump a revision.\n if ((previous?.where ?? null) !== (next?.where ?? null)) {\n changes.push({ severity: \"risky\", table, detail: \"shape predicate changed (re-sync required)\" });\n }\n}\n\n/**\n * Row-classification changes (ADR-0052). Classification is authoring metadata, invisible to the runtime and\n * to the fingerprint — but it decides which registry invariants an entry is ENROLLED in, so a change to it\n * is exactly the kind of quiet authoring drift the gate exists to surface.\n *\n * - class → different class: `risky` (the entry left one invariant's coverage and joined another's).\n * - unclassified → classified: `compatible` (pure adoption; nothing loses coverage).\n * - classified → unclassified: `risky` (the entry un-enrols from every invariant bound to that class).\n */\nfunction diffRowClass(table: string, previous: string | null, next: string | null, changes: RegistryChange[]): void {\n if (previous === next) {\n return;\n }\n if (previous == null) {\n changes.push({ severity: \"compatible\", table, detail: `row class declared: ${next}` });\n return;\n }\n if (next == null) {\n changes.push({\n severity: \"risky\",\n table,\n detail: `row class removed: ${previous} (un-enrols from registry invariants)`,\n });\n return;\n }\n changes.push({\n severity: \"risky\",\n table,\n detail: `row class changed: ${previous} -> ${next} (review invariant enrollment)`,\n });\n}\n\n/**\n * Event-stream changes (ADR-0053 decision 1). The Event lane is invisible to the fingerprint, so the lock is\n * the ONLY place a change to it can surface.\n *\n * - added → `compatible` (a new Event stream takes nothing away; a client that does not know it appends\n * nothing to it).\n * - removed → `breaking`. Events for it are already durable in some clients' Outboxes, and a server that no\n * longer knows the stream can only park them (`deferred`, retried forever) or refuse them — the removal is\n * a deliberate release decision, exactly what the gate exists to force.\n * - payload/identity hash changed → `risky`. The hash cannot judge compatibility (see\n * {@link canonicalEventStreamString}); the rule it enforces socially is the ADR's: evolve only\n * backward-compatibly, and take a NEW Event-stream name for anything else.\n */\nfunction diffEventStreams(previous: RegistryEventStreams, next: RegistryEventStreams, changes: RegistryChange[]): void {\n for (const name of Object.keys(previous).sort(asString)) {\n const nextHash = next[name];\n if (nextHash === undefined) {\n changes.push({\n severity: \"breaking\",\n table: name,\n detail: `event stream removed: ${name} (in-flight client events will be deferred/refused)`,\n });\n continue;\n }\n if (previous[name] !== nextHash) {\n changes.push({\n severity: \"risky\",\n table: name,\n detail:\n `event stream ${name} payload/identity changed (must remain backward-compatible; ` +\n `incompatible change requires a new Event-stream name)`,\n });\n }\n }\n\n for (const name of Object.keys(next).sort(asString)) {\n if (!(name in previous)) {\n changes.push({ severity: \"compatible\", table: name, detail: `event stream added: ${name}` });\n }\n }\n}\n\n/**\n * Classify the change from one canonical registry shape to another. `rowClasses` carries each side's row\n * classification (ADR-0052) and `streams` each side's Event-stream contract hashes (ADR-0053) — both siblings\n * of the canonical tables, never fields of them (see {@link RegistryLock.rowClasses} /\n * {@link RegistryLock.streams}). An omitted side reads as entirely unclassified / streamless, which is how a\n * lock predating either field diffs as adoption rather than as spurious risk.\n *\n * `RegistryChange.table` names the SUBJECT of the change, which for an Event-stream change is the\n * Event-stream name rather than a registry table key; each such `detail` says \"event stream …\" so the\n * summary line stays unambiguous.\n */\nexport function diffCanonicalRegistries(\n previous: readonly CanonicalTable[],\n next: readonly CanonicalTable[],\n rowClasses?: { previous?: RegistryRowClasses | undefined; next?: RegistryRowClasses | undefined },\n streams?: { previous?: RegistryEventStreams | undefined; next?: RegistryEventStreams | undefined },\n): RegistryDiff {\n const changes: RegistryChange[] = [];\n const prevByKey = new Map(previous.map((table) => [table.key, table]));\n const nextByKey = new Map(next.map((table) => [table.key, table]));\n const prevClasses = rowClasses?.previous ?? {};\n const nextClasses = rowClasses?.next ?? {};\n\n for (const [key, prevTable] of prevByKey) {\n const nextTable = nextByKey.get(key);\n if (!nextTable) {\n changes.push({ severity: \"breaking\", table: key, detail: \"table removed\" });\n continue;\n }\n diffTable(key, prevTable, nextTable, changes);\n diffRowClass(key, prevClasses[key] ?? null, nextClasses[key] ?? null, changes);\n }\n\n for (const key of nextByKey.keys()) {\n if (!prevByKey.has(key)) {\n changes.push({ severity: \"compatible\", table: key, detail: \"table added\" });\n }\n }\n\n diffEventStreams(streams?.previous ?? {}, streams?.next ?? {}, changes);\n\n return { changes, severity: maxSeverity(changes) };\n}\n\n/** Classify the change between two registries. */\nexport function compareRegistries(previous: SyncTableRegistry, next: SyncTableRegistry): RegistryDiff {\n return diffCanonicalRegistries(\n canonicalizeRegistry(previous),\n canonicalizeRegistry(next),\n { previous: registryRowClasses(previous), next: registryRowClasses(next) },\n { previous: registryEventStreams(previous), next: registryEventStreams(next) },\n );\n}\n\n/** Classify a registry against a committed lock baseline. */\nexport function diffRegistryAgainstLock(registry: SyncTableRegistry, lock: RegistryLock): RegistryDiff {\n return diffCanonicalRegistries(\n lock.tables,\n canonicalizeRegistry(registry),\n { previous: lock.rowClasses, next: registryRowClasses(registry) },\n { previous: lock.streams, next: registryEventStreams(registry) },\n );\n}\n\n/**\n * The consumer-facing check: `ok` is false on a breaking diff. The consumer wires the\n * exit code (e.g. `process.exit(result.ok ? 0 : 1)`) into their own CI — pgxsinkit does\n * not reach into anyone's pipeline.\n */\nexport function runRegistryCheck(input: { registry: SyncTableRegistry; lock: RegistryLock }): {\n ok: boolean;\n diff: RegistryDiff;\n} {\n const diff = diffRegistryAgainstLock(input.registry, input.lock);\n return { ok: diff.severity !== \"breaking\", diff };\n}\n\n/** A human-readable, stable summary of a diff (one line per change). */\nexport function summarizeRegistryDiff(diff: RegistryDiff): string {\n if (diff.changes.length === 0) {\n return \"no registry changes\";\n }\n return diff.changes.map((change) => `[${change.severity}] ${change.table}: ${change.detail}`).join(\"\\n\");\n}\n",
16
+ "import type { SQL } from \"drizzle-orm\";\nimport { getTableConfig, PgDialect } from \"drizzle-orm/pg-core\";\n\nimport { DENY_ALL_PREDICATE, type JwtClaims } from \"./config\";\nimport { isOrPredicate, type Predicate } from \"./predicate\";\nimport { getSyncRegistryRowClasses, type SyncTableEntry, type SyncTableRegistry } from \"./registry\";\n\n/**\n * Registry invariants (ADR-0052): assert a claim about the RENDERED authorization artifacts of every entry\n * a classification binds, evaluated against named claims personas — the whole-registry counterpart to\n * `assertReadContractPreserved`'s per-table read-contract check.\n *\n * It exists because a privacy/visibility invariant spanning many entries drifts in two structural ways that\n * per-entry review cannot catch:\n *\n * 1. **Read/write asymmetry** — the shape's row filter and the Postgres RLS policies are two engines, so one\n * can be tightened (or loosened) without the other. The assertion audits BOTH surfaces of every bound\n * entry in one predicate, so \"readable but unwritable\" (or the reverse) is a test failure, not a bug report.\n * 2. **Under-enumeration** — an invariant expressed over a hand-maintained list of tables silently stops\n * covering the registry the moment someone adds an entry. Binding by {@link SyncTableEntry.rowClass}\n * inverts that: with a declared `rowClasses` vocabulary, a new entry cannot even be registered without\n * being classified, so it joins its class's invariants by construction.\n *\n * It audits RESOLVED output, so it sees things the fingerprint structurally cannot (the `customPredicate`\n * BODY is a closure — only its presence and `RowFilterSpec.revision` are hashed). The trade: it sees exactly\n * the claims fixtures you give it, and nothing else.\n */\n\n/**\n * Whether a predicate admits no row at all — the read half of \"this persona sees nothing\".\n *\n * Recognises the {@link DENY_ALL_PREDICATE} singleton by reference AND any structurally empty `or`,\n * because both are always-FALSE on the wire and an invariant is asking about the outcome, not about\n * which spelling produced it.\n */\nexport function deniesAllRows(predicate: Predicate | null): boolean {\n if (predicate === DENY_ALL_PREDICATE) return true;\n return predicate != null && isOrPredicate(predicate) && predicate.or.length === 0;\n}\n\n/** One rendered write policy on a bound entry's Postgres table, as the invariant predicate sees it. */\nexport interface RenderedPolicy {\n /** The policy name as declared (e.g. `widgets_select_owner_or_admin`). */\n name: string;\n /** The command the policy governs: `select` | `insert` | `update` | `delete`, or `all` when undeclared. */\n command: string;\n /** The `USING` predicate rendered to inline SQL text, or `null` when the policy declares none. */\n using: string | null;\n /** The `WITH CHECK` predicate rendered to inline SQL text, or `null` when the policy declares none. */\n withCheck: string | null;\n}\n\n/** One (entry × claims fixture) cell handed to a {@link RegistryInvariantSpec.holds} predicate. */\nexport interface RegistryInvariantCell {\n /** The entry's key in the registry. */\n key: string;\n entry: SyncTableEntry;\n /** The entry's classification, or `undefined` when it carries none (possible only for a `appliesTo` predicate). */\n rowClass: string | undefined;\n /** The fixture's name, as declared in {@link RegistryInvariantSpec.claimsFixtures}. */\n fixtureName: string;\n claims: JwtClaims;\n /**\n * The read predicate this entry resolves to FOR THESE CLAIMS — the real read pipeline's output, exactly\n * what the control plane compiles into the shape at subscribe.\n *\n * `null` means **unfiltered**, and covers both ways that arises: the entry declares no shape/`rowFilter`\n * at all, or its `customPredicate` returned `null` for these claims (the documented \"bypass filtering,\n * every row is visible\" answer — e.g. an admin persona). Both are the same statement about what the\n * client receives, which is what an invariant reasons about; distinguish them via\n * `entry.shape?.rowFilter` if a predicate genuinely needs to.\n *\n * An AST, not SQL text: an invariant matches on structure ({@link deniesAllRows}, the `isXPredicate`\n * guards) rather than on a rendered string that could drift on formatting alone.\n */\n readPredicate: Predicate | null;\n /** Every RLS policy attached to the entry's Postgres table, rendered to inline SQL text. */\n renderedPolicies: RenderedPolicy[];\n}\n\nexport interface RegistryInvariantSpec {\n /** Human name for the invariant, used as the error header (e.g. \"private rows never leave their owner\"). */\n name: string;\n /**\n * Which entries the invariant binds: a list of {@link SyncTableEntry.rowClass} values (the normal form —\n * coverage then grows with the registry), or a predicate over the entry for the rare case a class cannot\n * express. When the registry declares its `rowClasses`, a class named here that is not in that vocabulary\n * throws immediately — a typo would otherwise bind nothing and pass vacuously.\n */\n appliesTo: readonly string[] | ((entry: SyncTableEntry, key: string) => boolean);\n /**\n * The claims personas the invariant is evaluated against, by name (`{ anonymous: {}, owner: {...} }`). Every\n * bound entry is checked against every fixture; the names appear in the failure report.\n */\n claimsFixtures: Record<string, JwtClaims>;\n /**\n * The invariant itself, over ONE (entry × fixture) cell's rendered artifacts. Return `true` when it holds,\n * `false` or a reason string when it does not — a reason string is reproduced verbatim in the error, so\n * prefer it.\n */\n holds: (cell: RegistryInvariantCell) => boolean | string;\n}\n\n// Policy predicates are rendered with values INLINED, matching how `CREATE POLICY` DDL carries them (and how\n// supabase-rls.ts's own text builders render): a `$n` bind would be meaningless to compare against.\nconst policyDialect = new PgDialect();\n\nfunction renderPolicyPredicate(fragment: SQL | undefined): string | null {\n return fragment == null ? null : policyDialect.sqlToQuery(fragment.inlineParams()).sql;\n}\n\n/**\n * The write policies attached to an entry's Postgres table, rendered to inline SQL text. Read straight off\n * drizzle's own table config, so it sees exactly what the migration will emit — including policies passed\n * through `defineSyncTable`'s `policies:`/`extras:` options, which are merged into the `pgTable` extras.\n *\n * A read PROJECTION's `table` IS its owner's, so a projection reports the OWNER's policies. That is correct:\n * a projection owns no table and adds no DDL, so the owner's policies are the ones governing its rows.\n */\nfunction renderPolicies(entry: SyncTableEntry): RenderedPolicy[] {\n return getTableConfig(entry.table).policies.map((policy) => ({\n name: policy.name,\n // drizzle leaves `for` undefined when the policy does not narrow the command, which is Postgres's `ALL`.\n command: policy.for ?? \"all\",\n using: renderPolicyPredicate(policy.using),\n withCheck: renderPolicyPredicate(policy.withCheck),\n }));\n}\n\n/** The read predicate for these claims, through the real pipeline the control plane uses. */\nfunction resolvePredicate(entry: SyncTableEntry, claims: JwtClaims): Predicate | null {\n return entry.shape?.rowFilter?.customPredicate?.(claims) ?? null;\n}\n\nfunction boundEntries(\n registry: SyncTableRegistry,\n appliesTo: RegistryInvariantSpec[\"appliesTo\"],\n): Array<[string, SyncTableEntry]> {\n const entries = Object.entries(registry) as Array<[string, SyncTableEntry]>;\n if (typeof appliesTo === \"function\") {\n return entries.filter(([key, entry]) => appliesTo(entry, key));\n }\n const classes = new Set(appliesTo);\n return entries.filter(([, entry]) => entry.rowClass != null && classes.has(entry.rowClass));\n}\n\n/**\n * Assert a {@link RegistryInvariantSpec} over a registry: for every entry the invariant binds, and every\n * claims fixture, evaluate `holds` against the entry's RENDERED read filter and write policies. Pure audit —\n * it renders through the production code paths but changes no runtime behaviour.\n *\n * Call it at module eval beside the registry (or in a test), the same way {@link assertReadContractPreserved}\n * is called, so a violation fails closed rather than shipping.\n *\n * ```ts\n * assertRegistryInvariant(registry, {\n * name: \"private rows are never visible to an anonymous caller\",\n * appliesTo: [\"private\"],\n * claimsFixtures: { anonymous: {}, member: { sub: \"u-1\" } },\n * holds: ({ fixtureName, readPredicate }) =>\n * fixtureName !== \"anonymous\" || deniesAllRows(readPredicate) || \"anonymous read is not denied\",\n * });\n * ```\n *\n * Two deliberate fail-closed behaviours:\n * - An `appliesTo` class the registry's declared vocabulary does not contain throws immediately (a typo must\n * not pass as \"nothing to check\").\n * - An invariant that binds ZERO entries throws. A spec that checks nothing is a bug in the spec — nearly\n * always a wrong class name or an invariant left behind after its class was renamed — and silently passing\n * is the exact failure mode this whole mechanism exists to remove.\n *\n * Every failing cell is collected and reported together: the header names the invariant, then one\n * `entry (fixture): reason` line per violation. Never first-failure-only — you fix a classification-wide\n * problem in one pass, not one re-run per entry.\n */\nexport function assertRegistryInvariant(registry: SyncTableRegistry, spec: RegistryInvariantSpec): void {\n const declaredClasses = getSyncRegistryRowClasses(registry);\n if (Array.isArray(spec.appliesTo) && declaredClasses != null) {\n const unknown = spec.appliesTo.filter((rowClass) => !declaredClasses.includes(rowClass));\n if (unknown.length > 0) {\n throw new Error(\n `registry invariant \"${spec.name}\" applies to unknown row class(es): ${unknown.join(\", \")}. This ` +\n `registry declares [${declaredClasses.join(\", \")}] — a misspelled class would bind no entries and ` +\n `pass vacuously, so it is rejected here.`,\n );\n }\n }\n\n const bound = boundEntries(registry, spec.appliesTo);\n if (bound.length === 0) {\n const binding = Array.isArray(spec.appliesTo) ? `row class(es) ${spec.appliesTo.join(\", \")}` : \"its predicate\";\n throw new Error(\n `registry invariant \"${spec.name}\" binds no entries (${binding}). An invariant that checks nothing ` +\n `passes vacuously, which defeats the point — check the class name(s) against the entries' rowClass, ` +\n `or drop the invariant if its rows are gone.`,\n );\n }\n\n const fixtures = Object.entries(spec.claimsFixtures);\n if (fixtures.length === 0) {\n throw new Error(\n `registry invariant \"${spec.name}\" declares no claims fixtures: the invariant is evaluated per persona, ` +\n `so with none it checks nothing. Declare at least one (e.g. { anonymous: {} }).`,\n );\n }\n\n const violations: string[] = [];\n for (const [key, entry] of bound) {\n const renderedPolicies = renderPolicies(entry);\n for (const [fixtureName, claims] of fixtures) {\n const verdict = spec.holds({\n key,\n entry,\n rowClass: entry.rowClass,\n fixtureName,\n claims,\n readPredicate: resolvePredicate(entry, claims),\n renderedPolicies,\n });\n if (verdict === true) {\n continue;\n }\n violations.push(`${key} (${fixtureName}): ${typeof verdict === \"string\" ? verdict : \"invariant does not hold\"}`);\n }\n }\n\n if (violations.length > 0) {\n throw new Error(\n `registry invariant \"${spec.name}\" is violated by ${violations.length} of ${bound.length * fixtures.length} ` +\n `checked cells:\\n ${violations.join(\"\\n \")}`,\n );\n }\n}\n",
16
17
  "import { z } from \"zod\";\n\nimport { unixMicrosecondsSchema } from \"./common\";\n\nexport const mutationKindSchema = z.enum([\"create\", \"update\", \"delete\"]);\n/**\n * The full Mutation-journal status machine — every status a journal row can hold, including the two\n * terminal states (`quarantined`, ADR-0006; `conflicted`, ADR-0015). Kept in lockstep with the\n * client's `MutationStatus` (packages/client/src/mutation-state.ts). Distinct from\n * {@link mutationAckStatusSchema}, the narrower *transport* subset a server ack may carry.\n */\nexport const mutationStatusSchema = z.enum([\n \"pending\",\n \"sending\",\n \"acked\",\n \"failed\",\n \"quarantined\",\n \"conflicted\",\n \"rejected\",\n]);\n/**\n * The *transport* statuses a server ack may carry. `acked` (applied), `failed` (transient, retry),\n * `conflicted` (ADR-0015 stale write — overlay KEPT, resolve as a new write), and `rejected` (ADR-0022 —\n * a business rejection from the authoritative endpoint: a server-side invariant the client cannot evaluate\n * said no, so the optimistic overlay is auto-discarded for the whole write-unit and the typed reason is\n * surfaced).\n */\nexport const mutationAckStatusSchema = z.enum([\"acked\", \"failed\", \"conflicted\", \"rejected\"]);\n\nexport const entityKeySchema = z.record(z.string().trim().min(1), z.string().trim().min(1));\n\nexport const mutationEnvelopeSchema = z\n .object({\n tableName: z.string().trim().min(1),\n entityKey: entityKeySchema,\n // INVARIANT — the public mutation surface is UUID-only by contract (this schema, the ack/rejection\n // schemas below, and the client's `mutation_id UUID` journal). The generated apply function and the\n // `operations_log` accept an OPAQUE TEXT id for one narrow case: a DIRECT server-side caller that\n // derives child envelopes (composite `${parentId}:<tag>:<n>` ids) and calls the apply function\n // itself, never crossing this HTTP route or the client journal. So a non-UUID id can never enter a\n // request that this schema validates. See packages/server/src/mutations/plpgsql-apply.ts.\n mutationId: z.uuid(),\n mutationSeq: z.number().int().nonnegative(),\n kind: mutationKindSchema,\n payload: z.unknown(),\n clientTimestampUs: unixMicrosecondsSchema,\n /**\n * The Base server version this write was authored against (ADR-0015): the row's Server version\n * at enqueue for a chain head, or its predecessor's resolved version for a chained write. The\n * applier compares the row's *current* Server version to it — `current > base` ⇒ a stale write\n * (an external write interleaved). Absent on a `create` (its conflict is a PK collision, a\n * separate concern) and on blind authoritative writes; absence means no stale check runs.\n */\n baseServerVersion: unixMicrosecondsSchema.optional(),\n })\n .strict();\n\nexport const mutationAckSchema = z\n .object({\n tableName: z.string().trim().min(1),\n entityKey: entityKeySchema,\n // UUID-only (public-surface invariant; see mutationEnvelopeSchema). The route builds every ack from\n // the request envelope's own UUID `mutationId` — never from the apply function's returned conflict\n // rows (which are TEXT and, for a direct caller's derived child, non-UUID) — so a text id can never\n // reach this ack: the conflict map is keyed by returned text ids but only looked up by request UUIDs.\n mutationId: z.uuid(),\n mutationSeq: z.number().int().nonnegative(),\n status: mutationAckStatusSchema,\n serverUpdatedAtUs: unixMicrosecondsSchema.optional(),\n conflictReason: z.string().trim().min(1).optional(),\n /**\n * The typed reason a `rejected` ack carries (ADR-0022): the authoritative endpoint's account of why the\n * write-unit was declined (a capacity/quota/uniqueness rule — e.g. the DB constraint or trigger message).\n * Surfaced to the app when the optimistic overlay is auto-discarded.\n */\n rejectionReason: z.string().trim().min(1).optional(),\n httpStatus: z.number().int().min(100).max(599).optional(),\n })\n .strict();\n\nexport const batchMutationRequestSchema = z\n .object({\n mutations: z.array(mutationEnvelopeSchema).min(1),\n })\n .strict();\n\n/**\n * The body of an **authoritative write** (ADR-0022 §3, mechanism c): one pessimistic write-**unit** — a set\n * of co-committed mutations the server applies in its **own isolated transaction**, atomically, returning a\n * per-mutation ack. `writeUnit` is the client's unit id (the dynamic `transaction` tag, or the static\n * consistency-group key), carried for attribution. Distinct from `batchMutationRequestSchema` only in\n * *semantics* (atomic unit + a constraint exception → a clean `rejected` ack, never a whole-batch 500) and\n * its endpoint path; the mutation envelope is identical.\n */\nexport const authoritativeWriteRequestSchema = z\n .object({\n writeUnit: z.string().trim().min(1).optional(),\n mutations: z.array(mutationEnvelopeSchema).min(1),\n })\n .strict();\n\nexport const batchMutationAckSchema = z\n .object({\n acks: z.array(mutationAckSchema),\n })\n .strict();\n\n/**\n * Per-mutation attribution for a structural batch rejection. The batch write is atomic —\n * one structurally-invalid mutation rejects the whole POST with a single non-2xx — so the\n * server names the offending mutation(s) here. That lets the client quarantine exactly those\n * and keep the innocent siblings retryable, instead of dragging the whole offline queue to\n * quarantine at the shared attempt cap.\n */\nexport const mutationRejectionSchema = z\n .object({\n tableName: z.string().trim().min(1),\n // UUID-only (public-surface invariant; see mutationEnvelopeSchema). Attribution names an offending\n // request mutation, whose id this same contract already validated as a UUID.\n mutationId: z.uuid(),\n mutationSeq: z.number().int().nonnegative(),\n reason: z.string().trim().min(1),\n })\n .strict();\n\n/**\n * The body of a non-2xx batch-mutation response. `rejections` is present only when the fault\n * is attributable to specific mutations (payload validation); whole-batch faults (execution\n * 5xx, auth, malformed envelope) carry just a `message`. Unknown extra fields are stripped.\n */\nexport const batchMutationErrorSchema = z.object({\n message: z.string().optional(),\n rejections: z.array(mutationRejectionSchema).optional(),\n});\n\nexport type MutationKind = z.infer<typeof mutationKindSchema>;\nexport type MutationStatus = z.infer<typeof mutationStatusSchema>;\nexport type MutationAckStatus = z.infer<typeof mutationAckStatusSchema>;\nexport type EntityKey = z.infer<typeof entityKeySchema>;\nexport type MutationEnvelope = z.infer<typeof mutationEnvelopeSchema>;\nexport type MutationAck = z.infer<typeof mutationAckSchema>;\nexport type BatchMutationRequest = z.infer<typeof batchMutationRequestSchema>;\nexport type AuthoritativeWriteRequest = z.infer<typeof authoritativeWriteRequestSchema>;\nexport type BatchMutationAck = z.infer<typeof batchMutationAckSchema>;\nexport type MutationRejection = z.infer<typeof mutationRejectionSchema>;\nexport type BatchMutationError = z.infer<typeof batchMutationErrorSchema>;\n",
17
- "import type { AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport type { Retention } from \"./config\";\nimport { fingerprintReadContract } from \"./fingerprint\";\nimport type { ClientProjectionSpecForTable, SyncTableEntry, SyncTableRegistry } from \"./registry\";\n\n/**\n * Per-client mode projection (ADR-0025). The authoritative (server) registry defines a table once with\n * its full write contract; a client that must only *read* that table consumes the same entry through\n * `asReadonly`. The read/identity contract — table, columns, primary key, synced-table name, column\n * omission, the shape/row filter, the row classification (`rowClass`), AND the column-builder factory\n * (`makeColumns`) — is preserved verbatim; the write-capability metadata is dropped:\n *\n * - `mode` flips to `readonly`;\n * - the overlay-merged read-model `view` and the overlay/journal client projection (the local write\n * machinery `@pgxsinkit/client` provisions for a writable table) are removed — a readonly client reads\n * the synced base table directly;\n * - `conflictPolicy`, `governance` (managed fields), and `writeMode` are removed — a readonly table has\n * no write path, and `defineSyncRegistry` would otherwise still treat them as a writable declaration.\n *\n * The result is the same entry `defineSyncTable` would have produced for this table with\n * `mode: \"readonly\"`, so `defineSyncRegistry` accepts it without the writable-table requirements\n * (server-version field + `conflictPolicy`).\n *\n * Lifecycle axes (`consistencyGroup`, `subscription`, `retention`) are preserved — a projection may keep\n * the authoritative grouping/timing/durability; change them on the projected entry if a client needs to.\n *\n * `makeColumns` (the column-builder factory `defineSyncTable` stashes) is carried too: since ADR-0029 P1\n * the client derives EVERY synced-table object from it (`getSyncedLocalTable` → `projectedColumnBuilders`),\n * so a readonly projection that dropped it could not build its own local synced read cache — the member-boot\n * failure this keep-list's NOTE below predicted. It is read-derivation machinery, not a write handle.\n *\n * NOTE: if a new *read-relevant* field is added to {@link SyncTableEntry}, carry it here too (this builds\n * the readonly entry by listing what to keep, so a new field is otherwise silently dropped).\n */\nexport function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable, TLocalTable>,\n): SyncTableEntry<TTable, TLocalTable> {\n const { clientProjection } = entry;\n const readonlyProjection: ClientProjectionSpecForTable<TTable> | undefined =\n clientProjection != null\n ? {\n ...(clientProjection.syncedTable != null ? { syncedTable: clientProjection.syncedTable } : {}),\n ...(clientProjection.omitColumns != null ? { omitColumns: clientProjection.omitColumns } : {}),\n ...(clientProjection.localPrimaryKey != null ? { localPrimaryKey: clientProjection.localPrimaryKey } : {}),\n }\n : undefined;\n\n return {\n table: entry.table,\n localTable: entry.localTable,\n mode: \"readonly\",\n primaryKey: entry.primaryKey,\n // Read-relevant (ADR-0045): a readonly projection over a table that receives locally-derived rows must\n // apply CDC inserts with the same idempotent policy, so carry the resolved applyMode verbatim.\n applyMode: entry.applyMode,\n // Read-relevant (ADR-0052): the classification describes the KIND of rows this entry carries, which a\n // readonly projection carries unchanged (it syncs the same rows). Dropping it would silently un-enrol the\n // projected entry from every invariant bound to that class — and, in a registry that declares its\n // `rowClasses`, the projection registry would fail closed at module eval instead.\n ...(entry.rowClass != null ? { rowClass: entry.rowClass } : {}),\n ...(entry.shape != null ? { shape: entry.shape } : {}),\n ...(readonlyProjection != null ? { clientProjection: readonlyProjection } : {}),\n ...(entry.serverProjection != null ? { serverProjection: entry.serverProjection } : {}),\n ...(entry.consistencyGroup != null ? { consistencyGroup: entry.consistencyGroup } : {}),\n ...(entry.subscription != null ? { subscription: entry.subscription } : {}),\n ...(entry.retention != null ? { retention: entry.retention } : {}),\n ...(entry.readProjection ? { readProjection: true } : {}),\n // Read-derivation machinery, not a write handle: the client rebuilds the readonly table's own local\n // synced object from this factory (ADR-0029 P1). Dropping it would break member-mode boot.\n ...(entry.makeColumns != null ? { makeColumns: entry.makeColumns } : {}),\n };\n}\n\n/**\n * Project an entry onto a different **retention** (ADR-0021) — the per-table local-persistence axis:\n * `persistent` (the durable PGlite/OPFS backend) | `ephemeral` (the table's whole local cluster — read\n * cache, overlay, journal, sequence, views, reconcile function — emitted as `TEMP`/`pg_temp`, leaving no\n * durable trace). Returns a copy of `entry` with `retention` overridden and **everything else preserved\n * verbatim** (table, columns, mode, write contract, shape/row filter, the other lifecycle axes).\n *\n * Retention is a **lifecycle** axis, not a read-contract one, so a per-client registry may legitimately\n * differ on it: {@link fingerprintReadContract} excludes retention, so a `withRetention(...)` of an\n * authoritative entry still satisfies {@link assertReadContractPreserved}. This is how one authoritative\n * registry yields a table that is durable for one client and ephemeral for another, e.g.\n * `withRetention(asReadonly(authoritative.exam), \"ephemeral\")`.\n *\n * Unlike `mode` (whose overlay/journal/view fields {@link asReadonly} must re-resolve), retention has **no\n * entry-derived fields** — the durable-vs-`TEMP` decision is taken by the client's schema generator at\n * runtime from this scalar — so overriding it needs no re-resolution and a plain copy is correct. The\n * return type is the input entry's exact type (write handles, create/update typing, governance marker all\n * carry through); the cast restates what a generic object spread cannot prove.\n *\n * Two constraints carry over (enforced elsewhere, not by this helper):\n * - **Consistency-group uniformity** (ADR-0021 §4): every table sharing a `consistencyGroup` must agree on\n * retention — override the whole group, not one member, or `defineSyncRegistry` rejects the mixed group.\n * A singleton-group table can be flipped alone.\n * - **No durable offline write queue for `ephemeral`** (ADR-0021 composition rule): an ephemeral writable\n * table's journal is `TEMP`, so a write staged offline does not survive session end — pair a must-not-lose\n * write with a `pessimistic` write-mode (ADR-0022) or a prompt flush.\n */\nexport function withRetention<TEntry extends SyncTableEntry>(entry: TEntry, retention: Retention): TEntry {\n return { ...entry, retention } as TEntry;\n}\n\n/**\n * The named `ephemeral` lifecycle projection — `withRetention(entry, \"ephemeral\")` — the lifecycle twin of\n * {@link asReadonly}, for the common direction (a client wants no durable trace of a table the authoritative\n * registry keeps `persistent`). Composes with `asReadonly`: `asEphemeral(asReadonly(authoritative.exam))`\n * is a read-only, no-durable-trace projection. The reverse direction (an ephemeral authoritative table a\n * client wants durable) is the bidirectional {@link withRetention} with `\"persistent\"`. See\n * {@link withRetention} for the constraints that carry over (group uniformity; no durable offline queue).\n */\nexport function asEphemeral<TEntry extends SyncTableEntry>(entry: TEntry): TEntry {\n return withRetention(entry, \"ephemeral\");\n}\n\n/**\n * Assert that a per-client `projection` registry preserves the **read contract** (ADR-0025) of the\n * `authoritative` registry it projects from. For every table the projection declares, its\n * {@link fingerprintReadContract} must equal the authoritative entry's: a projection may differ only in\n * write capability and lifecycle orchestration, never in the data it syncs (columns, primary key,\n * row-filter shape). A table present in the authoritative registry but absent from the projection is a\n * permitted subset; a table in the projection with no authoritative source is an error (no contract to\n * project from).\n *\n * Throws, naming the divergent tables, on any mismatch. Call it where the client registries are assembled\n * (module-eval or a test) so a drifted projection fails closed instead of silently serving different rows\n * to different clients. The `customWhere` body is invisible to the fingerprint — bump\n * {@link RowFilterSpec.revision} so a logic-only divergence is caught.\n */\nexport function assertReadContractPreserved(\n authoritative: SyncTableRegistry,\n projection: SyncTableRegistry,\n options?: { label?: string },\n): void {\n const divergent: string[] = [];\n\n for (const [key, projectedEntry] of Object.entries(projection)) {\n const authoritativeEntry = authoritative[key];\n if (authoritativeEntry == null) {\n divergent.push(`${key} (absent from the authoritative registry)`);\n continue;\n }\n if (fingerprintReadContract(authoritativeEntry) !== fingerprintReadContract(projectedEntry)) {\n divergent.push(key);\n }\n }\n\n if (divergent.length > 0) {\n const where = options?.label ? ` (${options.label})` : \"\";\n throw new Error(\n `read-contract divergence${where}: a per-client projection must preserve its authoritative table's ` +\n `read contract (synced columns, primary key, row-filter shape) and differ only in write capability ` +\n `and lifecycle. Divergent tables: ${divergent.join(\", \")}.`,\n );\n }\n}\n",
18
+ "import type { AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport type { Retention } from \"./config\";\nimport { fingerprintReadContract } from \"./fingerprint\";\nimport type { ClientProjectionSpecForTable, SyncTableEntry, SyncTableRegistry } from \"./registry\";\n\n/**\n * Per-client mode projection (ADR-0025). The authoritative (server) registry defines a table once with\n * its full write contract; a client that must only *read* that table consumes the same entry through\n * `asReadonly`. The read/identity contract — table, columns, primary key, synced-table name, column\n * omission, the shape/row filter, the row classification (`rowClass`), AND the column-builder factory\n * (`makeColumns`) — is preserved verbatim; the write-capability metadata is dropped:\n *\n * - `mode` flips to `readonly`;\n * - the overlay-merged read-model `view` and the overlay/journal client projection (the local write\n * machinery `@pgxsinkit/client` provisions for a writable table) are removed — a readonly client reads\n * the synced base table directly;\n * - `conflictPolicy`, `governance` (managed fields), and `writeMode` are removed — a readonly table has\n * no write path, and `defineSyncRegistry` would otherwise still treat them as a writable declaration.\n *\n * The result is the same entry `defineSyncTable` would have produced for this table with\n * `mode: \"readonly\"`, so `defineSyncRegistry` accepts it without the writable-table requirements\n * (server-version field + `conflictPolicy`).\n *\n * Lifecycle axes (`consistencyGroup`, `subscription`, `retention`) are preserved — a projection may keep\n * the authoritative grouping/timing/durability; change them on the projected entry if a client needs to.\n *\n * `makeColumns` (the column-builder factory `defineSyncTable` stashes) is carried too: since ADR-0029 P1\n * the client derives EVERY synced-table object from it (`getSyncedLocalTable` → `projectedColumnBuilders`),\n * so a readonly projection that dropped it could not build its own local synced read cache — the member-boot\n * failure this keep-list's NOTE below predicted. It is read-derivation machinery, not a write handle.\n *\n * NOTE: if a new *read-relevant* field is added to {@link SyncTableEntry}, carry it here too (this builds\n * the readonly entry by listing what to keep, so a new field is otherwise silently dropped).\n */\nexport function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable, TLocalTable>,\n): SyncTableEntry<TTable, TLocalTable> {\n const { clientProjection } = entry;\n const readonlyProjection: ClientProjectionSpecForTable<TTable> | undefined =\n clientProjection != null\n ? {\n ...(clientProjection.syncedTable != null ? { syncedTable: clientProjection.syncedTable } : {}),\n ...(clientProjection.omitColumns != null ? { omitColumns: clientProjection.omitColumns } : {}),\n ...(clientProjection.localPrimaryKey != null ? { localPrimaryKey: clientProjection.localPrimaryKey } : {}),\n }\n : undefined;\n\n return {\n table: entry.table,\n localTable: entry.localTable,\n mode: \"readonly\",\n primaryKey: entry.primaryKey,\n // Read-relevant (ADR-0045): a readonly projection over a table that receives locally-derived rows must\n // apply CDC inserts with the same idempotent policy, so carry the resolved applyMode verbatim.\n applyMode: entry.applyMode,\n // Read-relevant (ADR-0052): the classification describes the KIND of rows this entry carries, which a\n // readonly projection carries unchanged (it syncs the same rows). Dropping it would silently un-enrol the\n // projected entry from every invariant bound to that class — and, in a registry that declares its\n // `rowClasses`, the projection registry would fail closed at module eval instead.\n ...(entry.rowClass != null ? { rowClass: entry.rowClass } : {}),\n ...(entry.shape != null ? { shape: entry.shape } : {}),\n ...(readonlyProjection != null ? { clientProjection: readonlyProjection } : {}),\n ...(entry.serverProjection != null ? { serverProjection: entry.serverProjection } : {}),\n ...(entry.consistencyGroup != null ? { consistencyGroup: entry.consistencyGroup } : {}),\n ...(entry.subscription != null ? { subscription: entry.subscription } : {}),\n ...(entry.retention != null ? { retention: entry.retention } : {}),\n ...(entry.readProjection ? { readProjection: true } : {}),\n // Read-derivation machinery, not a write handle: the client rebuilds the readonly table's own local\n // synced object from this factory (ADR-0029 P1). Dropping it would break member-mode boot.\n ...(entry.makeColumns != null ? { makeColumns: entry.makeColumns } : {}),\n };\n}\n\n/**\n * Project an entry onto a different **retention** (ADR-0021) — the per-table local-persistence axis:\n * `persistent` (the durable PGlite/OPFS backend) | `ephemeral` (the table's whole local cluster — read\n * cache, overlay, journal, sequence, views, reconcile function — emitted as `TEMP`/`pg_temp`, leaving no\n * durable trace). Returns a copy of `entry` with `retention` overridden and **everything else preserved\n * verbatim** (table, columns, mode, write contract, shape/row filter, the other lifecycle axes).\n *\n * Retention is a **lifecycle** axis, not a read-contract one, so a per-client registry may legitimately\n * differ on it: {@link fingerprintReadContract} excludes retention, so a `withRetention(...)` of an\n * authoritative entry still satisfies {@link assertReadContractPreserved}. This is how one authoritative\n * registry yields a table that is durable for one client and ephemeral for another, e.g.\n * `withRetention(asReadonly(authoritative.exam), \"ephemeral\")`.\n *\n * Unlike `mode` (whose overlay/journal/view fields {@link asReadonly} must re-resolve), retention has **no\n * entry-derived fields** — the durable-vs-`TEMP` decision is taken by the client's schema generator at\n * runtime from this scalar — so overriding it needs no re-resolution and a plain copy is correct. The\n * return type is the input entry's exact type (write handles, create/update typing, governance marker all\n * carry through); the cast restates what a generic object spread cannot prove.\n *\n * Two constraints carry over (enforced elsewhere, not by this helper):\n * - **Consistency-group uniformity** (ADR-0021 §4): every table sharing a `consistencyGroup` must agree on\n * retention — override the whole group, not one member, or `defineSyncRegistry` rejects the mixed group.\n * A singleton-group table can be flipped alone.\n * - **No durable offline write queue for `ephemeral`** (ADR-0021 composition rule): an ephemeral writable\n * table's journal is `TEMP`, so a write staged offline does not survive session end — pair a must-not-lose\n * write with a `pessimistic` write-mode (ADR-0022) or a prompt flush.\n */\nexport function withRetention<TEntry extends SyncTableEntry>(entry: TEntry, retention: Retention): TEntry {\n return { ...entry, retention } as TEntry;\n}\n\n/**\n * The named `ephemeral` lifecycle projection — `withRetention(entry, \"ephemeral\")` — the lifecycle twin of\n * {@link asReadonly}, for the common direction (a client wants no durable trace of a table the authoritative\n * registry keeps `persistent`). Composes with `asReadonly`: `asEphemeral(asReadonly(authoritative.exam))`\n * is a read-only, no-durable-trace projection. The reverse direction (an ephemeral authoritative table a\n * client wants durable) is the bidirectional {@link withRetention} with `\"persistent\"`. See\n * {@link withRetention} for the constraints that carry over (group uniformity; no durable offline queue).\n */\nexport function asEphemeral<TEntry extends SyncTableEntry>(entry: TEntry): TEntry {\n return withRetention(entry, \"ephemeral\");\n}\n\n/**\n * Assert that a per-client `projection` registry preserves the **read contract** (ADR-0025) of the\n * `authoritative` registry it projects from. For every table the projection declares, its\n * {@link fingerprintReadContract} must equal the authoritative entry's: a projection may differ only in\n * write capability and lifecycle orchestration, never in the data it syncs (columns, primary key,\n * row-filter shape). A table present in the authoritative registry but absent from the projection is a\n * permitted subset; a table in the projection with no authoritative source is an error (no contract to\n * project from).\n *\n * Throws, naming the divergent tables, on any mismatch. Call it where the client registries are assembled\n * (module-eval or a test) so a drifted projection fails closed instead of silently serving different rows\n * to different clients. The `customPredicate` body is invisible to the fingerprint — bump\n * {@link RowFilterSpec.revision} so a logic-only divergence is caught.\n */\nexport function assertReadContractPreserved(\n authoritative: SyncTableRegistry,\n projection: SyncTableRegistry,\n options?: { label?: string },\n): void {\n const divergent: string[] = [];\n\n for (const [key, projectedEntry] of Object.entries(projection)) {\n const authoritativeEntry = authoritative[key];\n if (authoritativeEntry == null) {\n divergent.push(`${key} (absent from the authoritative registry)`);\n continue;\n }\n if (fingerprintReadContract(authoritativeEntry) !== fingerprintReadContract(projectedEntry)) {\n divergent.push(key);\n }\n }\n\n if (divergent.length > 0) {\n const where = options?.label ? ` (${options.label})` : \"\";\n throw new Error(\n `read-contract divergence${where}: a per-client projection must preserve its authoritative table's ` +\n `read contract (synced columns, primary key, row-filter shape) and differ only in write capability ` +\n `and lifecycle. Divergent tables: ${divergent.join(\", \")}.`,\n );\n }\n}\n",
18
19
  "import { sql, type SQL } from \"drizzle-orm\";\n\n/**\n * The BODY of the canonical microsecond clock — `clock_timestamp()` epoch microseconds as BIGINT.\n * This text is the SINGLE source for the `public.pgxsinkit_clock_us()` function body rendered by the\n * server's utilities migration ({@link renderPgxsinkitUtilitiesMigration}) and NOTHING else. No column\n * DEFAULT and no generated apply-function DDL may embed this expression — every surface CALLS the\n * function ({@link CLOCK_US_CALL_SQL_TEXT} / {@link clockMicrosecondsSql}), so the semantic choices\n * (`clock_timestamp()` over `now()`; `FLOOR` + `BIGINT`) live in exactly one reviewable body.\n */\nexport const NOW_MICROSECONDS_SQL_TEXT = \"CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)\";\n\n/**\n * The CALL form of the canonical microsecond clock, for string-rendering contexts (the apply-function\n * generator's PL/pgSQL literals). Deliberately `clock_timestamp()` (via the function body), never\n * `now()`/`transaction_timestamp()`: `now()` freezes at transaction start, but LWW/audit ordering of a\n * multi-row apply within one transaction needs an ADVANCING clock. The DB function is the canonical\n * home — never inline the expression at a call site.\n */\nexport const CLOCK_US_CALL_SQL_TEXT = \"public.pgxsinkit_clock_us()\";\n\n/**\n * The canonical microsecond clock as a Drizzle fragment, for `.default(...)` column positions — the\n * CALL form `public.pgxsinkit_clock_us()`, never the inline expression. Deliberately `clock_timestamp()`\n * (inside the function), never `now()`/`transaction_timestamp()`: `now()` freezes at transaction start,\n * whereas LWW/audit ordering of a multi-row apply within one transaction needs an advancing clock. The\n * DB function (installed by the utilities migration) is the canonical home; never inline the expression.\n */\nexport const clockMicrosecondsSql: SQL = sql.raw(CLOCK_US_CALL_SQL_TEXT);\n",
20
+ "/**\n * The change envelope carried on every Circuits table and shape stream.\n *\n * Restated rather than imported from `@electric-circuits/protocol`, for the reasons given on\n * {@link Predicate}: this is the wire contract pgxsinkit commits to, the protocol package is alpha,\n * and a published library should not put an alpha peer in its public types. The engine's serde\n * definitions are authoritative; any divergence is a bug here.\n */\n\n/** A scalar cell value on the wire. */\nexport type StreamValue = string | number | boolean | null;\n\n/** A row is a flat map of column name to value. */\nexport type StreamRow = Record<string, StreamValue>;\n\n/**\n * The engine's **complete** shape-stream vocabulary — two verbs, not four.\n *\n * `insert`/`update` are the *input* side: what the replication ingestor parses out of Postgres. They\n * never reach a shape stream. Every row the engine emits goes out as `upsert` (`output.rs`\n * `translate_output`/`agg_envelope`) and every eviction as key-only `delete`\n * (`translate_output`/`delete_envelopes`) — the engine states the row's new value rather than\n * claiming anything about what preceded it, because a shape row can enter a subscriber's view for\n * reasons that are not a Postgres INSERT (a subquery flip, a scope grant, a backfill replay).\n *\n * Listing the input verbs here as if they might arrive is what produced a dead `\"update\"` branch in\n * the translator and a comment asserting `upsert` was backfill-only. Both were wrong.\n */\nexport type StreamOperation = \"upsert\" | \"delete\";\n\nexport interface StreamEnvelope {\n /** The table name — the collection discriminator. */\n type: string;\n /** The stringified primary key. Composite keys are already joined by the engine. */\n key: string;\n /** Present for insert/update/upsert; **absent for delete**, which is key-only. */\n value?: StreamRow;\n headers: {\n operation: StreamOperation;\n txid?: string;\n /** Stamped by the durable-streams server on read; never sent by a producer. */\n offset?: string;\n /**\n * Postgres commit LSN (`\"HI/LO\"` hex), stamped by the engine on **live** shape envelopes.\n *\n * **Absent on backfill rows**, and absent in library (no-Postgres) mode. That absence is why\n * ADR-0056 floors catch-up on the stream OFFSET rather than on this: a frontier that only some\n * envelopes can advance is not a frontier.\n */\n lsn?: string;\n /**\n * Position of the change within its transaction, stamped by the replication ingestor on\n * **table**-stream envelopes so the engine's own tailer can skip at-least-once duplicates.\n * **Not present on shape streams**, which is what we read — recorded so nobody builds\n * deduplication on a field that will never arrive.\n */\n seq?: number;\n };\n}\n\n/** A delete envelope carries no row body, so an eviction discloses nothing but the key. */\nexport function isDeleteEnvelope(envelope: StreamEnvelope): boolean {\n return envelope.headers.operation === \"delete\";\n}\n\n/**\n * One change as the APPLIER consumes it, after an envelope has been resolved against its table.\n *\n * Distinct from {@link StreamEnvelope} on purpose. An envelope is the wire form — key-only on a\n * delete, headers carrying transport metadata. This is what the apply path needs instead: a value\n * that is always present (a delete's is its reconstructed primary key), and the transport metadata\n * dropped.\n *\n * The operation set is {@link StreamOperation}'s, unchanged. The applier used to narrow the wire's\n * four verbs down to three DML verbs; there are only two verbs to carry now, and inventing a DML\n * distinction the engine never made is what the translator got wrong.\n *\n * `value` is `Record<string, unknown>` rather than {@link StreamRow} because the applier handles\n * values the wire never carries — a `bigint` id kept as a string for precision, a JSON column\n * arriving as a parsed object — and narrowing here would only push casts into the codecs.\n */\nexport type SyncRow = Record<string, unknown>;\n\nexport type SyncOperation = StreamOperation;\n\nexport interface SyncChange<T extends SyncRow = SyncRow> {\n /** The stringified primary key, as the stream named it. */\n key: string;\n value: T;\n headers: { operation: SyncOperation } & Record<string, unknown>;\n}\n",
19
21
  "/**\n * The single role-existence guard used by every pgxsinkit-emitted GRANT/REVOKE.\n *\n * pgxsinkit artifacts are portable: the same migration runs on a Supabase-shaped cluster (where\n * `anon`/`authenticated`/`service_role` exist), on a plain Postgres, and on a PGlite test lane\n * (where none of them do). A bare `REVOKE … FROM anon` is a hard error where the role is absent, so\n * every role-scoped grant/revoke is wrapped in a `DO $$ … IF EXISTS (SELECT 1 FROM pg_roles …)`\n * block and simply does nothing there.\n *\n * Two callers share this one definition — `buildRegistryGovernanceSql` (@pgxsinkit/schema, table\n * grants) and the apply-function ACL (@pgxsinkit/server, ADR-0054) — so the guard idiom cannot\n * drift between the artifacts that carry a deployment's authorization posture.\n */\n\nimport { escapeSqlLiteral } from \"./sql-identifier\";\n\n/**\n * Wrap one already-rendered SQL statement (no trailing semicolon) in the role-existence guard.\n *\n * `statementSql` is embedded as a PL/pgSQL string literal, so it is escaped as a whole — callers pass\n * ordinary SQL with real single quotes and real double-quoted identifiers.\n */\nexport function buildRoleGuardedStatement(roleName: string, statementSql: string): string {\n return [\n \"DO $$\",\n \"BEGIN\",\n ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${escapeSqlLiteral(roleName)}') THEN`,\n ` EXECUTE '${escapeSqlLiteral(statementSql)}';`,\n \" END IF;\",\n \"END;\",\n \"$$;\",\n ].join(\"\\n\");\n}\n",
20
- "import { and, eq, getTableName, or, sql, type AnyColumn, type SQL } from \"drizzle-orm\";\nimport { PgDialect, pgPolicy, type AnyPgTable, type PgRole } from \"drizzle-orm/pg-core\";\n\nimport { buildOwnershipShapeWhere, c, DENY_ALL, type JwtClaims } from \"./config\";\n\n// Render a typed fragment to inline-literal SQL text (CREATE POLICY DDL cannot carry `$n` binds).\n// The tier-② discipline for the text builders below: values enter as typed `${value}` interpolations\n// and drizzle owns the escaping; only the claim-extraction leaves stay raw text.\nconst textDialect = new PgDialect();\nfunction renderInlineSql(fragment: SQL): string {\n return textDialect.sqlToQuery(fragment.inlineParams()).sql;\n}\n\n// Walk a dotted claim path defensively (unverified claims may be any shape): anything that is not a\n// plain object on the way down yields `undefined` rather than throwing. Shared by every Electric\n// read-path mirror below — each family's mirror sits beside its own policies and reads exactly the\n// claim the policy's SQL reads.\nfunction readClaimsPath(claims: JwtClaims | null, path: string[]): unknown {\n let current: unknown = claims;\n for (const segment of path) {\n if (typeof current !== \"object\" || current === null || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n// The JWT subject as the read path sees it: a non-empty `sub` string, else null (no subject → the\n// mirrors deny). The RLS counterpart is `buildSubjectSqlText`, which reads the same claim in Postgres.\nfunction readSubjectClaim(claims: JwtClaims | null): string | null {\n const subject = readClaimsPath(claims, [\"sub\"]);\n return typeof subject === \"string\" && subject.length > 0 ? subject : null;\n}\n\ntype SupabaseOwnerOrAdminPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\ntype SupabaseOwnerOrAdminPolicyShape = {\n command: SupabaseOwnerOrAdminPolicyKind;\n using: boolean;\n withCheck: boolean;\n};\n\n// Options for the raw predicate *text* builder (`buildSupabaseOwnerOrAdminPredicateSqlText`) — the\n// documented escape hatch that returns the predicate as a SQL string (for a hand-written trigger or\n// migration). It takes a column *name* because text has no column object. The native policy builder\n// below takes a real Drizzle column instead.\nexport type SupabaseOwnerOrAdminPredicateOptions = {\n ownerSqlColumn?: string;\n adminRoleName?: string;\n subjectCastType?: string;\n /** Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}. */\n adminRolesClaimPath?: readonly string[];\n};\n\nexport type SupabaseOwnerOrAdminNativePoliciesOptions = {\n /** Owner column on the governed row (e.g. `authors.ownerId`). The governed table name is derived from it. */\n ownerColumn: AnyColumn;\n role: PgRole;\n /** Role value (in `app_metadata.roles`) that bypasses ownership (default \"admin\"). */\n adminRoleName?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n /**\n * Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}; pass the SAME value to\n * {@link resolveOwnerOrAdminAccess} / {@link buildOwnerOrAdminShapeWhere} so both surfaces read one claim.\n */\n adminRolesClaimPath?: readonly string[];\n};\n\nconst defaultOwnerSqlColumn = \"owner_id\";\nconst defaultOwnerPropertyKey = \"ownerId\";\nconst defaultAuthenticatedRoleName = \"authenticated\";\nconst defaultAdminRoleName = \"admin\";\nconst defaultSubjectCastType = \"uuid\";\n// The DEFAULT claim path the admin check reads — the single source for BOTH surfaces: the SQL `EXISTS`\n// in `buildAdminRoleExistsSqlText` renders its `-> 'seg'` chain from this array, and the read-path mirror\n// (`resolveOwnerOrAdminAccess`) walks the same segments in JS. Overridable per call via\n// `adminRolesClaimPath` on either surface — pass the same value to both or they drift.\nconst adminRolesClaimPath = [\"app_metadata\", \"roles\"] as const;\n\nconst ownerOrAdminPolicyShapes: SupabaseOwnerOrAdminPolicyShape[] = [\n {\n command: \"select\",\n using: true,\n withCheck: false,\n },\n {\n command: \"insert\",\n using: false,\n withCheck: true,\n },\n {\n command: \"update\",\n using: true,\n withCheck: true,\n },\n {\n command: \"delete\",\n using: true,\n withCheck: false,\n },\n];\n\nfunction assertIdentifier(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL identifier: ${value}`);\n }\n}\n\nfunction assertTypeName(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\\s+[A-Za-z_][A-Za-z0-9_]*)*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL type name: ${value}`);\n }\n}\n\nfunction buildOwnerOrAdminPolicyName(tableName: string, command: SupabaseOwnerOrAdminPolicyKind) {\n return `${tableName}_${command}_owner_or_admin`;\n}\n\n// ---------------------------------------------------------------------------\n// Shared predicate leaves (used by both policy families). RLS is the *write* path\n// (Postgres), so columns may serialize qualified — unlike the Electric read `where`,\n// which needs bare columns. The only bits that stay raw `sql` are genuinely-Postgres\n// expressions with no Drizzle operator: the JWT-subject `(select current_setting(...)::type)`\n// and the admin-roles `EXISTS`. Literal values use `eq(col, value).inlineParams()` so the\n// value is inlined into the DDL — a bare `$n` is something `CREATE POLICY` cannot carry.\n// ---------------------------------------------------------------------------\n\n// The governed table name (for policy identifiers) derived from a built Drizzle column, so renaming\n// the table renames its policies. Columns built inside `defineSyncTable`'s `extras` callback carry\n// their `.table` — which is where these builders are meant to be called (the table object does not\n// yet exist when its own `policies:` array would be built).\nfunction tableNameForColumn(column: AnyColumn, label: string): string {\n const table = (column as { table?: AnyPgTable }).table;\n if (!table) {\n throw new Error(\n `${label} must be a built Drizzle column carrying its table — call this builder inside defineSyncTable's \\`extras\\` callback`,\n );\n }\n return getTableName(table);\n}\n\n// The JWT subject as a Postgres expression (irreducibly raw: `current_setting` + cast). Used as the\n// right-hand side of `eq(ownerColumn, subject)` — eq splices an SQL fragment verbatim (no bound\n// param), so the DDL carries the literal expression, not a `$n` CREATE POLICY cannot bind. Wrapped in\n// a scalar subquery — the Supabase RLS performance idiom: the stable `current_setting` expression is\n// evaluated once per statement (InitPlan), not once per row.\nfunction buildSubjectSql(subjectCastType: string): SQL {\n assertTypeName(subjectCastType, \"subjectCastType\");\n return sql.raw(`(select ${buildSubjectSqlText(subjectCastType)})`);\n}\n\nfunction buildSubjectSqlText(subjectCastType: string): string {\n return `coalesce(\n nullif(current_setting('request.jwt.claim.sub', true), ''),\n (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')\n )::${subjectCastType}`;\n}\n\n// The claim path the admin check walks, validated as plain identifiers (they are emitted into policy\n// DDL). Mirrors `resolveGrantsClaimPath` in the grant-scope family below.\nfunction resolveAdminRolesClaimPath(path: readonly string[] | undefined): string[] {\n const segments = path && path.length > 0 ? [...path] : [...adminRolesClaimPath];\n for (const segment of segments) {\n assertIdentifier(segment, \"adminRolesClaimPath segment\");\n }\n return segments;\n}\n\n// The claim path as a jsonb `-> 'seg'` chain, one typed interpolation per segment (drizzle owns the\n// quoting), so the SQL walks the SAME array the JS mirror walks — textual agreement is not enough.\nfunction buildClaimPathChainSql(path: string[]): SQL {\n return sql.join(\n path.map((segment) => sql` -> ${segment}`),\n sql``,\n );\n}\n\n// An extracted claim as an ARRAY or nothing at all — the SQL twin of the mirrors' \"an unverified claim\n// of the wrong shape confers nothing\". Absent/null already yields `[]`; the load-bearing case is a\n// claim that is PRESENT but not an array (a token hook emitting `roles: \"admin\"` instead of\n// `[\"admin\"]`), which would otherwise reach `jsonb_array_elements(_text)` and raise \"cannot extract\n// elements from a scalar/object\" — turning every governed write into an RLS execution ERROR instead of\n// a clean deny. Wrapped here, a non-array claim behaves exactly like an absent one, so the policy\n// reaches the same verdict as `resolveOwnerOrAdminAccess` / `resolveGrantScopeAccess`.\n// The expression is repeated (Postgres has nowhere to bind it inside a policy predicate); it is a\n// stable per-statement expression, so the planner evaluates it once, not per row.\nfunction buildClaimArraySqlText(claimSqlText: string): string {\n return `case jsonb_typeof(${claimSqlText}) when 'array' then ${claimSqlText} else '[]'::jsonb end`;\n}\n\n// The admin-bypass test: the roles array at `adminRolesClaimPath` (from the JWT claims) contains\n// `adminRoleName`. No column reference and no recursion risk, so it is inlined as text (shared by the\n// text builder and the native builder). The role value and the claim-path segments enter as typed\n// interpolations (drizzle owns the escaping); the claim-extraction body is the allowed raw leaf, and it\n// goes through {@link buildClaimArraySqlText} so a malformed `roles` denies instead of erroring.\nfunction buildAdminRoleExistsSqlText(adminRoleName: string, claimPath: string[]): string {\n const rolesClaim = renderInlineSql(sql`(\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb${buildClaimPathChainSql(claimPath)}\n )`);\n\n return renderInlineSql(sql`EXISTS (\n SELECT 1\n FROM jsonb_array_elements_text(\n ${sql.raw(buildClaimArraySqlText(rolesClaim))}\n ) AS assigned_role(role_name_value)\n WHERE assigned_role.role_name_value = ${adminRoleName}\n )`);\n}\n\nfunction normalizePredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions = {}) {\n const ownerSqlColumn = options.ownerSqlColumn ?? defaultOwnerSqlColumn;\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subjectCastType = options.subjectCastType ?? defaultSubjectCastType;\n\n assertIdentifier(ownerSqlColumn, \"ownerSqlColumn\");\n assertTypeName(subjectCastType, \"subjectCastType\");\n\n return {\n ownerSqlColumn,\n adminRoleName,\n subjectCastType,\n claimPath: resolveAdminRolesClaimPath(options.adminRolesClaimPath),\n };\n}\n\n/**\n * The owner-or-admin predicate as raw SQL **text** — the escape hatch for when you need the predicate\n * as a string (a hand-written trigger, a manual migration). For attaching RLS to a Drizzle table,\n * prefer `buildSupabaseOwnerOrAdminNativePolicies`, which takes the real column and is rename-tracked.\n */\nexport function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwnerOrAdminPredicateOptions = {}): string {\n const normalized = normalizePredicateOptions(options);\n\n return `\n ${normalized.ownerSqlColumn} = ${buildSubjectSqlText(normalized.subjectCastType)}\n OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName, normalized.claimPath)}\n`;\n}\n\n// owner-or-admin predicate built from the real Drizzle column: `eq(ownerColumn, subject)` (qualified,\n// rename-tracked) OR the raw admin-roles EXISTS (no column, no Drizzle operator). The single boolean\n// is `or(...)`.\nexport function buildSupabaseOwnerOrAdminNativePolicies(options: SupabaseOwnerOrAdminNativePoliciesOptions) {\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);\n const adminExists = sql.raw(\n buildAdminRoleExistsSqlText(adminRoleName, resolveAdminRolesClaimPath(options.adminRolesClaimPath)),\n );\n const predicate = or(eq(options.ownerColumn, subject), adminExists)!;\n const tableName = tableNameForColumn(options.ownerColumn, \"ownerColumn\");\n\n return ownerOrAdminPolicyShapes.map((shape) =>\n pgPolicy(buildOwnerOrAdminPolicyName(tableName, shape.command), {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\nexport const supabaseOwnerOrAdminDefaults = {\n ownerSqlColumn: defaultOwnerSqlColumn,\n ownerPropertyKey: defaultOwnerPropertyKey,\n authenticatedRoleName: defaultAuthenticatedRoleName,\n adminRoleName: defaultAdminRoleName,\n subjectCastType: defaultSubjectCastType,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Electric read-path mirror of the owner-or-admin policies. Electric cannot read RLS, so the proxy has\n// to reach the same verdict in JS, from the same claims: the policy's `OR` admin branch becomes \"no\n// filter at all\" (every row streams), and its owner branch becomes the ownership shape `where`. One\n// declaration — the owner column plus the admin role name — two enforcement surfaces, so a row can\n// never be writable-but-unreadable (or the reverse).\n//\n// SELECT only, by construction: a shape `where` filters a read stream, so it mirrors the `select`\n// policy. INSERT/UPDATE/DELETE remain the policies' business.\n// ---------------------------------------------------------------------------\n\n/**\n * Claim-reading options for the read mirror; every field must match the value the policies were built\n * with, or the two surfaces stop agreeing.\n */\nexport type OwnerOrAdminAccessOptions = {\n /** Role value (in `app_metadata.roles`) that bypasses ownership (default \"admin\"). */\n adminRoleName?: string;\n /** Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}. */\n adminRolesClaimPath?: readonly string[];\n};\n\n/** The caller's standing on an owner-or-admin table, as resolved from the claims. */\nexport type OwnerOrAdminAccess = {\n /** The caller holds the admin role — the policy's bypass branch; every row is visible. */\n admin: boolean;\n /** The JWT subject when it is a non-empty string, else null (no subject → nothing is visible). */\n subject: string | null;\n};\n\n/**\n * The caller's owner-or-admin standing, resolved from the JWT claims — the JS mirror of the policy's\n * admin `EXISTS` and its subject comparison. `admin` is true when the roles array at\n * `adminRolesClaimPath` (`app_metadata.roles` by default — the very array\n * {@link buildSupabaseOwnerOrAdminNativePolicies} renders its `-> 'seg'` chain from, so the two surfaces\n * read one declaration) contains `adminRoleName`; `subject` is the `sub` claim when it is a non-empty\n * string, else null.\n *\n * Claims arrive unverified in shape, so this never throws: a missing/non-object claims bag, a\n * non-array `roles`, or non-string members simply confer nothing.\n */\nexport function resolveOwnerOrAdminAccess(\n claims: JwtClaims | null,\n options: OwnerOrAdminAccessOptions = {},\n): OwnerOrAdminAccess {\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const roles = readClaimsPath(claims, resolveAdminRolesClaimPath(options.adminRolesClaimPath));\n const admin = Array.isArray(roles) && roles.some((role) => typeof role === \"string\" && role === adminRoleName);\n\n return { admin, subject: readSubjectClaim(claims) };\n}\n\n/**\n * The Electric shape `where` for an owner-or-admin table — the read counterpart of\n * {@link buildSupabaseOwnerOrAdminNativePolicies}, built from the same owner column. An admin gets\n * `null` (no filter, every row — the policy's bypass branch); anyone else gets\n * {@link buildOwnershipShapeWhere}, i.e. their own rows, or the {@link DENY_ALL} sentinel when there is\n * no subject. Returning the sentinel *by reference* is what lets a `customWhere` built on this probe as\n * claims-dependent (`isClaimsDependentRowFilter`).\n */\nexport function buildOwnerOrAdminShapeWhere(\n ownerColumn: AnyColumn,\n claims: JwtClaims | null,\n options: OwnerOrAdminAccessOptions = {},\n): SQL | null {\n const access = resolveOwnerOrAdminAccess(claims, options);\n return access.admin ? null : buildOwnershipShapeWhere(ownerColumn, access.subject);\n}\n\n// ---------------------------------------------------------------------------\n// Membership-scoped policies (generic). A row belongs to a *container* and is\n// visible/writable through membership of that container — not just ownership.\n// This is the readwrite counterpart to a membership row-filter: every member of\n// the container may read the row (fan-out to non-owners); only the owner may\n// create it (as themselves) and edit it, while a container *manager* may moderate\n// any row. Domain-agnostic: the container, membership table, and manager role are\n// all parameters.\n//\n// The container, membership, and owner references are **real Drizzle columns/tables**\n// (not name strings), so the policy tracks the schema — a column or table rename is a\n// compile error, and the governed table name is *derived* from the container column\n// (no redundant `tableName` to drift). Predicate structure is built with Drizzle\n// operators (`and`/`or`/`eq`, with `.inlineParams()` on the `'manager'` / `false` literals so\n// they inline instead of becoming a `$n` CREATE POLICY cannot carry); only the irreducibly-Postgres\n// leaves stay `sql`: the `IN (subquery)` containment (Drizzle's `inArray` cannot wrap a raw subquery)\n// and the `(select current_setting(...)::type)` JWT-subject expression (wrapped in a scalar subquery —\n// the Supabase per-statement-eval RLS perf idiom). Columns serialize qualified\n// (`\"work_items\".\"workspace_id\"`) — fine for Postgres RLS (the write path, unlike Electric's bare rule).\n//\n// The `select` half of this family is mirrored on the Electric read path by\n// {@link buildMembershipShapeWhere}, built from the same column declarations — Electric cannot read\n// RLS, so the two surfaces are generated from one declaration and must agree.\n// ---------------------------------------------------------------------------\n\ntype MembershipPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nexport type SupabaseMembershipPredicateColumns = {\n /** Column on the governed row naming its container (e.g. `workItems.workspaceId`). */\n containerColumn: AnyColumn;\n /** Membership link table (e.g. the `workspace_members` table). */\n membershipTable: AnyPgTable;\n /** Container column on the membership link table (e.g. `workspaceMembers.workspaceId`). */\n membershipContainerColumn: AnyColumn;\n /** Subject (member) column on the membership link table, compared to the JWT sub. */\n membershipSubjectColumn: AnyColumn;\n /** Owner column on the governed row (e.g. `workItems.ownerId`). */\n ownerColumn: AnyColumn;\n /** Optional role column on the membership link enabling manager moderation. */\n managerRoleColumn?: AnyColumn;\n /** Role value that grants moderation (default \"manager\"); only used with managerRoleColumn. */\n managerRoleValue?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n};\n\n// Optional write-state gate (generic). When supplied, INSERT and UPDATE are additionally gated on\n// mutable state: a *locked* container admits writes only from a manager (e.g. a frozen discussion\n// thread), and a *muted* member may not write at all. SELECT and DELETE are unaffected — reads and\n// moderation deletes still flow. Domain-agnostic: the container/lock and membership/mute columns are\n// parameters. Requires managerRoleColumn (managers bypass the lock).\nexport type SupabaseMembershipWriteGateColumns = {\n /** Container table holding the lock flag (e.g. the `workspaces` table). */\n containerTable: AnyPgTable;\n /** PK column on the container table the governed row's container column references (e.g. `workspaces.id`). */\n containerPkColumn: AnyColumn;\n /** Boolean column on the container table; when true, only a manager may write (e.g. `workspaces.locked`). */\n containerLockColumn: AnyColumn;\n /** Boolean column on the membership table; when true, that member may not write (e.g. `workspaceMembers.muted`). */\n membershipMutedColumn: AnyColumn;\n};\n\nexport type SupabaseMembershipNativePoliciesOptions = SupabaseMembershipPredicateColumns & {\n role: PgRole;\n /** Optional write-state gate applied to INSERT and UPDATE only. */\n writeGate?: SupabaseMembershipWriteGateColumns;\n};\n\nconst defaultManagerRoleValue = \"manager\";\n\nconst membershipPolicyShapes: { command: MembershipPolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\ntype NormalizedMembershipColumns = SupabaseMembershipPredicateColumns & {\n managerRoleValue: string;\n subjectCastType: string;\n};\n\nfunction normalizeMembershipColumns(options: SupabaseMembershipPredicateColumns): NormalizedMembershipColumns {\n return {\n ...options,\n managerRoleValue: options.managerRoleValue ?? defaultManagerRoleValue,\n subjectCastType: options.subjectCastType ?? defaultSubjectCastType,\n };\n}\n\n// Containment form (not a correlated EXISTS): the governed row's container column must be in the set\n// of containers the subject belongs to. Two reasons it is `= ANY(ARRAY(subquery))` and not\n// `IN (subquery)`, both load-bearing:\n// 1. Correctness — the subquery stays uncorrelated (its `WHERE` references only the subject), so the\n// membership table's same-named column can't shadow the outer container column. A correlated\n// `EXISTS (… WHERE m.container = container …)` would collapse the correlation.\n// 2. Performance — for a runtime-resolved set (the subject comes from `current_setting`, opaque to\n// the planner) `IN (subquery)` is costed as a hashed semi-join → **sequential scan** of the\n// governed table; `= ANY(ARRAY(subquery))` materializes the set once (InitPlan) and the\n// ScalarArrayOp drives a **bitmap index scan**. At scale that is ~25-45× faster (the rls-read\n// perf track proves it). `inArray` can't wrap a raw subquery, so this stays `sql`.\nfunction membershipMatch(cols: NormalizedMembershipColumns, subject: SQL, requireManager: boolean): SQL {\n const subjectIsMember = eq(cols.membershipSubjectColumn, subject);\n const where =\n requireManager && cols.managerRoleColumn\n ? and(subjectIsMember, eq(cols.managerRoleColumn, cols.managerRoleValue).inlineParams())!\n : subjectIsMember;\n\n return sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${where}))`;\n}\n\n/** owner-or-manager predicate (edit / moderate). */\nfunction ownerOrManager(cols: NormalizedMembershipColumns, subject: SQL): SQL {\n const owner = eq(cols.ownerColumn, subject);\n return cols.managerRoleColumn ? or(owner, membershipMatch(cols, subject, true))! : owner;\n}\n\n// write-state gate: ((container not locked) OR caller is a manager) AND caller's membership not muted.\n// Same `= ANY(ARRAY(subquery))` containment discipline as membershipMatch (uncorrelated set, index-scan\n// friendly), so the container/membership tables can reuse their own column names without shadowing the\n// governed row's container column.\nfunction membershipWriteGate(\n cols: NormalizedMembershipColumns,\n gate: SupabaseMembershipWriteGateColumns,\n subject: SQL,\n): SQL {\n const unlocked = sql`${cols.containerColumn} = any(array(select ${gate.containerPkColumn} from ${gate.containerTable} where ${eq(gate.containerLockColumn, false).inlineParams()}))`;\n const notMuted = sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${and(eq(cols.membershipSubjectColumn, subject), eq(gate.membershipMutedColumn, false).inlineParams())}))`;\n return and(or(unlocked, membershipMatch(cols, subject, true))!, notMuted)!;\n}\n\nexport function buildSupabaseMembershipNativePolicies(options: SupabaseMembershipNativePoliciesOptions) {\n const cols = normalizeMembershipColumns(options);\n const subject = buildSubjectSql(cols.subjectCastType);\n const tableName = tableNameForColumn(cols.containerColumn, \"containerColumn\");\n\n const memberPredicate = membershipMatch(cols, subject, false);\n const ownerAndMember = and(eq(cols.ownerColumn, subject), memberPredicate)!;\n const ownerOrManagerPredicate = ownerOrManager(cols, subject);\n\n let writeGateClause: SQL | null = null;\n if (options.writeGate) {\n if (!cols.managerRoleColumn) {\n throw new Error(\"writeGate requires managerRoleColumn so a manager can write into a locked container\");\n }\n writeGateClause = membershipWriteGate(cols, options.writeGate, subject);\n }\n\n const gatedForWrite = (base: SQL): SQL => (writeGateClause ? and(base, writeGateClause)! : base);\n\n const predicateFor = (command: MembershipPolicyKind): SQL => {\n switch (command) {\n case \"select\":\n return memberPredicate;\n case \"insert\":\n return gatedForWrite(ownerAndMember);\n case \"update\":\n return gatedForWrite(ownerOrManagerPredicate);\n case \"delete\":\n return ownerOrManagerPredicate;\n }\n };\n\n return membershipPolicyShapes.map((shape) => {\n const predicate = predicateFor(shape.command);\n\n return pgPolicy(`${tableName}_${shape.command}_membership`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n });\n });\n}\n\n// ---------------------------------------------------------------------------\n// Electric read-path mirror of the membership policies. Electric cannot read RLS, so the proxy must\n// re-derive the same visible set in the shape `where`, from the SAME Drizzle columns the policies were\n// built from — one declaration, two enforcement surfaces, so a row can never be readable-but-unwritable\n// (or the reverse) through a rename or a typo.\n//\n// SELECT only, by construction: the mirror reproduces the family's `select` predicate — plain\n// membership of the container. The owner/manager branches and the write-state gate are WRITE-side\n// concerns (INSERT/UPDATE/DELETE) and are deliberately absent here; a shape `where` filters a read\n// stream and has nothing to gate.\n//\n// The two surfaces render the SAME containment differently, on purpose:\n// - RLS (`membershipMatch`) renders `= ANY(ARRAY(select …))` — the InitPlan/bitmap-index-scan\n// discipline Postgres needs for a runtime-resolved set (see that function's comment).\n// - Electric renders a plain `IN (subquery)`, because that is what Electric's shape `where` grammar\n// accepts; there is no Postgres planner on this side to appease.\n// Same columns, two dialects — that is exactly what the mirror is for.\n// ---------------------------------------------------------------------------\n\n/**\n * The columns {@link buildMembershipShapeWhere} needs: the SELECT-relevant subset of\n * {@link SupabaseMembershipPredicateColumns}. The write-only fields (owner, manager role, subject cast,\n * write gate, policy role) are accepted but ignored, so the **same declaration object** you hand to\n * {@link buildSupabaseMembershipNativePolicies} can be handed to the read mirror verbatim.\n */\nexport type SupabaseMembershipShapeColumns = Pick<\n SupabaseMembershipPredicateColumns,\n \"containerColumn\" | \"membershipTable\" | \"membershipContainerColumn\" | \"membershipSubjectColumn\"\n> &\n Partial<SupabaseMembershipNativePoliciesOptions>;\n\n/**\n * The Electric shape `where` for a membership-scoped table — the read counterpart of the `select`\n * policy in {@link buildSupabaseMembershipNativePolicies}: the row's container must be one the caller\n * is a member of. Columns are referenced **bare** via {@link c} (Electric's grammar requires plain\n * column refs) yet still through the real Drizzle column objects, so the reference is rename-safe; the\n * subject rides as a typed interpolation and becomes a bound param once `buildRowFilterShape`\n * serializes it (never a hand-escaped literal). The subquery is **self-contained** (uncorrelated) — it\n * gets its own `FROM`, so the membership table's bare column names resolve to it.\n *\n * No subject → {@link DENY_ALL} (by reference, so a `customWhere` built on it probes claims-dependent),\n * mirroring the policy, whose membership subquery matches nothing without a JWT sub.\n */\nexport function buildMembershipShapeWhere(columns: SupabaseMembershipShapeColumns, claims: JwtClaims | null): SQL {\n const subject = readSubjectClaim(claims);\n if (subject === null) {\n return DENY_ALL;\n }\n\n return sql`${c(columns.containerColumn)} in (select ${c(columns.membershipContainerColumn)} from ${columns.membershipTable} where ${c(columns.membershipSubjectColumn)} = ${subject})`;\n}\n\n// ---------------------------------------------------------------------------\n// Grant-scope policies (generic). Authorization is carried IN THE JWT, not a DB\n// table: `app_metadata.authorization.grants` is an array of\n// `{ role, scope: { kind, <kind>Id } }` minted into the token. A row is visible\n// when its scope column (e.g. `offering_id`) appears among the caller's grants for\n// one of the accepting roles. Because the grant set lives in the token, the\n// predicate needs NO join — it parses the claims jsonb and tests set membership.\n//\n// Two forms, deliberately:\n// - default (InitPlan-correct): an **uncorrelated** `scope_col IN (SELECT …\n// jsonb_array_elements(claims) …)`. The subquery never references the outer row,\n// so the planner hoists it to an InitPlan and the JWT is parsed **once per\n// statement**.\n// - `naive: true` (the cliff): a **correlated** `EXISTS (… WHERE (g->…->>id) =\n// scope_col)`. Referencing the outer row forces per-row re-evaluation — the JWT\n// is re-parsed for **every row scanned**. It exists only to demonstrate and\n// regression-guard the InitPlan discipline (see the `rls-read-load` perf track);\n// never ship it.\n//\n// The same grant set is mirrored on the Electric read path by {@link resolveGrantScopeAccess}\n// (or {@link resolveGrantScopeIds} for the id set alone) + {@link buildGrantScopeShapeWhere}: the proxy\n// resolves the ids from the claims in JS and injects a literal `scope_col IN ('a','b')` — Electric\n// cannot read RLS, so the two surfaces are generated from one declaration and must agree.\n// ---------------------------------------------------------------------------\n\ntype GrantScopePolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nconst defaultGrantsClaimPath = [\"app_metadata\", \"authorization\", \"grants\"] as const;\nconst defaultGrantScopeCastType = \"uuid\";\n// Scope kind a bypass grant must carry, on BOTH surfaces: the policy's `buildBypassExistsSqlText`\n// inlines it and the read mirror's `resolveGrantScopeAccess` compares against it.\nconst defaultBypassScopeKind = \"platform\";\n\n/**\n * An unconditional bypass declaration: any grant whose `role` ∈ `roleValues` and whose `scope.kind` =\n * `scopeKind` (default `\"platform\"`) confers access to every row — e.g. a platform-scoped\n * `platform_admin`. Hand the SAME object to the policy builder and to\n * {@link resolveGrantScopeAccess} / {@link buildGrantScopeAccessShapeWhere}.\n */\nexport type GrantScopeBypassOptions = {\n roleValues: string[];\n scopeKind?: string;\n};\n\nexport type GrantScopeClaimOptions = {\n /** Value matched against each grant's `scope.kind` (e.g. \"offering\"). */\n scopeKind: string;\n /** Grant `role` values that confer access (e.g. [\"teacher\", \"assistant\"]). */\n roleValues: string[];\n /** Field within `scope` holding the id (e.g. \"offeringId\"). Defaults to `${scopeKind}Id`. */\n scopeIdField?: string;\n /** Path to the grants array in the claims. Defaults to `app_metadata.authorization.grants`. */\n grantsClaimPath?: string[];\n};\n\nexport type SupabaseGrantScopePredicateColumns = GrantScopeClaimOptions & {\n /** Column on the governed row naming its scope (e.g. `offerings.id` reference column). Table name is derived from it. */\n scopeColumn: AnyColumn;\n /** SQL type the extracted grant id is cast to before comparison (default \"uuid\"). */\n scopeCastType?: string;\n /**\n * Optional unconditional bypass ({@link GrantScopeBypassOptions}): any grant whose `role` ∈\n * `bypass.roleValues` and whose `scope.kind` = `bypass.scopeKind` (default \"platform\") grants all\n * rows — e.g. a platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it\n * stays InitPlan-hoisted in both the correct and naive forms. Its read-path twin is\n * {@link buildGrantScopeAccessShapeWhere} (bypass → `null`, i.e. no shape filter at all).\n */\n bypass?: GrantScopeBypassOptions;\n};\n\nexport type SupabaseGrantScopeNativePoliciesOptions = SupabaseGrantScopePredicateColumns & {\n role: PgRole;\n /** Emit the deliberately-naive per-row correlated form (cliff demo / regression guard only). */\n naive?: boolean;\n};\n\nconst grantScopePolicyShapes: { command: GrantScopePolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\nfunction resolveGrantsClaimPath(path: readonly string[] | undefined): string[] {\n const segments = path && path.length > 0 ? [...path] : [...defaultGrantsClaimPath];\n for (const segment of segments) {\n assertIdentifier(segment, \"grantsClaimPath segment\");\n }\n return segments;\n}\n\n// The grants array as a Postgres jsonb expression, guarded by {@link buildClaimArraySqlText} so\n// `jsonb_array_elements` never errors: an absent, null, OR non-array grants claim all yield `[]`, i.e.\n// no grants — the same \"confers nothing\" verdict `resolveGrantScopeAccess` reaches in JS. Shared by the\n// scope predicate (both forms) and the bypass EXISTS. `#>` takes a text[] path; the segments are\n// validated identifiers, so the `'{…}'` path literal is injection-safe.\nfunction buildGrantsArraySqlText(path: string[]): string {\n return buildClaimArraySqlText(`(\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb #> '{${path.join(\",\")}}'\n )`);\n}\n\nfunction buildRoleInListSqlText(roleValues: string[]): string {\n if (roleValues.length === 0) {\n throw new Error(\"grant-scope policy requires at least one role value\");\n }\n return renderInlineSql(\n sql.join(\n roleValues.map((role) => sql`${role}`),\n sql`, `,\n ),\n );\n}\n\nfunction resolveGrantScopeIdField(options: GrantScopeClaimOptions): string {\n const field = options.scopeIdField ?? `${options.scopeKind}Id`;\n assertIdentifier(field, \"scopeIdField\");\n return field;\n}\n\n// Uncorrelated bypass test (never references the governed row), so it is InitPlan-hoisted in both forms.\nfunction buildBypassExistsSqlText(bypass: GrantScopeBypassOptions, grantsText: string): string {\n const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;\n return `exists (\n select 1\n from jsonb_array_elements(${grantsText}) as bypass_grant\n where bypass_grant -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)}\n and bypass_grant ->> 'role' in (${buildRoleInListSqlText(bypass.roleValues)})\n )`;\n}\n\nfunction buildGrantScopePredicate(options: SupabaseGrantScopeNativePoliciesOptions): SQL {\n const scopeKind = options.scopeKind;\n assertIdentifier(scopeKind, \"scopeKind\");\n const scopeIdField = resolveGrantScopeIdField(options);\n const castType = options.scopeCastType ?? defaultGrantScopeCastType;\n assertTypeName(castType, \"scopeCastType\");\n const grantsText = buildGrantsArraySqlText(resolveGrantsClaimPath(options.grantsClaimPath));\n const roleIn = buildRoleInListSqlText(options.roleValues);\n const kindMatch = `grant_elem -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)} and grant_elem ->> 'role' in (${roleIn})`;\n const idExpr = `(grant_elem -> 'scope' ->> ${renderInlineSql(sql`${scopeIdField}`)})::${castType}`;\n\n // Correct: uncorrelated `= ANY(ARRAY(select …))` → the grant set materializes once (InitPlan, JWT\n // parsed once) and the ScalarArrayOp drives a bitmap index scan on the scope column — ~25-45× faster\n // at scale than `IN (select …)`, which the planner costs as a hashed semi-join → sequential scan (the\n // rls-read perf track proves both). Naive: correlated `EXISTS` referencing the governed scope column →\n // re-evaluated per row (JWT parsed per row). The column object is spliced so it serializes qualified —\n // valid CREATE POLICY DDL on the write path.\n const base = options.naive\n ? sql`exists (select 1 from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)} and ${sql.raw(idExpr)} = ${options.scopeColumn})`\n : sql`${options.scopeColumn} = any(array(select ${sql.raw(idExpr)} from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)}))`;\n\n if (!options.bypass) {\n return base;\n }\n return or(base, sql.raw(buildBypassExistsSqlText(options.bypass, grantsText)))!;\n}\n\n/**\n * Native Drizzle RLS policies for a JWT-resident grant set (see the section comment). Pass the real\n * scope column; the governed table name is derived from it. By default the predicate is the\n * InitPlan-correct uncorrelated `IN (subquery)`; pass `naive: true` for the correlated cliff variant.\n */\nexport function buildSupabaseGrantScopeNativePolicies(options: SupabaseGrantScopeNativePoliciesOptions) {\n const predicate = buildGrantScopePredicate(options);\n const tableName = tableNameForColumn(options.scopeColumn, \"scopeColumn\");\n const suffix = options.naive ? \"grant_scope_naive\" : \"grant_scope\";\n\n return grantScopePolicyShapes.map((shape) =>\n pgPolicy(`${tableName}_${shape.command}_${suffix}`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Electric read-path mirror of the grant-scope policy. Electric cannot read RLS, so the proxy must\n// resolve the same visible scope-id set from the claims in JS and inject a literal `IN (…)` shape\n// `where`. These helpers are the read-path counterpart to the policy above — one declaration,\n// two enforcement surfaces, derived from the same grant data so they cannot drift.\n//\n// The policy's OR bypass branch has a mirror too: {@link resolveGrantScopeAccess} reports it and\n// {@link buildGrantScopeAccessShapeWhere} turns it into `null` — no shape filter at all, every row\n// streams — exactly as the `exists (…)` OR-branch makes the scope test irrelevant on the write side.\n// Without it a bypass grant would be enforced on writes yet invisible on reads.\n// ---------------------------------------------------------------------------\n\n/**\n * The set of scope ids the caller can see, resolved from the JWT grants — the JS mirror of the\n * grant-scope RLS subquery. Returns a de-duplicated list (empty → no rows visible).\n */\nexport function resolveGrantScopeIds(claims: JwtClaims | null, options: GrantScopeClaimOptions): string[] {\n const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));\n if (!Array.isArray(grants)) {\n return [];\n }\n\n const scopeIdField = resolveGrantScopeIdField(options);\n const roleValues = new Set(options.roleValues);\n const ids = new Set<string>();\n\n for (const grant of grants) {\n if (typeof grant !== \"object\" || grant === null) {\n continue;\n }\n const record = grant as Record<string, unknown>;\n if (!roleValues.has(String(record[\"role\"]))) {\n continue;\n }\n const scope = record[\"scope\"];\n if (typeof scope !== \"object\" || scope === null) {\n continue;\n }\n const scopeRecord = scope as Record<string, unknown>;\n if (scopeRecord[\"kind\"] !== options.scopeKind) {\n continue;\n }\n const id = scopeRecord[scopeIdField];\n if (typeof id === \"string\" && id.length > 0) {\n ids.add(id);\n }\n }\n\n return [...ids];\n}\n\n/**\n * The Electric shape `where` for a grant-scope table: an `IN (…)` over the resolved ids (what the\n * proxy injects). Takes the real Drizzle scope column — referenced bare via `c()` (Electric's grammar\n * requires bare columns), so the reference is rename-safe — and returns a typed fragment whose ids\n * are **bound params** once `buildRowFilterShape` serializes it (never hand-escaped literals). An\n * empty id set denies all rows ({@link DENY_ALL}), mirroring the policy returning no rows.\n */\nexport function buildGrantScopeShapeWhere(scopeColumn: AnyColumn, ids: string[]): SQL {\n if (ids.length === 0) {\n return DENY_ALL;\n }\n return sql`${c(scopeColumn)} in (${sql.join(\n ids.map((id) => sql`${id}`),\n sql`, `,\n )})`;\n}\n\n/** The full grant-scope declaration the read mirror needs: the claim options plus the optional bypass. */\nexport type GrantScopeAccessOptions = GrantScopeClaimOptions & {\n /** The same {@link GrantScopeBypassOptions} handed to {@link buildSupabaseGrantScopeNativePolicies}. */\n bypass?: GrantScopeBypassOptions;\n};\n\n/** The caller's standing on a grant-scope table, as resolved from the claims. */\nexport type GrantScopeAccess = {\n /** A bypass grant is present — the policy's OR branch; every row is visible. */\n bypass: boolean;\n /** The de-duplicated scope ids the caller can see (empty → no rows, absent a bypass). */\n ids: string[];\n};\n\n// The JS mirror of `buildBypassExistsSqlText`: a grant whose `role` is one of `bypass.roleValues` and\n// whose `scope.kind` is `bypass.scopeKind` (defaulting to the same `defaultBypassScopeKind` the SQL\n// inlines). Claims arrive unverified in shape, so nothing here throws — a non-array grants claim, a\n// non-object grant, or a missing `scope` simply confers nothing.\nfunction hasGrantScopeBypass(claims: JwtClaims | null, options: GrantScopeAccessOptions): boolean {\n const bypass = options.bypass;\n if (!bypass) {\n return false;\n }\n\n const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));\n if (!Array.isArray(grants)) {\n return false;\n }\n\n const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;\n const roleValues = new Set(bypass.roleValues);\n\n for (const grant of grants) {\n if (typeof grant !== \"object\" || grant === null) {\n continue;\n }\n const record = grant as Record<string, unknown>;\n if (!roleValues.has(String(record[\"role\"]))) {\n continue;\n }\n const scope = record[\"scope\"];\n if (typeof scope !== \"object\" || scope === null) {\n continue;\n }\n if ((scope as Record<string, unknown>)[\"kind\"] === scopeKind) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * The caller's grant-scope standing, resolved from the JWT grants — the JS mirror of the whole policy\n * predicate, both branches: `ids` is {@link resolveGrantScopeIds} (the scope-set subquery) and `bypass`\n * mirrors the policy's OR `exists (…)` branch. One declaration, two enforcement surfaces: pass the SAME\n * options object you gave {@link buildSupabaseGrantScopeNativePolicies} and a bypass grant cannot be\n * enforced on writes yet invisible on reads.\n *\n * Never throws on malformed claims (they reach a `customWhere` unverified in shape) — a wrong shape\n * simply confers nothing. A malformed `grantsClaimPath`/`scopeIdField` **option** is still a loud error.\n */\nexport function resolveGrantScopeAccess(claims: JwtClaims | null, options: GrantScopeAccessOptions): GrantScopeAccess {\n return {\n bypass: hasGrantScopeBypass(claims, options),\n ids: resolveGrantScopeIds(claims, options),\n };\n}\n\n/**\n * The Electric shape `where` for a grant-scope table, bypass included — the read counterpart of the\n * `select` policy in {@link buildSupabaseGrantScopeNativePolicies}, from the same declaration. A caller\n * holding a bypass grant gets `null` (no filter, every row — the policy's OR branch); anyone else gets\n * {@link buildGrantScopeShapeWhere} over their resolved ids, i.e. the {@link DENY_ALL} sentinel *by\n * reference* when the set is empty (which is what lets a `customWhere` built on this probe as\n * claims-dependent). Use {@link buildGrantScopeShapeWhere} directly only when there is no bypass to mirror.\n */\nexport function buildGrantScopeAccessShapeWhere(\n scopeColumn: AnyColumn,\n claims: JwtClaims | null,\n options: GrantScopeAccessOptions,\n): SQL | null {\n const access = resolveGrantScopeAccess(claims, options);\n return access.bypass ? null : buildGrantScopeShapeWhere(scopeColumn, access.ids);\n}\n"
22
+ "import { and, eq, getTableName, or, sql, type AnyColumn, type SQL } from \"drizzle-orm\";\nimport { PgDialect, pgPolicy, type AnyPgTable, type PgRole } from \"drizzle-orm/pg-core\";\n\nimport { buildOwnershipShapePredicate, DENY_ALL_PREDICATE, type JwtClaims } from \"./config\";\nimport { p, type Predicate } from \"./predicate\";\n\n// Render a typed fragment to inline-literal SQL text (CREATE POLICY DDL cannot carry `$n` binds).\n// The tier-② discipline for the text builders below: values enter as typed `${value}` interpolations\n// and drizzle owns the escaping; only the claim-extraction leaves stay raw text.\nconst textDialect = new PgDialect();\nfunction renderInlineSql(fragment: SQL): string {\n return textDialect.sqlToQuery(fragment.inlineParams()).sql;\n}\n\n// Walk a dotted claim path defensively (unverified claims may be any shape): anything that is not a\n// plain object on the way down yields `undefined` rather than throwing. Shared by every read-path\n// predicate mirror below — each family's mirror sits beside its own policies and reads exactly the\n// claim the policy's SQL reads.\nfunction readClaimsPath(claims: JwtClaims | null, path: string[]): unknown {\n let current: unknown = claims;\n for (const segment of path) {\n if (typeof current !== \"object\" || current === null || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n// The JWT subject as the read path sees it: a non-empty `sub` string, else null (no subject → the\n// mirrors deny). The RLS counterpart is `buildSubjectSqlText`, which reads the same claim in Postgres.\nfunction readSubjectClaim(claims: JwtClaims | null): string | null {\n const subject = readClaimsPath(claims, [\"sub\"]);\n return typeof subject === \"string\" && subject.length > 0 ? subject : null;\n}\n\ntype SupabaseOwnerOrAdminPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\ntype SupabaseOwnerOrAdminPolicyShape = {\n command: SupabaseOwnerOrAdminPolicyKind;\n using: boolean;\n withCheck: boolean;\n};\n\n// Options for the raw predicate *text* builder (`buildSupabaseOwnerOrAdminPredicateSqlText`) — the\n// documented escape hatch that returns the predicate as a SQL string (for a hand-written trigger or\n// migration). It takes a column *name* because text has no column object. The native policy builder\n// below takes a real Drizzle column instead.\nexport type SupabaseOwnerOrAdminPredicateOptions = {\n ownerSqlColumn?: string;\n adminRoleName?: string;\n subjectCastType?: string;\n /** Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}. */\n adminRolesClaimPath?: readonly string[];\n};\n\nexport type SupabaseOwnerOrAdminNativePoliciesOptions = {\n /** Owner column on the governed row (e.g. `authors.ownerId`). The governed table name is derived from it. */\n ownerColumn: AnyColumn;\n role: PgRole;\n /** Role value (in `app_metadata.roles`) that bypasses ownership (default \"admin\"). */\n adminRoleName?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n /**\n * Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}; pass the SAME value to\n * {@link resolveOwnerOrAdminAccess} / {@link buildOwnerOrAdminShapePredicate} so both surfaces read one claim.\n */\n adminRolesClaimPath?: readonly string[];\n};\n\nconst defaultOwnerSqlColumn = \"owner_id\";\nconst defaultOwnerPropertyKey = \"ownerId\";\nconst defaultAuthenticatedRoleName = \"authenticated\";\nconst defaultAdminRoleName = \"admin\";\nconst defaultSubjectCastType = \"uuid\";\n// The DEFAULT claim path the admin check reads — the single source for BOTH surfaces: the SQL `EXISTS`\n// in `buildAdminRoleExistsSqlText` renders its `-> 'seg'` chain from this array, and the read-path mirror\n// (`resolveOwnerOrAdminAccess`) walks the same segments in JS. Overridable per call via\n// `adminRolesClaimPath` on either surface — pass the same value to both or they drift.\nconst adminRolesClaimPath = [\"app_metadata\", \"roles\"] as const;\n\nconst ownerOrAdminPolicyShapes: SupabaseOwnerOrAdminPolicyShape[] = [\n {\n command: \"select\",\n using: true,\n withCheck: false,\n },\n {\n command: \"insert\",\n using: false,\n withCheck: true,\n },\n {\n command: \"update\",\n using: true,\n withCheck: true,\n },\n {\n command: \"delete\",\n using: true,\n withCheck: false,\n },\n];\n\nfunction assertIdentifier(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL identifier: ${value}`);\n }\n}\n\nfunction assertTypeName(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\\s+[A-Za-z_][A-Za-z0-9_]*)*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL type name: ${value}`);\n }\n}\n\nfunction buildOwnerOrAdminPolicyName(tableName: string, command: SupabaseOwnerOrAdminPolicyKind) {\n return `${tableName}_${command}_owner_or_admin`;\n}\n\n// ---------------------------------------------------------------------------\n// Shared predicate leaves (used by both policy families). RLS is the *write* path\n// (Postgres), so these render to SQL text with columns qualified — unlike the read-path\n// mirrors, which carry the column objects themselves in a predicate AST and render no SQL\n// at all. The only bits that stay raw `sql` are genuinely-Postgres\n// expressions with no Drizzle operator: the JWT-subject `(select current_setting(...)::type)`\n// and the admin-roles `EXISTS`. Literal values use `eq(col, value).inlineParams()` so the\n// value is inlined into the DDL — a bare `$n` is something `CREATE POLICY` cannot carry.\n// ---------------------------------------------------------------------------\n\n// The governed table name (for policy identifiers) derived from a built Drizzle column, so renaming\n// the table renames its policies. Columns built inside `defineSyncTable`'s `extras` callback carry\n// their `.table` — which is where these builders are meant to be called (the table object does not\n// yet exist when its own `policies:` array would be built).\nfunction tableNameForColumn(column: AnyColumn, label: string): string {\n const table = (column as { table?: AnyPgTable }).table;\n if (!table) {\n throw new Error(\n `${label} must be a built Drizzle column carrying its table — call this builder inside defineSyncTable's \\`extras\\` callback`,\n );\n }\n return getTableName(table);\n}\n\n// The JWT subject as a Postgres expression (irreducibly raw: `current_setting` + cast). Used as the\n// right-hand side of `eq(ownerColumn, subject)` — eq splices an SQL fragment verbatim (no bound\n// param), so the DDL carries the literal expression, not a `$n` CREATE POLICY cannot bind. Wrapped in\n// a scalar subquery — the Supabase RLS performance idiom: the stable `current_setting` expression is\n// evaluated once per statement (InitPlan), not once per row.\nfunction buildSubjectSql(subjectCastType: string): SQL {\n assertTypeName(subjectCastType, \"subjectCastType\");\n return sql.raw(`(select ${buildSubjectSqlText(subjectCastType)})`);\n}\n\nfunction buildSubjectSqlText(subjectCastType: string): string {\n return `coalesce(\n nullif(current_setting('request.jwt.claim.sub', true), ''),\n (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')\n )::${subjectCastType}`;\n}\n\n// The claim path the admin check walks, validated as plain identifiers (they are emitted into policy\n// DDL). Mirrors `resolveGrantsClaimPath` in the grant-scope family below.\nfunction resolveAdminRolesClaimPath(path: readonly string[] | undefined): string[] {\n const segments = path && path.length > 0 ? [...path] : [...adminRolesClaimPath];\n for (const segment of segments) {\n assertIdentifier(segment, \"adminRolesClaimPath segment\");\n }\n return segments;\n}\n\n// The claim path as a jsonb `-> 'seg'` chain, one typed interpolation per segment (drizzle owns the\n// quoting), so the SQL walks the SAME array the JS mirror walks — textual agreement is not enough.\nfunction buildClaimPathChainSql(path: string[]): SQL {\n return sql.join(\n path.map((segment) => sql` -> ${segment}`),\n sql``,\n );\n}\n\n// An extracted claim as an ARRAY or nothing at all — the SQL twin of the mirrors' \"an unverified claim\n// of the wrong shape confers nothing\". Absent/null already yields `[]`; the load-bearing case is a\n// claim that is PRESENT but not an array (a token hook emitting `roles: \"admin\"` instead of\n// `[\"admin\"]`), which would otherwise reach `jsonb_array_elements(_text)` and raise \"cannot extract\n// elements from a scalar/object\" — turning every governed write into an RLS execution ERROR instead of\n// a clean deny. Wrapped here, a non-array claim behaves exactly like an absent one, so the policy\n// reaches the same verdict as `resolveOwnerOrAdminAccess` / `resolveGrantScopeAccess`.\n// The expression is repeated (Postgres has nowhere to bind it inside a policy predicate); it is a\n// stable per-statement expression, so the planner evaluates it once, not per row.\nfunction buildClaimArraySqlText(claimSqlText: string): string {\n return `case jsonb_typeof(${claimSqlText}) when 'array' then ${claimSqlText} else '[]'::jsonb end`;\n}\n\n// The admin-bypass test: the roles array at `adminRolesClaimPath` (from the JWT claims) contains\n// `adminRoleName`. No column reference and no recursion risk, so it is inlined as text (shared by the\n// text builder and the native builder). The role value and the claim-path segments enter as typed\n// interpolations (drizzle owns the escaping); the claim-extraction body is the allowed raw leaf, and it\n// goes through {@link buildClaimArraySqlText} so a malformed `roles` denies instead of erroring.\nfunction buildAdminRoleExistsSqlText(adminRoleName: string, claimPath: string[]): string {\n const rolesClaim = renderInlineSql(sql`(\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb${buildClaimPathChainSql(claimPath)}\n )`);\n\n return renderInlineSql(sql`EXISTS (\n SELECT 1\n FROM jsonb_array_elements_text(\n ${sql.raw(buildClaimArraySqlText(rolesClaim))}\n ) AS assigned_role(role_name_value)\n WHERE assigned_role.role_name_value = ${adminRoleName}\n )`);\n}\n\nfunction normalizePredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions = {}) {\n const ownerSqlColumn = options.ownerSqlColumn ?? defaultOwnerSqlColumn;\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subjectCastType = options.subjectCastType ?? defaultSubjectCastType;\n\n assertIdentifier(ownerSqlColumn, \"ownerSqlColumn\");\n assertTypeName(subjectCastType, \"subjectCastType\");\n\n return {\n ownerSqlColumn,\n adminRoleName,\n subjectCastType,\n claimPath: resolveAdminRolesClaimPath(options.adminRolesClaimPath),\n };\n}\n\n/**\n * The owner-or-admin predicate as raw SQL **text** — the escape hatch for when you need the predicate\n * as a string (a hand-written trigger, a manual migration). For attaching RLS to a Drizzle table,\n * prefer `buildSupabaseOwnerOrAdminNativePolicies`, which takes the real column and is rename-tracked.\n */\nexport function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwnerOrAdminPredicateOptions = {}): string {\n const normalized = normalizePredicateOptions(options);\n\n return `\n ${normalized.ownerSqlColumn} = ${buildSubjectSqlText(normalized.subjectCastType)}\n OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName, normalized.claimPath)}\n`;\n}\n\n// owner-or-admin predicate built from the real Drizzle column: `eq(ownerColumn, subject)` (qualified,\n// rename-tracked) OR the raw admin-roles EXISTS (no column, no Drizzle operator). The single boolean\n// is `or(...)`.\nexport function buildSupabaseOwnerOrAdminNativePolicies(options: SupabaseOwnerOrAdminNativePoliciesOptions) {\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);\n const adminExists = sql.raw(\n buildAdminRoleExistsSqlText(adminRoleName, resolveAdminRolesClaimPath(options.adminRolesClaimPath)),\n );\n const predicate = or(eq(options.ownerColumn, subject), adminExists)!;\n const tableName = tableNameForColumn(options.ownerColumn, \"ownerColumn\");\n\n return ownerOrAdminPolicyShapes.map((shape) =>\n pgPolicy(buildOwnerOrAdminPolicyName(tableName, shape.command), {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\nexport const supabaseOwnerOrAdminDefaults = {\n ownerSqlColumn: defaultOwnerSqlColumn,\n ownerPropertyKey: defaultOwnerPropertyKey,\n authenticatedRoleName: defaultAuthenticatedRoleName,\n adminRoleName: defaultAdminRoleName,\n subjectCastType: defaultSubjectCastType,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Read-path mirror of the owner-or-admin policies. The read path never runs RLS, so the control plane\n// has to reach the same verdict in JS, from the same claims: the policy's `OR` admin branch becomes \"no\n// filter at all\" (every row streams), and its owner branch becomes the ownership shape predicate. One\n// declaration — the owner column plus the admin role name — two enforcement surfaces, so a row can\n// never be writable-but-unreadable (or the reverse).\n//\n// SELECT only, by construction: a shape predicate filters a read stream, so it mirrors the `select`\n// policy. INSERT/UPDATE/DELETE remain the policies' business.\n// ---------------------------------------------------------------------------\n\n/**\n * Claim-reading options for the read mirror; every field must match the value the policies were built\n * with, or the two surfaces stop agreeing.\n */\nexport type OwnerOrAdminAccessOptions = {\n /** Role value (in `app_metadata.roles`) that bypasses ownership (default \"admin\"). */\n adminRoleName?: string;\n /** Path to the roles array in the claims. Defaults to {@link adminRolesClaimPath}. */\n adminRolesClaimPath?: readonly string[];\n};\n\n/** The caller's standing on an owner-or-admin table, as resolved from the claims. */\nexport type OwnerOrAdminAccess = {\n /** The caller holds the admin role — the policy's bypass branch; every row is visible. */\n admin: boolean;\n /** The JWT subject when it is a non-empty string, else null (no subject → nothing is visible). */\n subject: string | null;\n};\n\n/**\n * The caller's owner-or-admin standing, resolved from the JWT claims — the JS mirror of the policy's\n * admin `EXISTS` and its subject comparison. `admin` is true when the roles array at\n * `adminRolesClaimPath` (`app_metadata.roles` by default — the very array\n * {@link buildSupabaseOwnerOrAdminNativePolicies} renders its `-> 'seg'` chain from, so the two surfaces\n * read one declaration) contains `adminRoleName`; `subject` is the `sub` claim when it is a non-empty\n * string, else null.\n *\n * Claims arrive unverified in shape, so this never throws: a missing/non-object claims bag, a\n * non-array `roles`, or non-string members simply confer nothing.\n */\nexport function resolveOwnerOrAdminAccess(\n claims: JwtClaims | null,\n options: OwnerOrAdminAccessOptions = {},\n): OwnerOrAdminAccess {\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const roles = readClaimsPath(claims, resolveAdminRolesClaimPath(options.adminRolesClaimPath));\n const admin = Array.isArray(roles) && roles.some((role) => typeof role === \"string\" && role === adminRoleName);\n\n return { admin, subject: readSubjectClaim(claims) };\n}\n\n/**\n * The owner-or-admin **predicate** — the native-path counterpart to\n * the owner-or-admin `select` policy, from the same declaration. An admin gets `null` (no filter,\n * every row — the policy's bypass branch); anyone else gets {@link buildOwnershipShapePredicate}.\n */\nexport function buildOwnerOrAdminShapePredicate(\n ownerColumn: AnyColumn,\n claims: JwtClaims | null,\n options: OwnerOrAdminAccessOptions = {},\n): Predicate | null {\n const access = resolveOwnerOrAdminAccess(claims, options);\n return access.admin ? null : buildOwnershipShapePredicate(ownerColumn, access.subject);\n}\n\n// ---------------------------------------------------------------------------\n// Membership-scoped policies (generic). A row belongs to a *container* and is\n// visible/writable through membership of that container — not just ownership.\n// This is the readwrite counterpart to a membership row-filter: every member of\n// the container may read the row (fan-out to non-owners); only the owner may\n// create it (as themselves) and edit it, while a container *manager* may moderate\n// any row. Domain-agnostic: the container, membership table, and manager role are\n// all parameters.\n//\n// The container, membership, and owner references are **real Drizzle columns/tables**\n// (not name strings), so the policy tracks the schema — a column or table rename is a\n// compile error, and the governed table name is *derived* from the container column\n// (no redundant `tableName` to drift). Predicate structure is built with Drizzle\n// operators (`and`/`or`/`eq`, with `.inlineParams()` on the `'manager'` / `false` literals so\n// they inline instead of becoming a `$n` CREATE POLICY cannot carry); only the irreducibly-Postgres\n// leaves stay `sql`: the `IN (subquery)` containment (Drizzle's `inArray` cannot wrap a raw subquery)\n// and the `(select current_setting(...)::type)` JWT-subject expression (wrapped in a scalar subquery —\n// the Supabase per-statement-eval RLS perf idiom). Columns serialize qualified\n// (`\"work_items\".\"workspace_id\"`) — fine for Postgres RLS, which is the write path; the read mirror\n// builds a predicate AST from the same column objects and serializes no SQL at all.\n//\n// The `select` half of this family is mirrored on the read path by\n// {@link buildMembershipShapePredicate}, built from the same column declarations — the sync engine cannot\n// read RLS, so the two surfaces are generated from one declaration and must agree.\n// ---------------------------------------------------------------------------\n\ntype MembershipPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nexport type SupabaseMembershipPredicateColumns = {\n /** Column on the governed row naming its container (e.g. `workItems.workspaceId`). */\n containerColumn: AnyColumn;\n /** Membership link table (e.g. the `workspace_members` table). */\n membershipTable: AnyPgTable;\n /** Container column on the membership link table (e.g. `workspaceMembers.workspaceId`). */\n membershipContainerColumn: AnyColumn;\n /** Subject (member) column on the membership link table, compared to the JWT sub. */\n membershipSubjectColumn: AnyColumn;\n /** Owner column on the governed row (e.g. `workItems.ownerId`). */\n ownerColumn: AnyColumn;\n /** Optional role column on the membership link enabling manager moderation. */\n managerRoleColumn?: AnyColumn;\n /** Role value that grants moderation (default \"manager\"); only used with managerRoleColumn. */\n managerRoleValue?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n};\n\n// Optional write-state gate (generic). When supplied, INSERT and UPDATE are additionally gated on\n// mutable state: a *locked* container admits writes only from a manager (e.g. a frozen discussion\n// thread), and a *muted* member may not write at all. SELECT and DELETE are unaffected — reads and\n// moderation deletes still flow. Domain-agnostic: the container/lock and membership/mute columns are\n// parameters. Requires managerRoleColumn (managers bypass the lock).\nexport type SupabaseMembershipWriteGateColumns = {\n /** Container table holding the lock flag (e.g. the `workspaces` table). */\n containerTable: AnyPgTable;\n /** PK column on the container table the governed row's container column references (e.g. `workspaces.id`). */\n containerPkColumn: AnyColumn;\n /** Boolean column on the container table; when true, only a manager may write (e.g. `workspaces.locked`). */\n containerLockColumn: AnyColumn;\n /** Boolean column on the membership table; when true, that member may not write (e.g. `workspaceMembers.muted`). */\n membershipMutedColumn: AnyColumn;\n};\n\nexport type SupabaseMembershipNativePoliciesOptions = SupabaseMembershipPredicateColumns & {\n role: PgRole;\n /** Optional write-state gate applied to INSERT and UPDATE only. */\n writeGate?: SupabaseMembershipWriteGateColumns;\n};\n\nconst defaultManagerRoleValue = \"manager\";\n\nconst membershipPolicyShapes: { command: MembershipPolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\ntype NormalizedMembershipColumns = SupabaseMembershipPredicateColumns & {\n managerRoleValue: string;\n subjectCastType: string;\n};\n\nfunction normalizeMembershipColumns(options: SupabaseMembershipPredicateColumns): NormalizedMembershipColumns {\n return {\n ...options,\n managerRoleValue: options.managerRoleValue ?? defaultManagerRoleValue,\n subjectCastType: options.subjectCastType ?? defaultSubjectCastType,\n };\n}\n\n// Containment form (not a correlated EXISTS): the governed row's container column must be in the set\n// of containers the subject belongs to. Two reasons it is `= ANY(ARRAY(subquery))` and not\n// `IN (subquery)`, both load-bearing:\n// 1. Correctness — the subquery stays uncorrelated (its `WHERE` references only the subject), so the\n// membership table's same-named column can't shadow the outer container column. A correlated\n// `EXISTS (… WHERE m.container = container …)` would collapse the correlation.\n// 2. Performance — for a runtime-resolved set (the subject comes from `current_setting`, opaque to\n// the planner) `IN (subquery)` is costed as a hashed semi-join → **sequential scan** of the\n// governed table; `= ANY(ARRAY(subquery))` materializes the set once (InitPlan) and the\n// ScalarArrayOp drives a **bitmap index scan**. At scale that is ~25-45× faster (the rls-read\n// perf track proves it). `inArray` can't wrap a raw subquery, so this stays `sql`.\nfunction membershipMatch(cols: NormalizedMembershipColumns, subject: SQL, requireManager: boolean): SQL {\n const subjectIsMember = eq(cols.membershipSubjectColumn, subject);\n const where =\n requireManager && cols.managerRoleColumn\n ? and(subjectIsMember, eq(cols.managerRoleColumn, cols.managerRoleValue).inlineParams())!\n : subjectIsMember;\n\n return sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${where}))`;\n}\n\n/** owner-or-manager predicate (edit / moderate). */\nfunction ownerOrManager(cols: NormalizedMembershipColumns, subject: SQL): SQL {\n const owner = eq(cols.ownerColumn, subject);\n return cols.managerRoleColumn ? or(owner, membershipMatch(cols, subject, true))! : owner;\n}\n\n// write-state gate: ((container not locked) OR caller is a manager) AND caller's membership not muted.\n// Same `= ANY(ARRAY(subquery))` containment discipline as membershipMatch (uncorrelated set, index-scan\n// friendly), so the container/membership tables can reuse their own column names without shadowing the\n// governed row's container column.\nfunction membershipWriteGate(\n cols: NormalizedMembershipColumns,\n gate: SupabaseMembershipWriteGateColumns,\n subject: SQL,\n): SQL {\n const unlocked = sql`${cols.containerColumn} = any(array(select ${gate.containerPkColumn} from ${gate.containerTable} where ${eq(gate.containerLockColumn, false).inlineParams()}))`;\n const notMuted = sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${and(eq(cols.membershipSubjectColumn, subject), eq(gate.membershipMutedColumn, false).inlineParams())}))`;\n return and(or(unlocked, membershipMatch(cols, subject, true))!, notMuted)!;\n}\n\nexport function buildSupabaseMembershipNativePolicies(options: SupabaseMembershipNativePoliciesOptions) {\n const cols = normalizeMembershipColumns(options);\n const subject = buildSubjectSql(cols.subjectCastType);\n const tableName = tableNameForColumn(cols.containerColumn, \"containerColumn\");\n\n const memberPredicate = membershipMatch(cols, subject, false);\n const ownerAndMember = and(eq(cols.ownerColumn, subject), memberPredicate)!;\n const ownerOrManagerPredicate = ownerOrManager(cols, subject);\n\n let writeGateClause: SQL | null = null;\n if (options.writeGate) {\n if (!cols.managerRoleColumn) {\n throw new Error(\"writeGate requires managerRoleColumn so a manager can write into a locked container\");\n }\n writeGateClause = membershipWriteGate(cols, options.writeGate, subject);\n }\n\n const gatedForWrite = (base: SQL): SQL => (writeGateClause ? and(base, writeGateClause)! : base);\n\n const predicateFor = (command: MembershipPolicyKind): SQL => {\n switch (command) {\n case \"select\":\n return memberPredicate;\n case \"insert\":\n return gatedForWrite(ownerAndMember);\n case \"update\":\n return gatedForWrite(ownerOrManagerPredicate);\n case \"delete\":\n return ownerOrManagerPredicate;\n }\n };\n\n return membershipPolicyShapes.map((shape) => {\n const predicate = predicateFor(shape.command);\n\n return pgPolicy(`${tableName}_${shape.command}_membership`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n });\n });\n}\n\n// ---------------------------------------------------------------------------\n// Read-path mirror of the membership policies. The read path never runs RLS, so the control plane must\n// re-derive the same visible set in the shape predicate, from the SAME Drizzle columns the policies were\n// built from — one declaration, two enforcement surfaces, so a row can never be readable-but-unwritable\n// (or the reverse) through a rename or a typo.\n//\n// SELECT only, by construction: the mirror reproduces the family's `select` predicate — plain\n// membership of the container. The owner/manager branches and the write-state gate are WRITE-side\n// concerns (INSERT/UPDATE/DELETE) and are deliberately absent here; a shape predicate filters a read\n// stream and has nothing to gate.\n//\n// The two surfaces express the SAME containment differently, on purpose:\n// - RLS (`membershipMatch`) renders `= ANY(ARRAY(select …))` — the InitPlan/bitmap-index-scan\n// discipline Postgres needs for a runtime-resolved set (see that function's comment).\n// - The mirror emits `p.in(col, p.subquery(…))` — an AST node the engine plans itself. There is no\n// Postgres planner on this side to appease, and no SQL text for anything to lex.\n// Same columns, two forms — that is exactly what the mirror is for.\n// ---------------------------------------------------------------------------\n\n/**\n * The columns {@link buildMembershipShapePredicate} needs: the SELECT-relevant subset of\n * {@link SupabaseMembershipPredicateColumns}. The write-only fields (owner, manager role, subject cast,\n * write gate, policy role) are accepted but ignored, so the **same declaration object** you hand to\n * {@link buildSupabaseMembershipNativePolicies} can be handed to the read mirror verbatim.\n */\nexport type SupabaseMembershipShapeColumns = Pick<\n SupabaseMembershipPredicateColumns,\n \"containerColumn\" | \"membershipTable\" | \"membershipContainerColumn\" | \"membershipSubjectColumn\"\n> &\n Partial<SupabaseMembershipNativePoliciesOptions>;\n\n/**\n * The membership **predicate** — the read-path mirror of the membership `select` policy, from the\n * same column declarations.\n *\n * The containment becomes a first-class {@link InSubqueryPredicate} rather than SQL text, which buys\n * something the text form could not: the engine maintains the inner set incrementally and **shares it\n * across every shape referencing the same subquery**, so an entitlement-shaped membership costs one\n * index rather than one per shape. The subquery is uncorrelated, as the engine requires — the inner\n * `where` reads the membership table's own columns only.\n */\nexport function buildMembershipShapePredicate(\n columns: SupabaseMembershipShapeColumns,\n claims: JwtClaims | null,\n): Predicate {\n const subject = readSubjectClaim(claims);\n if (subject === null) {\n return DENY_ALL_PREDICATE;\n }\n\n return p.in(\n columns.containerColumn,\n p.subquery(columns.membershipContainerColumn, p.eq(columns.membershipSubjectColumn, subject)),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Grant-scope policies (generic). Authorization is carried IN THE JWT, not a DB\n// table: `app_metadata.authorization.grants` is an array of\n// `{ role, scope: { kind, <kind>Id } }` minted into the token. A row is visible\n// when its scope column (e.g. `offering_id`) appears among the caller's grants for\n// one of the accepting roles. Because the grant set lives in the token, the\n// predicate needs NO join — it parses the claims jsonb and tests set membership.\n//\n// Two forms, deliberately:\n// - default (InitPlan-correct): an **uncorrelated** `scope_col IN (SELECT …\n// jsonb_array_elements(claims) …)`. The subquery never references the outer row,\n// so the planner hoists it to an InitPlan and the JWT is parsed **once per\n// statement**.\n// - `naive: true` (the cliff): a **correlated** `EXISTS (… WHERE (g->…->>id) =\n// scope_col)`. Referencing the outer row forces per-row re-evaluation — the JWT\n// is re-parsed for **every row scanned**. It exists only to demonstrate and\n// regression-guard the InitPlan discipline (see the `rls-read-load` perf track);\n// never ship it.\n//\n// The same grant set is mirrored on the read path by {@link resolveGrantScopeAccess} (or\n// {@link resolveGrantScopeIds} for the id set alone) + {@link buildGrantScopeShapePredicate}: the control\n// plane resolves the ids from the claims in JS and compiles them into the shape's predicate — the sync\n// engine cannot read RLS, so the two surfaces are generated from one declaration and must agree.\n// ---------------------------------------------------------------------------\n\ntype GrantScopePolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nconst defaultGrantsClaimPath = [\"app_metadata\", \"authorization\", \"grants\"] as const;\nconst defaultGrantScopeCastType = \"uuid\";\n// Scope kind a bypass grant must carry, on BOTH surfaces: the policy's `buildBypassExistsSqlText`\n// inlines it and the read mirror's `resolveGrantScopeAccess` compares against it.\nconst defaultBypassScopeKind = \"platform\";\n\n/**\n * An unconditional bypass declaration: any grant whose `role` ∈ `roleValues` and whose `scope.kind` =\n * `scopeKind` (default `\"platform\"`) confers access to every row — e.g. a platform-scoped\n * `platform_admin`. Hand the SAME object to the policy builder and to\n * {@link resolveGrantScopeAccess} / {@link buildGrantScopeAccessShapePredicate}.\n */\nexport type GrantScopeBypassOptions = {\n roleValues: string[];\n scopeKind?: string;\n};\n\nexport type GrantScopeClaimOptions = {\n /** Value matched against each grant's `scope.kind` (e.g. \"offering\"). */\n scopeKind: string;\n /** Grant `role` values that confer access (e.g. [\"teacher\", \"assistant\"]). */\n roleValues: string[];\n /** Field within `scope` holding the id (e.g. \"offeringId\"). Defaults to `${scopeKind}Id`. */\n scopeIdField?: string;\n /** Path to the grants array in the claims. Defaults to `app_metadata.authorization.grants`. */\n grantsClaimPath?: string[];\n};\n\nexport type SupabaseGrantScopePredicateColumns = GrantScopeClaimOptions & {\n /** Column on the governed row naming its scope (e.g. `offerings.id` reference column). Table name is derived from it. */\n scopeColumn: AnyColumn;\n /** SQL type the extracted grant id is cast to before comparison (default \"uuid\"). */\n scopeCastType?: string;\n /**\n * Optional unconditional bypass ({@link GrantScopeBypassOptions}): any grant whose `role` ∈\n * `bypass.roleValues` and whose `scope.kind` = `bypass.scopeKind` (default \"platform\") grants all\n * rows — e.g. a platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it\n * stays InitPlan-hoisted in both the correct and naive forms. Its read-path twin is\n * {@link buildGrantScopeAccessShapePredicate} (bypass → `null`, i.e. no shape filter at all).\n */\n bypass?: GrantScopeBypassOptions;\n};\n\nexport type SupabaseGrantScopeNativePoliciesOptions = SupabaseGrantScopePredicateColumns & {\n role: PgRole;\n /** Emit the deliberately-naive per-row correlated form (cliff demo / regression guard only). */\n naive?: boolean;\n};\n\nconst grantScopePolicyShapes: { command: GrantScopePolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\nfunction resolveGrantsClaimPath(path: readonly string[] | undefined): string[] {\n const segments = path && path.length > 0 ? [...path] : [...defaultGrantsClaimPath];\n for (const segment of segments) {\n assertIdentifier(segment, \"grantsClaimPath segment\");\n }\n return segments;\n}\n\n// The grants array as a Postgres jsonb expression, guarded by {@link buildClaimArraySqlText} so\n// `jsonb_array_elements` never errors: an absent, null, OR non-array grants claim all yield `[]`, i.e.\n// no grants — the same \"confers nothing\" verdict `resolveGrantScopeAccess` reaches in JS. Shared by the\n// scope predicate (both forms) and the bypass EXISTS. `#>` takes a text[] path; the segments are\n// validated identifiers, so the `'{…}'` path literal is injection-safe.\nfunction buildGrantsArraySqlText(path: string[]): string {\n return buildClaimArraySqlText(`(\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb #> '{${path.join(\",\")}}'\n )`);\n}\n\nfunction buildRoleInListSqlText(roleValues: string[]): string {\n if (roleValues.length === 0) {\n throw new Error(\"grant-scope policy requires at least one role value\");\n }\n return renderInlineSql(\n sql.join(\n roleValues.map((role) => sql`${role}`),\n sql`, `,\n ),\n );\n}\n\nfunction resolveGrantScopeIdField(options: GrantScopeClaimOptions): string {\n const field = options.scopeIdField ?? `${options.scopeKind}Id`;\n assertIdentifier(field, \"scopeIdField\");\n return field;\n}\n\n// Uncorrelated bypass test (never references the governed row), so it is InitPlan-hoisted in both forms.\nfunction buildBypassExistsSqlText(bypass: GrantScopeBypassOptions, grantsText: string): string {\n const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;\n return `exists (\n select 1\n from jsonb_array_elements(${grantsText}) as bypass_grant\n where bypass_grant -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)}\n and bypass_grant ->> 'role' in (${buildRoleInListSqlText(bypass.roleValues)})\n )`;\n}\n\nfunction buildGrantScopePredicate(options: SupabaseGrantScopeNativePoliciesOptions): SQL {\n const scopeKind = options.scopeKind;\n assertIdentifier(scopeKind, \"scopeKind\");\n const scopeIdField = resolveGrantScopeIdField(options);\n const castType = options.scopeCastType ?? defaultGrantScopeCastType;\n assertTypeName(castType, \"scopeCastType\");\n const grantsText = buildGrantsArraySqlText(resolveGrantsClaimPath(options.grantsClaimPath));\n const roleIn = buildRoleInListSqlText(options.roleValues);\n const kindMatch = `grant_elem -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)} and grant_elem ->> 'role' in (${roleIn})`;\n const idExpr = `(grant_elem -> 'scope' ->> ${renderInlineSql(sql`${scopeIdField}`)})::${castType}`;\n\n // Correct: uncorrelated `= ANY(ARRAY(select …))` → the grant set materializes once (InitPlan, JWT\n // parsed once) and the ScalarArrayOp drives a bitmap index scan on the scope column — ~25-45× faster\n // at scale than `IN (select …)`, which the planner costs as a hashed semi-join → sequential scan (the\n // rls-read perf track proves both). Naive: correlated `EXISTS` referencing the governed scope column →\n // re-evaluated per row (JWT parsed per row). The column object is spliced so it serializes qualified —\n // valid CREATE POLICY DDL on the write path.\n const base = options.naive\n ? sql`exists (select 1 from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)} and ${sql.raw(idExpr)} = ${options.scopeColumn})`\n : sql`${options.scopeColumn} = any(array(select ${sql.raw(idExpr)} from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)}))`;\n\n if (!options.bypass) {\n return base;\n }\n return or(base, sql.raw(buildBypassExistsSqlText(options.bypass, grantsText)))!;\n}\n\n/**\n * Native Drizzle RLS policies for a JWT-resident grant set (see the section comment). Pass the real\n * scope column; the governed table name is derived from it. By default the predicate is the\n * InitPlan-correct uncorrelated `IN (subquery)`; pass `naive: true` for the correlated cliff variant.\n */\nexport function buildSupabaseGrantScopeNativePolicies(options: SupabaseGrantScopeNativePoliciesOptions) {\n const predicate = buildGrantScopePredicate(options);\n const tableName = tableNameForColumn(options.scopeColumn, \"scopeColumn\");\n const suffix = options.naive ? \"grant_scope_naive\" : \"grant_scope\";\n\n return grantScopePolicyShapes.map((shape) =>\n pgPolicy(`${tableName}_${shape.command}_${suffix}`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Read-path mirror of the grant-scope policy. The read path never runs RLS, so the control plane must\n// resolve the same visible scope-id set from the claims in JS and emit it as a literal `in` predicate.\n// These helpers are the read-path counterpart to the policy above — one declaration,\n// two enforcement surfaces, derived from the same grant data so they cannot drift.\n//\n// The policy's OR bypass branch has a mirror too: {@link resolveGrantScopeAccess} reports it and\n// {@link buildGrantScopeAccessShapePredicate} turns it into `null` — no shape filter at all, every row\n// streams — exactly as the `exists (…)` OR-branch makes the scope test irrelevant on the write side.\n// Without it a bypass grant would be enforced on writes yet invisible on reads.\n// ---------------------------------------------------------------------------\n\n/**\n * The set of scope ids the caller can see, resolved from the JWT grants — the JS mirror of the\n * grant-scope RLS subquery. Returns a de-duplicated list (empty → no rows visible).\n */\nexport function resolveGrantScopeIds(claims: JwtClaims | null, options: GrantScopeClaimOptions): string[] {\n const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));\n if (!Array.isArray(grants)) {\n return [];\n }\n\n const scopeIdField = resolveGrantScopeIdField(options);\n const roleValues = new Set(options.roleValues);\n const ids = new Set<string>();\n\n for (const grant of grants) {\n if (typeof grant !== \"object\" || grant === null) {\n continue;\n }\n const record = grant as Record<string, unknown>;\n if (!roleValues.has(String(record[\"role\"]))) {\n continue;\n }\n const scope = record[\"scope\"];\n if (typeof scope !== \"object\" || scope === null) {\n continue;\n }\n const scopeRecord = scope as Record<string, unknown>;\n if (scopeRecord[\"kind\"] !== options.scopeKind) {\n continue;\n }\n const id = scopeRecord[scopeIdField];\n if (typeof id === \"string\" && id.length > 0) {\n ids.add(id);\n }\n }\n\n return [...ids];\n}\n\n/**\n * The grant-scope **predicate** — the read-path mirror of the grant-scope `select` policy.\n * An empty id set denies all rows ({@link DENY_ALL_PREDICATE}), mirroring the policy returning no rows.\n *\n * An `OR` of equalities, not an `IN`: the engine's `In` leaf takes a *subquery*, and a grant set lives\n * in the JWT rather than in a table, so there is nothing to select from. This is not a workaround —\n * `OR(=v…)` is exactly what the engine's own SQL parser desugars `IN (list)` to, so the two forms\n * compile to the same nodes.\n */\nexport function buildGrantScopeShapePredicate(scopeColumn: AnyColumn, ids: string[]): Predicate {\n if (ids.length === 0) {\n return DENY_ALL_PREDICATE;\n }\n const equalities = ids.map((id) => p.eq(scopeColumn, id));\n return equalities.length === 1 ? equalities[0]! : p.or(...equalities);\n}\n\n/** The full grant-scope declaration the read mirror needs: the claim options plus the optional bypass. */\nexport type GrantScopeAccessOptions = GrantScopeClaimOptions & {\n /** The same {@link GrantScopeBypassOptions} handed to {@link buildSupabaseGrantScopeNativePolicies}. */\n bypass?: GrantScopeBypassOptions;\n};\n\n/** The caller's standing on a grant-scope table, as resolved from the claims. */\nexport type GrantScopeAccess = {\n /** A bypass grant is present — the policy's OR branch; every row is visible. */\n bypass: boolean;\n /** The de-duplicated scope ids the caller can see (empty → no rows, absent a bypass). */\n ids: string[];\n};\n\n// The JS mirror of `buildBypassExistsSqlText`: a grant whose `role` is one of `bypass.roleValues` and\n// whose `scope.kind` is `bypass.scopeKind` (defaulting to the same `defaultBypassScopeKind` the SQL\n// inlines). Claims arrive unverified in shape, so nothing here throws — a non-array grants claim, a\n// non-object grant, or a missing `scope` simply confers nothing.\nfunction hasGrantScopeBypass(claims: JwtClaims | null, options: GrantScopeAccessOptions): boolean {\n const bypass = options.bypass;\n if (!bypass) {\n return false;\n }\n\n const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));\n if (!Array.isArray(grants)) {\n return false;\n }\n\n const scopeKind = bypass.scopeKind ?? defaultBypassScopeKind;\n const roleValues = new Set(bypass.roleValues);\n\n for (const grant of grants) {\n if (typeof grant !== \"object\" || grant === null) {\n continue;\n }\n const record = grant as Record<string, unknown>;\n if (!roleValues.has(String(record[\"role\"]))) {\n continue;\n }\n const scope = record[\"scope\"];\n if (typeof scope !== \"object\" || scope === null) {\n continue;\n }\n if ((scope as Record<string, unknown>)[\"kind\"] === scopeKind) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * The caller's grant-scope standing, resolved from the JWT grants — the JS mirror of the whole policy\n * predicate, both branches: `ids` is {@link resolveGrantScopeIds} (the scope-set subquery) and `bypass`\n * mirrors the policy's OR `exists (…)` branch. One declaration, two enforcement surfaces: pass the SAME\n * options object you gave {@link buildSupabaseGrantScopeNativePolicies} and a bypass grant cannot be\n * enforced on writes yet invisible on reads.\n *\n * Never throws on malformed claims (they reach a `customPredicate` unverified in shape) — a wrong shape\n * simply confers nothing. A malformed `grantsClaimPath`/`scopeIdField` **option** is still a loud error.\n */\nexport function resolveGrantScopeAccess(claims: JwtClaims | null, options: GrantScopeAccessOptions): GrantScopeAccess {\n return {\n bypass: hasGrantScopeBypass(claims, options),\n ids: resolveGrantScopeIds(claims, options),\n };\n}\n\n/**\n * The grant-scope **predicate**, bypass included — the native-path counterpart to\n * the grant-scope `select` policy, from the same declaration. A caller holding a bypass grant\n * gets `null` (no filter, every row); anyone else gets {@link buildGrantScopeShapePredicate} over\n * their resolved ids.\n */\nexport function buildGrantScopeAccessShapePredicate(\n scopeColumn: AnyColumn,\n claims: JwtClaims | null,\n options: GrantScopeAccessOptions,\n): Predicate | null {\n const access = resolveGrantScopeAccess(claims, options);\n return access.bypass ? null : buildGrantScopeShapePredicate(scopeColumn, access.ids);\n}\n"
21
23
  ],
22
- "mappings": ";;AA8CA,IAAM,uBAAuB,IAAI,IAAY;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,SAAS,iBAAiB,CAAC,SAAyB;AAAA,EAClD,OAAO,QACJ,QAAQ,SAAS,EAAE,EACnB,QAAQ,WAAW,EAAE,EACrB,QAAQ,QAAQ,GAAG,EACnB,KAAK,EACL,YAAY;AAAA;AAGjB,SAAS,UAAU,CAAC,QAAiC;AAAA,EACnD,IAAI,OAAO,SAAS;AAAA,IAClB,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