@pgxsinkit/contracts 0.2.7 → 0.5.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/dist/apply-strategy.d.ts +13 -1
  3. package/dist/apply-strategy.d.ts.map +1 -1
  4. package/dist/config.d.ts +256 -87
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +2 -2
  7. package/dist/convergence-model.d.ts.map +1 -1
  8. package/dist/event-stream.d.ts +1 -1
  9. package/dist/fingerprint.d.ts +31 -11
  10. package/dist/fingerprint.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +480 -202
  14. package/dist/index.js.map +16 -14
  15. package/dist/predicate.d.ts +162 -0
  16. package/dist/predicate.d.ts.map +1 -0
  17. package/dist/projection.d.ts +2 -2
  18. package/dist/projection.d.ts.map +1 -1
  19. package/dist/registry-diff.d.ts.map +1 -1
  20. package/dist/registry-invariant.d.ts +26 -14
  21. package/dist/registry-invariant.d.ts.map +1 -1
  22. package/dist/registry.d.ts +74 -48
  23. package/dist/registry.d.ts.map +1 -1
  24. package/dist/sql-role-guard.d.ts +1 -1
  25. package/dist/stream-envelope.d.ts +84 -0
  26. package/dist/stream-envelope.d.ts.map +1 -0
  27. package/dist/supabase-rls.d.ts +32 -36
  28. package/dist/supabase-rls.d.ts.map +1 -1
  29. package/package.json +3 -2
  30. package/skills/registry-authoring/SKILL.md +185 -185
  31. package/skills/registry-authoring/references/storage-engine-and-build.md +29 -0
  32. package/src/apply-strategy.ts +23 -4
  33. package/src/config.ts +340 -116
  34. package/src/convergence-model.ts +2 -2
  35. package/src/event-stream.ts +1 -1
  36. package/src/fingerprint.ts +76 -14
  37. package/src/index.ts +2 -0
  38. package/src/predicate.ts +274 -0
  39. package/src/projection.ts +6 -2
  40. package/src/registry-diff.ts +15 -4
  41. package/src/registry-invariant.ts +34 -19
  42. package/src/registry.ts +324 -78
  43. package/src/sql-role-guard.ts +1 -1
  44. package/src/stream-envelope.ts +91 -0
  45. package/src/supabase-rls.ts +76 -74
package/src/registry.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ColumnBuilderBase, InferInsertModel, InferSelectModel } from "drizzle-orm";
1
+ import type { AnyColumn, ColumnBuilderBase, InferInsertModel, InferSelectModel } from "drizzle-orm";
2
2
  import {
3
3
  bigint,
4
4
  getTableConfig,
@@ -30,11 +30,16 @@ import {
30
30
  isConflictPolicy,
31
31
  isRetention,
32
32
  isStorageBackend,
33
+ isStorageBuild,
33
34
  isStorageDurability,
35
+ isStorageEngineDeclaration,
34
36
  isSubscriptionTiming,
35
37
  isWriteMode,
38
+ assertShapeFilterIsEnforceable,
39
+ readShapeTier,
36
40
  RETENTIONS,
37
41
  STORAGE_BACKENDS,
42
+ STORAGE_BUILDS,
38
43
  STORAGE_DURABILITIES,
39
44
  SUBSCRIPTION_TIMINGS,
40
45
  WRITE_MODES,
@@ -64,6 +69,7 @@ import {
64
69
  isZodSchema,
65
70
  type EventStreamRegistry,
66
71
  } from "./event-stream";
72
+ import type { Predicate } from "./predicate";
67
73
 
68
74
  type PgSchemaType = ReturnType<typeof pgSchema>;
69
75
 
@@ -122,7 +128,7 @@ type SyncTableInputGovernanceMarker<TGovernance> = {
122
128
  export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTable extends AnyPgTable = TTable> {
123
129
  table: TTable;
124
130
  /**
125
- * Projected client-side table for PGlite use. Columns listed in
131
+ * Projected client-side table for pgwasm use. Columns listed in
126
132
  * `clientProjection.omitColumns` (e.g. `created_by_id`) are absent from
127
133
  * both the runtime table definition and the TypeScript shape of this table.
128
134
  */
@@ -133,12 +139,19 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
133
139
  mode: TableMode;
134
140
  primaryKey: PrimaryKeySpec;
135
141
  /**
136
- * CDC insert-apply policy (ADR-0045). Default `"insert"`: a server CDC `insert` is applied as a plain
137
- * INSERT, so a genuine primary-key collision surfaces (the ADR-0014 collision-surfacing invariant).
138
- * `"upsert"`: this table legitimately receives locally-derived provisional rows (e.g. written by a
139
- * local trigger from another synced table), so server CDC inserts are applied idempotently as
140
- * `INSERT … ON CONFLICT (pk) DO UPDATE` — the authoritative server row overwrites the provisional
141
- * local row instead of failing the commit. Resolved to `"insert"` when omitted.
142
+ * **Backfill** conflict policy (ADR-0045). Resolved to `"insert"` when omitted.
143
+ *
144
+ * This no longer selects how steady-state changes apply. The engine emits `upsert`, which states a
145
+ * row's value without claiming it is new, so every streamed change now applies as `INSERT … ON
146
+ * CONFLICT (pk) DO UPDATE` regardless of this setting. ADR-0014's plain-INSERT collision surfacing
147
+ * went with the `insert` verb it depended on.
148
+ *
149
+ * What survives is the **initial load**, which is a different question: a fresh subscription or a
150
+ * post-must-refetch re-snapshot lands on a table assumed empty, which is what lets it use COPY or a
151
+ * plain multi-row INSERT — neither of which can express `ON CONFLICT`. Set `"upsert"` when that
152
+ * assumption does not hold for this table, i.e. it legitimately receives locally-DERIVED provisional
153
+ * rows (e.g. a local trigger on another synced table inserts one here) that a backfill could meet.
154
+ * The backfill then takes the conflict-tolerant applier instead, at the cost of the faster path.
142
155
  */
143
156
  applyMode: "insert" | "upsert";
144
157
  /**
@@ -171,12 +184,12 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
171
184
  */
172
185
  conflictPolicy?: ConflictPolicy;
173
186
  /**
174
- * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced on one
175
- * `MultiShapeStream` and committed atomically at a shared LSN frontier, so a local reader never
176
- * sees one grouped table advanced past another for the same server transaction. Omitted → the
177
- * table is its own singleton group (independent frontier, no cross-table atomicity — the resolution
178
- * for a table that declares no group). The latency cost (a group advances only as fast as its
179
- * slowest shape) is contained to the tables that opt in.
187
+ * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced as one set
188
+ * of streams and committed atomically — held until every stream reports up-to-date, then applied in
189
+ * one transaction (ADR-0056) — so a local reader never sees one grouped table advanced past another
190
+ * for the same server transaction. Omitted → the table is its own singleton group (its own stream, no
191
+ * cross-table atomicity — the resolution for a table that declares no group). The latency cost (a
192
+ * group advances only as fast as its slowest shape) is contained to the tables that opt in.
180
193
  */
181
194
  consistencyGroup?: string;
182
195
  /**
@@ -308,19 +321,41 @@ export type SyncTableInputProjection<
308
321
  /**
309
322
  * A row filter for {@link defineSyncTable}'s `shape`, authored from the table's built, typed columns.
310
323
  * Reference columns through `c(columns.x)` exactly as `extras` does with its `self` argument, so
311
- * `customWhere` builds parameterized Electric `where`s from real, rename-safe column objects instead
324
+ * `customPredicate` builds the shape's predicate from real, rename-safe column objects instead
312
325
  * of hand-written column-name strings.
313
326
  */
314
327
  export type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> = (
315
328
  columns: PgBuildExtraConfigColumns<TColumns>,
316
329
  ) => RowFilterSpec;
317
330
 
318
- /** {@link ShapeSpecInput} whose `rowFilter` is authored from the built columns (typed by `TColumns`). */
331
+ /**
332
+ * The scope declaration for a SHARED-tier shape (ADR-0055), authored from the built, typed columns —
333
+ * the columns whose values key the shape family, in the order they parameterize it.
334
+ *
335
+ * Returning real column objects rather than names is what makes the family rename-safe: a renamed
336
+ * column moves the scope with it, where a string would have gone on naming a column that no longer
337
+ * exists and silently produced a predicate over nothing.
338
+ */
339
+ export type ScopeInput<TColumns extends Record<string, ColumnBuilderBase>> = (
340
+ columns: PgBuildExtraConfigColumns<TColumns>,
341
+ ) => readonly AnyColumn[];
342
+
343
+ /**
344
+ * The static, subscriber-independent half of a shape's native predicate, authored from the built,
345
+ * typed columns. Build it with {@link p} — `(c) => p.eq(c.published, true)`.
346
+ */
347
+ export type ShapeWhereInput<TColumns extends Record<string, ColumnBuilderBase>> = (
348
+ columns: PgBuildExtraConfigColumns<TColumns>,
349
+ ) => Predicate;
350
+
351
+ /** {@link ShapeSpecInput} whose callbacks are authored from the built columns (typed by `TColumns`). */
319
352
  export type ShapeSpecInputFor<TColumns extends Record<string, ColumnBuilderBase>> = Omit<
320
353
  ShapeSpecInput,
321
- "rowFilter"
354
+ "rowFilter" | "scope" | "where"
322
355
  > & {
323
356
  rowFilter?: RowFilterInput<TColumns>;
357
+ scope?: ScopeInput<TColumns>;
358
+ where?: ShapeWhereInput<TColumns>;
324
359
  };
325
360
 
326
361
  /**
@@ -364,14 +399,13 @@ export type SyncTableInput<
364
399
  */
365
400
  primaryKey?: string[] | { name: string; columns: string[] };
366
401
  /**
367
- * CDC insert-apply policy (ADR-0045). **Default `"insert"`** — a CDC insert is a plain INSERT, so a
368
- * genuine PK collision must surface (the ADR-0014 collision-surfacing invariant; a synced cache table
369
- * is server-authoritative and a duplicate insert is a real bug). Set `"upsert"` **only** when this
370
- * table legitimately receives locally-DERIVED provisional rows — e.g. a local trigger on another
371
- * synced table inserts a provisional row here, and the server independently creates the same row so
372
- * its CDC insert would collide (23505). With `"upsert"`, server CDC inserts are applied idempotently
373
- * as `INSERT … ON CONFLICT (pk) DO UPDATE`; the authoritative server row overwrites the provisional
374
- * local row. Declare the exception here, where it lives — do not weaken the invariant repo-wide.
402
+ * **Backfill** conflict policy (ADR-0045). **Default `"insert"`** — the initial load assumes an empty
403
+ * table (fresh subscription or post-must-refetch re-snapshot) and takes the fast path, COPY or a plain
404
+ * multi-row INSERT, neither of which can express `ON CONFLICT`. Set `"upsert"` **only** when this table
405
+ * legitimately receives locally-DERIVED provisional rows a backfill could land on top of — e.g. a local
406
+ * trigger on another synced table inserts a provisional row here, and the server independently creates
407
+ * the same row (23505). Steady-state changes are unaffected: the engine emits `upsert`, so they apply
408
+ * as `INSERT … ON CONFLICT (pk) DO UPDATE` for every table. See {@link SyncTableEntry.applyMode}.
375
409
  */
376
410
  applyMode?: "insert" | "upsert";
377
411
  /**
@@ -392,8 +426,8 @@ export type SyncTableInput<
392
426
  */
393
427
  conflictPolicy?: ConflictPolicy;
394
428
  /**
395
- * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync on one
396
- * `MultiShapeStream` and commit atomically. Omit for the default singleton group. See
429
+ * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync as one set of
430
+ * streams and commit atomically. Omit for the default singleton group. See
397
431
  * {@link SyncTableEntry.consistencyGroup}.
398
432
  */
399
433
  consistencyGroup?: string;
@@ -420,9 +454,11 @@ export interface SyncRegistryDefinition<TRegistry extends SyncTableRegistry> {
420
454
  /**
421
455
  * The storage contract for every store this registry mints (ADR-0049 decision 1, ADR-0047). Part of the
422
456
  * DATA contract, not a per-open knob: `durability` binds every toolkit-minted open (relaxed default),
423
- * and `backend` scopes the BROWSER store only (`opfs` default; Node/`file` and `memory` clones
424
- * unaffected). Validated at {@link defineSyncRegistry} (fail-closed at module-eval); carried through on
425
- * the returned registry and read back with {@link getSyncRegistryStorage}. See {@link SyncStorageDeclaration}.
457
+ * `backend` scopes the BROWSER store only (`opfs` default; Node/`file` and `memory` clones
458
+ * unaffected), and `engine` names the store-factory module that mints the store at all (absent default —
459
+ * the toolkit's own). Validated at {@link defineSyncRegistry} (fail-closed at module-eval); carried
460
+ * through on the returned registry and read back with {@link getSyncRegistryStorage}. See
461
+ * {@link SyncStorageDeclaration}.
426
462
  */
427
463
  storage?: SyncStorageDeclaration;
428
464
  /**
@@ -657,12 +693,13 @@ export function defineSyncTable<
657
693
  const columnLevelPkKeys = Object.entries(probeColumns)
658
694
  .filter(([, col]) => col.primary === true)
659
695
  .map(([key]) => key);
660
- const specPropertyKeys = primaryKeyColumns.map((key) => {
696
+ const toPropertyKey = (key: string, label: string) => {
661
697
  if (probeColumns[key]) return key;
662
698
  const byColumnName = Object.entries(probeColumns).find(([, col]) => col.name === key);
663
699
  if (byColumnName) return byColumnName[0];
664
- throw new Error(`[pgxsinkit] ${tableName}: primaryKey column "${key}" not found among the table's columns`);
665
- });
700
+ throw new Error(`[pgxsinkit] ${tableName}: ${label} column "${key}" not found among the table's columns`);
701
+ };
702
+ const specPropertyKeys = primaryKeyColumns.map((key) => toPropertyKey(key, "primaryKey"));
666
703
 
667
704
  if (columnLevelPkKeys.length > 1) {
668
705
  throw new Error(
@@ -719,25 +756,59 @@ export function defineSyncTable<
719
756
 
720
757
  // Resolve `shape.rowFilter` against the built typed columns so all authoring uses rename-safe
721
758
  // Drizzle column objects rather than hand-written column-name strings.
722
- const resolvedRowFilter = shape?.rowFilter?.(
723
- getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>,
724
- );
759
+ const shapeColumns = getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>;
760
+ const resolvedRowFilter = shape?.rowFilter?.(shapeColumns);
761
+ const resolvedScope = shape?.scope?.(shapeColumns).map((column) => column.name);
762
+ const resolvedWhere = shape?.where?.(shapeColumns);
725
763
  const resolvedShape: ShapeSpec | undefined =
726
764
  resolvedMode !== "writeonly" || shape != null
727
765
  ? {
728
766
  tableName: shape?.tableName ?? tableName,
729
767
  shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,
730
- // `electricTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its
768
+ // `physicalTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its
731
769
  // own table. It is filled by `attachSyncRegistrySchema` (schema qualification) or by
732
770
  // `defineReadProjection` (which points a projection at the owning physical table).
733
771
  ...(resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {}),
772
+ ...(resolvedScope != null ? { scope: resolvedScope } : {}),
773
+ ...(resolvedWhere != null ? { where: resolvedWhere } : {}),
734
774
  }
735
775
  : undefined;
736
776
 
777
+ // Read the tier for its side effect: a shape declaring both `scope` and `rowFilter` is refused
778
+ // HERE, at definition time, rather than at the first shape creation — the two are contradictory
779
+ // by construction, so there is no input for which it could later turn out to be fine.
780
+ if (resolvedShape != null) {
781
+ readShapeTier(resolvedShape);
782
+ assertShapeFilterIsEnforceable(resolvedShape);
783
+ }
784
+
737
785
  const omittedColumns = (clientProjection?.omitColumns ?? []) as TOmittedColumns;
738
786
  const projectedCols = viewColumnsForProjection(makeColumns(), omittedColumns);
787
+
788
+ // The local synced table carries its OWN primary key, mirroring exactly what the local-schema
789
+ // generator emits for it (`getLocalSyncPrimaryKeyColumns` → `buildTableColumnSql`) — including a
790
+ // `clientProjection.localPrimaryKey` narrowing, where the server's key columns may not even be
791
+ // projected. Stating it here keeps the drizzle object and the physical table in agreement; a
792
+ // localTable that claimed no key while its table had one stayed invisible only while the apply path
793
+ // was a plain INSERT plus `UPDATE … WHERE pk`, and became a 42P10 the moment anything said
794
+ // `ON CONFLICT (pk)` (ADR-0058 decision 3). Skipped when a single column already carries the flag
795
+ // itself, since drizzle would then render two primary keys.
796
+ const localPkPropertyKeys = (clientProjection?.localPrimaryKey?.columns ?? primaryKeyColumns).map((key) =>
797
+ toPropertyKey(key, "localPrimaryKey"),
798
+ );
799
+ const localPkIsColumnLevel =
800
+ localPkPropertyKeys.length === 1 && probeColumns[localPkPropertyKeys[0]!]?.primary === true;
801
+ const localExtrasFn = localPkIsColumnLevel
802
+ ? undefined
803
+ : (self: PgBuildExtraConfigColumns<Record<string, ColumnBuilderBase>>) => {
804
+ const selfCols = self as unknown as Record<string, AnyPgColumn>;
805
+ const pkColumns = localPkPropertyKeys.map((k) => selfCols[k]!) as [AnyPgColumn, ...AnyPgColumn[]];
806
+ return [pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];
807
+ };
739
808
  const localTable = (
740
- schema ? schema.table(tableName, projectedCols) : pgTable(tableName, projectedCols)
809
+ schema
810
+ ? schema.table(tableName, projectedCols, localExtrasFn as never)
811
+ : pgTable(tableName, projectedCols, localExtrasFn as never)
741
812
  ) as ProjectedLocalTable<TName, TColumns, TOmittedColumns>;
742
813
 
743
814
  const viewColumns = viewColumnsForProjection(makeColumns(), omittedColumns);
@@ -789,7 +860,7 @@ export function defineSyncTable<
789
860
  * not the jsonb), while the learner keeps reading the full table through the owner's shape.
790
861
  *
791
862
  * It is the *obvious, DRY* way to express "another shape over this table", versus the bare
792
- * `shape.electricTable` string it replaces (a footgun — config that silently un-asserts table
863
+ * `shape.physicalTable` string it replaces (a footgun — config that silently un-asserts table
793
864
  * ownership):
794
865
  *
795
866
  * - **Owns nothing.** The returned entry's `table` IS `owner.table` (the same object), so there is no
@@ -797,17 +868,17 @@ export function defineSyncTable<
797
868
  * and `shape` are its own. `readProjection` is set so generators skip it.
798
869
  * - **DRY columns.** `columns` is a typed subset of the owner's column keys; the local table is built by
799
870
  * filtering the owner's own column definitions (never restated), and the same subset becomes the
800
- * Electric `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The
871
+ * shape's `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The
801
872
  * primary key is always kept. Omit `columns` to sync every column.
802
- * - **Source is derived, never named.** The physical Electric target is taken from the owner — there is
803
- * no consumer-facing source field to get wrong (see {@link ShapeSpec.electricTable}).
804
- * - **Readonly.** A projection has no write path; the engine resolves an incoming shape request by its
805
- * unique `shapeKey` (= `as`) and consults the derived physical target only on egress.
873
+ * - **Source is derived, never named.** The physical source table is taken from the owner — there is
874
+ * no consumer-facing source field to get wrong (see {@link ShapeSpec.physicalTable}).
875
+ * - **Readonly.** A projection has no write path; the control plane resolves an incoming subscription by
876
+ * its unique `shapeKey` (= `as`) and consults the derived physical target when it creates the shape.
806
877
  *
807
- * The `rowFilter` callback receives the OWNER's full columns — `customWhere` runs in Electric against
878
+ * The `rowFilter` callback receives the OWNER's full columns — the predicate is evaluated against
808
879
  * the physical table, so it may reference a column the local subset omits. RLS for the projection's
809
880
  * reads lives on the OWNER's table (a projection adds no DDL to a table it does not own); its
810
- * `customWhere` must be a subset of what that RLS allows.
881
+ * `customPredicate` must be a subset of what that RLS allows.
811
882
  *
812
883
  * The `owner` may be a `defineSyncTable` entry OR an `asReadonly` of one — an `asReadonly` projection
813
884
  * preserves the full read contract (physical table, columns, primary key) and only drops the write path,
@@ -817,15 +888,16 @@ export function defineSyncTable<
817
888
  * ### Server-side egress redaction (`serverProjection` + `serverOnlyColumns`)
818
889
  *
819
890
  * A projection may carry its own `serverProjection` (a {@link ServerProjectionSpec}, typically a
820
- * `rowTransform`) — resolved by the projection's `shapeKey` and run on the proxy egress path for this
821
- * shape only. The order on egress is **transform first, then omission**: the transform runs against the
822
- * fetched row, then column omission strips this projection's omitted columns (the client keep-set is
823
- * `columns ∪ primaryKey`) before the row reaches the client wire. This lets a "secure window" over a
824
- * keyed table stream the body while stripping the keys per row.
891
+ * `rowTransform`) — resolved by the projection's `shapeKey` and run at the STREAM EDGE, per request, for
892
+ * this shape only (ADR-0055 decision 5). The order on egress is **transform first, then omission**: the
893
+ * transform runs against the fetched row, then the edge strips the row to the client keep-set
894
+ * (`columns ∪ primaryKey`) before it reaches the client wire. This lets a "secure window" over a keyed
895
+ * table stream the body while stripping the keys per row. Such a shape is private-tier by construction
896
+ * (its bytes depend on the reader) and is answered `cache-control: private, no-store`.
825
897
  *
826
898
  * `serverOnlyColumns` are owner column keys the transform must READ but that are NOT in the client shape
827
899
  * (e.g. a `keysWithheld` control flag). Such a key stays omitted from the client keep-set, yet is ADDED
828
- * to the Electric fetch allow-list — so it is fetched from Electric, visible to the transform, and then
900
+ * to the shape's `columns` allow-list — so it is fetched, visible to the transform, and then
829
901
  * stripped on egress by the same omission pass, never reaching the client. It requires a
830
902
  * `serverProjection.rowTransform` (a fetch no transform reads is dead weight) AND `columns` (with
831
903
  * `columns` omitted every column is already kept, so "server-only" is a contradiction), and must be
@@ -857,9 +929,9 @@ export function defineReadProjection<
857
929
  // accepted — `TOwnerTable` (the physical table) is what `columns`/`rowFilter` are typed against.
858
930
  owner: SyncTableEntry<TOwnerTable, TOwnerLocal>,
859
931
  opts: {
860
- /** The projection's distinct local identity — its PGlite table name AND its `shapeKey`. */
932
+ /** The projection's distinct local identity — its pgwasm table name AND its `shapeKey`. */
861
933
  as: TAs;
862
- /** Column keys (of the owner) to sync locally + fetch from Electric. The PK is always kept. Omit → all. */
934
+ /** Column keys (of the owner) to sync locally + fetch on the shape. The PK is always kept. Omit → all. */
863
935
  columns?: TColumns;
864
936
  /** Row filter for this shape; the callback form receives the owner's full (physical) columns. */
865
937
  rowFilter?: (columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec;
@@ -879,8 +951,8 @@ export function defineReadProjection<
879
951
  serverProjection?: ServerProjectionSpec | "unredacted";
880
952
  /**
881
953
  * Owner column keys the `serverProjection.rowTransform` must READ but which are NOT part of the client
882
- * shape (e.g. a `keysWithheld` control flag). They are added to the Electric fetch allow-list so the
883
- * transform can see them, then stripped on egress before the client wire. Requires
954
+ * shape (e.g. a `keysWithheld` control flag). They are added to the shape's `columns` allow-list so
955
+ * the transform can see them, then stripped on egress before the client wire. Requires
884
956
  * `serverProjection.rowTransform` and `columns`; must be disjoint from `columns` and the primary key.
885
957
  */
886
958
  serverOnlyColumns?: readonly TableColumnKey<TOwnerTable>[];
@@ -933,9 +1005,9 @@ export function defineReadProjection<
933
1005
  const omittedKeys = allKeys.filter((key) => !keep.has(key));
934
1006
 
935
1007
  // serverOnlyColumns — owner keys the egress rowTransform must READ but that are NOT in the client
936
- // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND the proxy strips them on
937
- // egress), yet are added to the Electric fetch allow-list below so the transform can see them. Each
938
- // guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.
1008
+ // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND egress strips them on
1009
+ // the way out), yet are added to the shape's `columns` allow-list below so the transform can see them.
1010
+ // Each guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.
939
1011
  // Fail-closed posture guard. A projection does NOT inherit its owner's egress `serverProjection`
940
1012
  // (see the docblock's no-inheritance caution: an inherited transform whose input column is unfetched
941
1013
  // reads `undefined` and fails OPEN — half-protection worse than none). So if the OWNER redacts on
@@ -994,7 +1066,7 @@ export function defineReadProjection<
994
1066
  if (!allKeys.includes(key)) {
995
1067
  throw new Error(
996
1068
  `defineReadProjection: projection "${opts.as}" serverOnlyColumns names "${key}", which is not a ` +
997
- `column of owner "${physicalTable}". It feeds the Electric fetch allow-list, so a typo would ` +
1069
+ `column of owner "${physicalTable}". It feeds the shape's "columns" allow-list, so a typo would ` +
998
1070
  `silently mis-fetch — name an existing owner column key.`,
999
1071
  );
1000
1072
  }
@@ -1024,15 +1096,18 @@ export function defineReadProjection<
1024
1096
  ...(opts.retention != null ? { retention: opts.retention } : {}),
1025
1097
  });
1026
1098
 
1027
- // Resolve the row filter against the OWNER's full columns (the customWhere runs in Electric on the
1099
+ // Resolve the row filter against the OWNER's full columns (the predicate is evaluated on the
1028
1100
  // physical table, so it may reference a column the subset omits).
1029
1101
  const resolvedRowFilter = opts.rowFilter?.(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>);
1030
1102
 
1031
- // When a subset is requested, set the Electric `columns` allow-list to the KEPT physical column names
1103
+ // When a subset is requested, set the shape's `columns` allow-list to the KEPT physical column names
1032
1104
  // so an omitted (e.g. heavy jsonb) column is never fetched over the wire — not merely stripped after.
1033
1105
  // serverOnlyColumns are added ON TOP of the kept names: a server-only column must be FETCHED (so the
1034
- // egress rowTransform can read it) even though it is omitted from the client keep-set — proxy omission
1035
- // then strips it after the transform runs. Resolve key -> physical name the same way getProjectedColumns
1106
+ // egress rowTransform can read it) even though it is omitted from the client keep-set. It is stripped
1107
+ // after the transform runs, at the STREAM EDGE — `createStreamGate` (packages/server/src/circuits/edge.ts)
1108
+ // rewrites each row of a transform shape's long-poll body and then narrows it to `entry.localTable`'s
1109
+ // columns, which is precisely this keep-set. So the column rides the engine's stream and comes off the
1110
+ // wire one hop before the client. Resolve key -> physical name the same way getProjectedColumns
1036
1111
  // does (the drizzle column's `.name`), never a hand-map. A full-width projection (no omitted keys, hence
1037
1112
  // no serverOnlyColumns — validated above) declares no allow-list at all.
1038
1113
  const ownerColumns = getColumns(owner.table) as Record<string, { name: string }>;
@@ -1051,10 +1126,14 @@ export function defineReadProjection<
1051
1126
  const shape: ShapeSpec = {
1052
1127
  tableName: opts.as,
1053
1128
  shapeKey: opts.as,
1054
- electricTable: physicalTable,
1129
+ physicalTable: physicalTable,
1055
1130
  ...(rowFilter != null ? { rowFilter } : {}),
1056
1131
  };
1057
1132
 
1133
+ // Same definition-time refusal the owning `defineSyncTable` performs: a projection's filter is a
1134
+ // filter, and one that cannot run here is the same unfiltered stream it would be there.
1135
+ assertShapeFilterIsEnforceable(shape);
1136
+
1058
1137
  // Point `table` at the owner's physical table and flag `readProjection` — that flag (not the absence of
1059
1138
  // a column factory) is what generators/appliers key on to skip owning-table work (see plpgsql-apply's
1060
1139
  // `!entry.readProjection` filter). The owner's `makeColumns` is KEPT (it rode in via `built`): since
@@ -1102,6 +1181,8 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
1102
1181
  validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);
1103
1182
  }
1104
1183
  validateRegistryTableUniqueness(input.tables);
1184
+ validateRegistryShapeKeyUniqueness(input.tables);
1185
+ validateRegistryLocalIndexNames(input.tables);
1105
1186
  validateRegistryLifecycleGroups(input.tables);
1106
1187
  validateStorageDeclaration(input.storage);
1107
1188
  validateRowClassification(input.tables, input.rowClasses);
@@ -1127,13 +1208,15 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
1127
1208
  validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);
1128
1209
  }
1129
1210
  validateRegistryTableUniqueness(input);
1211
+ validateRegistryShapeKeyUniqueness(input);
1212
+ validateRegistryLocalIndexNames(input);
1130
1213
  validateRegistryLifecycleGroups(input);
1131
1214
 
1132
1215
  return input;
1133
1216
  }
1134
1217
 
1135
1218
  /** The local/shape identity an entry resolves to: its `shape.tableName` (the unique shape key a client
1136
- * requests and the local PGlite table), falling back to the Drizzle table name when an entry has no
1219
+ * requests and the local pgwasm table), falling back to the Drizzle table name when an entry has no
1137
1220
  * shape (a write-only table). A read projection carries a distinct `shape.tableName` (`as`) even though
1138
1221
  * its `table` is the owner's, so it is identified here by `as`, never by the shared physical table. */
1139
1222
  function localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {
@@ -1142,10 +1225,10 @@ function localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {
1142
1225
 
1143
1226
  /**
1144
1227
  * A registry must not declare the same local table twice. Every entry resolves to one local identity
1145
- * ({@link localShapeIdentity}) — the PGlite table a client reads and the `shapeKey` the proxy resolves a
1228
+ * ({@link localShapeIdentity}) — the pgwasm table a client reads and the `shapeKey` the proxy resolves a
1146
1229
  * request by — so two entries sharing it would collide locally (one shadows the other) and make the
1147
1230
  * shape unresolvable. A read PROJECTION over a shared physical table does NOT trip this: it carries a
1148
- * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.electricTable`,
1231
+ * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.physicalTable`,
1149
1232
  * so several shapes read one physical table while their local identities stay unique. Fails closed at
1150
1233
  * module-eval, for every consumer.
1151
1234
  */
@@ -1168,9 +1251,69 @@ function validateRegistryTableUniqueness(registry: SyncTableRegistry) {
1168
1251
  }
1169
1252
  }
1170
1253
 
1254
+ /**
1255
+ * A local index NAME is a SCHEMA-level object name, so two entries declaring the same
1256
+ * `clientProjection.localIndexes` name collide across tables — and the collision is SILENT: the generator
1257
+ * emits `CREATE INDEX IF NOT EXISTS`, which matches on the name alone, so the second table simply never
1258
+ * gets its index and the read it was declared for quietly scans. Per-entry uniqueness (checked with the
1259
+ * rest of the declaration in `validateSyncTableEntry`) cannot see that, so it is checked here, once per
1260
+ * registry, at module eval.
1261
+ */
1262
+ function validateRegistryLocalIndexNames(registry: SyncTableRegistry) {
1263
+ const declaredBy = new Map<string, string>();
1264
+
1265
+ for (const [key, entry] of Object.entries(registry)) {
1266
+ for (const index of (entry as SyncTableEntry<AnyPgTable>).clientProjection?.localIndexes ?? []) {
1267
+ const firstKey = declaredBy.get(index.name);
1268
+ if (firstKey !== undefined) {
1269
+ throw new Error(
1270
+ `local index "${index.name}" is declared by two registry entries ("${firstKey}" and "${key}"): ` +
1271
+ `an index name is a schema-level object name, and the generator's CREATE INDEX IF NOT EXISTS ` +
1272
+ `would silently skip the second one. Name each local index after its own table.`,
1273
+ );
1274
+ }
1275
+ declaredBy.set(index.name, key);
1276
+ }
1277
+ }
1278
+ }
1279
+
1280
+ /**
1281
+ * A registry must not expose the same PUBLIC `shapeKey` twice. This is a DISTINCT identity from the
1282
+ * local table checked by {@link validateRegistryTableUniqueness}: `shapeKey` is what a subscription
1283
+ * request names on the wire and what the control plane resolves an entry by (`resolveEntryByShapeKey`
1284
+ * is first-match), while the local identity is the pgwasm table a client reads into. They coincide by
1285
+ * default (`shapeKey` falls back to `tableName`), so the local check already covers the common case,
1286
+ * and read projections over one physical table stay legal because `as` yields a distinct value for
1287
+ * BOTH identities. The only way to collide here is an EXPLICIT `shape.shapeKey` that diverges from the
1288
+ * table name: two such entries would leave the second permanently unreachable, silently served the
1289
+ * first's shape (and therefore the first's row filter). Write-only entries carry no shape and are
1290
+ * skipped — they are not publicly requestable. Fails closed at module-eval, for every consumer.
1291
+ */
1292
+ function validateRegistryShapeKeyUniqueness(registry: SyncTableRegistry) {
1293
+ const declaredBy = new Map<string, string>();
1294
+
1295
+ for (const [key, entry] of Object.entries(registry)) {
1296
+ const shape = (entry as SyncTableEntry<AnyPgTable>).shape;
1297
+ if (shape === undefined) continue;
1298
+
1299
+ const firstKey = declaredBy.get(shape.shapeKey);
1300
+
1301
+ if (firstKey !== undefined) {
1302
+ throw new Error(
1303
+ `shapeKey "${shape.shapeKey}" is declared by two registry entries ("${firstKey}" and "${key}"): ` +
1304
+ `a duplicate shapeKey makes the second entry unreachable — the control plane resolves a ` +
1305
+ `subscription by shapeKey and would serve the first entry's shape. Give each entry a unique ` +
1306
+ `shape.shapeKey, or use defineReadProjection (a distinct "as") for a second shape over one table.`,
1307
+ );
1308
+ }
1309
+
1310
+ declaredBy.set(shape.shapeKey, key);
1311
+ }
1312
+ }
1313
+
1171
1314
  /**
1172
1315
  * ADR-0021 §4 / ADR-0022 §1–2: subscription timing, retention, and write-mode are properties of a
1173
- * **consistency group**, not a single table — a group commits atomically on one `MultiShapeStream`
1316
+ * **consistency group**, not a single table — a group's streams commit atomically together
1174
1317
  * (so it cannot be partly lazy or partly ephemeral) and a consistency group *is* the static
1175
1318
  * write-unit (so it cannot be partly pessimistic). Reject a registry whose grouped tables disagree on
1176
1319
  * any of the three. Tables without a `consistencyGroup` are their own singleton group and are
@@ -1365,10 +1508,10 @@ export function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(re
1365
1508
  const qualifiedTableName = `${normalizedSchema}.${entry.shape.tableName}`;
1366
1509
  entry.shape = {
1367
1510
  ...entry.shape,
1368
- // A read projection sets electricTable to the owner's (bare) physical name; qualify it the same
1511
+ // A read projection sets physicalTable to the owner's (bare) physical name; qualify it the same
1369
1512
  // way the owner's own target is qualified, so both shapes hit one schema-qualified table on egress.
1370
- // An owner (no electricTable) qualifies its own tableName. An already-qualified value is left as-is.
1371
- electricTable: entry.shape.electricTable ? qualify(entry.shape.electricTable) : qualifiedTableName,
1513
+ // An owner (no physicalTable) qualifies its own tableName. An already-qualified value is left as-is.
1514
+ physicalTable: entry.shape.physicalTable ? qualify(entry.shape.physicalTable) : qualifiedTableName,
1372
1515
  ...(entry.shape.shapeKey === entry.shape.tableName ? { shapeKey: qualifiedTableName } : {}),
1373
1516
  };
1374
1517
  }
@@ -1404,11 +1547,15 @@ export function attachSyncRegistryStorage<TRegistry extends SyncTableRegistry>(
1404
1547
  }
1405
1548
  // Idempotent for an EQUAL declaration (a registry value reused across constructions may be re-stamped with
1406
1549
  // the same contract) but fail-closed on a CONFLICT — two different storage contracts over one registry is a
1407
- // definition error, never silently resolved. `backend`/`durability` are the only fields, so a shallow
1408
- // compare is exhaustive.
1550
+ // definition error, never silently resolved. `backend`/`durability`/`engine` are the only fields, and
1551
+ // `engine`'s identity is its module URL, so comparing those three is exhaustive.
1409
1552
  const existing = getSyncRegistryStorage(registry);
1410
1553
  if (existing != null) {
1411
- if (existing.backend !== storage.backend || existing.durability !== storage.durability) {
1554
+ if (
1555
+ existing.backend !== storage.backend ||
1556
+ existing.durability !== storage.durability ||
1557
+ existing.engine?.module !== storage.engine?.module
1558
+ ) {
1412
1559
  throw new Error(
1413
1560
  `conflicting storage declaration for registry: already ${JSON.stringify(existing)}, cannot re-declare ` +
1414
1561
  `${JSON.stringify(storage)}`,
@@ -1702,9 +1849,10 @@ function validateRowClassification(registry: SyncTableRegistry, rowClasses: read
1702
1849
  }
1703
1850
 
1704
1851
  /**
1705
- * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` must
1706
- * be a known value, matching how the other registry axes reject bad input at `defineSyncRegistry`. An absent
1707
- * declaration or absent field is fine — it resolves to the ADR-0047 defaults (`opfs` / `relaxed`).
1852
+ * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` /
1853
+ * `storage.build` / `storage.engine` must be a known value, matching how the other registry axes reject bad
1854
+ * input at `defineSyncRegistry`. An absent declaration or absent field is fine — it resolves to the
1855
+ * defaults (`opfs` / `relaxed` / `c`) and, for `engine`, to the toolkit's own store.
1708
1856
  */
1709
1857
  function validateStorageDeclaration(storage: SyncStorageDeclaration | undefined) {
1710
1858
  if (storage == null) {
@@ -1720,6 +1868,16 @@ function validateStorageDeclaration(storage: SyncStorageDeclaration | undefined)
1720
1868
  `invalid storage.durability "${String(storage.durability)}": must be one of ${STORAGE_DURABILITIES.join(", ")}`,
1721
1869
  );
1722
1870
  }
1871
+ if (storage.build !== undefined && !isStorageBuild(storage.build)) {
1872
+ throw new Error(`invalid storage.build "${String(storage.build)}": must be one of ${STORAGE_BUILDS.join(", ")}`);
1873
+ }
1874
+ if (storage.engine !== undefined && !isStorageEngineDeclaration(storage.engine)) {
1875
+ throw new Error(
1876
+ `invalid storage.engine ${JSON.stringify(storage.engine)}: must be { module } naming an ABSOLUTE ` +
1877
+ `("https://host/factory.js") or ORIGIN-RELATIVE ("/store-engine/factory.js") module URL the engine ` +
1878
+ `home can import — a document-relative specifier resolves differently in a worker scope`,
1879
+ );
1880
+ }
1723
1881
  }
1724
1882
 
1725
1883
  function isSyncRegistryDefinition<TRegistry extends SyncTableRegistry>(
@@ -1761,6 +1919,24 @@ function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
1761
1919
  );
1762
1920
  }
1763
1921
 
1922
+ // ADR-0055 decision 5: an egress `serverProjection.rowTransform` makes the shape's bytes a function
1923
+ // of the SUBJECT — the stream edge rewrites them per request, with the subject from the stream
1924
+ // token — so the shape is private-tier BY CONSTRUCTION and cannot be served from a scope-keyed
1925
+ // shared stream. Letting the two ride together would produce exactly what `readShapeTier` refuses
1926
+ // for `scope` + `rowFilter`: a stream cached under a scope key while carrying subject-dependent
1927
+ // bytes, which is a disclosure rather than a stale row. Checked HERE rather than in `readShapeTier`
1928
+ // because the transform lives on the ENTRY (a projection attaches it after its shape is built), and
1929
+ // this is the one validation every registrable entry passes through, projections included.
1930
+ if (entry.serverProjection?.rowTransform != null && entry.shape?.scope != null) {
1931
+ throw new Error(
1932
+ `[pgxsinkit] shape "${entry.shape.shapeKey}" declares both scope and a serverProjection.rowTransform ` +
1933
+ `— an egress transform rewrites the stream's bytes per request with the reader's subject, so the ` +
1934
+ `shape is private-tier by construction (ADR-0055 decision 5) and cannot be served from a ` +
1935
+ `scope-keyed shared stream. Drop the transform and pre-compute the redaction into a column the ` +
1936
+ `shape projects, or drop scope and keep this shape private.`,
1937
+ );
1938
+ }
1939
+
1764
1940
  // ADR-0010: a writable synced table must declare a Server version — a nowMicroseconds-on-update
1765
1941
  // managed field (conventionally updated_at_us) the applier stamps and keeps strictly monotonic.
1766
1942
  // Optimistic convergence is unsound without a per-row version (the barrier would degenerate to a
@@ -1876,6 +2052,8 @@ function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
1876
2052
  const omitColumns = entry.clientProjection?.omitColumns ?? [];
1877
2053
  const localPrimaryKeyColumns = entry.clientProjection?.localPrimaryKey?.columns ?? [];
1878
2054
 
2055
+ validateLocalIndexes(entry, tableName, columnsByPropertyKey, columnsByColumnName, omitColumns);
2056
+
1879
2057
  if (omitColumns.length === 0 && localPrimaryKeyColumns.length === 0) {
1880
2058
  return;
1881
2059
  }
@@ -1956,3 +2134,71 @@ function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
1956
2134
  );
1957
2135
  }
1958
2136
  }
2137
+
2138
+ /**
2139
+ * Refuse a `clientProjection.localIndexes` declaration the local schema generator could not render
2140
+ * faithfully — at REGISTRY-BUILD time (module eval), never at boot: a store that has already been created
2141
+ * cannot report a typo in a column name in any useful way, and a half-rendered index set is worse than a
2142
+ * refused registry.
2143
+ *
2144
+ * Four refusals, each with the thing the author has to change in the message: an unknown column, a column
2145
+ * the client projection omits (the local table has no such column — the index would target a column that
2146
+ * exists only on the server), a duplicate index name within the entry, and a name that is not a plain
2147
+ * identifier (it is emitted into DDL). An empty column list is refused for the same reason.
2148
+ */
2149
+ function validateLocalIndexes(
2150
+ entry: SyncTableEntry<AnyPgTable>,
2151
+ tableName: string,
2152
+ columnsByPropertyKey: Map<string, { propertyKey: string; columnName: string }>,
2153
+ columnsByColumnName: Map<string, { propertyKey: string; columnName: string }>,
2154
+ omitColumns: readonly string[],
2155
+ ): void {
2156
+ const localIndexes = entry.clientProjection?.localIndexes ?? [];
2157
+ if (localIndexes.length === 0) {
2158
+ return;
2159
+ }
2160
+
2161
+ // Omission is declared by property key; a column may be named either way in an index, so both keys of
2162
+ // an omitted column are refused.
2163
+ const omitted = new Set<string>();
2164
+ for (const propertyKey of omitColumns) {
2165
+ omitted.add(propertyKey);
2166
+ const column = columnsByPropertyKey.get(propertyKey);
2167
+ if (column) omitted.add(column.columnName);
2168
+ }
2169
+
2170
+ const seenNames = new Set<string>();
2171
+ for (const index of localIndexes) {
2172
+ if (typeof index.name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(index.name)) {
2173
+ throw new Error(
2174
+ `clientProjection.localIndexes on ${tableName} declares an invalid index name ${JSON.stringify(index.name)}: ` +
2175
+ `it is emitted into DDL, so it must be a plain identifier ([A-Za-z_][A-Za-z0-9_]*)`,
2176
+ );
2177
+ }
2178
+ if (seenNames.has(index.name)) {
2179
+ throw new Error(
2180
+ `clientProjection.localIndexes on ${tableName} declares the index name "${index.name}" twice: ` +
2181
+ `an index name must be unique (it is a schema-level object name)`,
2182
+ );
2183
+ }
2184
+ seenNames.add(index.name);
2185
+
2186
+ if (index.columns.length === 0) {
2187
+ throw new Error(`clientProjection.localIndexes on ${tableName}: index "${index.name}" declares no columns`);
2188
+ }
2189
+
2190
+ for (const column of index.columns) {
2191
+ if (omitted.has(column)) {
2192
+ throw new Error(
2193
+ `clientProjection.localIndexes on ${tableName}: index "${index.name}" names column "${column}", which ` +
2194
+ `clientProjection.omitColumns removes from the local table — index only projected columns`,
2195
+ );
2196
+ }
2197
+ if (!columnsByPropertyKey.has(column) && !columnsByColumnName.has(column)) {
2198
+ throw new Error(
2199
+ `clientProjection.localIndexes on ${tableName}: index "${index.name}" names unknown column "${column}"`,
2200
+ );
2201
+ }
2202
+ }
2203
+ }
2204
+ }