@syncular/client 0.58.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,789 @@
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 { SECURITY_PREFLIGHT_REQUIRED_CODE, } from './client.js';
15
+ import { withClientDiagnosticsHost, } from './diagnostics.js';
16
+ import { decodeLocalDataRebootstrapResult, } from './local-rebootstrap.js';
17
+ import { decodePreviousVersionAuditResult, decodePreviousVersionDiscardResult, decodePreviousVersionSnapshot, } from './previous-version.js';
18
+ import { ProgressEmitter, } from './progress.js';
19
+ /** The error a native `{error}` reply surfaces (mirrors `ClientSyncError`). */
20
+ export class NativeSyncError extends Error {
21
+ code;
22
+ details;
23
+ retryable;
24
+ constructor(code, message, details, retryable = false) {
25
+ super(message);
26
+ this.name = 'NativeSyncError';
27
+ this.code = code;
28
+ this.details = details;
29
+ this.retryable = retryable;
30
+ }
31
+ }
32
+ /** §7.1: exactly one `$bytes` key holding even-length hexadecimal. */
33
+ function isBytesEnvelope(value) {
34
+ if (typeof value !== 'object' || value === null)
35
+ return false;
36
+ const record = value;
37
+ return (Object.keys(record).length === 1 &&
38
+ typeof record.$bytes === 'string' &&
39
+ /^(?:[0-9a-fA-F]{2})*$/.test(record.$bytes));
40
+ }
41
+ function hexToBytes(hex) {
42
+ const out = new Uint8Array(hex.length / 2);
43
+ for (let i = 0; i < out.length; i++) {
44
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
45
+ }
46
+ return out;
47
+ }
48
+ /** Encode a command value: bytes → `{$bytes}`, bigint → `{$bigint}`, recursively. */
49
+ function encodeValue(value) {
50
+ if (value instanceof Uint8Array) {
51
+ let hex = '';
52
+ for (const byte of value)
53
+ hex += byte.toString(16).padStart(2, '0');
54
+ return { $bytes: hex };
55
+ }
56
+ if (typeof value === 'bigint')
57
+ return { $bigint: value.toString() };
58
+ if (Array.isArray(value))
59
+ return value.map(encodeValue);
60
+ if (value !== null && typeof value === 'object') {
61
+ const encoded = {};
62
+ for (const [key, member] of Object.entries(value)) {
63
+ encoded[key] = encodeValue(member);
64
+ }
65
+ return encoded;
66
+ }
67
+ return value;
68
+ }
69
+ function toStringSet(value) {
70
+ return new Set(Array.isArray(value)
71
+ ? value.filter((v) => typeof v === 'string')
72
+ : []);
73
+ }
74
+ function decodeChangeBatch(value) {
75
+ if (value === null || typeof value !== 'object')
76
+ return undefined;
77
+ const raw = value;
78
+ if (typeof raw.revision !== 'string')
79
+ return undefined;
80
+ const tables = Array.isArray(raw.tables)
81
+ ? raw.tables.flatMap((entry) => {
82
+ if (entry === null || typeof entry !== 'object')
83
+ return [];
84
+ const item = entry;
85
+ if (typeof item.table !== 'string')
86
+ return [];
87
+ return [
88
+ {
89
+ table: item.table,
90
+ ...(Array.isArray(item.scopeKeys)
91
+ ? { scopeKeys: toStringSet(item.scopeKeys) }
92
+ : {}),
93
+ },
94
+ ];
95
+ })
96
+ : [];
97
+ const windows = Array.isArray(raw.windows)
98
+ ? raw.windows.flatMap((entry) => {
99
+ if (entry === null || typeof entry !== 'object')
100
+ return [];
101
+ const item = entry;
102
+ if (typeof item.baseKey !== 'string' ||
103
+ typeof item.table !== 'string') {
104
+ return [];
105
+ }
106
+ return [
107
+ {
108
+ baseKey: item.baseKey,
109
+ table: item.table,
110
+ units: toStringSet(item.units),
111
+ },
112
+ ];
113
+ })
114
+ : [];
115
+ const appliedCommits = [];
116
+ if (raw.appliedCommits !== undefined) {
117
+ if (!Array.isArray(raw.appliedCommits))
118
+ return undefined;
119
+ for (const entry of raw.appliedCommits) {
120
+ if (entry === null || typeof entry !== 'object')
121
+ return undefined;
122
+ const item = entry;
123
+ if (typeof item.subscriptionId !== 'string' ||
124
+ typeof item.table !== 'string' ||
125
+ typeof item.commitSeq !== 'number' ||
126
+ !Number.isSafeInteger(item.commitSeq) ||
127
+ item.commitSeq < 1 ||
128
+ (item.source !== 'delta' && item.source !== 'pull'))
129
+ return undefined;
130
+ appliedCommits.push({
131
+ subscriptionId: item.subscriptionId,
132
+ table: item.table,
133
+ commitSeq: item.commitSeq,
134
+ source: item.source,
135
+ });
136
+ }
137
+ }
138
+ return {
139
+ revision: BigInt(raw.revision),
140
+ tables,
141
+ windows,
142
+ ...(raw.appliedCommits !== undefined ? { appliedCommits } : {}),
143
+ ...(raw.status !== undefined
144
+ ? { status: raw.status }
145
+ : {}),
146
+ conflictsChanged: raw.conflictsChanged === true,
147
+ rejectionsChanged: raw.rejectionsChanged === true,
148
+ outcomesChanged: raw.outcomesChanged === true,
149
+ };
150
+ }
151
+ /**
152
+ * The `create` params every native host sends. Keys cannot be installed
153
+ * before a security preflight; that combination fails before the host is
154
+ * touched.
155
+ */
156
+ export function nativeCreateParams(config, ErrorType) {
157
+ if (config.securityPreflight === true && config.encryption !== undefined) {
158
+ throw new ErrorType('sync.invalid_request', 'securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight');
159
+ }
160
+ return {
161
+ schema: config.schema,
162
+ ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
163
+ ...(config.limits !== undefined ? { limits: config.limits } : {}),
164
+ ...(config.realtimePolicy !== undefined
165
+ ? { realtimePolicy: config.realtimePolicy }
166
+ : {}),
167
+ ...(config.encryption !== undefined
168
+ ? { encryption: encodeValue(config.encryption) }
169
+ : {}),
170
+ ...(config.securityPreflight !== undefined
171
+ ? { securityPreflight: config.securityPreflight }
172
+ : {}),
173
+ ...(config.previousVersionContext !== undefined
174
+ ? { previousVersionContext: config.previousVersionContext }
175
+ : {}),
176
+ };
177
+ }
178
+ /**
179
+ * The `SyncClientLike` proxy over a native core. Every snapshot method
180
+ * returns a promise from one host round trip; React hooks accept the
181
+ * canonical snapshot interface directly.
182
+ */
183
+ export class NativeBridgeClient {
184
+ #kind;
185
+ #Error;
186
+ #release;
187
+ #invalidationListeners = new Set();
188
+ #changeListeners = new Set();
189
+ #progress = new ProgressEmitter();
190
+ #diagnosticsListeners = new Set();
191
+ #presenceListeners = new Set();
192
+ #closed = false;
193
+ #closing;
194
+ #securityLifecycle;
195
+ #preflightBarrier;
196
+ /**
197
+ * `release` detaches the host event listener; the bridge calls it once,
198
+ * after shutdown or after a failed `create`.
199
+ */
200
+ constructor(kind, ErrorType, release, securityLifecycle) {
201
+ this.#kind = kind;
202
+ this.#Error = ErrorType;
203
+ this.#release = release;
204
+ this.#securityLifecycle = securityLifecycle;
205
+ }
206
+ /** Unwrap a host reply; a rejected host call surfaces as `client.failed`. */
207
+ async #reply(send) {
208
+ let reply;
209
+ try {
210
+ reply = await send();
211
+ }
212
+ catch (cause) {
213
+ throw new this.#Error('client.failed', 'the native host rejected the call', { cause: String(cause) });
214
+ }
215
+ if (reply.error !== undefined) {
216
+ throw new this.#Error(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
217
+ }
218
+ return reply.result;
219
+ }
220
+ /** @internal Settle the native `create`; a failure detaches the listener. */
221
+ async __open(create) {
222
+ try {
223
+ await this.#reply(create);
224
+ }
225
+ catch (error) {
226
+ this.#release();
227
+ throw error;
228
+ }
229
+ }
230
+ /** Dispatch a command through the closed check and the preflight gate. */
231
+ async command(method, params) {
232
+ this.requireOpen();
233
+ if (this.#securityLifecycle === 'preflight' &&
234
+ ![
235
+ 'authoritySnapshot',
236
+ 'securityLifecycle',
237
+ 'beginSecurityPreflight',
238
+ 'activateSecurity',
239
+ 'setTransportEnabled',
240
+ 'purgeLocalData',
241
+ 'previousVersionDiscard',
242
+ 'localRevision',
243
+ 'statusSnapshot',
244
+ 'drainRealtime',
245
+ 'shutdown',
246
+ ].includes(method) &&
247
+ !this.allowPreflightCommand(method)) {
248
+ this.#throwSecurityPreflight();
249
+ }
250
+ return this.#reply(() => this.send(method, params));
251
+ }
252
+ /** Additional preflight operations a host subclass permits. */
253
+ allowPreflightCommand(_method) {
254
+ return false;
255
+ }
256
+ get closed() {
257
+ return this.#closed;
258
+ }
259
+ get preflight() {
260
+ return this.#securityLifecycle === 'preflight';
261
+ }
262
+ requireOpen() {
263
+ if (this.#closed) {
264
+ throw new this.#Error('client.closed', 'the native sync client is closed');
265
+ }
266
+ }
267
+ #throwSecurityPreflight() {
268
+ throw new this.#Error(SECURITY_PREFLIGHT_REQUIRED_CODE, 'the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data');
269
+ }
270
+ #requireActive() {
271
+ this.requireOpen();
272
+ if (this.#securityLifecycle === 'preflight')
273
+ this.#throwSecurityPreflight();
274
+ }
275
+ #cell(value) {
276
+ if (typeof value === 'object' && value !== null && '$bytes' in value) {
277
+ // §7.1: a malformed envelope is refused, never padded into other bytes.
278
+ if (!isBytesEnvelope(value))
279
+ throw new this.#Error('sync.invalid_request', 'a $bytes envelope requires exactly one $bytes key holding an even-length hexadecimal string');
280
+ return hexToBytes(value.$bytes);
281
+ }
282
+ if (typeof value === 'object' &&
283
+ value !== null &&
284
+ '$bigint' in value &&
285
+ typeof value.$bigint === 'string')
286
+ return BigInt(value.$bigint);
287
+ if (value === null ||
288
+ typeof value === 'string' ||
289
+ typeof value === 'number' ||
290
+ typeof value === 'boolean') {
291
+ return value;
292
+ }
293
+ // Other objects keep their JSON text (SQLite json columns arrive as text).
294
+ return JSON.stringify(value);
295
+ }
296
+ /** Decode a native row. Reserved `_sync_*` columns stay engine-internal,
297
+ * so a `SELECT *` row round-trips into `mutate()` values. */
298
+ decodeRow(row) {
299
+ const out = {};
300
+ for (const [key, value] of Object.entries(row)) {
301
+ if (!key.startsWith('_sync_'))
302
+ out[key] = this.#cell(value);
303
+ }
304
+ return out;
305
+ }
306
+ #outcomeRow(row) {
307
+ const out = {};
308
+ for (const [key, cell] of Object.entries(this.decodeRow(row))) {
309
+ out[key] =
310
+ typeof cell === 'bigint'
311
+ ? JSON.stringify({ $bigint: String(cell) })
312
+ : cell;
313
+ }
314
+ return out;
315
+ }
316
+ #retainedRows(rows) {
317
+ return rows.map((row) => ({
318
+ ...row,
319
+ localRow: row.localRow === null ? null : this.#outcomeRow(row.localRow),
320
+ serverRow: row.serverRow === null ? null : this.#outcomeRow(row.serverRow),
321
+ ...(row.uniqueConflicts !== undefined
322
+ ? {
323
+ uniqueConflicts: row.uniqueConflicts.map((conflict) => ({
324
+ ...conflict,
325
+ serverRow: this.#outcomeRow(conflict.serverRow),
326
+ })),
327
+ }
328
+ : {}),
329
+ }));
330
+ }
331
+ #conflict(conflict) {
332
+ return { ...conflict, serverRow: this.#outcomeRow(conflict.serverRow) };
333
+ }
334
+ #commitOutcome(outcome) {
335
+ return {
336
+ ...outcome,
337
+ results: outcome.results.map((result) => result.status === 'conflict'
338
+ ? { ...result, conflict: this.#conflict(result.conflict) }
339
+ : result),
340
+ ...(outcome.retainedRows !== undefined
341
+ ? { retainedRows: this.#retainedRows(outcome.retainedRows) }
342
+ : {}),
343
+ };
344
+ }
345
+ /** @internal Fan an incoming native event out to the local listeners. */
346
+ __dispatchEvent(event) {
347
+ // A UI listener that throws must never break event dispatch.
348
+ const fanOut = (listeners, ...args) => {
349
+ for (const listener of listeners) {
350
+ try {
351
+ listener(...args);
352
+ }
353
+ catch { }
354
+ }
355
+ };
356
+ switch (event.type) {
357
+ case 'progress':
358
+ this.#progress.emit(event.progress);
359
+ break;
360
+ case 'change': {
361
+ const batch = decodeChangeBatch(event.batch);
362
+ if (batch === undefined)
363
+ break;
364
+ fanOut(this.#changeListeners, batch);
365
+ if (batch.tables.length === 0 && batch.windows.length === 0)
366
+ break;
367
+ const tables = new Set();
368
+ const scopeKeys = new Set();
369
+ for (const table of batch.tables) {
370
+ tables.add(table.table);
371
+ for (const key of table.scopeKeys ?? [])
372
+ scopeKeys.add(key);
373
+ }
374
+ for (const window of batch.windows)
375
+ tables.add(window.table);
376
+ fanOut(this.#invalidationListeners, { tables, scopeKeys });
377
+ break;
378
+ }
379
+ case 'presence':
380
+ fanOut(this.#presenceListeners, typeof event.scopeKey === 'string' ? event.scopeKey : '', event.error);
381
+ break;
382
+ case 'diagnostics': {
383
+ const snapshot = event.snapshot;
384
+ if (snapshot === null ||
385
+ typeof snapshot !== 'object' ||
386
+ snapshot.version !== 1 ||
387
+ snapshot.host === undefined)
388
+ break;
389
+ fanOut(this.#diagnosticsListeners, withClientDiagnosticsHost(snapshot, {
390
+ ...snapshot.host,
391
+ kind: this.#kind,
392
+ role: 'single',
393
+ }));
394
+ break;
395
+ }
396
+ default:
397
+ // Unknown extension events are deliberately ignored. All durable
398
+ // observable state arrives in the revisioned `change` batch.
399
+ break;
400
+ }
401
+ }
402
+ // -- SyncClientLike --------------------------------------------------------
403
+ async securityLifecycle() {
404
+ this.requireOpen();
405
+ return this.#securityLifecycle;
406
+ }
407
+ beginSecurityPreflight() {
408
+ if (this.#closed) {
409
+ return Promise.reject(new this.#Error('client.closed', 'the native sync client is closed'));
410
+ }
411
+ if (this.#preflightBarrier !== undefined)
412
+ return this.#preflightBarrier;
413
+ // Flip synchronously so a same-tick query cannot race the native barrier.
414
+ this.#securityLifecycle = 'preflight';
415
+ const barrier = this.command('beginSecurityPreflight', {}).then(() => { });
416
+ this.#preflightBarrier = barrier;
417
+ const settle = () => {
418
+ if (this.#preflightBarrier === barrier)
419
+ this.#preflightBarrier = undefined;
420
+ };
421
+ void barrier.then(settle, settle);
422
+ return barrier;
423
+ }
424
+ /**
425
+ * Complete the security preflight. `headers` optionally carries a fresh
426
+ * FULL transport header set that the native host applies atomically with
427
+ * the activation, before the startup sync it enqueues, so a preflight that
428
+ * outlives the boot token starts its first round with valid credentials
429
+ * (the direct `setHeaders` path stays refused while gated).
430
+ */
431
+ async activateSecurity(options = {}) {
432
+ this.requireOpen();
433
+ if (this.#securityLifecycle === 'active') {
434
+ throw new this.#Error('sync.invalid_request', 'activateSecurity requires the client to be in security preflight');
435
+ }
436
+ await this.#preflightBarrier;
437
+ await this.command('activateSecurity', {
438
+ ...(options.encryption !== undefined
439
+ ? { encryption: encodeValue(options.encryption) }
440
+ : {}),
441
+ ...(options.headers !== undefined ? { headers: options.headers } : {}),
442
+ });
443
+ this.#securityLifecycle = 'active';
444
+ }
445
+ onInvalidate(listener) {
446
+ this.requireOpen();
447
+ this.#invalidationListeners.add(listener);
448
+ return () => this.#invalidationListeners.delete(listener);
449
+ }
450
+ onProgress(listener) {
451
+ this.requireOpen();
452
+ return this.#progress.on(listener);
453
+ }
454
+ progressSnapshot() {
455
+ this.requireOpen();
456
+ return this.#progress.snapshot();
457
+ }
458
+ onChange(listener) {
459
+ this.requireOpen();
460
+ this.#changeListeners.add(listener);
461
+ return () => this.#changeListeners.delete(listener);
462
+ }
463
+ onDiagnostics(listener) {
464
+ this.requireOpen();
465
+ this.#diagnosticsListeners.add(listener);
466
+ return () => this.#diagnosticsListeners.delete(listener);
467
+ }
468
+ onPresence(listener) {
469
+ this.requireOpen();
470
+ this.#presenceListeners.add(listener);
471
+ return () => this.#presenceListeners.delete(listener);
472
+ }
473
+ async query(sql, params = []) {
474
+ this.#requireActive();
475
+ const result = (await this.#reply(() => this.sendQuery(sql, encodeValue(params))));
476
+ return (result.rows ?? []).map((row) => this.decodeRow(row));
477
+ }
478
+ async querySnapshot(spec) {
479
+ this.#requireActive();
480
+ const result = (await this.#reply(() => this.sendQuerySnapshot({
481
+ sql: spec.sql,
482
+ params: encodeValue(spec.params ?? []),
483
+ coverage: spec.coverage ?? [],
484
+ ...(spec.owner !== undefined ? { owner: spec.owner } : {}),
485
+ })));
486
+ return {
487
+ revision: BigInt(result.revision),
488
+ rows: result.rows.map((row) => this.decodeRow(row)),
489
+ coverage: result.coverage,
490
+ };
491
+ }
492
+ /**
493
+ * §7.5: one atomic read. Every statement and every catch-up and delivery
494
+ * read shares one revision and one read transaction.
495
+ */
496
+ async snapshotRead(request) {
497
+ const result = (await this.command('snapshotRead', {
498
+ statements: request.statements.map((statement) => ({
499
+ sql: statement.sql,
500
+ params: encodeValue(statement.params ?? []),
501
+ })),
502
+ coverage: request.coverage ?? [],
503
+ subscriptions: request.subscriptions ?? [],
504
+ commitIds: request.commitIds ?? [],
505
+ ...(request.owner !== undefined ? { owner: request.owner } : {}),
506
+ }));
507
+ return {
508
+ revision: BigInt(result.revision),
509
+ queries: result.queries.map((rows) => rows.map((row) => this.decodeRow(row))),
510
+ coverage: result.coverage,
511
+ subscriptions: result.subscriptions,
512
+ deliveries: result.deliveries.map((delivery) => delivery.status === 'known'
513
+ ? { ...delivery, outcome: this.#commitOutcome(delivery.outcome) }
514
+ : delivery),
515
+ };
516
+ }
517
+ async localRevision() {
518
+ const result = (await this.command('localRevision', {}));
519
+ return BigInt(result.revision);
520
+ }
521
+ async statusSnapshot() {
522
+ return (await this.command('statusSnapshot', {}));
523
+ }
524
+ async diagnosticsSnapshot(request = {}) {
525
+ const snapshot = (await this.command('diagnosticsSnapshot', {
526
+ expectedSubscriptions: request.expectedSubscriptions ?? [],
527
+ }));
528
+ return withClientDiagnosticsHost(snapshot, {
529
+ ...snapshot.host,
530
+ kind: this.#kind,
531
+ role: 'single',
532
+ });
533
+ }
534
+ async mutate(mutations) {
535
+ const result = (await this.command('mutate', {
536
+ mutations: encodeValue(mutations),
537
+ }));
538
+ return result.clientCommitId;
539
+ }
540
+ async patch(table, rowId, partial, options) {
541
+ const result = (await this.command('patch', {
542
+ table,
543
+ rowId,
544
+ partial: encodeValue(partial),
545
+ ...(options?.baseVersion !== undefined
546
+ ? { baseVersion: options.baseVersion }
547
+ : {}),
548
+ }));
549
+ return result.clientCommitId;
550
+ }
551
+ async purgeLocalData(input) {
552
+ return (await this.command('purgeLocalData', {
553
+ input,
554
+ }));
555
+ }
556
+ async rebootstrapLocalData(input) {
557
+ return decodeLocalDataRebootstrapResult(await this.command('rebootstrapLocalData', { input }));
558
+ }
559
+ async previousVersionSnapshot(spec) {
560
+ const reply = await this.command('previousVersionSnapshot', { spec });
561
+ // Decode the row cell envelopes first; a malformed reply passes through
562
+ // untouched so the strict decoder rejects it.
563
+ return decodePreviousVersionSnapshot(reply !== null &&
564
+ typeof reply === 'object' &&
565
+ 'rows' in reply &&
566
+ Array.isArray(reply.rows)
567
+ ? {
568
+ ...reply,
569
+ rows: reply.rows.map((row) => row !== null && typeof row === 'object' && !Array.isArray(row)
570
+ ? this.decodeRow(row)
571
+ : row),
572
+ }
573
+ : reply);
574
+ }
575
+ async previousVersionAudit() {
576
+ return decodePreviousVersionAuditResult(await this.command('previousVersionAudit', {}));
577
+ }
578
+ async previousVersionDiscard() {
579
+ return decodePreviousVersionDiscardResult(await this.command('previousVersionDiscard', {}));
580
+ }
581
+ /**
582
+ * Replace the native transport's request headers at runtime, the auth
583
+ * rotation path. Pass the FULL header set: it replaces the current set.
584
+ * HTTP requests use the new set from the next call; the realtime socket
585
+ * applies it on its next (re)connect.
586
+ */
587
+ async setHeaders(headers) {
588
+ this.#requireActive();
589
+ await this.#reply(() => this.sendHeaders(headers));
590
+ }
591
+ // -- Native CRDT (SPEC.md §5.10.5; needs the host's `crdt-yjs` feature) ----
592
+ /** Materialize a `crdt` column's collaborative text from the stored
593
+ * (server-merged) Yjs bytes. `name` selects the shared text (default
594
+ * `"text"`). An absent row or NULL column is the empty document. */
595
+ async crdtText(table, rowId, column, name = 'text') {
596
+ const result = (await this.command('crdtText', {
597
+ table,
598
+ rowId,
599
+ column,
600
+ name,
601
+ }));
602
+ return result.text;
603
+ }
604
+ /** Insert `value` at UTF-16 offset `index` in a `crdt` column's text and
605
+ * push the resulting Yjs update (baseVersion-less). Returns the commit id. */
606
+ async crdtInsertText(table, rowId, column, index, value, name = 'text') {
607
+ const result = (await this.command('crdtInsertText', {
608
+ table,
609
+ rowId,
610
+ column,
611
+ name,
612
+ index,
613
+ value,
614
+ }));
615
+ return result.clientCommitId;
616
+ }
617
+ /** Delete `len` UTF-16 code units at `index` in a `crdt` column's text. */
618
+ async crdtDeleteText(table, rowId, column, index, len, name = 'text') {
619
+ const result = (await this.command('crdtDeleteText', {
620
+ table,
621
+ rowId,
622
+ column,
623
+ name,
624
+ index,
625
+ len,
626
+ }));
627
+ return result.clientCommitId;
628
+ }
629
+ /** Apply an arbitrary Yjs update onto a `crdt` column. */
630
+ async crdtApplyUpdate(table, rowId, column, update) {
631
+ const result = (await this.command('crdtApplyUpdate', {
632
+ table,
633
+ rowId,
634
+ column,
635
+ update: encodeValue(update),
636
+ }));
637
+ return result.clientCommitId;
638
+ }
639
+ /**
640
+ * Stage a blob for attachment (§5.9.7) and return the canonical `BlobRef`
641
+ * string to store in a `blob_ref` column. The native core owns the upload
642
+ * queue; write the referencing row after this resolves (§5.9.3).
643
+ */
644
+ async uploadBlob(bytes, options) {
645
+ const result = (await this.command('uploadBlob', {
646
+ bytes: encodeValue(bytes),
647
+ ...(options?.mediaType !== undefined
648
+ ? { mediaType: options.mediaType }
649
+ : {}),
650
+ ...(options?.name !== undefined ? { name: options.name } : {}),
651
+ }));
652
+ return result.ref;
653
+ }
654
+ /**
655
+ * Resolve blob bytes for a `blob_ref` column value or a bare `blobId`
656
+ * (§5.9.7): the native core serves a local cache hit and otherwise
657
+ * downloads and verifies the content address.
658
+ */
659
+ async fetchBlob(ref) {
660
+ const result = (await this.command('fetchBlob', { blob: ref }));
661
+ const bytes = result.blob.bytes;
662
+ if (!isBytesEnvelope(bytes))
663
+ throw new this.#Error('sync.invalid_request', 'fetchBlob reply carried no $bytes envelope');
664
+ return {
665
+ blobId: result.blob.blobId,
666
+ byteLength: result.blob.byteLength,
667
+ bytes: hexToBytes(bytes.$bytes),
668
+ ...(result.blob.mediaType !== undefined
669
+ ? { mediaType: result.blob.mediaType }
670
+ : {}),
671
+ };
672
+ }
673
+ async subscribe(input) {
674
+ await this.command('subscribe', {
675
+ id: input.id,
676
+ table: input.table,
677
+ scopes: input.scopes ?? {},
678
+ ...(input.params !== undefined ? { params: input.params } : {}),
679
+ });
680
+ }
681
+ /** Register several subscriptions in one local transaction. */
682
+ async subscribeMany(inputs) {
683
+ await this.command('subscribeMany', {
684
+ subscriptions: inputs.map((input) => ({
685
+ id: input.id,
686
+ table: input.table,
687
+ scopes: input.scopes ?? {},
688
+ ...(input.params !== undefined ? { params: input.params } : {}),
689
+ })),
690
+ });
691
+ }
692
+ async unsubscribe(id) {
693
+ await this.command('unsubscribe', { id });
694
+ }
695
+ async setWindow(base, units) {
696
+ await this.command('setWindow', { base, units });
697
+ }
698
+ async windowState(base) {
699
+ const result = (await this.command('windowState', { base }));
700
+ return { units: result.units, pending: result.pending };
701
+ }
702
+ async sync() {
703
+ return this.command('sync', {});
704
+ }
705
+ async syncUntilIdle(maxRounds, timeoutMs) {
706
+ return this.command('syncUntilIdle', {
707
+ ...(maxRounds !== undefined ? { maxRounds } : {}),
708
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
709
+ });
710
+ }
711
+ async proveCurrentBase(outcome, maxRounds) {
712
+ if (maxRounds !== undefined &&
713
+ (!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff))
714
+ throw new this.#Error('sync.invalid_request', 'maxRounds must be a positive integer');
715
+ const proof = (await this.command('proveCurrentBase', {
716
+ outcome: {
717
+ clientCommitId: outcome.clientCommitId,
718
+ sequence: outcome.sequence,
719
+ },
720
+ ...(maxRounds !== undefined ? { maxRounds } : {}),
721
+ }));
722
+ return proof.proven
723
+ ? { proven: true, rows: this.#retainedRows(proof.rows) }
724
+ : proof;
725
+ }
726
+ async conflicts() {
727
+ const result = (await this.command('conflicts', {}));
728
+ return result.conflicts.map((conflict) => this.#conflict(conflict));
729
+ }
730
+ async rejections() {
731
+ const result = (await this.command('rejections', {}));
732
+ return result.rejections;
733
+ }
734
+ async commitOutcome(clientCommitId) {
735
+ const result = (await this.command('commitOutcome', {
736
+ clientCommitId,
737
+ }));
738
+ return result.outcome === undefined
739
+ ? undefined
740
+ : this.#commitOutcome(result.outcome);
741
+ }
742
+ async commitOutcomes(query = {}) {
743
+ const result = (await this.command('commitOutcomes', { query }));
744
+ return result.outcomes.map((outcome) => this.#commitOutcome(outcome));
745
+ }
746
+ async resolveCommitOutcome(input) {
747
+ const result = (await this.command('resolveCommitOutcome', {
748
+ input,
749
+ }));
750
+ return this.#commitOutcome(result.outcome);
751
+ }
752
+ async pendingCommits() {
753
+ const result = (await this.command('pendingCommitIds', {}));
754
+ return result.ids;
755
+ }
756
+ async presence(scopeKey) {
757
+ const result = (await this.command('presence', { scopeKey }));
758
+ return result.peers;
759
+ }
760
+ async setPresence(scopeKey, doc) {
761
+ await this.command('setPresence', { scopeKey, doc });
762
+ }
763
+ async connectRealtime() {
764
+ await this.command('connectRealtime', {});
765
+ }
766
+ async disconnectRealtime() {
767
+ await this.command('disconnectRealtime', {});
768
+ }
769
+ /**
770
+ * Shut down the native core, then detach listeners. Every call returns the
771
+ * same promise, so a concurrent or repeated close settles only when the one
772
+ * native shutdown settles, with its outcome.
773
+ */
774
+ close() {
775
+ if (this.#closing === undefined) {
776
+ const shutdown = this.shutdown();
777
+ this.#closed = true;
778
+ this.#closing = shutdown.finally(() => {
779
+ this.#release();
780
+ this.#invalidationListeners.clear();
781
+ this.#progress.clear();
782
+ this.#changeListeners.clear();
783
+ this.#diagnosticsListeners.clear();
784
+ this.#presenceListeners.clear();
785
+ });
786
+ }
787
+ return this.#closing;
788
+ }
789
+ }