@cf-sync/client 0.1.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/LICENSE +21 -0
- package/README.md +32 -0
- package/dist/client-tvsT_ixa.d.ts +714 -0
- package/dist/index.d.ts +139 -0
- package/dist/index.js +2051 -0
- package/dist/react.d.ts +49 -0
- package/dist/react.js +53 -0
- package/package.json +76 -0
|
@@ -0,0 +1,714 @@
|
|
|
1
|
+
import { AnyMutators, AnySyncSchema, AppDefinition, AuthContextOf, Cursor, EngineErrorCode, MutationArgs, PresencePeer, StandardSchemaV1 } from "@cf-sync/protocol";
|
|
2
|
+
//#region src/errors.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The known codes a rejected `mutate` promise carries — the engine's built-in
|
|
5
|
+
* rejections ({@link EngineErrorCode}) plus the client-local outcomes:
|
|
6
|
+
*
|
|
7
|
+
* - `Timeout` — memory-only client, unconfirmed past `confirmTimeoutMs`.
|
|
8
|
+
* - `Stopped` — `destroy()` was called with the mutation still unconfirmed.
|
|
9
|
+
* - `Fatal` — the client is in (or entered) the fatal state.
|
|
10
|
+
* - `LocalApplyFailed` — the optimistic apply threw a non-`AppError`; nothing
|
|
11
|
+
* was sent.
|
|
12
|
+
*
|
|
13
|
+
* App-defined `AppError` codes flow through as themselves, so `code` stays
|
|
14
|
+
* open to any string — this union is the vocabulary that autocompletes.
|
|
15
|
+
*/
|
|
16
|
+
type MutationErrorCode = EngineErrorCode | 'Timeout' | 'Stopped' | 'Fatal' | 'LocalApplyFailed';
|
|
17
|
+
/**
|
|
18
|
+
* The error a refused mutation settles with — what an awaited `mutate` call
|
|
19
|
+
* rejects with and what `onMutationRejected` receives. `code` is the
|
|
20
|
+
* branchable identity, drawn from three groups: the engine's built-in
|
|
21
|
+
* rejections ({@link EngineErrorCode}, e.g. `InvalidArgs`,
|
|
22
|
+
* `UnknownMutator`), the client-local outcomes (`Timeout`, `Stopped`,
|
|
23
|
+
* `Fatal`, `LocalApplyFailed`), and app-defined `AppError` codes passed
|
|
24
|
+
* through verbatim — {@link MutationErrorCode} is the full vocabulary.
|
|
25
|
+
* `message` is diagnostic prose; branch on `code`, not on it. `mutation`
|
|
26
|
+
* carries the rejected mutation's name and args when the client knows them —
|
|
27
|
+
* an awaiting `catch` gets the same context `onMutationRejected` receives.
|
|
28
|
+
*/
|
|
29
|
+
declare class MutationError extends Error {
|
|
30
|
+
readonly code: MutationErrorCode | (string & {});
|
|
31
|
+
readonly mutation?: {
|
|
32
|
+
name: string;
|
|
33
|
+
args: unknown;
|
|
34
|
+
} | undefined;
|
|
35
|
+
constructor(code: MutationErrorCode | (string & {}), message: string, mutation?: {
|
|
36
|
+
name: string;
|
|
37
|
+
args: unknown;
|
|
38
|
+
} | undefined);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* What {@link SyncFatalError.code} can hold: the WebSocket close code
|
|
42
|
+
* (4400–4499) when the rejection arrived as a close frame, or the in-band
|
|
43
|
+
* server code — only `VersionNotSupported` and `Unauthorized` are ever fatal.
|
|
44
|
+
*/
|
|
45
|
+
type SyncFatalCode = number | 'VersionNotSupported' | 'Unauthorized';
|
|
46
|
+
/**
|
|
47
|
+
* What `onFatal` receives when the server permanently rejects this client.
|
|
48
|
+
* `reason` is the close frame's slug (`membership-revoked`,
|
|
49
|
+
* `project-deleted`) — stable strings apps can branch on.
|
|
50
|
+
*/
|
|
51
|
+
declare class SyncFatalError extends Error {
|
|
52
|
+
readonly code: SyncFatalCode;
|
|
53
|
+
readonly reason: string;
|
|
54
|
+
constructor(code: SyncFatalCode, reason: string);
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/mutate.d.ts
|
|
58
|
+
type NamespaceHeads<K extends string> = K extends `${infer H}.${string}` ? H : K;
|
|
59
|
+
type NamespaceSub<M, H extends string> = { [K in keyof M & `${H}.${string}` as K extends `${H}.${infer R}` ? R : never]: M[K]; };
|
|
60
|
+
/**
|
|
61
|
+
* The property-access half of `client.mutate`: dots in mutator names become
|
|
62
|
+
* namespaces, so `'todos.clearCompleted'` is called as
|
|
63
|
+
* `client.mutate.todos.clearCompleted()` — names autocomplete, args are typed
|
|
64
|
+
* from the mutator's schema. (`defineMutators` rejects a name that is both a
|
|
65
|
+
* mutator and a namespace prefix of another, so the tree is unambiguous.)
|
|
66
|
+
*/
|
|
67
|
+
type MutateNamespace<M> = { [H in NamespaceHeads<keyof M & string>]: H extends keyof M ? (...args: MutationArgs<M[H]>) => Promise<void> : MutateNamespace<NamespaceSub<M, H>>; };
|
|
68
|
+
/**
|
|
69
|
+
* `client.mutate` is both a function and a namespace tree: call it with a
|
|
70
|
+
* mutator name (`mutate('todos.clearCompleted')`) or through properties
|
|
71
|
+
* (`mutate.todos.clearCompleted()`). Both forms are identical at runtime.
|
|
72
|
+
*/
|
|
73
|
+
type Mutate<M extends AnyMutators> = (<K extends keyof M & string>(name: K, ...args: MutationArgs<M[K]>) => Promise<void>) & MutateNamespace<M>;
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/store.d.ts
|
|
76
|
+
/** A queued mutation in durable form. `id` is null until a baseline is known. */
|
|
77
|
+
interface PersistedOutboxEntry {
|
|
78
|
+
id: number | null;
|
|
79
|
+
name: string;
|
|
80
|
+
args: unknown;
|
|
81
|
+
}
|
|
82
|
+
/** A put/del row operation in durable form (clear is signaled separately). */
|
|
83
|
+
type PersistedRowOp = {
|
|
84
|
+
op: 'put';
|
|
85
|
+
tbl: string;
|
|
86
|
+
id: string;
|
|
87
|
+
value: Record<string, unknown>;
|
|
88
|
+
} | {
|
|
89
|
+
op: 'del';
|
|
90
|
+
tbl: string;
|
|
91
|
+
id: string;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Everything a {@link SyncStore} hands back at hydration: cached rows, the
|
|
95
|
+
* cursor they correspond to, and this client's outbox.
|
|
96
|
+
*/
|
|
97
|
+
interface PersistedState {
|
|
98
|
+
/** App schema version the cached rows were written under — a mismatch discards the cache. Null when only an outbox was ever persisted. */
|
|
99
|
+
schemaVersion: number | null;
|
|
100
|
+
/** Null when mutations were queued before the first successful sync. */
|
|
101
|
+
cursor: Cursor | null;
|
|
102
|
+
/** The highest mutation id the server had confirmed when this was written; queued mutations number upward from it. */
|
|
103
|
+
confirmedLmid: number;
|
|
104
|
+
/** Cached full row values across all tables; hydration buckets them by table. */
|
|
105
|
+
rows: {
|
|
106
|
+
tbl: string;
|
|
107
|
+
id: string;
|
|
108
|
+
value: Record<string, unknown>;
|
|
109
|
+
}[];
|
|
110
|
+
/** This client's queued mutations, in enqueue order. */
|
|
111
|
+
outbox: PersistedOutboxEntry[];
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* One poke's durable effects, committed atomically by
|
|
115
|
+
* {@link SyncStore.applyPoke}: the row operations, the cursor they produce,
|
|
116
|
+
* and the outbox as it stands after settlement.
|
|
117
|
+
*/
|
|
118
|
+
interface PokePersist {
|
|
119
|
+
/** Row puts/dels from the poke's patch, in patch order. */
|
|
120
|
+
ops: PersistedRowOp[];
|
|
121
|
+
/** True when the poke contained a clear op (reset/bootstrap): replace all rows. */
|
|
122
|
+
clear: boolean;
|
|
123
|
+
/** The cursor after applying `ops` — must commit atomically with them. */
|
|
124
|
+
cursor: Cursor;
|
|
125
|
+
/** The app schema version the rows conform to. */
|
|
126
|
+
schemaVersion: number;
|
|
127
|
+
/** The server-confirmed mutation id after this poke's settlements. */
|
|
128
|
+
confirmedLmid: number;
|
|
129
|
+
/** Full outbox snapshot after settlement — replaces the stored one. */
|
|
130
|
+
outbox: PersistedOutboxEntry[];
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Durable client-side storage for synced rows, the cursor, and the outbox.
|
|
134
|
+
*
|
|
135
|
+
* The contract mirrors the server's transaction invariant on
|
|
136
|
+
* the client: applyPoke must commit rows, cursor, confirmedLmid, and the
|
|
137
|
+
* outbox snapshot atomically, so the persisted cursor is never newer than
|
|
138
|
+
* the persisted rows. A cursor that lags the rows is harmless — patches are
|
|
139
|
+
* idempotent full-row puts/dels, so re-applying a delta converges.
|
|
140
|
+
*
|
|
141
|
+
* Implementations must apply operations in call order.
|
|
142
|
+
*/
|
|
143
|
+
interface SyncStore {
|
|
144
|
+
/** Load everything needed for hydration; null when nothing is stored. */
|
|
145
|
+
load(): Promise<PersistedState | null>;
|
|
146
|
+
/** Atomically persist a poke's effects plus the resulting outbox. */
|
|
147
|
+
applyPoke(update: PokePersist): Promise<void>;
|
|
148
|
+
/** Persist the outbox alone (enqueue, settle, or renumber without a poke). */
|
|
149
|
+
saveOutbox(outbox: PersistedOutboxEntry[], confirmedLmid: number): Promise<void>;
|
|
150
|
+
/** Discard all persisted state (schema change or corrupt cache). */
|
|
151
|
+
reset(): Promise<void>;
|
|
152
|
+
/**
|
|
153
|
+
* Release the store's underlying connection (`SyncClient.destroy` calls it
|
|
154
|
+
* when present). Persisted state stays on disk for the next client.
|
|
155
|
+
*/
|
|
156
|
+
close?(): Promise<void>;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* In-memory SyncStore: reference implementation and test double. Also usable
|
|
160
|
+
* to pass a fresh "store" that intentionally forgets on reload.
|
|
161
|
+
*/
|
|
162
|
+
declare class MemorySyncStore implements SyncStore {
|
|
163
|
+
#private;
|
|
164
|
+
load(): Promise<PersistedState | null>;
|
|
165
|
+
applyPoke(update: PokePersist): Promise<void>;
|
|
166
|
+
saveOutbox(outbox: PersistedOutboxEntry[], confirmedLmid: number): Promise<void>;
|
|
167
|
+
reset(): Promise<void>;
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/types.d.ts
|
|
171
|
+
/**
|
|
172
|
+
* The client's connection lifecycle — one value describing the pipe, not any
|
|
173
|
+
* individual mutation (those settle through `mutate`'s promise and
|
|
174
|
+
* `onMutationRejected`). `idle` is before `start()` and after `destroy()`;
|
|
175
|
+
* `connecting` covers hydration and the first socket attempt; `syncing` means
|
|
176
|
+
* the socket is open and catch-up is in flight; `synced` means this
|
|
177
|
+
* connection has caught up (the status holds there between pokes);
|
|
178
|
+
* `reconnecting` means the connection dropped and backoff retries are running
|
|
179
|
+
* — queued mutations wait, nothing is lost; `fatal` means the server
|
|
180
|
+
* permanently rejected this client (see `SyncClientOptions.onFatal`).
|
|
181
|
+
*/
|
|
182
|
+
type SyncStatus = 'idle' | 'connecting' | 'syncing' | 'synced' | 'reconnecting' | 'fatal';
|
|
183
|
+
/**
|
|
184
|
+
* Minimal socket surface so tests and non-browser runtimes can inject one.
|
|
185
|
+
* A custom `createSocket` that wraps a real browser WebSocket must set
|
|
186
|
+
* `binaryType = 'arraybuffer'` — binary-lane frames must arrive as
|
|
187
|
+
* ArrayBuffer, not Blob — which the default factory does.
|
|
188
|
+
*/
|
|
189
|
+
interface WebSocketLike {
|
|
190
|
+
send(data: string | ArrayBufferLike | ArrayBufferView): void;
|
|
191
|
+
close(code?: number, reason?: string): void;
|
|
192
|
+
addEventListener(type: 'open' | 'message' | 'close' | 'error', listener: (event: any) => void): void;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* One row operation delivered to a table's hooks: a full-row `put` (rows are
|
|
196
|
+
* last-writer-wins documents, so `value` replaces the row entirely) or a
|
|
197
|
+
* `del` by id.
|
|
198
|
+
*/
|
|
199
|
+
type TableWriteOp = {
|
|
200
|
+
type: 'put';
|
|
201
|
+
id: string;
|
|
202
|
+
value: Record<string, unknown>;
|
|
203
|
+
} | {
|
|
204
|
+
type: 'del';
|
|
205
|
+
id: string;
|
|
206
|
+
};
|
|
207
|
+
/** What a table (collection adapter) must implement to receive synced data. */
|
|
208
|
+
interface TableHooks {
|
|
209
|
+
begin(): void;
|
|
210
|
+
write(op: TableWriteOp): void;
|
|
211
|
+
commit(): void;
|
|
212
|
+
/** Called inside an open begin()…commit() to reset the table (bootstrap/reset). */
|
|
213
|
+
truncate(): void;
|
|
214
|
+
markReady(): void;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* What a table's collection exposes for optimistic intent execution
|
|
218
|
+
* (adapter-facing, like `TableHooks`). Reads must reflect the collection's
|
|
219
|
+
* combined view — synced state plus earlier pending optimistic overlays — so
|
|
220
|
+
* overlapping intents read each other. Writes are only ever invoked inside
|
|
221
|
+
* the `IntentTransactionRunner`'s atomic scope. Row values must be plain data
|
|
222
|
+
* (no adapter-specific virtual fields): they flow back into mutator `tx.get`
|
|
223
|
+
* reads and from there potentially onto the wire.
|
|
224
|
+
*/
|
|
225
|
+
interface TableApplier {
|
|
226
|
+
has(id: string): boolean;
|
|
227
|
+
get(id: string): Record<string, unknown> | null;
|
|
228
|
+
list(): Array<{
|
|
229
|
+
id: string;
|
|
230
|
+
data: Record<string, unknown>;
|
|
231
|
+
}>;
|
|
232
|
+
insert(data: Record<string, unknown>): void;
|
|
233
|
+
update(id: string, data: Record<string, unknown>): void;
|
|
234
|
+
delete(id: string): void;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Runs `flush` (the intent's buffered writes, translated to collection ops)
|
|
238
|
+
* as one atomic optimistic transaction whose sole persistence step is
|
|
239
|
+
* `persist` (enqueue the intent mutation and await server confirm). Must
|
|
240
|
+
* resolve/reject with `persist`'s outcome, roll every flushed write back on
|
|
241
|
+
* rejection, and — critically — still call `persist` when `flush` produced
|
|
242
|
+
* zero effective writes (local state may be behind; the server's run is the
|
|
243
|
+
* one that counts).
|
|
244
|
+
*/
|
|
245
|
+
type IntentTransactionRunner = (intent: string, flush: () => void, persist: () => Promise<void>) => Promise<void>;
|
|
246
|
+
/**
|
|
247
|
+
* Internal seam for the collection adapter: enqueue a mutation *without* the
|
|
248
|
+
* speculative local run. Collection mutation handlers (`onInsert` etc.) must
|
|
249
|
+
* use this — their optimistic effect already happened via the collection
|
|
250
|
+
* write itself, and routing them through `mutate` would recursively spawn a
|
|
251
|
+
* second transaction re-applying it. Not part of the public API.
|
|
252
|
+
*/
|
|
253
|
+
declare const RAW_MUTATE: unique symbol;
|
|
254
|
+
/**
|
|
255
|
+
* The sink for the client's diagnostics. `message` arrives fully formatted
|
|
256
|
+
* (including the `[cf-sync]` prefix); `detail` carries any associated error
|
|
257
|
+
* or payload. The default writes to `console[level]`.
|
|
258
|
+
*/
|
|
259
|
+
type SyncLogger = (level: 'warn' | 'error', message: string, ...detail: unknown[]) => void;
|
|
260
|
+
type PresenceInputOf<P> = P extends StandardSchemaV1 ? StandardSchemaV1.InferInput<P> : never;
|
|
261
|
+
type PresenceStateOf<P> = P extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<P> : never;
|
|
262
|
+
/**
|
|
263
|
+
* `client.presence` — ephemeral peer state on the existing sync socket.
|
|
264
|
+
* The library owns transport and lifecycle: `set` is throttled
|
|
265
|
+
* trailing-edge at `presenceThrottleMs` (safe to call at input frequency) and
|
|
266
|
+
* the last state is re-announced on every reconnect, so apps write neither
|
|
267
|
+
* throttle nor reconnect glue. Peers exclude self (render your own state from
|
|
268
|
+
* your own source of truth) and reset to empty on disconnect — stale presence
|
|
269
|
+
* is worse than absent presence. Requires a `presence` schema in `defineApp`;
|
|
270
|
+
* without one `set`/`clear` throw (and the state type is `never`).
|
|
271
|
+
*/
|
|
272
|
+
interface PresenceApi<TIn = unknown, TOut = unknown> {
|
|
273
|
+
/** Replace this client's presence state. Validated locally; fail-fast like mutate-time args. */
|
|
274
|
+
set(state: TIn): void;
|
|
275
|
+
/**
|
|
276
|
+
* Shallow-merge into the current state — `update({ cursor })` from one call
|
|
277
|
+
* site never clobbers what another call site set, so no component has to
|
|
278
|
+
* hold the canonical whole. The merged result is validated like `set`
|
|
279
|
+
* (starting from `{}` when nothing is set, so required fields must arrive
|
|
280
|
+
* by then — `initialPresence` is the mount-order-proof way to provide
|
|
281
|
+
* them). Clear one field with `update({ field: undefined })`. The merge
|
|
282
|
+
* base is the *parsed* state, so the presence schema must parse its own
|
|
283
|
+
* output (no `transform`s — see `defineApp`'s `presence` docs).
|
|
284
|
+
*/
|
|
285
|
+
update(state: Partial<TIn>): void;
|
|
286
|
+
/** Clear this client's presence; peers see `state: null`. */
|
|
287
|
+
clear(): void;
|
|
288
|
+
/**
|
|
289
|
+
* This client's own last-set state (parsed, defaults applied — the same
|
|
290
|
+
* shape peers receive of you), or null when unset/cleared. Presence never
|
|
291
|
+
* round-trips to self: render "you" from here, not from `peers`.
|
|
292
|
+
*/
|
|
293
|
+
readonly self: TOut | null;
|
|
294
|
+
/** Synchronous snapshot of peers, self excluded. Stable identity between changes. */
|
|
295
|
+
readonly peers: ReadonlyArray<PresencePeer<TOut>>;
|
|
296
|
+
/** Notifies on any peer change and on local `set`/`update`/`clear` (so `self` is reactive too); returns an unsubscribe function. Plugs into `useSyncExternalStore`. */
|
|
297
|
+
subscribe(listener: () => void): () => void;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Constructor options for {@link SyncClient} — fixed for the instance's
|
|
301
|
+
* lifetime. Only `url`, `workspaceId`, and `app` are required; the rest
|
|
302
|
+
* tune persistence, connection behavior, presence, and the lifecycle hooks.
|
|
303
|
+
*/
|
|
304
|
+
interface SyncClientOptions<S extends AnySyncSchema = AnySyncSchema, M extends AnyMutators = AnyMutators, P extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined> {
|
|
305
|
+
/**
|
|
306
|
+
* Base URL of the sync worker — origin plus any mount path, no sync route:
|
|
307
|
+
* `wss://sync.example.com`. `http(s)://` is accepted and converted. The
|
|
308
|
+
* client appends `<pathPrefix>/<workspaceId>?clientId=<clientId>` itself,
|
|
309
|
+
* so the clientId in the URL (which the server binds at upgrade) can never
|
|
310
|
+
* diverge from the one used for confirmation matching.
|
|
311
|
+
*/
|
|
312
|
+
url: string;
|
|
313
|
+
/**
|
|
314
|
+
* The workspace to sync. Names the server-side Durable Object (via the URL
|
|
315
|
+
* path), the local IndexedDB database, and the collection ids.
|
|
316
|
+
*/
|
|
317
|
+
workspaceId: string;
|
|
318
|
+
/** URL prefix for sync routes, matching the server router's `pathPrefix`. Default: "/sync". */
|
|
319
|
+
pathPrefix?: string;
|
|
320
|
+
/**
|
|
321
|
+
* Identifies one contiguous mutation sequence — unique per SyncClient
|
|
322
|
+
* instance (per tab/session), never shared across concurrent tabs. Default:
|
|
323
|
+
* managed by the library — persisted per workspace in sessionStorage
|
|
324
|
+
* (reload continuity without cross-tab sharing), random where
|
|
325
|
+
* sessionStorage is unavailable.
|
|
326
|
+
*/
|
|
327
|
+
clientId?: string;
|
|
328
|
+
/**
|
|
329
|
+
* The shared app definition (`defineApp`) — the same object the server is
|
|
330
|
+
* configured with: schema version, table schemas, and mutator registry.
|
|
331
|
+
* Collections created via `workspaceCollectionOptions` derive their row
|
|
332
|
+
* types and runtime validation from its schema; `mutate` is typed by
|
|
333
|
+
* mutator name and validates args locally before queueing, so bad calls
|
|
334
|
+
* fail immediately instead of surfacing as a server round-trip error (the
|
|
335
|
+
* server's validation remains authoritative).
|
|
336
|
+
*/
|
|
337
|
+
app: AppDefinition<S, M, P>;
|
|
338
|
+
/**
|
|
339
|
+
* The connection credential. Browsers cannot set headers on a WebSocket
|
|
340
|
+
* upgrade, so the token travels as a `token` query parameter on the sync
|
|
341
|
+
* URL, where the worker's `authorize` hook reads it:
|
|
342
|
+
* `new URL(request.url).searchParams.get('token')`.
|
|
343
|
+
*
|
|
344
|
+
* A function is invoked fresh on **every** connection attempt — including
|
|
345
|
+
* the immediate reconnect after a 4300 refresh close — so short-lived
|
|
346
|
+
* tokens renew naturally: `authToken: () => getSession().accessToken`.
|
|
347
|
+
* It may be async; a rejection is treated like a failed connection
|
|
348
|
+
* attempt (logged, retried with backoff).
|
|
349
|
+
*/
|
|
350
|
+
authToken?: string | (() => string | Promise<string>);
|
|
351
|
+
/**
|
|
352
|
+
* This client's own view of its auth context — the same shape the server's
|
|
353
|
+
* `authorize` hook stamps (typed by the registry's `authContext` schema).
|
|
354
|
+
* Optimistic mutator runs see it as `ctx.auth` with
|
|
355
|
+
* `ctx.authoritative: false`, so permission checks written without the
|
|
356
|
+
* `authoritative` guard fail fast locally instead of surfacing as a server
|
|
357
|
+
* round-trip rejection. Validated against the app's `authContext` schema at
|
|
358
|
+
* construction when one is declared. The server's stamps remain
|
|
359
|
+
* authoritative either way.
|
|
360
|
+
*
|
|
361
|
+
* Not a credential: it is never transmitted, and the server never trusts
|
|
362
|
+
* it. (If you're arriving from Replicache or Zero, their `auth` option is
|
|
363
|
+
* the transmitted token — here that's {@link authToken}.)
|
|
364
|
+
*/
|
|
365
|
+
authContext?: AuthContextOf<M>;
|
|
366
|
+
/**
|
|
367
|
+
* Durable storage for synced rows, the cursor, and the outbox. When set,
|
|
368
|
+
* start() hydrates registered tables from the store (collections show
|
|
369
|
+
* cached data before the socket connects), hello resumes from the
|
|
370
|
+
* persisted cursor, and unconfirmed mutations survive reloads — re-shown
|
|
371
|
+
* as optimistic overlays at hydration and replayed to the server exactly
|
|
372
|
+
* once. A schema version mismatch discards the cache and bootstraps fresh.
|
|
373
|
+
*/
|
|
374
|
+
store?: SyncStore;
|
|
375
|
+
/**
|
|
376
|
+
* Shorthand for the common case: `store: new IndexedDBSyncStore(...)`
|
|
377
|
+
* built from `workspaceId` and the managed clientId. Where IndexedDB is
|
|
378
|
+
* unavailable (SSR, some workers), the client warns and runs without
|
|
379
|
+
* persistence instead of throwing. Mutually exclusive with `store`.
|
|
380
|
+
*/
|
|
381
|
+
persist?: boolean;
|
|
382
|
+
/**
|
|
383
|
+
* Connect on construction (the default). Pass false when construction and
|
|
384
|
+
* connection must be decoupled — SSR (module-scope construction would open
|
|
385
|
+
* sockets from the server; Node 22+ has a global WebSocket), tests, or
|
|
386
|
+
* apps that gate syncing on auth — and call `start()` yourself.
|
|
387
|
+
*/
|
|
388
|
+
autoStart?: boolean;
|
|
389
|
+
createSocket?: (url: string) => WebSocketLike;
|
|
390
|
+
/**
|
|
391
|
+
* Where the client's diagnostics go — reconnect/backoff decisions, dropped
|
|
392
|
+
* frames, persistence failures. Default: the console. Inject to route them
|
|
393
|
+
* into your own logging (the first place you'll want this is a bug report
|
|
394
|
+
* whose reconnect behavior you can no longer reproduce).
|
|
395
|
+
*/
|
|
396
|
+
logger?: SyncLogger;
|
|
397
|
+
/**
|
|
398
|
+
* Memory-only clients (no `store`/`persist`): reject unconfirmed mutations
|
|
399
|
+
* after this long — the mutation is discarded and TanStack DB rolls the
|
|
400
|
+
* optimistic overlay back, which is honest because nothing would survive a
|
|
401
|
+
* reload anyway. Ignored when a durable store is present: a queued mutation
|
|
402
|
+
* survives reloads and still applies when connectivity returns, so the
|
|
403
|
+
* promise stays pending until a connection confirms it (it settles early
|
|
404
|
+
* only on permanent app error, `destroy()`, or a fatal). Default: 30s.
|
|
405
|
+
*/
|
|
406
|
+
confirmTimeoutMs?: number;
|
|
407
|
+
maxBackoffMs?: number;
|
|
408
|
+
/**
|
|
409
|
+
* Keepalive ping cadence. Pings keep idle edge connections alive (the
|
|
410
|
+
* server's auto-response answers without waking the DO) and give the
|
|
411
|
+
* heartbeat a liveness signal. 0 disables the heartbeat entirely.
|
|
412
|
+
* Default: 25s.
|
|
413
|
+
*/
|
|
414
|
+
pingIntervalMs?: number;
|
|
415
|
+
/**
|
|
416
|
+
* Force a reconnect when no frame of any kind has arrived for this long —
|
|
417
|
+
* the only way to detect a half-open socket, which never emits a close
|
|
418
|
+
* event. Default: 2×pingInterval + 5s.
|
|
419
|
+
*/
|
|
420
|
+
idleTimeoutMs?: number;
|
|
421
|
+
/**
|
|
422
|
+
* Trailing-edge throttle window for `presence.set` — the client sends at
|
|
423
|
+
* most one presence frame per window, carrying the latest state, so apps
|
|
424
|
+
* call `set` at input frequency without throttle glue. Default: 100ms
|
|
425
|
+
* (Liveblocks' default, proven at far larger scale).
|
|
426
|
+
*/
|
|
427
|
+
presenceThrottleMs?: number;
|
|
428
|
+
/**
|
|
429
|
+
* The presence state announced as soon as the connection is ready, before
|
|
430
|
+
* any `presence.set` call — Liveblocks' initialPresence-at-room-entry
|
|
431
|
+
* shape. Provide identity here once (validated at construction, like
|
|
432
|
+
* `auth`) and every later call can be a bare `presence.update(partial)`:
|
|
433
|
+
* without it, an `update` firing before some component's `set` (mount
|
|
434
|
+
* order, a mousemove handler) merges into `{}` and throws on missing
|
|
435
|
+
* required fields — a race that presents as a schema error. Requires a
|
|
436
|
+
* `presence` schema in the app.
|
|
437
|
+
*/
|
|
438
|
+
initialPresence?: PresenceInputOf<P>;
|
|
439
|
+
/** Constructor-time convenience; for dynamic subscribers use `subscribeStatus`. */
|
|
440
|
+
onStatusChange?: (status: SyncStatus) => void;
|
|
441
|
+
/**
|
|
442
|
+
* One place to learn that a mutation was rejected — its optimistic overlay
|
|
443
|
+
* rolled back and this session will not apply it. Fires for every
|
|
444
|
+
* rejection `mutate` (or a collection write) would deliver: server app
|
|
445
|
+
* errors, local fail-fast (`InvalidArgs`, `UnknownMutator`,
|
|
446
|
+
* `LocalApplyFailed`), and the lifecycle codes (`Timeout`, `Stopped`,
|
|
447
|
+
* `Fatal` — filter on `error.code` if you only want server verdicts).
|
|
448
|
+
* Crucially it also fires for rejections that have **no awaiting caller**:
|
|
449
|
+
* collection `insert`/`update`/`delete` handlers, and mutations restored
|
|
450
|
+
* from the persisted outbox after a reload — without this hook, those
|
|
451
|
+
* roll back silently.
|
|
452
|
+
*
|
|
453
|
+
* ```ts
|
|
454
|
+
* onMutationRejected: (error, { name }) =>
|
|
455
|
+
* toast.error(`"${name}" was rejected: ${error.message}`)
|
|
456
|
+
* ```
|
|
457
|
+
*
|
|
458
|
+
* With the hook set, fire-and-forget calls (`void client.mutate.todos.clear()`)
|
|
459
|
+
* no longer surface unhandled-rejection noise — the rejection is considered
|
|
460
|
+
* handled here. Awaiting callers still see the rejection too.
|
|
461
|
+
*/
|
|
462
|
+
onMutationRejected?: (error: MutationError, mutation: {
|
|
463
|
+
name: string;
|
|
464
|
+
args: unknown;
|
|
465
|
+
}) => void;
|
|
466
|
+
/**
|
|
467
|
+
* Called when the server permanently rejects this client — an in-band
|
|
468
|
+
* VersionNotSupported/Unauthorized error, or a close code in the permanent
|
|
469
|
+
* band [4400, 4499] (an `authorize` rejection or an admin kick). The
|
|
470
|
+
* error carries the close `{code, reason}`, so apps can branch
|
|
471
|
+
* on the rejection slug:
|
|
472
|
+
*
|
|
473
|
+
* ```ts
|
|
474
|
+
* onFatal: (err) => {
|
|
475
|
+
* if (err.reason === 'membership-revoked') return leaveProject()
|
|
476
|
+
* if (err.reason === 'project-deleted') return cleanupAndRedirect()
|
|
477
|
+
* location.reload()
|
|
478
|
+
* }
|
|
479
|
+
* ```
|
|
480
|
+
*
|
|
481
|
+
* Default in the browser: reload the page — the designed recovery for a
|
|
482
|
+
* version mismatch is loading the new bundle — throttled to once per
|
|
483
|
+
* minute per workspace so a bad deploy window (e.g. stale web assets)
|
|
484
|
+
* degrades to a slow retry instead of a reload loop. Pass a handler to
|
|
485
|
+
* customize, or a no-op to disable.
|
|
486
|
+
*/
|
|
487
|
+
onFatal?: (error: SyncFatalError) => void;
|
|
488
|
+
/** Progress during large pokes (bootstrap): ops received so far vs. still to come. */
|
|
489
|
+
onSyncProgress?: (progress: {
|
|
490
|
+
receivedOps: number;
|
|
491
|
+
remainingOps: number;
|
|
492
|
+
}) => void;
|
|
493
|
+
}
|
|
494
|
+
//#endregion
|
|
495
|
+
//#region src/client.d.ts
|
|
496
|
+
/**
|
|
497
|
+
* The per-workspace sync client: it owns the WebSocket to the workspace's
|
|
498
|
+
* Durable Object, the outbox of unconfirmed mutations, optimistic application
|
|
499
|
+
* and rollback, presence, and reconnection with cursor catch-up. Construct
|
|
500
|
+
* one instance per workspace per tab — the clientId names one contiguous
|
|
501
|
+
* mutation sequence, so concurrent tabs must never share one (the managed
|
|
502
|
+
* default handles this) — and it connects on construction unless
|
|
503
|
+
* `autoStart: false`. The shared `defineApp` value passed in
|
|
504
|
+
* {@link SyncClientOptions} types `mutate` and the collections;
|
|
505
|
+
* `persist: true` adds the IndexedDB row mirror and a reload-surviving
|
|
506
|
+
* outbox.
|
|
507
|
+
*
|
|
508
|
+
* Attach TanStack DB collections with `createCollections` (or per-table
|
|
509
|
+
* `workspaceCollectionOptions`) for reads and optimistic writes; drive
|
|
510
|
+
* domain logic through {@link mutate}, which runs the shared mutator locally
|
|
511
|
+
* for an instant overlay and settles on the server's verdict. To switch
|
|
512
|
+
* workspaces, {@link destroy} this client and construct a fresh one.
|
|
513
|
+
*
|
|
514
|
+
* @example
|
|
515
|
+
* ```ts
|
|
516
|
+
* import { SyncClient, createCollections } from '@cf-sync/client'
|
|
517
|
+
* import { app } from './schema' // the shared defineApp value
|
|
518
|
+
*
|
|
519
|
+
* const client = new SyncClient({
|
|
520
|
+
* url: 'wss://sync.example.com', // ws://localhost:8787 in dev
|
|
521
|
+
* workspaceId: 'my-first-workspace',
|
|
522
|
+
* app,
|
|
523
|
+
* persist: true, // IndexedDB mirror + durable offline outbox
|
|
524
|
+
* })
|
|
525
|
+
*
|
|
526
|
+
* const { todos } = createCollections(client)
|
|
527
|
+
*
|
|
528
|
+
* // Optimistic local write, synced as a full-row mutation:
|
|
529
|
+
* todos.insert({ id: crypto.randomUUID(), title: 'ship it' })
|
|
530
|
+
*
|
|
531
|
+
* // Typed intent mutation — instant locally, authoritative on the server:
|
|
532
|
+
* await client.mutate.todo.toggle({ id })
|
|
533
|
+
* ```
|
|
534
|
+
*/
|
|
535
|
+
declare class SyncClient<S extends AnySyncSchema = AnySyncSchema, M extends AnyMutators = AnyMutators, P extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined> {
|
|
536
|
+
#private;
|
|
537
|
+
/**
|
|
538
|
+
* Applies a named mutation optimistically and queues it for the server.
|
|
539
|
+
* Callable two ways — `mutate.todos.clearCompleted(args)` (dots in mutator
|
|
540
|
+
* names are namespaces; names and args are typed from the app's registry)
|
|
541
|
+
* or `mutate('todos.clearCompleted', args)` — both identical at runtime.
|
|
542
|
+
* Resolves when the server confirms the mutation (the client's LMID reaches
|
|
543
|
+
* the mutation's id), rejects on permanent app error or timeout. Args are
|
|
544
|
+
* validated locally before queueing (the wire still carries the original
|
|
545
|
+
* args — the server's parse is authoritative).
|
|
546
|
+
*
|
|
547
|
+
* When collections are attached (`createCollections` /
|
|
548
|
+
* `workspaceCollectionOptions`), the shared mutator's `apply` runs locally
|
|
549
|
+
* first against the collections' current view, and its writes land as one
|
|
550
|
+
* atomic optimistic overlay: visible immediately, swapped for the server's
|
|
551
|
+
* authoritative patch on confirm, rolled back together on rejection. The
|
|
552
|
+
* overlay is a frozen prediction — a remote change arriving mid-flight
|
|
553
|
+
* rebases the *originally computed* writes, and the confirm patch replaces
|
|
554
|
+
* them with the server's authoritative result (which ran against current
|
|
555
|
+
* state). A mutator that throws `AppError` locally rejects immediately and
|
|
556
|
+
* queues nothing; one that touches a table without an attached collection
|
|
557
|
+
* skips the overlay (warns once) but still reaches the server.
|
|
558
|
+
*
|
|
559
|
+
* Settlement is honest about durability: with a durable store
|
|
560
|
+
* (`persist`/`store`) the promise stays *pending* while offline — the
|
|
561
|
+
* mutation is queued durably and applies when connectivity returns, so a
|
|
562
|
+
* rejection always means the mutation will not apply (permanent app error,
|
|
563
|
+
* `destroy()`, or fatal). Only memory-only clients reject with `Timeout` after
|
|
564
|
+
* `confirmTimeoutMs`, discarding the mutation along with its overlay.
|
|
565
|
+
*/
|
|
566
|
+
readonly mutate: Mutate<M>;
|
|
567
|
+
/** Ephemeral peer state on the sync socket — see {@link PresenceApi}. */
|
|
568
|
+
readonly presence: PresenceApi<PresenceInputOf<P>, PresenceStateOf<P>>;
|
|
569
|
+
constructor(opts: SyncClientOptions<S, M, P>);
|
|
570
|
+
/** The current connection status — see {@link SyncStatus}; subscribe to changes via {@link subscribeStatus}. */
|
|
571
|
+
get status(): SyncStatus;
|
|
572
|
+
/**
|
|
573
|
+
* Whether locally cached data has been restored and collections are ready
|
|
574
|
+
* to render — the signal offline-first UIs gate their first paint on.
|
|
575
|
+
*
|
|
576
|
+
* `status` cannot answer this: it reads `connecting` both before and after
|
|
577
|
+
* hydration, so an offline launch holding a full cache looks exactly like
|
|
578
|
+
* one holding nothing. Nor can collection contents — an empty collection
|
|
579
|
+
* mid-hydration is indistinguishable from a genuinely empty workspace.
|
|
580
|
+
*
|
|
581
|
+
* True only when there was a cached snapshot to restore. It stays false
|
|
582
|
+
* when no store is configured, when the store is empty (a first launch),
|
|
583
|
+
* when the cache was discarded because it targets a different app version,
|
|
584
|
+
* and when the store failed to load — in each of those cases there is
|
|
585
|
+
* nothing cached to paint, and the UI should wait for the first sync:
|
|
586
|
+
*
|
|
587
|
+
* ```tsx
|
|
588
|
+
* // Render cached rows immediately when offline, otherwise wait for sync.
|
|
589
|
+
* const status = useSyncStatus(client)
|
|
590
|
+
* const hydrated = useHydrated(client)
|
|
591
|
+
* if (status !== 'synced' && !hydrated) return <Spinner />
|
|
592
|
+
* ```
|
|
593
|
+
*
|
|
594
|
+
* Subscribe to the transition via {@link subscribeHydrated}, or await
|
|
595
|
+
* {@link whenHydrated} outside React.
|
|
596
|
+
*/
|
|
597
|
+
get hydrated(): boolean;
|
|
598
|
+
/**
|
|
599
|
+
* Resolves when hydration settles, with the value {@link hydrated} takes —
|
|
600
|
+
* true if a cached snapshot was restored, false if there was nothing to
|
|
601
|
+
* restore. The imperative form of the same signal, for gating a first
|
|
602
|
+
* render outside React:
|
|
603
|
+
*
|
|
604
|
+
* ```ts
|
|
605
|
+
* if (await client.whenHydrated) renderFromCache()
|
|
606
|
+
* ```
|
|
607
|
+
*
|
|
608
|
+
* A client constructed with `autoStart: false` settles this when `start()`
|
|
609
|
+
* runs, or with false if it is destroyed first — it never hangs past the
|
|
610
|
+
* client's life.
|
|
611
|
+
*/
|
|
612
|
+
get whenHydrated(): Promise<boolean>;
|
|
613
|
+
/** The last server cursor this client applied, or null before the first sync. */
|
|
614
|
+
get cursor(): Cursor | null;
|
|
615
|
+
/** The workspace this client syncs, as passed at construction. */
|
|
616
|
+
get workspaceId(): string;
|
|
617
|
+
/** The resolved clientId — the configured one, or the library-managed default. */
|
|
618
|
+
get clientId(): string;
|
|
619
|
+
/** The app definition this client was constructed with. */
|
|
620
|
+
get app(): AppDefinition<S, M, P>;
|
|
621
|
+
/** The table schema from the app definition (used by collections). */
|
|
622
|
+
get schema(): S;
|
|
623
|
+
/**
|
|
624
|
+
* Subscribes to status changes; returns an unsubscribe function. An arrow
|
|
625
|
+
* property, so it can be passed around unbound — it plugs directly into
|
|
626
|
+
* React: `useSyncExternalStore(client.subscribeStatus, () => client.status)`.
|
|
627
|
+
*/
|
|
628
|
+
readonly subscribeStatus: (listener: (status: SyncStatus) => void) => (() => void);
|
|
629
|
+
/**
|
|
630
|
+
* Subscribes to {@link hydrated} changes; returns an unsubscribe function.
|
|
631
|
+
* Fires at most once per client — hydration settles one way and stays
|
|
632
|
+
* settled. An arrow property, so it plugs straight into React:
|
|
633
|
+
* `useSyncExternalStore(client.subscribeHydrated, () => client.hydrated)`.
|
|
634
|
+
*/
|
|
635
|
+
readonly subscribeHydrated: (listener: (hydrated: boolean) => void) => (() => void);
|
|
636
|
+
/**
|
|
637
|
+
* Registers a table's hooks. Returns an unregister function. Registering
|
|
638
|
+
* after the first sync completes forces a full resync, since the engine
|
|
639
|
+
* keeps no mirror of already-applied data — register all collections
|
|
640
|
+
* before meaningful traffic to avoid the extra round-trip.
|
|
641
|
+
*/
|
|
642
|
+
registerTable(tbl: string, hooks: TableHooks): () => void;
|
|
643
|
+
/**
|
|
644
|
+
* Attaches a table's collection applier so `mutate` can run the shared
|
|
645
|
+
* mutator locally for an instant optimistic effect (adapter-facing, like
|
|
646
|
+
* `registerTable`; `workspaceCollectionOptions` and `createCollections`
|
|
647
|
+
* call it for you). Re-registering a table replaces its applier. The
|
|
648
|
+
* runner supplies the atomic-transaction primitive; every adapter passes
|
|
649
|
+
* an equivalent one, so the last registration wins.
|
|
650
|
+
*/
|
|
651
|
+
registerApplier(tbl: string, applier: TableApplier, runner: IntentTransactionRunner): void;
|
|
652
|
+
/**
|
|
653
|
+
* Sends one binary-lane frame — the client half of the extension seam,
|
|
654
|
+
* used by add-ons like `createYjsFields`. Fire-and-forget
|
|
655
|
+
* like every frame on this socket: a broken socket surfaces through the
|
|
656
|
+
* close event, and binary-lane consumers re-sync on the next ready
|
|
657
|
+
* transition (`subscribeStatus` reaching 'synced'), so nothing is lost.
|
|
658
|
+
* The server only accepts binary frames once the connection is ready.
|
|
659
|
+
*/
|
|
660
|
+
sendBinary(bytes: Uint8Array): void;
|
|
661
|
+
/**
|
|
662
|
+
* Subscribes to inbound binary-lane frames; returns an unsubscribe
|
|
663
|
+
* function. Frames are delivered as-received — framing and dispatch belong
|
|
664
|
+
* to the add-on (see `@cf-sync/protocol`'s field-frame helpers).
|
|
665
|
+
*/
|
|
666
|
+
onBinary(listener: (bytes: Uint8Array) => void): () => void;
|
|
667
|
+
/** Begins hydration and connection. Called from the constructor unless `autoStart: false`; idempotent. */
|
|
668
|
+
start(): void;
|
|
669
|
+
/**
|
|
670
|
+
* Registers a teardown callback run (and awaited) by {@link destroy} —
|
|
671
|
+
* how resources created against this client tie their lifetime to it
|
|
672
|
+
* (`createCollections` registers each collection's cleanup here). Returns
|
|
673
|
+
* an unregister function. Apps rarely call this directly.
|
|
674
|
+
*/
|
|
675
|
+
onDestroy(callback: () => void | Promise<void>): () => void;
|
|
676
|
+
/**
|
|
677
|
+
* The one teardown, idempotent. Synchronously: closes the socket, cancels
|
|
678
|
+
* timers, and rejects every unconfirmed `mutate` promise with `Stopped`
|
|
679
|
+
* (all before the first await, so fire-and-forget `void client.destroy()`
|
|
680
|
+
* is safe in unload paths). Then: runs every {@link onDestroy} callback
|
|
681
|
+
* (collections from `createCollections` clean up here) and closes the
|
|
682
|
+
* store's connection when it has a `close`. The instance is inert
|
|
683
|
+
* afterwards — `start()` throws, `mutate` rejects with `Stopped` — and
|
|
684
|
+
* constructing a fresh SyncClient (plus fresh collections) for the same or
|
|
685
|
+
* another workspace is the supported way to (re)connect: the pattern for
|
|
686
|
+
* workspace-per-project apps switching projects. State is not lost: the
|
|
687
|
+
* durable store keeps its rows and outbox for the next client, and this
|
|
688
|
+
* tab's managed clientId is reused, so mutations queued offline still
|
|
689
|
+
* replay exactly once.
|
|
690
|
+
*/
|
|
691
|
+
destroy(): Promise<void>;
|
|
692
|
+
/**
|
|
693
|
+
* Subscribes to permanent mutation rejections — the attach-later
|
|
694
|
+
* counterpart to the `onMutationRejected` constructor option, for layers
|
|
695
|
+
* that mount after the client exists (a toast system, an error boundary).
|
|
696
|
+
* Same payload and same "considered handled" semantics: a mutation issued
|
|
697
|
+
* while at least one listener (or the constructor option) is attached has
|
|
698
|
+
* its rejection routed here instead of tripping unhandled-rejection
|
|
699
|
+
* reporting. Both surfaces fire when both are set. Returns an unsubscribe
|
|
700
|
+
* function.
|
|
701
|
+
*/
|
|
702
|
+
onMutationRejected(listener: (error: MutationError, mutation: {
|
|
703
|
+
name: string;
|
|
704
|
+
args: unknown;
|
|
705
|
+
}) => void): () => void;
|
|
706
|
+
/**
|
|
707
|
+
* The adapter's raw path (see `RAW_MUTATE`): validate and enqueue, no
|
|
708
|
+
* speculative local run — collection mutation handlers already *are* the
|
|
709
|
+
* optimistic effect.
|
|
710
|
+
*/
|
|
711
|
+
[RAW_MUTATE](name: string, args: unknown): Promise<void>;
|
|
712
|
+
}
|
|
713
|
+
//#endregion
|
|
714
|
+
export { SyncFatalError as S, Mutate as _, SyncLogger as a, MutationErrorCode as b, TableHooks as c, MemorySyncStore as d, PersistedOutboxEntry as f, SyncStore as g, PokePersist as h, SyncClientOptions as i, TableWriteOp as l, PersistedState as m, IntentTransactionRunner as n, SyncStatus as o, PersistedRowOp as p, PresenceApi as r, TableApplier as s, SyncClient as t, WebSocketLike as u, MutateNamespace as v, SyncFatalCode as x, MutationError as y };
|