@pgxsinkit/contracts 0.1.31 → 0.1.36

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.
Files changed (44) hide show
  1. package/README.md +13 -0
  2. package/dist/apply-strategy.d.ts +35 -0
  3. package/dist/apply-strategy.d.ts.map +1 -0
  4. package/dist/config.d.ts +210 -32
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +106 -0
  7. package/dist/convergence-model.d.ts.map +1 -0
  8. package/dist/fingerprint.d.ts +136 -0
  9. package/dist/fingerprint.d.ts.map +1 -0
  10. package/dist/index.d.ts +7 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +5222 -3494
  13. package/dist/index.js.map +37 -30
  14. package/dist/mutation.d.ts +78 -0
  15. package/dist/mutation.d.ts.map +1 -1
  16. package/dist/projection.d.ts +88 -0
  17. package/dist/projection.d.ts.map +1 -0
  18. package/dist/registry-diff.d.ts +50 -0
  19. package/dist/registry-diff.d.ts.map +1 -0
  20. package/dist/registry.d.ts +253 -2
  21. package/dist/registry.d.ts.map +1 -1
  22. package/dist/runtime.d.ts +21 -1
  23. package/dist/runtime.d.ts.map +1 -1
  24. package/dist/sql-defaults.d.ts +27 -0
  25. package/dist/sql-defaults.d.ts.map +1 -0
  26. package/dist/sql-identifier.d.ts +26 -0
  27. package/dist/sql-identifier.d.ts.map +1 -0
  28. package/dist/supabase-rls.d.ts +99 -3
  29. package/dist/supabase-rls.d.ts.map +1 -1
  30. package/package.json +12 -3
  31. package/skills/registry-authoring/SKILL.md +376 -0
  32. package/src/apply-strategy.ts +124 -0
  33. package/src/config.ts +254 -106
  34. package/src/convergence-model.ts +190 -0
  35. package/src/fingerprint.ts +265 -0
  36. package/src/index.ts +7 -0
  37. package/src/mutation.ts +94 -2
  38. package/src/projection.ts +150 -0
  39. package/src/registry-diff.ts +215 -0
  40. package/src/registry.ts +751 -23
  41. package/src/runtime.ts +21 -1
  42. package/src/sql-defaults.ts +29 -0
  43. package/src/sql-identifier.ts +130 -0
  44. package/src/supabase-rls.ts +515 -37
package/src/registry.ts CHANGED
@@ -21,17 +21,32 @@ import { varchar } from "drizzle-orm/pg-core";
21
21
  import type { ExtractTablesWithRelations } from "drizzle-orm/relations";
22
22
  import { getColumns } from "drizzle-orm/utils";
23
23
 
24
- import type {
25
- ClientProjectionSpec,
26
- DeferrableConstraintSpec,
27
- ManagedFieldApplyOn,
28
- ManagedFieldSpec,
29
- ManagedFieldStrategy,
30
- PrimaryKeySpec,
31
- ShapeSpec,
32
- ShapeSpecInput,
33
- TableGovernanceSpec as TableGovernanceSpecBase,
34
- TableMode,
24
+ import { type ApplyStrategy, classifyApplyStrategy, type SyncColumnType } from "./apply-strategy";
25
+ import {
26
+ CONFLICT_POLICIES,
27
+ isConflictPolicy,
28
+ isRetention,
29
+ isSubscriptionTiming,
30
+ isWriteMode,
31
+ RETENTIONS,
32
+ SUBSCRIPTION_TIMINGS,
33
+ WRITE_MODES,
34
+ type ClientProjectionSpec,
35
+ type ConflictPolicy,
36
+ type DeferrableConstraintSpec,
37
+ type ManagedFieldApplyOn,
38
+ type ManagedFieldSpec,
39
+ type ManagedFieldStrategy,
40
+ type PrimaryKeySpec,
41
+ type Retention,
42
+ type RowFilterSpec,
43
+ type ServerProjectionSpec,
44
+ type ShapeSpec,
45
+ type ShapeSpecInput,
46
+ type SubscriptionTiming,
47
+ type TableGovernanceSpec as TableGovernanceSpecBase,
48
+ type TableMode,
49
+ type WriteMode,
35
50
  } from "./config";
36
51
 
37
52
  type PgSchemaType = ReturnType<typeof pgSchema>;
@@ -101,7 +116,63 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
101
116
  primaryKey: PrimaryKeySpec;
102
117
  shape?: ShapeSpec;
103
118
  clientProjection?: ClientProjectionSpecForTable<TTable>;
119
+ serverProjection?: ServerProjectionSpec;
104
120
  governance?: TableGovernanceSpecForTable<TTable>;
121
+ /**
122
+ * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable
123
+ * tables** (registry validation rejects an undeclared one — the third hard-require); ignored for
124
+ * `readonly` tables (they have no write path). See {@link ConflictPolicy}.
125
+ */
126
+ conflictPolicy?: ConflictPolicy;
127
+ /**
128
+ * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced on one
129
+ * `MultiShapeStream` and committed atomically at a shared LSN frontier, so a local reader never
130
+ * sees one grouped table advanced past another for the same server transaction. Omitted → the
131
+ * table is its own singleton group (independent frontier, today's behaviour). The latency cost (a
132
+ * group advances only as fast as its slowest shape) is contained to the tables that opt in.
133
+ */
134
+ consistencyGroup?: string;
135
+ /**
136
+ * Subscription timing (ADR-0021): `eager` (default) | `lazy`. A `lazy` table is excluded from the
137
+ * boot subscription set and subscribed on first query-reference. A property of the **consistency
138
+ * group** — every table sharing a `consistencyGroup` must agree (validated). See
139
+ * {@link SubscriptionTiming}.
140
+ */
141
+ subscription?: SubscriptionTiming;
142
+ /**
143
+ * Retention (ADR-0021): `persistent` (default) | `ephemeral`. An `ephemeral` table's whole local
144
+ * cluster is emitted as `TEMP` — no durable trace, no durable offline write queue. A property of the
145
+ * consistency group — every table sharing a `consistencyGroup` must agree (validated). See
146
+ * {@link Retention}.
147
+ */
148
+ retention?: Retention;
149
+ /**
150
+ * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. A `pessimistic` consistency group is a
151
+ * standing server-authoritative write-unit — its writes flush-route to the authoritative endpoint and
152
+ * the UI shows success only after the server confirms. Write-mode is a property of the **write-unit**;
153
+ * the static write-unit is the consistency group, so every table sharing a `consistencyGroup` must agree
154
+ * (validated). See {@link WriteMode}.
155
+ */
156
+ writeMode?: WriteMode;
157
+ /**
158
+ * True when this entry is a read PROJECTION over a table OWNED by another entry (built by
159
+ * {@link defineReadProjection}). Such an entry owns no physical table — its `table` is the owner's,
160
+ * and only its `localTable` + `shape` are its own — so migration/apply/RLS generation skips it and a
161
+ * consumer's schema barrel must never export a fresh table for it. Absent → the entry owns its table.
162
+ */
163
+ readProjection?: boolean;
164
+ /**
165
+ * The column-builder factory that produced this entry's table (set by {@link defineSyncTable}).
166
+ * Retained so {@link defineReadProjection} can reuse the owner's column definitions to build a typed
167
+ * column subset without restating them, AND — since ADR-0029 P1 — so the client can derive every
168
+ * synced-table object (the local synced read cache, overlay, journal) via
169
+ * `getSyncedLocalTable` → `projectedColumnBuilders`. It is therefore read-derivation machinery, not a
170
+ * write handle: it is carried through every projection ({@link asReadonly}, `withRetention`,
171
+ * `defineReadProjection`), NOT fingerprinted (functions are invisible to the read-contract hash), and
172
+ * required on every registered entry — `defineSyncRegistry`/`validateSyncTableEntry` reject a
173
+ * hand-assembled entry that lacks it, since the client hard-requires it at boot.
174
+ */
175
+ makeColumns?: () => Record<string, ColumnBuilderBase>;
105
176
  }
106
177
 
107
178
  /** Column property key names from a `makeColumns` factory function. */
@@ -128,6 +199,32 @@ type ProjectedLocalTable<
128
199
  dialect: "pg";
129
200
  }>;
130
201
 
202
+ /**
203
+ * The local table TYPE for a {@link defineReadProjection} entry: the OWNER's already-built columns
204
+ * (`TableColumnsShape<TOwnerTable>`) restricted to the kept keys (`TKeptKey`), under the projection's own
205
+ * local name (`TAs`).
206
+ *
207
+ * Why this exists rather than reusing the inner `defineSyncTable`'s `localTable` type: a projection
208
+ * rebuilds its columns from the owner's stashed `makeColumns`, but {@link SyncTableEntry.makeColumns} is
209
+ * type-erased to `() => Record<string, ColumnBuilderBase>`, so a `localTable` inferred through it collapses
210
+ * to an open index signature — forcing bracket-access + `!` in consumers. Picking directly off
211
+ * `TOwnerTable`'s real column types restores rename-safe, per-column typing.
212
+ *
213
+ * Sound by construction — never an over-claim: the runtime keeps `columns ∪ primaryKey`, a SUPERSET of
214
+ * `TKeptKey`, so every typed column exists at runtime. A primary-key column not listed in `columns` is
215
+ * kept at runtime but omitted from the type (a safe under-claim; include it in `columns` to type it).
216
+ */
217
+ type ProjectionLocalTable<
218
+ TOwnerTable extends AnyPgTable,
219
+ TAs extends string,
220
+ TKeptKey extends string,
221
+ > = PgTableWithColumns<{
222
+ name: TAs;
223
+ schema: string | undefined;
224
+ columns: Pick<TableColumnsShape<TOwnerTable>, TKeptKey & keyof TableColumnsShape<TOwnerTable>>;
225
+ dialect: "pg";
226
+ }>;
227
+
131
228
  type ReadModelView<
132
229
  TName extends string,
133
230
  TColumns extends Record<string, ColumnBuilderBase>,
@@ -161,6 +258,25 @@ export type SyncTableInputProjection<
161
258
  omitColumns?: TOmittedColumns;
162
259
  };
163
260
 
261
+ /**
262
+ * A row filter for {@link defineSyncTable}'s `shape`: either a static {@link RowFilterSpec}, or a
263
+ * function of the table's built (typed) columns. The function form is the all-in-one way to author a
264
+ * typed-Drizzle row filter inline — reference columns through `c(columns.x)` exactly as `extras`
265
+ * does with its `self` argument, so `customWhere` builds parameterized Electric `where`s from real,
266
+ * rename-safe column objects instead of hand-written column-name strings.
267
+ */
268
+ export type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> =
269
+ | RowFilterSpec
270
+ | ((columns: PgBuildExtraConfigColumns<TColumns>) => RowFilterSpec);
271
+
272
+ /** {@link ShapeSpecInput} whose `rowFilter` may also be a function of the built columns (typed by `TColumns`). */
273
+ export type ShapeSpecInputFor<TColumns extends Record<string, ColumnBuilderBase>> = Omit<
274
+ ShapeSpecInput,
275
+ "rowFilter"
276
+ > & {
277
+ rowFilter?: RowFilterInput<TColumns>;
278
+ };
279
+
164
280
  /**
165
281
  * Input for `defineSyncTable`. Supply `tableName + makeColumns` — the Drizzle table
166
282
  * (and, for `readwrite` mode, the read-model view) are created internally.
@@ -191,9 +307,36 @@ export type SyncTableInput<
191
307
  * Use an array with multiple entries for composite keys.
192
308
  */
193
309
  primaryKey?: string[];
194
- shape?: ShapeSpecInput;
310
+ shape?: ShapeSpecInputFor<TColumns>;
195
311
  clientProjection?: SyncTableInputProjection<TColumns, TOmittedColumns>;
312
+ /** Server-side response-path projection (e.g. `rowTransform`). Server authority, not client shape. */
313
+ serverProjection?: ServerProjectionSpec;
196
314
  governance?: SyncTableInputGovernance<TColumns>;
315
+ /**
316
+ * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable
317
+ * tables** — `defineSyncTable`/`defineSyncRegistry` reject a writable table without one. See
318
+ * {@link ConflictPolicy}.
319
+ */
320
+ conflictPolicy?: ConflictPolicy;
321
+ /**
322
+ * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync on one
323
+ * `MultiShapeStream` and commit atomically. Omit for the default singleton group. See
324
+ * {@link SyncTableEntry.consistencyGroup}.
325
+ */
326
+ consistencyGroup?: string;
327
+ /**
328
+ * Subscription timing (ADR-0021): `eager` (default) | `lazy`. See
329
+ * {@link SyncTableEntry.subscription}.
330
+ */
331
+ subscription?: SubscriptionTiming;
332
+ /**
333
+ * Retention (ADR-0021): `persistent` (default) | `ephemeral`. See {@link SyncTableEntry.retention}.
334
+ */
335
+ retention?: Retention;
336
+ /**
337
+ * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. See {@link SyncTableEntry.writeMode}.
338
+ */
339
+ writeMode?: WriteMode;
197
340
  };
198
341
 
199
342
  export type SyncTableRegistry = Record<string, SyncTableEntry>;
@@ -299,6 +442,7 @@ export function defineSyncTable<
299
442
  primaryKey,
300
443
  governance,
301
444
  clientProjection,
445
+ serverProjection,
302
446
  shape,
303
447
  ...otherRest
304
448
  } = input;
@@ -320,16 +464,6 @@ export function defineSyncTable<
320
464
  }
321
465
  : undefined;
322
466
 
323
- const resolvedShape: ShapeSpec | undefined =
324
- resolvedMode !== "writeonly" || shape != null
325
- ? {
326
- tableName: shape?.tableName ?? tableName,
327
- shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,
328
- ...(shape?.electricTable != null ? { electricTable: shape.electricTable } : {}),
329
- ...(shape?.rowFilter != null ? { rowFilter: shape.rowFilter } : {}),
330
- }
331
- : undefined;
332
-
333
467
  const extrasFn =
334
468
  policies || extras
335
469
  ? (self: PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>) => [
@@ -339,6 +473,26 @@ export function defineSyncTable<
339
473
  : undefined;
340
474
  const table = schema ? schema.table(tableName, makeColumns(), extrasFn) : pgTable(tableName, makeColumns(), extrasFn);
341
475
 
476
+ // A function-form `shape.rowFilter` is resolved here against the built (typed) columns, so an
477
+ // all-in-one `defineSyncTable` can author a row filter with `c(columns.x)` Drizzle fragments — the
478
+ // same typed columns `extras` receives — instead of hand-written column-name strings. A static
479
+ // `RowFilterSpec` passes through unchanged.
480
+ const resolvedRowFilter: RowFilterSpec | undefined =
481
+ typeof shape?.rowFilter === "function"
482
+ ? shape.rowFilter(getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>)
483
+ : (shape?.rowFilter ?? undefined);
484
+ const resolvedShape: ShapeSpec | undefined =
485
+ resolvedMode !== "writeonly" || shape != null
486
+ ? {
487
+ tableName: shape?.tableName ?? tableName,
488
+ shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,
489
+ // `electricTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its
490
+ // own table. It is filled by `attachSyncRegistrySchema` (schema qualification) or by
491
+ // `defineReadProjection` (which points a projection at the owning physical table).
492
+ ...(resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {}),
493
+ }
494
+ : undefined;
495
+
342
496
  const omittedColumns = (clientProjection?.omitColumns ?? []) as TOmittedColumns;
343
497
  const projectedCols = viewColumnsForProjection(makeColumns(), omittedColumns);
344
498
  const localTable = (
@@ -368,14 +522,315 @@ export function defineSyncTable<
368
522
  ...(resolvedClientProjection != null
369
523
  ? { clientProjection: resolvedClientProjection as unknown as ClientProjectionSpecForTable<typeof table> }
370
524
  : {}),
525
+ ...(serverProjection != null ? { serverProjection } : {}),
371
526
  table,
372
527
  localTable,
373
528
  ...(view != null ? { view } : {}),
529
+ // Retained so `defineReadProjection` can reuse these column definitions for a typed subset.
530
+ makeColumns: makeColumns as () => Record<string, ColumnBuilderBase>,
374
531
  };
375
532
  validateSyncTableEntry(entry as unknown as SyncTableEntry<AnyPgTable>);
376
533
  return entry as typeof entry & SyncTableInputGovernanceMarker<TGovernance>;
377
534
  }
378
535
 
536
+ /**
537
+ * Define a **read projection**: a second client shape over a table an `owner` entry already owns. The
538
+ * projection reads the SAME physical rows under a DISTINCT local identity (`as`) and its own narrower
539
+ * shape — a typed column subset and/or an admin/role-scoped `rowFilter` — without owning, migrating, or
540
+ * RLS-guarding any new table. The first use is a light admin view of a heavy authoring table (titles,
541
+ * not the jsonb), while the learner keeps reading the full table through the owner's shape.
542
+ *
543
+ * It is the *obvious, DRY* way to express "another shape over this table", versus the bare
544
+ * `shape.electricTable` string it replaces (a footgun — config that silently un-asserts table
545
+ * ownership):
546
+ *
547
+ * - **Owns nothing.** The returned entry's `table` IS `owner.table` (the same object), so there is no
548
+ * new `pgTable` to migrate or to leak into a drizzle-kit schema barrel. Only `localTable` (named `as`)
549
+ * and `shape` are its own. `readProjection` is set so generators skip it.
550
+ * - **DRY columns.** `columns` is a typed subset of the owner's column keys; the local table is built by
551
+ * filtering the owner's own column definitions (never restated), and the same subset becomes the
552
+ * Electric `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The
553
+ * primary key is always kept. Omit `columns` to sync every column.
554
+ * - **Source is derived, never named.** The physical Electric target is taken from the owner — there is
555
+ * no consumer-facing source field to get wrong (see {@link ShapeSpec.electricTable}).
556
+ * - **Readonly.** A projection has no write path; the engine resolves an incoming shape request by its
557
+ * unique `shapeKey` (= `as`) and consults the derived physical target only on egress.
558
+ *
559
+ * The `rowFilter` callback receives the OWNER's full columns — `customWhere` runs in Electric against
560
+ * the physical table, so it may reference a column the local subset omits. RLS for the projection's
561
+ * reads lives on the OWNER's table (a projection adds no DDL to a table it does not own); its
562
+ * `customWhere` must be a subset of what that RLS allows.
563
+ *
564
+ * The `owner` may be a `defineSyncTable` entry OR an `asReadonly` of one — an `asReadonly` projection
565
+ * preserves the full read contract (physical table, columns, primary key) and only drops the write path,
566
+ * so projecting off it is equivalent to projecting off its writable source. A CHAINED read projection
567
+ * (an owner that is itself a `defineReadProjection`) is rejected, because it composes wrongly — see below.
568
+ *
569
+ * ### Server-side egress redaction (`serverProjection` + `serverOnlyColumns`)
570
+ *
571
+ * A projection may carry its own `serverProjection` (a {@link ServerProjectionSpec}, typically a
572
+ * `rowTransform`) — resolved by the projection's `shapeKey` and run on the proxy egress path for this
573
+ * shape only. The order on egress is **transform first, then omission**: the transform runs against the
574
+ * fetched row, then column omission strips this projection's omitted columns (the client keep-set is
575
+ * `columns ∪ primaryKey`) before the row reaches the client wire. This lets a "secure window" over a
576
+ * keyed table stream the body while stripping the keys per row.
577
+ *
578
+ * `serverOnlyColumns` are owner column keys the transform must READ but that are NOT in the client shape
579
+ * (e.g. a `keysWithheld` control flag). Such a key stays omitted from the client keep-set, yet is ADDED
580
+ * to the Electric fetch allow-list — so it is fetched from Electric, visible to the transform, and then
581
+ * stripped on egress by the same omission pass, never reaching the client. It requires a
582
+ * `serverProjection.rowTransform` (a fetch no transform reads is dead weight) AND `columns` (with
583
+ * `columns` omitted every column is already kept, so "server-only" is a contradiction), and must be
584
+ * disjoint from `columns` and the primary key.
585
+ *
586
+ * **No inheritance — ENFORCED.** A projection does NOT inherit its owner's `serverProjection`. That is
587
+ * deliberate: an inherited transform whose input column is absent from the projection's fetch list would
588
+ * read `undefined` and silently fail OPEN (serving the un-redacted body) — half-protection worse than
589
+ * none. Because a bare projection over a redacting owner would therefore egress RAW owner rows, the
590
+ * registry no longer merely warns: when `owner.serverProjection?.rowTransform` exists, this function
591
+ * THROWS at definition time unless the projection declares a posture. You must either declare your own
592
+ * `serverProjection` on the projection (typically the same transform fn, plus `serverOnlyColumns` for its
593
+ * control-flag inputs), or — only after confirming the projection's kept columns leak nothing — opt out
594
+ * explicitly with the literal `serverProjection: "unredacted"`, which attaches no transform (egress raw)
595
+ * but records that as a visible, reviewed decision at the definition site. The opt-out is meaningful only
596
+ * where it applies: `"unredacted"` over an owner with NO egress `rowTransform` is itself rejected, so a
597
+ * stale opt-out cannot silently pre-authorize a leak the day the owner grows one.
598
+ */
599
+ export function defineReadProjection<
600
+ const TOwnerTable extends AnyPgTable,
601
+ const TOwnerLocal extends AnyPgTable,
602
+ const TAs extends string,
603
+ // Captures `opts.columns` as a literal tuple so the projection's local table can carry the OWNER's real
604
+ // per-column types restricted to the kept keys. Defaults to "all owner keys" (its `[number]` is the full
605
+ // key union), which is exactly the shape when `columns` is omitted — one uniform kept-key expression.
606
+ const TColumns extends readonly TableColumnKey<TOwnerTable>[] = readonly TableColumnKey<TOwnerTable>[],
607
+ >(
608
+ // Two table params so an owner that uses `omitColumns` (its `table` and `localTable` types differ) is
609
+ // accepted — `TOwnerTable` (the physical table) is what `columns`/`rowFilter` are typed against.
610
+ owner: SyncTableEntry<TOwnerTable, TOwnerLocal>,
611
+ opts: {
612
+ /** The projection's distinct local identity — its PGlite table name AND its `shapeKey`. */
613
+ as: TAs;
614
+ /** Column keys (of the owner) to sync locally + fetch from Electric. The PK is always kept. Omit → all. */
615
+ columns?: TColumns;
616
+ /** Row filter for this shape; the callback form receives the owner's full (physical) columns. */
617
+ rowFilter?: RowFilterSpec | ((columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec);
618
+ /**
619
+ * Server-side egress projection (ADR-0004) for THIS shape — typically a `rowTransform` that redacts a
620
+ * sub-document of a kept column conditionally on row data. A projection does NOT inherit its owner's
621
+ * `serverProjection` (see the docblock's no-inheritance caution): an inherited transform whose input
622
+ * column is unfetched would fail OPEN, so inheritance is refused, not silent. When the OWNER declares
623
+ * an egress `rowTransform`, this is therefore **required** — the registry throws at definition time
624
+ * unless you either declare your own spec here (typically the same transform fn, plus
625
+ * `serverOnlyColumns` for its control-flag inputs) OR opt out with the literal `"unredacted"`. Use
626
+ * `"unredacted"` only after confirming this projection's kept columns leak nothing; it attaches NO
627
+ * egress transform (the shape streams raw owner rows), but records that as a visible, reviewed
628
+ * decision at the definition site. `"unredacted"` over a transform-less owner is itself rejected — a
629
+ * stale opt-out would silently pre-authorize a leak the day the owner grows a transform.
630
+ */
631
+ serverProjection?: ServerProjectionSpec | "unredacted";
632
+ /**
633
+ * Owner column keys the `serverProjection.rowTransform` must READ but which are NOT part of the client
634
+ * shape (e.g. a `keysWithheld` control flag). They are added to the Electric fetch allow-list so the
635
+ * transform can see them, then stripped on egress before the client wire. Requires
636
+ * `serverProjection.rowTransform` and `columns`; must be disjoint from `columns` and the primary key.
637
+ */
638
+ serverOnlyColumns?: readonly TableColumnKey<TOwnerTable>[];
639
+ consistencyGroup?: string;
640
+ subscription?: SubscriptionTiming;
641
+ retention?: Retention;
642
+ },
643
+ ) {
644
+ // A read projection composes off the OWNER's physical table + full columns. A chained projection (an
645
+ // owner that is itself a read projection) would silently discard the intermediate's OWN column subset
646
+ // and rowFilter — this derivation reads the intermediate's `table`/`makeColumns` (the physical table,
647
+ // full columns), not its narrowed shape — so it cannot mean "project the projection". Reject it and
648
+ // point at the owning defineSyncTable entry, which is the only sound base. (An `asReadonly` owner is
649
+ // NOT a read projection and IS accepted — see the docblock.)
650
+ if (owner.readProjection) {
651
+ throw new Error(
652
+ `defineReadProjection: owner "${opts.as}" is itself a read projection — chained projections compose ` +
653
+ `wrongly (this derives off the owner's physical table + full columns, so the intermediate's own ` +
654
+ `column subset and rowFilter would be silently discarded). Project off the owning defineSyncTable ` +
655
+ `entry instead.`,
656
+ );
657
+ }
658
+
659
+ // Defensive: every registrable entry (defineSyncTable + every transform — asReadonly / asEphemeral /
660
+ // withRetention) now carries the column factory, so its absence means a hand-assembled owner, which
661
+ // cannot be projected (there is nothing to derive columns from).
662
+ const ownerMakeColumns = owner.makeColumns;
663
+ if (!ownerMakeColumns) {
664
+ throw new Error(
665
+ `defineReadProjection: owner "${getTableConfig(owner.table).name}" has no column factory — pass an ` +
666
+ `entry built by defineSyncTable (or an asReadonly of one), not a hand-assembled entry.`,
667
+ );
668
+ }
669
+
670
+ const physicalTable = getTableConfig(owner.table).name;
671
+ const allKeys = Object.keys(ownerMakeColumns());
672
+ const pkKeys = owner.primaryKey.columns;
673
+ const keep = opts.columns ? new Set<string>([...opts.columns, ...pkKeys]) : new Set(allKeys);
674
+ // The subset is expressed as `omitColumns` over the OWNER's full columns, so every column-derivation
675
+ // helper (deriveSyncColumnTypes / classifyTableApplyStrategy / getProjectedColumnNames) — which read
676
+ // `entry.table` minus `omitColumns` — yields the right subset for the client, with `entry.table`
677
+ // staying the owner's physical table (nothing new to migrate). The primary key is always kept.
678
+ const omittedKeys = allKeys.filter((key) => !keep.has(key));
679
+
680
+ // serverOnlyColumns — owner keys the egress rowTransform must READ but that are NOT in the client
681
+ // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND the proxy strips them on
682
+ // egress), yet are added to the Electric fetch allow-list below so the transform can see them. Each
683
+ // guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.
684
+ // Fail-closed posture guard. A projection does NOT inherit its owner's egress `serverProjection`
685
+ // (see the docblock's no-inheritance caution: an inherited transform whose input column is unfetched
686
+ // reads `undefined` and fails OPEN — half-protection worse than none). So if the OWNER redacts on
687
+ // egress via `serverProjection.rowTransform`, this projection would silently egress RAW owner rows
688
+ // unless it declares a posture. We REFUSE that silence: the projection must either declare its own
689
+ // `serverProjection` (an object spec) or opt out with the literal `serverProjection: "unredacted"`.
690
+ const optServerProjection = opts.serverProjection;
691
+ const ownerHasEgressTransform = owner.serverProjection?.rowTransform != null;
692
+ if (optServerProjection === "unredacted" && !ownerHasEgressTransform) {
693
+ // A stale "unredacted" over a transform-less owner would silently pre-authorize a leak if the owner
694
+ // later grew a transform. Keep the opt-out meaningful exactly where it applies.
695
+ throw new Error(
696
+ `defineReadProjection: projection "${opts.as}" declares serverProjection: "unredacted", but owner ` +
697
+ `"${physicalTable}" declares no egress rowTransform — the opt-out masks nothing here and would ` +
698
+ `silently pre-authorize a leak if the owner later gains one. Remove the opt-out so it cannot mask ` +
699
+ `a future one.`,
700
+ );
701
+ }
702
+ if (ownerHasEgressTransform && optServerProjection == null) {
703
+ throw new Error(
704
+ `defineReadProjection: projection "${opts.as}" projects over owner "${physicalTable}", which declares ` +
705
+ `an egress rowTransform — a projection does NOT inherit it, so this shape would egress RAW owner ` +
706
+ `rows. Declare your own serverProjection (typically the same transform fn, plus serverOnlyColumns ` +
707
+ `for its control-flag inputs) or — only after confirming the projection's kept columns leak nothing ` +
708
+ `— opt out with serverProjection: "unredacted".`,
709
+ );
710
+ }
711
+ // Only an object spec attaches to the entry; "unredacted" attaches NOTHING (egress raw, but now a
712
+ // visible, reviewed decision at the definition site).
713
+ const serverProjection = typeof optServerProjection === "object" ? optServerProjection : undefined;
714
+ const serverOnlyColumns = opts.serverOnlyColumns ?? [];
715
+ if (serverOnlyColumns.length > 0) {
716
+ if (optServerProjection === "unredacted") {
717
+ throw new Error(
718
+ `defineReadProjection: projection "${opts.as}" declares serverProjection: "unredacted" together ` +
719
+ `with serverOnlyColumns — the opt-out runs no transform, so there is nothing to read them. Drop ` +
720
+ `serverOnlyColumns, or declare a serverProjection.rowTransform that reads them.`,
721
+ );
722
+ }
723
+ if (!serverProjection?.rowTransform) {
724
+ throw new Error(
725
+ `defineReadProjection: projection "${opts.as}" declares serverOnlyColumns but no ` +
726
+ `serverProjection.rowTransform — a server-only fetch that no transform reads is dead weight. ` +
727
+ `Add the rowTransform that reads them, or drop serverOnlyColumns.`,
728
+ );
729
+ }
730
+ if (!opts.columns) {
731
+ throw new Error(
732
+ `defineReadProjection: projection "${opts.as}" declares serverOnlyColumns without columns — with ` +
733
+ `columns omitted every column is already kept client-side, so a "server-only" column is a ` +
734
+ `contradiction. Declare columns (the client subset) so some columns can be genuinely server-only.`,
735
+ );
736
+ }
737
+ const clientKept = new Set<string>([...opts.columns, ...pkKeys]);
738
+ for (const key of serverOnlyColumns) {
739
+ if (!allKeys.includes(key)) {
740
+ throw new Error(
741
+ `defineReadProjection: projection "${opts.as}" serverOnlyColumns names "${key}", which is not a ` +
742
+ `column of owner "${physicalTable}". It feeds the Electric fetch allow-list, so a typo would ` +
743
+ `silently mis-fetch — name an existing owner column key.`,
744
+ );
745
+ }
746
+ if (clientKept.has(key)) {
747
+ throw new Error(
748
+ `defineReadProjection: projection "${opts.as}" lists "${key}" in BOTH serverOnlyColumns and the ` +
749
+ `client shape (columns or primary key) — it is already fetched and kept client-side, so ` +
750
+ `declaring it server-only is contradictory. Remove it from serverOnlyColumns.`,
751
+ );
752
+ }
753
+ }
754
+ }
755
+
756
+ // The local table (subset) + base shape (tableName/shapeKey = `as`) + readonly validation come from the
757
+ // normal constructor — reusing the OWNER's column definitions, never restating them. Below we override
758
+ // only what a projection differs in (it owns no table; it reads the owner's physical table).
759
+ const built = defineSyncTable({
760
+ tableName: opts.as,
761
+ makeColumns: ownerMakeColumns,
762
+ mode: "readonly",
763
+ primaryKey: [...pkKeys],
764
+ ...(omittedKeys.length > 0
765
+ ? { clientProjection: { omitColumns: omittedKeys as unknown as readonly never[] } }
766
+ : {}),
767
+ ...(opts.consistencyGroup != null ? { consistencyGroup: opts.consistencyGroup } : {}),
768
+ ...(opts.subscription != null ? { subscription: opts.subscription } : {}),
769
+ ...(opts.retention != null ? { retention: opts.retention } : {}),
770
+ });
771
+
772
+ // Resolve the row filter against the OWNER's full columns (the customWhere runs in Electric on the
773
+ // physical table, so it may reference a column the subset omits).
774
+ const resolvedRowFilter: RowFilterSpec | undefined =
775
+ typeof opts.rowFilter === "function"
776
+ ? opts.rowFilter(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>)
777
+ : opts.rowFilter;
778
+
779
+ // When a subset is requested, set the Electric `columns` allow-list to the KEPT physical column names
780
+ // so an omitted (e.g. heavy jsonb) column is never fetched over the wire — not merely stripped after.
781
+ // serverOnlyColumns are added ON TOP of the kept names: a server-only column must be FETCHED (so the
782
+ // egress rowTransform can read it) even though it is omitted from the client keep-set — proxy omission
783
+ // then strips it after the transform runs. Resolve key -> physical name the same way getProjectedColumns
784
+ // does (the drizzle column's `.name`), never a hand-map. A full-width projection (no omitted keys, hence
785
+ // no serverOnlyColumns — validated above) declares no allow-list at all.
786
+ const ownerColumns = getColumns(owner.table) as Record<string, { name: string }>;
787
+ const serverOnlyColumnNames = serverOnlyColumns.map((key) => ownerColumns[key]!.name);
788
+ const allowListColumns =
789
+ omittedKeys.length > 0 ? [...getProjectedColumnNames(built), ...serverOnlyColumnNames] : undefined;
790
+
791
+ const rowFilter: RowFilterSpec | undefined =
792
+ resolvedRowFilter != null || allowListColumns != null
793
+ ? {
794
+ ...(resolvedRowFilter ?? {}),
795
+ ...(allowListColumns != null ? { columns: allowListColumns } : {}),
796
+ }
797
+ : undefined;
798
+
799
+ const shape: ShapeSpec = {
800
+ tableName: opts.as,
801
+ shapeKey: opts.as,
802
+ electricTable: physicalTable,
803
+ ...(rowFilter != null ? { rowFilter } : {}),
804
+ };
805
+
806
+ // Point `table` at the owner's physical table and flag `readProjection` — that flag (not the absence of
807
+ // a column factory) is what generators/appliers key on to skip owning-table work (see plpgsql-apply's
808
+ // `!entry.readProjection` filter). The owner's `makeColumns` is KEPT (it rode in via `built`): since
809
+ // ADR-0029 P1 the client derives a projection's OWN local synced object from it too
810
+ // (`getSyncedLocalTable` → `projectedColumnBuilders`, with this entry's `omitColumns` applied), so a
811
+ // subscribed read projection that dropped it would fail to boot exactly as an `asReadonly` entry did.
812
+ // `built` was validated by defineSyncTable and only its `table` is replaced (with the owner's,
813
+ // structurally identical role), so the result is a sound SyncTableEntry — cast past the spread's
814
+ // exactOptional friction to a clean entry type that keeps the projected local-table shape.
815
+ // `serverProjection` is attached HERE on the outer object (mirroring `shape`), NOT threaded through the
816
+ // inner `defineSyncTable` call — that alone makes the proxy's shapeKey resolution find and run the
817
+ // projection's egress transform (getRowTransformForTable → resolveEntryByShapeKey(…)?.serverProjection).
818
+ const projection = {
819
+ ...built,
820
+ table: owner.table,
821
+ shape,
822
+ readProjection: true as const,
823
+ ...(serverProjection != null ? { serverProjection } : {}),
824
+ };
825
+ // The local table carries the OWNER's real column types restricted to the kept keys (`TColumns[number]`
826
+ // — the full owner key union when `columns` was omitted), NOT the type-erased `built.localTable` (which
827
+ // collapses to an open index signature because it is rebuilt through the stashed `makeColumns`).
828
+ return projection as unknown as SyncTableEntry<
829
+ TOwnerTable,
830
+ ProjectionLocalTable<TOwnerTable, TAs, TColumns[number]>
831
+ > & { readProjection: true };
832
+ }
833
+
379
834
  export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(
380
835
  registry: TRegistry,
381
836
  ): TRegistry;
@@ -389,6 +844,8 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
389
844
  for (const entry of getRegistryEntries(input.tables)) {
390
845
  validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);
391
846
  }
847
+ validateRegistryTableUniqueness(input.tables);
848
+ validateRegistryLifecycleGroups(input.tables);
392
849
 
393
850
  return attachSyncRegistrySchema(input.tables, input.schema);
394
851
  }
@@ -396,10 +853,94 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
396
853
  for (const entry of getRegistryEntries(input)) {
397
854
  validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);
398
855
  }
856
+ validateRegistryTableUniqueness(input);
857
+ validateRegistryLifecycleGroups(input);
399
858
 
400
859
  return input;
401
860
  }
402
861
 
862
+ /** The local/shape identity an entry resolves to: its `shape.tableName` (the unique shape key a client
863
+ * requests and the local PGlite table), falling back to the Drizzle table name when an entry has no
864
+ * shape (a write-only table). A read projection carries a distinct `shape.tableName` (`as`) even though
865
+ * its `table` is the owner's, so it is identified here by `as`, never by the shared physical table. */
866
+ function localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {
867
+ return entry.shape?.tableName ?? getTableConfig(entry.table).name;
868
+ }
869
+
870
+ /**
871
+ * A registry must not declare the same local table twice. Every entry resolves to one local identity
872
+ * ({@link localShapeIdentity}) — the PGlite table a client reads and the `shapeKey` the proxy resolves a
873
+ * request by — so two entries sharing it would collide locally (one shadows the other) and make the
874
+ * shape unresolvable. A read PROJECTION over a shared physical table does NOT trip this: it carries a
875
+ * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.electricTable`,
876
+ * so several shapes read one physical table while their local identities stay unique. Fails closed at
877
+ * module-eval, for every consumer.
878
+ */
879
+ function validateRegistryTableUniqueness(registry: SyncTableRegistry) {
880
+ const declaredBy = new Map<string, string>();
881
+
882
+ for (const [key, entry] of Object.entries(registry)) {
883
+ const identity = localShapeIdentity(entry as SyncTableEntry<AnyPgTable>);
884
+ const firstKey = declaredBy.get(identity);
885
+
886
+ if (firstKey !== undefined) {
887
+ throw new Error(
888
+ `local table "${identity}" is declared by two registry entries ("${firstKey}" and "${key}"): ` +
889
+ `each entry must map to a unique local table. A second shape over an existing physical table ` +
890
+ `must use defineReadProjection (a distinct "as") rather than a second owning entry.`,
891
+ );
892
+ }
893
+
894
+ declaredBy.set(identity, key);
895
+ }
896
+ }
897
+
898
+ /**
899
+ * ADR-0021 §4 / ADR-0022 §1–2: subscription timing, retention, and write-mode are properties of a
900
+ * **consistency group**, not a single table — a group commits atomically on one `MultiShapeStream`
901
+ * (so it cannot be partly lazy or partly ephemeral) and a consistency group *is* the static
902
+ * write-unit (so it cannot be partly pessimistic). Reject a registry whose grouped tables disagree on
903
+ * any of the three. Tables without a `consistencyGroup` are their own singleton group and are
904
+ * unconstrained.
905
+ */
906
+ function validateRegistryLifecycleGroups(registry: SyncTableRegistry) {
907
+ const groups = new Map<
908
+ string,
909
+ Array<{ tableName: string; subscription: SubscriptionTiming; retention: Retention; writeMode: WriteMode }>
910
+ >();
911
+
912
+ for (const entry of getRegistryEntries(registry)) {
913
+ if (!entry.consistencyGroup) {
914
+ continue;
915
+ }
916
+
917
+ const members = groups.get(entry.consistencyGroup) ?? [];
918
+ members.push({
919
+ tableName: getTableConfig(entry.table).name,
920
+ subscription: entry.subscription ?? "eager",
921
+ retention: entry.retention ?? "persistent",
922
+ writeMode: entry.writeMode ?? "optimistic",
923
+ });
924
+ groups.set(entry.consistencyGroup, members);
925
+ }
926
+
927
+ for (const [group, members] of groups) {
928
+ const subscriptions = new Set(members.map((member) => member.subscription));
929
+ const retentions = new Set(members.map((member) => member.retention));
930
+ const writeModes = new Set(members.map((member) => member.writeMode));
931
+
932
+ if (subscriptions.size > 1 || retentions.size > 1 || writeModes.size > 1) {
933
+ throw new Error(
934
+ `consistency group "${group}" mixes lifecycle (ADR-0021 §4 / ADR-0022 §1): every table in a ` +
935
+ `group must share one subscription, one retention, and one write-mode; got ` +
936
+ members
937
+ .map((member) => `${member.tableName}=${member.subscription}/${member.retention}/${member.writeMode}`)
938
+ .join(", "),
939
+ );
940
+ }
941
+ }
942
+ }
943
+
403
944
  export function getProjectedColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {
404
945
  const omittedColumns = new Set(entry.clientProjection?.omitColumns ?? []);
405
946
 
@@ -440,6 +981,54 @@ export function getProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTa
440
981
  return getProjectedColumns(entry).map(({ columnName }) => columnName);
441
982
  }
442
983
 
984
+ /**
985
+ * Resolves the {@link SyncColumnType}s of a synced table's client-projected columns from its Drizzle
986
+ * definition (ADR-0009 decision 3) — the same `getSQLType()`/`dimensions` introspection the local
987
+ * schema generator uses, so the apply ladder and the generated DDL can never disagree about a
988
+ * column's type. Drives both {@link classifyTableApplyStrategy} and the engine's `json` apply cast,
989
+ * removing the runtime `information_schema` round-trip.
990
+ */
991
+ export function deriveSyncColumnTypes<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): SyncColumnType[] {
992
+ return getProjectedColumns(entry).map(({ column, columnName }) => {
993
+ const typedColumn = column as { getSQLType?: () => string; dimensions?: number };
994
+ const sqlType = normalizeCastPositionType(typedColumn.getSQLType?.() ?? "");
995
+ return {
996
+ name: columnName,
997
+ sqlType,
998
+ isArray: (typedColumn.dimensions ?? 0) > 0,
999
+ } satisfies SyncColumnType;
1000
+ });
1001
+ }
1002
+
1003
+ /**
1004
+ * `serial`/`bigserial`/`smallserial` are DDL-position conveniences (an integer column plus a sequence
1005
+ * default), NOT real cast-position types: `json_to_recordset(… AS x(id serial))` and `value::serial`
1006
+ * are both invalid SQL. {@link SyncColumnType.sqlType} is contracted to be usable verbatim as a cast
1007
+ * type, so we normalise the serial family to its underlying integer type here — the single derivation
1008
+ * point — which also lets the column classify as COPY-safe rather than falling to the `insert` floor.
1009
+ *
1010
+ * Exported so any code deriving a {@link SyncColumnType} from a bare Drizzle column (e.g. test-support
1011
+ * `makeApplyTarget`, which cannot go through {@link deriveSyncColumnTypes} without a registry entry)
1012
+ * stays byte-faithful to this single normalisation rather than re-`getSQLType()`ing without it.
1013
+ */
1014
+ export function normalizeCastPositionType(sqlType: string): string {
1015
+ switch (sqlType.trim().toLowerCase()) {
1016
+ case "serial":
1017
+ return "integer";
1018
+ case "bigserial":
1019
+ return "bigint";
1020
+ case "smallserial":
1021
+ return "smallint";
1022
+ default:
1023
+ return sqlType;
1024
+ }
1025
+ }
1026
+
1027
+ /** The statically-chosen bulk-insert strategy for a synced table (ADR-0009 decision 3). */
1028
+ export function classifyTableApplyStrategy<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): ApplyStrategy {
1029
+ return classifyApplyStrategy(deriveSyncColumnTypes(entry));
1030
+ }
1031
+
443
1032
  export function getOmittedProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {
444
1033
  return getOmittedProjectedColumns(entry).map(({ columnName }) => columnName);
445
1034
  }
@@ -448,6 +1037,35 @@ export function getLocalSyncedTablePrimaryKeyColumns<TTable extends AnyPgTable>(
448
1037
  return [...(entry.clientProjection?.localPrimaryKey?.columns ?? entry.primaryKey.columns)];
449
1038
  }
450
1039
 
1040
+ /**
1041
+ * The Server version column (ADR-0010): the `nowMicroseconds`-on-update managed field a writable
1042
+ * table stamps on every write (conventionally `updated_at_us`), made strictly monotonic by the
1043
+ * applier. Returns its **column name**, resolving the managed field's drizzle property key. Returns
1044
+ * `undefined` when none is declared — registry validation rejects that for writable tables, so the
1045
+ * convergence barrier never has to degrade.
1046
+ */
1047
+ export function resolveServerVersionColumnName<TTable extends AnyPgTable>(
1048
+ entry: SyncTableEntry<TTable>,
1049
+ ): string | undefined {
1050
+ const field = (entry.governance?.managedFields ?? []).find(
1051
+ (managed) => managed.strategy === "nowMicroseconds" && managed.applyOn.includes("update"),
1052
+ );
1053
+
1054
+ if (!field) {
1055
+ return undefined;
1056
+ }
1057
+
1058
+ const columns = getColumns(entry.table);
1059
+ // `field.column` is the drizzle property key; resolve it to the underlying column name.
1060
+ const byProperty = (columns as Record<string, { name: string } | undefined>)[field.column as string];
1061
+ if (byProperty) {
1062
+ return byProperty.name;
1063
+ }
1064
+
1065
+ // Defensive: a managed field declared by column name rather than property key.
1066
+ return Object.values(columns).find((column) => column.name === field.column)?.name;
1067
+ }
1068
+
451
1069
  export function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry, schema?: string) {
452
1070
  const normalizedSchema = normalizeSchemaName(schema);
453
1071
 
@@ -468,10 +1086,14 @@ export function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(re
468
1086
  continue;
469
1087
  }
470
1088
 
1089
+ const qualify = (name: string) => (name.includes(".") ? name : `${normalizedSchema}.${name}`);
471
1090
  const qualifiedTableName = `${normalizedSchema}.${entry.shape.tableName}`;
472
1091
  entry.shape = {
473
1092
  ...entry.shape,
474
- ...(entry.shape.electricTable ? {} : { electricTable: qualifiedTableName }),
1093
+ // A read projection sets electricTable to the owner's (bare) physical name; qualify it the same
1094
+ // way the owner's own target is qualified, so both shapes hit one schema-qualified table on egress.
1095
+ // An owner (no electricTable) qualifies its own tableName. An already-qualified value is left as-is.
1096
+ electricTable: entry.shape.electricTable ? qualify(entry.shape.electricTable) : qualifiedTableName,
475
1097
  ...(entry.shape.shapeKey === entry.shape.tableName ? { shapeKey: qualifiedTableName } : {}),
476
1098
  };
477
1099
  }
@@ -515,6 +1137,112 @@ function getRegistryEntries<TRegistry extends SyncTableRegistry>(registry: TRegi
515
1137
  function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
516
1138
  const tableName = getTableConfig(entry.table).name;
517
1139
 
1140
+ // ADR-0029 P1: the client derives every synced-table object (the local synced read cache, and — for a
1141
+ // writable table — the overlay/journal) from this column-builder factory (getSyncedLocalTable →
1142
+ // projectedColumnBuilders), so it is hard-required at client boot. Promote the check to registry-build
1143
+ // time (better DX than an opaque engine-boot throw): defineSyncTable always stashes it, and every
1144
+ // projection (asReadonly / withRetention / defineReadProjection) carries it through — only a
1145
+ // hand-assembled entry can lack it, and such an entry cannot be synced.
1146
+ if (typeof entry.makeColumns !== "function") {
1147
+ throw new Error(
1148
+ `sync table ${tableName} has no makeColumns factory: every registered entry must be built by ` +
1149
+ `defineSyncTable (or a projection of one — asReadonly / asEphemeral / defineReadProjection), which ` +
1150
+ `stashes the column-builder factory the client requires (ADR-0029 P1) to derive its local ` +
1151
+ `synced/overlay/journal objects. Hand-assembled entries are unsupported.`,
1152
+ );
1153
+ }
1154
+
1155
+ // ADR-0010: a writable synced table must declare a Server version — a nowMicroseconds-on-update
1156
+ // managed field (conventionally updated_at_us) the applier stamps and keeps strictly monotonic.
1157
+ // Optimistic convergence is unsound without a per-row version (the barrier would degenerate to a
1158
+ // flicker-prone key-match), so this is a hard requirement, not a silent degraded fallback.
1159
+ if (entry.mode !== "readonly" && resolveServerVersionColumnName(entry) === undefined) {
1160
+ throw new Error(
1161
+ `writable table ${tableName} must declare a Server version: a managed field with strategy ` +
1162
+ `"nowMicroseconds" and applyOn including "update" (conventionally updated_at_us) — ADR-0010`,
1163
+ );
1164
+ }
1165
+
1166
+ // ADR-0015: every writable table must declare a Conflict policy — what happens to a stale write.
1167
+ // There is no silent default: silent last-write-wins is exactly the data loss the policy exists to
1168
+ // turn into a conscious per-table decision. This is the third hard-require (after the Server version
1169
+ // above and the server-PK-in-projection rule below), accepted as consistent with the footgun-averse
1170
+ // stance.
1171
+ if (entry.mode !== "readonly" && !isConflictPolicy(entry.conflictPolicy)) {
1172
+ throw new Error(
1173
+ `writable table ${tableName} must declare a Conflict policy (ADR-0015): conflictPolicy must be ` +
1174
+ `one of ${CONFLICT_POLICIES.join(", ")}` +
1175
+ (entry.conflictPolicy === undefined ? " (none was declared)" : ` (got ${String(entry.conflictPolicy)})`),
1176
+ );
1177
+ }
1178
+
1179
+ // ADR-0021: the lifecycle axes are optional (default eager/persistent), but a declared value must be
1180
+ // valid. Group-level uniformity (every table in a consistency group agrees) is checked at the
1181
+ // registry level in defineSyncRegistry, where the whole table set is visible.
1182
+ if (entry.subscription !== undefined && !isSubscriptionTiming(entry.subscription)) {
1183
+ throw new Error(
1184
+ `table ${tableName} has an invalid subscription (ADR-0021): must be one of ` +
1185
+ `${SUBSCRIPTION_TIMINGS.join(", ")} (got ${String(entry.subscription)})`,
1186
+ );
1187
+ }
1188
+ if (entry.retention !== undefined && !isRetention(entry.retention)) {
1189
+ throw new Error(
1190
+ `table ${tableName} has an invalid retention (ADR-0021): must be one of ` +
1191
+ `${RETENTIONS.join(", ")} (got ${String(entry.retention)})`,
1192
+ );
1193
+ }
1194
+
1195
+ // ADR-0022: write-mode is optional (default optimistic), but a declared value must be valid and
1196
+ // meaningful. `pessimistic` governs the write path, which a `readonly` table does not have, so reject
1197
+ // it there. Group-level uniformity is checked at the registry level alongside the lifecycle axes.
1198
+ if (entry.writeMode !== undefined && !isWriteMode(entry.writeMode)) {
1199
+ throw new Error(
1200
+ `table ${tableName} has an invalid writeMode (ADR-0022): must be one of ` +
1201
+ `${WRITE_MODES.join(", ")} (got ${String(entry.writeMode)})`,
1202
+ );
1203
+ }
1204
+ if (entry.writeMode === "pessimistic" && entry.mode === "readonly") {
1205
+ throw new Error(
1206
+ `readonly table ${tableName} cannot be pessimistic (ADR-0022): write-mode governs the write path, ` +
1207
+ `which a readonly table does not have. Declare writeMode only on a writable table.`,
1208
+ );
1209
+ }
1210
+
1211
+ // The single claim-stamping strategy (ADR-0026): an `authClaim` managed field reads a value from the
1212
+ // verified request claims at a JSON path, emitted into the apply-function DDL — so the path segments
1213
+ // must be plain identifiers and any cast a plain type name (never a value-injection surface). A
1214
+ // non-authClaim field carrying claimPath/cast is an authoring slip; reject it rather than ignore it.
1215
+ for (const field of entry.governance?.managedFields ?? []) {
1216
+ if (field.strategy === "authClaim") {
1217
+ if (!Array.isArray(field.claimPath) || field.claimPath.length === 0) {
1218
+ throw new Error(
1219
+ `managed field ${tableName}.${String(field.column)} (strategy "authClaim") must declare a non-empty ` +
1220
+ `claimPath (e.g. ["sub"] or ["app_metadata","person_id"]) — ADR-0026`,
1221
+ );
1222
+ }
1223
+ for (const segment of field.claimPath) {
1224
+ if (typeof segment !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment)) {
1225
+ throw new Error(
1226
+ `managed field ${tableName}.${String(field.column)} has an invalid claimPath segment ` +
1227
+ `${JSON.stringify(segment)}: each segment must match [A-Za-z_][A-Za-z0-9_]* (it is emitted into ` +
1228
+ `the apply-function DDL)`,
1229
+ );
1230
+ }
1231
+ }
1232
+ if (field.cast !== undefined && !/^[A-Za-z_][A-Za-z0-9_ ]*$/.test(field.cast)) {
1233
+ throw new Error(
1234
+ `managed field ${tableName}.${String(field.column)} has an invalid cast ${JSON.stringify(field.cast)}: ` +
1235
+ `must be a plain SQL type name (e.g. "uuid", "text")`,
1236
+ );
1237
+ }
1238
+ } else if (field.claimPath !== undefined || field.cast !== undefined) {
1239
+ throw new Error(
1240
+ `managed field ${tableName}.${String(field.column)} declares claimPath/cast but its strategy is ` +
1241
+ `"${field.strategy}" — those apply only to "authClaim"`,
1242
+ );
1243
+ }
1244
+ }
1245
+
518
1246
  const columns = Object.entries(getColumns(entry.table)).map(([propertyKey, column]) => ({
519
1247
  propertyKey,
520
1248
  columnName: column.name,