@syncular/tauri 0.58.0 → 0.60.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/remote.ts CHANGED
@@ -1,110 +1,47 @@
1
- import {
2
- ProgressEmitter,
3
- type SyncProgress,
4
- type SyncProgressListener,
5
- } from '@syncular/client';
6
- import type { ClientSnapshotMethods, PromiseMethods } from '@syncular/client';
7
1
  /**
8
- * @syncular/tauri — the JS bridge to the native syncular instance running
9
- * inside the Tauri process (see `tauri-plugin-syncular`).
2
+ * @syncular/tauri: the JS bridge to the native syncular client running inside
3
+ * the Tauri process (see `tauri-plugin-syncular`).
10
4
  *
11
5
  * The Tauri host runs a REAL Rust syncular client (file DB + native HTTP+WS
12
- * transport). This module is a thin webview-side proxy that implements the SAME
13
- * `SyncClientLike` interface the React package normalizes — so the hooks
14
- * (`useRawSql`, `useMutation`, `usePresence`, …) work UNCHANGED against a
15
- * Tauri app. It is the fourth host of one interface, after the direct
16
- * `SyncClient`, the worker-leader `SyncClientHandle`, and the multi-tab
17
- * follower.
6
+ * transport). This module is the webview-side proxy over the shared native
7
+ * command bridge (`@syncular/client/native-bridge`), so the React hooks
8
+ * (`useRawSql`, `useMutation`, `usePresence`, …) work unchanged against a
9
+ * Tauri app.
18
10
  *
19
11
  * Every method forwards to the plugin's `syncular_command` command (the whole
20
- * command surface in one JSON envelope — `{method, params}`), mirroring the FFI
21
- * and the conformance shim. `query` uses the dedicated `syncular_query` fast
22
- * path; atomic reactive reads use `syncular_query_snapshot`, backed by an
23
- * independent read-only SQLite connection so network sync cannot stall local
24
- * UI reads. Client-observable
25
- * events (`change` / `presence`) arrive on
26
- * the `syncular://event` Tauri event and fan out to the registered listeners.
27
- *
28
- * Bytes cross the command JSON as the established `{$bytes: hex}` envelope, the
29
- * same convention the Rust command router and the driver protocol use.
12
+ * command surface in one `{method, params}` envelope). `query` uses the
13
+ * dedicated `syncular_query` fast path; atomic reactive reads use
14
+ * `syncular_query_snapshot`, backed by an independent read-only SQLite
15
+ * connection so network sync cannot stall local UI reads. Client-observable
16
+ * events arrive on the Tauri IPC channel the bridge passes to `create`, so
17
+ * only this webview receives them.
30
18
  *
31
- * `@tauri-apps/api` is a required peer dependency: the bridge takes
32
- * `invoke`/`listen` either from its ESM entry points, from the ambient
19
+ * `@tauri-apps/api` is a required peer dependency: the bridge takes `invoke`
20
+ * and `Channel` either from `@tauri-apps/api/core`, from the ambient
33
21
  * `window.__TAURI__`, or via injected doubles (tests).
34
22
  */
35
-
36
23
  import type {
37
24
  AuthorityReadPolicy,
38
- ClientChangeBatch,
39
- ClientChangeListener,
40
25
  ClientDiagnosticsListener,
41
- ClientDiagnosticsRequest,
42
- ClientDiagnosticsSnapshot,
43
- CommitOutcome,
44
- CommitOutcomeQuery,
45
- CurrentBaseProof,
46
- ConflictRecord,
47
- EncryptionKeyringConfig,
48
- InvalidationEvent,
49
- InvalidationListener,
50
- LocalDataPurgeInput,
51
- LocalDataPurgeResult,
52
- LocalDataRebootstrapInput,
53
- LocalDataRebootstrapResult,
54
- MutationInput,
55
- PresencePeer,
56
- PreviousVersionAudit,
57
- PreviousVersionReadSpec,
58
- PreviousVersionSnapshot,
59
- QueryReadSpec,
60
- QuerySnapshot,
61
- RejectionRecord,
62
- ResolveCommitOutcomeInput,
63
- RetainedCommitRow,
64
26
  SecurityLifecycle,
65
27
  SnapshotRead,
66
- SnapshotReadRequest,
67
- SqlRow,
68
- SqlValue,
69
- SyncClientConfig,
70
- SyncStatusSnapshot,
71
- WindowBase,
72
- WindowState,
73
28
  } from '@syncular/client';
74
- // -- Types the bridge speaks (structurally the web-client's) -----------------
75
- // Most imports stay type-only; the stable preflight error code is shared at
76
- // runtime so every host surfaces byte-identical policy evidence.
77
29
  import {
78
- decodeLocalDataRebootstrapResult,
79
- decodePreviousVersionAuditResult,
80
- decodePreviousVersionDiscardResult,
81
- decodePreviousVersionSnapshot,
82
- SECURITY_PREFLIGHT_REQUIRED_CODE,
83
- withClientDiagnosticsHost,
84
- } from '@syncular/client';
30
+ NativeBridgeClient,
31
+ type NativeCreateConfig,
32
+ type NativeReply,
33
+ NativeSyncError,
34
+ nativeCreateParams,
35
+ type SyncularEvent,
36
+ } from '@syncular/client/native-bridge';
85
37
 
86
- /** A driver-protocol reply: `{result}` on success or `{error}` on failure. */
87
- interface CommandReply {
88
- readonly result?: unknown;
89
- readonly error?: {
90
- readonly code: string;
91
- readonly message: string;
92
- readonly details?: Readonly<Record<string, unknown>> | null;
93
- readonly retryable?: boolean;
94
- };
95
- }
96
-
97
- /** One event pushed on `syncular://event` (the derived client-observable set). */
98
- interface SyncularEvent {
99
- readonly type: string;
100
- readonly [key: string]: unknown;
101
- }
38
+ export type { BytesEnvelope } from '@syncular/client/native-bridge';
102
39
 
103
40
  /** §7.5: one read-only statement in an atomic sidecar snapshot read. */
104
41
  export type { SnapshotStatement } from '@syncular/client';
105
42
 
106
- /** §7.5: the catch-up state of one subscription from the sidecar. */
107
- export type { SubscriptionCatchup } from '@syncular/client';
43
+ /** §7.5: the catch-up state of one unit from the sidecar. */
44
+ export type { UnitCatchup } from '@syncular/client';
108
45
 
109
46
  /** §7.5: delivery status for one client commit id. */
110
47
  export type { CommitDelivery } from '@syncular/client';
@@ -115,14 +52,20 @@ export type SnapshotReadResult = SnapshotRead;
115
52
  /** The two Tauri primitives the bridge needs — injectable for tests. */
116
53
  export interface TauriApi {
117
54
  invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T>;
118
- listen<T>(
119
- event: string,
120
- handler: (event: { payload: T }) => void,
121
- ): Promise<() => void>;
55
+ /**
56
+ * A Tauri IPC channel delivering each message to `onMessage`. Only the
57
+ * webview that created it receives its messages.
58
+ */
59
+ channel<T>(onMessage: (message: T) => void): { toJSON(): string };
122
60
  }
123
61
 
124
- /** The plugin's Tauri event name — mirror of `tauri-plugin-syncular`. */
125
- export const SYNCULAR_EVENT = 'syncular://event';
62
+ interface TauriCore {
63
+ invoke: TauriApi['invoke'];
64
+ Channel: new <T>() => {
65
+ onmessage: (message: T) => void;
66
+ toJSON(): string;
67
+ };
68
+ }
126
69
 
127
70
  const PLUGIN = 'plugin:syncular|';
128
71
 
@@ -130,15 +73,7 @@ const PLUGIN = 'plugin:syncular|';
130
73
  export type LocalAuthorityState = 'local' | 'attaching' | 'attached';
131
74
 
132
75
  /** Config for {@link createTauriSyncClient}. */
133
- export interface TauriSyncClientConfig {
134
- /** The generated schema JSON (the app passes `schema` from typegen). */
135
- readonly schema: unknown;
136
- /**
137
- * Client id for this device/actor. If omitted, the native client generates
138
- * one and persists it in the database. Supplying a different id when opening
139
- * an existing database fails with `client.identity_mismatch`.
140
- */
141
- readonly clientId?: string;
76
+ export interface TauriSyncClientConfig extends NativeCreateConfig {
142
77
  /**
143
78
  * Name of the native database to open, for example one replica per
144
79
  * signed-in actor. The plugin opens `<database_dir>/<database>.db` from its
@@ -146,32 +81,11 @@ export interface TauriSyncClientConfig {
146
81
  * `.` and starts with a letter or digit. Absent ⇒ the plugin's `db_path`.
147
82
  */
148
83
  readonly database?: string;
149
- /** §4.2 client limits, forwarded to the native `create`. */
150
- readonly limits?: Record<string, unknown>;
151
- /**
152
- * SPEC §8.8 realtime policy, forwarded to the native `create`. Absent ⇒
153
- * `optional`. `required` refuses a sync round while the socket is not
154
- * connected instead of falling back to HTTP.
155
- */
156
- readonly realtimePolicy?: SyncClientConfig['realtimePolicy'];
157
84
  readonly retainFailedCommits?: boolean;
158
- /**
159
- * Portable E2EE keys and declarative per-row key-id columns. Raw keys are
160
- * encoded into the native command envelope and never sent to the server.
161
- */
162
- readonly encryption?: EncryptionKeyringConfig;
163
85
  /** Fixed plain authority reads permitted before security activation. */
164
86
  readonly authorityReads?: AuthorityReadPolicy;
165
- /** Open the native replica behind the fail-closed security gate. */
166
- readonly securityPreflight?: boolean;
167
87
  /** Open local storage with network transport closed until explicitly resumed. */
168
88
  readonly transportEnabled?: boolean;
169
- /**
170
- * RFC 0005 previous-version context, forwarded to the native `create`. The
171
- * Rust create handler must read this key to enable capture; while it does
172
- * not, the native core treats the feature as off (default-off).
173
- */
174
- readonly previousVersionContext?: SyncClientConfig['previousVersionContext'];
175
89
  /**
176
90
  * The Tauri primitives. Omit in a real Tauri webview to auto-resolve from
177
91
  * `@tauri-apps/api` (peer dep) or the ambient `window.__TAURI__`; inject in
@@ -180,728 +94,103 @@ export interface TauriSyncClientConfig {
180
94
  readonly tauri?: TauriApi;
181
95
  }
182
96
 
183
- /** The bytes envelope both sides share. */
184
- export type BytesEnvelope = { readonly $bytes: string };
185
- type BigIntEnvelope = { readonly $bigint: string };
186
-
187
- function isBytesEnvelope(value: unknown): value is BytesEnvelope {
188
- if (typeof value !== 'object' || value === null) return false;
189
- const record = value as Record<string, unknown>;
190
- return (
191
- Object.keys(record).length === 1 &&
192
- typeof record.$bytes === 'string' &&
193
- /^(?:[0-9a-fA-F]{2})*$/.test(record.$bytes)
194
- );
195
- }
196
-
197
- /**
198
- * §7.1: a host reply that carries an envelope-shaped object with a malformed
199
- * body is refused, never padded into different bytes. Objects without a
200
- * `$bytes` key keep the defensive JSON text round-trip below.
201
- */
202
- function assertBytesEnvelope(value: unknown): void {
203
- if (typeof value !== 'object' || value === null || !('$bytes' in value))
204
- return;
205
- if (!isBytesEnvelope(value))
206
- throw new TauriSyncError(
207
- 'sync.invalid_request',
208
- 'a $bytes envelope requires exactly one $bytes key holding an even-length hexadecimal string',
209
- );
210
- }
211
-
212
- function isBigIntEnvelope(value: unknown): value is BigIntEnvelope {
213
- return (
214
- typeof value === 'object' &&
215
- value !== null &&
216
- typeof (value as { $bigint?: unknown }).$bigint === 'string'
217
- );
218
- }
219
-
220
- function bytesToHex(bytes: Uint8Array): string {
221
- let out = '';
222
- for (const b of bytes) {
223
- out += b.toString(16).padStart(2, '0');
224
- }
225
- return out;
226
- }
227
-
228
- function hexToBytes(hex: string): Uint8Array {
229
- if (!/^(?:[0-9a-fA-F]{2})*$/.test(hex))
230
- throw new TauriSyncError(
231
- 'sync.invalid_request',
232
- 'a $bytes envelope requires an even-length hexadecimal string',
233
- );
234
- const out = new Uint8Array(hex.length / 2);
235
- for (let i = 0; i < out.length; i++) {
236
- out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
237
- }
238
- return out;
239
- }
240
-
241
- /** Encode an SQL param for the command JSON (bytes → `{$bytes: hex}`). */
242
- function encodeParam(value: SqlValue): unknown {
243
- if (value instanceof Uint8Array) return { $bytes: bytesToHex(value) };
244
- if (typeof value === 'bigint') return { $bigint: value.toString() };
245
- return value;
246
- }
247
-
248
- function encodeJsonValue(value: unknown): unknown {
249
- if (value instanceof Uint8Array) return { $bytes: bytesToHex(value) };
250
- if (typeof value === 'bigint') return { $bigint: value.toString() };
251
- if (Array.isArray(value)) return value.map(encodeJsonValue);
252
- if (value !== null && typeof value === 'object') {
253
- const encoded: Record<string, unknown> = {};
254
- for (const [key, member] of Object.entries(value)) {
255
- encoded[key] = encodeJsonValue(member);
256
- }
257
- return encoded;
258
- }
259
- return value;
260
- }
261
-
262
- function encodeEncryption(config: EncryptionKeyringConfig): unknown {
263
- return {
264
- keys: Object.fromEntries(
265
- Object.entries(config.keys).map(([keyId, key]) => [
266
- keyId,
267
- { $bytes: bytesToHex(key) },
268
- ]),
269
- ),
270
- ...(config.keyIdColumns !== undefined
271
- ? { keyIdColumns: config.keyIdColumns }
272
- : {}),
273
- };
274
- }
275
-
276
- /** Decode one query-result cell back to an `SqlValue` (`{$bytes}` → bytes). */
277
- function decodeCell(value: unknown): SqlValue {
278
- assertBytesEnvelope(value);
279
- if (isBytesEnvelope(value)) return hexToBytes(value.$bytes);
280
- if (isBigIntEnvelope(value)) return BigInt(value.$bigint);
281
- if (
282
- value === null ||
283
- typeof value === 'string' ||
284
- typeof value === 'number' ||
285
- typeof value === 'boolean'
286
- ) {
287
- return value;
288
- }
289
- // Objects/arrays that are not the bytes envelope round-trip as their JSON
290
- // string (SQLite json columns arrive as text already; this is defensive).
291
- return JSON.stringify(value);
292
- }
293
-
294
- /** A decoded outcome row cell. Structurally the shared `RowValue` (bytes are
295
- * `Uint8Array`); native outcome rows emit plain JSON numbers, never `$bigint`. */
296
- type OutcomeRowValue = ConflictRecord['serverRow'][string];
297
-
298
- /** Decode one native outcome row image. Only the `{$bytes}` envelope is
299
- * honored; operation `values` stay `JsonRowValue` and are not passed here. */
300
- function decodeOutcomeRow(
301
- row: Readonly<Record<string, unknown>>,
302
- ): Record<string, OutcomeRowValue> {
303
- const out: Record<string, OutcomeRowValue> = {};
304
- for (const [key, value] of Object.entries(row)) {
305
- // Reserved `_sync_*` columns stay engine-internal, matching `decodeRow`.
306
- if (key.startsWith('_sync_')) continue;
307
- assertBytesEnvelope(value);
308
- if (
309
- value === null ||
310
- typeof value === 'string' ||
311
- typeof value === 'number' ||
312
- typeof value === 'boolean'
313
- ) {
314
- out[key] = value;
315
- } else if (isBytesEnvelope(value)) {
316
- out[key] = hexToBytes(value.$bytes);
317
- } else {
318
- out[key] = JSON.stringify(value);
319
- }
320
- }
321
- return out;
322
- }
323
-
324
- function decodeRetainedRows(
325
- rows: readonly RetainedCommitRow[],
326
- ): RetainedCommitRow[] {
327
- return rows.map((row) => ({
328
- ...row,
329
- localRow: row.localRow === null ? null : decodeOutcomeRow(row.localRow),
330
- serverRow: row.serverRow === null ? null : decodeOutcomeRow(row.serverRow),
331
- ...(row.uniqueConflicts !== undefined
332
- ? {
333
- uniqueConflicts: row.uniqueConflicts.map((conflict) => ({
334
- ...conflict,
335
- serverRow: decodeOutcomeRow(conflict.serverRow),
336
- })),
337
- }
338
- : {}),
339
- }));
340
- }
341
-
342
- /** Decode the row images a native `CommitOutcome` carries: conflict server
343
- * rows and retained-row images. */
344
- function decodeCommitOutcome(outcome: CommitOutcome): CommitOutcome {
345
- return {
346
- ...outcome,
347
- results: outcome.results.map((result) =>
348
- result.status === 'conflict'
349
- ? {
350
- ...result,
351
- conflict: {
352
- ...result.conflict,
353
- serverRow: decodeOutcomeRow(result.conflict.serverRow),
354
- },
355
- }
356
- : result,
357
- ),
358
- ...(outcome.retainedRows !== undefined
359
- ? {
360
- retainedRows: decodeRetainedRows(outcome.retainedRows),
361
- }
362
- : {}),
363
- };
364
- }
365
-
366
- /** @internal Shared native row codec. */
367
- export function decodeRow(row: Record<string, unknown>): SqlRow {
368
- const out: SqlRow = {};
369
- for (const [key, value] of Object.entries(row)) {
370
- // Reserved `_sync_*` columns stay engine-internal (parity with the
371
- // web client's `query()`), so a `SELECT *` row round-trips straight
372
- // into `mutate()` values. Alias (`_sync_version AS v`) to read one.
373
- if (key.startsWith('_sync_')) continue;
374
- out[key] = decodeCell(value);
375
- }
376
- return out;
377
- }
378
-
379
- /**
380
- * Decode the JSON cell envelopes in an RFC 0005 snapshot reply's rows before
381
- * the strict bridge decoder sees them; a malformed reply is passed through
382
- * untouched so `decodePreviousVersionSnapshot` rejects it.
383
- */
384
- function decodeSnapshotRows(value: unknown): unknown {
385
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
386
- return value;
387
- }
388
- const source = value as Record<string, unknown>;
389
- if (!Array.isArray(source.rows)) return value;
390
- return {
391
- ...source,
392
- rows: source.rows.map((row) =>
393
- row !== null && typeof row === 'object' && !Array.isArray(row)
394
- ? decodeRow(row as Record<string, unknown>)
395
- : row,
396
- ),
397
- };
97
+ /** The error a `{error}` reply surfaces (mirrors the web-client `ClientSyncError`). */
98
+ export class TauriSyncError extends NativeSyncError {
99
+ override name = 'TauriSyncError';
398
100
  }
399
101
 
400
102
  /** Resolve the Tauri primitives from the ambient environment when not injected. */
401
103
  async function resolveTauri(injected: TauriApi | undefined): Promise<TauriApi> {
402
104
  if (injected !== undefined) return injected;
403
105
  // Prefer the ambient global (present when `withGlobalTauri` is enabled).
404
- const ambient = (
405
- globalThis as {
406
- __TAURI__?: {
407
- core?: { invoke?: TauriApi['invoke'] };
408
- event?: { listen?: TauriApi['listen'] };
409
- };
410
- }
411
- ).__TAURI__;
412
- if (ambient?.core?.invoke && ambient.event?.listen) {
413
- return {
414
- invoke: ambient.core.invoke.bind(ambient.core),
415
- listen: ambient.event.listen.bind(ambient.event),
416
- };
417
- }
418
- // Fall back to the ESM package (the common path). These must remain literal,
419
- // bundler-visible specifiers: hiding a bare package import behind
106
+ // Otherwise use the ESM package (the common path). The specifier must remain
107
+ // literal and bundler-visible: hiding a bare package import behind
420
108
  // `@vite-ignore` makes WebKit resolve it as a URL at runtime instead of
421
109
  // letting Vite/Bun include the Tauri API in the webview bundle.
422
- const [core, event] = await Promise.all([
423
- import('@tauri-apps/api/core'),
424
- import('@tauri-apps/api/event'),
425
- ]);
426
- return { invoke: core.invoke, listen: event.listen };
110
+ const ambient = (globalThis as { __TAURI__?: { core?: Partial<TauriCore> } })
111
+ .__TAURI__?.core;
112
+ const core: TauriCore =
113
+ ambient?.invoke !== undefined && ambient.Channel !== undefined
114
+ ? { invoke: ambient.invoke.bind(ambient), Channel: ambient.Channel }
115
+ : await import('@tauri-apps/api/core');
116
+ return {
117
+ invoke: core.invoke,
118
+ channel: (onMessage) => {
119
+ const channel = new core.Channel<Parameters<typeof onMessage>[0]>();
120
+ channel.onmessage = onMessage;
121
+ return channel;
122
+ },
123
+ };
427
124
  }
428
125
 
429
- /**
430
- * The webview-side proxy implementing `SyncClientLike` over the plugin. Every
431
- * snapshot method returns a promise from an IPC round trip. React hooks accept
432
- * the canonical snapshot interface directly.
433
- */
434
- export class TauriSyncClient implements PromiseMethods<ClientSnapshotMethods> {
126
+ /** The webview-side proxy implementing `SyncClientLike` over the plugin. */
127
+ export class TauriSyncClient extends NativeBridgeClient {
435
128
  readonly #tauri: TauriApi;
436
- readonly #invalidationListeners = new Set<InvalidationListener>();
437
- readonly #changeListeners = new Set<ClientChangeListener>();
438
- readonly #progress = new ProgressEmitter();
439
- readonly #diagnosticsListeners = new Set<ClientDiagnosticsListener>();
440
- readonly #presenceListeners = new Set<(scopeKey: string) => void>();
441
- #unlisten: (() => void) | undefined;
442
- #closed = false;
443
- #closing: Promise<void> | undefined;
444
- #securityLifecycle: SecurityLifecycle;
445
- #preflightBarrier: Promise<void> | undefined;
446
129
  #diagnosticsEnabled = false;
447
130
 
448
131
  /** @internal — use {@link createTauriSyncClient}. */
449
132
  constructor(
450
133
  tauri: TauriApi,
451
- unlisten: () => void,
134
+ release: () => void,
452
135
  securityLifecycle: SecurityLifecycle = 'active',
453
136
  ) {
137
+ super('tauri', TauriSyncError, release, securityLifecycle);
454
138
  this.#tauri = tauri;
455
- this.#unlisten = unlisten;
456
- this.#securityLifecycle = securityLifecycle;
457
- }
458
-
459
- /** Dispatch a `syncular_command` and unwrap `{result}` / throw on `{error}`. */
460
- async #command(
461
- method: string,
462
- params: Record<string, unknown>,
463
- ): Promise<unknown> {
464
- this.#requireOpen();
465
- if (
466
- this.#securityLifecycle === 'preflight' &&
467
- ![
468
- 'authoritySnapshot',
469
- 'securityLifecycle',
470
- 'beginSecurityPreflight',
471
- 'activateSecurity',
472
- 'setTransportEnabled',
473
- 'purgeLocalData',
474
- 'previousVersionDiscard',
475
- 'localRevision',
476
- 'statusSnapshot',
477
- 'shutdown',
478
- ].includes(method) &&
479
- !this.allowPreflightCommand(method)
480
- ) {
481
- this.#throwSecurityPreflight();
482
- }
483
- const reply = await this.#tauri.invoke<CommandReply>(
484
- `${PLUGIN}syncular_command`,
485
- { command: { method, params } },
486
- );
487
- if (reply.error !== undefined) {
488
- throw new TauriSyncError(
489
- reply.error.code,
490
- reply.error.message,
491
- reply.error.details ?? undefined,
492
- reply.error.retryable ?? false,
493
- );
494
- }
495
- return reply.result;
496
- }
497
-
498
- #throwSecurityPreflight(): never {
499
- throw new TauriSyncError(
500
- SECURITY_PREFLIGHT_REQUIRED_CODE,
501
- 'the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data',
502
- );
503
- }
504
-
505
- #requireOpen(): void {
506
- if (this.#closed) {
507
- throw new TauriSyncError(
508
- 'client.closed',
509
- 'the Tauri sync client is closed',
510
- );
511
- }
512
139
  }
513
140
 
514
- /** @internal Shared command gate for explicit bridge extensions. */
515
- protected command(
141
+ protected override send(
516
142
  method: string,
517
143
  params: Record<string, unknown>,
518
- ): Promise<unknown> {
519
- return this.#command(method, params);
520
- }
521
-
522
- /** @internal Additional preflight operations supplied by bridge extensions. */
523
- protected allowPreflightCommand(_method: string): boolean {
524
- return false;
525
- }
526
-
527
- /** @internal Recheck local close after an extension's asynchronous reply. */
528
- protected requireOpen(): void {
529
- this.#requireOpen();
530
- }
531
-
532
- #requireActive(): void {
533
- this.#requireOpen();
534
- if (this.#securityLifecycle === 'preflight') this.#throwSecurityPreflight();
535
- }
536
-
537
- /** @internal — fan an incoming plugin event out to the local listeners. */
538
- __dispatchEvent(event: SyncularEvent): void {
539
- switch (event.type) {
540
- case 'progress': {
541
- this.#progress.emit(event.progress as SyncProgress);
542
- break;
543
- }
544
- case 'change': {
545
- const batch = decodeChangeBatch(event.batch);
546
- if (batch === undefined) break;
547
- for (const listener of this.#changeListeners) {
548
- try {
549
- listener(batch);
550
- } catch {
551
- /* a UI listener must never break event dispatch */
552
- }
553
- }
554
- const payload = invalidationFromChange(batch);
555
- if (payload === undefined) break;
556
- for (const listener of this.#invalidationListeners) {
557
- try {
558
- listener(payload);
559
- } catch {
560
- /* a UI listener must never break event dispatch */
561
- }
562
- }
563
- break;
564
- }
565
- case 'presence': {
566
- const scopeKey =
567
- typeof event.scopeKey === 'string' ? event.scopeKey : '';
568
- for (const listener of this.#presenceListeners) {
569
- try {
570
- listener(scopeKey);
571
- } catch {
572
- /* never break dispatch */
573
- }
574
- }
575
- break;
576
- }
577
- case 'diagnostics': {
578
- const snapshot = decodeDiagnosticsSnapshot(event.snapshot, 'tauri');
579
- if (snapshot === undefined) break;
580
- for (const listener of this.#diagnosticsListeners) {
581
- try {
582
- listener(snapshot);
583
- } catch {
584
- /* a diagnostics observer must never break event dispatch */
585
- }
586
- }
587
- break;
588
- }
589
- default:
590
- // Unknown extension events are deliberately ignored. All durable
591
- // observable state arrives in the revisioned `change` batch.
592
- break;
593
- }
594
- }
595
-
596
- // -- SyncClientLike --------------------------------------------------------
597
-
598
- async securityLifecycle(): Promise<SecurityLifecycle> {
599
- this.#requireOpen();
600
- return Promise.resolve(this.#securityLifecycle);
601
- }
602
-
603
- beginSecurityPreflight(): Promise<void> {
604
- if (this.#closed) {
605
- return Promise.reject(
606
- new TauriSyncError('client.closed', 'the Tauri sync client is closed'),
607
- );
608
- }
609
- if (this.#preflightBarrier !== undefined) return this.#preflightBarrier;
610
- // Flip synchronously so a same-webview query cannot race the IPC barrier.
611
- this.#securityLifecycle = 'preflight';
612
- const barrier = this.#command('beginSecurityPreflight', {}).then(() => {});
613
- this.#preflightBarrier = barrier;
614
- void barrier.then(
615
- () => {
616
- if (this.#preflightBarrier === barrier)
617
- this.#preflightBarrier = undefined;
618
- },
619
- () => {
620
- if (this.#preflightBarrier === barrier)
621
- this.#preflightBarrier = undefined;
622
- },
623
- );
624
- return barrier;
625
- }
626
-
627
- /**
628
- * Complete the security preflight. `headers` optionally carries a fresh
629
- * FULL transport header set that the native host applies atomically with
630
- * the activation, before the startup sync it enqueues — so a preflight
631
- * that outlives the boot token starts its first round with valid
632
- * credentials (the direct `setHeaders` path stays refused while gated).
633
- */
634
- async activateSecurity(
635
- options: {
636
- readonly encryption?: EncryptionKeyringConfig;
637
- readonly headers?: Readonly<Record<string, string>>;
638
- } = {},
639
- ): Promise<void> {
640
- this.#requireOpen();
641
- if (this.#securityLifecycle === 'active') {
642
- throw new TauriSyncError(
643
- 'sync.invalid_request',
644
- 'activateSecurity requires the client to be in security preflight',
645
- );
646
- }
647
- await this.#preflightBarrier;
648
- await this.#command('activateSecurity', {
649
- ...(options.encryption !== undefined
650
- ? { encryption: encodeEncryption(options.encryption) }
651
- : {}),
652
- ...(options.headers !== undefined ? { headers: options.headers } : {}),
144
+ ): Promise<NativeReply> {
145
+ return this.#tauri.invoke(`${PLUGIN}syncular_command`, {
146
+ command: { method, params },
653
147
  });
654
- this.#securityLifecycle = 'active';
655
- }
656
-
657
- onInvalidate(listener: InvalidationListener): () => void {
658
- this.#requireOpen();
659
- this.#invalidationListeners.add(listener);
660
- return () => this.#invalidationListeners.delete(listener);
661
- }
662
-
663
- onProgress(listener: SyncProgressListener): () => void {
664
- this.#requireOpen();
665
- return this.#progress.on(listener);
666
- }
667
- progressSnapshot(): SyncProgress | undefined {
668
- this.#requireOpen();
669
- return this.#progress.snapshot();
670
148
  }
671
149
 
672
- onChange(listener: ClientChangeListener): () => void {
673
- this.#requireOpen();
674
- this.#changeListeners.add(listener);
675
- return () => this.#changeListeners.delete(listener);
150
+ protected override sendQuery(
151
+ sql: string,
152
+ params: unknown,
153
+ ): Promise<NativeReply> {
154
+ return this.#tauri.invoke(`${PLUGIN}syncular_query`, { sql, params });
676
155
  }
677
156
 
678
- onDiagnostics(listener: ClientDiagnosticsListener): () => void {
679
- this.#requireOpen();
680
- this.#diagnosticsListeners.add(listener);
681
- this.#enableDiagnosticsPush();
682
- return () => this.#diagnosticsListeners.delete(listener);
683
- }
684
-
685
- /**
686
- * Host-local push registration: the native core emits pushed diagnostics
687
- * snapshots only once a consumer is known (a `diagnosticsSnapshot` pull, or
688
- * this explicit `enableDiagnostics` signal). Fired once, on the first
689
- * registered listener, fire-and-forget. The invoke deliberately bypasses
690
- * the bridge's preflight gate — the command is a pure observability
691
- * registration handled before dispatch, and the native side stays silent
692
- * until activation anyway. Errors are tolerated: an older native core
693
- * rejects the unknown command, and the mount-time snapshot pull path keeps
694
- * `useDiagnostics` working there.
695
- */
696
- #enableDiagnosticsPush(): void {
697
- if (this.#diagnosticsEnabled || this.#closed) return;
698
- this.#diagnosticsEnabled = true;
699
- void this.#tauri
700
- .invoke<CommandReply>(`${PLUGIN}syncular_command`, {
701
- command: { method: 'enableDiagnostics', params: {} },
702
- })
703
- .catch(() => {
704
- /* fire-and-forget; an error reply is equally ignored above */
705
- });
706
- }
707
-
708
- onPresence(listener: (scopeKey: string) => void): () => void {
709
- this.#requireOpen();
710
- this.#presenceListeners.add(listener);
711
- return () => this.#presenceListeners.delete(listener);
712
- }
713
-
714
- async query(sql: string, params?: readonly SqlValue[]): Promise<SqlRow[]> {
715
- this.#requireActive();
716
- const reply = await this.#tauri.invoke<CommandReply>(
717
- `${PLUGIN}syncular_query`,
718
- { sql, params: (params ?? []).map(encodeParam) },
719
- );
720
- if (reply.error !== undefined) {
721
- throw new TauriSyncError(
722
- reply.error.code,
723
- reply.error.message,
724
- reply.error.details ?? undefined,
725
- reply.error.retryable ?? false,
726
- );
727
- }
728
- const rows = (reply.result as { rows?: unknown[] }).rows ?? [];
729
- return rows.map((r) => decodeRow(r as Record<string, unknown>));
157
+ protected override sendQuerySnapshot(
158
+ params: Record<string, unknown>,
159
+ ): Promise<NativeReply> {
160
+ return this.#tauri.invoke(`${PLUGIN}syncular_query_snapshot`, params);
730
161
  }
731
162
 
732
- async querySnapshot<Row = SqlRow>(
733
- spec: QueryReadSpec,
734
- ): Promise<QuerySnapshot<Row>> {
735
- this.#requireActive();
736
- const reply = await this.#tauri.invoke<CommandReply>(
737
- `${PLUGIN}syncular_query_snapshot`,
738
- {
739
- sql: spec.sql,
740
- params: (spec.params ?? []).map(encodeParam),
741
- coverage: spec.coverage ?? [],
742
- ...(spec.owner !== undefined ? { owner: spec.owner } : {}),
743
- },
744
- );
745
- if (reply.error !== undefined) {
746
- throw new TauriSyncError(
747
- reply.error.code,
748
- reply.error.message,
749
- reply.error.details ?? undefined,
750
- reply.error.retryable ?? false,
751
- );
752
- }
753
- const result = reply.result as {
754
- revision: string;
755
- rows: Record<string, unknown>[];
756
- coverage: QuerySnapshot['coverage'];
757
- };
758
- return {
759
- revision: BigInt(result.revision),
760
- rows: result.rows.map(decodeRow) as unknown as readonly Row[],
761
- coverage: result.coverage,
762
- };
163
+ protected override sendHeaders(
164
+ headers: Readonly<Record<string, string>>,
165
+ ): Promise<NativeReply> {
166
+ return this.#tauri.invoke(`${PLUGIN}syncular_set_headers`, { headers });
763
167
  }
764
168
 
765
- async localRevision(): Promise<bigint> {
766
- const result = (await this.#command('localRevision', {})) as {
767
- revision: string;
768
- };
769
- return BigInt(result.revision);
169
+ /** Shut down the native core and release its keyring. */
170
+ protected override async shutdown(): Promise<void> {
171
+ await this.command('shutdown', {});
770
172
  }
771
173
 
772
174
  /**
773
- * §7.5: one atomic read over the file-backed sidecar. Every statement and
774
- * every catch-up/delivery read shares one revision (a `bigint`, matching
775
- * `querySnapshot`) and one read transaction; every query row is decoded.
175
+ * The native core pushes diagnostics snapshots only once a consumer is
176
+ * known (a `diagnosticsSnapshot` pull, or this `enableDiagnostics` signal).
177
+ * The first listener sends it once, fire-and-forget and outside the
178
+ * preflight gate: it is a pure observability registration, and the native
179
+ * side stays silent until activation. An error is tolerated, because the
180
+ * mount-time snapshot pull keeps `useDiagnostics` working without it.
776
181
  */
777
- async snapshotRead(request: SnapshotReadRequest): Promise<SnapshotRead> {
778
- this.#requireActive();
779
- const reply = await this.#tauri.invoke<CommandReply>(
780
- `${PLUGIN}syncular_snapshot_read`,
781
- {
782
- statements: request.statements.map((statement) => ({
783
- sql: statement.sql,
784
- params: (statement.params ?? []).map(encodeParam),
785
- })),
786
- coverage: request.coverage ?? [],
787
- subscriptions: request.subscriptions ?? [],
788
- commitIds: request.commitIds ?? [],
789
- ...(request.owner !== undefined ? { owner: request.owner } : {}),
790
- },
791
- );
792
- if (reply.error !== undefined) {
793
- throw new TauriSyncError(
794
- reply.error.code,
795
- reply.error.message,
796
- reply.error.details ?? undefined,
797
- reply.error.retryable ?? false,
798
- );
182
+ override onDiagnostics(listener: ClientDiagnosticsListener): () => void {
183
+ const off = super.onDiagnostics(listener);
184
+ if (!this.#diagnosticsEnabled) {
185
+ this.#diagnosticsEnabled = true;
186
+ void this.send('enableDiagnostics', {}).catch(() => {});
799
187
  }
800
- const result = reply.result as {
801
- revision: string;
802
- queries: readonly (readonly Record<string, unknown>[])[];
803
- coverage: SnapshotRead['coverage'];
804
- subscriptions: SnapshotRead['subscriptions'];
805
- deliveries: SnapshotRead['deliveries'];
806
- };
807
- return {
808
- revision: BigInt(result.revision),
809
- queries: result.queries.map((rows) => rows.map(decodeRow)),
810
- coverage: result.coverage,
811
- subscriptions: result.subscriptions,
812
- deliveries: result.deliveries.map((delivery) =>
813
- delivery.status === 'known'
814
- ? { ...delivery, outcome: decodeCommitOutcome(delivery.outcome) }
815
- : delivery,
816
- ),
817
- };
818
- }
819
-
820
- async statusSnapshot(): Promise<SyncStatusSnapshot> {
821
- return (await this.#command('statusSnapshot', {})) as SyncStatusSnapshot;
822
- }
823
-
824
- async diagnosticsSnapshot(
825
- request: ClientDiagnosticsRequest = {},
826
- ): Promise<ClientDiagnosticsSnapshot> {
827
- const snapshot = (await this.#command('diagnosticsSnapshot', {
828
- expectedSubscriptions: request.expectedSubscriptions ?? [],
829
- })) as ClientDiagnosticsSnapshot;
830
- return withClientDiagnosticsHost(snapshot, {
831
- ...snapshot.host,
832
- kind: 'tauri',
833
- role: 'single',
834
- });
835
- }
836
-
837
- async mutate(mutations: readonly MutationInput[]): Promise<string> {
838
- const result = (await this.#command('mutate', {
839
- mutations: mutations.map(encodeMutation),
840
- })) as { clientCommitId: string };
841
- return result.clientCommitId;
842
- }
843
-
844
- async patch(
845
- table: string,
846
- rowId: string,
847
- partial: Readonly<Record<string, unknown>>,
848
- options?: { readonly baseVersion?: number },
849
- ): Promise<string> {
850
- const result = (await this.#command('patch', {
851
- table,
852
- rowId,
853
- partial: encodeJsonValue(partial),
854
- ...(options?.baseVersion !== undefined
855
- ? { baseVersion: options.baseVersion }
856
- : {}),
857
- })) as { clientCommitId: string };
858
- return result.clientCommitId;
859
- }
860
-
861
- async purgeLocalData(
862
- input: LocalDataPurgeInput,
863
- ): Promise<LocalDataPurgeResult> {
864
- return (await this.#command('purgeLocalData', {
865
- input,
866
- })) as LocalDataPurgeResult;
867
- }
868
-
869
- async rebootstrapLocalData(
870
- input: LocalDataRebootstrapInput,
871
- ): Promise<LocalDataRebootstrapResult> {
872
- return decodeLocalDataRebootstrapResult(
873
- await this.#command('rebootstrapLocalData', { input }),
874
- );
875
- }
876
-
877
- async previousVersionSnapshot(
878
- spec: PreviousVersionReadSpec,
879
- ): Promise<PreviousVersionSnapshot> {
880
- return decodePreviousVersionSnapshot(
881
- decodeSnapshotRows(
882
- await this.#command('previousVersionSnapshot', { spec }),
883
- ),
884
- );
885
- }
886
-
887
- async previousVersionAudit(): Promise<PreviousVersionAudit | undefined> {
888
- return decodePreviousVersionAuditResult(
889
- await this.#command('previousVersionAudit', {}),
890
- );
891
- }
892
-
893
- async previousVersionDiscard(): Promise<{
894
- present: boolean;
895
- discarded: boolean;
896
- }> {
897
- return decodePreviousVersionDiscardResult(
898
- await this.#command('previousVersionDiscard', {}),
899
- );
188
+ return off;
900
189
  }
901
190
 
902
191
  /** Suspend new network work while retaining local access and queued commits. */
903
192
  async setTransportEnabled(enabled: boolean): Promise<void> {
904
- await this.#command('setTransportEnabled', { enabled });
193
+ await this.command('setTransportEnabled', { enabled });
905
194
  }
906
195
 
907
196
  /** Browser offline-control parity; local reads and commits remain available. */
@@ -909,493 +198,17 @@ export class TauriSyncClient implements PromiseMethods<ClientSnapshotMethods> {
909
198
  await this.setTransportEnabled(!offline);
910
199
  }
911
200
 
912
- /**
913
- * Replace the native transport's request headers at runtime — the auth
914
- * rotation path. Pass the FULL header set (it replaces,
915
- * it does not merge). HTTP requests use the new set from the next call;
916
- * the realtime socket applies it on its next (re)connect.
917
- */
918
- async setHeaders(headers: Readonly<Record<string, string>>): Promise<void> {
919
- this.#requireActive();
920
- const reply = await this.#tauri.invoke<CommandReply>(
921
- `${PLUGIN}syncular_set_headers`,
922
- { headers },
923
- );
924
- if (reply.error !== undefined) {
925
- throw new TauriSyncError(
926
- reply.error.code,
927
- reply.error.message,
928
- reply.error.details ?? undefined,
929
- reply.error.retryable ?? false,
930
- );
931
- }
932
- }
933
-
934
- // -- Native CRDT (SPEC.md §5.10.5; needs the plugin `crdt-yjs` feature) ------
935
-
936
- /** Materialize a `crdt` column's collaborative text — decoded from the
937
- * stored (server-merged) Yjs bytes. `name` selects the shared text
938
- * (default `"text"`). An absent row / NULL column is the empty document. */
939
- async crdtText(
940
- table: string,
941
- rowId: string,
942
- column: string,
943
- name = 'text',
944
- ): Promise<string> {
945
- const result = (await this.#command('crdtText', {
946
- table,
947
- rowId,
948
- column,
949
- name,
950
- })) as { text: string };
951
- return result.text;
952
- }
953
-
954
- /** Insert `value` at UTF-16 offset `index` in a `crdt` column's text and
955
- * push the resulting Yjs update (baseVersion-less). Returns the commit id. */
956
- async crdtInsertText(
957
- table: string,
958
- rowId: string,
959
- column: string,
960
- index: number,
961
- value: string,
962
- name = 'text',
963
- ): Promise<string> {
964
- const result = (await this.#command('crdtInsertText', {
965
- table,
966
- rowId,
967
- column,
968
- name,
969
- index,
970
- value,
971
- })) as { clientCommitId: string };
972
- return result.clientCommitId;
973
- }
974
-
975
- /** Delete `len` UTF-16 code units at `index` in a `crdt` column's text. */
976
- async crdtDeleteText(
977
- table: string,
978
- rowId: string,
979
- column: string,
980
- index: number,
981
- len: number,
982
- name = 'text',
983
- ): Promise<string> {
984
- const result = (await this.#command('crdtDeleteText', {
985
- table,
986
- rowId,
987
- column,
988
- name,
989
- index,
990
- len,
991
- })) as { clientCommitId: string };
992
- return result.clientCommitId;
993
- }
994
-
995
- /** Escape hatch: apply an arbitrary Yjs update onto a `crdt` column. */
996
- async crdtApplyUpdate(
997
- table: string,
998
- rowId: string,
999
- column: string,
1000
- update: Uint8Array,
1001
- ): Promise<string> {
1002
- const result = (await this.#command('crdtApplyUpdate', {
1003
- table,
1004
- rowId,
1005
- column,
1006
- update: { $bytes: bytesToHex(update) },
1007
- })) as { clientCommitId: string };
1008
- return result.clientCommitId;
1009
- }
1010
-
1011
- /**
1012
- * Stage a blob for attachment (§5.9.7) and return the canonical `BlobRef`
1013
- * string to store in a `blob_ref` column. The native core owns the upload
1014
- * queue; write the referencing row after this resolves (§5.9.3).
1015
- */
1016
- async uploadBlob(
1017
- bytes: Uint8Array,
1018
- options?: { readonly mediaType?: string; readonly name?: string },
1019
- ): Promise<string> {
1020
- const result = (await this.#command('uploadBlob', {
1021
- bytes: { $bytes: bytesToHex(bytes) },
1022
- ...(options?.mediaType !== undefined
1023
- ? { mediaType: options.mediaType }
1024
- : {}),
1025
- ...(options?.name !== undefined ? { name: options.name } : {}),
1026
- })) as { ref: string };
1027
- return result.ref;
1028
- }
1029
-
1030
- /**
1031
- * Resolve blob bytes for a `blob_ref` column value or a bare `blobId`
1032
- * (§5.9.7): the native core serves a local cache hit and otherwise
1033
- * downloads and verifies the content address.
1034
- */
1035
- async fetchBlob(ref: string): Promise<{
1036
- readonly blobId: string;
1037
- readonly byteLength: number;
1038
- readonly bytes: Uint8Array;
1039
- readonly mediaType?: string;
1040
- }> {
1041
- const result = (await this.#command('fetchBlob', { blob: ref })) as {
1042
- blob: {
1043
- blobId: string;
1044
- byteLength: number;
1045
- bytes: unknown;
1046
- mediaType?: string;
1047
- };
1048
- };
1049
- const bytes = result.blob.bytes;
1050
- if (!isBytesEnvelope(bytes))
1051
- throw new TauriSyncError(
1052
- 'sync.invalid_request',
1053
- 'fetchBlob reply carried no $bytes envelope',
1054
- );
1055
- return {
1056
- blobId: result.blob.blobId,
1057
- byteLength: result.blob.byteLength,
1058
- bytes: hexToBytes(bytes.$bytes),
1059
- ...(result.blob.mediaType !== undefined
1060
- ? { mediaType: result.blob.mediaType }
1061
- : {}),
1062
- };
1063
- }
1064
-
1065
- async subscribe(input: {
1066
- readonly id: string;
1067
- readonly table: string;
1068
- readonly scopes?: Record<string, readonly string[]>;
1069
- readonly params?: string;
1070
- }): Promise<void> {
1071
- await this.#command('subscribe', {
1072
- id: input.id,
1073
- table: input.table,
1074
- scopes: input.scopes ?? {},
1075
- ...(input.params !== undefined ? { params: input.params } : {}),
1076
- });
1077
- }
1078
-
1079
- /** Register several subscriptions in one local transaction. */
1080
- async subscribeMany(
1081
- inputs: readonly {
1082
- readonly id: string;
1083
- readonly table: string;
1084
- readonly scopes?: Record<string, readonly string[]>;
1085
- readonly params?: string;
1086
- }[],
1087
- ): Promise<void> {
1088
- await this.#command('subscribeMany', {
1089
- subscriptions: inputs.map((input) => ({
1090
- id: input.id,
1091
- table: input.table,
1092
- scopes: input.scopes ?? {},
1093
- ...(input.params !== undefined ? { params: input.params } : {}),
1094
- })),
1095
- });
1096
- }
1097
-
1098
- async unsubscribe(id: string): Promise<void> {
1099
- await this.#command('unsubscribe', { id });
1100
- }
1101
-
1102
- async setWindow(base: WindowBase, units: readonly string[]): Promise<void> {
1103
- await this.#command('setWindow', {
1104
- base: base as unknown as Record<string, unknown>,
1105
- units: units as string[],
1106
- });
1107
- }
1108
-
1109
- async windowState(base: WindowBase): Promise<WindowState> {
1110
- const result = (await this.#command('windowState', {
1111
- base: base as unknown as Record<string, unknown>,
1112
- })) as { units: string[]; pending: string[] };
1113
- return { units: result.units, pending: result.pending };
1114
- }
1115
-
1116
- async sync(): Promise<unknown> {
1117
- return this.#command('sync', {});
1118
- }
1119
-
1120
201
  /**
1121
202
  * Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal
1122
203
  * (`recommendedAction: resetClientId`). The next round carries the new id;
1123
204
  * the replica and outbox stay in place.
1124
205
  */
1125
206
  async resetClientId(): Promise<string> {
1126
- const result = (await this.#command('resetClientId', {})) as {
207
+ const result = (await this.command('resetClientId', {})) as {
1127
208
  clientId: string;
1128
209
  };
1129
210
  return result.clientId;
1130
211
  }
1131
-
1132
- async syncUntilIdle(maxRounds?: number): Promise<unknown> {
1133
- return this.#command('syncUntilIdle', {
1134
- ...(maxRounds !== undefined ? { maxRounds } : {}),
1135
- });
1136
- }
1137
-
1138
- async proveCurrentBase(
1139
- outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>,
1140
- maxRounds?: number,
1141
- ): Promise<CurrentBaseProof> {
1142
- if (
1143
- maxRounds !== undefined &&
1144
- (!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff)
1145
- )
1146
- throw new TauriSyncError(
1147
- 'sync.invalid_request',
1148
- 'maxRounds must be a positive integer',
1149
- );
1150
- const proof = (await this.#command('proveCurrentBase', {
1151
- outcome: {
1152
- clientCommitId: outcome.clientCommitId,
1153
- sequence: outcome.sequence,
1154
- },
1155
- ...(maxRounds !== undefined ? { maxRounds } : {}),
1156
- })) as CurrentBaseProof;
1157
- return proof.proven
1158
- ? { proven: true, rows: decodeRetainedRows(proof.rows) }
1159
- : proof;
1160
- }
1161
-
1162
- async conflicts(): Promise<readonly ConflictRecord[]> {
1163
- const result = (await this.#command('conflicts', {})) as {
1164
- conflicts: ConflictRecord[];
1165
- };
1166
- return result.conflicts;
1167
- }
1168
-
1169
- async rejections(): Promise<readonly RejectionRecord[]> {
1170
- const result = (await this.#command('rejections', {})) as {
1171
- rejections: RejectionRecord[];
1172
- };
1173
- return result.rejections;
1174
- }
1175
-
1176
- async commitOutcome(
1177
- clientCommitId: string,
1178
- ): Promise<CommitOutcome | undefined> {
1179
- const result = (await this.#command('commitOutcome', {
1180
- clientCommitId,
1181
- })) as { outcome?: CommitOutcome };
1182
- return result.outcome === undefined
1183
- ? undefined
1184
- : decodeCommitOutcome(result.outcome);
1185
- }
1186
-
1187
- async commitOutcomes(
1188
- query: CommitOutcomeQuery = {},
1189
- ): Promise<readonly CommitOutcome[]> {
1190
- const result = (await this.#command('commitOutcomes', { query })) as {
1191
- outcomes: CommitOutcome[];
1192
- };
1193
- return result.outcomes.map(decodeCommitOutcome);
1194
- }
1195
-
1196
- async resolveCommitOutcome(
1197
- input: ResolveCommitOutcomeInput,
1198
- ): Promise<CommitOutcome> {
1199
- const result = (await this.#command('resolveCommitOutcome', {
1200
- input,
1201
- })) as { outcome: CommitOutcome };
1202
- return decodeCommitOutcome(result.outcome);
1203
- }
1204
-
1205
- async pendingCommits(): Promise<unknown[]> {
1206
- const result = (await this.#command('pendingCommitIds', {})) as {
1207
- ids: string[];
1208
- };
1209
- return result.ids;
1210
- }
1211
-
1212
- async presence(scopeKey: string): Promise<readonly PresencePeer[]> {
1213
- const result = (await this.#command('presence', { scopeKey })) as {
1214
- peers: PresencePeer[];
1215
- };
1216
- return result.peers;
1217
- }
1218
-
1219
- async setPresence(
1220
- scopeKey: string,
1221
- doc: Record<string, unknown> | null,
1222
- ): Promise<void> {
1223
- await this.#command('setPresence', { scopeKey, doc });
1224
- }
1225
-
1226
- async connectRealtime(): Promise<void> {
1227
- await this.#command('connectRealtime', {});
1228
- }
1229
-
1230
- async disconnectRealtime(): Promise<void> {
1231
- await this.#command('disconnectRealtime', {});
1232
- }
1233
-
1234
- /**
1235
- * Shut down the native core, release its keyring, then detach listeners.
1236
- * Every call returns the same promise, so a concurrent or repeated close
1237
- * settles only when the one native shutdown settles, with its outcome.
1238
- */
1239
- close(): Promise<void> {
1240
- if (this.#closing === undefined) {
1241
- const shutdown = this.#command('shutdown', {});
1242
- this.#closed = true;
1243
- this.#closing = shutdown
1244
- .then(() => {})
1245
- .finally(() => {
1246
- this.#unlisten?.();
1247
- this.#unlisten = undefined;
1248
- this.#invalidationListeners.clear();
1249
- this.#progress.clear();
1250
- this.#changeListeners.clear();
1251
- this.#diagnosticsListeners.clear();
1252
- this.#presenceListeners.clear();
1253
- });
1254
- }
1255
- return this.#closing;
1256
- }
1257
- }
1258
-
1259
- function decodeDiagnosticsSnapshot(
1260
- value: unknown,
1261
- kind: 'tauri',
1262
- ): ClientDiagnosticsSnapshot | undefined {
1263
- if (value === null || typeof value !== 'object') return undefined;
1264
- const snapshot = value as ClientDiagnosticsSnapshot;
1265
- if (snapshot.version !== 1 || snapshot.host === undefined) return undefined;
1266
- return withClientDiagnosticsHost(snapshot, {
1267
- ...snapshot.host,
1268
- kind,
1269
- role: 'single',
1270
- });
1271
- }
1272
-
1273
- /** The error a `{error}` reply surfaces (mirrors the web-client `ClientSyncError`). */
1274
- export class TauriSyncError extends Error {
1275
- readonly code: string;
1276
- readonly details: Readonly<Record<string, unknown>> | undefined;
1277
- readonly retryable: boolean;
1278
- constructor(
1279
- code: string,
1280
- message: string,
1281
- details?: Readonly<Record<string, unknown>>,
1282
- retryable = false,
1283
- ) {
1284
- super(message);
1285
- this.name = 'TauriSyncError';
1286
- this.code = code;
1287
- this.details = details;
1288
- this.retryable = retryable;
1289
- }
1290
- }
1291
-
1292
- function toStringSet(value: unknown): ReadonlySet<string> {
1293
- if (Array.isArray(value)) {
1294
- return new Set(value.filter((v): v is string => typeof v === 'string'));
1295
- }
1296
- return new Set<string>();
1297
- }
1298
-
1299
- function decodeChangeBatch(value: unknown): ClientChangeBatch | undefined {
1300
- if (value === null || typeof value !== 'object') return undefined;
1301
- const raw = value as Record<string, unknown>;
1302
- if (typeof raw.revision !== 'string') return undefined;
1303
- const tables = Array.isArray(raw.tables)
1304
- ? raw.tables.flatMap((entry) => {
1305
- if (entry === null || typeof entry !== 'object') return [];
1306
- const item = entry as Record<string, unknown>;
1307
- if (typeof item.table !== 'string') return [];
1308
- return [
1309
- {
1310
- table: item.table,
1311
- ...(Array.isArray(item.scopeKeys)
1312
- ? { scopeKeys: toStringSet(item.scopeKeys) }
1313
- : {}),
1314
- },
1315
- ];
1316
- })
1317
- : [];
1318
- const windows = Array.isArray(raw.windows)
1319
- ? raw.windows.flatMap((entry) => {
1320
- if (entry === null || typeof entry !== 'object') return [];
1321
- const item = entry as Record<string, unknown>;
1322
- if (
1323
- typeof item.baseKey !== 'string' ||
1324
- typeof item.table !== 'string'
1325
- ) {
1326
- return [];
1327
- }
1328
- return [
1329
- {
1330
- baseKey: item.baseKey,
1331
- table: item.table,
1332
- units: toStringSet(item.units),
1333
- },
1334
- ];
1335
- })
1336
- : [];
1337
- const appliedCommits: NonNullable<
1338
- ClientChangeBatch['appliedCommits']
1339
- >[number][] = [];
1340
- if (raw.appliedCommits !== undefined) {
1341
- if (!Array.isArray(raw.appliedCommits)) return undefined;
1342
- for (const entry of raw.appliedCommits) {
1343
- if (entry === null || typeof entry !== 'object') return undefined;
1344
- const item = entry as Record<string, unknown>;
1345
- if (
1346
- typeof item.subscriptionId !== 'string' ||
1347
- typeof item.table !== 'string' ||
1348
- typeof item.commitSeq !== 'number' ||
1349
- !Number.isSafeInteger(item.commitSeq) ||
1350
- item.commitSeq < 1 ||
1351
- (item.source !== 'delta' && item.source !== 'pull')
1352
- )
1353
- return undefined;
1354
- appliedCommits.push({
1355
- subscriptionId: item.subscriptionId,
1356
- table: item.table,
1357
- commitSeq: item.commitSeq,
1358
- source: item.source,
1359
- });
1360
- }
1361
- }
1362
- return {
1363
- revision: BigInt(raw.revision),
1364
- tables,
1365
- windows,
1366
- ...(raw.appliedCommits !== undefined ? { appliedCommits } : {}),
1367
- ...(raw.status !== undefined
1368
- ? { status: raw.status as SyncStatusSnapshot }
1369
- : {}),
1370
- conflictsChanged: raw.conflictsChanged === true,
1371
- rejectionsChanged: raw.rejectionsChanged === true,
1372
- outcomesChanged: raw.outcomesChanged === true,
1373
- };
1374
- }
1375
-
1376
- function invalidationFromChange(
1377
- batch: ClientChangeBatch,
1378
- ): InvalidationEvent | undefined {
1379
- if (batch.tables.length === 0 && batch.windows.length === 0) return undefined;
1380
- const tables = new Set<string>();
1381
- const scopeKeys = new Set<string>();
1382
- for (const table of batch.tables) {
1383
- tables.add(table.table);
1384
- for (const key of table.scopeKeys ?? []) scopeKeys.add(key);
1385
- }
1386
- for (const window of batch.windows) tables.add(window.table);
1387
- return { tables, scopeKeys };
1388
- }
1389
-
1390
- /** Encode one mutation for the command JSON (bytes inside `values` handled by
1391
- * the native side; the driver form is already JSON-able). */
1392
- function encodeMutation(mutation: MutationInput): unknown {
1393
- if (mutation.op === 'delete') return mutation;
1394
- const values: Record<string, unknown> = {};
1395
- for (const [key, value] of Object.entries(mutation.values)) {
1396
- values[key] = encodeJsonValue(value);
1397
- }
1398
- return { ...mutation, values };
1399
212
  }
1400
213
 
1401
214
  /**
@@ -1419,77 +232,40 @@ export async function createTauriSyncClient(
1419
232
  createClient = (...args: ConstructorParameters<typeof TauriSyncClient>) =>
1420
233
  new TauriSyncClient(...args),
1421
234
  ): Promise<TauriSyncClient> {
1422
- const tauri = await resolveTauri(config.tauri);
1423
-
1424
- // Wire the event stream BEFORE create, so no early change batch is missed.
1425
- const clientRef: { client: TauriSyncClient | undefined } = {
1426
- client: undefined,
235
+ // The native side owns every path (plugin config); the JS side names a
236
+ // database and supplies the schema, clientId, and limits.
237
+ const params = {
238
+ ...nativeCreateParams(config, TauriSyncError),
239
+ ...(config.database !== undefined ? { database: config.database } : {}),
240
+ ...(config.retainFailedCommits !== undefined
241
+ ? { retainFailedCommits: config.retainFailedCommits }
242
+ : {}),
243
+ ...(config.transportEnabled !== undefined
244
+ ? { transportEnabled: config.transportEnabled }
245
+ : {}),
246
+ ...(config.authorityReads !== undefined
247
+ ? { authorityReads: config.authorityReads.declarations }
248
+ : {}),
1427
249
  };
1428
- const unlisten = await tauri.listen<SyncularEvent>(
1429
- SYNCULAR_EVENT,
1430
- (event) => {
1431
- clientRef.client?.__dispatchEvent(event.payload);
1432
- },
250
+ const tauri = await resolveTauri(config.tauri);
251
+ // The create carries the event channel, so no early change batch is missed.
252
+ // Releasing the bridge drops its reference, which ends dispatch.
253
+ let client: TauriSyncClient | undefined;
254
+ const events = tauri.channel<SyncularEvent>((event) =>
255
+ client?.__dispatchEvent(event),
1433
256
  );
1434
-
1435
- if (config.securityPreflight === true && config.encryption !== undefined) {
1436
- unlisten();
1437
- throw new TauriSyncError(
1438
- 'sync.invalid_request',
1439
- 'securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight',
1440
- );
1441
- }
1442
-
1443
- const client = createClient(
257
+ const opened = createClient(
1444
258
  tauri,
1445
- unlisten,
259
+ () => {
260
+ client = undefined;
261
+ },
1446
262
  config.securityPreflight === true ? 'preflight' : 'active',
1447
263
  );
1448
- clientRef.client = client;
1449
-
1450
- // The native side owns every path (plugin config); the JS side names a
1451
- // database and supplies the schema, clientId, and limits.
1452
- const reply = await tauri.invoke<CommandReply>(`${PLUGIN}syncular_command`, {
1453
- command: {
1454
- method: 'create',
1455
- params: {
1456
- ...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
1457
- ...(config.database !== undefined ? { database: config.database } : {}),
1458
- schema: config.schema,
1459
- ...(config.limits !== undefined ? { limits: config.limits } : {}),
1460
- ...(config.retainFailedCommits !== undefined
1461
- ? { retainFailedCommits: config.retainFailedCommits }
1462
- : {}),
1463
- ...(config.realtimePolicy !== undefined
1464
- ? { realtimePolicy: config.realtimePolicy }
1465
- : {}),
1466
- ...(config.encryption !== undefined
1467
- ? { encryption: encodeEncryption(config.encryption) }
1468
- : {}),
1469
- ...(config.transportEnabled !== undefined
1470
- ? { transportEnabled: config.transportEnabled }
1471
- : {}),
1472
- ...(config.authorityReads !== undefined
1473
- ? { authorityReads: config.authorityReads.declarations }
1474
- : {}),
1475
- ...(config.securityPreflight !== undefined
1476
- ? { securityPreflight: config.securityPreflight }
1477
- : {}),
1478
- ...(config.previousVersionContext !== undefined
1479
- ? { previousVersionContext: config.previousVersionContext }
1480
- : {}),
1481
- },
1482
- },
1483
- });
1484
- if (reply.error !== undefined) {
1485
- unlisten();
1486
- throw new TauriSyncError(
1487
- reply.error.code,
1488
- reply.error.message,
1489
- reply.error.details ?? undefined,
1490
- reply.error.retryable ?? false,
1491
- );
1492
- }
1493
-
1494
- return client;
264
+ client = opened;
265
+ await opened.__open(() =>
266
+ tauri.invoke<NativeReply>(`${PLUGIN}syncular_command`, {
267
+ command: { method: 'create', params: { ...params, events } },
268
+ }),
269
+ );
270
+ return opened;
1495
271
  }