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