@syncular/client 0.90.0 → 0.92.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/src/encryption.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  type PlainValue,
20
20
  type RowColumn,
21
21
  type RowValue,
22
+ definedObject,
22
23
  } from '@syncular/core';
23
24
  import { invalidRequest } from './errors';
24
25
  import type { CompiledClientTable } from './schema';
@@ -90,12 +91,10 @@ export function encryptionConfigFromKeyring(
90
91
  // and take the clean DecryptError path.
91
92
  keyProvider: (keyId) =>
92
93
  Object.hasOwn(keyring.keys, keyId) ? keyring.keys[keyId] : undefined,
93
- ...(keyring.keyIdColumns !== undefined
94
- ? { keyIdColumns: keyring.keyIdColumns }
95
- : {}),
96
- ...(keyring.missingKey !== undefined
97
- ? { missingKey: keyring.missingKey }
98
- : {}),
94
+ ...definedObject({
95
+ keyIdColumns: keyring.keyIdColumns,
96
+ missingKey: keyring.missingKey,
97
+ }),
99
98
  };
100
99
  }
101
100
 
package/src/errors.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { DecryptError } from '@syncular/core';
1
+ import { DecryptError, definedObject } from '@syncular/core';
2
2
  import type { RealtimeState } from './diagnostics';
3
3
  import { WORKER_FAILED_CODE, type WorkerErrorShape } from './worker-protocol';
4
4
 
@@ -273,12 +273,12 @@ export function toErrorShape(caught: unknown): WorkerErrorShape {
273
273
  error instanceof ClientSyncError || error instanceof DecryptError
274
274
  ? error.details
275
275
  : undefined;
276
- return {
276
+ return definedObject({
277
277
  code: error.code,
278
278
  message: error.message,
279
279
  retryable: 'retryable' in error && error.retryable === true,
280
- ...(details !== undefined ? { details } : {}),
281
- };
280
+ details,
281
+ });
282
282
  }
283
283
  return {
284
284
  code: WORKER_FAILED_CODE,
package/src/http.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * protocol core conformance uses loopback.
6
6
  */
7
7
  import type { BlobTransport } from './blob';
8
+ import { definedObject } from '@syncular/core';
8
9
  import { SSP2_CONTENT_TYPE } from './content-type';
9
10
  import { ClientSyncError, transportFailed } from './errors';
10
11
  import { hexToBytes } from './schema';
@@ -38,7 +39,7 @@ async function transfer<T>(
38
39
  : 'unknown';
39
40
  throw transportFailed(message, {
40
41
  causeKind,
41
- ...(httpStatus !== undefined ? { httpStatus } : {}),
42
+ ...definedObject({ httpStatus }),
42
43
  });
43
44
  }
44
45
  }
@@ -127,7 +128,7 @@ export function httpSyncTransport(
127
128
  ...hostHeaders(options),
128
129
  },
129
130
  body: request.slice().buffer as ArrayBuffer,
130
- ...(signal !== undefined ? { signal } : {}),
131
+ ...definedObject({ signal }),
131
132
  }),
132
133
  );
133
134
  if (!response.ok) await throwHttpError(response);
@@ -326,7 +327,7 @@ export function httpSegmentDownloader(
326
327
  'X-Syncular-Scopes': request.requestedScopesJson,
327
328
  ...hostHeaders(options),
328
329
  },
329
- ...(request.signal !== undefined ? { signal: request.signal } : {}),
330
+ ...definedObject({ signal: request.signal }),
330
331
  },
331
332
  request.onProgress,
332
333
  false,
@@ -338,14 +339,7 @@ export function httpSegmentDownloader(
338
339
  onProgress?: (bytesReceived: number) => void,
339
340
  signal?: AbortSignal,
340
341
  byteLength?: number,
341
- ) =>
342
- download(
343
- url,
344
- signal !== undefined ? { signal } : undefined,
345
- onProgress,
346
- true,
347
- byteLength,
348
- );
342
+ ) => download(url, signal && { signal }, onProgress, true, byteLength);
349
343
  return Object.assign(direct, { fetchUrl });
350
344
  }
351
345
 
@@ -372,7 +366,7 @@ export function httpBlobTransport(
372
366
  ...hostHeaders(options),
373
367
  },
374
368
  body: bytes.slice().buffer as ArrayBuffer,
375
- ...(signal !== undefined ? { signal } : {}),
369
+ ...definedObject({ signal }),
376
370
  }),
377
371
  );
378
372
  if (!response.ok) await throwHttpError(response);
@@ -444,9 +438,9 @@ export function httpBlobTransport(
444
438
  },
445
439
  body: JSON.stringify({
446
440
  byteLength,
447
- ...(mediaType !== undefined ? { mediaType } : {}),
441
+ mediaType,
448
442
  }),
449
- ...(signal !== undefined ? { signal } : {}),
443
+ ...definedObject({ signal }),
450
444
  }),
451
445
  );
452
446
  if (!response.ok) await throwHttpError(response);
@@ -482,7 +476,7 @@ export function httpBlobTransport(
482
476
  'x-amz-checksum-sha256': checksum,
483
477
  },
484
478
  body,
485
- ...(signal !== undefined ? { signal } : {}),
479
+ ...definedObject({ signal }),
486
480
  }),
487
481
  );
488
482
  if (!response.ok) {
package/src/multi-tab.ts CHANGED
@@ -97,9 +97,10 @@ export const TAKEOVER_REFUSED_CODE = 'client.takeover_refused';
97
97
  /**
98
98
  * Version of the leader/follower wire and the forwarded handle API. Bump it
99
99
  * with every change to a message shape or to a forwarded method's arguments
100
- * or result, so tabs of different builds never serve each other.
100
+ * or result, so tabs of different builds never serve each other;
101
+ * test/multi-tab-protocol.test.ts pins the surface's fingerprint to it.
101
102
  */
102
- export const MULTI_TAB_PROTOCOL_VERSION = 3;
103
+ export const MULTI_TAB_PROTOCOL_VERSION = 4;
103
104
 
104
105
  /** What a tab must share with its leader to be served by it. */
105
106
  export interface TabIdentity {
@@ -1095,7 +1095,7 @@ export abstract class NativeBridgeClient implements PromiseMethods<
1095
1095
  return this.command('sync', {});
1096
1096
  }
1097
1097
 
1098
- /** The Rust core has no §8.4 empty-replica gate: `skipEmpty` is not sent. */
1098
+ /** The Rust core has no §8.4 host policy: `skipEmpty` and `coalesceMs` are not sent. */
1099
1099
  async syncUntilIdle(
1100
1100
  options?: number | SyncIdleOptions,
1101
1101
  timeoutMs?: number,
@@ -600,7 +600,8 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
600
600
  ),
601
601
  );
602
602
  if (rowChange && this.#claimError !== undefined) this.reclaim();
603
- else this.#requestRead();
603
+ // A running read reads again only when its snapshot predates the batch.
604
+ else if (!this.#running) this.#requestRead();
604
605
  }
605
606
 
606
607
  #publish(next: LiveQueryResult<Row>): void {
@@ -743,9 +744,11 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
743
744
  if (this.#running || this.#listeners.size === 0) return;
744
745
  const generation = this.#generation;
745
746
  this.#running = true;
747
+ let asked = this.#desiredRevision;
746
748
  try {
747
749
  do {
748
750
  this.#requested = false;
751
+ asked = this.#desiredRevision;
749
752
  if (localReadsBlocked(this.store.availabilitySnapshot())) break;
750
753
 
751
754
  if (generation !== this.#generation || this.#listeners.size === 0)
@@ -827,6 +830,8 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
827
830
  this.#gate();
828
831
  return;
829
832
  }
833
+ // A batch that arrived during the failed read reads again.
834
+ if (this.#desiredRevision > asked) this.#requested = true;
830
835
  // SPEC §7.5: a failed latest read is never `ready`; the last
831
836
  // successful rows and revision stay available beside the error.
832
837
  this.#publish({
package/src/schema.ts CHANGED
@@ -16,7 +16,7 @@ import { ensureFailedOverlaySchema, RETAINED_ROWS } from './failed-overlay';
16
16
  * DDL, the generated row codec, mutation helpers, and the §3.3 purge
17
17
  * mapping (scope variable → local column).
18
18
  */
19
- import type { RowColumn, RowValue } from '@syncular/core';
19
+ import { definedObject, type RowColumn, type RowValue } from '@syncular/core';
20
20
  import type { ClientDatabase, SqlRow, SqlValue } from './database';
21
21
  import { invalidRequest, localStateCorrupt } from './errors';
22
22
  import { snakeToCamel } from './naming';
@@ -250,9 +250,7 @@ export function compileClientSchema(
250
250
  }
251
251
  tables.set(table.name, {
252
252
  name: table.name,
253
- ...(table.generation !== undefined
254
- ? { generation: table.generation }
255
- : {}),
253
+ ...definedObject({ generation: table.generation }),
256
254
  columns: table.columns,
257
255
  primaryKey: table.primaryKey,
258
256
  primaryKeyIndex,
@@ -100,7 +100,11 @@ export function installSyncScheduler(
100
100
  running = true;
101
101
  backgroundReady = false;
102
102
  void client
103
- .syncUntilIdle({ maxRounds: options.maxRounds, skipEmpty: true })
103
+ .syncUntilIdle({
104
+ maxRounds: options.maxRounds,
105
+ skipEmpty: true,
106
+ coalesceMs,
107
+ })
104
108
  .then((result) => {
105
109
  retryDelayMs = 250;
106
110
  if (
@@ -13,6 +13,7 @@
13
13
  * RPC-driven and auto-driven sync rounds serialize on one queue because
14
14
  * the core owns exactly one loop.
15
15
  */
16
+ import { definedObject } from '@syncular/core';
16
17
  import type { defineAuthorityReads } from './authority';
17
18
  import { SyncClient } from './client';
18
19
  import type { ClientDatabase } from './database';
@@ -274,7 +275,7 @@ export function startSyncWorkerCore(
274
275
  // let every wake-up that arrives while this round waits behind the
275
276
  // running one queue its own full drive (§8.4 coalescing).
276
277
  autoSyncScheduled = false;
277
- return running.syncUntilIdle({ skipEmpty: true });
278
+ return running.syncUntilIdle({ skipEmpty: true, coalesceMs });
278
279
  })
279
280
  .then((summary) => {
280
281
  retryDelayMs = 250;
@@ -409,11 +410,8 @@ export function startSyncWorkerCore(
409
410
  // Retain the leader lease while the previous worker's OPFS handles
410
411
  // drain. Only opening is retried; core initialization has not started.
411
412
  const delayMs = Math.min(50 * 2 ** attempt, 1000);
412
- if (overrides.waitForStorageRetry !== undefined) {
413
- await overrides.waitForStorageRetry(delayMs);
414
- } else {
415
- await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
416
- }
413
+ await (overrides.waitForStorageRetry?.(delayMs) ??
414
+ new Promise<void>((resolve) => setTimeout(resolve, delayMs)));
417
415
  }
418
416
  }
419
417
  const remote =
@@ -442,14 +440,26 @@ export function startSyncWorkerCore(
442
440
  let realtimeConnector: RealtimeConnector | undefined;
443
441
  offline = config.transportEnabled === false;
444
442
  const started = new SyncClient({
443
+ ...definedObject({
444
+ segments: bindings.segments,
445
+ blobs,
446
+ clientId: config.clientId,
447
+ limits: config.limits,
448
+ retainFailedCommits: config.retainFailedCommits,
449
+ realtimePolicy: config.realtimePolicy,
450
+ realtimeHeartbeatMs: config.realtimeHeartbeatMs,
451
+ encryption:
452
+ config.encryption && encryptionConfigFromKeyring(config.encryption),
453
+ authorityReads:
454
+ config.authorityReads &&
455
+ overrides.createAuthorityReads!(config.authorityReads),
456
+ securityPreflight: config.securityPreflight,
457
+ previousVersionContext: config.previousVersionContext,
458
+ }),
445
459
  transportEnabled: !offline,
446
460
  database,
447
461
  schema: config.schema,
448
462
  transport: bindings.transport,
449
- ...(bindings.segments !== undefined
450
- ? { segments: bindings.segments }
451
- : {}),
452
- ...(blobs !== undefined ? { blobs } : {}),
453
463
  realtime: (handlers, clientId) => {
454
464
  // §12.2: a local authority has no realtime channel.
455
465
  if (realtimeConnector === undefined || local?.active()) {
@@ -457,34 +467,7 @@ export function startSyncWorkerCore(
457
467
  }
458
468
  return realtimeConnector(handlers, clientId);
459
469
  },
460
- ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
461
- ...(config.limits !== undefined ? { limits: config.limits } : {}),
462
- ...(config.retainFailedCommits !== undefined
463
- ? { retainFailedCommits: config.retainFailedCommits }
464
- : {}),
465
- ...(config.realtimePolicy !== undefined
466
- ? { realtimePolicy: config.realtimePolicy }
467
- : {}),
468
- ...(config.realtimeHeartbeatMs !== undefined
469
- ? { realtimeHeartbeatMs: config.realtimeHeartbeatMs }
470
- : {}),
471
470
  schedule: scheduleBackground,
472
- ...(config.encryption !== undefined
473
- ? { encryption: encryptionConfigFromKeyring(config.encryption) }
474
- : {}),
475
- ...(config.authorityReads !== undefined
476
- ? {
477
- authorityReads: overrides.createAuthorityReads!(
478
- config.authorityReads,
479
- ),
480
- }
481
- : {}),
482
- ...(config.securityPreflight !== undefined
483
- ? { securityPreflight: config.securityPreflight }
484
- : {}),
485
- ...(config.previousVersionContext !== undefined
486
- ? { previousVersionContext: config.previousVersionContext }
487
- : {}),
488
471
  onSyncNeeded: (reason) => {
489
472
  emit({ kind: 'sync-needed', reason });
490
473
  consumeSyncIntent({ kind: 'interactive' });
@@ -600,7 +583,17 @@ export function startSyncWorkerCore(
600
583
  },
601
584
  syncUntilIdle: (options) => {
602
585
  const running = requireClient();
603
- return drive(() => running.syncUntilIdle(options));
586
+ // §8.4: a host drive through this handle (the realtime supervisor's)
587
+ // takes the handle's coalesceMs unless it names its own.
588
+ return drive(() =>
589
+ running.syncUntilIdle(
590
+ typeof options === 'object' &&
591
+ options.skipEmpty === true &&
592
+ options.coalesceMs === undefined
593
+ ? { ...options, coalesceMs }
594
+ : options,
595
+ ),
596
+ );
604
597
  },
605
598
  proveCurrentBase: (outcome, options) => {
606
599
  const running = requireClient();
@@ -721,10 +714,11 @@ async function defaultOpenDatabase(
721
714
  "database mode 'custom' requires startSyncWorker({ openDatabase })",
722
715
  );
723
716
  }
724
- return openPersistentWasmDatabase(config.database.name, {
725
- ...(config.database.directory !== undefined
726
- ? { directory: config.database.directory }
727
- : {}),
728
- ...(config.takeOverStorage === true ? { takeOver: true } : {}),
729
- });
717
+ return openPersistentWasmDatabase(
718
+ config.database.name,
719
+ definedObject({
720
+ directory: config.database.directory,
721
+ takeOver: config.takeOverStorage || undefined,
722
+ }),
723
+ );
730
724
  }