@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.
@@ -0,0 +1,266 @@
1
+ import { type SyncProgress, type SyncProgressListener } from '@syncular/client';
2
+ import type { ClientSnapshotMethods, PromiseMethods } from '@syncular/client';
3
+ /**
4
+ * @syncular/tauri — the JS bridge to the native syncular instance running
5
+ * inside the Tauri process (see `tauri-plugin-syncular`).
6
+ *
7
+ * The Tauri host runs a REAL Rust syncular client (file DB + native HTTP+WS
8
+ * transport). This module is a thin webview-side proxy that implements the SAME
9
+ * `SyncClientLike` interface the React package normalizes — so the hooks
10
+ * (`useRawSql`, `useMutation`, `usePresence`, …) work UNCHANGED against a
11
+ * Tauri app. It is the fourth host of one interface, after the direct
12
+ * `SyncClient`, the worker-leader `SyncClientHandle`, and the multi-tab
13
+ * follower.
14
+ *
15
+ * Every method forwards to the plugin's `syncular_command` command (the whole
16
+ * command surface in one JSON envelope — `{method, params}`), mirroring the FFI
17
+ * and the conformance shim. `query` uses the dedicated `syncular_query` fast
18
+ * path; atomic reactive reads use `syncular_query_snapshot`, backed by an
19
+ * independent read-only SQLite connection so network sync cannot stall local
20
+ * UI reads. Client-observable
21
+ * events (`change` / `presence`) arrive on
22
+ * the `syncular://event` Tauri event and fan out to the registered listeners.
23
+ *
24
+ * Bytes cross the command JSON as the established `{$bytes: hex}` envelope, the
25
+ * same convention the Rust command router and the driver protocol use.
26
+ *
27
+ * `@tauri-apps/api` is a required peer dependency: the bridge takes
28
+ * `invoke`/`listen` either from its ESM entry points, from the ambient
29
+ * `window.__TAURI__`, or via injected doubles (tests).
30
+ */
31
+ import type { AuthorityReadPolicy, ClientChangeListener, ClientDiagnosticsListener, ClientDiagnosticsRequest, ClientDiagnosticsSnapshot, CommitOutcome, CommitOutcomeQuery, CurrentBaseProof, ConflictRecord, EncryptionKeyringConfig, InvalidationListener, LocalDataPurgeInput, LocalDataPurgeResult, LocalDataRebootstrapInput, LocalDataRebootstrapResult, MutationInput, PresencePeer, PreviousVersionAudit, PreviousVersionReadSpec, PreviousVersionSnapshot, QueryReadSpec, QuerySnapshot, RejectionRecord, ResolveCommitOutcomeInput, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SqlRow, SqlValue, SyncClientConfig, SyncStatusSnapshot, WindowBase, WindowState } from '@syncular/client';
32
+ /** One event pushed on `syncular://event` (the derived client-observable set). */
33
+ interface SyncularEvent {
34
+ readonly type: string;
35
+ readonly [key: string]: unknown;
36
+ }
37
+ /** §7.5: one read-only statement in an atomic sidecar snapshot read. */
38
+ export type { SnapshotStatement } from '@syncular/client';
39
+ /** §7.5: the catch-up state of one subscription from the sidecar. */
40
+ export type { SubscriptionCatchup } from '@syncular/client';
41
+ /** §7.5: delivery status for one client commit id. */
42
+ export type { CommitDelivery } from '@syncular/client';
43
+ /** §7.5: one atomic sidecar snapshot read result with decoded rows. */
44
+ export type SnapshotReadResult = SnapshotRead;
45
+ /** The two Tauri primitives the bridge needs — injectable for tests. */
46
+ export interface TauriApi {
47
+ invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T>;
48
+ listen<T>(event: string, handler: (event: {
49
+ payload: T;
50
+ }) => void): Promise<() => void>;
51
+ }
52
+ /** The plugin's Tauri event name — mirror of `tauri-plugin-syncular`. */
53
+ export declare const SYNCULAR_EVENT = "syncular://event";
54
+ /** SPEC §12 local authority lifecycle state. */
55
+ export type LocalAuthorityState = 'local' | 'attaching' | 'attached';
56
+ /** Config for {@link createTauriSyncClient}. */
57
+ export interface TauriSyncClientConfig {
58
+ /** The generated schema JSON (the app passes `schema` from typegen). */
59
+ readonly schema: unknown;
60
+ /**
61
+ * Client id for this device/actor. If omitted, the native client generates
62
+ * one and persists it in the database. Supplying a different id when opening
63
+ * an existing database fails with `client.identity_mismatch`.
64
+ */
65
+ readonly clientId?: string;
66
+ /**
67
+ * Name of the native database to open, for example one replica per
68
+ * signed-in actor. The plugin opens `<database_dir>/<database>.db` from its
69
+ * `SyncularConfig`; a name is 1 to 128 ASCII letters, digits, `-`, `_` or
70
+ * `.` and starts with a letter or digit. Absent ⇒ the plugin's `db_path`.
71
+ */
72
+ readonly database?: string;
73
+ /** §4.2 client limits, forwarded to the native `create`. */
74
+ readonly limits?: Record<string, unknown>;
75
+ /**
76
+ * SPEC §8.8 realtime policy, forwarded to the native `create`. Absent ⇒
77
+ * `optional`. `required` refuses a sync round while the socket is not
78
+ * connected instead of falling back to HTTP.
79
+ */
80
+ readonly realtimePolicy?: SyncClientConfig['realtimePolicy'];
81
+ readonly retainFailedCommits?: boolean;
82
+ /**
83
+ * Portable E2EE keys and declarative per-row key-id columns. Raw keys are
84
+ * encoded into the native command envelope and never sent to the server.
85
+ */
86
+ readonly encryption?: EncryptionKeyringConfig;
87
+ /** Fixed plain authority reads permitted before security activation. */
88
+ readonly authorityReads?: AuthorityReadPolicy;
89
+ /** Open the native replica behind the fail-closed security gate. */
90
+ readonly securityPreflight?: boolean;
91
+ /** Open local storage with network transport closed until explicitly resumed. */
92
+ readonly transportEnabled?: boolean;
93
+ /**
94
+ * RFC 0005 previous-version context, forwarded to the native `create`. The
95
+ * Rust create handler must read this key to enable capture; while it does
96
+ * not, the native core treats the feature as off (default-off).
97
+ */
98
+ readonly previousVersionContext?: SyncClientConfig['previousVersionContext'];
99
+ /**
100
+ * The Tauri primitives. Omit in a real Tauri webview to auto-resolve from
101
+ * `@tauri-apps/api` (peer dep) or the ambient `window.__TAURI__`; inject in
102
+ * tests. Resolution is async, so construction is a factory (below).
103
+ */
104
+ readonly tauri?: TauriApi;
105
+ }
106
+ /** The bytes envelope both sides share. */
107
+ export type BytesEnvelope = {
108
+ readonly $bytes: string;
109
+ };
110
+ /** @internal Shared native row codec. */
111
+ export declare function decodeRow(row: Record<string, unknown>): SqlRow;
112
+ /**
113
+ * The webview-side proxy implementing `SyncClientLike` over the plugin. Every
114
+ * snapshot method returns a promise from an IPC round trip. React hooks accept
115
+ * the canonical snapshot interface directly.
116
+ */
117
+ export declare class TauriSyncClient implements PromiseMethods<ClientSnapshotMethods> {
118
+ #private;
119
+ /** @internal — use {@link createTauriSyncClient}. */
120
+ constructor(tauri: TauriApi, unlisten: () => void, securityLifecycle?: SecurityLifecycle);
121
+ /** @internal Shared command gate for explicit bridge extensions. */
122
+ protected command(method: string, params: Record<string, unknown>): Promise<unknown>;
123
+ /** @internal Additional preflight operations supplied by bridge extensions. */
124
+ protected allowPreflightCommand(_method: string): boolean;
125
+ /** @internal Recheck local close after an extension's asynchronous reply. */
126
+ protected requireOpen(): void;
127
+ /** @internal — fan an incoming plugin event out to the local listeners. */
128
+ __dispatchEvent(event: SyncularEvent): void;
129
+ securityLifecycle(): Promise<SecurityLifecycle>;
130
+ beginSecurityPreflight(): Promise<void>;
131
+ /**
132
+ * Complete the security preflight. `headers` optionally carries a fresh
133
+ * FULL transport header set that the native host applies atomically with
134
+ * the activation, before the startup sync it enqueues — so a preflight
135
+ * that outlives the boot token starts its first round with valid
136
+ * credentials (the direct `setHeaders` path stays refused while gated).
137
+ */
138
+ activateSecurity(options?: {
139
+ readonly encryption?: EncryptionKeyringConfig;
140
+ readonly headers?: Readonly<Record<string, string>>;
141
+ }): Promise<void>;
142
+ onInvalidate(listener: InvalidationListener): () => void;
143
+ onProgress(listener: SyncProgressListener): () => void;
144
+ progressSnapshot(): SyncProgress | undefined;
145
+ onChange(listener: ClientChangeListener): () => void;
146
+ onDiagnostics(listener: ClientDiagnosticsListener): () => void;
147
+ onPresence(listener: (scopeKey: string) => void): () => void;
148
+ query(sql: string, params?: readonly SqlValue[]): Promise<SqlRow[]>;
149
+ querySnapshot<Row = SqlRow>(spec: QueryReadSpec): Promise<QuerySnapshot<Row>>;
150
+ localRevision(): Promise<bigint>;
151
+ /**
152
+ * §7.5: one atomic read over the file-backed sidecar. Every statement and
153
+ * every catch-up/delivery read shares one revision (a `bigint`, matching
154
+ * `querySnapshot`) and one read transaction; every query row is decoded.
155
+ */
156
+ snapshotRead(request: SnapshotReadRequest): Promise<SnapshotRead>;
157
+ statusSnapshot(): Promise<SyncStatusSnapshot>;
158
+ diagnosticsSnapshot(request?: ClientDiagnosticsRequest): Promise<ClientDiagnosticsSnapshot>;
159
+ mutate(mutations: readonly MutationInput[]): Promise<string>;
160
+ patch(table: string, rowId: string, partial: Readonly<Record<string, unknown>>, options?: {
161
+ readonly baseVersion?: number;
162
+ }): Promise<string>;
163
+ purgeLocalData(input: LocalDataPurgeInput): Promise<LocalDataPurgeResult>;
164
+ rebootstrapLocalData(input: LocalDataRebootstrapInput): Promise<LocalDataRebootstrapResult>;
165
+ previousVersionSnapshot(spec: PreviousVersionReadSpec): Promise<PreviousVersionSnapshot>;
166
+ previousVersionAudit(): Promise<PreviousVersionAudit | undefined>;
167
+ previousVersionDiscard(): Promise<{
168
+ present: boolean;
169
+ discarded: boolean;
170
+ }>;
171
+ /** Suspend new network work while retaining local access and queued commits. */
172
+ setTransportEnabled(enabled: boolean): Promise<void>;
173
+ /** Browser offline-control parity; local reads and commits remain available. */
174
+ setOffline(offline: boolean): Promise<void>;
175
+ /**
176
+ * Replace the native transport's request headers at runtime — the auth
177
+ * rotation path. Pass the FULL header set (it replaces,
178
+ * it does not merge). HTTP requests use the new set from the next call;
179
+ * the realtime socket applies it on its next (re)connect.
180
+ */
181
+ setHeaders(headers: Readonly<Record<string, string>>): Promise<void>;
182
+ /** Materialize a `crdt` column's collaborative text — decoded from the
183
+ * stored (server-merged) Yjs bytes. `name` selects the shared text
184
+ * (default `"text"`). An absent row / NULL column is the empty document. */
185
+ crdtText(table: string, rowId: string, column: string, name?: string): Promise<string>;
186
+ /** Insert `value` at UTF-16 offset `index` in a `crdt` column's text and
187
+ * push the resulting Yjs update (baseVersion-less). Returns the commit id. */
188
+ crdtInsertText(table: string, rowId: string, column: string, index: number, value: string, name?: string): Promise<string>;
189
+ /** Delete `len` UTF-16 code units at `index` in a `crdt` column's text. */
190
+ crdtDeleteText(table: string, rowId: string, column: string, index: number, len: number, name?: string): Promise<string>;
191
+ /** Escape hatch: apply an arbitrary Yjs update onto a `crdt` column. */
192
+ crdtApplyUpdate(table: string, rowId: string, column: string, update: Uint8Array): Promise<string>;
193
+ /**
194
+ * Stage a blob for attachment (§5.9.7) and return the canonical `BlobRef`
195
+ * string to store in a `blob_ref` column. The native core owns the upload
196
+ * queue; write the referencing row after this resolves (§5.9.3).
197
+ */
198
+ uploadBlob(bytes: Uint8Array, options?: {
199
+ readonly mediaType?: string;
200
+ readonly name?: string;
201
+ }): Promise<string>;
202
+ /**
203
+ * Resolve blob bytes for a `blob_ref` column value or a bare `blobId`
204
+ * (§5.9.7): the native core serves a local cache hit and otherwise
205
+ * downloads and verifies the content address.
206
+ */
207
+ fetchBlob(ref: string): Promise<{
208
+ readonly blobId: string;
209
+ readonly byteLength: number;
210
+ readonly bytes: Uint8Array;
211
+ readonly mediaType?: string;
212
+ }>;
213
+ subscribe(input: {
214
+ readonly id: string;
215
+ readonly table: string;
216
+ readonly scopes?: Record<string, readonly string[]>;
217
+ readonly params?: string;
218
+ }): Promise<void>;
219
+ /** Register several subscriptions in one local transaction. */
220
+ subscribeMany(inputs: readonly {
221
+ readonly id: string;
222
+ readonly table: string;
223
+ readonly scopes?: Record<string, readonly string[]>;
224
+ readonly params?: string;
225
+ }[]): Promise<void>;
226
+ unsubscribe(id: string): Promise<void>;
227
+ setWindow(base: WindowBase, units: readonly string[]): Promise<void>;
228
+ windowState(base: WindowBase): Promise<WindowState>;
229
+ sync(): Promise<unknown>;
230
+ /**
231
+ * Rotate the client id (§1.5) after a `sync.invalid_client_id` refusal
232
+ * (`recommendedAction: resetClientId`). The next round carries the new id;
233
+ * the replica and outbox stay in place.
234
+ */
235
+ resetClientId(): Promise<string>;
236
+ syncUntilIdle(maxRounds?: number): Promise<unknown>;
237
+ proveCurrentBase(outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>, maxRounds?: number): Promise<CurrentBaseProof>;
238
+ conflicts(): Promise<readonly ConflictRecord[]>;
239
+ rejections(): Promise<readonly RejectionRecord[]>;
240
+ commitOutcome(clientCommitId: string): Promise<CommitOutcome | undefined>;
241
+ commitOutcomes(query?: CommitOutcomeQuery): Promise<readonly CommitOutcome[]>;
242
+ resolveCommitOutcome(input: ResolveCommitOutcomeInput): Promise<CommitOutcome>;
243
+ pendingCommits(): Promise<unknown[]>;
244
+ presence(scopeKey: string): Promise<readonly PresencePeer[]>;
245
+ setPresence(scopeKey: string, doc: Record<string, unknown> | null): Promise<void>;
246
+ connectRealtime(): Promise<void>;
247
+ disconnectRealtime(): Promise<void>;
248
+ /** Shut down the native core, release its keyring, then detach listeners. */
249
+ close(): Promise<void>;
250
+ }
251
+ /** The error a `{error}` reply surfaces (mirrors the web-client `ClientSyncError`). */
252
+ export declare class TauriSyncError extends Error {
253
+ readonly code: string;
254
+ readonly details: Readonly<Record<string, unknown>> | undefined;
255
+ readonly retryable: boolean;
256
+ constructor(code: string, message: string, details?: Readonly<Record<string, unknown>>, retryable?: boolean);
257
+ }
258
+ /**
259
+ * Construct the bridge and issue the native `create` (opening/attaching the
260
+ * file DB on the Rust side per the plugin config). Returns a ready
261
+ * `TauriSyncClient` that satisfies `SyncClientLike` — pass it straight to the
262
+ * React `<SyncProvider client={…}>`.
263
+ */
264
+ export declare function createTauriSyncClient(config: TauriSyncClientConfig): Promise<TauriSyncClient>;
265
+ /** @internal Explicit bridge extension used by the authority entry. */
266
+ export declare function createTauriSyncClient<Client extends TauriSyncClient>(config: TauriSyncClientConfig, createClient: (...args: ConstructorParameters<typeof TauriSyncClient>) => Client): Promise<Client>;