@pgxsinkit/contracts 0.1.51 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -2,20 +2,20 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/apply-strategy.ts", "../src/common.ts", "../src/config.ts", "../src/convergence-model.ts", "../src/registry.ts", "../src/sql-identifier.ts", "../src/fingerprint.ts", "../src/registry-diff.ts", "../src/mutation.ts", "../src/projection.ts", "../src/sql-defaults.ts", "../src/supabase-rls.ts"],
4
4
  "sourcesContent": [
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\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`, enums, `json`/`jsonb`, and arrays — those\n * route to the `json` tier (if json-representable) or the always-correct `insert` floor.\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 return !column.isArray && 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",
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. This is today's implicit behaviour, but now a\n * conscious, named choice rather than silent clobbering.\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; the union is additive so they slot in without a breaking\n * change.\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 * 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 * The non-parameterized inline `where` for a filter: the string a `customWhere` returns (the raw\n * escape hatch), or `null` when there is no filter or `customWhere` returns a Drizzle `SQL` fragment\n * (which is parameterized by {@link buildRowFilterShape}, not inlined here). Most callers want\n * `buildRowFilterShape` — this is the inline-string view it composes from.\n */\nexport function buildRowFilterWhere(\n filter: RowFilterSpec,\n claims: JwtClaims | null,\n params?: Record<string, unknown>,\n): string | null {\n const custom = filter.customWhere?.(claims ?? {}, params);\n return typeof custom === \"string\" && custom ? custom : null;\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",
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 * 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
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 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 isSubscriptionTiming,\n isWriteMode,\n RETENTIONS,\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 TableGovernanceSpec as TableGovernanceSpecBase,\n type TableMode,\n type WriteMode,\n} from \"./config\";\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 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, today's behaviour). 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`: either a static {@link RowFilterSpec}, or a\n * function of the table's built (typed) columns. The function form is the all-in-one way to author a\n * typed-Drizzle row filter inline — reference columns through `c(columns.x)` exactly as `extras`\n * does with its `self` argument, so `customWhere` builds parameterized Electric `where`s from real,\n * rename-safe column objects instead of hand-written column-name strings.\n */\nexport type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> =\n | RowFilterSpec\n | ((columns: PgBuildExtraConfigColumns<TColumns>) => RowFilterSpec);\n\n/** {@link ShapeSpecInput} whose `rowFilter` may also be a function of 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 * Primary key column names. Defaults to `[\"id\"]`.\n * Use an array with multiple entries for composite keys.\n */\n primaryKey?: 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\nexport const syncRegistrySchemaSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistrySchema\");\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\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\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>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], \"update\">>>\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 governance,\n clientProjection,\n serverProjection,\n shape,\n ...otherRest\n } = input;\n\n const resolvedMode: TableMode = mode ?? \"readonly\";\n const resolvedPrimaryKey: PrimaryKeySpec = { columns: primaryKey ?? [\"id\"] };\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\n ? (self: PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>) => [\n ...(policies ?? []),\n ...(extras ? extras(self) : []),\n ]\n : undefined;\n const table = schema ? schema.table(tableName, makeColumns(), extrasFn) : pgTable(tableName, makeColumns(), extrasFn);\n\n // A function-form `shape.rowFilter` is resolved here against the built (typed) columns, so an\n // all-in-one `defineSyncTable` can author a row filter with `c(columns.x)` Drizzle fragments — the\n // same typed columns `extras` receives — instead of hand-written column-name strings. A static\n // `RowFilterSpec` passes through unchanged.\n const resolvedRowFilter: RowFilterSpec | undefined =\n typeof shape?.rowFilter === \"function\"\n ? shape.rowFilter(getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>)\n : (shape?.rowFilter ?? undefined);\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 ...(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?: RowFilterSpec | ((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 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: RowFilterSpec | undefined =\n typeof opts.rowFilter === \"function\"\n ? opts.rowFilter(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>)\n : opts.rowFilter;\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 const projection = {\n ...built,\n table: owner.table,\n shape,\n readProjection: true as const,\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\n return attachSyncRegistrySchema(input.tables, input.schema);\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 };\n const sqlType = normalizeCastPositionType(typedColumn.getSQLType?.() ?? \"\");\n return {\n name: columnName,\n sqlType,\n isArray: (typedColumn.dimensions ?? 0) > 0,\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 const columns = getColumns(entry.table);\n // `field.column` is the drizzle property key; resolve it to the underlying column name.\n const byProperty = (columns as Record<string, { name: string } | undefined>)[field.column as string];\n if (byProperty) {\n return byProperty.name;\n }\n\n // Defensive: a managed field declared by column name rather than property key.\n return Object.values(columns).find((column) => column.name === field.column)?.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\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 // 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 (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",
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\";\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 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 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\nexport const syncRegistrySchemaSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistrySchema\");\n\nexport const syncRegistryStorageSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistryStorage\");\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\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\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>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], \"update\">>>\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 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 const projection = {\n ...built,\n table: owner.table,\n shape,\n readProjection: true as const,\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\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.\n return attachSyncRegistryStorage(attachSyncRegistrySchema(input.tables, input.schema), input.storage);\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 * 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
10
  "/**\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",
11
11
  "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 * 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.\n */\nexport function fingerprintRegistry(registry: SyncTableRegistry): string {\n return hashString(canonicalRegistryString(registry));\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 */\nexport function hashString(input: string): string {\n const bytes = new TextEncoder().encode(input);\n const prime = 0x100000001b3n;\n const mask = (1n << 64n) - 1n;\n let hash = 0xcbf29ce484222325n;\n for (const byte of bytes) {\n hash = ((hash ^ BigInt(byte)) * prime) & mask;\n }\n return hash.toString(16).padStart(16, \"0\");\n}\n",
12
12
  "import { canonicalizeRegistry, fingerprintRegistry, type CanonicalTable } from \"./fingerprint\";\nimport 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\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\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/** Build the committed lock (fingerprint + canonical shape) for a registry. */\nexport function buildRegistryLock(registry: SyncTableRegistry): RegistryLock {\n return { version: fingerprintRegistry(registry), tables: canonicalizeRegistry(registry) };\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/** Classify the change from one canonical registry shape to another. */\nexport function diffCanonicalRegistries(\n previous: readonly CanonicalTable[],\n next: readonly CanonicalTable[],\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\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 }\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 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(canonicalizeRegistry(previous), canonicalizeRegistry(next));\n}\n\n/** Classify a registry against a committed lock baseline. */\nexport function diffRegistryAgainstLock(registry: SyncTableRegistry, lock: RegistryLock): RegistryDiff {\n return diffCanonicalRegistries(lock.tables, canonicalizeRegistry(registry));\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",
13
- "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 any write whose table predates the policy; absence means no stale\n * 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",
14
- "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, AND the column-builder factory (`makeColumns`) — is preserved\n * 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 ...(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",
13
+ "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",
14
+ "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, AND the column-builder factory (`makeColumns`) — is preserved\n * 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 ...(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",
15
15
  "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",
16
16
  "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 { 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\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};\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\nconst defaultOwnerSqlColumn = \"owner_id\";\nconst defaultOwnerPropertyKey = \"ownerId\";\nconst defaultAuthenticatedRoleName = \"authenticated\";\nconst defaultAdminRoleName = \"admin\";\nconst defaultSubjectCastType = \"uuid\";\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 admin-bypass test: `app_metadata.roles` (from the JWT claims) contains `adminRoleName`. No\n// column reference and no recursion risk, so it is inlined as text (shared by the text builder and\n// the native builder). The role value enters as a typed interpolation (drizzle owns the escaping);\n// the claim-extraction body is the allowed raw leaf.\nfunction buildAdminRoleExistsSqlText(adminRoleName: string): string {\n return renderInlineSql(sql`EXISTS (\n SELECT 1\n FROM jsonb_array_elements_text(\n COALESCE(\n (\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb -> 'app_metadata' -> 'roles'\n ),\n '[]'::jsonb\n )\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 };\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)}\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(buildAdminRoleExistsSqlText(adminRoleName));\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// 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\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// 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 resolveGrantScopeIds}\n// + {@link buildGrantScopeShapeWhere}: the proxy resolves the ids from the claims in JS\n// and injects a literal `scope_col IN ('a','b')` — Electric cannot read RLS, so the two\n// 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\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: any grant whose `role` ∈ `bypass.roleValues` and whose\n * `scope.kind` = `bypass.scopeKind` (default \"platform\") grants all rows — e.g. a\n * platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it stays\n * InitPlan-hoisted in both the correct and naive forms.\n */\n bypass?: { roleValues: string[]; scopeKind?: string };\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, defaulting to `[]` when absent so\n// `jsonb_array_elements` never errors. `#>` takes a text[] path; the segments are validated\n// identifiers, so the `'{…}'` path literal is injection-safe.\nfunction buildGrantsArraySqlText(path: string[]): string {\n return `coalesce(\n (\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb #> '{${path.join(\",\")}}'\n ),\n '[]'::jsonb\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: { roleValues: string[]; scopeKind?: string }, grantsText: string): string {\n const scopeKind = bypass.scopeKind ?? \"platform\";\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 two 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\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/**\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"
17
17
  ],
18
- "mappings": ";;AAmCA,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,OAAO,CAAC,OAAO,WAAW,qBAAqB,IAAI,kBAAkB,OAAO,OAAO,CAAC;AAAA;AAOtF,SAAS,UAAU,CAAC,QAAiC;AAAA,EACnD,IAAI,WAAW,MAAM,GAAG;AAAA,IACtB,OAAO;AAAA,EACT;AAAA,EACA,IAA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