@syncular/tauri 0.53.1 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/index.d.ts +8 -272
- package/dist/index.js +15 -962
- package/dist/remote.d.ts +266 -0
- package/dist/remote.js +977 -0
- package/package.json +12 -4
- package/src/index.ts +18 -1451
- package/src/remote.ts +1488 -0
package/src/index.ts
CHANGED
|
@@ -1,1398 +1,37 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
type
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* @syncular/tauri — the JS bridge to the native syncular instance running
|
|
9
|
-
* inside the Tauri process (see `tauri-plugin-syncular`).
|
|
10
|
-
*
|
|
11
|
-
* 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.
|
|
18
|
-
*
|
|
19
|
-
* 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.
|
|
30
|
-
*
|
|
31
|
-
* `@tauri-apps/api` is a required peer dependency: the bridge takes
|
|
32
|
-
* `invoke`/`listen` either from its ESM entry points, from the ambient
|
|
33
|
-
* `window.__TAURI__`, or via injected doubles (tests).
|
|
34
|
-
*/
|
|
2
|
+
createTauriSyncClient as createRemoteTauriSyncClient,
|
|
3
|
+
TauriSyncClient as RemoteTauriSyncClient,
|
|
4
|
+
type LocalAuthorityState,
|
|
5
|
+
type TauriSyncClientConfig,
|
|
6
|
+
} from './remote';
|
|
35
7
|
|
|
36
|
-
|
|
37
|
-
AuthorityReadPolicy,
|
|
38
|
-
ClientChangeBatch,
|
|
39
|
-
ClientChangeListener,
|
|
40
|
-
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
|
-
SecurityLifecycle,
|
|
65
|
-
SnapshotRead,
|
|
66
|
-
SnapshotReadRequest,
|
|
67
|
-
SqlRow,
|
|
68
|
-
SqlValue,
|
|
69
|
-
SyncClientConfig,
|
|
70
|
-
SyncStatusSnapshot,
|
|
71
|
-
WindowBase,
|
|
72
|
-
WindowState,
|
|
73
|
-
} 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
|
-
import {
|
|
78
|
-
decodeLocalDataRebootstrapResult,
|
|
79
|
-
decodePreviousVersionAuditResult,
|
|
80
|
-
decodePreviousVersionDiscardResult,
|
|
81
|
-
decodePreviousVersionSnapshot,
|
|
82
|
-
SECURITY_PREFLIGHT_REQUIRED_CODE,
|
|
83
|
-
withClientDiagnosticsHost,
|
|
84
|
-
} from '@syncular/client';
|
|
85
|
-
|
|
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
|
-
}
|
|
102
|
-
|
|
103
|
-
/** §7.5: one read-only statement in an atomic sidecar snapshot read. */
|
|
104
|
-
export type { SnapshotStatement } from '@syncular/client';
|
|
105
|
-
|
|
106
|
-
/** §7.5: the catch-up state of one subscription from the sidecar. */
|
|
107
|
-
export type { SubscriptionCatchup } from '@syncular/client';
|
|
108
|
-
|
|
109
|
-
/** §7.5: delivery status for one client commit id. */
|
|
110
|
-
export type { CommitDelivery } from '@syncular/client';
|
|
111
|
-
|
|
112
|
-
/** §7.5: one atomic sidecar snapshot read result with decoded rows. */
|
|
113
|
-
export type SnapshotReadResult = SnapshotRead;
|
|
114
|
-
|
|
115
|
-
/** The two Tauri primitives the bridge needs — injectable for tests. */
|
|
116
|
-
export interface TauriApi {
|
|
117
|
-
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>;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** The plugin's Tauri event name — mirror of `tauri-plugin-syncular`. */
|
|
125
|
-
export const SYNCULAR_EVENT = 'syncular://event';
|
|
126
|
-
|
|
127
|
-
const PLUGIN = 'plugin:syncular|';
|
|
128
|
-
|
|
129
|
-
/** SPEC §12 local authority lifecycle state. */
|
|
130
|
-
export type LocalAuthorityState = 'local' | 'attaching' | 'attached';
|
|
131
|
-
|
|
132
|
-
/** 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;
|
|
142
|
-
/**
|
|
143
|
-
* Name of the native database to open, for example one replica per
|
|
144
|
-
* signed-in actor. The plugin opens `<database_dir>/<database>.db` from its
|
|
145
|
-
* `SyncularConfig`; a name is 1 to 128 ASCII letters, digits, `-`, `_` or
|
|
146
|
-
* `.` and starts with a letter or digit. Absent ⇒ the plugin's `db_path`.
|
|
147
|
-
*/
|
|
148
|
-
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
|
-
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
|
-
/** Fixed plain authority reads permitted before security activation. */
|
|
164
|
-
readonly authorityReads?: AuthorityReadPolicy;
|
|
165
|
-
/** Open the native replica behind the fail-closed security gate. */
|
|
166
|
-
readonly securityPreflight?: boolean;
|
|
167
|
-
/** Open local storage with network transport closed until explicitly resumed. */
|
|
168
|
-
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
|
-
/**
|
|
176
|
-
* The Tauri primitives. Omit in a real Tauri webview to auto-resolve from
|
|
177
|
-
* `@tauri-apps/api` (peer dep) or the ambient `window.__TAURI__`; inject in
|
|
178
|
-
* tests. Resolution is async, so construction is a factory (below).
|
|
179
|
-
*/
|
|
180
|
-
readonly tauri?: TauriApi;
|
|
181
|
-
}
|
|
182
|
-
|
|
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
|
-
};
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/** Resolve the Tauri primitives from the ambient environment when not injected. */
|
|
401
|
-
async function resolveTauri(injected: TauriApi | undefined): Promise<TauriApi> {
|
|
402
|
-
if (injected !== undefined) return injected;
|
|
403
|
-
// 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
|
|
420
|
-
// `@vite-ignore` makes WebKit resolve it as a URL at runtime instead of
|
|
421
|
-
// 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 };
|
|
427
|
-
}
|
|
428
|
-
|
|
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> {
|
|
435
|
-
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
|
-
#securityLifecycle: SecurityLifecycle;
|
|
444
|
-
#preflightBarrier: Promise<void> | undefined;
|
|
445
|
-
#diagnosticsEnabled = false;
|
|
446
|
-
|
|
447
|
-
/** @internal — use {@link createTauriSyncClient}. */
|
|
448
|
-
constructor(
|
|
449
|
-
tauri: TauriApi,
|
|
450
|
-
unlisten: () => void,
|
|
451
|
-
securityLifecycle: SecurityLifecycle = 'active',
|
|
452
|
-
) {
|
|
453
|
-
this.#tauri = tauri;
|
|
454
|
-
this.#unlisten = unlisten;
|
|
455
|
-
this.#securityLifecycle = securityLifecycle;
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
/** Dispatch a `syncular_command` and unwrap `{result}` / throw on `{error}`. */
|
|
459
|
-
async #command(
|
|
460
|
-
method: string,
|
|
461
|
-
params: Record<string, unknown>,
|
|
462
|
-
): Promise<unknown> {
|
|
463
|
-
this.#requireOpen();
|
|
464
|
-
if (
|
|
465
|
-
this.#securityLifecycle === 'preflight' &&
|
|
466
|
-
![
|
|
467
|
-
'authoritySnapshot',
|
|
468
|
-
'securityLifecycle',
|
|
469
|
-
'beginSecurityPreflight',
|
|
470
|
-
'activateSecurity',
|
|
471
|
-
'setTransportEnabled',
|
|
472
|
-
'purgeLocalData',
|
|
473
|
-
'previousVersionDiscard',
|
|
474
|
-
'localRevision',
|
|
475
|
-
'statusSnapshot',
|
|
476
|
-
'localAuthorityState',
|
|
477
|
-
'shutdown',
|
|
478
|
-
].includes(method)
|
|
479
|
-
) {
|
|
480
|
-
this.#throwSecurityPreflight();
|
|
481
|
-
}
|
|
482
|
-
const reply = await this.#tauri.invoke<CommandReply>(
|
|
483
|
-
`${PLUGIN}syncular_command`,
|
|
484
|
-
{ command: { method, params } },
|
|
485
|
-
);
|
|
486
|
-
if (reply.error !== undefined) {
|
|
487
|
-
throw new TauriSyncError(
|
|
488
|
-
reply.error.code,
|
|
489
|
-
reply.error.message,
|
|
490
|
-
reply.error.details ?? undefined,
|
|
491
|
-
reply.error.retryable ?? false,
|
|
492
|
-
);
|
|
493
|
-
}
|
|
494
|
-
return reply.result;
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
#throwSecurityPreflight(): never {
|
|
498
|
-
throw new TauriSyncError(
|
|
499
|
-
SECURITY_PREFLIGHT_REQUIRED_CODE,
|
|
500
|
-
'the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data',
|
|
501
|
-
);
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
#requireOpen(): void {
|
|
505
|
-
if (this.#closed) {
|
|
506
|
-
throw new TauriSyncError(
|
|
507
|
-
'client.closed',
|
|
508
|
-
'the Tauri sync client is closed',
|
|
509
|
-
);
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
/** @internal Shared command gate for explicit bridge extensions. */
|
|
514
|
-
protected command(
|
|
515
|
-
method: string,
|
|
516
|
-
params: Record<string, unknown>,
|
|
517
|
-
): Promise<unknown> {
|
|
518
|
-
return this.#command(method, params);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
/** @internal Recheck local close after an extension's asynchronous reply. */
|
|
522
|
-
protected requireOpen(): void {
|
|
523
|
-
this.#requireOpen();
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
#requireActive(): void {
|
|
527
|
-
this.#requireOpen();
|
|
528
|
-
if (this.#securityLifecycle === 'preflight') this.#throwSecurityPreflight();
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
/** @internal — fan an incoming plugin event out to the local listeners. */
|
|
532
|
-
__dispatchEvent(event: SyncularEvent): void {
|
|
533
|
-
switch (event.type) {
|
|
534
|
-
case 'progress': {
|
|
535
|
-
this.#progress.emit(event.progress as SyncProgress);
|
|
536
|
-
break;
|
|
537
|
-
}
|
|
538
|
-
case 'change': {
|
|
539
|
-
const batch = decodeChangeBatch(event.batch);
|
|
540
|
-
if (batch === undefined) break;
|
|
541
|
-
for (const listener of this.#changeListeners) {
|
|
542
|
-
try {
|
|
543
|
-
listener(batch);
|
|
544
|
-
} catch {
|
|
545
|
-
/* a UI listener must never break event dispatch */
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
const payload = invalidationFromChange(batch);
|
|
549
|
-
if (payload === undefined) break;
|
|
550
|
-
for (const listener of this.#invalidationListeners) {
|
|
551
|
-
try {
|
|
552
|
-
listener(payload);
|
|
553
|
-
} catch {
|
|
554
|
-
/* a UI listener must never break event dispatch */
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
break;
|
|
558
|
-
}
|
|
559
|
-
case 'presence': {
|
|
560
|
-
const scopeKey =
|
|
561
|
-
typeof event.scopeKey === 'string' ? event.scopeKey : '';
|
|
562
|
-
for (const listener of this.#presenceListeners) {
|
|
563
|
-
try {
|
|
564
|
-
listener(scopeKey);
|
|
565
|
-
} catch {
|
|
566
|
-
/* never break dispatch */
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
break;
|
|
570
|
-
}
|
|
571
|
-
case 'diagnostics': {
|
|
572
|
-
const snapshot = decodeDiagnosticsSnapshot(event.snapshot, 'tauri');
|
|
573
|
-
if (snapshot === undefined) break;
|
|
574
|
-
for (const listener of this.#diagnosticsListeners) {
|
|
575
|
-
try {
|
|
576
|
-
listener(snapshot);
|
|
577
|
-
} catch {
|
|
578
|
-
/* a diagnostics observer must never break event dispatch */
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
break;
|
|
582
|
-
}
|
|
583
|
-
default:
|
|
584
|
-
// Unknown extension events are deliberately ignored. All durable
|
|
585
|
-
// observable state arrives in the revisioned `change` batch.
|
|
586
|
-
break;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
// -- SyncClientLike --------------------------------------------------------
|
|
591
|
-
|
|
592
|
-
async securityLifecycle(): Promise<SecurityLifecycle> {
|
|
593
|
-
this.#requireOpen();
|
|
594
|
-
return Promise.resolve(this.#securityLifecycle);
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
beginSecurityPreflight(): Promise<void> {
|
|
598
|
-
if (this.#closed) {
|
|
599
|
-
return Promise.reject(
|
|
600
|
-
new TauriSyncError('client.closed', 'the Tauri sync client is closed'),
|
|
601
|
-
);
|
|
602
|
-
}
|
|
603
|
-
if (this.#preflightBarrier !== undefined) return this.#preflightBarrier;
|
|
604
|
-
// Flip synchronously so a same-webview query cannot race the IPC barrier.
|
|
605
|
-
this.#securityLifecycle = 'preflight';
|
|
606
|
-
const barrier = this.#command('beginSecurityPreflight', {}).then(() => {});
|
|
607
|
-
this.#preflightBarrier = barrier;
|
|
608
|
-
void barrier.then(
|
|
609
|
-
() => {
|
|
610
|
-
if (this.#preflightBarrier === barrier)
|
|
611
|
-
this.#preflightBarrier = undefined;
|
|
612
|
-
},
|
|
613
|
-
() => {
|
|
614
|
-
if (this.#preflightBarrier === barrier)
|
|
615
|
-
this.#preflightBarrier = undefined;
|
|
616
|
-
},
|
|
617
|
-
);
|
|
618
|
-
return barrier;
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
/**
|
|
622
|
-
* Complete the security preflight. `headers` optionally carries a fresh
|
|
623
|
-
* FULL transport header set that the native host applies atomically with
|
|
624
|
-
* the activation, before the startup sync it enqueues — so a preflight
|
|
625
|
-
* that outlives the boot token starts its first round with valid
|
|
626
|
-
* credentials (the direct `setHeaders` path stays refused while gated).
|
|
627
|
-
*/
|
|
628
|
-
async activateSecurity(
|
|
629
|
-
options: {
|
|
630
|
-
readonly encryption?: EncryptionKeyringConfig;
|
|
631
|
-
readonly headers?: Readonly<Record<string, string>>;
|
|
632
|
-
} = {},
|
|
633
|
-
): Promise<void> {
|
|
634
|
-
this.#requireOpen();
|
|
635
|
-
if (this.#securityLifecycle === 'active') {
|
|
636
|
-
throw new TauriSyncError(
|
|
637
|
-
'sync.invalid_request',
|
|
638
|
-
'activateSecurity requires the client to be in security preflight',
|
|
639
|
-
);
|
|
640
|
-
}
|
|
641
|
-
await this.#preflightBarrier;
|
|
642
|
-
await this.#command('activateSecurity', {
|
|
643
|
-
...(options.encryption !== undefined
|
|
644
|
-
? { encryption: encodeEncryption(options.encryption) }
|
|
645
|
-
: {}),
|
|
646
|
-
...(options.headers !== undefined ? { headers: options.headers } : {}),
|
|
647
|
-
});
|
|
648
|
-
this.#securityLifecycle = 'active';
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
onInvalidate(listener: InvalidationListener): () => void {
|
|
652
|
-
this.#requireOpen();
|
|
653
|
-
this.#invalidationListeners.add(listener);
|
|
654
|
-
return () => this.#invalidationListeners.delete(listener);
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
onProgress(listener: SyncProgressListener): () => void {
|
|
658
|
-
this.#requireOpen();
|
|
659
|
-
return this.#progress.on(listener);
|
|
660
|
-
}
|
|
661
|
-
progressSnapshot(): SyncProgress | undefined {
|
|
662
|
-
this.#requireOpen();
|
|
663
|
-
return this.#progress.snapshot();
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
onChange(listener: ClientChangeListener): () => void {
|
|
667
|
-
this.#requireOpen();
|
|
668
|
-
this.#changeListeners.add(listener);
|
|
669
|
-
return () => this.#changeListeners.delete(listener);
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
onDiagnostics(listener: ClientDiagnosticsListener): () => void {
|
|
673
|
-
this.#requireOpen();
|
|
674
|
-
this.#diagnosticsListeners.add(listener);
|
|
675
|
-
this.#enableDiagnosticsPush();
|
|
676
|
-
return () => this.#diagnosticsListeners.delete(listener);
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
/**
|
|
680
|
-
* Host-local push registration: the native core emits pushed diagnostics
|
|
681
|
-
* snapshots only once a consumer is known (a `diagnosticsSnapshot` pull, or
|
|
682
|
-
* this explicit `enableDiagnostics` signal). Fired once, on the first
|
|
683
|
-
* registered listener, fire-and-forget. The invoke deliberately bypasses
|
|
684
|
-
* the bridge's preflight gate — the command is a pure observability
|
|
685
|
-
* registration handled before dispatch, and the native side stays silent
|
|
686
|
-
* until activation anyway. Errors are tolerated: an older native core
|
|
687
|
-
* rejects the unknown command, and the mount-time snapshot pull path keeps
|
|
688
|
-
* `useDiagnostics` working there.
|
|
689
|
-
*/
|
|
690
|
-
#enableDiagnosticsPush(): void {
|
|
691
|
-
if (this.#diagnosticsEnabled || this.#closed) return;
|
|
692
|
-
this.#diagnosticsEnabled = true;
|
|
693
|
-
void this.#tauri
|
|
694
|
-
.invoke<CommandReply>(`${PLUGIN}syncular_command`, {
|
|
695
|
-
command: { method: 'enableDiagnostics', params: {} },
|
|
696
|
-
})
|
|
697
|
-
.catch(() => {
|
|
698
|
-
/* fire-and-forget; an error reply is equally ignored above */
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
onPresence(listener: (scopeKey: string) => void): () => void {
|
|
703
|
-
this.#requireOpen();
|
|
704
|
-
this.#presenceListeners.add(listener);
|
|
705
|
-
return () => this.#presenceListeners.delete(listener);
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
async query(sql: string, params?: readonly SqlValue[]): Promise<SqlRow[]> {
|
|
709
|
-
this.#requireActive();
|
|
710
|
-
const reply = await this.#tauri.invoke<CommandReply>(
|
|
711
|
-
`${PLUGIN}syncular_query`,
|
|
712
|
-
{ sql, params: (params ?? []).map(encodeParam) },
|
|
713
|
-
);
|
|
714
|
-
if (reply.error !== undefined) {
|
|
715
|
-
throw new TauriSyncError(
|
|
716
|
-
reply.error.code,
|
|
717
|
-
reply.error.message,
|
|
718
|
-
reply.error.details ?? undefined,
|
|
719
|
-
reply.error.retryable ?? false,
|
|
720
|
-
);
|
|
721
|
-
}
|
|
722
|
-
const rows = (reply.result as { rows?: unknown[] }).rows ?? [];
|
|
723
|
-
return rows.map((r) => decodeRow(r as Record<string, unknown>));
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
async querySnapshot<Row = SqlRow>(
|
|
727
|
-
spec: QueryReadSpec,
|
|
728
|
-
): Promise<QuerySnapshot<Row>> {
|
|
729
|
-
this.#requireActive();
|
|
730
|
-
const reply = await this.#tauri.invoke<CommandReply>(
|
|
731
|
-
`${PLUGIN}syncular_query_snapshot`,
|
|
732
|
-
{
|
|
733
|
-
sql: spec.sql,
|
|
734
|
-
params: (spec.params ?? []).map(encodeParam),
|
|
735
|
-
coverage: spec.coverage ?? [],
|
|
736
|
-
...(spec.owner !== undefined ? { owner: spec.owner } : {}),
|
|
737
|
-
},
|
|
738
|
-
);
|
|
739
|
-
if (reply.error !== undefined) {
|
|
740
|
-
throw new TauriSyncError(
|
|
741
|
-
reply.error.code,
|
|
742
|
-
reply.error.message,
|
|
743
|
-
reply.error.details ?? undefined,
|
|
744
|
-
reply.error.retryable ?? false,
|
|
745
|
-
);
|
|
746
|
-
}
|
|
747
|
-
const result = reply.result as {
|
|
748
|
-
revision: string;
|
|
749
|
-
rows: Record<string, unknown>[];
|
|
750
|
-
coverage: QuerySnapshot['coverage'];
|
|
751
|
-
};
|
|
752
|
-
return {
|
|
753
|
-
revision: BigInt(result.revision),
|
|
754
|
-
rows: result.rows.map(decodeRow) as unknown as readonly Row[],
|
|
755
|
-
coverage: result.coverage,
|
|
756
|
-
};
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
async localRevision(): Promise<bigint> {
|
|
760
|
-
const result = (await this.#command('localRevision', {})) as {
|
|
761
|
-
revision: string;
|
|
762
|
-
};
|
|
763
|
-
return BigInt(result.revision);
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
/**
|
|
767
|
-
* §7.5: one atomic read over the file-backed sidecar. Every statement and
|
|
768
|
-
* every catch-up/delivery read shares one revision (a `bigint`, matching
|
|
769
|
-
* `querySnapshot`) and one read transaction; every query row is decoded.
|
|
770
|
-
*/
|
|
771
|
-
async snapshotRead(request: SnapshotReadRequest): Promise<SnapshotRead> {
|
|
772
|
-
this.#requireActive();
|
|
773
|
-
const reply = await this.#tauri.invoke<CommandReply>(
|
|
774
|
-
`${PLUGIN}syncular_snapshot_read`,
|
|
775
|
-
{
|
|
776
|
-
statements: request.statements.map((statement) => ({
|
|
777
|
-
sql: statement.sql,
|
|
778
|
-
params: (statement.params ?? []).map(encodeParam),
|
|
779
|
-
})),
|
|
780
|
-
coverage: request.coverage ?? [],
|
|
781
|
-
subscriptions: request.subscriptions ?? [],
|
|
782
|
-
commitIds: request.commitIds ?? [],
|
|
783
|
-
...(request.owner !== undefined ? { owner: request.owner } : {}),
|
|
784
|
-
},
|
|
785
|
-
);
|
|
786
|
-
if (reply.error !== undefined) {
|
|
787
|
-
throw new TauriSyncError(
|
|
788
|
-
reply.error.code,
|
|
789
|
-
reply.error.message,
|
|
790
|
-
reply.error.details ?? undefined,
|
|
791
|
-
reply.error.retryable ?? false,
|
|
792
|
-
);
|
|
793
|
-
}
|
|
794
|
-
const result = reply.result as {
|
|
795
|
-
revision: string;
|
|
796
|
-
queries: readonly (readonly Record<string, unknown>[])[];
|
|
797
|
-
coverage: SnapshotRead['coverage'];
|
|
798
|
-
subscriptions: SnapshotRead['subscriptions'];
|
|
799
|
-
deliveries: SnapshotRead['deliveries'];
|
|
800
|
-
};
|
|
801
|
-
return {
|
|
802
|
-
revision: BigInt(result.revision),
|
|
803
|
-
queries: result.queries.map((rows) => rows.map(decodeRow)),
|
|
804
|
-
coverage: result.coverage,
|
|
805
|
-
subscriptions: result.subscriptions,
|
|
806
|
-
deliveries: result.deliveries.map((delivery) =>
|
|
807
|
-
delivery.status === 'known'
|
|
808
|
-
? { ...delivery, outcome: decodeCommitOutcome(delivery.outcome) }
|
|
809
|
-
: delivery,
|
|
810
|
-
),
|
|
811
|
-
};
|
|
812
|
-
}
|
|
8
|
+
export * from './remote';
|
|
813
9
|
|
|
814
|
-
|
|
815
|
-
|
|
10
|
+
/** Tauri bridge with the optional local-authority lifecycle (§12). */
|
|
11
|
+
export class TauriSyncClient extends RemoteTauriSyncClient {
|
|
12
|
+
protected override allowPreflightCommand(method: string): boolean {
|
|
13
|
+
return method === 'localAuthorityState';
|
|
816
14
|
}
|
|
817
15
|
|
|
818
|
-
|
|
819
|
-
request: ClientDiagnosticsRequest = {},
|
|
820
|
-
): Promise<ClientDiagnosticsSnapshot> {
|
|
821
|
-
const snapshot = (await this.#command('diagnosticsSnapshot', {
|
|
822
|
-
expectedSubscriptions: request.expectedSubscriptions ?? [],
|
|
823
|
-
})) as ClientDiagnosticsSnapshot;
|
|
824
|
-
return withClientDiagnosticsHost(snapshot, {
|
|
825
|
-
...snapshot.host,
|
|
826
|
-
kind: 'tauri',
|
|
827
|
-
role: 'single',
|
|
828
|
-
});
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
async mutate(mutations: readonly MutationInput[]): Promise<string> {
|
|
832
|
-
const result = (await this.#command('mutate', {
|
|
833
|
-
mutations: mutations.map(encodeMutation),
|
|
834
|
-
})) as { clientCommitId: string };
|
|
835
|
-
return result.clientCommitId;
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
async patch(
|
|
839
|
-
table: string,
|
|
840
|
-
rowId: string,
|
|
841
|
-
partial: Readonly<Record<string, unknown>>,
|
|
842
|
-
options?: { readonly baseVersion?: number },
|
|
843
|
-
): Promise<string> {
|
|
844
|
-
const result = (await this.#command('patch', {
|
|
845
|
-
table,
|
|
846
|
-
rowId,
|
|
847
|
-
partial: encodeJsonValue(partial),
|
|
848
|
-
...(options?.baseVersion !== undefined
|
|
849
|
-
? { baseVersion: options.baseVersion }
|
|
850
|
-
: {}),
|
|
851
|
-
})) as { clientCommitId: string };
|
|
852
|
-
return result.clientCommitId;
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
async purgeLocalData(
|
|
856
|
-
input: LocalDataPurgeInput,
|
|
857
|
-
): Promise<LocalDataPurgeResult> {
|
|
858
|
-
return (await this.#command('purgeLocalData', {
|
|
859
|
-
input,
|
|
860
|
-
})) as LocalDataPurgeResult;
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
async rebootstrapLocalData(
|
|
864
|
-
input: LocalDataRebootstrapInput,
|
|
865
|
-
): Promise<LocalDataRebootstrapResult> {
|
|
866
|
-
return decodeLocalDataRebootstrapResult(
|
|
867
|
-
await this.#command('rebootstrapLocalData', { input }),
|
|
868
|
-
);
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
async previousVersionSnapshot(
|
|
872
|
-
spec: PreviousVersionReadSpec,
|
|
873
|
-
): Promise<PreviousVersionSnapshot> {
|
|
874
|
-
return decodePreviousVersionSnapshot(
|
|
875
|
-
decodeSnapshotRows(
|
|
876
|
-
await this.#command('previousVersionSnapshot', { spec }),
|
|
877
|
-
),
|
|
878
|
-
);
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
async previousVersionAudit(): Promise<PreviousVersionAudit | undefined> {
|
|
882
|
-
return decodePreviousVersionAuditResult(
|
|
883
|
-
await this.#command('previousVersionAudit', {}),
|
|
884
|
-
);
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
async previousVersionDiscard(): Promise<{
|
|
888
|
-
present: boolean;
|
|
889
|
-
discarded: boolean;
|
|
890
|
-
}> {
|
|
891
|
-
return decodePreviousVersionDiscardResult(
|
|
892
|
-
await this.#command('previousVersionDiscard', {}),
|
|
893
|
-
);
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
/** Suspend new network work while retaining local access and queued commits. */
|
|
897
|
-
async setTransportEnabled(enabled: boolean): Promise<void> {
|
|
898
|
-
await this.#command('setTransportEnabled', { enabled });
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
/** Browser offline-control parity; local reads and commits remain available. */
|
|
902
|
-
async setOffline(offline: boolean): Promise<void> {
|
|
903
|
-
await this.setTransportEnabled(!offline);
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
/**
|
|
907
|
-
* Replace the native transport's request headers at runtime — the auth
|
|
908
|
-
* rotation path. Pass the FULL header set (it replaces,
|
|
909
|
-
* it does not merge). HTTP requests use the new set from the next call;
|
|
910
|
-
* the realtime socket applies it on its next (re)connect.
|
|
911
|
-
*/
|
|
912
|
-
async setHeaders(headers: Readonly<Record<string, string>>): Promise<void> {
|
|
913
|
-
this.#requireActive();
|
|
914
|
-
const reply = await this.#tauri.invoke<CommandReply>(
|
|
915
|
-
`${PLUGIN}syncular_set_headers`,
|
|
916
|
-
{ headers },
|
|
917
|
-
);
|
|
918
|
-
if (reply.error !== undefined) {
|
|
919
|
-
throw new TauriSyncError(
|
|
920
|
-
reply.error.code,
|
|
921
|
-
reply.error.message,
|
|
922
|
-
reply.error.details ?? undefined,
|
|
923
|
-
reply.error.retryable ?? false,
|
|
924
|
-
);
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
// -- Native CRDT (SPEC.md §5.10.5; needs the plugin `crdt-yjs` feature) ------
|
|
929
|
-
|
|
930
|
-
/** Materialize a `crdt` column's collaborative text — decoded from the
|
|
931
|
-
* stored (server-merged) Yjs bytes. `name` selects the shared text
|
|
932
|
-
* (default `"text"`). An absent row / NULL column is the empty document. */
|
|
933
|
-
async crdtText(
|
|
934
|
-
table: string,
|
|
935
|
-
rowId: string,
|
|
936
|
-
column: string,
|
|
937
|
-
name = 'text',
|
|
938
|
-
): Promise<string> {
|
|
939
|
-
const result = (await this.#command('crdtText', {
|
|
940
|
-
table,
|
|
941
|
-
rowId,
|
|
942
|
-
column,
|
|
943
|
-
name,
|
|
944
|
-
})) as { text: string };
|
|
945
|
-
return result.text;
|
|
946
|
-
}
|
|
947
|
-
|
|
948
|
-
/** Insert `value` at UTF-16 offset `index` in a `crdt` column's text and
|
|
949
|
-
* push the resulting Yjs update (baseVersion-less). Returns the commit id. */
|
|
950
|
-
async crdtInsertText(
|
|
951
|
-
table: string,
|
|
952
|
-
rowId: string,
|
|
953
|
-
column: string,
|
|
954
|
-
index: number,
|
|
955
|
-
value: string,
|
|
956
|
-
name = 'text',
|
|
957
|
-
): Promise<string> {
|
|
958
|
-
const result = (await this.#command('crdtInsertText', {
|
|
959
|
-
table,
|
|
960
|
-
rowId,
|
|
961
|
-
column,
|
|
962
|
-
name,
|
|
963
|
-
index,
|
|
964
|
-
value,
|
|
965
|
-
})) as { clientCommitId: string };
|
|
966
|
-
return result.clientCommitId;
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
/** Delete `len` UTF-16 code units at `index` in a `crdt` column's text. */
|
|
970
|
-
async crdtDeleteText(
|
|
971
|
-
table: string,
|
|
972
|
-
rowId: string,
|
|
973
|
-
column: string,
|
|
974
|
-
index: number,
|
|
975
|
-
len: number,
|
|
976
|
-
name = 'text',
|
|
977
|
-
): Promise<string> {
|
|
978
|
-
const result = (await this.#command('crdtDeleteText', {
|
|
979
|
-
table,
|
|
980
|
-
rowId,
|
|
981
|
-
column,
|
|
982
|
-
name,
|
|
983
|
-
index,
|
|
984
|
-
len,
|
|
985
|
-
})) as { clientCommitId: string };
|
|
986
|
-
return result.clientCommitId;
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
/** Escape hatch: apply an arbitrary Yjs update onto a `crdt` column. */
|
|
990
|
-
async crdtApplyUpdate(
|
|
991
|
-
table: string,
|
|
992
|
-
rowId: string,
|
|
993
|
-
column: string,
|
|
994
|
-
update: Uint8Array,
|
|
995
|
-
): Promise<string> {
|
|
996
|
-
const result = (await this.#command('crdtApplyUpdate', {
|
|
997
|
-
table,
|
|
998
|
-
rowId,
|
|
999
|
-
column,
|
|
1000
|
-
update: { $bytes: bytesToHex(update) },
|
|
1001
|
-
})) as { clientCommitId: string };
|
|
1002
|
-
return result.clientCommitId;
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
/**
|
|
1006
|
-
* Stage a blob for attachment (§5.9.7) and return the canonical `BlobRef`
|
|
1007
|
-
* string to store in a `blob_ref` column. The native core owns the upload
|
|
1008
|
-
* queue; write the referencing row after this resolves (§5.9.3).
|
|
1009
|
-
*/
|
|
1010
|
-
async uploadBlob(
|
|
1011
|
-
bytes: Uint8Array,
|
|
1012
|
-
options?: { readonly mediaType?: string; readonly name?: string },
|
|
1013
|
-
): Promise<string> {
|
|
1014
|
-
const result = (await this.#command('uploadBlob', {
|
|
1015
|
-
bytes: { $bytes: bytesToHex(bytes) },
|
|
1016
|
-
...(options?.mediaType !== undefined
|
|
1017
|
-
? { mediaType: options.mediaType }
|
|
1018
|
-
: {}),
|
|
1019
|
-
...(options?.name !== undefined ? { name: options.name } : {}),
|
|
1020
|
-
})) as { ref: string };
|
|
1021
|
-
return result.ref;
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
/**
|
|
1025
|
-
* Resolve blob bytes for a `blob_ref` column value or a bare `blobId`
|
|
1026
|
-
* (§5.9.7): the native core serves a local cache hit and otherwise
|
|
1027
|
-
* downloads and verifies the content address.
|
|
1028
|
-
*/
|
|
1029
|
-
async fetchBlob(ref: string): Promise<{
|
|
1030
|
-
readonly blobId: string;
|
|
1031
|
-
readonly byteLength: number;
|
|
1032
|
-
readonly bytes: Uint8Array;
|
|
1033
|
-
readonly mediaType?: string;
|
|
1034
|
-
}> {
|
|
1035
|
-
const result = (await this.#command('fetchBlob', { blob: ref })) as {
|
|
1036
|
-
blob: {
|
|
1037
|
-
blobId: string;
|
|
1038
|
-
byteLength: number;
|
|
1039
|
-
bytes: unknown;
|
|
1040
|
-
mediaType?: string;
|
|
1041
|
-
};
|
|
1042
|
-
};
|
|
1043
|
-
const bytes = result.blob.bytes;
|
|
1044
|
-
if (!isBytesEnvelope(bytes))
|
|
1045
|
-
throw new TauriSyncError(
|
|
1046
|
-
'sync.invalid_request',
|
|
1047
|
-
'fetchBlob reply carried no $bytes envelope',
|
|
1048
|
-
);
|
|
1049
|
-
return {
|
|
1050
|
-
blobId: result.blob.blobId,
|
|
1051
|
-
byteLength: result.blob.byteLength,
|
|
1052
|
-
bytes: hexToBytes(bytes.$bytes),
|
|
1053
|
-
...(result.blob.mediaType !== undefined
|
|
1054
|
-
? { mediaType: result.blob.mediaType }
|
|
1055
|
-
: {}),
|
|
1056
|
-
};
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
async subscribe(input: {
|
|
1060
|
-
readonly id: string;
|
|
1061
|
-
readonly table: string;
|
|
1062
|
-
readonly scopes?: Record<string, readonly string[]>;
|
|
1063
|
-
readonly params?: string;
|
|
1064
|
-
}): Promise<void> {
|
|
1065
|
-
await this.#command('subscribe', {
|
|
1066
|
-
id: input.id,
|
|
1067
|
-
table: input.table,
|
|
1068
|
-
scopes: input.scopes ?? {},
|
|
1069
|
-
...(input.params !== undefined ? { params: input.params } : {}),
|
|
1070
|
-
});
|
|
1071
|
-
}
|
|
1072
|
-
|
|
1073
|
-
/** Register several subscriptions in one local transaction. */
|
|
1074
|
-
async subscribeMany(
|
|
1075
|
-
inputs: readonly {
|
|
1076
|
-
readonly id: string;
|
|
1077
|
-
readonly table: string;
|
|
1078
|
-
readonly scopes?: Record<string, readonly string[]>;
|
|
1079
|
-
readonly params?: string;
|
|
1080
|
-
}[],
|
|
1081
|
-
): Promise<void> {
|
|
1082
|
-
await this.#command('subscribeMany', {
|
|
1083
|
-
subscriptions: inputs.map((input) => ({
|
|
1084
|
-
id: input.id,
|
|
1085
|
-
table: input.table,
|
|
1086
|
-
scopes: input.scopes ?? {},
|
|
1087
|
-
...(input.params !== undefined ? { params: input.params } : {}),
|
|
1088
|
-
})),
|
|
1089
|
-
});
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
async unsubscribe(id: string): Promise<void> {
|
|
1093
|
-
await this.#command('unsubscribe', { id });
|
|
1094
|
-
}
|
|
1095
|
-
|
|
1096
|
-
async setWindow(base: WindowBase, units: readonly string[]): Promise<void> {
|
|
1097
|
-
await this.#command('setWindow', {
|
|
1098
|
-
base: base as unknown as Record<string, unknown>,
|
|
1099
|
-
units: units as string[],
|
|
1100
|
-
});
|
|
1101
|
-
}
|
|
1102
|
-
|
|
1103
|
-
async windowState(base: WindowBase): Promise<WindowState> {
|
|
1104
|
-
const result = (await this.#command('windowState', {
|
|
1105
|
-
base: base as unknown as Record<string, unknown>,
|
|
1106
|
-
})) as { units: string[]; pending: string[] };
|
|
1107
|
-
return { units: result.units, pending: result.pending };
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
async sync(): Promise<unknown> {
|
|
1111
|
-
return this.#command('sync', {});
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
/**
|
|
1115
|
-
* Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal
|
|
1116
|
-
* (`recommendedAction: resetClientId`). The next round carries the new id;
|
|
1117
|
-
* the replica and outbox stay in place.
|
|
1118
|
-
*/
|
|
1119
|
-
async resetClientId(): Promise<string> {
|
|
1120
|
-
const result = (await this.#command('resetClientId', {})) as {
|
|
1121
|
-
clientId: string;
|
|
1122
|
-
};
|
|
1123
|
-
return result.clientId;
|
|
1124
|
-
}
|
|
1125
|
-
|
|
1126
|
-
/**
|
|
1127
|
-
* SPEC §12 local authority state: `local` while rounds run against the
|
|
1128
|
-
* in-process authority, `attaching` during an attach, `attached` once rounds
|
|
1129
|
-
* run against `base_url`, and `null` when the plugin configured no
|
|
1130
|
-
* `local_authority_path`.
|
|
1131
|
-
*/
|
|
16
|
+
/** Local authority state, or null when the plugin configured no authority. */
|
|
1132
17
|
async localAuthorityState(): Promise<LocalAuthorityState | null> {
|
|
1133
|
-
const result = (await this
|
|
18
|
+
const result = (await this.command('localAuthorityState', {})) as {
|
|
1134
19
|
state: LocalAuthorityState | null;
|
|
1135
20
|
};
|
|
1136
21
|
return result.state;
|
|
1137
22
|
}
|
|
1138
23
|
|
|
1139
|
-
/**
|
|
1140
|
-
* Upload the local authority's live rows to the `base_url` server (§12.3).
|
|
1141
|
-
* Rejects with `sync.attach_rejected` (`details.reason`) when the server
|
|
1142
|
-
* refuses; call {@link abandonLocalAuthorityAttach} to roll back.
|
|
1143
|
-
*/
|
|
24
|
+
/** Upload the authority's live rows to the remote server (§12.3). */
|
|
1144
25
|
async attachLocalAuthority(): Promise<void> {
|
|
1145
|
-
await this
|
|
26
|
+
await this.command('attachLocalAuthority', {});
|
|
1146
27
|
}
|
|
1147
28
|
|
|
1148
|
-
/** Roll back
|
|
29
|
+
/** Roll back a stopped attach and resume the local authority. */
|
|
1149
30
|
async abandonLocalAuthorityAttach(): Promise<void> {
|
|
1150
|
-
await this
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
async syncUntilIdle(maxRounds?: number): Promise<unknown> {
|
|
1154
|
-
return this.#command('syncUntilIdle', {
|
|
1155
|
-
...(maxRounds !== undefined ? { maxRounds } : {}),
|
|
1156
|
-
});
|
|
31
|
+
await this.command('abandonLocalAuthorityAttach', {});
|
|
1157
32
|
}
|
|
1158
|
-
|
|
1159
|
-
async proveCurrentBase(
|
|
1160
|
-
outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>,
|
|
1161
|
-
maxRounds?: number,
|
|
1162
|
-
): Promise<CurrentBaseProof> {
|
|
1163
|
-
if (
|
|
1164
|
-
maxRounds !== undefined &&
|
|
1165
|
-
(!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff)
|
|
1166
|
-
)
|
|
1167
|
-
throw new TauriSyncError(
|
|
1168
|
-
'sync.invalid_request',
|
|
1169
|
-
'maxRounds must be a positive integer',
|
|
1170
|
-
);
|
|
1171
|
-
const proof = (await this.#command('proveCurrentBase', {
|
|
1172
|
-
outcome: {
|
|
1173
|
-
clientCommitId: outcome.clientCommitId,
|
|
1174
|
-
sequence: outcome.sequence,
|
|
1175
|
-
},
|
|
1176
|
-
...(maxRounds !== undefined ? { maxRounds } : {}),
|
|
1177
|
-
})) as CurrentBaseProof;
|
|
1178
|
-
return proof.proven
|
|
1179
|
-
? { proven: true, rows: decodeRetainedRows(proof.rows) }
|
|
1180
|
-
: proof;
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
async conflicts(): Promise<readonly ConflictRecord[]> {
|
|
1184
|
-
const result = (await this.#command('conflicts', {})) as {
|
|
1185
|
-
conflicts: ConflictRecord[];
|
|
1186
|
-
};
|
|
1187
|
-
return result.conflicts;
|
|
1188
|
-
}
|
|
1189
|
-
|
|
1190
|
-
async rejections(): Promise<readonly RejectionRecord[]> {
|
|
1191
|
-
const result = (await this.#command('rejections', {})) as {
|
|
1192
|
-
rejections: RejectionRecord[];
|
|
1193
|
-
};
|
|
1194
|
-
return result.rejections;
|
|
1195
|
-
}
|
|
1196
|
-
|
|
1197
|
-
async commitOutcome(
|
|
1198
|
-
clientCommitId: string,
|
|
1199
|
-
): Promise<CommitOutcome | undefined> {
|
|
1200
|
-
const result = (await this.#command('commitOutcome', {
|
|
1201
|
-
clientCommitId,
|
|
1202
|
-
})) as { outcome?: CommitOutcome };
|
|
1203
|
-
return result.outcome === undefined
|
|
1204
|
-
? undefined
|
|
1205
|
-
: decodeCommitOutcome(result.outcome);
|
|
1206
|
-
}
|
|
1207
|
-
|
|
1208
|
-
async commitOutcomes(
|
|
1209
|
-
query: CommitOutcomeQuery = {},
|
|
1210
|
-
): Promise<readonly CommitOutcome[]> {
|
|
1211
|
-
const result = (await this.#command('commitOutcomes', { query })) as {
|
|
1212
|
-
outcomes: CommitOutcome[];
|
|
1213
|
-
};
|
|
1214
|
-
return result.outcomes.map(decodeCommitOutcome);
|
|
1215
|
-
}
|
|
1216
|
-
|
|
1217
|
-
async resolveCommitOutcome(
|
|
1218
|
-
input: ResolveCommitOutcomeInput,
|
|
1219
|
-
): Promise<CommitOutcome> {
|
|
1220
|
-
const result = (await this.#command('resolveCommitOutcome', {
|
|
1221
|
-
input,
|
|
1222
|
-
})) as { outcome: CommitOutcome };
|
|
1223
|
-
return decodeCommitOutcome(result.outcome);
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
async pendingCommits(): Promise<unknown[]> {
|
|
1227
|
-
const result = (await this.#command('pendingCommitIds', {})) as {
|
|
1228
|
-
ids: string[];
|
|
1229
|
-
};
|
|
1230
|
-
return result.ids;
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
async presence(scopeKey: string): Promise<readonly PresencePeer[]> {
|
|
1234
|
-
const result = (await this.#command('presence', { scopeKey })) as {
|
|
1235
|
-
peers: PresencePeer[];
|
|
1236
|
-
};
|
|
1237
|
-
return result.peers;
|
|
1238
|
-
}
|
|
1239
|
-
|
|
1240
|
-
async setPresence(
|
|
1241
|
-
scopeKey: string,
|
|
1242
|
-
doc: Record<string, unknown> | null,
|
|
1243
|
-
): Promise<void> {
|
|
1244
|
-
await this.#command('setPresence', { scopeKey, doc });
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
async connectRealtime(): Promise<void> {
|
|
1248
|
-
await this.#command('connectRealtime', {});
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1251
|
-
async disconnectRealtime(): Promise<void> {
|
|
1252
|
-
await this.#command('disconnectRealtime', {});
|
|
1253
|
-
}
|
|
1254
|
-
|
|
1255
|
-
/** Shut down the native core, release its keyring, then detach listeners. */
|
|
1256
|
-
async close(): Promise<void> {
|
|
1257
|
-
if (this.#closed) return;
|
|
1258
|
-
const shutdown = this.#command('shutdown', {});
|
|
1259
|
-
this.#closed = true;
|
|
1260
|
-
try {
|
|
1261
|
-
await shutdown;
|
|
1262
|
-
} finally {
|
|
1263
|
-
this.#unlisten?.();
|
|
1264
|
-
this.#unlisten = undefined;
|
|
1265
|
-
this.#invalidationListeners.clear();
|
|
1266
|
-
this.#progress.clear();
|
|
1267
|
-
this.#changeListeners.clear();
|
|
1268
|
-
this.#diagnosticsListeners.clear();
|
|
1269
|
-
this.#presenceListeners.clear();
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
function decodeDiagnosticsSnapshot(
|
|
1275
|
-
value: unknown,
|
|
1276
|
-
kind: 'tauri',
|
|
1277
|
-
): ClientDiagnosticsSnapshot | undefined {
|
|
1278
|
-
if (value === null || typeof value !== 'object') return undefined;
|
|
1279
|
-
const snapshot = value as ClientDiagnosticsSnapshot;
|
|
1280
|
-
if (snapshot.version !== 1 || snapshot.host === undefined) return undefined;
|
|
1281
|
-
return withClientDiagnosticsHost(snapshot, {
|
|
1282
|
-
...snapshot.host,
|
|
1283
|
-
kind,
|
|
1284
|
-
role: 'single',
|
|
1285
|
-
});
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
|
-
/** The error a `{error}` reply surfaces (mirrors the web-client `ClientSyncError`). */
|
|
1289
|
-
export class TauriSyncError extends Error {
|
|
1290
|
-
readonly code: string;
|
|
1291
|
-
readonly details: Readonly<Record<string, unknown>> | undefined;
|
|
1292
|
-
readonly retryable: boolean;
|
|
1293
|
-
constructor(
|
|
1294
|
-
code: string,
|
|
1295
|
-
message: string,
|
|
1296
|
-
details?: Readonly<Record<string, unknown>>,
|
|
1297
|
-
retryable = false,
|
|
1298
|
-
) {
|
|
1299
|
-
super(message);
|
|
1300
|
-
this.name = 'TauriSyncError';
|
|
1301
|
-
this.code = code;
|
|
1302
|
-
this.details = details;
|
|
1303
|
-
this.retryable = retryable;
|
|
1304
|
-
}
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
function toStringSet(value: unknown): ReadonlySet<string> {
|
|
1308
|
-
if (Array.isArray(value)) {
|
|
1309
|
-
return new Set(value.filter((v): v is string => typeof v === 'string'));
|
|
1310
|
-
}
|
|
1311
|
-
return new Set<string>();
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
function decodeChangeBatch(value: unknown): ClientChangeBatch | undefined {
|
|
1315
|
-
if (value === null || typeof value !== 'object') return undefined;
|
|
1316
|
-
const raw = value as Record<string, unknown>;
|
|
1317
|
-
if (typeof raw.revision !== 'string') return undefined;
|
|
1318
|
-
const tables = Array.isArray(raw.tables)
|
|
1319
|
-
? raw.tables.flatMap((entry) => {
|
|
1320
|
-
if (entry === null || typeof entry !== 'object') return [];
|
|
1321
|
-
const item = entry as Record<string, unknown>;
|
|
1322
|
-
if (typeof item.table !== 'string') return [];
|
|
1323
|
-
return [
|
|
1324
|
-
{
|
|
1325
|
-
table: item.table,
|
|
1326
|
-
...(Array.isArray(item.scopeKeys)
|
|
1327
|
-
? { scopeKeys: toStringSet(item.scopeKeys) }
|
|
1328
|
-
: {}),
|
|
1329
|
-
},
|
|
1330
|
-
];
|
|
1331
|
-
})
|
|
1332
|
-
: [];
|
|
1333
|
-
const windows = Array.isArray(raw.windows)
|
|
1334
|
-
? raw.windows.flatMap((entry) => {
|
|
1335
|
-
if (entry === null || typeof entry !== 'object') return [];
|
|
1336
|
-
const item = entry as Record<string, unknown>;
|
|
1337
|
-
if (
|
|
1338
|
-
typeof item.baseKey !== 'string' ||
|
|
1339
|
-
typeof item.table !== 'string'
|
|
1340
|
-
) {
|
|
1341
|
-
return [];
|
|
1342
|
-
}
|
|
1343
|
-
return [
|
|
1344
|
-
{
|
|
1345
|
-
baseKey: item.baseKey,
|
|
1346
|
-
table: item.table,
|
|
1347
|
-
units: toStringSet(item.units),
|
|
1348
|
-
},
|
|
1349
|
-
];
|
|
1350
|
-
})
|
|
1351
|
-
: [];
|
|
1352
|
-
return {
|
|
1353
|
-
revision: BigInt(raw.revision),
|
|
1354
|
-
tables,
|
|
1355
|
-
windows,
|
|
1356
|
-
...(raw.status !== undefined
|
|
1357
|
-
? { status: raw.status as SyncStatusSnapshot }
|
|
1358
|
-
: {}),
|
|
1359
|
-
conflictsChanged: raw.conflictsChanged === true,
|
|
1360
|
-
rejectionsChanged: raw.rejectionsChanged === true,
|
|
1361
|
-
outcomesChanged: raw.outcomesChanged === true,
|
|
1362
|
-
};
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
|
-
function invalidationFromChange(
|
|
1366
|
-
batch: ClientChangeBatch,
|
|
1367
|
-
): InvalidationEvent | undefined {
|
|
1368
|
-
if (batch.tables.length === 0 && batch.windows.length === 0) return undefined;
|
|
1369
|
-
const tables = new Set<string>();
|
|
1370
|
-
const scopeKeys = new Set<string>();
|
|
1371
|
-
for (const table of batch.tables) {
|
|
1372
|
-
tables.add(table.table);
|
|
1373
|
-
for (const key of table.scopeKeys ?? []) scopeKeys.add(key);
|
|
1374
|
-
}
|
|
1375
|
-
for (const window of batch.windows) tables.add(window.table);
|
|
1376
|
-
return { tables, scopeKeys };
|
|
1377
33
|
}
|
|
1378
34
|
|
|
1379
|
-
/** Encode one mutation for the command JSON (bytes inside `values` handled by
|
|
1380
|
-
* the native side; the driver form is already JSON-able). */
|
|
1381
|
-
function encodeMutation(mutation: MutationInput): unknown {
|
|
1382
|
-
if (mutation.op === 'delete') return mutation;
|
|
1383
|
-
const values: Record<string, unknown> = {};
|
|
1384
|
-
for (const [key, value] of Object.entries(mutation.values)) {
|
|
1385
|
-
values[key] = encodeJsonValue(value);
|
|
1386
|
-
}
|
|
1387
|
-
return { ...mutation, values };
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
/**
|
|
1391
|
-
* Construct the bridge and issue the native `create` (opening/attaching the
|
|
1392
|
-
* file DB on the Rust side per the plugin config). Returns a ready
|
|
1393
|
-
* `TauriSyncClient` that satisfies `SyncClientLike` — pass it straight to the
|
|
1394
|
-
* React `<SyncProvider client={…}>`.
|
|
1395
|
-
*/
|
|
1396
35
|
export function createTauriSyncClient(
|
|
1397
36
|
config: TauriSyncClientConfig,
|
|
1398
37
|
): Promise<TauriSyncClient>;
|
|
@@ -1403,82 +42,10 @@ export function createTauriSyncClient<Client extends TauriSyncClient>(
|
|
|
1403
42
|
...args: ConstructorParameters<typeof TauriSyncClient>
|
|
1404
43
|
) => Client,
|
|
1405
44
|
): Promise<Client>;
|
|
1406
|
-
export
|
|
45
|
+
export function createTauriSyncClient(
|
|
1407
46
|
config: TauriSyncClientConfig,
|
|
1408
47
|
createClient = (...args: ConstructorParameters<typeof TauriSyncClient>) =>
|
|
1409
48
|
new TauriSyncClient(...args),
|
|
1410
49
|
): Promise<TauriSyncClient> {
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
// Wire the event stream BEFORE create, so no early change batch is missed.
|
|
1414
|
-
const clientRef: { client: TauriSyncClient | undefined } = {
|
|
1415
|
-
client: undefined,
|
|
1416
|
-
};
|
|
1417
|
-
const unlisten = await tauri.listen<SyncularEvent>(
|
|
1418
|
-
SYNCULAR_EVENT,
|
|
1419
|
-
(event) => {
|
|
1420
|
-
clientRef.client?.__dispatchEvent(event.payload);
|
|
1421
|
-
},
|
|
1422
|
-
);
|
|
1423
|
-
|
|
1424
|
-
if (config.securityPreflight === true && config.encryption !== undefined) {
|
|
1425
|
-
unlisten();
|
|
1426
|
-
throw new TauriSyncError(
|
|
1427
|
-
'sync.invalid_request',
|
|
1428
|
-
'securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight',
|
|
1429
|
-
);
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
const client = createClient(
|
|
1433
|
-
tauri,
|
|
1434
|
-
unlisten,
|
|
1435
|
-
config.securityPreflight === true ? 'preflight' : 'active',
|
|
1436
|
-
);
|
|
1437
|
-
clientRef.client = client;
|
|
1438
|
-
|
|
1439
|
-
// The native side owns every path (plugin config); the JS side names a
|
|
1440
|
-
// database and supplies the schema, clientId, and limits.
|
|
1441
|
-
const reply = await tauri.invoke<CommandReply>(`${PLUGIN}syncular_command`, {
|
|
1442
|
-
command: {
|
|
1443
|
-
method: 'create',
|
|
1444
|
-
params: {
|
|
1445
|
-
...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
|
|
1446
|
-
...(config.database !== undefined ? { database: config.database } : {}),
|
|
1447
|
-
schema: config.schema,
|
|
1448
|
-
...(config.limits !== undefined ? { limits: config.limits } : {}),
|
|
1449
|
-
...(config.retainFailedCommits !== undefined
|
|
1450
|
-
? { retainFailedCommits: config.retainFailedCommits }
|
|
1451
|
-
: {}),
|
|
1452
|
-
...(config.realtimePolicy !== undefined
|
|
1453
|
-
? { realtimePolicy: config.realtimePolicy }
|
|
1454
|
-
: {}),
|
|
1455
|
-
...(config.encryption !== undefined
|
|
1456
|
-
? { encryption: encodeEncryption(config.encryption) }
|
|
1457
|
-
: {}),
|
|
1458
|
-
...(config.transportEnabled !== undefined
|
|
1459
|
-
? { transportEnabled: config.transportEnabled }
|
|
1460
|
-
: {}),
|
|
1461
|
-
...(config.authorityReads !== undefined
|
|
1462
|
-
? { authorityReads: config.authorityReads.declarations }
|
|
1463
|
-
: {}),
|
|
1464
|
-
...(config.securityPreflight !== undefined
|
|
1465
|
-
? { securityPreflight: config.securityPreflight }
|
|
1466
|
-
: {}),
|
|
1467
|
-
...(config.previousVersionContext !== undefined
|
|
1468
|
-
? { previousVersionContext: config.previousVersionContext }
|
|
1469
|
-
: {}),
|
|
1470
|
-
},
|
|
1471
|
-
},
|
|
1472
|
-
});
|
|
1473
|
-
if (reply.error !== undefined) {
|
|
1474
|
-
unlisten();
|
|
1475
|
-
throw new TauriSyncError(
|
|
1476
|
-
reply.error.code,
|
|
1477
|
-
reply.error.message,
|
|
1478
|
-
reply.error.details ?? undefined,
|
|
1479
|
-
reply.error.retryable ?? false,
|
|
1480
|
-
);
|
|
1481
|
-
}
|
|
1482
|
-
|
|
1483
|
-
return client;
|
|
50
|
+
return createRemoteTauriSyncClient(config, createClient);
|
|
1484
51
|
}
|