@syncular/client 0.53.1 → 0.54.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.
@@ -0,0 +1,713 @@
1
+ /**
2
+ * Worker-side bootstrap: constructs the WHOLE
3
+ * client core — SyncClient + transports + realtime + SQLite — inside the
4
+ * worker and serves the `worker-protocol` RPC over postMessage.
5
+ *
6
+ * Browsers get the defaults: opfs-sahpool persistence and the fetch/WS
7
+ * transports from `./http`, wired from `WorkerInitConfig.endpoints`.
8
+ * Tests inject a database factory (bun:sqlite) through `overrides` — the
9
+ * same bootstrap, the same RPC, a different SQLite.
10
+ *
11
+ * The §8.4 host loop lives HERE: wake-ups (hello/`sync` events, delta
12
+ * drops) coalesce into one intent-driven `syncUntilIdle` round in the worker;
13
+ * RPC-driven and auto-driven sync rounds serialize on one queue because
14
+ * the core owns exactly one loop.
15
+ */
16
+ import type { defineAuthorityReads } from './authority';
17
+ import { SyncClient } from './client';
18
+ import type { ClientDatabase } from './database';
19
+ import {
20
+ type ClientDiagnosticsSnapshot,
21
+ withClientDiagnosticsHost,
22
+ } from './diagnostics';
23
+ import { encryptionConfigFromKeyring } from './encryption';
24
+ import {
25
+ classifySqliteFailure,
26
+ ClientSyncError,
27
+ STORAGE_BUSY_CODE,
28
+ } from './errors';
29
+ import {
30
+ httpBlobTransport,
31
+ httpSegmentDownloader,
32
+ httpSyncTransport,
33
+ webSocketRealtimeConnector,
34
+ } from './http';
35
+ import type { SyncIntent } from './invalidation';
36
+ import type {
37
+ RealtimeConnector,
38
+ SegmentDownloader,
39
+ SyncTransport,
40
+ } from './transport';
41
+ import type { ClientSchema } from './schema';
42
+ import { openPersistentWasmDatabase } from './wasm-database';
43
+ import {
44
+ LOCAL_AUTHORITY_UNCONFIGURED_CODE,
45
+ type LocalAuthorityState,
46
+ type MainToWorkerMessage,
47
+ WORKER_FAILED_CODE,
48
+ WORKER_METHOD_UNAVAILABLE_CODE,
49
+ type WorkerApi,
50
+ type WorkerCallMessage,
51
+ type WorkerErrorShape,
52
+ type WorkerInitConfig,
53
+ type WorkerInitResult,
54
+ type WorkerMethod,
55
+ type WorkerToMainMessage,
56
+ } from './worker-protocol';
57
+
58
+ export interface SyncWorkerOverrides {
59
+ /** Explicit authority reader factory. Required when init declares authorityReads. */
60
+ readonly createAuthorityReads?: typeof defineAuthorityReads;
61
+ /** Database factory indirection: tests inject bun:sqlite here. */
62
+ readonly openDatabase?: (
63
+ config: WorkerInitConfig,
64
+ ) => Promise<ClientDatabase> | ClientDatabase;
65
+ /** Retry deadline indirection for deterministic worker-host tests. */
66
+ readonly waitForStorageRetry?: (delayMs: number) => Promise<void>;
67
+ readonly createTransport?: (config: WorkerInitConfig) => SyncTransport;
68
+ readonly createSegments?: (
69
+ config: WorkerInitConfig,
70
+ ) => SegmentDownloader | undefined;
71
+ /**
72
+ * Custom realtime connector, e.g. one that mints a fresh ticket per
73
+ * connection attempt. `headers` reads the current host auth set.
74
+ */
75
+ readonly createRealtime?: (
76
+ config: WorkerInitConfig,
77
+ clientId: string,
78
+ headers: () => Readonly<Record<string, string>>,
79
+ ) => RealtimeConnector | undefined;
80
+ /**
81
+ * SPEC §12 local authority, required by init's `localAuthority: true`:
82
+ * `(database, schema) => openLocalAuthority({ database:
83
+ * clientSqliteDatabase(database), schema })` from `@syncular/server`. Only
84
+ * a worker entry that passes it bundles the server code.
85
+ */
86
+ readonly openLocalAuthority?: (
87
+ database: ClientDatabase,
88
+ schema: ClientSchema,
89
+ ) => Promise<WorkerLocalAuthority>;
90
+ }
91
+
92
+ /** The `LocalAuthority` surface of `@syncular/server` the worker drives (§12). */
93
+ export interface WorkerLocalAuthority {
94
+ readonly state: LocalAuthorityState;
95
+ readonly sync: SyncTransport;
96
+ readonly downloadSegment: SegmentDownloader;
97
+ readonly attach: (transport: SyncTransport) => Promise<void>;
98
+ readonly abandonAttach: (transport?: SyncTransport) => Promise<void>;
99
+ }
100
+
101
+ type LocalAuthorityMethod =
102
+ | 'localAuthorityState'
103
+ | 'attachLocalAuthority'
104
+ | 'abandonLocalAuthorityAttach';
105
+
106
+ /** @internal Optional §12 behavior supplied by the authority-enabled entry. */
107
+ interface WorkerLocalAuthorityExtension {
108
+ readonly methods: Pick<WorkerApi, LocalAuthorityMethod>;
109
+ open(
110
+ config: WorkerInitConfig,
111
+ database: ClientDatabase,
112
+ remote: SyncTransport,
113
+ segments: SegmentDownloader | undefined,
114
+ ): Promise<{
115
+ readonly transport: SyncTransport;
116
+ readonly segments: SegmentDownloader | undefined;
117
+ }>;
118
+ active(): boolean;
119
+ close(): void;
120
+ }
121
+
122
+ /** @internal Dependencies shared with the worker's single sync loop. */
123
+ export type WorkerLocalAuthorityFactory = (context: {
124
+ readonly overrides: SyncWorkerOverrides;
125
+ readonly requireClient: () => SyncClient;
126
+ readonly serializedSync: <T>(run: () => Promise<T>) => Promise<T>;
127
+ readonly isOffline: () => boolean;
128
+ readonly wake: () => void;
129
+ }) => WorkerLocalAuthorityExtension;
130
+
131
+ /** Minimal structural view of the dedicated-worker global scope. */
132
+ interface WorkerScope {
133
+ postMessage(message: unknown, transfer?: Transferable[]): void;
134
+ addEventListener(
135
+ type: 'message',
136
+ listener: (event: MessageEvent) => void,
137
+ ): void;
138
+ }
139
+
140
+ function toErrorShape(caught: unknown): WorkerErrorShape {
141
+ const error = classifySqliteFailure(caught).error;
142
+ if (error instanceof ClientSyncError) {
143
+ return {
144
+ code: error.code,
145
+ message: error.message,
146
+ retryable: error.retryable,
147
+ ...(error.details !== undefined ? { details: error.details } : {}),
148
+ };
149
+ }
150
+ return {
151
+ code: WORKER_FAILED_CODE,
152
+ message: error instanceof Error ? error.message : String(error),
153
+ retryable: false,
154
+ };
155
+ }
156
+
157
+ /**
158
+ * ArrayBuffers safe to transfer out of a query result: whole-buffer
159
+ * views only (a view into a larger/pooled buffer is cloned instead —
160
+ * transferring would detach unrelated data), deduplicated because a
161
+ * buffer may only appear once in a transfer list.
162
+ */
163
+ function queryTransferables(rows: readonly unknown[]): Transferable[] {
164
+ const buffers = new Set<ArrayBuffer>();
165
+ for (const row of rows) {
166
+ if (row === null || typeof row !== 'object') continue;
167
+ for (const value of Object.values(row)) {
168
+ if (
169
+ value instanceof Uint8Array &&
170
+ value.buffer instanceof ArrayBuffer &&
171
+ value.byteOffset === 0 &&
172
+ value.byteLength === value.buffer.byteLength
173
+ ) {
174
+ buffers.add(value.buffer);
175
+ }
176
+ }
177
+ }
178
+ return [...buffers];
179
+ }
180
+
181
+ /**
182
+ * Register the RPC server on the current worker scope. Call this once
183
+ * from a worker entry script; the main-thread handle drives everything
184
+ * else through `init`/`call` messages.
185
+ */
186
+ export function startSyncWorkerCore(
187
+ overrides: SyncWorkerOverrides,
188
+ createLocalAuthority?: WorkerLocalAuthorityFactory,
189
+ ): void {
190
+ const scope = globalThis as unknown as WorkerScope;
191
+ const post = (message: WorkerToMainMessage, transfer?: Transferable[]) => {
192
+ if (transfer !== undefined && transfer.length > 0) {
193
+ scope.postMessage(message, transfer);
194
+ } else {
195
+ scope.postMessage(message);
196
+ }
197
+ };
198
+
199
+ let client: SyncClient | undefined;
200
+ let database: ClientDatabase | undefined;
201
+ let offline = false;
202
+ let headers: Readonly<Record<string, string>> = {};
203
+ let closed = false;
204
+
205
+ // -- one sync loop: RPC-driven and auto-driven rounds serialize ----------
206
+ let syncChain: Promise<unknown> = Promise.resolve();
207
+ function serializedSync<T>(fn: () => Promise<T>): Promise<T> {
208
+ const next = syncChain.then(fn, fn);
209
+ syncChain = next.then(
210
+ () => undefined,
211
+ () => undefined,
212
+ );
213
+ return next;
214
+ }
215
+
216
+ // -- SPEC §7.5 host loop: event-driven intents, no interactive polling --
217
+ let autoSync = true;
218
+ let autoSyncScheduled = false;
219
+ let backgroundTimer: ReturnType<typeof setTimeout> | undefined;
220
+ let backgroundDue = Number.POSITIVE_INFINITY;
221
+
222
+ function runAutoSync(): void {
223
+ if (
224
+ closed ||
225
+ client === undefined ||
226
+ offline ||
227
+ client.securityLifecycle() === 'preflight'
228
+ ) {
229
+ autoSyncScheduled = false;
230
+ return;
231
+ }
232
+ const running = client;
233
+ void serializedSync(() => {
234
+ // The queued round owns the flag from here. Clearing it at entry would
235
+ // let every wake-up that arrives while this round waits behind the
236
+ // running one queue its own full drive (§8.4 coalescing).
237
+ autoSyncScheduled = false;
238
+ return running.syncUntilIdle();
239
+ })
240
+ .then((summary) => {
241
+ if (!closed) post({ t: 'event', event: { kind: 'synced', summary } });
242
+ if (summary.budgetExhausted) consumeSyncIntent({ kind: 'interactive' });
243
+ })
244
+ .catch((error: unknown) => {
245
+ if (!closed) {
246
+ post({
247
+ t: 'event',
248
+ event: { kind: 'synced', error: toErrorShape(error) },
249
+ });
250
+ }
251
+ });
252
+ }
253
+
254
+ function consumeSyncIntent(intent: SyncIntent): void {
255
+ if (
256
+ !autoSync ||
257
+ closed ||
258
+ client === undefined ||
259
+ offline ||
260
+ client.securityLifecycle() === 'preflight' ||
261
+ intent.kind === 'none'
262
+ ) {
263
+ return;
264
+ }
265
+ if (intent.kind === 'background') {
266
+ if (autoSyncScheduled) return;
267
+ const due = Date.now() + Math.max(0, intent.delayMs);
268
+ if (backgroundTimer !== undefined && due >= backgroundDue) return;
269
+ if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
270
+ backgroundDue = due;
271
+ backgroundTimer = setTimeout(
272
+ () => {
273
+ backgroundTimer = undefined;
274
+ backgroundDue = Number.POSITIVE_INFINITY;
275
+ if (!autoSyncScheduled) {
276
+ autoSyncScheduled = true;
277
+ runAutoSync();
278
+ }
279
+ },
280
+ Math.max(0, due - Date.now()),
281
+ );
282
+ return;
283
+ }
284
+ if (backgroundTimer !== undefined) {
285
+ clearTimeout(backgroundTimer);
286
+ backgroundTimer = undefined;
287
+ backgroundDue = Number.POSITIVE_INFINITY;
288
+ }
289
+ if (!autoSync || autoSyncScheduled || closed || client === undefined) {
290
+ return;
291
+ }
292
+ autoSyncScheduled = true;
293
+ queueMicrotask(runAutoSync);
294
+ }
295
+
296
+ function requireClient(): SyncClient {
297
+ if (client === undefined) {
298
+ throw new ClientSyncError(
299
+ WORKER_FAILED_CODE,
300
+ 'the worker received a call before init completed',
301
+ );
302
+ }
303
+ return client;
304
+ }
305
+
306
+ const local = createLocalAuthority?.({
307
+ overrides,
308
+ requireClient,
309
+ serializedSync,
310
+ isOffline: () => offline,
311
+ wake: () => consumeSyncIntent({ kind: 'interactive' }),
312
+ });
313
+
314
+ async function init(config: WorkerInitConfig): Promise<WorkerInitResult> {
315
+ if (config.localAuthority === true && local === undefined)
316
+ throw new ClientSyncError(
317
+ LOCAL_AUTHORITY_UNCONFIGURED_CODE,
318
+ 'this worker does not support a local authority',
319
+ );
320
+ if (config.authorityReads !== undefined && !overrides.createAuthorityReads)
321
+ throw new ClientSyncError(
322
+ 'client.authority_read_forbidden',
323
+ 'authorityReads requires startSyncWorker({ createAuthorityReads })',
324
+ );
325
+ if (client !== undefined) {
326
+ throw new ClientSyncError(
327
+ WORKER_FAILED_CODE,
328
+ 'the worker is already initialized',
329
+ );
330
+ }
331
+ autoSync = config.autoSync ?? true;
332
+ headers = config.headers ?? {};
333
+ const http = { headers: () => headers };
334
+
335
+ for (let attempt = 0; ; attempt++) {
336
+ try {
337
+ database =
338
+ overrides.openDatabase !== undefined
339
+ ? await overrides.openDatabase(config)
340
+ : await defaultOpenDatabase(config);
341
+ break;
342
+ } catch (error) {
343
+ if (
344
+ config.database.mode !== 'persistent' ||
345
+ !(error instanceof ClientSyncError) ||
346
+ error.code !== STORAGE_BUSY_CODE ||
347
+ !error.retryable ||
348
+ attempt === 6
349
+ ) {
350
+ throw error;
351
+ }
352
+ // Retain the leader lease while the previous worker's OPFS handles
353
+ // drain. Only opening is retried; core initialization has not started.
354
+ const delayMs = Math.min(50 * 2 ** attempt, 1000);
355
+ if (overrides.waitForStorageRetry !== undefined) {
356
+ await overrides.waitForStorageRetry(delayMs);
357
+ } else {
358
+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
359
+ }
360
+ }
361
+ }
362
+ const remote =
363
+ overrides.createTransport !== undefined
364
+ ? overrides.createTransport(config)
365
+ : httpSyncTransport(config.endpoints.syncUrl, http);
366
+ const remoteSegments =
367
+ overrides.createSegments !== undefined
368
+ ? overrides.createSegments(config)
369
+ : config.endpoints.segmentsUrl !== undefined
370
+ ? httpSegmentDownloader(config.endpoints.segmentsUrl, http)
371
+ : undefined;
372
+ const bindings =
373
+ config.localAuthority === true && local !== undefined
374
+ ? await local.open(config, database, remote, remoteSegments)
375
+ : { transport: remote, segments: remoteSegments };
376
+ // §5.9 blob transport: only when a blobs URL is configured.
377
+ const blobs =
378
+ config.endpoints.blobsUrl !== undefined
379
+ ? httpBlobTransport(config.endpoints.blobsUrl, http)
380
+ : undefined;
381
+
382
+ // Realtime needs the (possibly persisted) clientId for the
383
+ // `{clientId}` URL placeholder — start the client first, then attach
384
+ // the connector through a mutable slot read at connect time.
385
+ let realtimeConnector: RealtimeConnector | undefined;
386
+ offline = config.transportEnabled === false;
387
+ const started = new SyncClient({
388
+ transportEnabled: !offline,
389
+ database,
390
+ schema: config.schema,
391
+ transport: bindings.transport,
392
+ ...(bindings.segments !== undefined
393
+ ? { segments: bindings.segments }
394
+ : {}),
395
+ ...(blobs !== undefined ? { blobs } : {}),
396
+ realtime: (handlers) => {
397
+ // §12.2: a local authority has no realtime channel.
398
+ if (realtimeConnector === undefined || local?.active()) {
399
+ throw new ClientSyncError(
400
+ 'sync.invalid_request',
401
+ 'no realtime connector configured',
402
+ );
403
+ }
404
+ return realtimeConnector(handlers);
405
+ },
406
+ ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
407
+ ...(config.limits !== undefined ? { limits: config.limits } : {}),
408
+ ...(config.retainFailedCommits !== undefined
409
+ ? { retainFailedCommits: config.retainFailedCommits }
410
+ : {}),
411
+ ...(config.realtimePolicy !== undefined
412
+ ? { realtimePolicy: config.realtimePolicy }
413
+ : {}),
414
+ ...(config.encryption !== undefined
415
+ ? { encryption: encryptionConfigFromKeyring(config.encryption) }
416
+ : {}),
417
+ ...(config.authorityReads !== undefined
418
+ ? {
419
+ authorityReads: overrides.createAuthorityReads!(
420
+ config.authorityReads,
421
+ ),
422
+ }
423
+ : {}),
424
+ ...(config.securityPreflight !== undefined
425
+ ? { securityPreflight: config.securityPreflight }
426
+ : {}),
427
+ ...(config.previousVersionContext !== undefined
428
+ ? { previousVersionContext: config.previousVersionContext }
429
+ : {}),
430
+ onSyncNeeded: (reason) => {
431
+ post({ t: 'event', event: { kind: 'sync-needed', reason } });
432
+ consumeSyncIntent({ kind: 'interactive' });
433
+ },
434
+ onSyncIntent: consumeSyncIntent,
435
+ onConflict: (conflict) => {
436
+ post({ t: 'event', event: { kind: 'conflict', conflict } });
437
+ },
438
+ onUpgrading: (upgrading) => {
439
+ // §7.4.5: surface the schema-bump reset + completion to the UI thread.
440
+ post({ t: 'event', event: { kind: 'upgrading', upgrading } });
441
+ },
442
+ onPresence: (scopeKey) => {
443
+ // §8.6: surface a presence change to the UI thread.
444
+ post({ t: 'event', event: { kind: 'presence', scopeKey } });
445
+ },
446
+ });
447
+ started.onProgress((progress) => {
448
+ if (!closed) post({ t: 'event', event: { kind: 'progress', progress } });
449
+ });
450
+ started.onChange((batch) => {
451
+ if (!closed) post({ t: 'event', event: { kind: 'change', batch } });
452
+ });
453
+ const postDiagnostics = (snapshot: ClientDiagnosticsSnapshot): void => {
454
+ if (closed) return;
455
+ post({
456
+ t: 'event',
457
+ event: {
458
+ kind: 'diagnostics',
459
+ snapshot: withClientDiagnosticsHost(snapshot, {
460
+ kind: 'worker',
461
+ role: 'leader',
462
+ connectivity: offline ? 'offline' : snapshot.host.connectivity,
463
+ realtime: snapshot.host.realtime,
464
+ }),
465
+ },
466
+ });
467
+ };
468
+ started.onDiagnostics(postDiagnostics);
469
+ await started.start();
470
+ realtimeConnector =
471
+ overrides.createRealtime !== undefined
472
+ ? overrides.createRealtime(config, started.clientId, http.headers)
473
+ : config.endpoints.realtimeUrl !== undefined
474
+ ? webSocketRealtimeConnector(
475
+ config.endpoints.realtimeUrl.replace(
476
+ '{clientId}',
477
+ encodeURIComponent(started.clientId),
478
+ ),
479
+ )
480
+ : undefined;
481
+ client = started;
482
+ // `start()` may discover persisted subscriptions/outbox work. Its callback
483
+ // fires before this worker publishes the initialized client, so consume
484
+ // the durable state once here as well; coalescing makes this a single task.
485
+ if (started.statusSnapshot().syncNeeded)
486
+ consumeSyncIntent({ kind: 'interactive' });
487
+ return { clientId: started.clientId };
488
+ }
489
+
490
+ // Forward every argument to core methods, including authority's zero-argument check.
491
+ const coreMethods = [
492
+ 'securityLifecycle',
493
+ 'subscribe',
494
+ 'subscribeMany',
495
+ 'unsubscribe',
496
+ 'windowState',
497
+ 'purgeLocalData',
498
+ 'rebootstrapLocalData',
499
+ 'previousVersionSnapshot',
500
+ 'previousVersionAudit',
501
+ 'previousVersionDiscard',
502
+ 'query',
503
+ 'authoritySnapshot',
504
+ 'querySnapshot',
505
+ 'snapshotRead',
506
+ 'statusSnapshot',
507
+ 'conflicts',
508
+ 'rejections',
509
+ 'commitOutcome',
510
+ 'commitOutcomes',
511
+ 'resolveCommitOutcome',
512
+ 'pendingCommits',
513
+ 'subscriptions',
514
+ 'subscription',
515
+ 'connectRealtime',
516
+ 'disconnectRealtime',
517
+ 'setPresence',
518
+ 'presence',
519
+ 'uploadBlob',
520
+ 'fetchBlob',
521
+ ] as const satisfies readonly (keyof WorkerApi & keyof SyncClient)[];
522
+ const api: Omit<WorkerApi, LocalAuthorityMethod> & Partial<WorkerApi> = {
523
+ ...(Object.fromEntries(
524
+ coreMethods.map((method) => [
525
+ method,
526
+ (...args: unknown[]) => {
527
+ const running = requireClient();
528
+ return Reflect.apply(running[method], running, args);
529
+ },
530
+ ]),
531
+ ) as Pick<WorkerApi, (typeof coreMethods)[number]>),
532
+ beginSecurityPreflight: async () => {
533
+ if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
534
+ backgroundTimer = undefined;
535
+ backgroundDue = Number.POSITIVE_INFINITY;
536
+ autoSyncScheduled = false;
537
+ await requireClient().beginSecurityPreflight();
538
+ },
539
+ activateSecurity: async (options = {}) => {
540
+ await requireClient().activateSecurity({
541
+ ...(options.encryption !== undefined
542
+ ? { encryption: encryptionConfigFromKeyring(options.encryption) }
543
+ : {}),
544
+ });
545
+ },
546
+ setWindow: async (base, units) => {
547
+ await requireClient().setWindowCommand(base, units);
548
+ },
549
+ mutate: (mutations) => {
550
+ return requireClient().mutateCommand(mutations).value;
551
+ },
552
+ patch: (table, rowId, partial, options) => {
553
+ // Same §8.4 rule as `mutate`: a local write must push without the app
554
+ // orchestrating sync, so consume the core's immediate intent.
555
+ const result = requireClient().patchCommand(
556
+ table,
557
+ rowId,
558
+ partial,
559
+ options,
560
+ );
561
+ return result.value;
562
+ },
563
+ sync: () => {
564
+ const running = requireClient();
565
+ return serializedSync(() => running.sync());
566
+ },
567
+ syncUntilIdle: (options) => {
568
+ const running = requireClient();
569
+ return serializedSync(() => running.syncUntilIdle(options));
570
+ },
571
+ proveCurrentBase: (outcome, options) => {
572
+ const running = requireClient();
573
+ return serializedSync(() => running.proveCurrentBase(outcome, options));
574
+ },
575
+ resetClientId: () => requireClient().resetClientId(),
576
+ localRevision: () => requireClient().localRevision,
577
+ diagnosticsSnapshot: (request) => {
578
+ const snapshot = requireClient().diagnosticsSnapshot(request);
579
+ return withClientDiagnosticsHost(snapshot, {
580
+ kind: 'worker',
581
+ role: 'leader',
582
+ connectivity: offline ? 'offline' : snapshot.host.connectivity,
583
+ realtime: snapshot.host.realtime,
584
+ });
585
+ },
586
+ setHeaders: (next) => {
587
+ headers = next;
588
+ },
589
+ setOffline: (value) => {
590
+ offline = value;
591
+ requireClient().setTransportEnabled(!value);
592
+ if (offline) {
593
+ if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
594
+ backgroundTimer = undefined;
595
+ backgroundDue = Number.POSITIVE_INFINITY;
596
+ } else if (client !== undefined) {
597
+ const snapshot = client.diagnosticsSnapshot();
598
+ post({
599
+ t: 'event',
600
+ event: {
601
+ kind: 'diagnostics',
602
+ snapshot: withClientDiagnosticsHost(snapshot, {
603
+ kind: 'worker',
604
+ role: 'leader',
605
+ connectivity: snapshot.host.connectivity,
606
+ realtime: snapshot.host.realtime,
607
+ }),
608
+ },
609
+ });
610
+ }
611
+ },
612
+ ...local?.methods,
613
+ close: async () => {
614
+ closed = true;
615
+ if (backgroundTimer !== undefined) clearTimeout(backgroundTimer);
616
+ await client?.close();
617
+ local?.close();
618
+ database?.close();
619
+ client = undefined;
620
+ database = undefined;
621
+ },
622
+ };
623
+
624
+ // Local purge/rebootstrap/discard rewrite the same durable state an
625
+ // in-flight sync round captured at send time, and the RFC 0005 reads observe
626
+ // (and can themselves trigger the discard of) that same previous-version
627
+ // container. Running all of them on the sync chain orders them against RPC-
628
+ // and auto-driven rounds (the client core's reset fence covers hosts that
629
+ // call the core directly).
630
+ const syncChainMethods: ReadonlySet<WorkerMethod> = new Set<WorkerMethod>([
631
+ 'purgeLocalData',
632
+ 'rebootstrapLocalData',
633
+ 'previousVersionSnapshot',
634
+ 'previousVersionAudit',
635
+ 'previousVersionDiscard',
636
+ ]);
637
+
638
+ async function dispatch(message: WorkerCallMessage): Promise<unknown> {
639
+ const method = api[message.method] as
640
+ | ((...args: unknown[]) => unknown)
641
+ | undefined;
642
+ if (!Object.hasOwn(api, message.method) || typeof method !== 'function')
643
+ throw new ClientSyncError(
644
+ WORKER_METHOD_UNAVAILABLE_CODE,
645
+ 'the worker method is not configured',
646
+ );
647
+ const invoke = () => Reflect.apply(method, api, message.args);
648
+ if (syncChainMethods.has(message.method)) {
649
+ return await serializedSync(async () => invoke());
650
+ }
651
+ return await invoke();
652
+ }
653
+
654
+ function run(
655
+ id: number,
656
+ fn: () => Promise<unknown>,
657
+ transfer?: (value: unknown) => Transferable[],
658
+ ): void {
659
+ void (async () => {
660
+ try {
661
+ const value = await fn();
662
+ post(
663
+ { t: 'result', id, value },
664
+ transfer !== undefined ? transfer(value) : undefined,
665
+ );
666
+ } catch (error) {
667
+ post({ t: 'error', id, error: toErrorShape(error) });
668
+ }
669
+ })();
670
+ }
671
+
672
+ scope.addEventListener('message', (event) => {
673
+ const message = event.data as MainToWorkerMessage;
674
+ if (message.t === 'init') {
675
+ run(message.id, () => init(message.config));
676
+ return;
677
+ }
678
+ if (message.t === 'call') {
679
+ run(
680
+ message.id,
681
+ () => dispatch(message),
682
+ message.method === 'query'
683
+ ? (value) => queryTransferables(value as readonly unknown[])
684
+ : message.method === 'querySnapshot'
685
+ ? (value) =>
686
+ queryTransferables(
687
+ (value as { readonly rows: readonly unknown[] }).rows,
688
+ )
689
+ : undefined,
690
+ );
691
+ }
692
+ });
693
+
694
+ post({ t: 'ready' });
695
+ }
696
+
697
+ async function defaultOpenDatabase(
698
+ config: WorkerInitConfig,
699
+ ): Promise<ClientDatabase> {
700
+ if (config.database.mode !== 'persistent') {
701
+ throw new ClientSyncError(
702
+ WORKER_FAILED_CODE,
703
+ "database mode 'custom' requires an openDatabase override in the " +
704
+ 'worker bootstrap (startSyncWorker({ openDatabase }))',
705
+ );
706
+ }
707
+ return openPersistentWasmDatabase(config.database.name, {
708
+ ...(config.database.directory !== undefined
709
+ ? { directory: config.database.directory }
710
+ : {}),
711
+ ...(config.takeOverStorage === true ? { takeOver: true } : {}),
712
+ });
713
+ }