@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/dist/index.js
CHANGED
|
@@ -1,971 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
function isBytesEnvelope(value) {
|
|
10
|
-
if (typeof value !== 'object' || value === null)
|
|
11
|
-
return false;
|
|
12
|
-
const record = value;
|
|
13
|
-
return (Object.keys(record).length === 1 &&
|
|
14
|
-
typeof record.$bytes === 'string' &&
|
|
15
|
-
/^(?:[0-9a-fA-F]{2})*$/.test(record.$bytes));
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* §7.1: a host reply that carries an envelope-shaped object with a malformed
|
|
19
|
-
* body is refused, never padded into different bytes. Objects without a
|
|
20
|
-
* `$bytes` key keep the defensive JSON text round-trip below.
|
|
21
|
-
*/
|
|
22
|
-
function assertBytesEnvelope(value) {
|
|
23
|
-
if (typeof value !== 'object' || value === null || !('$bytes' in value))
|
|
24
|
-
return;
|
|
25
|
-
if (!isBytesEnvelope(value))
|
|
26
|
-
throw new TauriSyncError('sync.invalid_request', 'a $bytes envelope requires exactly one $bytes key holding an even-length hexadecimal string');
|
|
27
|
-
}
|
|
28
|
-
function isBigIntEnvelope(value) {
|
|
29
|
-
return (typeof value === 'object' &&
|
|
30
|
-
value !== null &&
|
|
31
|
-
typeof value.$bigint === 'string');
|
|
32
|
-
}
|
|
33
|
-
function bytesToHex(bytes) {
|
|
34
|
-
let out = '';
|
|
35
|
-
for (const b of bytes) {
|
|
36
|
-
out += b.toString(16).padStart(2, '0');
|
|
37
|
-
}
|
|
38
|
-
return out;
|
|
39
|
-
}
|
|
40
|
-
function hexToBytes(hex) {
|
|
41
|
-
if (!/^(?:[0-9a-fA-F]{2})*$/.test(hex))
|
|
42
|
-
throw new TauriSyncError('sync.invalid_request', 'a $bytes envelope requires an even-length hexadecimal string');
|
|
43
|
-
const out = new Uint8Array(hex.length / 2);
|
|
44
|
-
for (let i = 0; i < out.length; i++) {
|
|
45
|
-
out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
46
|
-
}
|
|
47
|
-
return out;
|
|
48
|
-
}
|
|
49
|
-
/** Encode an SQL param for the command JSON (bytes → `{$bytes: hex}`). */
|
|
50
|
-
function encodeParam(value) {
|
|
51
|
-
if (value instanceof Uint8Array)
|
|
52
|
-
return { $bytes: bytesToHex(value) };
|
|
53
|
-
if (typeof value === 'bigint')
|
|
54
|
-
return { $bigint: value.toString() };
|
|
55
|
-
return value;
|
|
56
|
-
}
|
|
57
|
-
function encodeJsonValue(value) {
|
|
58
|
-
if (value instanceof Uint8Array)
|
|
59
|
-
return { $bytes: bytesToHex(value) };
|
|
60
|
-
if (typeof value === 'bigint')
|
|
61
|
-
return { $bigint: value.toString() };
|
|
62
|
-
if (Array.isArray(value))
|
|
63
|
-
return value.map(encodeJsonValue);
|
|
64
|
-
if (value !== null && typeof value === 'object') {
|
|
65
|
-
const encoded = {};
|
|
66
|
-
for (const [key, member] of Object.entries(value)) {
|
|
67
|
-
encoded[key] = encodeJsonValue(member);
|
|
68
|
-
}
|
|
69
|
-
return encoded;
|
|
70
|
-
}
|
|
71
|
-
return value;
|
|
72
|
-
}
|
|
73
|
-
function encodeEncryption(config) {
|
|
74
|
-
return {
|
|
75
|
-
keys: Object.fromEntries(Object.entries(config.keys).map(([keyId, key]) => [
|
|
76
|
-
keyId,
|
|
77
|
-
{ $bytes: bytesToHex(key) },
|
|
78
|
-
])),
|
|
79
|
-
...(config.keyIdColumns !== undefined
|
|
80
|
-
? { keyIdColumns: config.keyIdColumns }
|
|
81
|
-
: {}),
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
/** Decode one query-result cell back to an `SqlValue` (`{$bytes}` → bytes). */
|
|
85
|
-
function decodeCell(value) {
|
|
86
|
-
assertBytesEnvelope(value);
|
|
87
|
-
if (isBytesEnvelope(value))
|
|
88
|
-
return hexToBytes(value.$bytes);
|
|
89
|
-
if (isBigIntEnvelope(value))
|
|
90
|
-
return BigInt(value.$bigint);
|
|
91
|
-
if (value === null ||
|
|
92
|
-
typeof value === 'string' ||
|
|
93
|
-
typeof value === 'number' ||
|
|
94
|
-
typeof value === 'boolean') {
|
|
95
|
-
return value;
|
|
96
|
-
}
|
|
97
|
-
// Objects/arrays that are not the bytes envelope round-trip as their JSON
|
|
98
|
-
// string (SQLite json columns arrive as text already; this is defensive).
|
|
99
|
-
return JSON.stringify(value);
|
|
100
|
-
}
|
|
101
|
-
/** Decode one native outcome row image. Only the `{$bytes}` envelope is
|
|
102
|
-
* honored; operation `values` stay `JsonRowValue` and are not passed here. */
|
|
103
|
-
function decodeOutcomeRow(row) {
|
|
104
|
-
const out = {};
|
|
105
|
-
for (const [key, value] of Object.entries(row)) {
|
|
106
|
-
// Reserved `_sync_*` columns stay engine-internal, matching `decodeRow`.
|
|
107
|
-
if (key.startsWith('_sync_'))
|
|
108
|
-
continue;
|
|
109
|
-
assertBytesEnvelope(value);
|
|
110
|
-
if (value === null ||
|
|
111
|
-
typeof value === 'string' ||
|
|
112
|
-
typeof value === 'number' ||
|
|
113
|
-
typeof value === 'boolean') {
|
|
114
|
-
out[key] = value;
|
|
115
|
-
}
|
|
116
|
-
else if (isBytesEnvelope(value)) {
|
|
117
|
-
out[key] = hexToBytes(value.$bytes);
|
|
118
|
-
}
|
|
119
|
-
else {
|
|
120
|
-
out[key] = JSON.stringify(value);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
return out;
|
|
124
|
-
}
|
|
125
|
-
function decodeRetainedRows(rows) {
|
|
126
|
-
return rows.map((row) => ({
|
|
127
|
-
...row,
|
|
128
|
-
localRow: row.localRow === null ? null : decodeOutcomeRow(row.localRow),
|
|
129
|
-
serverRow: row.serverRow === null ? null : decodeOutcomeRow(row.serverRow),
|
|
130
|
-
...(row.uniqueConflicts !== undefined
|
|
131
|
-
? {
|
|
132
|
-
uniqueConflicts: row.uniqueConflicts.map((conflict) => ({
|
|
133
|
-
...conflict,
|
|
134
|
-
serverRow: decodeOutcomeRow(conflict.serverRow),
|
|
135
|
-
})),
|
|
136
|
-
}
|
|
137
|
-
: {}),
|
|
138
|
-
}));
|
|
139
|
-
}
|
|
140
|
-
/** Decode the row images a native `CommitOutcome` carries: conflict server
|
|
141
|
-
* rows and retained-row images. */
|
|
142
|
-
function decodeCommitOutcome(outcome) {
|
|
143
|
-
return {
|
|
144
|
-
...outcome,
|
|
145
|
-
results: outcome.results.map((result) => result.status === 'conflict'
|
|
146
|
-
? {
|
|
147
|
-
...result,
|
|
148
|
-
conflict: {
|
|
149
|
-
...result.conflict,
|
|
150
|
-
serverRow: decodeOutcomeRow(result.conflict.serverRow),
|
|
151
|
-
},
|
|
152
|
-
}
|
|
153
|
-
: result),
|
|
154
|
-
...(outcome.retainedRows !== undefined
|
|
155
|
-
? {
|
|
156
|
-
retainedRows: decodeRetainedRows(outcome.retainedRows),
|
|
157
|
-
}
|
|
158
|
-
: {}),
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
/** @internal Shared native row codec. */
|
|
162
|
-
export function decodeRow(row) {
|
|
163
|
-
const out = {};
|
|
164
|
-
for (const [key, value] of Object.entries(row)) {
|
|
165
|
-
// Reserved `_sync_*` columns stay engine-internal (parity with the
|
|
166
|
-
// web client's `query()`), so a `SELECT *` row round-trips straight
|
|
167
|
-
// into `mutate()` values. Alias (`_sync_version AS v`) to read one.
|
|
168
|
-
if (key.startsWith('_sync_'))
|
|
169
|
-
continue;
|
|
170
|
-
out[key] = decodeCell(value);
|
|
171
|
-
}
|
|
172
|
-
return out;
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Decode the JSON cell envelopes in an RFC 0005 snapshot reply's rows before
|
|
176
|
-
* the strict bridge decoder sees them; a malformed reply is passed through
|
|
177
|
-
* untouched so `decodePreviousVersionSnapshot` rejects it.
|
|
178
|
-
*/
|
|
179
|
-
function decodeSnapshotRows(value) {
|
|
180
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
181
|
-
return value;
|
|
182
|
-
}
|
|
183
|
-
const source = value;
|
|
184
|
-
if (!Array.isArray(source.rows))
|
|
185
|
-
return value;
|
|
186
|
-
return {
|
|
187
|
-
...source,
|
|
188
|
-
rows: source.rows.map((row) => row !== null && typeof row === 'object' && !Array.isArray(row)
|
|
189
|
-
? decodeRow(row)
|
|
190
|
-
: row),
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
/** Resolve the Tauri primitives from the ambient environment when not injected. */
|
|
194
|
-
async function resolveTauri(injected) {
|
|
195
|
-
if (injected !== undefined)
|
|
196
|
-
return injected;
|
|
197
|
-
// Prefer the ambient global (present when `withGlobalTauri` is enabled).
|
|
198
|
-
const ambient = globalThis.__TAURI__;
|
|
199
|
-
if (ambient?.core?.invoke && ambient.event?.listen) {
|
|
200
|
-
return {
|
|
201
|
-
invoke: ambient.core.invoke.bind(ambient.core),
|
|
202
|
-
listen: ambient.event.listen.bind(ambient.event),
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
// Fall back to the ESM package (the common path). These must remain literal,
|
|
206
|
-
// bundler-visible specifiers: hiding a bare package import behind
|
|
207
|
-
// `@vite-ignore` makes WebKit resolve it as a URL at runtime instead of
|
|
208
|
-
// letting Vite/Bun include the Tauri API in the webview bundle.
|
|
209
|
-
const [core, event] = await Promise.all([
|
|
210
|
-
import('@tauri-apps/api/core'),
|
|
211
|
-
import('@tauri-apps/api/event'),
|
|
212
|
-
]);
|
|
213
|
-
return { invoke: core.invoke, listen: event.listen };
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* The webview-side proxy implementing `SyncClientLike` over the plugin. Every
|
|
217
|
-
* snapshot method returns a promise from an IPC round trip. React hooks accept
|
|
218
|
-
* the canonical snapshot interface directly.
|
|
219
|
-
*/
|
|
220
|
-
export class TauriSyncClient {
|
|
221
|
-
#tauri;
|
|
222
|
-
#invalidationListeners = new Set();
|
|
223
|
-
#changeListeners = new Set();
|
|
224
|
-
#progress = new ProgressEmitter();
|
|
225
|
-
#diagnosticsListeners = new Set();
|
|
226
|
-
#presenceListeners = new Set();
|
|
227
|
-
#unlisten;
|
|
228
|
-
#closed = false;
|
|
229
|
-
#securityLifecycle;
|
|
230
|
-
#preflightBarrier;
|
|
231
|
-
#diagnosticsEnabled = false;
|
|
232
|
-
/** @internal — use {@link createTauriSyncClient}. */
|
|
233
|
-
constructor(tauri, unlisten, securityLifecycle = 'active') {
|
|
234
|
-
this.#tauri = tauri;
|
|
235
|
-
this.#unlisten = unlisten;
|
|
236
|
-
this.#securityLifecycle = securityLifecycle;
|
|
237
|
-
}
|
|
238
|
-
/** Dispatch a `syncular_command` and unwrap `{result}` / throw on `{error}`. */
|
|
239
|
-
async #command(method, params) {
|
|
240
|
-
this.#requireOpen();
|
|
241
|
-
if (this.#securityLifecycle === 'preflight' &&
|
|
242
|
-
![
|
|
243
|
-
'authoritySnapshot',
|
|
244
|
-
'securityLifecycle',
|
|
245
|
-
'beginSecurityPreflight',
|
|
246
|
-
'activateSecurity',
|
|
247
|
-
'setTransportEnabled',
|
|
248
|
-
'purgeLocalData',
|
|
249
|
-
'previousVersionDiscard',
|
|
250
|
-
'localRevision',
|
|
251
|
-
'statusSnapshot',
|
|
252
|
-
'localAuthorityState',
|
|
253
|
-
'shutdown',
|
|
254
|
-
].includes(method)) {
|
|
255
|
-
this.#throwSecurityPreflight();
|
|
256
|
-
}
|
|
257
|
-
const reply = await this.#tauri.invoke(`${PLUGIN}syncular_command`, { command: { method, params } });
|
|
258
|
-
if (reply.error !== undefined) {
|
|
259
|
-
throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
|
|
260
|
-
}
|
|
261
|
-
return reply.result;
|
|
262
|
-
}
|
|
263
|
-
#throwSecurityPreflight() {
|
|
264
|
-
throw new TauriSyncError(SECURITY_PREFLIGHT_REQUIRED_CODE, 'the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data');
|
|
265
|
-
}
|
|
266
|
-
#requireOpen() {
|
|
267
|
-
if (this.#closed) {
|
|
268
|
-
throw new TauriSyncError('client.closed', 'the Tauri sync client is closed');
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
/** @internal Shared command gate for explicit bridge extensions. */
|
|
272
|
-
command(method, params) {
|
|
273
|
-
return this.#command(method, params);
|
|
274
|
-
}
|
|
275
|
-
/** @internal Recheck local close after an extension's asynchronous reply. */
|
|
276
|
-
requireOpen() {
|
|
277
|
-
this.#requireOpen();
|
|
278
|
-
}
|
|
279
|
-
#requireActive() {
|
|
280
|
-
this.#requireOpen();
|
|
281
|
-
if (this.#securityLifecycle === 'preflight')
|
|
282
|
-
this.#throwSecurityPreflight();
|
|
283
|
-
}
|
|
284
|
-
/** @internal — fan an incoming plugin event out to the local listeners. */
|
|
285
|
-
__dispatchEvent(event) {
|
|
286
|
-
switch (event.type) {
|
|
287
|
-
case 'progress': {
|
|
288
|
-
this.#progress.emit(event.progress);
|
|
289
|
-
break;
|
|
290
|
-
}
|
|
291
|
-
case 'change': {
|
|
292
|
-
const batch = decodeChangeBatch(event.batch);
|
|
293
|
-
if (batch === undefined)
|
|
294
|
-
break;
|
|
295
|
-
for (const listener of this.#changeListeners) {
|
|
296
|
-
try {
|
|
297
|
-
listener(batch);
|
|
298
|
-
}
|
|
299
|
-
catch {
|
|
300
|
-
/* a UI listener must never break event dispatch */
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
const payload = invalidationFromChange(batch);
|
|
304
|
-
if (payload === undefined)
|
|
305
|
-
break;
|
|
306
|
-
for (const listener of this.#invalidationListeners) {
|
|
307
|
-
try {
|
|
308
|
-
listener(payload);
|
|
309
|
-
}
|
|
310
|
-
catch {
|
|
311
|
-
/* a UI listener must never break event dispatch */
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
break;
|
|
315
|
-
}
|
|
316
|
-
case 'presence': {
|
|
317
|
-
const scopeKey = typeof event.scopeKey === 'string' ? event.scopeKey : '';
|
|
318
|
-
for (const listener of this.#presenceListeners) {
|
|
319
|
-
try {
|
|
320
|
-
listener(scopeKey);
|
|
321
|
-
}
|
|
322
|
-
catch {
|
|
323
|
-
/* never break dispatch */
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
break;
|
|
327
|
-
}
|
|
328
|
-
case 'diagnostics': {
|
|
329
|
-
const snapshot = decodeDiagnosticsSnapshot(event.snapshot, 'tauri');
|
|
330
|
-
if (snapshot === undefined)
|
|
331
|
-
break;
|
|
332
|
-
for (const listener of this.#diagnosticsListeners) {
|
|
333
|
-
try {
|
|
334
|
-
listener(snapshot);
|
|
335
|
-
}
|
|
336
|
-
catch {
|
|
337
|
-
/* a diagnostics observer must never break event dispatch */
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
break;
|
|
341
|
-
}
|
|
342
|
-
default:
|
|
343
|
-
// Unknown extension events are deliberately ignored. All durable
|
|
344
|
-
// observable state arrives in the revisioned `change` batch.
|
|
345
|
-
break;
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
// -- SyncClientLike --------------------------------------------------------
|
|
349
|
-
async securityLifecycle() {
|
|
350
|
-
this.#requireOpen();
|
|
351
|
-
return Promise.resolve(this.#securityLifecycle);
|
|
352
|
-
}
|
|
353
|
-
beginSecurityPreflight() {
|
|
354
|
-
if (this.#closed) {
|
|
355
|
-
return Promise.reject(new TauriSyncError('client.closed', 'the Tauri sync client is closed'));
|
|
356
|
-
}
|
|
357
|
-
if (this.#preflightBarrier !== undefined)
|
|
358
|
-
return this.#preflightBarrier;
|
|
359
|
-
// Flip synchronously so a same-webview query cannot race the IPC barrier.
|
|
360
|
-
this.#securityLifecycle = 'preflight';
|
|
361
|
-
const barrier = this.#command('beginSecurityPreflight', {}).then(() => { });
|
|
362
|
-
this.#preflightBarrier = barrier;
|
|
363
|
-
void barrier.then(() => {
|
|
364
|
-
if (this.#preflightBarrier === barrier)
|
|
365
|
-
this.#preflightBarrier = undefined;
|
|
366
|
-
}, () => {
|
|
367
|
-
if (this.#preflightBarrier === barrier)
|
|
368
|
-
this.#preflightBarrier = undefined;
|
|
369
|
-
});
|
|
370
|
-
return barrier;
|
|
371
|
-
}
|
|
372
|
-
/**
|
|
373
|
-
* Complete the security preflight. `headers` optionally carries a fresh
|
|
374
|
-
* FULL transport header set that the native host applies atomically with
|
|
375
|
-
* the activation, before the startup sync it enqueues — so a preflight
|
|
376
|
-
* that outlives the boot token starts its first round with valid
|
|
377
|
-
* credentials (the direct `setHeaders` path stays refused while gated).
|
|
378
|
-
*/
|
|
379
|
-
async activateSecurity(options = {}) {
|
|
380
|
-
this.#requireOpen();
|
|
381
|
-
if (this.#securityLifecycle === 'active') {
|
|
382
|
-
throw new TauriSyncError('sync.invalid_request', 'activateSecurity requires the client to be in security preflight');
|
|
383
|
-
}
|
|
384
|
-
await this.#preflightBarrier;
|
|
385
|
-
await this.#command('activateSecurity', {
|
|
386
|
-
...(options.encryption !== undefined
|
|
387
|
-
? { encryption: encodeEncryption(options.encryption) }
|
|
388
|
-
: {}),
|
|
389
|
-
...(options.headers !== undefined ? { headers: options.headers } : {}),
|
|
390
|
-
});
|
|
391
|
-
this.#securityLifecycle = 'active';
|
|
392
|
-
}
|
|
393
|
-
onInvalidate(listener) {
|
|
394
|
-
this.#requireOpen();
|
|
395
|
-
this.#invalidationListeners.add(listener);
|
|
396
|
-
return () => this.#invalidationListeners.delete(listener);
|
|
397
|
-
}
|
|
398
|
-
onProgress(listener) {
|
|
399
|
-
this.#requireOpen();
|
|
400
|
-
return this.#progress.on(listener);
|
|
401
|
-
}
|
|
402
|
-
progressSnapshot() {
|
|
403
|
-
this.#requireOpen();
|
|
404
|
-
return this.#progress.snapshot();
|
|
405
|
-
}
|
|
406
|
-
onChange(listener) {
|
|
407
|
-
this.#requireOpen();
|
|
408
|
-
this.#changeListeners.add(listener);
|
|
409
|
-
return () => this.#changeListeners.delete(listener);
|
|
410
|
-
}
|
|
411
|
-
onDiagnostics(listener) {
|
|
412
|
-
this.#requireOpen();
|
|
413
|
-
this.#diagnosticsListeners.add(listener);
|
|
414
|
-
this.#enableDiagnosticsPush();
|
|
415
|
-
return () => this.#diagnosticsListeners.delete(listener);
|
|
416
|
-
}
|
|
417
|
-
/**
|
|
418
|
-
* Host-local push registration: the native core emits pushed diagnostics
|
|
419
|
-
* snapshots only once a consumer is known (a `diagnosticsSnapshot` pull, or
|
|
420
|
-
* this explicit `enableDiagnostics` signal). Fired once, on the first
|
|
421
|
-
* registered listener, fire-and-forget. The invoke deliberately bypasses
|
|
422
|
-
* the bridge's preflight gate — the command is a pure observability
|
|
423
|
-
* registration handled before dispatch, and the native side stays silent
|
|
424
|
-
* until activation anyway. Errors are tolerated: an older native core
|
|
425
|
-
* rejects the unknown command, and the mount-time snapshot pull path keeps
|
|
426
|
-
* `useDiagnostics` working there.
|
|
427
|
-
*/
|
|
428
|
-
#enableDiagnosticsPush() {
|
|
429
|
-
if (this.#diagnosticsEnabled || this.#closed)
|
|
430
|
-
return;
|
|
431
|
-
this.#diagnosticsEnabled = true;
|
|
432
|
-
void this.#tauri
|
|
433
|
-
.invoke(`${PLUGIN}syncular_command`, {
|
|
434
|
-
command: { method: 'enableDiagnostics', params: {} },
|
|
435
|
-
})
|
|
436
|
-
.catch(() => {
|
|
437
|
-
/* fire-and-forget; an error reply is equally ignored above */
|
|
438
|
-
});
|
|
439
|
-
}
|
|
440
|
-
onPresence(listener) {
|
|
441
|
-
this.#requireOpen();
|
|
442
|
-
this.#presenceListeners.add(listener);
|
|
443
|
-
return () => this.#presenceListeners.delete(listener);
|
|
444
|
-
}
|
|
445
|
-
async query(sql, params) {
|
|
446
|
-
this.#requireActive();
|
|
447
|
-
const reply = await this.#tauri.invoke(`${PLUGIN}syncular_query`, { sql, params: (params ?? []).map(encodeParam) });
|
|
448
|
-
if (reply.error !== undefined) {
|
|
449
|
-
throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
|
|
450
|
-
}
|
|
451
|
-
const rows = reply.result.rows ?? [];
|
|
452
|
-
return rows.map((r) => decodeRow(r));
|
|
453
|
-
}
|
|
454
|
-
async querySnapshot(spec) {
|
|
455
|
-
this.#requireActive();
|
|
456
|
-
const reply = await this.#tauri.invoke(`${PLUGIN}syncular_query_snapshot`, {
|
|
457
|
-
sql: spec.sql,
|
|
458
|
-
params: (spec.params ?? []).map(encodeParam),
|
|
459
|
-
coverage: spec.coverage ?? [],
|
|
460
|
-
...(spec.owner !== undefined ? { owner: spec.owner } : {}),
|
|
461
|
-
});
|
|
462
|
-
if (reply.error !== undefined) {
|
|
463
|
-
throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
|
|
464
|
-
}
|
|
465
|
-
const result = reply.result;
|
|
466
|
-
return {
|
|
467
|
-
revision: BigInt(result.revision),
|
|
468
|
-
rows: result.rows.map(decodeRow),
|
|
469
|
-
coverage: result.coverage,
|
|
470
|
-
};
|
|
471
|
-
}
|
|
472
|
-
async localRevision() {
|
|
473
|
-
const result = (await this.#command('localRevision', {}));
|
|
474
|
-
return BigInt(result.revision);
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* §7.5: one atomic read over the file-backed sidecar. Every statement and
|
|
478
|
-
* every catch-up/delivery read shares one revision (a `bigint`, matching
|
|
479
|
-
* `querySnapshot`) and one read transaction; every query row is decoded.
|
|
480
|
-
*/
|
|
481
|
-
async snapshotRead(request) {
|
|
482
|
-
this.#requireActive();
|
|
483
|
-
const reply = await this.#tauri.invoke(`${PLUGIN}syncular_snapshot_read`, {
|
|
484
|
-
statements: request.statements.map((statement) => ({
|
|
485
|
-
sql: statement.sql,
|
|
486
|
-
params: (statement.params ?? []).map(encodeParam),
|
|
487
|
-
})),
|
|
488
|
-
coverage: request.coverage ?? [],
|
|
489
|
-
subscriptions: request.subscriptions ?? [],
|
|
490
|
-
commitIds: request.commitIds ?? [],
|
|
491
|
-
...(request.owner !== undefined ? { owner: request.owner } : {}),
|
|
492
|
-
});
|
|
493
|
-
if (reply.error !== undefined) {
|
|
494
|
-
throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
|
|
495
|
-
}
|
|
496
|
-
const result = reply.result;
|
|
497
|
-
return {
|
|
498
|
-
revision: BigInt(result.revision),
|
|
499
|
-
queries: result.queries.map((rows) => rows.map(decodeRow)),
|
|
500
|
-
coverage: result.coverage,
|
|
501
|
-
subscriptions: result.subscriptions,
|
|
502
|
-
deliveries: result.deliveries.map((delivery) => delivery.status === 'known'
|
|
503
|
-
? { ...delivery, outcome: decodeCommitOutcome(delivery.outcome) }
|
|
504
|
-
: delivery),
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
async statusSnapshot() {
|
|
508
|
-
return (await this.#command('statusSnapshot', {}));
|
|
509
|
-
}
|
|
510
|
-
async diagnosticsSnapshot(request = {}) {
|
|
511
|
-
const snapshot = (await this.#command('diagnosticsSnapshot', {
|
|
512
|
-
expectedSubscriptions: request.expectedSubscriptions ?? [],
|
|
513
|
-
}));
|
|
514
|
-
return withClientDiagnosticsHost(snapshot, {
|
|
515
|
-
...snapshot.host,
|
|
516
|
-
kind: 'tauri',
|
|
517
|
-
role: 'single',
|
|
518
|
-
});
|
|
519
|
-
}
|
|
520
|
-
async mutate(mutations) {
|
|
521
|
-
const result = (await this.#command('mutate', {
|
|
522
|
-
mutations: mutations.map(encodeMutation),
|
|
523
|
-
}));
|
|
524
|
-
return result.clientCommitId;
|
|
525
|
-
}
|
|
526
|
-
async patch(table, rowId, partial, options) {
|
|
527
|
-
const result = (await this.#command('patch', {
|
|
528
|
-
table,
|
|
529
|
-
rowId,
|
|
530
|
-
partial: encodeJsonValue(partial),
|
|
531
|
-
...(options?.baseVersion !== undefined
|
|
532
|
-
? { baseVersion: options.baseVersion }
|
|
533
|
-
: {}),
|
|
534
|
-
}));
|
|
535
|
-
return result.clientCommitId;
|
|
536
|
-
}
|
|
537
|
-
async purgeLocalData(input) {
|
|
538
|
-
return (await this.#command('purgeLocalData', {
|
|
539
|
-
input,
|
|
540
|
-
}));
|
|
541
|
-
}
|
|
542
|
-
async rebootstrapLocalData(input) {
|
|
543
|
-
return decodeLocalDataRebootstrapResult(await this.#command('rebootstrapLocalData', { input }));
|
|
544
|
-
}
|
|
545
|
-
async previousVersionSnapshot(spec) {
|
|
546
|
-
return decodePreviousVersionSnapshot(decodeSnapshotRows(await this.#command('previousVersionSnapshot', { spec })));
|
|
547
|
-
}
|
|
548
|
-
async previousVersionAudit() {
|
|
549
|
-
return decodePreviousVersionAuditResult(await this.#command('previousVersionAudit', {}));
|
|
550
|
-
}
|
|
551
|
-
async previousVersionDiscard() {
|
|
552
|
-
return decodePreviousVersionDiscardResult(await this.#command('previousVersionDiscard', {}));
|
|
553
|
-
}
|
|
554
|
-
/** Suspend new network work while retaining local access and queued commits. */
|
|
555
|
-
async setTransportEnabled(enabled) {
|
|
556
|
-
await this.#command('setTransportEnabled', { enabled });
|
|
557
|
-
}
|
|
558
|
-
/** Browser offline-control parity; local reads and commits remain available. */
|
|
559
|
-
async setOffline(offline) {
|
|
560
|
-
await this.setTransportEnabled(!offline);
|
|
561
|
-
}
|
|
562
|
-
/**
|
|
563
|
-
* Replace the native transport's request headers at runtime — the auth
|
|
564
|
-
* rotation path. Pass the FULL header set (it replaces,
|
|
565
|
-
* it does not merge). HTTP requests use the new set from the next call;
|
|
566
|
-
* the realtime socket applies it on its next (re)connect.
|
|
567
|
-
*/
|
|
568
|
-
async setHeaders(headers) {
|
|
569
|
-
this.#requireActive();
|
|
570
|
-
const reply = await this.#tauri.invoke(`${PLUGIN}syncular_set_headers`, { headers });
|
|
571
|
-
if (reply.error !== undefined) {
|
|
572
|
-
throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
// -- Native CRDT (SPEC.md §5.10.5; needs the plugin `crdt-yjs` feature) ------
|
|
576
|
-
/** Materialize a `crdt` column's collaborative text — decoded from the
|
|
577
|
-
* stored (server-merged) Yjs bytes. `name` selects the shared text
|
|
578
|
-
* (default `"text"`). An absent row / NULL column is the empty document. */
|
|
579
|
-
async crdtText(table, rowId, column, name = 'text') {
|
|
580
|
-
const result = (await this.#command('crdtText', {
|
|
581
|
-
table,
|
|
582
|
-
rowId,
|
|
583
|
-
column,
|
|
584
|
-
name,
|
|
585
|
-
}));
|
|
586
|
-
return result.text;
|
|
587
|
-
}
|
|
588
|
-
/** Insert `value` at UTF-16 offset `index` in a `crdt` column's text and
|
|
589
|
-
* push the resulting Yjs update (baseVersion-less). Returns the commit id. */
|
|
590
|
-
async crdtInsertText(table, rowId, column, index, value, name = 'text') {
|
|
591
|
-
const result = (await this.#command('crdtInsertText', {
|
|
592
|
-
table,
|
|
593
|
-
rowId,
|
|
594
|
-
column,
|
|
595
|
-
name,
|
|
596
|
-
index,
|
|
597
|
-
value,
|
|
598
|
-
}));
|
|
599
|
-
return result.clientCommitId;
|
|
600
|
-
}
|
|
601
|
-
/** Delete `len` UTF-16 code units at `index` in a `crdt` column's text. */
|
|
602
|
-
async crdtDeleteText(table, rowId, column, index, len, name = 'text') {
|
|
603
|
-
const result = (await this.#command('crdtDeleteText', {
|
|
604
|
-
table,
|
|
605
|
-
rowId,
|
|
606
|
-
column,
|
|
607
|
-
name,
|
|
608
|
-
index,
|
|
609
|
-
len,
|
|
610
|
-
}));
|
|
611
|
-
return result.clientCommitId;
|
|
612
|
-
}
|
|
613
|
-
/** Escape hatch: apply an arbitrary Yjs update onto a `crdt` column. */
|
|
614
|
-
async crdtApplyUpdate(table, rowId, column, update) {
|
|
615
|
-
const result = (await this.#command('crdtApplyUpdate', {
|
|
616
|
-
table,
|
|
617
|
-
rowId,
|
|
618
|
-
column,
|
|
619
|
-
update: { $bytes: bytesToHex(update) },
|
|
620
|
-
}));
|
|
621
|
-
return result.clientCommitId;
|
|
622
|
-
}
|
|
623
|
-
/**
|
|
624
|
-
* Stage a blob for attachment (§5.9.7) and return the canonical `BlobRef`
|
|
625
|
-
* string to store in a `blob_ref` column. The native core owns the upload
|
|
626
|
-
* queue; write the referencing row after this resolves (§5.9.3).
|
|
627
|
-
*/
|
|
628
|
-
async uploadBlob(bytes, options) {
|
|
629
|
-
const result = (await this.#command('uploadBlob', {
|
|
630
|
-
bytes: { $bytes: bytesToHex(bytes) },
|
|
631
|
-
...(options?.mediaType !== undefined
|
|
632
|
-
? { mediaType: options.mediaType }
|
|
633
|
-
: {}),
|
|
634
|
-
...(options?.name !== undefined ? { name: options.name } : {}),
|
|
635
|
-
}));
|
|
636
|
-
return result.ref;
|
|
637
|
-
}
|
|
638
|
-
/**
|
|
639
|
-
* Resolve blob bytes for a `blob_ref` column value or a bare `blobId`
|
|
640
|
-
* (§5.9.7): the native core serves a local cache hit and otherwise
|
|
641
|
-
* downloads and verifies the content address.
|
|
642
|
-
*/
|
|
643
|
-
async fetchBlob(ref) {
|
|
644
|
-
const result = (await this.#command('fetchBlob', { blob: ref }));
|
|
645
|
-
const bytes = result.blob.bytes;
|
|
646
|
-
if (!isBytesEnvelope(bytes))
|
|
647
|
-
throw new TauriSyncError('sync.invalid_request', 'fetchBlob reply carried no $bytes envelope');
|
|
648
|
-
return {
|
|
649
|
-
blobId: result.blob.blobId,
|
|
650
|
-
byteLength: result.blob.byteLength,
|
|
651
|
-
bytes: hexToBytes(bytes.$bytes),
|
|
652
|
-
...(result.blob.mediaType !== undefined
|
|
653
|
-
? { mediaType: result.blob.mediaType }
|
|
654
|
-
: {}),
|
|
655
|
-
};
|
|
656
|
-
}
|
|
657
|
-
async subscribe(input) {
|
|
658
|
-
await this.#command('subscribe', {
|
|
659
|
-
id: input.id,
|
|
660
|
-
table: input.table,
|
|
661
|
-
scopes: input.scopes ?? {},
|
|
662
|
-
...(input.params !== undefined ? { params: input.params } : {}),
|
|
663
|
-
});
|
|
664
|
-
}
|
|
665
|
-
/** Register several subscriptions in one local transaction. */
|
|
666
|
-
async subscribeMany(inputs) {
|
|
667
|
-
await this.#command('subscribeMany', {
|
|
668
|
-
subscriptions: inputs.map((input) => ({
|
|
669
|
-
id: input.id,
|
|
670
|
-
table: input.table,
|
|
671
|
-
scopes: input.scopes ?? {},
|
|
672
|
-
...(input.params !== undefined ? { params: input.params } : {}),
|
|
673
|
-
})),
|
|
674
|
-
});
|
|
675
|
-
}
|
|
676
|
-
async unsubscribe(id) {
|
|
677
|
-
await this.#command('unsubscribe', { id });
|
|
678
|
-
}
|
|
679
|
-
async setWindow(base, units) {
|
|
680
|
-
await this.#command('setWindow', {
|
|
681
|
-
base: base,
|
|
682
|
-
units: units,
|
|
683
|
-
});
|
|
684
|
-
}
|
|
685
|
-
async windowState(base) {
|
|
686
|
-
const result = (await this.#command('windowState', {
|
|
687
|
-
base: base,
|
|
688
|
-
}));
|
|
689
|
-
return { units: result.units, pending: result.pending };
|
|
690
|
-
}
|
|
691
|
-
async sync() {
|
|
692
|
-
return this.#command('sync', {});
|
|
693
|
-
}
|
|
694
|
-
/**
|
|
695
|
-
* Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal
|
|
696
|
-
* (`recommendedAction: resetClientId`). The next round carries the new id;
|
|
697
|
-
* the replica and outbox stay in place.
|
|
698
|
-
*/
|
|
699
|
-
async resetClientId() {
|
|
700
|
-
const result = (await this.#command('resetClientId', {}));
|
|
701
|
-
return result.clientId;
|
|
702
|
-
}
|
|
703
|
-
/**
|
|
704
|
-
* SPEC §12 local authority state: `local` while rounds run against the
|
|
705
|
-
* in-process authority, `attaching` during an attach, `attached` once rounds
|
|
706
|
-
* run against `base_url`, and `null` when the plugin configured no
|
|
707
|
-
* `local_authority_path`.
|
|
708
|
-
*/
|
|
1
|
+
import { createTauriSyncClient as createRemoteTauriSyncClient, TauriSyncClient as RemoteTauriSyncClient, } from './remote.js';
|
|
2
|
+
export * from './remote.js';
|
|
3
|
+
/** Tauri bridge with the optional local-authority lifecycle (§12). */
|
|
4
|
+
export class TauriSyncClient extends RemoteTauriSyncClient {
|
|
5
|
+
allowPreflightCommand(method) {
|
|
6
|
+
return method === 'localAuthorityState';
|
|
7
|
+
}
|
|
8
|
+
/** Local authority state, or null when the plugin configured no authority. */
|
|
709
9
|
async localAuthorityState() {
|
|
710
|
-
const result = (await this
|
|
10
|
+
const result = (await this.command('localAuthorityState', {}));
|
|
711
11
|
return result.state;
|
|
712
12
|
}
|
|
713
|
-
/**
|
|
714
|
-
* Upload the local authority's live rows to the `base_url` server (§12.3).
|
|
715
|
-
* Rejects with `sync.attach_rejected` (`details.reason`) when the server
|
|
716
|
-
* refuses; call {@link abandonLocalAuthorityAttach} to roll back.
|
|
717
|
-
*/
|
|
13
|
+
/** Upload the authority's live rows to the remote server (§12.3). */
|
|
718
14
|
async attachLocalAuthority() {
|
|
719
|
-
await this
|
|
15
|
+
await this.command('attachLocalAuthority', {});
|
|
720
16
|
}
|
|
721
|
-
/** Roll back
|
|
17
|
+
/** Roll back a stopped attach and resume the local authority. */
|
|
722
18
|
async abandonLocalAuthorityAttach() {
|
|
723
|
-
await this
|
|
724
|
-
}
|
|
725
|
-
async syncUntilIdle(maxRounds) {
|
|
726
|
-
return this.#command('syncUntilIdle', {
|
|
727
|
-
...(maxRounds !== undefined ? { maxRounds } : {}),
|
|
728
|
-
});
|
|
729
|
-
}
|
|
730
|
-
async proveCurrentBase(outcome, maxRounds) {
|
|
731
|
-
if (maxRounds !== undefined &&
|
|
732
|
-
(!Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 0xffffffff))
|
|
733
|
-
throw new TauriSyncError('sync.invalid_request', 'maxRounds must be a positive integer');
|
|
734
|
-
const proof = (await this.#command('proveCurrentBase', {
|
|
735
|
-
outcome: {
|
|
736
|
-
clientCommitId: outcome.clientCommitId,
|
|
737
|
-
sequence: outcome.sequence,
|
|
738
|
-
},
|
|
739
|
-
...(maxRounds !== undefined ? { maxRounds } : {}),
|
|
740
|
-
}));
|
|
741
|
-
return proof.proven
|
|
742
|
-
? { proven: true, rows: decodeRetainedRows(proof.rows) }
|
|
743
|
-
: proof;
|
|
19
|
+
await this.command('abandonLocalAuthorityAttach', {});
|
|
744
20
|
}
|
|
745
|
-
async conflicts() {
|
|
746
|
-
const result = (await this.#command('conflicts', {}));
|
|
747
|
-
return result.conflicts;
|
|
748
|
-
}
|
|
749
|
-
async rejections() {
|
|
750
|
-
const result = (await this.#command('rejections', {}));
|
|
751
|
-
return result.rejections;
|
|
752
|
-
}
|
|
753
|
-
async commitOutcome(clientCommitId) {
|
|
754
|
-
const result = (await this.#command('commitOutcome', {
|
|
755
|
-
clientCommitId,
|
|
756
|
-
}));
|
|
757
|
-
return result.outcome === undefined
|
|
758
|
-
? undefined
|
|
759
|
-
: decodeCommitOutcome(result.outcome);
|
|
760
|
-
}
|
|
761
|
-
async commitOutcomes(query = {}) {
|
|
762
|
-
const result = (await this.#command('commitOutcomes', { query }));
|
|
763
|
-
return result.outcomes.map(decodeCommitOutcome);
|
|
764
|
-
}
|
|
765
|
-
async resolveCommitOutcome(input) {
|
|
766
|
-
const result = (await this.#command('resolveCommitOutcome', {
|
|
767
|
-
input,
|
|
768
|
-
}));
|
|
769
|
-
return decodeCommitOutcome(result.outcome);
|
|
770
|
-
}
|
|
771
|
-
async pendingCommits() {
|
|
772
|
-
const result = (await this.#command('pendingCommitIds', {}));
|
|
773
|
-
return result.ids;
|
|
774
|
-
}
|
|
775
|
-
async presence(scopeKey) {
|
|
776
|
-
const result = (await this.#command('presence', { scopeKey }));
|
|
777
|
-
return result.peers;
|
|
778
|
-
}
|
|
779
|
-
async setPresence(scopeKey, doc) {
|
|
780
|
-
await this.#command('setPresence', { scopeKey, doc });
|
|
781
|
-
}
|
|
782
|
-
async connectRealtime() {
|
|
783
|
-
await this.#command('connectRealtime', {});
|
|
784
|
-
}
|
|
785
|
-
async disconnectRealtime() {
|
|
786
|
-
await this.#command('disconnectRealtime', {});
|
|
787
|
-
}
|
|
788
|
-
/** Shut down the native core, release its keyring, then detach listeners. */
|
|
789
|
-
async close() {
|
|
790
|
-
if (this.#closed)
|
|
791
|
-
return;
|
|
792
|
-
const shutdown = this.#command('shutdown', {});
|
|
793
|
-
this.#closed = true;
|
|
794
|
-
try {
|
|
795
|
-
await shutdown;
|
|
796
|
-
}
|
|
797
|
-
finally {
|
|
798
|
-
this.#unlisten?.();
|
|
799
|
-
this.#unlisten = undefined;
|
|
800
|
-
this.#invalidationListeners.clear();
|
|
801
|
-
this.#progress.clear();
|
|
802
|
-
this.#changeListeners.clear();
|
|
803
|
-
this.#diagnosticsListeners.clear();
|
|
804
|
-
this.#presenceListeners.clear();
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
function decodeDiagnosticsSnapshot(value, kind) {
|
|
809
|
-
if (value === null || typeof value !== 'object')
|
|
810
|
-
return undefined;
|
|
811
|
-
const snapshot = value;
|
|
812
|
-
if (snapshot.version !== 1 || snapshot.host === undefined)
|
|
813
|
-
return undefined;
|
|
814
|
-
return withClientDiagnosticsHost(snapshot, {
|
|
815
|
-
...snapshot.host,
|
|
816
|
-
kind,
|
|
817
|
-
role: 'single',
|
|
818
|
-
});
|
|
819
21
|
}
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
code;
|
|
823
|
-
details;
|
|
824
|
-
retryable;
|
|
825
|
-
constructor(code, message, details, retryable = false) {
|
|
826
|
-
super(message);
|
|
827
|
-
this.name = 'TauriSyncError';
|
|
828
|
-
this.code = code;
|
|
829
|
-
this.details = details;
|
|
830
|
-
this.retryable = retryable;
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
function toStringSet(value) {
|
|
834
|
-
if (Array.isArray(value)) {
|
|
835
|
-
return new Set(value.filter((v) => typeof v === 'string'));
|
|
836
|
-
}
|
|
837
|
-
return new Set();
|
|
838
|
-
}
|
|
839
|
-
function decodeChangeBatch(value) {
|
|
840
|
-
if (value === null || typeof value !== 'object')
|
|
841
|
-
return undefined;
|
|
842
|
-
const raw = value;
|
|
843
|
-
if (typeof raw.revision !== 'string')
|
|
844
|
-
return undefined;
|
|
845
|
-
const tables = Array.isArray(raw.tables)
|
|
846
|
-
? raw.tables.flatMap((entry) => {
|
|
847
|
-
if (entry === null || typeof entry !== 'object')
|
|
848
|
-
return [];
|
|
849
|
-
const item = entry;
|
|
850
|
-
if (typeof item.table !== 'string')
|
|
851
|
-
return [];
|
|
852
|
-
return [
|
|
853
|
-
{
|
|
854
|
-
table: item.table,
|
|
855
|
-
...(Array.isArray(item.scopeKeys)
|
|
856
|
-
? { scopeKeys: toStringSet(item.scopeKeys) }
|
|
857
|
-
: {}),
|
|
858
|
-
},
|
|
859
|
-
];
|
|
860
|
-
})
|
|
861
|
-
: [];
|
|
862
|
-
const windows = Array.isArray(raw.windows)
|
|
863
|
-
? raw.windows.flatMap((entry) => {
|
|
864
|
-
if (entry === null || typeof entry !== 'object')
|
|
865
|
-
return [];
|
|
866
|
-
const item = entry;
|
|
867
|
-
if (typeof item.baseKey !== 'string' ||
|
|
868
|
-
typeof item.table !== 'string') {
|
|
869
|
-
return [];
|
|
870
|
-
}
|
|
871
|
-
return [
|
|
872
|
-
{
|
|
873
|
-
baseKey: item.baseKey,
|
|
874
|
-
table: item.table,
|
|
875
|
-
units: toStringSet(item.units),
|
|
876
|
-
},
|
|
877
|
-
];
|
|
878
|
-
})
|
|
879
|
-
: [];
|
|
880
|
-
return {
|
|
881
|
-
revision: BigInt(raw.revision),
|
|
882
|
-
tables,
|
|
883
|
-
windows,
|
|
884
|
-
...(raw.status !== undefined
|
|
885
|
-
? { status: raw.status }
|
|
886
|
-
: {}),
|
|
887
|
-
conflictsChanged: raw.conflictsChanged === true,
|
|
888
|
-
rejectionsChanged: raw.rejectionsChanged === true,
|
|
889
|
-
outcomesChanged: raw.outcomesChanged === true,
|
|
890
|
-
};
|
|
891
|
-
}
|
|
892
|
-
function invalidationFromChange(batch) {
|
|
893
|
-
if (batch.tables.length === 0 && batch.windows.length === 0)
|
|
894
|
-
return undefined;
|
|
895
|
-
const tables = new Set();
|
|
896
|
-
const scopeKeys = new Set();
|
|
897
|
-
for (const table of batch.tables) {
|
|
898
|
-
tables.add(table.table);
|
|
899
|
-
for (const key of table.scopeKeys ?? [])
|
|
900
|
-
scopeKeys.add(key);
|
|
901
|
-
}
|
|
902
|
-
for (const window of batch.windows)
|
|
903
|
-
tables.add(window.table);
|
|
904
|
-
return { tables, scopeKeys };
|
|
905
|
-
}
|
|
906
|
-
/** Encode one mutation for the command JSON (bytes inside `values` handled by
|
|
907
|
-
* the native side; the driver form is already JSON-able). */
|
|
908
|
-
function encodeMutation(mutation) {
|
|
909
|
-
if (mutation.op === 'delete')
|
|
910
|
-
return mutation;
|
|
911
|
-
const values = {};
|
|
912
|
-
for (const [key, value] of Object.entries(mutation.values)) {
|
|
913
|
-
values[key] = encodeJsonValue(value);
|
|
914
|
-
}
|
|
915
|
-
return { ...mutation, values };
|
|
916
|
-
}
|
|
917
|
-
export async function createTauriSyncClient(config, createClient = (...args) => new TauriSyncClient(...args)) {
|
|
918
|
-
const tauri = await resolveTauri(config.tauri);
|
|
919
|
-
// Wire the event stream BEFORE create, so no early change batch is missed.
|
|
920
|
-
const clientRef = {
|
|
921
|
-
client: undefined,
|
|
922
|
-
};
|
|
923
|
-
const unlisten = await tauri.listen(SYNCULAR_EVENT, (event) => {
|
|
924
|
-
clientRef.client?.__dispatchEvent(event.payload);
|
|
925
|
-
});
|
|
926
|
-
if (config.securityPreflight === true && config.encryption !== undefined) {
|
|
927
|
-
unlisten();
|
|
928
|
-
throw new TauriSyncError('sync.invalid_request', 'securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight');
|
|
929
|
-
}
|
|
930
|
-
const client = createClient(tauri, unlisten, config.securityPreflight === true ? 'preflight' : 'active');
|
|
931
|
-
clientRef.client = client;
|
|
932
|
-
// The native side owns every path (plugin config); the JS side names a
|
|
933
|
-
// database and supplies the schema, clientId, and limits.
|
|
934
|
-
const reply = await tauri.invoke(`${PLUGIN}syncular_command`, {
|
|
935
|
-
command: {
|
|
936
|
-
method: 'create',
|
|
937
|
-
params: {
|
|
938
|
-
...(config.clientId !== undefined ? { clientId: config.clientId } : {}),
|
|
939
|
-
...(config.database !== undefined ? { database: config.database } : {}),
|
|
940
|
-
schema: config.schema,
|
|
941
|
-
...(config.limits !== undefined ? { limits: config.limits } : {}),
|
|
942
|
-
...(config.retainFailedCommits !== undefined
|
|
943
|
-
? { retainFailedCommits: config.retainFailedCommits }
|
|
944
|
-
: {}),
|
|
945
|
-
...(config.realtimePolicy !== undefined
|
|
946
|
-
? { realtimePolicy: config.realtimePolicy }
|
|
947
|
-
: {}),
|
|
948
|
-
...(config.encryption !== undefined
|
|
949
|
-
? { encryption: encodeEncryption(config.encryption) }
|
|
950
|
-
: {}),
|
|
951
|
-
...(config.transportEnabled !== undefined
|
|
952
|
-
? { transportEnabled: config.transportEnabled }
|
|
953
|
-
: {}),
|
|
954
|
-
...(config.authorityReads !== undefined
|
|
955
|
-
? { authorityReads: config.authorityReads.declarations }
|
|
956
|
-
: {}),
|
|
957
|
-
...(config.securityPreflight !== undefined
|
|
958
|
-
? { securityPreflight: config.securityPreflight }
|
|
959
|
-
: {}),
|
|
960
|
-
...(config.previousVersionContext !== undefined
|
|
961
|
-
? { previousVersionContext: config.previousVersionContext }
|
|
962
|
-
: {}),
|
|
963
|
-
},
|
|
964
|
-
},
|
|
965
|
-
});
|
|
966
|
-
if (reply.error !== undefined) {
|
|
967
|
-
unlisten();
|
|
968
|
-
throw new TauriSyncError(reply.error.code, reply.error.message, reply.error.details ?? undefined, reply.error.retryable ?? false);
|
|
969
|
-
}
|
|
970
|
-
return client;
|
|
22
|
+
export function createTauriSyncClient(config, createClient = (...args) => new TauriSyncClient(...args)) {
|
|
23
|
+
return createRemoteTauriSyncClient(config, createClient);
|
|
971
24
|
}
|