@syncular/client 0.57.0 → 0.59.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.
Files changed (82) hide show
  1. package/README.md +7 -7
  2. package/dist/apply.d.ts +20 -11
  3. package/dist/apply.js +67 -45
  4. package/dist/blob.d.ts +17 -9
  5. package/dist/blob.js +5 -6
  6. package/dist/bun-database.d.ts +1 -0
  7. package/dist/bun-database.js +28 -0
  8. package/dist/client.d.ts +27 -10
  9. package/dist/client.js +357 -190
  10. package/dist/database.d.ts +5 -0
  11. package/dist/encryption.d.ts +2 -2
  12. package/dist/encryption.js +8 -2
  13. package/dist/errors.d.ts +2 -0
  14. package/dist/errors.js +4 -0
  15. package/dist/failed-overlay.d.ts +0 -1
  16. package/dist/failed-overlay.js +3 -6
  17. package/dist/http.d.ts +4 -1
  18. package/dist/http.js +61 -39
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/invalidation.d.ts +11 -10
  22. package/dist/invalidation.js +15 -26
  23. package/dist/local-purge.js +9 -12
  24. package/dist/local-rebootstrap.js +2 -2
  25. package/dist/multi-tab.d.ts +89 -1
  26. package/dist/multi-tab.js +70 -31
  27. package/dist/native-bridge.d.ts +235 -0
  28. package/dist/native-bridge.js +789 -0
  29. package/dist/node-database.d.ts +1 -0
  30. package/dist/node-database.js +29 -0
  31. package/dist/outbox.d.ts +9 -12
  32. package/dist/outbox.js +19 -36
  33. package/dist/outcomes.js +3 -3
  34. package/dist/previous-version.js +96 -114
  35. package/dist/query-guard.d.ts +25 -24
  36. package/dist/query-guard.js +34 -191
  37. package/dist/reactive-store.js +53 -11
  38. package/dist/realtime-supervisor.d.ts +9 -2
  39. package/dist/realtime-supervisor.js +31 -7
  40. package/dist/remote.js +11 -15
  41. package/dist/schema.js +15 -10
  42. package/dist/sync-scheduler.js +28 -2
  43. package/dist/transport.d.ts +19 -4
  44. package/dist/wasm-database.js +58 -21
  45. package/dist/worker-core.d.ts +5 -0
  46. package/dist/worker-core.js +80 -72
  47. package/dist/worker-host.d.ts +10 -5
  48. package/dist/worker-host.js +64 -7
  49. package/dist/worker-local-authority.js +2 -2
  50. package/dist/worker-protocol.d.ts +6 -2
  51. package/package.json +11 -3
  52. package/src/apply.ts +91 -55
  53. package/src/blob.ts +27 -15
  54. package/src/bun-database.ts +29 -0
  55. package/src/client.ts +477 -261
  56. package/src/database.ts +5 -0
  57. package/src/encryption.ts +10 -5
  58. package/src/errors.ts +8 -0
  59. package/src/failed-overlay.ts +3 -7
  60. package/src/http.ts +90 -79
  61. package/src/index.ts +1 -1
  62. package/src/invalidation.ts +17 -32
  63. package/src/local-purge.ts +11 -13
  64. package/src/local-rebootstrap.ts +2 -3
  65. package/src/multi-tab.ts +88 -30
  66. package/src/native-bridge.ts +1189 -0
  67. package/src/node-database.ts +32 -0
  68. package/src/outbox.ts +19 -41
  69. package/src/outcomes.ts +3 -5
  70. package/src/previous-version.ts +103 -114
  71. package/src/query-guard.ts +43 -180
  72. package/src/reactive-store.ts +50 -10
  73. package/src/realtime-supervisor.ts +37 -12
  74. package/src/remote.ts +12 -16
  75. package/src/schema.ts +19 -12
  76. package/src/sync-scheduler.ts +31 -1
  77. package/src/transport.ts +21 -2
  78. package/src/wasm-database.ts +76 -27
  79. package/src/worker-core.ts +94 -74
  80. package/src/worker-host.ts +63 -16
  81. package/src/worker-local-authority.ts +2 -5
  82. package/src/worker-protocol.ts +6 -2
@@ -0,0 +1,1189 @@
1
+ /**
2
+ * The command bridge shared by the native hosts: `@syncular/tauri` (the Tauri
3
+ * plugin over IPC) and the React Native binding (the C-ABI core behind a
4
+ * TurboModule). Both drive one Rust core through the driver-protocol command
5
+ * envelope `{method, params}`, so the codec, the security preflight gate, the
6
+ * event fanout, and every command method live here. A host subclass supplies
7
+ * the transport: the generic command, the query fast path, the snapshot read,
8
+ * header replacement, and shutdown.
9
+ *
10
+ * Bytes cross as `{$bytes: hex}` and unsafe SQLite integers as
11
+ * `{$bigint: decimal}`, the convention of the Rust command router. The browser
12
+ * client and worker entries never import this module.
13
+ */
14
+ import {
15
+ type ClientSnapshotMethods,
16
+ type CurrentBaseProof,
17
+ type MutationInput,
18
+ type PresencePeer,
19
+ type PromiseMethods,
20
+ type QueryReadSpec,
21
+ type QuerySnapshot,
22
+ SECURITY_PREFLIGHT_REQUIRED_CODE,
23
+ type SecurityLifecycle,
24
+ type SnapshotRead,
25
+ type SnapshotReadRequest,
26
+ type SyncClientConfig,
27
+ type WindowState,
28
+ } from './client';
29
+ import type { SqlRow, SqlValue } from './database';
30
+ import type { PresenceErrorCode } from '@syncular/core';
31
+ import {
32
+ type ClientDiagnosticsListener,
33
+ type ClientDiagnosticsRequest,
34
+ type ClientDiagnosticsSnapshot,
35
+ withClientDiagnosticsHost,
36
+ } from './diagnostics';
37
+ import type { EncryptionKeyringConfig } from './encryption';
38
+ import type {
39
+ ClientChangeBatch,
40
+ ClientChangeListener,
41
+ InvalidationListener,
42
+ SyncStatusSnapshot,
43
+ } from './invalidation';
44
+ import type { LocalDataPurgeInput, LocalDataPurgeResult } from './local-purge';
45
+ import {
46
+ decodeLocalDataRebootstrapResult,
47
+ type LocalDataRebootstrapInput,
48
+ type LocalDataRebootstrapResult,
49
+ } from './local-rebootstrap';
50
+ import type {
51
+ CommitOutcome,
52
+ CommitOutcomeQuery,
53
+ ConflictRecord,
54
+ RejectionRecord,
55
+ ResolveCommitOutcomeInput,
56
+ RetainedCommitRow,
57
+ } from './outcomes';
58
+ import {
59
+ decodePreviousVersionAuditResult,
60
+ decodePreviousVersionDiscardResult,
61
+ decodePreviousVersionSnapshot,
62
+ type PreviousVersionAudit,
63
+ type PreviousVersionReadSpec,
64
+ type PreviousVersionSnapshot,
65
+ } from './previous-version';
66
+ import {
67
+ ProgressEmitter,
68
+ type SyncProgress,
69
+ type SyncProgressListener,
70
+ } from './progress';
71
+ import type { WindowBase } from './window';
72
+
73
+ /** A driver-protocol reply: `{result}` on success or `{error}` on failure. */
74
+ export interface NativeReply {
75
+ readonly result?: unknown;
76
+ readonly error?: {
77
+ readonly code: string;
78
+ readonly message: string;
79
+ readonly details?: Readonly<Record<string, unknown>> | null;
80
+ readonly retryable?: boolean;
81
+ };
82
+ }
83
+
84
+ /** One event the native core pushes (the derived client-observable set). */
85
+ export interface SyncularEvent {
86
+ readonly type: string;
87
+ readonly [key: string]: unknown;
88
+ }
89
+
90
+ /** The bytes envelope both sides share. */
91
+ export type BytesEnvelope = { readonly $bytes: string };
92
+
93
+ /** The `create` options every native host forwards to the Rust core. */
94
+ export interface NativeCreateConfig {
95
+ /** The generated schema JSON (the app passes `schema` from typegen). */
96
+ readonly schema: unknown;
97
+ /**
98
+ * Client id for this device or actor. If omitted, the native core generates
99
+ * one and persists it in the database. Supplying a different id when opening
100
+ * an existing database fails with `client.identity_mismatch`.
101
+ */
102
+ readonly clientId?: string;
103
+ /** §4.2 client limits. */
104
+ readonly limits?: Record<string, unknown>;
105
+ /**
106
+ * SPEC §8.8 realtime policy. Absent ⇒ `optional`. `required` refuses a sync
107
+ * round while the socket is not connected instead of falling back to HTTP.
108
+ */
109
+ readonly realtimePolicy?: SyncClientConfig['realtimePolicy'];
110
+ /**
111
+ * Portable E2EE keys and declarative per-row key-id columns, installed in
112
+ * the Rust core. Raw keys are never sent to the server.
113
+ */
114
+ readonly encryption?: EncryptionKeyringConfig;
115
+ /** Open the native replica behind the fail-closed security gate. */
116
+ readonly securityPreflight?: boolean;
117
+ /** RFC 0005 previous-version context (default off). */
118
+ readonly previousVersionContext?: SyncClientConfig['previousVersionContext'];
119
+ }
120
+
121
+ /** The error a native `{error}` reply surfaces (mirrors `ClientSyncError`). */
122
+ export class NativeSyncError extends Error {
123
+ readonly code: string;
124
+ readonly details: Readonly<Record<string, unknown>> | undefined;
125
+ readonly retryable: boolean;
126
+ constructor(
127
+ code: string,
128
+ message: string,
129
+ details?: Readonly<Record<string, unknown>>,
130
+ retryable = false,
131
+ ) {
132
+ super(message);
133
+ this.name = 'NativeSyncError';
134
+ this.code = code;
135
+ this.details = details;
136
+ this.retryable = retryable;
137
+ }
138
+ }
139
+
140
+ /** §7.1: exactly one `$bytes` key holding even-length hexadecimal. */
141
+ function isBytesEnvelope(value: unknown): value is BytesEnvelope {
142
+ if (typeof value !== 'object' || value === null) return false;
143
+ const record = value as Record<string, unknown>;
144
+ return (
145
+ Object.keys(record).length === 1 &&
146
+ typeof record.$bytes === 'string' &&
147
+ /^(?:[0-9a-fA-F]{2})*$/.test(record.$bytes)
148
+ );
149
+ }
150
+
151
+ function hexToBytes(hex: string): Uint8Array {
152
+ const out = new Uint8Array(hex.length / 2);
153
+ for (let i = 0; i < out.length; i++) {
154
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /** Encode a command value: bytes → `{$bytes}`, bigint → `{$bigint}`, recursively. */
160
+ function encodeValue(value: unknown): unknown {
161
+ if (value instanceof Uint8Array) {
162
+ let hex = '';
163
+ for (const byte of value) hex += byte.toString(16).padStart(2, '0');
164
+ return { $bytes: hex };
165
+ }
166
+ if (typeof value === 'bigint') return { $bigint: value.toString() };
167
+ if (Array.isArray(value)) return value.map(encodeValue);
168
+ if (value !== null && typeof value === 'object') {
169
+ const encoded: Record<string, unknown> = {};
170
+ for (const [key, member] of Object.entries(value)) {
171
+ encoded[key] = encodeValue(member);
172
+ }
173
+ return encoded;
174
+ }
175
+ return value;
176
+ }
177
+
178
+ function toStringSet(value: unknown): ReadonlySet<string> {
179
+ return new Set(
180
+ Array.isArray(value)
181
+ ? value.filter((v): v is string => typeof v === 'string')
182
+ : [],
183
+ );
184
+ }
185
+
186
+ function decodeChangeBatch(value: unknown): ClientChangeBatch | undefined {
187
+ if (value === null || typeof value !== 'object') return undefined;
188
+ const raw = value as Record<string, unknown>;
189
+ if (typeof raw.revision !== 'string') return undefined;
190
+ const tables = Array.isArray(raw.tables)
191
+ ? raw.tables.flatMap((entry) => {
192
+ if (entry === null || typeof entry !== 'object') return [];
193
+ const item = entry as Record<string, unknown>;
194
+ if (typeof item.table !== 'string') return [];
195
+ return [
196
+ {
197
+ table: item.table,
198
+ ...(Array.isArray(item.scopeKeys)
199
+ ? { scopeKeys: toStringSet(item.scopeKeys) }
200
+ : {}),
201
+ },
202
+ ];
203
+ })
204
+ : [];
205
+ const windows = Array.isArray(raw.windows)
206
+ ? raw.windows.flatMap((entry) => {
207
+ if (entry === null || typeof entry !== 'object') return [];
208
+ const item = entry as Record<string, unknown>;
209
+ if (
210
+ typeof item.baseKey !== 'string' ||
211
+ typeof item.table !== 'string'
212
+ ) {
213
+ return [];
214
+ }
215
+ return [
216
+ {
217
+ baseKey: item.baseKey,
218
+ table: item.table,
219
+ units: toStringSet(item.units),
220
+ },
221
+ ];
222
+ })
223
+ : [];
224
+ const appliedCommits: NonNullable<
225
+ ClientChangeBatch['appliedCommits']
226
+ >[number][] = [];
227
+ if (raw.appliedCommits !== undefined) {
228
+ if (!Array.isArray(raw.appliedCommits)) return undefined;
229
+ for (const entry of raw.appliedCommits) {
230
+ if (entry === null || typeof entry !== 'object') return undefined;
231
+ const item = entry as Record<string, unknown>;
232
+ if (
233
+ typeof item.subscriptionId !== 'string' ||
234
+ typeof item.table !== 'string' ||
235
+ typeof item.commitSeq !== 'number' ||
236
+ !Number.isSafeInteger(item.commitSeq) ||
237
+ item.commitSeq < 1 ||
238
+ (item.source !== 'delta' && item.source !== 'pull')
239
+ )
240
+ return undefined;
241
+ appliedCommits.push({
242
+ subscriptionId: item.subscriptionId,
243
+ table: item.table,
244
+ commitSeq: item.commitSeq,
245
+ source: item.source,
246
+ });
247
+ }
248
+ }
249
+ return {
250
+ revision: BigInt(raw.revision),
251
+ tables,
252
+ windows,
253
+ ...(raw.appliedCommits !== undefined ? { appliedCommits } : {}),
254
+ ...(raw.status !== undefined
255
+ ? { status: raw.status as SyncStatusSnapshot }
256
+ : {}),
257
+ conflictsChanged: raw.conflictsChanged === true,
258
+ rejectionsChanged: raw.rejectionsChanged === true,
259
+ outcomesChanged: raw.outcomesChanged === true,
260
+ };
261
+ }
262
+
263
+ /**
264
+ * The `create` params every native host sends. Keys cannot be installed
265
+ * before a security preflight; that combination fails before the host is
266
+ * touched.
267
+ */
268
+ export function nativeCreateParams(
269
+ config: NativeCreateConfig,
270
+ ErrorType: typeof NativeSyncError,
271
+ ): Record<string, unknown> {
272
+ if (config.securityPreflight === true && config.encryption !== undefined) {
273
+ throw new ErrorType(
274
+ 'sync.invalid_request',
275
+ 'securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight',
276
+ );
277
+ }
278
+ return {
279
+ schema: config.schema,
280
+ ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
281
+ ...(config.limits !== undefined ? { limits: config.limits } : {}),
282
+ ...(config.realtimePolicy !== undefined
283
+ ? { realtimePolicy: config.realtimePolicy }
284
+ : {}),
285
+ ...(config.encryption !== undefined
286
+ ? { encryption: encodeValue(config.encryption) }
287
+ : {}),
288
+ ...(config.securityPreflight !== undefined
289
+ ? { securityPreflight: config.securityPreflight }
290
+ : {}),
291
+ ...(config.previousVersionContext !== undefined
292
+ ? { previousVersionContext: config.previousVersionContext }
293
+ : {}),
294
+ };
295
+ }
296
+
297
+ /** A decoded outcome row cell; native outcome rows carry no `$bigint`. */
298
+ type OutcomeRowValue = ConflictRecord['serverRow'][string];
299
+
300
+ /**
301
+ * The `SyncClientLike` proxy over a native core. Every snapshot method
302
+ * returns a promise from one host round trip; React hooks accept the
303
+ * canonical snapshot interface directly.
304
+ */
305
+ export abstract class NativeBridgeClient implements PromiseMethods<ClientSnapshotMethods> {
306
+ readonly #kind: 'tauri' | 'react-native';
307
+ readonly #Error: typeof NativeSyncError;
308
+ readonly #release: () => void;
309
+ readonly #invalidationListeners = new Set<InvalidationListener>();
310
+ readonly #changeListeners = new Set<ClientChangeListener>();
311
+ readonly #progress = new ProgressEmitter();
312
+ readonly #diagnosticsListeners = new Set<ClientDiagnosticsListener>();
313
+ readonly #presenceListeners = new Set<
314
+ (scopeKey: string, error?: PresenceErrorCode) => void
315
+ >();
316
+ #closed = false;
317
+ #closing: Promise<void> | undefined;
318
+ #securityLifecycle: SecurityLifecycle;
319
+ #preflightBarrier: Promise<void> | undefined;
320
+
321
+ /**
322
+ * `release` detaches the host event listener; the bridge calls it once,
323
+ * after shutdown or after a failed `create`.
324
+ */
325
+ constructor(
326
+ kind: 'tauri' | 'react-native',
327
+ ErrorType: typeof NativeSyncError,
328
+ release: () => void,
329
+ securityLifecycle: SecurityLifecycle,
330
+ ) {
331
+ this.#kind = kind;
332
+ this.#Error = ErrorType;
333
+ this.#release = release;
334
+ this.#securityLifecycle = securityLifecycle;
335
+ }
336
+
337
+ /** Run one `{method, params}` command on the native core. */
338
+ protected abstract send(
339
+ method: string,
340
+ params: Record<string, unknown>,
341
+ ): Promise<NativeReply>;
342
+ /** The read-only SQL fast path; `params` are already envelope-encoded. */
343
+ protected abstract sendQuery(
344
+ sql: string,
345
+ params: unknown,
346
+ ): Promise<NativeReply>;
347
+ /** The atomic `querySnapshot` read. */
348
+ protected abstract sendQuerySnapshot(
349
+ params: Record<string, unknown>,
350
+ ): Promise<NativeReply>;
351
+ /** Replace the native transport's full header set. */
352
+ protected abstract sendHeaders(
353
+ headers: Readonly<Record<string, string>>,
354
+ ): Promise<NativeReply>;
355
+ /** Stop the native core. `close()` detaches listeners once it settles. */
356
+ protected abstract shutdown(): Promise<void>;
357
+
358
+ /** Unwrap a host reply; a rejected host call surfaces as `client.failed`. */
359
+ async #reply(send: () => Promise<NativeReply>): Promise<unknown> {
360
+ let reply: NativeReply;
361
+ try {
362
+ reply = await send();
363
+ } catch (cause) {
364
+ throw new this.#Error(
365
+ 'client.failed',
366
+ 'the native host rejected the call',
367
+ { cause: String(cause) },
368
+ );
369
+ }
370
+ if (reply.error !== undefined) {
371
+ throw new this.#Error(
372
+ reply.error.code,
373
+ reply.error.message,
374
+ reply.error.details ?? undefined,
375
+ reply.error.retryable ?? false,
376
+ );
377
+ }
378
+ return reply.result;
379
+ }
380
+
381
+ /** @internal Settle the native `create`; a failure detaches the listener. */
382
+ async __open(create: () => Promise<NativeReply>): Promise<void> {
383
+ try {
384
+ await this.#reply(create);
385
+ } catch (error) {
386
+ this.#release();
387
+ throw error;
388
+ }
389
+ }
390
+
391
+ /** Dispatch a command through the closed check and the preflight gate. */
392
+ protected async command(
393
+ method: string,
394
+ params: Record<string, unknown>,
395
+ ): Promise<unknown> {
396
+ this.requireOpen();
397
+ if (
398
+ this.#securityLifecycle === 'preflight' &&
399
+ ![
400
+ 'authoritySnapshot',
401
+ 'securityLifecycle',
402
+ 'beginSecurityPreflight',
403
+ 'activateSecurity',
404
+ 'setTransportEnabled',
405
+ 'purgeLocalData',
406
+ 'previousVersionDiscard',
407
+ 'localRevision',
408
+ 'statusSnapshot',
409
+ 'drainRealtime',
410
+ 'shutdown',
411
+ ].includes(method) &&
412
+ !this.allowPreflightCommand(method)
413
+ ) {
414
+ this.#throwSecurityPreflight();
415
+ }
416
+ return this.#reply(() => this.send(method, params));
417
+ }
418
+
419
+ /** Additional preflight operations a host subclass permits. */
420
+ protected allowPreflightCommand(_method: string): boolean {
421
+ return false;
422
+ }
423
+
424
+ protected get closed(): boolean {
425
+ return this.#closed;
426
+ }
427
+
428
+ protected get preflight(): boolean {
429
+ return this.#securityLifecycle === 'preflight';
430
+ }
431
+
432
+ protected requireOpen(): void {
433
+ if (this.#closed) {
434
+ throw new this.#Error(
435
+ 'client.closed',
436
+ 'the native sync client is closed',
437
+ );
438
+ }
439
+ }
440
+
441
+ #throwSecurityPreflight(): never {
442
+ throw new this.#Error(
443
+ SECURITY_PREFLIGHT_REQUIRED_CODE,
444
+ 'the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data',
445
+ );
446
+ }
447
+
448
+ #requireActive(): void {
449
+ this.requireOpen();
450
+ if (this.#securityLifecycle === 'preflight') this.#throwSecurityPreflight();
451
+ }
452
+
453
+ #cell(value: unknown): SqlValue {
454
+ if (typeof value === 'object' && value !== null && '$bytes' in value) {
455
+ // §7.1: a malformed envelope is refused, never padded into other bytes.
456
+ if (!isBytesEnvelope(value))
457
+ throw new this.#Error(
458
+ 'sync.invalid_request',
459
+ 'a $bytes envelope requires exactly one $bytes key holding an even-length hexadecimal string',
460
+ );
461
+ return hexToBytes(value.$bytes);
462
+ }
463
+ if (
464
+ typeof value === 'object' &&
465
+ value !== null &&
466
+ '$bigint' in value &&
467
+ typeof value.$bigint === 'string'
468
+ )
469
+ return BigInt(value.$bigint);
470
+ if (
471
+ value === null ||
472
+ typeof value === 'string' ||
473
+ typeof value === 'number' ||
474
+ typeof value === 'boolean'
475
+ ) {
476
+ return value;
477
+ }
478
+ // Other objects keep their JSON text (SQLite json columns arrive as text).
479
+ return JSON.stringify(value);
480
+ }
481
+
482
+ /** Decode a native row. Reserved `_sync_*` columns stay engine-internal,
483
+ * so a `SELECT *` row round-trips into `mutate()` values. */
484
+ protected decodeRow(row: Readonly<Record<string, unknown>>): SqlRow {
485
+ const out: SqlRow = {};
486
+ for (const [key, value] of Object.entries(row)) {
487
+ if (!key.startsWith('_sync_')) out[key] = this.#cell(value);
488
+ }
489
+ return out;
490
+ }
491
+
492
+ #outcomeRow(
493
+ row: Readonly<Record<string, unknown>>,
494
+ ): Record<string, OutcomeRowValue> {
495
+ const out: Record<string, OutcomeRowValue> = {};
496
+ for (const [key, cell] of Object.entries(this.decodeRow(row))) {
497
+ out[key] =
498
+ typeof cell === 'bigint'
499
+ ? JSON.stringify({ $bigint: String(cell) })
500
+ : cell;
501
+ }
502
+ return out;
503
+ }
504
+
505
+ #retainedRows(rows: readonly RetainedCommitRow[]): RetainedCommitRow[] {
506
+ return rows.map((row) => ({
507
+ ...row,
508
+ localRow: row.localRow === null ? null : this.#outcomeRow(row.localRow),
509
+ serverRow:
510
+ row.serverRow === null ? null : this.#outcomeRow(row.serverRow),
511
+ ...(row.uniqueConflicts !== undefined
512
+ ? {
513
+ uniqueConflicts: row.uniqueConflicts.map((conflict) => ({
514
+ ...conflict,
515
+ serverRow: this.#outcomeRow(conflict.serverRow),
516
+ })),
517
+ }
518
+ : {}),
519
+ }));
520
+ }
521
+
522
+ #conflict(conflict: ConflictRecord): ConflictRecord {
523
+ return { ...conflict, serverRow: this.#outcomeRow(conflict.serverRow) };
524
+ }
525
+
526
+ #commitOutcome(outcome: CommitOutcome): CommitOutcome {
527
+ return {
528
+ ...outcome,
529
+ results: outcome.results.map((result) =>
530
+ result.status === 'conflict'
531
+ ? { ...result, conflict: this.#conflict(result.conflict) }
532
+ : result,
533
+ ),
534
+ ...(outcome.retainedRows !== undefined
535
+ ? { retainedRows: this.#retainedRows(outcome.retainedRows) }
536
+ : {}),
537
+ };
538
+ }
539
+
540
+ /** @internal Fan an incoming native event out to the local listeners. */
541
+ __dispatchEvent(event: SyncularEvent): void {
542
+ // A UI listener that throws must never break event dispatch.
543
+ const fanOut = <Args extends unknown[]>(
544
+ listeners: ReadonlySet<(...args: Args) => void>,
545
+ ...args: Args
546
+ ) => {
547
+ for (const listener of listeners) {
548
+ try {
549
+ listener(...args);
550
+ } catch {}
551
+ }
552
+ };
553
+ switch (event.type) {
554
+ case 'progress':
555
+ this.#progress.emit(event.progress as SyncProgress);
556
+ break;
557
+ case 'change': {
558
+ const batch = decodeChangeBatch(event.batch);
559
+ if (batch === undefined) break;
560
+ fanOut(this.#changeListeners, batch);
561
+ if (batch.tables.length === 0 && batch.windows.length === 0) break;
562
+ const tables = new Set<string>();
563
+ const scopeKeys = new Set<string>();
564
+ for (const table of batch.tables) {
565
+ tables.add(table.table);
566
+ for (const key of table.scopeKeys ?? []) scopeKeys.add(key);
567
+ }
568
+ for (const window of batch.windows) tables.add(window.table);
569
+ fanOut(this.#invalidationListeners, { tables, scopeKeys });
570
+ break;
571
+ }
572
+ case 'presence':
573
+ fanOut(
574
+ this.#presenceListeners,
575
+ typeof event.scopeKey === 'string' ? event.scopeKey : '',
576
+ event.error as PresenceErrorCode | undefined,
577
+ );
578
+ break;
579
+ case 'diagnostics': {
580
+ const snapshot = event.snapshot as ClientDiagnosticsSnapshot | null;
581
+ if (
582
+ snapshot === null ||
583
+ typeof snapshot !== 'object' ||
584
+ snapshot.version !== 1 ||
585
+ snapshot.host === undefined
586
+ )
587
+ break;
588
+ fanOut(
589
+ this.#diagnosticsListeners,
590
+ withClientDiagnosticsHost(snapshot, {
591
+ ...snapshot.host,
592
+ kind: this.#kind,
593
+ role: 'single',
594
+ }),
595
+ );
596
+ break;
597
+ }
598
+ default:
599
+ // Unknown extension events are deliberately ignored. All durable
600
+ // observable state arrives in the revisioned `change` batch.
601
+ break;
602
+ }
603
+ }
604
+
605
+ // -- SyncClientLike --------------------------------------------------------
606
+
607
+ async securityLifecycle(): Promise<SecurityLifecycle> {
608
+ this.requireOpen();
609
+ return this.#securityLifecycle;
610
+ }
611
+
612
+ beginSecurityPreflight(): Promise<void> {
613
+ if (this.#closed) {
614
+ return Promise.reject(
615
+ new this.#Error('client.closed', 'the native sync client is closed'),
616
+ );
617
+ }
618
+ if (this.#preflightBarrier !== undefined) return this.#preflightBarrier;
619
+ // Flip synchronously so a same-tick query cannot race the native barrier.
620
+ this.#securityLifecycle = 'preflight';
621
+ const barrier = this.command('beginSecurityPreflight', {}).then(() => {});
622
+ this.#preflightBarrier = barrier;
623
+ const settle = () => {
624
+ if (this.#preflightBarrier === barrier)
625
+ this.#preflightBarrier = undefined;
626
+ };
627
+ void barrier.then(settle, settle);
628
+ return barrier;
629
+ }
630
+
631
+ /**
632
+ * Complete the security preflight. `headers` optionally carries a fresh
633
+ * FULL transport header set that the native host applies atomically with
634
+ * the activation, before the startup sync it enqueues, so a preflight that
635
+ * outlives the boot token starts its first round with valid credentials
636
+ * (the direct `setHeaders` path stays refused while gated).
637
+ */
638
+ async activateSecurity(
639
+ options: {
640
+ readonly encryption?: EncryptionKeyringConfig;
641
+ readonly headers?: Readonly<Record<string, string>>;
642
+ } = {},
643
+ ): Promise<void> {
644
+ this.requireOpen();
645
+ if (this.#securityLifecycle === 'active') {
646
+ throw new this.#Error(
647
+ 'sync.invalid_request',
648
+ 'activateSecurity requires the client to be in security preflight',
649
+ );
650
+ }
651
+ await this.#preflightBarrier;
652
+ await this.command('activateSecurity', {
653
+ ...(options.encryption !== undefined
654
+ ? { encryption: encodeValue(options.encryption) }
655
+ : {}),
656
+ ...(options.headers !== undefined ? { headers: options.headers } : {}),
657
+ });
658
+ this.#securityLifecycle = 'active';
659
+ }
660
+
661
+ onInvalidate(listener: InvalidationListener): () => void {
662
+ this.requireOpen();
663
+ this.#invalidationListeners.add(listener);
664
+ return () => this.#invalidationListeners.delete(listener);
665
+ }
666
+
667
+ onProgress(listener: SyncProgressListener): () => void {
668
+ this.requireOpen();
669
+ return this.#progress.on(listener);
670
+ }
671
+
672
+ progressSnapshot(): SyncProgress | undefined {
673
+ this.requireOpen();
674
+ return this.#progress.snapshot();
675
+ }
676
+
677
+ onChange(listener: ClientChangeListener): () => void {
678
+ this.requireOpen();
679
+ this.#changeListeners.add(listener);
680
+ return () => this.#changeListeners.delete(listener);
681
+ }
682
+
683
+ onDiagnostics(listener: ClientDiagnosticsListener): () => void {
684
+ this.requireOpen();
685
+ this.#diagnosticsListeners.add(listener);
686
+ return () => this.#diagnosticsListeners.delete(listener);
687
+ }
688
+
689
+ onPresence(
690
+ listener: (scopeKey: string, error?: PresenceErrorCode) => void,
691
+ ): () => void {
692
+ this.requireOpen();
693
+ this.#presenceListeners.add(listener);
694
+ return () => this.#presenceListeners.delete(listener);
695
+ }
696
+
697
+ async query(
698
+ sql: string,
699
+ params: readonly SqlValue[] = [],
700
+ ): Promise<SqlRow[]> {
701
+ this.#requireActive();
702
+ const result = (await this.#reply(() =>
703
+ this.sendQuery(sql, encodeValue(params)),
704
+ )) as { rows?: Readonly<Record<string, unknown>>[] };
705
+ return (result.rows ?? []).map((row) => this.decodeRow(row));
706
+ }
707
+
708
+ querySnapshot<Row = SqlRow>(spec: QueryReadSpec): Promise<QuerySnapshot<Row>>;
709
+ async querySnapshot(spec: QueryReadSpec): Promise<QuerySnapshot> {
710
+ this.#requireActive();
711
+ const result = (await this.#reply(() =>
712
+ this.sendQuerySnapshot({
713
+ sql: spec.sql,
714
+ params: encodeValue(spec.params ?? []),
715
+ coverage: spec.coverage ?? [],
716
+ ...(spec.owner !== undefined ? { owner: spec.owner } : {}),
717
+ }),
718
+ )) as {
719
+ revision: string;
720
+ rows: Record<string, unknown>[];
721
+ coverage: QuerySnapshot['coverage'];
722
+ };
723
+ return {
724
+ revision: BigInt(result.revision),
725
+ rows: result.rows.map((row) => this.decodeRow(row)),
726
+ coverage: result.coverage,
727
+ };
728
+ }
729
+
730
+ /**
731
+ * §7.5: one atomic read. Every statement and every catch-up and delivery
732
+ * read shares one revision and one read transaction.
733
+ */
734
+ async snapshotRead(request: SnapshotReadRequest): Promise<SnapshotRead> {
735
+ const result = (await this.command('snapshotRead', {
736
+ statements: request.statements.map((statement) => ({
737
+ sql: statement.sql,
738
+ params: encodeValue(statement.params ?? []),
739
+ })),
740
+ coverage: request.coverage ?? [],
741
+ subscriptions: request.subscriptions ?? [],
742
+ commitIds: request.commitIds ?? [],
743
+ ...(request.owner !== undefined ? { owner: request.owner } : {}),
744
+ })) as {
745
+ revision: string;
746
+ queries: readonly (readonly Record<string, unknown>[])[];
747
+ coverage: SnapshotRead['coverage'];
748
+ subscriptions: SnapshotRead['subscriptions'];
749
+ deliveries: SnapshotRead['deliveries'];
750
+ };
751
+ return {
752
+ revision: BigInt(result.revision),
753
+ queries: result.queries.map((rows) =>
754
+ rows.map((row) => this.decodeRow(row)),
755
+ ),
756
+ coverage: result.coverage,
757
+ subscriptions: result.subscriptions,
758
+ deliveries: result.deliveries.map((delivery) =>
759
+ delivery.status === 'known'
760
+ ? { ...delivery, outcome: this.#commitOutcome(delivery.outcome) }
761
+ : delivery,
762
+ ),
763
+ };
764
+ }
765
+
766
+ async localRevision(): Promise<bigint> {
767
+ const result = (await this.command('localRevision', {})) as {
768
+ revision: string;
769
+ };
770
+ return BigInt(result.revision);
771
+ }
772
+
773
+ async statusSnapshot(): Promise<SyncStatusSnapshot> {
774
+ return (await this.command('statusSnapshot', {})) as SyncStatusSnapshot;
775
+ }
776
+
777
+ async diagnosticsSnapshot(
778
+ request: ClientDiagnosticsRequest = {},
779
+ ): Promise<ClientDiagnosticsSnapshot> {
780
+ const snapshot = (await this.command('diagnosticsSnapshot', {
781
+ expectedSubscriptions: request.expectedSubscriptions ?? [],
782
+ })) as ClientDiagnosticsSnapshot;
783
+ return withClientDiagnosticsHost(snapshot, {
784
+ ...snapshot.host,
785
+ kind: this.#kind,
786
+ role: 'single',
787
+ });
788
+ }
789
+
790
+ async mutate(mutations: readonly MutationInput[]): Promise<string> {
791
+ const result = (await this.command('mutate', {
792
+ mutations: encodeValue(mutations),
793
+ })) as { clientCommitId: string };
794
+ return result.clientCommitId;
795
+ }
796
+
797
+ async patch(
798
+ table: string,
799
+ rowId: string,
800
+ partial: Readonly<Record<string, unknown>>,
801
+ options?: { readonly baseVersion?: number },
802
+ ): Promise<string> {
803
+ const result = (await this.command('patch', {
804
+ table,
805
+ rowId,
806
+ partial: encodeValue(partial),
807
+ ...(options?.baseVersion !== undefined
808
+ ? { baseVersion: options.baseVersion }
809
+ : {}),
810
+ })) as { clientCommitId: string };
811
+ return result.clientCommitId;
812
+ }
813
+
814
+ async purgeLocalData(
815
+ input: LocalDataPurgeInput,
816
+ ): Promise<LocalDataPurgeResult> {
817
+ return (await this.command('purgeLocalData', {
818
+ input,
819
+ })) as LocalDataPurgeResult;
820
+ }
821
+
822
+ async rebootstrapLocalData(
823
+ input: LocalDataRebootstrapInput,
824
+ ): Promise<LocalDataRebootstrapResult> {
825
+ return decodeLocalDataRebootstrapResult(
826
+ await this.command('rebootstrapLocalData', { input }),
827
+ );
828
+ }
829
+
830
+ async previousVersionSnapshot(
831
+ spec: PreviousVersionReadSpec,
832
+ ): Promise<PreviousVersionSnapshot> {
833
+ const reply = await this.command('previousVersionSnapshot', { spec });
834
+ // Decode the row cell envelopes first; a malformed reply passes through
835
+ // untouched so the strict decoder rejects it.
836
+ return decodePreviousVersionSnapshot(
837
+ reply !== null &&
838
+ typeof reply === 'object' &&
839
+ 'rows' in reply &&
840
+ Array.isArray(reply.rows)
841
+ ? {
842
+ ...reply,
843
+ rows: reply.rows.map((row) =>
844
+ row !== null && typeof row === 'object' && !Array.isArray(row)
845
+ ? this.decodeRow(row)
846
+ : row,
847
+ ),
848
+ }
849
+ : reply,
850
+ );
851
+ }
852
+
853
+ async previousVersionAudit(): Promise<PreviousVersionAudit | undefined> {
854
+ return decodePreviousVersionAuditResult(
855
+ await this.command('previousVersionAudit', {}),
856
+ );
857
+ }
858
+
859
+ async previousVersionDiscard(): Promise<{
860
+ present: boolean;
861
+ discarded: boolean;
862
+ }> {
863
+ return decodePreviousVersionDiscardResult(
864
+ await this.command('previousVersionDiscard', {}),
865
+ );
866
+ }
867
+
868
+ /**
869
+ * Replace the native transport's request headers at runtime, the auth
870
+ * rotation path. Pass the FULL header set: it replaces the current set.
871
+ * HTTP requests use the new set from the next call; the realtime socket
872
+ * applies it on its next (re)connect.
873
+ */
874
+ async setHeaders(headers: Readonly<Record<string, string>>): Promise<void> {
875
+ this.#requireActive();
876
+ await this.#reply(() => this.sendHeaders(headers));
877
+ }
878
+
879
+ // -- Native CRDT (SPEC.md §5.10.5; needs the host's `crdt-yjs` feature) ----
880
+
881
+ /** Materialize a `crdt` column's collaborative text from the stored
882
+ * (server-merged) Yjs bytes. `name` selects the shared text (default
883
+ * `"text"`). An absent row or NULL column is the empty document. */
884
+ async crdtText(
885
+ table: string,
886
+ rowId: string,
887
+ column: string,
888
+ name = 'text',
889
+ ): Promise<string> {
890
+ const result = (await this.command('crdtText', {
891
+ table,
892
+ rowId,
893
+ column,
894
+ name,
895
+ })) as { text: string };
896
+ return result.text;
897
+ }
898
+
899
+ /** Insert `value` at UTF-16 offset `index` in a `crdt` column's text and
900
+ * push the resulting Yjs update (baseVersion-less). Returns the commit id. */
901
+ async crdtInsertText(
902
+ table: string,
903
+ rowId: string,
904
+ column: string,
905
+ index: number,
906
+ value: string,
907
+ name = 'text',
908
+ ): Promise<string> {
909
+ const result = (await this.command('crdtInsertText', {
910
+ table,
911
+ rowId,
912
+ column,
913
+ name,
914
+ index,
915
+ value,
916
+ })) as { clientCommitId: string };
917
+ return result.clientCommitId;
918
+ }
919
+
920
+ /** Delete `len` UTF-16 code units at `index` in a `crdt` column's text. */
921
+ async crdtDeleteText(
922
+ table: string,
923
+ rowId: string,
924
+ column: string,
925
+ index: number,
926
+ len: number,
927
+ name = 'text',
928
+ ): Promise<string> {
929
+ const result = (await this.command('crdtDeleteText', {
930
+ table,
931
+ rowId,
932
+ column,
933
+ name,
934
+ index,
935
+ len,
936
+ })) as { clientCommitId: string };
937
+ return result.clientCommitId;
938
+ }
939
+
940
+ /** Apply an arbitrary Yjs update onto a `crdt` column. */
941
+ async crdtApplyUpdate(
942
+ table: string,
943
+ rowId: string,
944
+ column: string,
945
+ update: Uint8Array,
946
+ ): Promise<string> {
947
+ const result = (await this.command('crdtApplyUpdate', {
948
+ table,
949
+ rowId,
950
+ column,
951
+ update: encodeValue(update),
952
+ })) as { clientCommitId: string };
953
+ return result.clientCommitId;
954
+ }
955
+
956
+ /**
957
+ * Stage a blob for attachment (§5.9.7) and return the canonical `BlobRef`
958
+ * string to store in a `blob_ref` column. The native core owns the upload
959
+ * queue; write the referencing row after this resolves (§5.9.3).
960
+ */
961
+ async uploadBlob(
962
+ bytes: Uint8Array,
963
+ options?: { readonly mediaType?: string; readonly name?: string },
964
+ ): Promise<string> {
965
+ const result = (await this.command('uploadBlob', {
966
+ bytes: encodeValue(bytes),
967
+ ...(options?.mediaType !== undefined
968
+ ? { mediaType: options.mediaType }
969
+ : {}),
970
+ ...(options?.name !== undefined ? { name: options.name } : {}),
971
+ })) as { ref: string };
972
+ return result.ref;
973
+ }
974
+
975
+ /**
976
+ * Resolve blob bytes for a `blob_ref` column value or a bare `blobId`
977
+ * (§5.9.7): the native core serves a local cache hit and otherwise
978
+ * downloads and verifies the content address.
979
+ */
980
+ async fetchBlob(ref: string): Promise<{
981
+ readonly blobId: string;
982
+ readonly byteLength: number;
983
+ readonly bytes: Uint8Array;
984
+ readonly mediaType?: string;
985
+ }> {
986
+ const result = (await this.command('fetchBlob', { blob: ref })) as {
987
+ blob: {
988
+ blobId: string;
989
+ byteLength: number;
990
+ bytes: unknown;
991
+ mediaType?: string;
992
+ };
993
+ };
994
+ const bytes = result.blob.bytes;
995
+ if (!isBytesEnvelope(bytes))
996
+ throw new this.#Error(
997
+ 'sync.invalid_request',
998
+ 'fetchBlob reply carried no $bytes envelope',
999
+ );
1000
+ return {
1001
+ blobId: result.blob.blobId,
1002
+ byteLength: result.blob.byteLength,
1003
+ bytes: hexToBytes(bytes.$bytes),
1004
+ ...(result.blob.mediaType !== undefined
1005
+ ? { mediaType: result.blob.mediaType }
1006
+ : {}),
1007
+ };
1008
+ }
1009
+
1010
+ async subscribe(input: {
1011
+ readonly id: string;
1012
+ readonly table: string;
1013
+ readonly scopes?: Record<string, readonly string[]>;
1014
+ readonly params?: string;
1015
+ }): Promise<void> {
1016
+ await this.command('subscribe', {
1017
+ id: input.id,
1018
+ table: input.table,
1019
+ scopes: input.scopes ?? {},
1020
+ ...(input.params !== undefined ? { params: input.params } : {}),
1021
+ });
1022
+ }
1023
+
1024
+ /** Register several subscriptions in one local transaction. */
1025
+ async subscribeMany(
1026
+ inputs: readonly {
1027
+ readonly id: string;
1028
+ readonly table: string;
1029
+ readonly scopes?: Record<string, readonly string[]>;
1030
+ readonly params?: string;
1031
+ }[],
1032
+ ): Promise<void> {
1033
+ await this.command('subscribeMany', {
1034
+ subscriptions: inputs.map((input) => ({
1035
+ id: input.id,
1036
+ table: input.table,
1037
+ scopes: input.scopes ?? {},
1038
+ ...(input.params !== undefined ? { params: input.params } : {}),
1039
+ })),
1040
+ });
1041
+ }
1042
+
1043
+ async unsubscribe(id: string): Promise<void> {
1044
+ await this.command('unsubscribe', { id });
1045
+ }
1046
+
1047
+ async setWindow(base: WindowBase, units: readonly string[]): Promise<void> {
1048
+ await this.command('setWindow', { base, units });
1049
+ }
1050
+
1051
+ async windowState(base: WindowBase): Promise<WindowState> {
1052
+ const result = (await this.command('windowState', { base })) as {
1053
+ units: string[];
1054
+ pending: string[];
1055
+ };
1056
+ return { units: result.units, pending: result.pending };
1057
+ }
1058
+
1059
+ async sync(): Promise<unknown> {
1060
+ return this.command('sync', {});
1061
+ }
1062
+
1063
+ async syncUntilIdle(
1064
+ maxRounds?: number,
1065
+ timeoutMs?: number,
1066
+ ): Promise<unknown> {
1067
+ return this.command('syncUntilIdle', {
1068
+ ...(maxRounds !== undefined ? { maxRounds } : {}),
1069
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
1070
+ });
1071
+ }
1072
+
1073
+ async proveCurrentBase(
1074
+ outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>,
1075
+ maxRounds?: number,
1076
+ ): Promise<CurrentBaseProof> {
1077
+ if (
1078
+ maxRounds !== undefined &&
1079
+ (!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff)
1080
+ )
1081
+ throw new this.#Error(
1082
+ 'sync.invalid_request',
1083
+ 'maxRounds must be a positive integer',
1084
+ );
1085
+ const proof = (await this.command('proveCurrentBase', {
1086
+ outcome: {
1087
+ clientCommitId: outcome.clientCommitId,
1088
+ sequence: outcome.sequence,
1089
+ },
1090
+ ...(maxRounds !== undefined ? { maxRounds } : {}),
1091
+ })) as CurrentBaseProof;
1092
+ return proof.proven
1093
+ ? { proven: true, rows: this.#retainedRows(proof.rows) }
1094
+ : proof;
1095
+ }
1096
+
1097
+ async conflicts(): Promise<readonly ConflictRecord[]> {
1098
+ const result = (await this.command('conflicts', {})) as {
1099
+ conflicts: ConflictRecord[];
1100
+ };
1101
+ return result.conflicts.map((conflict) => this.#conflict(conflict));
1102
+ }
1103
+
1104
+ async rejections(): Promise<readonly RejectionRecord[]> {
1105
+ const result = (await this.command('rejections', {})) as {
1106
+ rejections: RejectionRecord[];
1107
+ };
1108
+ return result.rejections;
1109
+ }
1110
+
1111
+ async commitOutcome(
1112
+ clientCommitId: string,
1113
+ ): Promise<CommitOutcome | undefined> {
1114
+ const result = (await this.command('commitOutcome', {
1115
+ clientCommitId,
1116
+ })) as { outcome?: CommitOutcome };
1117
+ return result.outcome === undefined
1118
+ ? undefined
1119
+ : this.#commitOutcome(result.outcome);
1120
+ }
1121
+
1122
+ async commitOutcomes(
1123
+ query: CommitOutcomeQuery = {},
1124
+ ): Promise<readonly CommitOutcome[]> {
1125
+ const result = (await this.command('commitOutcomes', { query })) as {
1126
+ outcomes: CommitOutcome[];
1127
+ };
1128
+ return result.outcomes.map((outcome) => this.#commitOutcome(outcome));
1129
+ }
1130
+
1131
+ async resolveCommitOutcome(
1132
+ input: ResolveCommitOutcomeInput,
1133
+ ): Promise<CommitOutcome> {
1134
+ const result = (await this.command('resolveCommitOutcome', {
1135
+ input,
1136
+ })) as { outcome: CommitOutcome };
1137
+ return this.#commitOutcome(result.outcome);
1138
+ }
1139
+
1140
+ async pendingCommits(): Promise<unknown[]> {
1141
+ const result = (await this.command('pendingCommitIds', {})) as {
1142
+ ids: string[];
1143
+ };
1144
+ return result.ids;
1145
+ }
1146
+
1147
+ async presence(scopeKey: string): Promise<readonly PresencePeer[]> {
1148
+ const result = (await this.command('presence', { scopeKey })) as {
1149
+ peers: PresencePeer[];
1150
+ };
1151
+ return result.peers;
1152
+ }
1153
+
1154
+ async setPresence(
1155
+ scopeKey: string,
1156
+ doc: Record<string, unknown> | null,
1157
+ ): Promise<void> {
1158
+ await this.command('setPresence', { scopeKey, doc });
1159
+ }
1160
+
1161
+ async connectRealtime(): Promise<void> {
1162
+ await this.command('connectRealtime', {});
1163
+ }
1164
+
1165
+ async disconnectRealtime(): Promise<void> {
1166
+ await this.command('disconnectRealtime', {});
1167
+ }
1168
+
1169
+ /**
1170
+ * Shut down the native core, then detach listeners. Every call returns the
1171
+ * same promise, so a concurrent or repeated close settles only when the one
1172
+ * native shutdown settles, with its outcome.
1173
+ */
1174
+ close(): Promise<void> {
1175
+ if (this.#closing === undefined) {
1176
+ const shutdown = this.shutdown();
1177
+ this.#closed = true;
1178
+ this.#closing = shutdown.finally(() => {
1179
+ this.#release();
1180
+ this.#invalidationListeners.clear();
1181
+ this.#progress.clear();
1182
+ this.#changeListeners.clear();
1183
+ this.#diagnosticsListeners.clear();
1184
+ this.#presenceListeners.clear();
1185
+ });
1186
+ }
1187
+ return this.#closing;
1188
+ }
1189
+ }