@syncular/client 0.53.1 → 0.55.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.
@@ -1,555 +1,6 @@
1
- import { SyncClient } from './client.js';
2
- import { withClientDiagnosticsHost, } from './diagnostics.js';
3
- import { encryptionConfigFromKeyring } from './encryption.js';
4
- import { classifySqliteFailure, ClientSyncError, STORAGE_BUSY_CODE, } from './errors.js';
5
- import { httpBlobTransport, httpSegmentDownloader, httpSyncTransport, webSocketRealtimeConnector, } from './http.js';
6
- import { openPersistentWasmDatabase } from './wasm-database.js';
7
- import { LOCAL_AUTHORITY_UNCONFIGURED_CODE, WORKER_FAILED_CODE, } from './worker-protocol.js';
8
- /** §12: the worker's sibling file for the local authority. */
9
- const LOCAL_AUTHORITY_SIBLING = 'local-authority';
10
- function toErrorShape(caught) {
11
- const error = classifySqliteFailure(caught).error;
12
- if (error instanceof ClientSyncError) {
13
- return {
14
- code: error.code,
15
- message: error.message,
16
- retryable: error.retryable,
17
- ...(error.details !== undefined ? { details: error.details } : {}),
18
- };
19
- }
20
- return {
21
- code: WORKER_FAILED_CODE,
22
- message: error instanceof Error ? error.message : String(error),
23
- retryable: false,
24
- };
25
- }
26
- /**
27
- * ArrayBuffers safe to transfer out of a query result: whole-buffer
28
- * views only (a view into a larger/pooled buffer is cloned instead —
29
- * transferring would detach unrelated data), deduplicated because a
30
- * buffer may only appear once in a transfer list.
31
- */
32
- function queryTransferables(rows) {
33
- const buffers = new Set();
34
- for (const row of rows) {
35
- if (row === null || typeof row !== 'object')
36
- continue;
37
- for (const value of Object.values(row)) {
38
- if (value instanceof Uint8Array &&
39
- value.buffer instanceof ArrayBuffer &&
40
- value.byteOffset === 0 &&
41
- value.byteLength === value.buffer.byteLength) {
42
- buffers.add(value.buffer);
43
- }
44
- }
45
- }
46
- return [...buffers];
47
- }
48
- /**
49
- * Register the RPC server on the current worker scope. Call this once
50
- * from a worker entry script; the main-thread handle drives everything
51
- * else through `init`/`call` messages.
52
- */
1
+ import { startSyncWorkerCore } from './worker-core.js';
2
+ import { createWorkerLocalAuthority } from './worker-local-authority.js';
3
+ /** Start a worker that supports the optional local authority (§12). */
53
4
  export function startSyncWorker(overrides = {}) {
54
- const scope = globalThis;
55
- const post = (message, transfer) => {
56
- if (transfer !== undefined && transfer.length > 0) {
57
- scope.postMessage(message, transfer);
58
- }
59
- else {
60
- scope.postMessage(message);
61
- }
62
- };
63
- let client;
64
- let database;
65
- let authority;
66
- let authoritySibling;
67
- let remoteTransport;
68
- let offline = false;
69
- let headers = {};
70
- let closed = false;
71
- // -- one sync loop: RPC-driven and auto-driven rounds serialize ----------
72
- let syncChain = Promise.resolve();
73
- function serializedSync(fn) {
74
- const next = syncChain.then(fn, fn);
75
- syncChain = next.then(() => undefined, () => undefined);
76
- return next;
77
- }
78
- // -- SPEC §7.5 host loop: event-driven intents, no interactive polling --
79
- let autoSync = true;
80
- let autoSyncScheduled = false;
81
- let backgroundTimer;
82
- let backgroundDue = Number.POSITIVE_INFINITY;
83
- function runAutoSync() {
84
- if (closed ||
85
- client === undefined ||
86
- offline ||
87
- client.securityLifecycle() === 'preflight') {
88
- autoSyncScheduled = false;
89
- return;
90
- }
91
- const running = client;
92
- void serializedSync(() => {
93
- // The queued round owns the flag from here. Clearing it at entry would
94
- // let every wake-up that arrives while this round waits behind the
95
- // running one queue its own full drive (§8.4 coalescing).
96
- autoSyncScheduled = false;
97
- return running.syncUntilIdle();
98
- })
99
- .then((summary) => {
100
- if (!closed)
101
- post({ t: 'event', event: { kind: 'synced', summary } });
102
- if (summary.budgetExhausted)
103
- consumeSyncIntent({ kind: 'interactive' });
104
- })
105
- .catch((error) => {
106
- if (!closed) {
107
- post({
108
- t: 'event',
109
- event: { kind: 'synced', error: toErrorShape(error) },
110
- });
111
- }
112
- });
113
- }
114
- function consumeSyncIntent(intent) {
115
- if (!autoSync ||
116
- closed ||
117
- client === undefined ||
118
- offline ||
119
- client.securityLifecycle() === 'preflight' ||
120
- intent.kind === 'none') {
121
- return;
122
- }
123
- if (intent.kind === 'background') {
124
- if (autoSyncScheduled)
125
- return;
126
- const due = Date.now() + Math.max(0, intent.delayMs);
127
- if (backgroundTimer !== undefined && due >= backgroundDue)
128
- return;
129
- if (backgroundTimer !== undefined)
130
- clearTimeout(backgroundTimer);
131
- backgroundDue = due;
132
- backgroundTimer = setTimeout(() => {
133
- backgroundTimer = undefined;
134
- backgroundDue = Number.POSITIVE_INFINITY;
135
- if (!autoSyncScheduled) {
136
- autoSyncScheduled = true;
137
- runAutoSync();
138
- }
139
- }, Math.max(0, due - Date.now()));
140
- return;
141
- }
142
- if (backgroundTimer !== undefined) {
143
- clearTimeout(backgroundTimer);
144
- backgroundTimer = undefined;
145
- backgroundDue = Number.POSITIVE_INFINITY;
146
- }
147
- if (!autoSync || autoSyncScheduled || closed || client === undefined) {
148
- return;
149
- }
150
- autoSyncScheduled = true;
151
- queueMicrotask(runAutoSync);
152
- }
153
- /**
154
- * §12.3: attach or abandon with the client's rounds held, so no round
155
- * reaches the authority while it uploads or rolls back.
156
- */
157
- async function driveLocalAuthority(run) {
158
- const running = requireClient();
159
- const local = authority;
160
- const remote = remoteTransport;
161
- if (local === undefined || remote === undefined) {
162
- throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'init did not enable the local authority');
163
- }
164
- running.setTransportEnabled(false);
165
- try {
166
- await serializedSync(() => run(local, remote));
167
- }
168
- catch (error) {
169
- // `sync.attach_rejected` keeps its code and details across the RPC.
170
- if (error instanceof Error &&
171
- !(error instanceof ClientSyncError) &&
172
- 'code' in error &&
173
- typeof error.code === 'string') {
174
- throw new ClientSyncError(error.code, error.message, false, 'details' in error &&
175
- typeof error.details === 'object' &&
176
- error.details !== null
177
- ? { ...error.details }
178
- : undefined);
179
- }
180
- throw error;
181
- }
182
- finally {
183
- running.setTransportEnabled(!offline);
184
- }
185
- consumeSyncIntent({ kind: 'interactive' });
186
- }
187
- function requireClient() {
188
- if (client === undefined) {
189
- throw new ClientSyncError(WORKER_FAILED_CODE, 'the worker received a call before init completed');
190
- }
191
- return client;
192
- }
193
- async function init(config) {
194
- if (config.authorityReads !== undefined && !overrides.createAuthorityReads)
195
- throw new ClientSyncError('client.authority_read_forbidden', 'authorityReads requires startSyncWorker({ createAuthorityReads })');
196
- if (client !== undefined) {
197
- throw new ClientSyncError(WORKER_FAILED_CODE, 'the worker is already initialized');
198
- }
199
- autoSync = config.autoSync ?? true;
200
- headers = config.headers ?? {};
201
- const http = { headers: () => headers };
202
- for (let attempt = 0;; attempt++) {
203
- try {
204
- database =
205
- overrides.openDatabase !== undefined
206
- ? await overrides.openDatabase(config)
207
- : await defaultOpenDatabase(config);
208
- break;
209
- }
210
- catch (error) {
211
- if (config.database.mode !== 'persistent' ||
212
- !(error instanceof ClientSyncError) ||
213
- error.code !== STORAGE_BUSY_CODE ||
214
- !error.retryable ||
215
- attempt === 6) {
216
- throw error;
217
- }
218
- // Retain the leader lease while the previous worker's OPFS handles
219
- // drain. Only opening is retried; core initialization has not started.
220
- const delayMs = Math.min(50 * 2 ** attempt, 1000);
221
- if (overrides.waitForStorageRetry !== undefined) {
222
- await overrides.waitForStorageRetry(delayMs);
223
- }
224
- else {
225
- await new Promise((resolve) => setTimeout(resolve, delayMs));
226
- }
227
- }
228
- }
229
- const remote = overrides.createTransport !== undefined
230
- ? overrides.createTransport(config)
231
- : httpSyncTransport(config.endpoints.syncUrl, http);
232
- remoteTransport = remote;
233
- const remoteSegments = overrides.createSegments !== undefined
234
- ? overrides.createSegments(config)
235
- : config.endpoints.segmentsUrl !== undefined
236
- ? httpSegmentDownloader(config.endpoints.segmentsUrl, http)
237
- : undefined;
238
- if (config.localAuthority === true) {
239
- if (overrides.openLocalAuthority === undefined) {
240
- throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'localAuthority requires startSyncWorker({ openLocalAuthority })');
241
- }
242
- authoritySibling = database.openSibling?.(LOCAL_AUTHORITY_SIBLING);
243
- if (authoritySibling === undefined) {
244
- throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'localAuthority requires a database with sibling files');
245
- }
246
- authority = await overrides.openLocalAuthority(authoritySibling.database, config.schema);
247
- }
248
- // §12.4: rounds reach the local authority until attach completes, then
249
- // the remote server; the replica rebinds through the §2.1 epoch reset.
250
- const localActive = () => authority !== undefined && authority.state !== 'attached';
251
- const transport = (request) => localActive() ? authority.sync(request) : remote(request);
252
- const segments = authority === undefined
253
- ? remoteSegments
254
- : (request) => {
255
- if (localActive())
256
- return authority.downloadSegment(request);
257
- if (remoteSegments === undefined) {
258
- throw new ClientSyncError('sync.invalid_request', 'no segment endpoint configured');
259
- }
260
- return remoteSegments(request);
261
- };
262
- // §5.9 blob transport: only when a blobs URL is configured.
263
- const blobs = config.endpoints.blobsUrl !== undefined
264
- ? httpBlobTransport(config.endpoints.blobsUrl, http)
265
- : undefined;
266
- // Realtime needs the (possibly persisted) clientId for the
267
- // `{clientId}` URL placeholder — start the client first, then attach
268
- // the connector through a mutable slot read at connect time.
269
- let realtimeConnector;
270
- offline = config.transportEnabled === false;
271
- const started = new SyncClient({
272
- transportEnabled: !offline,
273
- database,
274
- schema: config.schema,
275
- transport,
276
- ...(segments !== undefined ? { segments } : {}),
277
- ...(blobs !== undefined ? { blobs } : {}),
278
- realtime: (handlers) => {
279
- // §12.2: a local authority has no realtime channel.
280
- if (realtimeConnector === undefined || localActive()) {
281
- throw new ClientSyncError('sync.invalid_request', 'no realtime connector configured');
282
- }
283
- return realtimeConnector(handlers);
284
- },
285
- ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
286
- ...(config.limits !== undefined ? { limits: config.limits } : {}),
287
- ...(config.retainFailedCommits !== undefined
288
- ? { retainFailedCommits: config.retainFailedCommits }
289
- : {}),
290
- ...(config.realtimePolicy !== undefined
291
- ? { realtimePolicy: config.realtimePolicy }
292
- : {}),
293
- ...(config.encryption !== undefined
294
- ? { encryption: encryptionConfigFromKeyring(config.encryption) }
295
- : {}),
296
- ...(config.authorityReads !== undefined
297
- ? {
298
- authorityReads: overrides.createAuthorityReads(config.authorityReads),
299
- }
300
- : {}),
301
- ...(config.securityPreflight !== undefined
302
- ? { securityPreflight: config.securityPreflight }
303
- : {}),
304
- ...(config.previousVersionContext !== undefined
305
- ? { previousVersionContext: config.previousVersionContext }
306
- : {}),
307
- onSyncNeeded: (reason) => {
308
- post({ t: 'event', event: { kind: 'sync-needed', reason } });
309
- consumeSyncIntent({ kind: 'interactive' });
310
- },
311
- onSyncIntent: consumeSyncIntent,
312
- onConflict: (conflict) => {
313
- post({ t: 'event', event: { kind: 'conflict', conflict } });
314
- },
315
- onUpgrading: (upgrading) => {
316
- // §7.4.5: surface the schema-bump reset + completion to the UI thread.
317
- post({ t: 'event', event: { kind: 'upgrading', upgrading } });
318
- },
319
- onPresence: (scopeKey) => {
320
- // §8.6: surface a presence change to the UI thread.
321
- post({ t: 'event', event: { kind: 'presence', scopeKey } });
322
- },
323
- });
324
- started.onProgress((progress) => {
325
- if (!closed)
326
- post({ t: 'event', event: { kind: 'progress', progress } });
327
- });
328
- started.onChange((batch) => {
329
- if (!closed)
330
- post({ t: 'event', event: { kind: 'change', batch } });
331
- });
332
- const postDiagnostics = (snapshot) => {
333
- if (closed)
334
- return;
335
- post({
336
- t: 'event',
337
- event: {
338
- kind: 'diagnostics',
339
- snapshot: withClientDiagnosticsHost(snapshot, {
340
- kind: 'worker',
341
- role: 'leader',
342
- connectivity: offline ? 'offline' : snapshot.host.connectivity,
343
- realtime: snapshot.host.realtime,
344
- }),
345
- },
346
- });
347
- };
348
- started.onDiagnostics(postDiagnostics);
349
- await started.start();
350
- realtimeConnector =
351
- overrides.createRealtime !== undefined
352
- ? overrides.createRealtime(config, started.clientId, http.headers)
353
- : config.endpoints.realtimeUrl !== undefined
354
- ? webSocketRealtimeConnector(config.endpoints.realtimeUrl.replace('{clientId}', encodeURIComponent(started.clientId)))
355
- : undefined;
356
- client = started;
357
- // `start()` may discover persisted subscriptions/outbox work. Its callback
358
- // fires before this worker publishes the initialized client, so consume
359
- // the durable state once here as well; coalescing makes this a single task.
360
- if (started.statusSnapshot().syncNeeded)
361
- consumeSyncIntent({ kind: 'interactive' });
362
- return { clientId: started.clientId };
363
- }
364
- // Forward every argument to core methods, including authority's zero-argument check.
365
- const coreMethods = [
366
- 'securityLifecycle',
367
- 'subscribe',
368
- 'subscribeMany',
369
- 'unsubscribe',
370
- 'windowState',
371
- 'purgeLocalData',
372
- 'rebootstrapLocalData',
373
- 'previousVersionSnapshot',
374
- 'previousVersionAudit',
375
- 'previousVersionDiscard',
376
- 'query',
377
- 'authoritySnapshot',
378
- 'querySnapshot',
379
- 'snapshotRead',
380
- 'statusSnapshot',
381
- 'conflicts',
382
- 'rejections',
383
- 'commitOutcome',
384
- 'commitOutcomes',
385
- 'resolveCommitOutcome',
386
- 'pendingCommits',
387
- 'subscriptions',
388
- 'subscription',
389
- 'connectRealtime',
390
- 'disconnectRealtime',
391
- 'setPresence',
392
- 'presence',
393
- 'uploadBlob',
394
- 'fetchBlob',
395
- ];
396
- const api = {
397
- ...Object.fromEntries(coreMethods.map((method) => [
398
- method,
399
- (...args) => {
400
- const running = requireClient();
401
- return Reflect.apply(running[method], running, args);
402
- },
403
- ])),
404
- beginSecurityPreflight: async () => {
405
- if (backgroundTimer !== undefined)
406
- clearTimeout(backgroundTimer);
407
- backgroundTimer = undefined;
408
- backgroundDue = Number.POSITIVE_INFINITY;
409
- autoSyncScheduled = false;
410
- await requireClient().beginSecurityPreflight();
411
- },
412
- activateSecurity: async (options = {}) => {
413
- await requireClient().activateSecurity({
414
- ...(options.encryption !== undefined
415
- ? { encryption: encryptionConfigFromKeyring(options.encryption) }
416
- : {}),
417
- });
418
- },
419
- setWindow: async (base, units) => {
420
- await requireClient().setWindowCommand(base, units);
421
- },
422
- mutate: (mutations) => {
423
- return requireClient().mutateCommand(mutations).value;
424
- },
425
- patch: (table, rowId, partial, options) => {
426
- // Same §8.4 rule as `mutate`: a local write must push without the app
427
- // orchestrating sync, so consume the core's immediate intent.
428
- const result = requireClient().patchCommand(table, rowId, partial, options);
429
- return result.value;
430
- },
431
- sync: () => {
432
- const running = requireClient();
433
- return serializedSync(() => running.sync());
434
- },
435
- syncUntilIdle: (options) => {
436
- const running = requireClient();
437
- return serializedSync(() => running.syncUntilIdle(options));
438
- },
439
- proveCurrentBase: (outcome, options) => {
440
- const running = requireClient();
441
- return serializedSync(() => running.proveCurrentBase(outcome, options));
442
- },
443
- resetClientId: () => requireClient().resetClientId(),
444
- localRevision: () => requireClient().localRevision,
445
- diagnosticsSnapshot: (request) => {
446
- const snapshot = requireClient().diagnosticsSnapshot(request);
447
- return withClientDiagnosticsHost(snapshot, {
448
- kind: 'worker',
449
- role: 'leader',
450
- connectivity: offline ? 'offline' : snapshot.host.connectivity,
451
- realtime: snapshot.host.realtime,
452
- });
453
- },
454
- setHeaders: (next) => {
455
- headers = next;
456
- },
457
- setOffline: (value) => {
458
- offline = value;
459
- requireClient().setTransportEnabled(!value);
460
- if (offline) {
461
- if (backgroundTimer !== undefined)
462
- clearTimeout(backgroundTimer);
463
- backgroundTimer = undefined;
464
- backgroundDue = Number.POSITIVE_INFINITY;
465
- }
466
- else if (client !== undefined) {
467
- const snapshot = client.diagnosticsSnapshot();
468
- post({
469
- t: 'event',
470
- event: {
471
- kind: 'diagnostics',
472
- snapshot: withClientDiagnosticsHost(snapshot, {
473
- kind: 'worker',
474
- role: 'leader',
475
- connectivity: snapshot.host.connectivity,
476
- realtime: snapshot.host.realtime,
477
- }),
478
- },
479
- });
480
- }
481
- },
482
- localAuthorityState: () => authority?.state,
483
- attachLocalAuthority: () => driveLocalAuthority((local, remote) => local.attach(remote)),
484
- abandonLocalAuthorityAttach: () => driveLocalAuthority((local, remote) => local.abandonAttach(remote)),
485
- close: async () => {
486
- closed = true;
487
- if (backgroundTimer !== undefined)
488
- clearTimeout(backgroundTimer);
489
- await client?.close();
490
- authoritySibling?.close();
491
- database?.close();
492
- client = undefined;
493
- database = undefined;
494
- },
495
- };
496
- // Local purge/rebootstrap/discard rewrite the same durable state an
497
- // in-flight sync round captured at send time, and the RFC 0005 reads observe
498
- // (and can themselves trigger the discard of) that same previous-version
499
- // container. Running all of them on the sync chain orders them against RPC-
500
- // and auto-driven rounds (the client core's reset fence covers hosts that
501
- // call the core directly).
502
- const syncChainMethods = new Set([
503
- 'purgeLocalData',
504
- 'rebootstrapLocalData',
505
- 'previousVersionSnapshot',
506
- 'previousVersionAudit',
507
- 'previousVersionDiscard',
508
- ]);
509
- async function dispatch(message) {
510
- const method = api[message.method];
511
- const invoke = () => method.apply(api, message.args);
512
- if (syncChainMethods.has(message.method)) {
513
- return await serializedSync(async () => invoke());
514
- }
515
- return await invoke();
516
- }
517
- function run(id, fn, transfer) {
518
- void (async () => {
519
- try {
520
- const value = await fn();
521
- post({ t: 'result', id, value }, transfer !== undefined ? transfer(value) : undefined);
522
- }
523
- catch (error) {
524
- post({ t: 'error', id, error: toErrorShape(error) });
525
- }
526
- })();
527
- }
528
- scope.addEventListener('message', (event) => {
529
- const message = event.data;
530
- if (message.t === 'init') {
531
- run(message.id, () => init(message.config));
532
- return;
533
- }
534
- if (message.t === 'call') {
535
- run(message.id, () => dispatch(message), message.method === 'query'
536
- ? (value) => queryTransferables(value)
537
- : message.method === 'querySnapshot'
538
- ? (value) => queryTransferables(value.rows)
539
- : undefined);
540
- }
541
- });
542
- post({ t: 'ready' });
543
- }
544
- async function defaultOpenDatabase(config) {
545
- if (config.database.mode !== 'persistent') {
546
- throw new ClientSyncError(WORKER_FAILED_CODE, "database mode 'custom' requires an openDatabase override in the " +
547
- 'worker bootstrap (startSyncWorker({ openDatabase }))');
548
- }
549
- return openPersistentWasmDatabase(config.database.name, {
550
- ...(config.database.directory !== undefined
551
- ? { directory: config.database.directory }
552
- : {}),
553
- ...(config.takeOverStorage === true ? { takeOver: true } : {}),
554
- });
5
+ startSyncWorkerCore(overrides, createWorkerLocalAuthority);
555
6
  }
@@ -0,0 +1,3 @@
1
+ import type { WorkerLocalAuthorityFactory } from './worker-core.js';
2
+ /** §12 behavior loaded by the authority-enabled worker entry. */
3
+ export declare const createWorkerLocalAuthority: WorkerLocalAuthorityFactory;
@@ -0,0 +1,70 @@
1
+ import { ClientSyncError } from './errors.js';
2
+ import { LOCAL_AUTHORITY_UNCONFIGURED_CODE } from './worker-protocol.js';
3
+ /** §12 behavior loaded by the authority-enabled worker entry. */
4
+ export const createWorkerLocalAuthority = (context) => {
5
+ let authority;
6
+ let sibling;
7
+ let remoteTransport;
8
+ const active = () => authority !== undefined && authority.state !== 'attached';
9
+ async function drive(run) {
10
+ const running = context.requireClient();
11
+ const local = authority;
12
+ const remote = remoteTransport;
13
+ if (local === undefined || remote === undefined) {
14
+ throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'init did not enable the local authority');
15
+ }
16
+ running.setTransportEnabled(false);
17
+ try {
18
+ await context.serializedSync(() => run(local, remote));
19
+ }
20
+ catch (error) {
21
+ if (error instanceof Error &&
22
+ !(error instanceof ClientSyncError) &&
23
+ 'code' in error &&
24
+ typeof error.code === 'string') {
25
+ throw new ClientSyncError(error.code, error.message, false, 'details' in error &&
26
+ typeof error.details === 'object' &&
27
+ error.details !== null
28
+ ? { ...error.details }
29
+ : undefined);
30
+ }
31
+ throw error;
32
+ }
33
+ finally {
34
+ running.setTransportEnabled(!context.isOffline());
35
+ }
36
+ context.wake();
37
+ }
38
+ return {
39
+ methods: {
40
+ localAuthorityState: () => authority?.state,
41
+ attachLocalAuthority: () => drive((local, remote) => local.attach(remote)),
42
+ abandonLocalAuthorityAttach: () => drive((local, remote) => local.abandonAttach(remote)),
43
+ },
44
+ async open(config, database, remote, segments) {
45
+ remoteTransport = remote;
46
+ if (context.overrides.openLocalAuthority === undefined) {
47
+ throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'localAuthority requires startSyncWorker({ openLocalAuthority })');
48
+ }
49
+ sibling = database.openSibling?.('local-authority');
50
+ if (sibling === undefined) {
51
+ throw new ClientSyncError(LOCAL_AUTHORITY_UNCONFIGURED_CODE, 'localAuthority requires a database with sibling files');
52
+ }
53
+ const local = await context.overrides.openLocalAuthority(sibling.database, config.schema);
54
+ authority = local;
55
+ return {
56
+ transport: (request) => active() ? local.sync(request) : remote(request),
57
+ segments: (request) => {
58
+ if (active())
59
+ return local.downloadSegment(request);
60
+ if (segments === undefined) {
61
+ throw new ClientSyncError('sync.invalid_request', 'no segment endpoint configured');
62
+ }
63
+ return segments(request);
64
+ },
65
+ };
66
+ },
67
+ active,
68
+ close: () => sibling?.close(),
69
+ };
70
+ };
@@ -38,6 +38,8 @@ export declare const NOT_LEADER_CODE = "client.not_leader";
38
38
  export declare const WORKER_FAILED_CODE = "client.worker_failed";
39
39
  /** A page/worker bundle identity changed and a full host reload is required. */
40
40
  export declare const WORKER_RESTART_REQUIRED_CODE = "client.worker_restart_required";
41
+ /** The selected worker entry does not provide the requested method. */
42
+ export declare const WORKER_METHOD_UNAVAILABLE_CODE = "client.worker_method_unavailable";
41
43
  /** SPEC §12: local-authority use without `startSyncWorker({ openLocalAuthority })`. */
42
44
  export declare const LOCAL_AUTHORITY_UNCONFIGURED_CODE = "client.local_authority_unconfigured";
43
45
  /** SPEC §12.3 local-authority state. */
@@ -7,5 +7,7 @@ export const NOT_LEADER_CODE = 'client.not_leader';
7
7
  export const WORKER_FAILED_CODE = 'client.worker_failed';
8
8
  /** A page/worker bundle identity changed and a full host reload is required. */
9
9
  export const WORKER_RESTART_REQUIRED_CODE = 'client.worker_restart_required';
10
+ /** The selected worker entry does not provide the requested method. */
11
+ export const WORKER_METHOD_UNAVAILABLE_CODE = 'client.worker_method_unavailable';
10
12
  /** SPEC §12: local-authority use without `startSyncWorker({ openLocalAuthority })`. */
11
13
  export const LOCAL_AUTHORITY_UNCONFIGURED_CODE = 'client.local_authority_unconfigured';
@@ -0,0 +1,5 @@
1
+ import { type SyncWorkerOverrides } from './worker-core.js';
2
+ /** Worker overrides for a host that uses only a remote sync authority. */
3
+ export type RemoteSyncWorkerOverrides = Omit<SyncWorkerOverrides, 'openLocalAuthority'>;
4
+ /** Start a worker without the optional local-authority lifecycle (§12). */
5
+ export declare function startSyncWorker(overrides?: RemoteSyncWorkerOverrides): void;
@@ -0,0 +1,5 @@
1
+ import { startSyncWorkerCore } from './worker-core.js';
2
+ /** Start a worker without the optional local-authority lifecycle (§12). */
3
+ export function startSyncWorker(overrides = {}) {
4
+ startSyncWorkerCore(overrides);
5
+ }