@syncular/client 0.47.0 → 0.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -3333,12 +3333,21 @@ export class SyncClient {
3333
3333
  legacyCause: `sync.invalid_request: table ${table.name}: ${refusal}`,
3334
3334
  },
3335
3335
  );
3336
+ // §7.1 insert intent: a full-row write of a row the replica does not
3337
+ // show replays and encodes as a full row under every later schema.
3338
+ const insert =
3339
+ mutation.op !== 'patch' &&
3340
+ this.#db.query(
3341
+ `SELECT 1 FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=? LIMIT 1`,
3342
+ [pkSqlValue(table, pkValue)],
3343
+ ).length === 0;
3336
3344
  return definedObject({
3337
3345
  table: mutation.table,
3338
3346
  rowId: pkValue,
3339
3347
  op: 'upsert',
3340
3348
  baseVersion: mutation.baseVersion,
3341
3349
  values: json,
3350
+ insert: insert ? true : undefined,
3342
3351
  });
3343
3352
  });
3344
3353
  this.#applyBatch((batch) => {
@@ -6207,9 +6216,23 @@ export class SyncClient {
6207
6216
  // §7.1 overlay: apply the operation's PRESENT columns over the current
6208
6217
  // local row. A partial operation over an absent local row leaves it
6209
6218
  // absent — the server answers it with sync.row_deleted or
6210
- // sync.row_missing, and the local mirror never invents a base.
6219
+ // sync.row_missing, and the local mirror never invents a base. An
6220
+ // insert-intent operation is a full row: a column it lacks is NULL.
6211
6221
  const opValues = op.values ?? {};
6212
- const full = table.columns.every((column) => column.name in opValues);
6222
+ const full =
6223
+ op.insert === true ||
6224
+ table.columns.every((column) => column.name in opValues);
6225
+ // An insert lacking a non-nullable column cannot encode (§7.4.4); it
6226
+ // stays hidden until the send-time drop classifies it.
6227
+ if (
6228
+ op.insert === true &&
6229
+ table.columns.some(
6230
+ (column) => !column.nullable && opValues[column.name] === undefined,
6231
+ )
6232
+ ) {
6233
+ if (batch !== undefined && !precise) batch.table(op.table);
6234
+ continue;
6235
+ }
6213
6236
  const local = this.#db.query(
6214
6237
  `SELECT * FROM ${quoteIdent(table.name)} WHERE ${quoteIdent(table.primaryKey)}=?`,
6215
6238
  [pkSqlValue(table, op.rowId)],
@@ -6221,7 +6244,7 @@ export class SyncClient {
6221
6244
  const values = table.columns.map((column) => {
6222
6245
  const value = opValues[column.name];
6223
6246
  if (value !== undefined) return jsonToRowValue(value);
6224
- return local === undefined
6247
+ return local === undefined || op.insert === true
6225
6248
  ? null
6226
6249
  : replay
6227
6250
  ? (coerceSqlRepresentation(
package/src/multi-tab.ts CHANGED
@@ -20,7 +20,8 @@
20
20
  * — "I am the leader, this epoch";
21
21
  * the answer to every hello
22
22
  * res {t,epoch,reqId,ok,value|error} — reply to one req
23
- * event {t,epoch,event} — fan-out (invalidate/presence/…)
23
+ * event {t,epoch,event,to?} — fan-out (invalidate/presence/…),
24
+ * or one tab's event when `to` is set
24
25
  *
25
26
  * Epoch (leader generation token): a monotonic counter carried in a shared
26
27
  * BroadcastChannel and bumped by every promotion. Followers stamp requests
@@ -57,8 +58,18 @@
57
58
  * is exactly ONE presence peer collectively — `(actorId, leaderClientId)`.
58
59
  * A follower's `setPresence` forwards to the leader's single publisher; there
59
60
  * is no per-tab presence peer (documented in the web-client README).
61
+ *
62
+ * Tab lifetime: every tab of a {@link TabCoordinator} holds an exclusive Web
63
+ * Lock named for its tab id until it closes. A leader whose core keeps per-tab
64
+ * state waits on that lock for each tab that called it; the grant means the
65
+ * tab is gone.
60
66
  */
61
67
  import { ClientSyncError } from './errors';
68
+ import {
69
+ type LeaderLease,
70
+ type LeaderLock,
71
+ webLocksLeaderLock,
72
+ } from './leader-lock';
62
73
  import type { SyncWorkerEvent } from './worker-protocol';
63
74
  import { WORKER_FAILED_CODE } from './worker-protocol';
64
75
 
@@ -76,7 +87,7 @@ export const LEADER_HANDOVER_CODE = 'client.leader_handover';
76
87
  * with every change to a message shape or to a forwarded method's arguments
77
88
  * or result, so tabs of different builds never serve each other.
78
89
  */
79
- export const MULTI_TAB_PROTOCOL_VERSION = 1;
90
+ export const MULTI_TAB_PROTOCOL_VERSION = 2;
80
91
 
81
92
  /** What a tab must share with its leader to be served by it. */
82
93
  export interface TabIdentity {
@@ -179,39 +190,43 @@ interface ResMessage {
179
190
  };
180
191
  }
181
192
 
182
- interface EventMessage {
193
+ interface EventMessage<E> {
183
194
  readonly t: 'event';
184
195
  readonly epoch: number;
185
- readonly event: SyncWorkerEvent;
196
+ readonly event: E;
197
+ /** The one tab this event is for; absent for a fan-out to every tab. */
198
+ readonly to?: string;
186
199
  }
187
200
 
188
- export type MultiTabMessage =
201
+ export type MultiTabMessage<E = SyncWorkerEvent> =
189
202
  | HelloMessage
190
203
  | ReqMessage
191
204
  | AnnounceMessage
192
205
  | ResMessage
193
- | EventMessage;
206
+ | EventMessage<E>;
194
207
 
195
208
  /**
196
209
  * The tiny cross-tab channel surface we depend on — the DOM `BroadcastChannel`
197
210
  * satisfies it. Injectable so bun tests can pair two instances by name.
198
211
  */
199
- export interface CrossTabChannel {
200
- postMessage(message: MultiTabMessage): void;
212
+ export interface CrossTabChannel<E = SyncWorkerEvent> {
213
+ postMessage(message: MultiTabMessage<E>): void;
201
214
  addEventListener(
202
215
  type: 'message',
203
- listener: (event: { data: MultiTabMessage }) => void,
216
+ listener: (event: { data: MultiTabMessage<E> }) => void,
204
217
  ): void;
205
218
  removeEventListener(
206
219
  type: 'message',
207
- listener: (event: { data: MultiTabMessage }) => void,
220
+ listener: (event: { data: MultiTabMessage<E> }) => void,
208
221
  ): void;
209
222
  close(): void;
210
223
  }
211
224
 
212
225
  /** Default channel factory: a real `BroadcastChannel` named per lock. */
213
- export function broadcastChannelFactory(): (name: string) => CrossTabChannel {
214
- return (name) => new BroadcastChannel(name) as unknown as CrossTabChannel;
226
+ export function broadcastChannelFactory<E = SyncWorkerEvent>(): (
227
+ name: string,
228
+ ) => CrossTabChannel<E> {
229
+ return (name) => new BroadcastChannel(name) as unknown as CrossTabChannel<E>;
215
230
  }
216
231
 
217
232
  /** The channel name a leader and its followers rendezvous on. */
@@ -235,31 +250,39 @@ export function newTabId(): string {
235
250
 
236
251
  /**
237
252
  * Runs on the leader tab. Announces leadership, answers follower `req`s by
238
- * invoking the (already-running) worker via `invoke`, and rebroadcasts every
239
- * worker event to followers. Owns nothing about the worker lifecycle — the
240
- * worker-host stays the single core owner; this is a relay. A hello from a
241
- * newer tab calls `onNewerTab`, whose owner closes the core and releases the
242
- * lock.
253
+ * invoking the (already-running) core via `invoke` with the calling tab's id,
254
+ * and relays core events to followers. Owns nothing about the core lifecycle;
255
+ * this is a relay. `onFirstCall` runs once per tab, at its first request. A
256
+ * hello from a newer tab calls `onNewerTab`, whose owner closes the core and
257
+ * releases the lock.
243
258
  */
244
- export class LeaderBridge {
245
- readonly #channel: CrossTabChannel;
259
+ export class LeaderBridge<E = SyncWorkerEvent> {
260
+ readonly #channel: CrossTabChannel<E>;
246
261
  readonly #epoch: number;
247
262
  readonly #clientId: string;
248
263
  readonly #identity: TabIdentity;
249
264
  readonly #invoke: (
265
+ tabId: string,
250
266
  method: string,
251
267
  args: readonly unknown[],
252
268
  ) => Promise<unknown>;
269
+ readonly #onFirstCall: ((tabId: string) => void) | undefined;
253
270
  readonly #onNewerTab: () => void;
254
- readonly #onMessage: (event: { data: MultiTabMessage }) => void;
271
+ readonly #onMessage: (event: { data: MultiTabMessage<E> }) => void;
272
+ readonly #callers = new Set<string>();
255
273
  #closed = false;
256
274
 
257
275
  constructor(options: {
258
- channel: CrossTabChannel;
276
+ channel: CrossTabChannel<E>;
259
277
  epoch: number;
260
278
  clientId: string;
261
279
  identity: TabIdentity;
262
- invoke: (method: string, args: readonly unknown[]) => Promise<unknown>;
280
+ invoke: (
281
+ tabId: string,
282
+ method: string,
283
+ args: readonly unknown[],
284
+ ) => Promise<unknown>;
285
+ onFirstCall?: (tabId: string) => void;
263
286
  onNewerTab: () => void;
264
287
  }) {
265
288
  this.#channel = options.channel;
@@ -267,6 +290,7 @@ export class LeaderBridge {
267
290
  this.#clientId = options.clientId;
268
291
  this.#identity = options.identity;
269
292
  this.#invoke = options.invoke;
293
+ this.#onFirstCall = options.onFirstCall;
270
294
  this.#onNewerTab = options.onNewerTab;
271
295
  this.#onMessage = (event) => this.#handle(event.data);
272
296
  this.#channel.addEventListener('message', this.#onMessage);
@@ -284,13 +308,24 @@ export class LeaderBridge {
284
308
  });
285
309
  }
286
310
 
287
- /** Fan a worker event out to all followers on the current epoch. */
288
- broadcastEvent(event: SyncWorkerEvent): void {
311
+ /** Fan an event out to all followers on the current epoch. */
312
+ broadcastEvent(event: E): void {
289
313
  if (this.#closed) return;
290
314
  this.#channel.postMessage({ t: 'event', epoch: this.#epoch, event });
291
315
  }
292
316
 
293
- #handle(message: MultiTabMessage): void {
317
+ /** Post an event that only the follower `tabId` delivers. */
318
+ sendEvent(tabId: string, event: E): void {
319
+ if (this.#closed) return;
320
+ this.#channel.postMessage({
321
+ t: 'event',
322
+ epoch: this.#epoch,
323
+ event,
324
+ to: tabId,
325
+ });
326
+ }
327
+
328
+ #handle(message: MultiTabMessage<E>): void {
294
329
  if (this.#closed) return;
295
330
  if (message.t === 'hello') {
296
331
  // A newer tab takes over; any other follower learns who leads.
@@ -306,7 +341,7 @@ export class LeaderBridge {
306
341
  // Ignore requests stamped for a different (dead/older) leader; that
307
342
  // follower will re-stamp once it sees our announce.
308
343
  if (message.epoch !== this.#epoch) return;
309
- const { reqId, method, args } = message;
344
+ const { reqId, method, args, fromId } = message;
310
345
  if (compareTabIdentity(message, this.#identity) !== 0) {
311
346
  this.#channel.postMessage({
312
347
  t: 'res',
@@ -321,8 +356,12 @@ export class LeaderBridge {
321
356
  });
322
357
  return;
323
358
  }
359
+ if (!this.#callers.has(fromId)) {
360
+ this.#callers.add(fromId);
361
+ this.#onFirstCall?.(fromId);
362
+ }
324
363
  // A call can outlive close(); a closed BroadcastChannel throws on post.
325
- this.#invoke(method, args).then(
364
+ this.#invoke(fromId, method, args).then(
326
365
  (value) => {
327
366
  if (this.#closed) return;
328
367
  this.#channel.postMessage({
@@ -403,11 +442,11 @@ interface InFlight {
403
442
  * when a probe goes unanswered, or when the leader's identity differs from
404
443
  * this tab's (see the module comment).
405
444
  */
406
- export class FollowerLink {
407
- readonly #channel: CrossTabChannel;
445
+ export class FollowerLink<E = SyncWorkerEvent> {
446
+ readonly #channel: CrossTabChannel<E>;
408
447
  readonly #fromId: string;
409
448
  readonly #identity: TabIdentity;
410
- readonly #onEvent: (event: SyncWorkerEvent) => void;
449
+ readonly #onEvent: (event: E) => void;
411
450
  readonly #onLeaderChange: (clientId: string) => void;
412
451
  readonly #onStateChange: (state: LeadershipState) => void;
413
452
  readonly #callTimeoutMs: number;
@@ -415,7 +454,7 @@ export class FollowerLink {
415
454
  readonly #probeAfterMs: number;
416
455
  readonly #queueLimit: number;
417
456
  readonly #schedule: FollowerSchedule;
418
- readonly #onMessage: (event: { data: MultiTabMessage }) => void;
457
+ readonly #onMessage: (event: { data: MultiTabMessage<E> }) => void;
419
458
 
420
459
  /** -1 until the first `announce` binds us to a leader. */
421
460
  #epoch = -1;
@@ -436,10 +475,10 @@ export class FollowerLink {
436
475
  #bindWaiters: Array<() => void> = [];
437
476
 
438
477
  constructor(options: {
439
- channel: CrossTabChannel;
478
+ channel: CrossTabChannel<E>;
440
479
  fromId: string;
441
480
  identity: TabIdentity;
442
- onEvent: (event: SyncWorkerEvent) => void;
481
+ onEvent: (event: E) => void;
443
482
  onLeaderChange: (clientId: string) => void;
444
483
  onStateChange?: (state: LeadershipState) => void;
445
484
  callTimeoutMs?: number;
@@ -635,7 +674,7 @@ export class FollowerLink {
635
674
  if (index >= 0) this.#queue.splice(index, 1);
636
675
  }
637
676
 
638
- #handle(message: MultiTabMessage): void {
677
+ #handle(message: MultiTabMessage<E>): void {
639
678
  if (this.#closed) return;
640
679
  if (message.t === 'announce') {
641
680
  if (message.epoch > this.#maxEpochSeen) {
@@ -698,6 +737,7 @@ export class FollowerLink {
698
737
  }
699
738
  if (message.t === 'event') {
700
739
  if (message.epoch !== this.#epoch) return;
740
+ if (message.to !== undefined && message.to !== this.#fromId) return;
701
741
  this.#onEvent(message.event);
702
742
  return;
703
743
  }
@@ -893,3 +933,295 @@ export class FollowerLink {
893
933
  this.#cancelBlocked = undefined;
894
934
  }
895
935
  }
936
+
937
+ // ---------------------------------------------------------------------------
938
+ // Tab coordinator: the whole leader/follower lifecycle around any core
939
+ // ---------------------------------------------------------------------------
940
+
941
+ /** What a leader's core receives when this tab wins or promotes. */
942
+ export interface TabLeaderContext<E> {
943
+ /** This leadership's epoch; a promotion runs on a higher one. */
944
+ readonly epoch: number;
945
+ /** This tab's id. The leader's own calls arrive under it. */
946
+ readonly tabId: string;
947
+ /**
948
+ * The leader lock. The coordinator releases it after {@link TabLeader.close}
949
+ * resolves. Release it earlier only when the core is already gone, such as a
950
+ * worker terminated on `pagehide`.
951
+ */
952
+ readonly lease: LeaderLease;
953
+ /** Deliver an event to every tab, this one included. */
954
+ broadcast(event: E): void;
955
+ /** Deliver an event to the tab `tabId` only. */
956
+ send(tabId: string, event: E): void;
957
+ }
958
+
959
+ /** The core a leader tab runs for every tab of the coordinator. */
960
+ export interface TabLeader {
961
+ /** Announced to followers as `LeadershipState.leaderClientId`. */
962
+ readonly clientId: string;
963
+ /** Serve one call from the tab `tabId`. */
964
+ call(
965
+ tabId: string,
966
+ method: string,
967
+ args: readonly unknown[],
968
+ ): Promise<unknown>;
969
+ /**
970
+ * The tab `tabId`, which called this leader, closed. Defined only by cores
971
+ * that keep per-tab state; the coordinator then waits on each caller's tab
972
+ * lock.
973
+ */
974
+ tabClosed?(tabId: string): void;
975
+ /** Stop the core. The coordinator releases the leader lock afterwards. */
976
+ close(): Promise<void>;
977
+ }
978
+
979
+ export interface TabCoordinatorConfig<E> {
980
+ /** Web Lock name of the leadership; the channel and tab locks derive from it. */
981
+ readonly name: string;
982
+ /**
983
+ * The application build. Tabs of different versions never serve each other:
984
+ * a leader steps down for a higher version, and a tab next to a leader of
985
+ * another version is `blocked` with reason `leader-incompatible`.
986
+ */
987
+ readonly version: number;
988
+ /** Start the core. Runs when this tab wins the lock, and on every promotion. */
989
+ lead(context: TabLeaderContext<E>): Promise<TabLeader>;
990
+ /** Events the leader broadcast, or sent to this tab. */
991
+ onEvent?(event: E): void;
992
+ onStateChange?(state: LeadershipState): void;
993
+ /** Defaults to Web Locks; tests inject a name-keyed exclusive lock. */
994
+ readonly lock?: LeaderLock;
995
+ readonly channelFactory?: (name: string) => CrossTabChannel<E>;
996
+ /** Liveness and handover-queue deadline; defaults to 10 s. */
997
+ readonly callTimeoutMs?: number;
998
+ }
999
+
1000
+ /** One tab's end of the coordinator, the same in leader and follower tabs. */
1001
+ export interface TabCoordinator {
1002
+ readonly tabId: string;
1003
+ readonly state: LeadershipState;
1004
+ /** Run a call on the leader's core, in this tab or over the channel. */
1005
+ call(method: string, args: readonly unknown[]): Promise<unknown>;
1006
+ /** Stop the core (leader) or the link (follower), and release this tab's locks. */
1007
+ close(): Promise<void>;
1008
+ }
1009
+
1010
+ function tabLockName(name: string, tabId: string): string {
1011
+ return `${name}:tab:${tabId}`;
1012
+ }
1013
+
1014
+ /**
1015
+ * Elect one leader tab per `name` and run `lead` there; every other tab
1016
+ * forwards its calls to that core and receives its events. When the leader
1017
+ * tab closes, one follower promotes in place on a higher epoch and runs
1018
+ * `lead` itself. Resolves once this tab leads or is bound to a leader.
1019
+ */
1020
+ export async function createTabCoordinator<E>(
1021
+ config: TabCoordinatorConfig<E>,
1022
+ ): Promise<TabCoordinator> {
1023
+ const lock = config.lock ?? webLocksLeaderLock();
1024
+ const openChannel = config.channelFactory ?? broadcastChannelFactory<E>();
1025
+ const channelName = multiTabChannelName(config.name);
1026
+ const identity: TabIdentity = {
1027
+ protocol: MULTI_TAB_PROTOCOL_VERSION,
1028
+ schemaVersion: config.version,
1029
+ };
1030
+ const tabId = newTabId();
1031
+ let state: LeadershipState = {
1032
+ state: 'waiting',
1033
+ reason: 'leader-announcement',
1034
+ };
1035
+ let leading:
1036
+ | { leader: TabLeader; lease: LeaderLease; end(): void }
1037
+ | undefined;
1038
+ let follower: FollowerLink<E> | undefined;
1039
+ let closed = false;
1040
+
1041
+ const setState = (next: LeadershipState): void => {
1042
+ state = next;
1043
+ try {
1044
+ config.onStateChange?.(next);
1045
+ } catch {
1046
+ // A status listener must never break cross-tab coordination.
1047
+ }
1048
+ };
1049
+
1050
+ // Held until close: a leader waits on it to learn this tab is gone.
1051
+ const tabLease = await lock.acquire(tabLockName(config.name, tabId));
1052
+
1053
+ const lead = async (lease: LeaderLease, epoch: number): Promise<void> => {
1054
+ let bridge: LeaderBridge<E> | undefined;
1055
+ let current = true;
1056
+ const leader = await config.lead({
1057
+ epoch,
1058
+ tabId,
1059
+ lease,
1060
+ broadcast: (event) => {
1061
+ if (!current) return;
1062
+ bridge?.broadcastEvent(event);
1063
+ config.onEvent?.(event);
1064
+ },
1065
+ send: (to, event) => {
1066
+ if (!current) return;
1067
+ if (to === tabId) config.onEvent?.(event);
1068
+ else bridge?.sendEvent(to, event);
1069
+ },
1070
+ });
1071
+ if (closed) {
1072
+ // Closed while the core was starting: nobody holds this tab any more.
1073
+ current = false;
1074
+ await leader.close();
1075
+ await lease.release();
1076
+ return;
1077
+ }
1078
+ const ending = {
1079
+ leader,
1080
+ lease,
1081
+ end: () => {
1082
+ current = false;
1083
+ bridge?.close();
1084
+ },
1085
+ };
1086
+ leading = ending;
1087
+ bridge = new LeaderBridge<E>({
1088
+ channel: openChannel(channelName),
1089
+ epoch,
1090
+ clientId: leader.clientId,
1091
+ identity,
1092
+ invoke: (from, method, args) => leader.call(from, method, args),
1093
+ ...(leader.tabClosed !== undefined
1094
+ ? {
1095
+ onFirstCall: (from: string) => {
1096
+ void lock
1097
+ .acquire(tabLockName(config.name, from))
1098
+ .then(async (gone) => {
1099
+ await gone.release();
1100
+ if (current) leader.tabClosed?.(from);
1101
+ });
1102
+ },
1103
+ }
1104
+ : {}),
1105
+ onNewerTab: () => {
1106
+ // A newer build asked for the core: stop it and release the lock so
1107
+ // that tab promotes. This tab stays blocked until it reloads.
1108
+ if (leading !== ending) return;
1109
+ leading = undefined;
1110
+ ending.end();
1111
+ setState({
1112
+ state: 'blocked',
1113
+ reason: 'leader-incompatible',
1114
+ code: LEADER_INCOMPATIBLE_CODE,
1115
+ leader: 'newer',
1116
+ retryable: true,
1117
+ });
1118
+ void leader.close().finally(() => lease.release());
1119
+ },
1120
+ });
1121
+ // Calls queued for the next leader run on this tab's own core.
1122
+ follower?.handOver((method, args) => leader.call(tabId, method, args));
1123
+ follower = undefined;
1124
+ setState({ state: 'leader', clientId: leader.clientId });
1125
+ };
1126
+
1127
+ const coordinator: TabCoordinator = {
1128
+ tabId,
1129
+ get state() {
1130
+ return state;
1131
+ },
1132
+ call: (method, args) => {
1133
+ if (closed) {
1134
+ return Promise.reject(
1135
+ new ClientSyncError(
1136
+ WORKER_FAILED_CODE,
1137
+ 'the tab coordinator is closed',
1138
+ ),
1139
+ );
1140
+ }
1141
+ if (leading !== undefined)
1142
+ return leading.leader.call(tabId, method, args);
1143
+ if (state.state === 'blocked' && state.reason === 'leader-incompatible') {
1144
+ return Promise.reject(
1145
+ new ClientSyncError(
1146
+ LEADER_INCOMPATIBLE_CODE,
1147
+ 'the tab that owns the database runs a different protocol or schema version',
1148
+ true,
1149
+ ),
1150
+ );
1151
+ }
1152
+ if (follower !== undefined) return follower.call(method, args);
1153
+ return Promise.reject(
1154
+ new ClientSyncError(WORKER_FAILED_CODE, 'no core serves this tab'),
1155
+ );
1156
+ },
1157
+ close: async () => {
1158
+ if (closed) return;
1159
+ closed = true;
1160
+ follower?.close();
1161
+ follower = undefined;
1162
+ const ending = leading;
1163
+ leading = undefined;
1164
+ if (ending !== undefined) {
1165
+ ending.end();
1166
+ await ending.leader.close();
1167
+ await ending.lease.release();
1168
+ }
1169
+ await tabLease.release();
1170
+ },
1171
+ };
1172
+
1173
+ // Leadership before any core exists: a losing tab never starts one.
1174
+ const lease =
1175
+ lock.tryAcquire !== undefined
1176
+ ? await lock.tryAcquire(config.name)
1177
+ : await lock.acquire(config.name);
1178
+ if (lease !== undefined) {
1179
+ try {
1180
+ await lead(lease, 0);
1181
+ } catch (error) {
1182
+ await lease.release();
1183
+ await tabLease.release();
1184
+ throw error;
1185
+ }
1186
+ return coordinator;
1187
+ }
1188
+
1189
+ const link = new FollowerLink<E>({
1190
+ channel: openChannel(channelName),
1191
+ fromId: tabId,
1192
+ identity,
1193
+ onEvent: (event) => config.onEvent?.(event),
1194
+ onLeaderChange: () => {},
1195
+ onStateChange: setState,
1196
+ ...(config.callTimeoutMs !== undefined
1197
+ ? { callTimeoutMs: config.callTimeoutMs }
1198
+ : {}),
1199
+ });
1200
+ follower = link;
1201
+ // Granted only when the leader releases the lock (its tab closed).
1202
+ void lock.acquire(config.name).then(async (promoted) => {
1203
+ if (closed) {
1204
+ // Promoting a closed coordinator would hold the lock forever.
1205
+ await promoted.release();
1206
+ return;
1207
+ }
1208
+ // The new leader must exceed every epoch this tab saw, so stale replies
1209
+ // and events are discarded everywhere.
1210
+ const epoch = link.maxEpochSeen + 1;
1211
+ link.unbind();
1212
+ try {
1213
+ await lead(promoted, epoch);
1214
+ } catch {
1215
+ // The core failed to start: release so the next tab tries.
1216
+ await promoted.release();
1217
+ }
1218
+ });
1219
+ // Return bound: an event the leader fans out before binding is dropped.
1220
+ try {
1221
+ await link.waitUntilBound();
1222
+ } catch {
1223
+ // Bind timed out: the link keeps probing, queued calls flush on the next
1224
+ // announce, and the state says `blocked`.
1225
+ }
1226
+ return coordinator;
1227
+ }
package/src/outbox.ts CHANGED
@@ -40,6 +40,11 @@ export interface OutboxOperation {
40
40
  * presence set — `mutate` marks every column, `patch` the supplied ones).
41
41
  */
42
42
  readonly values?: Readonly<Record<string, JsonRowValue>>;
43
+ /**
44
+ * §7.1 insert intent: a `mutate` of a row absent from the replica. Replay
45
+ * and encoding treat the operation as a full row; a missing column is NULL.
46
+ */
47
+ readonly insert?: true;
43
48
  }
44
49
 
45
50
  export interface OutboxCommit {
@@ -205,6 +210,7 @@ export class OutboxEncodeError extends ClientSyncError {
205
210
  function sparseValues(
206
211
  table: CompiledClientTable,
207
212
  values: Readonly<Record<string, JsonRowValue>>,
213
+ insert: boolean,
208
214
  ): SparseRowValue[] {
209
215
  // Any persisted key that is not a column of the CURRENT schema means the
210
216
  // bump removed (or renamed) it — the commit cannot be expressed now.
@@ -217,7 +223,15 @@ function sparseValues(
217
223
  }
218
224
  return table.columns.map((column) => {
219
225
  const value = values[column.name];
220
- return value === undefined ? undefined : jsonToRowValue(value);
226
+ if (value !== undefined) return jsonToRowValue(value);
227
+ if (!insert) return undefined;
228
+ // §7.1: an insert-intent operation presents every current column.
229
+ if (!column.nullable) {
230
+ throw new OutboxEncodeError(
231
+ 'an outbox insert lacks a non-nullable column (§7.4.4)',
232
+ );
233
+ }
234
+ return null;
221
235
  });
222
236
  }
223
237
 
@@ -264,7 +278,7 @@ export async function encodeOutboxCommit(
264
278
  `outbox upsert on ${op.table}/${op.rowId} has no values`,
265
279
  );
266
280
  }
267
- let values = sparseValues(table, op.values);
281
+ let values = sparseValues(table, op.values, op.insert === true);
268
282
  if (encryption !== undefined && table.hasEncryptedColumns) {
269
283
  // Lazy: opt-in E2EE never enters an encryption-free app's bundle.
270
284
  const { encryptRowValues } = await import('./encryption');
package/src/outcomes.ts CHANGED
@@ -186,8 +186,12 @@ export function isStoredOperation(value: unknown): value is OutboxOperation {
186
186
  typeof value.rowId === 'string' &&
187
187
  (value.baseVersion === undefined ||
188
188
  Number.isSafeInteger(value.baseVersion)) &&
189
- ((value.op === 'upsert' && isStoredRow(value.values)) ||
190
- (value.op === 'delete' && value.values === undefined))
189
+ ((value.op === 'upsert' &&
190
+ isStoredRow(value.values) &&
191
+ (value.insert === undefined || value.insert === true)) ||
192
+ (value.op === 'delete' &&
193
+ value.values === undefined &&
194
+ value.insert === undefined))
191
195
  );
192
196
  }
193
197