@syncular/client 0.67.2 → 0.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -87,7 +87,8 @@ core per origin. Wake-ups are handled inside the worker (`autoSync`,
87
87
  SPEC §8.4); the supported page-level realtime supervisor owns reconnect and
88
88
  resume policy. The main thread gets `onSyncNeeded` / `onConflict` / `onSynced`
89
89
  events for rendering in the leader tab; `handle.onSynced(listener)` reports the
90
- end of each automatic drive in every tab, followers included.
90
+ end of each drive to idle, automatic or requested by any tab, in every tab,
91
+ followers included.
91
92
 
92
93
  For a reviewed recovery from a retained conflict or rejection, call
93
94
  `await client.proveCurrentBase(outcome)`. The result contains bases for every
package/dist/client.js CHANGED
@@ -139,6 +139,17 @@ function realtimeErrorCode(error) {
139
139
  const code = error?.code;
140
140
  return typeof code === 'string' ? code : undefined;
141
141
  }
142
+ /** §7.7: progress fields of a payload; no payload is current. */
143
+ const NO_PAYLOAD = {
144
+ table: undefined,
145
+ segmentId: undefined,
146
+ bytesReceived: 0,
147
+ bytesTotal: undefined,
148
+ rowsProcessed: 0,
149
+ rowsTotal: undefined,
150
+ importWriteMs: undefined,
151
+ importCommitMs: undefined,
152
+ };
142
153
  export class SyncClient {
143
154
  #config;
144
155
  #authorityReads;
@@ -450,18 +461,17 @@ export class SyncClient {
450
461
  throw classifySqliteFailure(error).error;
451
462
  }
452
463
  this.#started = true;
464
+ // §4.8: an eviction a crash interrupted finishes before any read, with or
465
+ // without a transport; a preflight replica finishes it at activation.
466
+ if (this.#securityLifecycle === 'active')
467
+ await this.#serialize(() => this.#drainPendingEvictions());
453
468
  // A persisted active subscription needs one catch-up round on every open:
454
469
  // realtime only covers changes after the socket connects, and an
455
470
  // idempotent setWindow/subscribe call correctly creates no new command
456
471
  // effect. Pending outbox work has the same restart requirement. Surface
457
472
  // this as an exact core-owned intent so hosts never need a startup poll or
458
473
  // an application-issued sync() call.
459
- const startupWork = this.#schemaFloor === undefined &&
460
- (countOutbox(this.#db) > 0 ||
461
- this.#db.query(`SELECT 1 FROM ${RETAINED_ROWS} WHERE commit_seq IS NOT NULL LIMIT 1`).length > 0 ||
462
- loadPendingEvictions(this.#db).length > 0 ||
463
- loadUnits(this.#db).some((unit) => unit.status === 'active'));
464
- if (startupWork && this.#securityLifecycle === 'active') {
474
+ if (this.#securityLifecycle === 'active' && this.#hasStartupWork()) {
465
475
  this.#needsPull = true;
466
476
  this.#emitSyncNeeded('startup');
467
477
  this.#emitSyncIntent({ kind: 'interactive' });
@@ -792,20 +802,25 @@ export class SyncClient {
792
802
  throw invalidRequest('activateSecurity requires the client to be in security preflight');
793
803
  }
794
804
  await (this.#preflightBarrier ?? this.#opChain);
805
+ // §4.8: an interrupted eviction finishes before protected reads open.
806
+ await this.#serialize(() => this.#drainPendingEvictions());
795
807
  this.#encryption = options.encryption;
796
808
  this.#securityLifecycle = 'active';
797
- const startupWork = this.#schemaFloor === undefined &&
798
- (countOutbox(this.#db) > 0 ||
799
- this.#db.query(`SELECT 1 FROM ${RETAINED_ROWS} WHERE commit_seq IS NOT NULL LIMIT 1`).length > 0 ||
800
- loadPendingEvictions(this.#db).length > 0 ||
801
- loadUnits(this.#db).some((unit) => unit.status === 'active'));
802
- if (startupWork) {
809
+ if (this.#hasStartupWork()) {
803
810
  this.#setSyncNeeded(true);
804
811
  this.#emitSyncNeeded('startup');
805
812
  this.#emitSyncIntent({ kind: 'interactive' });
806
813
  }
807
814
  this.#emitDiagnostics();
808
815
  }
816
+ /** Persisted work an opened or activated replica owes one round (§8.4). */
817
+ #hasStartupWork() {
818
+ return (this.#schemaFloor === undefined &&
819
+ (countOutbox(this.#db) > 0 ||
820
+ this.#db.query(`SELECT 1 FROM ${RETAINED_ROWS} WHERE commit_seq IS NOT NULL LIMIT 1`).length > 0 ||
821
+ loadPendingEvictions(this.#db).length > 0 ||
822
+ loadUnits(this.#db).some((unit) => unit.status === 'active')));
823
+ }
809
824
  // -- accessors ------------------------------------------------------------
810
825
  get clientId() {
811
826
  return this.#clientId;
@@ -3892,6 +3907,12 @@ export class SyncClient {
3892
3907
  skip: false,
3893
3908
  }
3894
3909
  : undefined;
3910
+ // §7.7: a section boundary ends the previous payload.
3911
+ this.#progress.update({
3912
+ ...NO_PAYLOAD,
3913
+ phase: 'import',
3914
+ unitId: section?.unit.id,
3915
+ });
3895
3916
  break;
3896
3917
  }
3897
3918
  case 'SEGMENT_INLINE':
@@ -3907,16 +3928,13 @@ export class SyncClient {
3907
3928
  let bytes;
3908
3929
  if (frame.type === 'SEGMENT_REF') {
3909
3930
  this.#progress.update({
3931
+ ...NO_PAYLOAD,
3910
3932
  phase: 'download',
3911
3933
  unitId,
3912
3934
  table: frame.table,
3913
3935
  segmentId: frame.segmentId,
3914
- bytesReceived: 0,
3915
3936
  bytesTotal: frame.byteLength,
3916
- rowsProcessed: 0,
3917
3937
  rowsTotal: frame.rowCount,
3918
- importWriteMs: undefined,
3919
- importCommitMs: undefined,
3920
3938
  });
3921
3939
  prefetch();
3922
3940
  const pending = prefetched.get(frame);
@@ -3941,16 +3959,13 @@ export class SyncClient {
3941
3959
  const segment = image === undefined ? decodeRowsSegment(bytes) : undefined;
3942
3960
  if (frame.type === 'SEGMENT_INLINE' && segment !== undefined)
3943
3961
  this.#progress.update({
3962
+ ...NO_PAYLOAD,
3944
3963
  phase: 'import',
3945
3964
  unitId,
3946
3965
  table: segment.table,
3947
- segmentId: undefined,
3948
3966
  bytesReceived: bytes.byteLength,
3949
3967
  bytesTotal: bytes.byteLength,
3950
- rowsProcessed: 0,
3951
3968
  rowsTotal: segment.blocks.reduce((n, block) => n + block.length, 0),
3952
- importWriteMs: undefined,
3953
- importCommitMs: undefined,
3954
3969
  });
3955
3970
  await this.#applySegmentOrFail(section, summary, image?.table ?? segment.table, (table, clearFirst, effective, owners) => {
3956
3971
  const options = this.#segmentApplyOptions(table, clearFirst, effective, owners, image !== undefined
@@ -3971,6 +3986,12 @@ export class SyncClient {
3971
3986
  this.#localResetEpoch === resetEpoch)
3972
3987
  this.#finishSection(section, frame, summary);
3973
3988
  section = undefined;
3989
+ // The counters stay: `complete` and `failed` report them.
3990
+ this.#progress.update({
3991
+ unitId: undefined,
3992
+ table: undefined,
3993
+ segmentId: undefined,
3994
+ });
3974
3995
  break;
3975
3996
  }
3976
3997
  case 'LIVE_START': {
@@ -84,11 +84,6 @@ export declare class NativeSyncError extends Error {
84
84
  * touched.
85
85
  */
86
86
  export declare function nativeCreateParams(config: NativeCreateConfig, ErrorType: typeof NativeSyncError): Record<string, unknown>;
87
- /**
88
- * The `SyncClientLike` proxy over a native core. Every snapshot method
89
- * returns a promise from one host round trip; React hooks accept the
90
- * canonical snapshot interface directly.
91
- */
92
87
  export declare abstract class NativeBridgeClient implements PromiseMethods<ClientSnapshotMethods & Pick<SyncClient, 'unit' | 'units' | 'unitCatchup'>> {
93
88
  #private;
94
89
  /**
@@ -106,8 +101,13 @@ export declare abstract class NativeBridgeClient implements PromiseMethods<Clien
106
101
  protected abstract sendHeaders(headers: Readonly<Record<string, string>>): Promise<NativeReply>;
107
102
  /** Stop the native core. `close()` detaches listeners once it settles. */
108
103
  protected abstract shutdown(): Promise<void>;
109
- /** @internal Settle the native `create`; a failure detaches the listener. */
110
- __open(create: () => Promise<NativeReply>): Promise<void>;
104
+ /**
105
+ * @internal Settle the native `create`; a failure detaches the listener.
106
+ * `host` is the page's native host: its one core serves one live bridge
107
+ * client, so a second `create` before `close()` settles is refused
108
+ * instead of replacing the first client's core.
109
+ */
110
+ __open(create: () => Promise<NativeReply>, host: object): Promise<void>;
111
111
  /** Dispatch a command through the closed check and the preflight gate. */
112
112
  protected command(method: string, params: Record<string, unknown>): Promise<unknown>;
113
113
  /** Additional preflight operations a host subclass permits. */
@@ -171,6 +171,8 @@ export function nativeCreateParams(config, ErrorType) {
171
171
  * returns a promise from one host round trip; React hooks accept the
172
172
  * canonical snapshot interface directly.
173
173
  */
174
+ /** Native hosts whose one core a live bridge client of this page holds. */
175
+ const heldHosts = new WeakSet();
174
176
  export class NativeBridgeClient {
175
177
  #kind;
176
178
  #Error;
@@ -182,6 +184,7 @@ export class NativeBridgeClient {
182
184
  #presenceListeners = new Set();
183
185
  #closed = false;
184
186
  #closing;
187
+ #host;
185
188
  #securityLifecycle;
186
189
  #preflightBarrier;
187
190
  /**
@@ -208,15 +211,27 @@ export class NativeBridgeClient {
208
211
  }
209
212
  return reply.result;
210
213
  }
211
- /** @internal Settle the native `create`; a failure detaches the listener. */
212
- async __open(create) {
214
+ /**
215
+ * @internal Settle the native `create`; a failure detaches the listener.
216
+ * `host` is the page's native host: its one core serves one live bridge
217
+ * client, so a second `create` before `close()` settles is refused
218
+ * instead of replacing the first client's core.
219
+ */
220
+ async __open(create, host) {
221
+ if (heldHosts.has(host)) {
222
+ this.#release();
223
+ throw new this.#Error('client.native_client_exists', 'this page already holds the native client; close it before creating another');
224
+ }
225
+ heldHosts.add(host);
213
226
  try {
214
227
  await this.#reply(create);
215
228
  }
216
229
  catch (error) {
230
+ heldHosts.delete(host);
217
231
  this.#release();
218
232
  throw error;
219
233
  }
234
+ this.#host = host;
220
235
  }
221
236
  /** Dispatch a command through the closed check and the preflight gate. */
222
237
  async command(method, params) {
@@ -764,6 +779,8 @@ export class NativeBridgeClient {
764
779
  const shutdown = this.shutdown();
765
780
  this.#closed = true;
766
781
  this.#closing = shutdown.finally(() => {
782
+ if (this.#host !== undefined)
783
+ heldHosts.delete(this.#host);
767
784
  this.#release();
768
785
  this.#invalidationListeners.clear();
769
786
  this.#progress.clear();
@@ -4,13 +4,13 @@ export interface SyncProgress {
4
4
  readonly attempt: number;
5
5
  readonly state: 'running' | 'complete' | 'failed';
6
6
  readonly phase: 'request' | 'download' | 'import';
7
- readonly unitId?: string;
8
- readonly table?: string;
7
+ readonly unitId?: string | undefined;
8
+ readonly table?: string | undefined;
9
9
  readonly segmentId?: string | undefined;
10
10
  readonly bytesReceived: number;
11
- readonly bytesTotal?: number;
11
+ readonly bytesTotal?: number | undefined;
12
12
  readonly rowsProcessed: number;
13
- readonly rowsTotal?: number;
13
+ readonly rowsTotal?: number | undefined;
14
14
  /** Time in this payload's import transactions before COMMIT, in ms. */
15
15
  readonly importWriteMs?: number | undefined;
16
16
  /** Time committing them and publishing their changes, in ms. */
@@ -49,8 +49,12 @@ export interface ExternalStoreEntry<T> {
49
49
  export interface WindowRetention {
50
50
  /** Resolves once this retained claim has reached the core window. */
51
51
  readonly ready: Promise<void>;
52
- /** Release only this retention owner's units from the composable union. */
53
- readonly release: () => void;
52
+ /**
53
+ * Release only this retention owner's units from the composable union.
54
+ * Settles with the core window edit that applies the release, after its
55
+ * eviction (§4.8); rejects with that edit's error.
56
+ */
57
+ readonly release: () => Promise<void>;
54
58
  }
55
59
  export interface StatusStoreSnapshot {
56
60
  readonly status: SyncStatusSnapshot | undefined;
@@ -87,7 +91,8 @@ export declare class ReactiveClientStore {
87
91
  retainWindow(base: WindowBase, units: readonly string[]): WindowRetention;
88
92
  window(base: WindowBase): ExternalStoreEntry<WindowState>;
89
93
  setWindowClaim(owner: symbol, base: WindowBase, units: readonly string[]): Promise<void>;
90
- releaseWindowClaims(owner: symbol): void;
94
+ /** Settles once every core window edit that drops the owner's claims ran. */
95
+ releaseWindowClaims(owner: symbol): Promise<void>;
91
96
  /** Retained observation counts for diagnostics and resource benchmarks. */
92
97
  cacheStats(): {
93
98
  queries: number;
@@ -329,7 +329,9 @@ class QueryEntry {
329
329
  this.#offStatus = undefined;
330
330
  this.#offRound?.();
331
331
  this.#offRound = undefined;
332
- this.store.releaseWindowClaims(this.#owner);
332
+ // A failed release leaves the group unapplied; the next claim on
333
+ // the base applies it again. Only a retention handle reports it.
334
+ this.store.releaseWindowClaims(this.#owner).catch(() => { });
333
335
  }
334
336
  };
335
337
  };
@@ -401,7 +403,7 @@ class QueryEntry {
401
403
  this.#offStatus = undefined;
402
404
  this.#offRound?.();
403
405
  this.#offRound = undefined;
404
- this.store.releaseWindowClaims(this.#owner);
406
+ this.store.releaseWindowClaims(this.#owner).catch(() => { });
405
407
  this.reset();
406
408
  }
407
409
  /** SPEC §7.8: a rejected claim is claimed again; its stored error would
@@ -894,9 +896,9 @@ export class ReactiveClientStore {
894
896
  ready,
895
897
  release: () => {
896
898
  if (!active)
897
- return;
899
+ return Promise.resolve();
898
900
  active = false;
899
- this.releaseWindowClaims(owner);
901
+ return this.releaseWindowClaims(owner);
900
902
  },
901
903
  };
902
904
  }
@@ -939,11 +941,18 @@ export class ReactiveClientStore {
939
941
  this.#scheduleWindow(group);
940
942
  return result;
941
943
  }
944
+ /** Settles once every core window edit that drops the owner's claims ran. */
942
945
  releaseWindowClaims(owner) {
946
+ const edits = [];
943
947
  for (const group of this.#windowClaims.values()) {
944
- if (group.claims.delete(owner))
945
- this.#scheduleWindow(group);
948
+ if (!group.claims.delete(owner))
949
+ continue;
950
+ edits.push(new Promise((resolve, reject) => {
951
+ group.waiters.push({ resolve, reject });
952
+ }));
953
+ this.#scheduleWindow(group);
946
954
  }
955
+ return Promise.all(edits).then(() => undefined);
947
956
  }
948
957
  /** Apply every claimed window group again and claim again for query entries
949
958
  * whose claim was rejected. An applied group compares equal and makes no
@@ -47,6 +47,11 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
47
47
  let offline = false;
48
48
  let headers = {};
49
49
  let closed = false;
50
+ // Every worker event goes through here; a closed worker posts none.
51
+ const emit = (event) => {
52
+ if (!closed)
53
+ post({ t: 'event', event });
54
+ };
50
55
  let pushingDiagnostics = false;
51
56
  // -- one sync loop: RPC-driven and auto-driven rounds serialize ----------
52
57
  let syncChain = Promise.resolve();
@@ -55,6 +60,17 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
55
60
  syncChain = next.then(() => undefined, () => undefined);
56
61
  return next;
57
62
  }
63
+ /**
64
+ * One drive to idle, automatic or requested: its end reaches every tab.
65
+ * The event is posted inside the serialized step, so the drive settles
66
+ * before the next queued drive starts, as without it.
67
+ */
68
+ function drive(run) {
69
+ return serializedSync(() => run().then((summary) => (emit({ kind: 'synced', summary }), summary), (error) => {
70
+ emit({ kind: 'synced', error: toErrorShape(error) });
71
+ throw error;
72
+ }));
73
+ }
58
74
  // -- SPEC §7.5 host loop: event-driven intents, no interactive polling --
59
75
  let autoSync = true;
60
76
  let autoSyncScheduled = false;
@@ -73,14 +89,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
73
89
  connectivity: offline ? 'offline' : snapshot.host.connectivity,
74
90
  realtime: snapshot.host.realtime,
75
91
  });
76
- const postDiagnostics = (snapshot) => {
77
- if (!closed) {
78
- post({
79
- t: 'event',
80
- event: { kind: 'diagnostics', snapshot: workerDiagnostics(snapshot) },
81
- });
82
- }
83
- };
92
+ const postDiagnostics = (snapshot) => emit({ kind: 'diagnostics', snapshot: workerDiagnostics(snapshot) });
84
93
  function runAutoSync() {
85
94
  if (closed ||
86
95
  client === undefined ||
@@ -90,7 +99,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
90
99
  return;
91
100
  }
92
101
  const running = client;
93
- void serializedSync(() => {
102
+ void drive(() => {
94
103
  // The queued round owns the flag from here. Clearing it at entry would
95
104
  // let every wake-up that arrives while this round waits behind the
96
105
  // running one queue its own full drive (§8.4 coalescing).
@@ -99,18 +108,12 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
99
108
  })
100
109
  .then((summary) => {
101
110
  retryDelayMs = 250;
102
- if (!closed)
103
- post({ t: 'event', event: { kind: 'synced', summary } });
104
111
  if (summary.budgetExhausted)
105
112
  consumeSyncIntent({ kind: 'interactive' });
106
113
  })
107
114
  .catch((error) => {
108
115
  if (closed)
109
116
  return;
110
- post({
111
- t: 'event',
112
- event: { kind: 'synced', error: toErrorShape(error) },
113
- });
114
117
  // §7.8: a retryable drive rejection owes another drive. A retryable
115
118
  // round failure already handed this loop its background intent; the
116
119
  // drive deadline did not. An unreachable endpoint waits for the
@@ -282,29 +285,27 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
282
285
  ? { previousVersionContext: config.previousVersionContext }
283
286
  : {}),
284
287
  onSyncNeeded: (reason) => {
285
- post({ t: 'event', event: { kind: 'sync-needed', reason } });
288
+ emit({ kind: 'sync-needed', reason });
286
289
  consumeSyncIntent({ kind: 'interactive' });
287
290
  },
288
291
  onSyncIntent: consumeSyncIntent,
289
292
  onConflict: (conflict) => {
290
- post({ t: 'event', event: { kind: 'conflict', conflict } });
293
+ emit({ kind: 'conflict', conflict });
291
294
  },
292
295
  onUpgrading: (upgrading) => {
293
296
  // §7.4.5: surface the schema-bump reset + completion to the UI thread.
294
- post({ t: 'event', event: { kind: 'upgrading', upgrading } });
297
+ emit({ kind: 'upgrading', upgrading });
295
298
  },
296
299
  onPresence: (scopeKey, error) => {
297
300
  // §8.6: surface a presence change or rejection to the UI thread.
298
- post({ t: 'event', event: { kind: 'presence', scopeKey, error } });
301
+ emit({ kind: 'presence', scopeKey, error });
299
302
  },
300
303
  });
301
304
  started.onProgress((progress) => {
302
- if (!closed)
303
- post({ t: 'event', event: { kind: 'progress', progress } });
305
+ emit({ kind: 'progress', progress });
304
306
  });
305
307
  started.onChange((batch) => {
306
- if (!closed)
307
- post({ t: 'event', event: { kind: 'change', batch } });
308
+ emit({ kind: 'change', batch });
308
309
  });
309
310
  await started.start();
310
311
  realtimeConnector =
@@ -391,7 +392,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
391
392
  },
392
393
  syncUntilIdle: (options) => {
393
394
  const running = requireClient();
394
- return serializedSync(() => running.syncUntilIdle(options));
395
+ return drive(() => running.syncUntilIdle(options));
395
396
  },
396
397
  proveCurrentBase: (outcome, options) => {
397
398
  const running = requireClient();
@@ -111,7 +111,10 @@ export interface SyncClientHandleConfig {
111
111
  readonly previousVersionContext?: SyncClientConfig['previousVersionContext'];
112
112
  /** Worker-side host loop (§8.4); default true. */
113
113
  readonly autoSync?: boolean;
114
- /** Default: Web Locks when available, else single-owner. */
114
+ /**
115
+ * Default: Web Locks. A runtime without Web Locks refuses the handle with
116
+ * `client.web_locks_unavailable` unless the host injects a lock.
117
+ */
115
118
  readonly leaderLock?: LeaderLock;
116
119
  readonly lockName?: string;
117
120
  /** Shared by default; isolated derives the database/lock/channel tuple. */
@@ -147,7 +150,7 @@ export interface SyncClientHandleConfig {
147
150
  readonly onLeadershipChange?: (state: LeadershipState) => void;
148
151
  readonly onSyncNeeded?: (reason: 'startup' | 'hello' | WakeReason) => void;
149
152
  readonly onConflict?: (conflict: ConflictRecord) => void;
150
- /** The leader worker's automatic drive ended (leader tab only). */
153
+ /** A drive to idle in the leader worker ended (leader tab only). */
151
154
  readonly onSynced?: SyncedListener;
152
155
  /** §7.4.5: schema-bump `upgrading` state changed (reset began/completed). */
153
156
  readonly onUpgrading?: (upgrading: boolean) => void;
@@ -158,8 +161,8 @@ export interface SyncClientHandleConfig {
158
161
  readonly onDiagnostics?: (snapshot: ClientDiagnosticsSnapshot) => void;
159
162
  }
160
163
  /**
161
- * The end of one automatic `syncUntilIdle` drive in the leader worker: its
162
- * summary, or the error it failed with.
164
+ * The end of one `syncUntilIdle` drive in the leader worker, automatic or
165
+ * requested by any tab: its summary, or the error it failed with.
163
166
  */
164
167
  export type SyncedListener = (result: {
165
168
  readonly summary?: SyncSummary;
@@ -231,8 +234,9 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
231
234
  */
232
235
  onPresence(listener: (scopeKey: string, error?: PresenceErrorCode) => void): () => void;
233
236
  /**
234
- * Subscribe to the end of every automatic drive of the current leader's
235
- * worker, in leader and follower tabs alike. A follower receives only the
237
+ * Subscribe to the end of every drive to idle (automatic or requested by
238
+ * any tab) in the current leader's worker, in leader and follower tabs
239
+ * alike. A follower receives only the
236
240
  * drives of the leader it is bound to; a drive that ended before this tab
237
241
  * bound is not replayed. Returns an unsubscribe function.
238
242
  */
@@ -26,7 +26,7 @@ import { serializeBlobRef, } from '@syncular/core';
26
26
  import { ClientDiagnosticsEmitter, withClientDiagnosticsHost, } from './diagnostics.js';
27
27
  import { ClientSyncError, invalidRequest } from './errors.js';
28
28
  import { ChangeEmitter, InvalidationEmitter, invalidationFromChange, } from './invalidation.js';
29
- import { singleOwnerLock, webLocksLeaderLock, } from './leader-lock.js';
29
+ import { webLocksLeaderLock, } from './leader-lock.js';
30
30
  import { decodeLocalDataRebootstrapResult, } from './local-rebootstrap.js';
31
31
  import { createTabCoordinator, multiTabChannelName, TAKEOVER_REFUSED_CODE, } from './multi-tab.js';
32
32
  import { decodePreviousVersionAuditResult, decodePreviousVersionDiscardResult, decodePreviousVersionSnapshot, } from './previous-version.js';
@@ -56,9 +56,9 @@ export function isolatedReplicaNames(options) {
56
56
  }
57
57
  function defaultLeaderLock() {
58
58
  const nav = globalThis.navigator;
59
- return nav?.locks !== undefined
60
- ? webLocksLeaderLock(nav.locks)
61
- : singleOwnerLock();
59
+ if (nav?.locks === undefined)
60
+ throw new ClientSyncError('client.web_locks_unavailable', 'this runtime has no Web Locks; inject a leaderLock');
61
+ return webLocksLeaderLock(nav.locks);
62
62
  }
63
63
  /**
64
64
  * The main-thread proxy: the same logical API as `SyncClient`, every method a
@@ -263,8 +263,9 @@ export class SyncClientHandle {
263
263
  };
264
264
  }
265
265
  /**
266
- * Subscribe to the end of every automatic drive of the current leader's
267
- * worker, in leader and follower tabs alike. A follower receives only the
266
+ * Subscribe to the end of every drive to idle (automatic or requested by
267
+ * any tab) in the current leader's worker, in leader and follower tabs
268
+ * alike. A follower receives only the
268
269
  * drives of the leader it is bound to; a drive that ended before this tab
269
270
  * bound is not replayed. Returns an unsubscribe function.
270
271
  */
@@ -225,7 +225,7 @@ export type SyncWorkerEvent = {
225
225
  readonly kind: 'conflict';
226
226
  readonly conflict: ConflictRecord;
227
227
  } | {
228
- /** An autoSync round finished (or failed) inside the worker. */
228
+ /** A drive to idle (automatic or requested) finished or failed inside the worker. */
229
229
  readonly kind: 'synced';
230
230
  readonly summary?: SyncSummary;
231
231
  readonly error?: WorkerErrorShape;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/client",
3
- "version": "0.67.2",
3
+ "version": "0.68.0",
4
4
  "description": "Syncular TypeScript client core — offline-first sync over SQLite (WASM/OPFS, Bun, Node)",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -121,11 +121,11 @@
121
121
  },
122
122
  "dependencies": {
123
123
  "@sqlite.org/sqlite-wasm": "^3.53.0-build1",
124
- "@syncular/core": "0.67.2"
124
+ "@syncular/core": "0.68.0"
125
125
  },
126
126
  "devDependencies": {
127
127
  "@electric-sql/pglite": "^0.5.4",
128
- "@syncular/server": "0.67.2",
128
+ "@syncular/server": "0.68.0",
129
129
  "playwright": "1.63.0",
130
130
  "vite": "8.3.4"
131
131
  }
package/src/client.ts CHANGED
@@ -910,6 +910,18 @@ export type ClientSnapshotReader = {
910
910
  | Promise<ReturnType<ClientSnapshotMethods[Key]>>;
911
911
  };
912
912
 
913
+ /** §7.7: progress fields of a payload; no payload is current. */
914
+ const NO_PAYLOAD: Partial<SyncProgress> = {
915
+ table: undefined,
916
+ segmentId: undefined,
917
+ bytesReceived: 0,
918
+ bytesTotal: undefined,
919
+ rowsProcessed: 0,
920
+ rowsTotal: undefined,
921
+ importWriteMs: undefined,
922
+ importCommitMs: undefined,
923
+ };
924
+
913
925
  export class SyncClient {
914
926
  readonly #config: SyncClientConfig;
915
927
  readonly #authorityReads: AuthorityReadPolicy | undefined;
@@ -1276,21 +1288,17 @@ export class SyncClient {
1276
1288
  throw classifySqliteFailure(error).error;
1277
1289
  }
1278
1290
  this.#started = true;
1291
+ // §4.8: an eviction a crash interrupted finishes before any read, with or
1292
+ // without a transport; a preflight replica finishes it at activation.
1293
+ if (this.#securityLifecycle === 'active')
1294
+ await this.#serialize(() => this.#drainPendingEvictions());
1279
1295
  // A persisted active subscription needs one catch-up round on every open:
1280
1296
  // realtime only covers changes after the socket connects, and an
1281
1297
  // idempotent setWindow/subscribe call correctly creates no new command
1282
1298
  // effect. Pending outbox work has the same restart requirement. Surface
1283
1299
  // this as an exact core-owned intent so hosts never need a startup poll or
1284
1300
  // an application-issued sync() call.
1285
- const startupWork =
1286
- this.#schemaFloor === undefined &&
1287
- (countOutbox(this.#db) > 0 ||
1288
- this.#db.query(
1289
- `SELECT 1 FROM ${RETAINED_ROWS} WHERE commit_seq IS NOT NULL LIMIT 1`,
1290
- ).length > 0 ||
1291
- loadPendingEvictions(this.#db).length > 0 ||
1292
- loadUnits(this.#db).some((unit) => unit.status === 'active'));
1293
- if (startupWork && this.#securityLifecycle === 'active') {
1301
+ if (this.#securityLifecycle === 'active' && this.#hasStartupWork()) {
1294
1302
  this.#needsPull = true;
1295
1303
  this.#emitSyncNeeded('startup');
1296
1304
  this.#emitSyncIntent({ kind: 'interactive' });
@@ -1667,22 +1675,29 @@ export class SyncClient {
1667
1675
  );
1668
1676
  }
1669
1677
  await (this.#preflightBarrier ?? this.#opChain);
1678
+ // §4.8: an interrupted eviction finishes before protected reads open.
1679
+ await this.#serialize(() => this.#drainPendingEvictions());
1670
1680
  this.#encryption = options.encryption;
1671
1681
  this.#securityLifecycle = 'active';
1672
- const startupWork =
1682
+ if (this.#hasStartupWork()) {
1683
+ this.#setSyncNeeded(true);
1684
+ this.#emitSyncNeeded('startup');
1685
+ this.#emitSyncIntent({ kind: 'interactive' });
1686
+ }
1687
+ this.#emitDiagnostics();
1688
+ }
1689
+
1690
+ /** Persisted work an opened or activated replica owes one round (§8.4). */
1691
+ #hasStartupWork(): boolean {
1692
+ return (
1673
1693
  this.#schemaFloor === undefined &&
1674
1694
  (countOutbox(this.#db) > 0 ||
1675
1695
  this.#db.query(
1676
1696
  `SELECT 1 FROM ${RETAINED_ROWS} WHERE commit_seq IS NOT NULL LIMIT 1`,
1677
1697
  ).length > 0 ||
1678
1698
  loadPendingEvictions(this.#db).length > 0 ||
1679
- loadUnits(this.#db).some((unit) => unit.status === 'active'));
1680
- if (startupWork) {
1681
- this.#setSyncNeeded(true);
1682
- this.#emitSyncNeeded('startup');
1683
- this.#emitSyncIntent({ kind: 'interactive' });
1684
- }
1685
- this.#emitDiagnostics();
1699
+ loadUnits(this.#db).some((unit) => unit.status === 'active'))
1700
+ );
1686
1701
  }
1687
1702
 
1688
1703
  // -- accessors ------------------------------------------------------------
@@ -5406,6 +5421,12 @@ export class SyncClient {
5406
5421
  skip: false,
5407
5422
  }
5408
5423
  : undefined;
5424
+ // §7.7: a section boundary ends the previous payload.
5425
+ this.#progress.update({
5426
+ ...NO_PAYLOAD,
5427
+ phase: 'import',
5428
+ unitId: section?.unit.id,
5429
+ });
5409
5430
  break;
5410
5431
  }
5411
5432
  case 'SEGMENT_INLINE':
@@ -5424,16 +5445,13 @@ export class SyncClient {
5424
5445
  let bytes: Uint8Array;
5425
5446
  if (frame.type === 'SEGMENT_REF') {
5426
5447
  this.#progress.update({
5448
+ ...NO_PAYLOAD,
5427
5449
  phase: 'download',
5428
5450
  unitId,
5429
5451
  table: frame.table,
5430
5452
  segmentId: frame.segmentId,
5431
- bytesReceived: 0,
5432
5453
  bytesTotal: frame.byteLength,
5433
- rowsProcessed: 0,
5434
5454
  rowsTotal: frame.rowCount,
5435
- importWriteMs: undefined,
5436
- importCommitMs: undefined,
5437
5455
  });
5438
5456
  prefetch();
5439
5457
  const pending = prefetched.get(frame);
@@ -5467,19 +5485,16 @@ export class SyncClient {
5467
5485
  image === undefined ? decodeRowsSegment(bytes) : undefined;
5468
5486
  if (frame.type === 'SEGMENT_INLINE' && segment !== undefined)
5469
5487
  this.#progress.update({
5488
+ ...NO_PAYLOAD,
5470
5489
  phase: 'import',
5471
5490
  unitId,
5472
5491
  table: segment.table,
5473
- segmentId: undefined,
5474
5492
  bytesReceived: bytes.byteLength,
5475
5493
  bytesTotal: bytes.byteLength,
5476
- rowsProcessed: 0,
5477
5494
  rowsTotal: segment.blocks.reduce(
5478
5495
  (n, block) => n + block.length,
5479
5496
  0,
5480
5497
  ),
5481
- importWriteMs: undefined,
5482
- importCommitMs: undefined,
5483
5498
  });
5484
5499
  await this.#applySegmentOrFail(
5485
5500
  section,
@@ -5529,6 +5544,12 @@ export class SyncClient {
5529
5544
  )
5530
5545
  this.#finishSection(section, frame, summary);
5531
5546
  section = undefined;
5547
+ // The counters stay: `complete` and `failed` report them.
5548
+ this.#progress.update({
5549
+ unitId: undefined,
5550
+ table: undefined,
5551
+ segmentId: undefined,
5552
+ });
5532
5553
  break;
5533
5554
  }
5534
5555
  case 'LIVE_START': {
@@ -293,6 +293,9 @@ type OutcomeRowValue = ConflictRecord['serverRow'][string];
293
293
  * returns a promise from one host round trip; React hooks accept the
294
294
  * canonical snapshot interface directly.
295
295
  */
296
+ /** Native hosts whose one core a live bridge client of this page holds. */
297
+ const heldHosts = new WeakSet<object>();
298
+
296
299
  export abstract class NativeBridgeClient implements PromiseMethods<
297
300
  ClientSnapshotMethods & Pick<SyncClient, 'unit' | 'units' | 'unitCatchup'>
298
301
  > {
@@ -308,6 +311,7 @@ export abstract class NativeBridgeClient implements PromiseMethods<
308
311
  >();
309
312
  #closed = false;
310
313
  #closing: Promise<void> | undefined;
314
+ #host: object | undefined;
311
315
  #securityLifecycle: SecurityLifecycle;
312
316
  #preflightBarrier: Promise<void> | undefined;
313
317
 
@@ -371,14 +375,32 @@ export abstract class NativeBridgeClient implements PromiseMethods<
371
375
  return reply.result;
372
376
  }
373
377
 
374
- /** @internal Settle the native `create`; a failure detaches the listener. */
375
- async __open(create: () => Promise<NativeReply>): Promise<void> {
378
+ /**
379
+ * @internal Settle the native `create`; a failure detaches the listener.
380
+ * `host` is the page's native host: its one core serves one live bridge
381
+ * client, so a second `create` before `close()` settles is refused
382
+ * instead of replacing the first client's core.
383
+ */
384
+ async __open(
385
+ create: () => Promise<NativeReply>,
386
+ host: object,
387
+ ): Promise<void> {
388
+ if (heldHosts.has(host)) {
389
+ this.#release();
390
+ throw new this.#Error(
391
+ 'client.native_client_exists',
392
+ 'this page already holds the native client; close it before creating another',
393
+ );
394
+ }
395
+ heldHosts.add(host);
376
396
  try {
377
397
  await this.#reply(create);
378
398
  } catch (error) {
399
+ heldHosts.delete(host);
379
400
  this.#release();
380
401
  throw error;
381
402
  }
403
+ this.#host = host;
382
404
  }
383
405
 
384
406
  /** Dispatch a command through the closed check and the preflight gate. */
@@ -1163,6 +1185,7 @@ export abstract class NativeBridgeClient implements PromiseMethods<
1163
1185
  const shutdown = this.shutdown();
1164
1186
  this.#closed = true;
1165
1187
  this.#closing = shutdown.finally(() => {
1188
+ if (this.#host !== undefined) heldHosts.delete(this.#host);
1166
1189
  this.#release();
1167
1190
  this.#invalidationListeners.clear();
1168
1191
  this.#progress.clear();
package/src/progress.ts CHANGED
@@ -5,13 +5,13 @@ export interface SyncProgress {
5
5
  readonly attempt: number;
6
6
  readonly state: 'running' | 'complete' | 'failed';
7
7
  readonly phase: 'request' | 'download' | 'import';
8
- readonly unitId?: string;
9
- readonly table?: string;
8
+ readonly unitId?: string | undefined;
9
+ readonly table?: string | undefined;
10
10
  readonly segmentId?: string | undefined;
11
11
  readonly bytesReceived: number;
12
- readonly bytesTotal?: number;
12
+ readonly bytesTotal?: number | undefined;
13
13
  readonly rowsProcessed: number;
14
- readonly rowsTotal?: number;
14
+ readonly rowsTotal?: number | undefined;
15
15
  /** Time in this payload's import transactions before COMMIT, in ms. */
16
16
  readonly importWriteMs?: number | undefined;
17
17
  /** Time committing them and publishing their changes, in ms. */
@@ -81,8 +81,12 @@ export interface ExternalStoreEntry<T> {
81
81
  export interface WindowRetention {
82
82
  /** Resolves once this retained claim has reached the core window. */
83
83
  readonly ready: Promise<void>;
84
- /** Release only this retention owner's units from the composable union. */
85
- readonly release: () => void;
84
+ /**
85
+ * Release only this retention owner's units from the composable union.
86
+ * Settles with the core window edit that applies the release, after its
87
+ * eviction (§4.8); rejects with that edit's error.
88
+ */
89
+ readonly release: () => Promise<void>;
86
90
  }
87
91
 
88
92
  export interface StatusStoreSnapshot {
@@ -465,7 +469,9 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
465
469
  this.#offStatus = undefined;
466
470
  this.#offRound?.();
467
471
  this.#offRound = undefined;
468
- this.store.releaseWindowClaims(this.#owner);
472
+ // A failed release leaves the group unapplied; the next claim on
473
+ // the base applies it again. Only a retention handle reports it.
474
+ this.store.releaseWindowClaims(this.#owner).catch(() => {});
469
475
  }
470
476
  };
471
477
  };
@@ -541,7 +547,7 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
541
547
  this.#offStatus = undefined;
542
548
  this.#offRound?.();
543
549
  this.#offRound = undefined;
544
- this.store.releaseWindowClaims(this.#owner);
550
+ this.store.releaseWindowClaims(this.#owner).catch(() => {});
545
551
  this.reset();
546
552
  }
547
553
 
@@ -1069,9 +1075,9 @@ export class ReactiveClientStore {
1069
1075
  return {
1070
1076
  ready,
1071
1077
  release: () => {
1072
- if (!active) return;
1078
+ if (!active) return Promise.resolve();
1073
1079
  active = false;
1074
- this.releaseWindowClaims(owner);
1080
+ return this.releaseWindowClaims(owner);
1075
1081
  },
1076
1082
  };
1077
1083
  }
@@ -1125,10 +1131,19 @@ export class ReactiveClientStore {
1125
1131
  return result;
1126
1132
  }
1127
1133
 
1128
- releaseWindowClaims(owner: symbol): void {
1134
+ /** Settles once every core window edit that drops the owner's claims ran. */
1135
+ releaseWindowClaims(owner: symbol): Promise<void> {
1136
+ const edits: Promise<void>[] = [];
1129
1137
  for (const group of this.#windowClaims.values()) {
1130
- if (group.claims.delete(owner)) this.#scheduleWindow(group);
1138
+ if (!group.claims.delete(owner)) continue;
1139
+ edits.push(
1140
+ new Promise<void>((resolve, reject) => {
1141
+ group.waiters.push({ resolve, reject });
1142
+ }),
1143
+ );
1144
+ this.#scheduleWindow(group);
1131
1145
  }
1146
+ return Promise.all(edits).then(() => undefined);
1132
1147
  }
1133
1148
 
1134
1149
  /** Apply every claimed window group again and claim again for query entries
@@ -48,6 +48,7 @@ import {
48
48
  WORKER_FAILED_CODE,
49
49
  WORKER_METHOD_UNAVAILABLE_CODE,
50
50
  type WorkerApi,
51
+ type SyncWorkerEvent,
51
52
  type WorkerCallMessage,
52
53
  type WorkerInitConfig,
53
54
  type WorkerInitResult,
@@ -196,6 +197,10 @@ export function startSyncWorkerCore(
196
197
  let offline = false;
197
198
  let headers: Readonly<Record<string, string>> = {};
198
199
  let closed = false;
200
+ // Every worker event goes through here; a closed worker posts none.
201
+ const emit = (event: SyncWorkerEvent): void => {
202
+ if (!closed) post({ t: 'event', event });
203
+ };
199
204
  let pushingDiagnostics = false;
200
205
 
201
206
  // -- one sync loop: RPC-driven and auto-driven rounds serialize ----------
@@ -209,6 +214,25 @@ export function startSyncWorkerCore(
209
214
  return next;
210
215
  }
211
216
 
217
+ /**
218
+ * One drive to idle, automatic or requested: its end reaches every tab.
219
+ * The event is posted inside the serialized step, so the drive settles
220
+ * before the next queued drive starts, as without it.
221
+ */
222
+ function drive(
223
+ run: () => ReturnType<SyncClient['syncUntilIdle']>,
224
+ ): ReturnType<SyncClient['syncUntilIdle']> {
225
+ return serializedSync(() =>
226
+ run().then(
227
+ (summary) => (emit({ kind: 'synced', summary }), summary),
228
+ (error: unknown) => {
229
+ emit({ kind: 'synced', error: toErrorShape(error) });
230
+ throw error;
231
+ },
232
+ ),
233
+ );
234
+ }
235
+
212
236
  // -- SPEC §7.5 host loop: event-driven intents, no interactive polling --
213
237
  let autoSync = true;
214
238
  let autoSyncScheduled = false;
@@ -230,14 +254,8 @@ export function startSyncWorkerCore(
230
254
  connectivity: offline ? 'offline' : snapshot.host.connectivity,
231
255
  realtime: snapshot.host.realtime,
232
256
  });
233
- const postDiagnostics = (snapshot: ClientDiagnosticsSnapshot): void => {
234
- if (!closed) {
235
- post({
236
- t: 'event',
237
- event: { kind: 'diagnostics', snapshot: workerDiagnostics(snapshot) },
238
- });
239
- }
240
- };
257
+ const postDiagnostics = (snapshot: ClientDiagnosticsSnapshot): void =>
258
+ emit({ kind: 'diagnostics', snapshot: workerDiagnostics(snapshot) });
241
259
 
242
260
  function runAutoSync(): void {
243
261
  if (
@@ -250,7 +268,7 @@ export function startSyncWorkerCore(
250
268
  return;
251
269
  }
252
270
  const running = client;
253
- void serializedSync(() => {
271
+ void drive(() => {
254
272
  // The queued round owns the flag from here. Clearing it at entry would
255
273
  // let every wake-up that arrives while this round waits behind the
256
274
  // running one queue its own full drive (§8.4 coalescing).
@@ -259,15 +277,10 @@ export function startSyncWorkerCore(
259
277
  })
260
278
  .then((summary) => {
261
279
  retryDelayMs = 250;
262
- if (!closed) post({ t: 'event', event: { kind: 'synced', summary } });
263
280
  if (summary.budgetExhausted) consumeSyncIntent({ kind: 'interactive' });
264
281
  })
265
282
  .catch((error: unknown) => {
266
283
  if (closed) return;
267
- post({
268
- t: 'event',
269
- event: { kind: 'synced', error: toErrorShape(error) },
270
- });
271
284
  // §7.8: a retryable drive rejection owes another drive. A retryable
272
285
  // round failure already handed this loop its background intent; the
273
286
  // drive deadline did not. An unreachable endpoint waits for the
@@ -470,27 +483,27 @@ export function startSyncWorkerCore(
470
483
  ? { previousVersionContext: config.previousVersionContext }
471
484
  : {}),
472
485
  onSyncNeeded: (reason) => {
473
- post({ t: 'event', event: { kind: 'sync-needed', reason } });
486
+ emit({ kind: 'sync-needed', reason });
474
487
  consumeSyncIntent({ kind: 'interactive' });
475
488
  },
476
489
  onSyncIntent: consumeSyncIntent,
477
490
  onConflict: (conflict) => {
478
- post({ t: 'event', event: { kind: 'conflict', conflict } });
491
+ emit({ kind: 'conflict', conflict });
479
492
  },
480
493
  onUpgrading: (upgrading) => {
481
494
  // §7.4.5: surface the schema-bump reset + completion to the UI thread.
482
- post({ t: 'event', event: { kind: 'upgrading', upgrading } });
495
+ emit({ kind: 'upgrading', upgrading });
483
496
  },
484
497
  onPresence: (scopeKey, error) => {
485
498
  // §8.6: surface a presence change or rejection to the UI thread.
486
- post({ t: 'event', event: { kind: 'presence', scopeKey, error } });
499
+ emit({ kind: 'presence', scopeKey, error });
487
500
  },
488
501
  });
489
502
  started.onProgress((progress) => {
490
- if (!closed) post({ t: 'event', event: { kind: 'progress', progress } });
503
+ emit({ kind: 'progress', progress });
491
504
  });
492
505
  started.onChange((batch) => {
493
- if (!closed) post({ t: 'event', event: { kind: 'change', batch } });
506
+ emit({ kind: 'change', batch });
494
507
  });
495
508
  await started.start();
496
509
  realtimeConnector =
@@ -585,7 +598,7 @@ export function startSyncWorkerCore(
585
598
  },
586
599
  syncUntilIdle: (options) => {
587
600
  const running = requireClient();
588
- return serializedSync(() => running.syncUntilIdle(options));
601
+ return drive(() => running.syncUntilIdle(options));
589
602
  },
590
603
  proveCurrentBase: (outcome, options) => {
591
604
  const running = requireClient();
@@ -74,7 +74,6 @@ import {
74
74
  import {
75
75
  type LeaderLease,
76
76
  type LeaderLock,
77
- singleOwnerLock,
78
77
  webLocksLeaderLock,
79
78
  } from './leader-lock';
80
79
  import type { LocalDataPurgeInput, LocalDataPurgeResult } from './local-purge';
@@ -224,7 +223,10 @@ export interface SyncClientHandleConfig {
224
223
  readonly previousVersionContext?: SyncClientConfig['previousVersionContext'];
225
224
  /** Worker-side host loop (§8.4); default true. */
226
225
  readonly autoSync?: boolean;
227
- /** Default: Web Locks when available, else single-owner. */
226
+ /**
227
+ * Default: Web Locks. A runtime without Web Locks refuses the handle with
228
+ * `client.web_locks_unavailable` unless the host injects a lock.
229
+ */
228
230
  readonly leaderLock?: LeaderLock;
229
231
  readonly lockName?: string;
230
232
  /** Shared by default; isolated derives the database/lock/channel tuple. */
@@ -260,7 +262,7 @@ export interface SyncClientHandleConfig {
260
262
  readonly onLeadershipChange?: (state: LeadershipState) => void;
261
263
  readonly onSyncNeeded?: (reason: 'startup' | 'hello' | WakeReason) => void;
262
264
  readonly onConflict?: (conflict: ConflictRecord) => void;
263
- /** The leader worker's automatic drive ended (leader tab only). */
265
+ /** A drive to idle in the leader worker ended (leader tab only). */
264
266
  readonly onSynced?: SyncedListener;
265
267
  /** §7.4.5: schema-bump `upgrading` state changed (reset began/completed). */
266
268
  readonly onUpgrading?: (upgrading: boolean) => void;
@@ -272,8 +274,8 @@ export interface SyncClientHandleConfig {
272
274
  }
273
275
 
274
276
  /**
275
- * The end of one automatic `syncUntilIdle` drive in the leader worker: its
276
- * summary, or the error it failed with.
277
+ * The end of one `syncUntilIdle` drive in the leader worker, automatic or
278
+ * requested by any tab: its summary, or the error it failed with.
277
279
  */
278
280
  export type SyncedListener = (result: {
279
281
  readonly summary?: SyncSummary;
@@ -287,9 +289,12 @@ interface Pending {
287
289
 
288
290
  function defaultLeaderLock(): LeaderLock {
289
291
  const nav = (globalThis as { navigator?: { locks?: LockManager } }).navigator;
290
- return nav?.locks !== undefined
291
- ? webLocksLeaderLock(nav.locks)
292
- : singleOwnerLock();
292
+ if (nav?.locks === undefined)
293
+ throw new ClientSyncError(
294
+ 'client.web_locks_unavailable',
295
+ 'this runtime has no Web Locks; inject a leaderLock',
296
+ );
297
+ return webLocksLeaderLock(nav.locks);
293
298
  }
294
299
 
295
300
  /**
@@ -532,8 +537,9 @@ export class SyncClientHandle implements PromiseMethods<WorkerApi> {
532
537
  }
533
538
 
534
539
  /**
535
- * Subscribe to the end of every automatic drive of the current leader's
536
- * worker, in leader and follower tabs alike. A follower receives only the
540
+ * Subscribe to the end of every drive to idle (automatic or requested by
541
+ * any tab) in the current leader's worker, in leader and follower tabs
542
+ * alike. A follower receives only the
537
543
  * drives of the leader it is bound to; a drive that ended before this tab
538
544
  * bound is not replayed. Returns an unsubscribe function.
539
545
  */
@@ -290,7 +290,7 @@ export type SyncWorkerEvent =
290
290
  }
291
291
  | { readonly kind: 'conflict'; readonly conflict: ConflictRecord }
292
292
  | {
293
- /** An autoSync round finished (or failed) inside the worker. */
293
+ /** A drive to idle (automatic or requested) finished or failed inside the worker. */
294
294
  readonly kind: 'synced';
295
295
  readonly summary?: SyncSummary;
296
296
  readonly error?: WorkerErrorShape;