@lunora/client 1.0.0-alpha.18 → 1.0.0-alpha.181

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.
Files changed (89) hide show
  1. package/README.md +16 -3
  2. package/dist/auth/index.d.mts +43 -12
  3. package/dist/auth/index.d.ts +43 -12
  4. package/dist/auth/index.mjs +1 -60
  5. package/dist/index.d.mts +808 -261
  6. package/dist/index.d.ts +808 -261
  7. package/dist/index.mjs +1 -15
  8. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  10. package/dist/packem_shared/LunoraClient-DnqTxmHd.mjs +1 -0
  11. package/dist/packem_shared/OfflineQueue-BWamzR6p.mjs +1 -0
  12. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  13. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  14. package/dist/packem_shared/SubscriptionRegistry-C3kLqped.mjs +1 -0
  15. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  16. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  17. package/dist/packem_shared/applyDelta-CIjpZ5h9.mjs +1 -0
  18. package/dist/packem_shared/createAsyncStoragePersistence-CeUW9NTj.mjs +1 -0
  19. package/dist/packem_shared/createAsyncStorageQueryCache-Dpszf7UD.mjs +1 -0
  20. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  21. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  22. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  25. package/dist/packem_shared/createLocalStore-0ARUZ892.mjs +1 -0
  26. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  27. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  28. package/dist/packem_shared/createServerClient-DApE8zg1.mjs +1 -0
  29. package/dist/packem_shared/createSnapshotPrecondition-5GQ_5fFu.mjs +1 -0
  30. package/dist/packem_shared/delta-merge-D_5ChS-C.mjs +1 -0
  31. package/dist/packem_shared/deserializePreloaded-Bffy70Wm.mjs +1 -0
  32. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  33. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  34. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  35. package/dist/packem_shared/httpStream-v4etRV7m.mjs +9 -0
  36. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  37. package/dist/packem_shared/local-store-DDppw8Qr.mjs +1 -0
  38. package/dist/packem_shared/lunora-client.d-CUpV_t_w.d.ts +4731 -0
  39. package/dist/packem_shared/lunora-client.d-gPd6tie1.d.mts +4731 -0
  40. package/dist/packem_shared/offline-queue-D_fr-uQ3.mjs +1 -0
  41. package/dist/packem_shared/preload.d-CyjUwQEv.d.ts +21 -0
  42. package/dist/packem_shared/preload.d-DECTCs0m.d.mts +21 -0
  43. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  44. package/dist/packem_shared/replay-CXXDZ1_h.mjs +1 -0
  45. package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
  46. package/dist/packem_shared/wire-codec-BeIi1K-T.mjs +1 -0
  47. package/dist/packem_shared/wire-key-DCPYV4t8.mjs +1 -0
  48. package/dist/pagination/index.d.mts +42 -42
  49. package/dist/pagination/index.d.ts +42 -42
  50. package/dist/pagination/index.mjs +1 -61
  51. package/dist/query/index.d.mts +111 -43
  52. package/dist/query/index.d.ts +111 -43
  53. package/dist/query/index.mjs +1 -1
  54. package/dist/service.d.mts +49 -0
  55. package/dist/service.d.ts +49 -0
  56. package/dist/service.mjs +1 -0
  57. package/dist/ssr/index.d.mts +109 -79
  58. package/dist/ssr/index.d.ts +109 -79
  59. package/dist/ssr/index.mjs +1 -4
  60. package/dist/upload.d.mts +35 -0
  61. package/dist/upload.d.ts +35 -0
  62. package/dist/upload.mjs +1 -0
  63. package/package.json +14 -2
  64. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  65. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  66. package/dist/packem_shared/LunoraClient-BECgZjx4.mjs +0 -3413
  67. package/dist/packem_shared/OfflineQueue-GGYJRmhF.mjs +0 -1
  68. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  69. package/dist/packem_shared/SubscriptionRegistry-Cxr70og-.mjs +0 -1
  70. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  71. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  72. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  73. package/dist/packem_shared/createInMemoryPersistence-Ds7z8n8d.mjs +0 -119
  74. package/dist/packem_shared/createInMemoryQueryCache-iWtKPrid.mjs +0 -152
  75. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +0 -1
  76. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  77. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  78. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  79. package/dist/packem_shared/createServerClient-Cet4TATX.mjs +0 -11
  80. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  81. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  82. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +0 -111
  83. package/dist/packem_shared/lunora-client.d-Dy4neKF6.d.mts +0 -2526
  84. package/dist/packem_shared/lunora-client.d-Dy4neKF6.d.ts +0 -2526
  85. package/dist/packem_shared/offline-queue-B9vfdSqp.mjs +0 -170
  86. package/dist/packem_shared/preload.d-BQaCmS5J.d.mts +0 -20
  87. package/dist/packem_shared/preload.d-DI-5eqHP.d.ts +0 -20
  88. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  89. package/dist/packem_shared/subscription-DoyO04-2.mjs +0 -65
@@ -0,0 +1,4731 @@
1
+ import { LunoraErrorCodeInput, LunoraErrorCode } from '@lunora/errors';
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.mjs";
3
+ import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
4
+ /**
5
+ * Reactive key-value store for local-only client state.
6
+ *
7
+ * Unlike a server {@link SubscriptionState} (which tracks a live WS connection,
8
+ * an `acked` flag, `serverBase`, optimistic layers, and the full subscription
9
+ * machinery), a `ClientQueryRef` is purely local — no server round-trip, no
10
+ * WebSocket, no persistence. It exists so framework adapters can offer a
11
+ * `useClientQuery` hook whose values survive component remounts and are shared
12
+ * across every consumer of the same ref, with none of the ceremony or coupling
13
+ * of a dedicated context provider.
14
+ *
15
+ * The store lives inside `LunoraClient` (a private field) and is surfaced through
16
+ * `client.getClientQuery(ref)` / `setClientQuery(ref, value)` /
17
+ * `subscribeClientQuery(ref, callback)`.
18
+ */
19
+ /** Opaque handle for a typed client-local query slot. */
20
+ interface ClientQueryRef<T = unknown> {
21
+ /** Default value when no value has been set explicitly. */
22
+ readonly defaultValue: T;
23
+ /** Stable identity for the slot. Must be unique within a client instance. */
24
+ readonly key: string;
25
+ }
26
+ /**
27
+ * Create a typed {@link ClientQueryRef}. Call once per slot at module scope
28
+ * (or inside a component module) — the ref object is the stable identity.
29
+ * @example
30
+ * ```ts
31
+ * // lunora/client-queries.ts
32
+ * import { createClientQuery } from "@lunora/client";
33
+ *
34
+ * export const sidebarOpen = createClientQuery("sidebarOpen", true);
35
+ * export const selectedMessageId = createClientQuery("selectedMessageId", undefined as string | undefined);
36
+ * ```
37
+ */
38
+ declare const createClientQuery: <T>(key: string, defaultValue: T) => ClientQueryRef<T>;
39
+ /**
40
+ * Typed reference to an HTTP-SSE stream route (`httpRoute.<verb>(path).stream()`)
41
+ * emitted by `@lunora/codegen` as `httpStreams.<namespace>.<name>`.
42
+ *
43
+ * Distinct from {@link FunctionReference}: this is the **HTTP-SSE route stream**
44
+ * (opened with `fetch` + `ReadableStream` against the route's own URL), not the
45
+ * WS procedure stream (`kind: "stream"`). At runtime it carries the HTTP verb
46
+ * and the route path; the phantom marker carries the chunk / searchParams /
47
+ * params types so `httpStream` (and the framework hooks over it) infer the
48
+ * chunk type end-to-end.
49
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
50
+ */
51
+ interface HttpStreamRef<Chunk = unknown, SearchParams = unknown, Params = unknown> {
52
+ /**
53
+ * Phantom marker carrying the `Chunk`/`SearchParams`/`Params` type
54
+ * parameters for inference. Never present at runtime; declared in a
55
+ * covariant (output) position so a concrete reference stays assignable to
56
+ * a widened one.
57
+ */
58
+ readonly __lunoraHttpStream?: {
59
+ chunk: Chunk;
60
+ params: Params;
61
+ searchParams: SearchParams;
62
+ };
63
+ /** HTTP verb the route binds to (uppercased), e.g. `"GET"`. */
64
+ readonly method: string;
65
+ /** The route path as declared, e.g. `/api/tokens/:id` — `:name` segments are filled from `params`. */
66
+ readonly path: string;
67
+ }
68
+ /**
69
+ * The call-side args of an HTTP-SSE stream route: `:name` path params plus URL query params.
70
+ * @experimental Part of the HTTP-SSE stream surface.
71
+ */
72
+ interface HttpStreamCallArgs<SearchParams = unknown, Params = unknown> {
73
+ /** Values for the route path's `:name` segments. */
74
+ params?: Params;
75
+ /** URL query params, appended to the request URL (undefined entries are skipped). */
76
+ searchParams?: SearchParams;
77
+ }
78
+ /**
79
+ * Extract the chunk type from a {@link HttpStreamRef}.
80
+ * @experimental Part of the HTTP-SSE stream surface.
81
+ */
82
+ type HttpStreamChunkOf<R> = R extends HttpStreamRef<infer Chunk, infer _S, infer _P> ? Chunk : never;
83
+ /**
84
+ * Extract the call-side args type from a {@link HttpStreamRef}.
85
+ * @experimental Part of the HTTP-SSE stream surface.
86
+ */
87
+ type HttpStreamArgsOf<R> = R extends HttpStreamRef<infer _C, infer S, infer P> ? HttpStreamCallArgs<S, P> : never;
88
+ type Unsubscribe = () => void;
89
+ /**
90
+ * Serializable result of `preloadQuery`. Produced on the server during SSR,
91
+ * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
92
+ * client so the first render shows the server value with no loading flash
93
+ * before a live subscription attaches. Every field survives `JSON.stringify`.
94
+ */
95
+ interface Preloaded<T = unknown> {
96
+ readonly __lunoraPreloaded: true;
97
+ readonly args: Record<string, unknown>;
98
+ readonly functionPath: string;
99
+ readonly shardKey?: string;
100
+ readonly value: T;
101
+ }
102
+ /**
103
+ * Pluggable storage for the `x-d1-bookmark` value used to provide
104
+ * read-your-writes between a mutation and subsequent queries.
105
+ */
106
+ interface BookmarkStorage {
107
+ get: () => string | null;
108
+ set: (value: string | null) => void;
109
+ }
110
+ interface ReconnectOptions {
111
+ initialDelayMs?: number;
112
+ jitter?: boolean;
113
+ maxDelayMs?: number;
114
+ }
115
+ /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
116
+ type PersistenceOperation = "append" | "clear" | "load" | "remove" | "replace";
117
+ /** Context handed to a persistence-error handler. */
118
+ interface PersistenceErrorContext {
119
+ readonly error: unknown;
120
+ /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
121
+ readonly mutationId?: string;
122
+ readonly operation: PersistenceOperation;
123
+ }
124
+ interface OfflineQueueOptions {
125
+ maxItems?: number;
126
+ /**
127
+ * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
128
+ * exceeded). Without a handler, failures are logged via `console.warn` so they
129
+ * are never fully silent. Note: a failed `append` means the write is queued in
130
+ * memory but NOT durable — it will not survive a reload.
131
+ */
132
+ onPersistenceError?: (context: PersistenceErrorContext) => void;
133
+ /**
134
+ * Queue mutations issued before a shard's first successful WebSocket
135
+ * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
136
+ * `mutation()`) queues only when the targeted shard has been connected at
137
+ * least once (`wasEverConnected`), so the registry / resubscribe handshake
138
+ * has run. Set this to `true` for offline-first apps that want to enqueue
139
+ * writes on the very first session before the WS is up.
140
+ */
141
+ queueBeforeFirstConnect?: boolean;
142
+ }
143
+ /**
144
+ * Serializable shape of an offline mutation, durably stored by a
145
+ * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
146
+ * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
147
+ * persisted — a restored mutation is replayed with no original awaiter.
148
+ */
149
+ interface PersistedMutation {
150
+ args: Record<string, unknown>;
151
+ /**
152
+ * The CDC cursor this write was composed against, persisted so a replay —
153
+ * including one after a reload, days later — is still judged against what its
154
+ * author could actually see. Consumed only by `.dropStalePatches()` tables.
155
+ *
156
+ * Persisting it is the entire point of the feature. Re-deriving a baseline at
157
+ * replay time would read the cursor the client has ADVANCED to while the write
158
+ * sat in the queue, which is the newer state the write must be compared
159
+ * against — so the stale write would always look fresh and always clobber.
160
+ *
161
+ * Absent on records written by older client versions, and on a client with no
162
+ * live subscription to take a cursor from; both replay with no baseline, which
163
+ * applies the write unchanged.
164
+ */
165
+ baselineSeq?: number;
166
+ /**
167
+ * The client id that queued this write, persisted so a replay after a reload
168
+ * lands in the SAME server-side dedup namespace it was issued under. The
169
+ * standalone client's own `clientId` is minted per session, so replaying under
170
+ * the live one would miss the `__idempotency` row for an anonymous caller and
171
+ * re-run a write the server already committed. Absent on records written by
172
+ * older client versions, which replay under the live id.
173
+ */
174
+ clientId?: string;
175
+ functionPath: string;
176
+ id: string;
177
+ /**
178
+ * Issuing identity fingerprint, persisted so a hydrated write replays only
179
+ * under the identity that queued it (`null` = queued while signed out).
180
+ * Absent on records written by older client versions, which replay under
181
+ * the ambient identity for back-compat.
182
+ */
183
+ identity?: string | null;
184
+ shardKey?: string;
185
+ /**
186
+ * App/schema version stamped at enqueue (from `LunoraClientOptions.persistenceVersion`).
187
+ * On hydrate, a record whose `version` doesn't match the current one is dropped
188
+ * and purged rather than replayed — so a write persisted by an older deploy
189
+ * (with a now-changed function signature) can't replay against the new schema.
190
+ * Absent when no `persistenceVersion` is configured (no version gating).
191
+ */
192
+ version?: string;
193
+ }
194
+ /**
195
+ * Durable store for the offline mutation queue. The default client keeps the
196
+ * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
197
+ * makes queued writes survive a page reload. Implementations must preserve FIFO
198
+ * (enqueue) order in `PersistenceAdapter.load`.
199
+ *
200
+ * Replay semantics are at-least-once: a mutation is removed only after the
201
+ * server confirms (or rejects) it, so a crash between commit and `remove` can
202
+ * replay it again on the next load.
203
+ */
204
+ interface PersistenceAdapter {
205
+ /** Append a mutation to durable storage (called on enqueue). */
206
+ append: (mutation: PersistedMutation) => Promise<void>;
207
+ /** Drop every persisted mutation (e.g. on logout). */
208
+ clear: () => Promise<void>;
209
+ /** Load all persisted mutations in FIFO order — called once at startup. */
210
+ load: () => Promise<PersistedMutation[]>;
211
+ /** Remove a mutation by id once it has been replayed (resolved or rejected). */
212
+ remove: (id: string) => Promise<void>;
213
+ /**
214
+ * Overwrite an already-persisted mutation IN PLACE, keeping its position in
215
+ * FIFO order. Used when a queued write's identity stamp is rewritten after a
216
+ * sign-in / sign-out.
217
+ *
218
+ * Must be atomic: a `remove` + `append` pair has a window where a process
219
+ * stop leaves the mutation in no durable store at all, and the in-memory
220
+ * entry has already advanced, so a reload loses the write outright. It also
221
+ * moved the record to the BACK of the queue, replaying it out of the order
222
+ * it was issued in. Implementations do the whole swap under one transaction
223
+ * (or one serialized blob write).
224
+ *
225
+ * A mutation whose id is not present is left alone — the record was drained
226
+ * concurrently and re-inserting it would replay a settled write.
227
+ */
228
+ replace: (mutation: PersistedMutation) => Promise<void>;
229
+ }
230
+ /**
231
+ * One write handed to an {@link OutboxSink}. Mirrors {@link PersistedMutation}
232
+ * plus the custom-mutator identity (`clientId`/`mutationId`/`idempotencyKey`)
233
+ * the durable outbox needs to dedupe and watermark replays.
234
+ */
235
+ interface OutboxMutation {
236
+ args: Record<string, unknown>;
237
+ /**
238
+ * The CDC cursor this write was composed against — see
239
+ * {@link PersistedMutation.baselineSeq}, whose contract this mirrors.
240
+ *
241
+ * A sink MUST persist it and hand it back unchanged on replay. This is the
242
+ * canonical statement of that rule for the durable path; every other site
243
+ * that carries the field points here. Re-deriving one at replay time reads
244
+ * the cursor the client has since advanced to — the newer state the write is
245
+ * supposed to be judged against — so a stale write always looks fresh and
246
+ * always clobbers.
247
+ *
248
+ * `undefined` when the client has no live subscription to take a cursor from,
249
+ * which replays the write unchanged.
250
+ */
251
+ baselineSeq?: number;
252
+ /** Stable per-client id; pairs with {@link OutboxMutation.mutationId} as `idempotencyKey`. */
253
+ clientId: string;
254
+ functionPath: string;
255
+ /**
256
+ * `${clientId}:${mutationId}`, or the caller's own `mutationId` when it passed
257
+ * one (an `importRows` chunk) — sent as `x-lunora-mutation-id` so a replay is
258
+ * server-idempotent.
259
+ */
260
+ idempotencyKey: string;
261
+ /** Issuing identity fingerprint (`null` = signed out); drives the sink's identity guard. */
262
+ identity: string | null;
263
+ /** Monotonic per-client mutation id, backing the server `__client_watermark`. */
264
+ mutationId: number;
265
+ /**
266
+ * Roll this write's optimistic patch back. The sink's owner invokes it when
267
+ * the replay reaches a PERMANENT verdict (a coded rejection, an identity
268
+ * drop) — never on a transient failure it will retry, and never on success.
269
+ *
270
+ * Without it a rejected replay leaves its predicted value on screen until an
271
+ * unrelated frame or a reload: the client drops the layer when it hands the
272
+ * write over (it cannot cursor-confirm through this path) and has no other
273
+ * signal that the write died. Absent when the write carried no optimistic
274
+ * update, and safe to ignore — a sink that never calls it behaves as before.
275
+ */
276
+ onRejected?: () => void;
277
+ shardKey?: string;
278
+ }
279
+ /**
280
+ * Pluggable durable outbox seam. When set on {@link LunoraClientOptions.outbox},
281
+ * the client delegates offline write durability + at-least-once replay to this
282
+ * sink instead of its built-in {@link PersistenceAdapter}-backed `OfflineQueue`.
283
+ * `@lunora/db` supplies the blessed implementation (`createExecutorOutboxSink`,
284
+ * backed by the TanStack `OfflineExecutor`); the interface itself is
285
+ * dependency-free so `@lunora/client` stays TanStack-free.
286
+ */
287
+ interface OutboxSink {
288
+ /**
289
+ * Persist and schedule a write for replay. Rejects with an
290
+ * `OFFLINE_QUEUE_OVERFLOW`-coded error when the sink's cap is exceeded, so
291
+ * the caller can surface back-pressure to the issuing mutation.
292
+ */
293
+ enqueue: (mutation: OutboxMutation) => Promise<void>;
294
+ /**
295
+ * Whether the sink still holds writes that have not replayed. The client
296
+ * consults this before sending a fresh mutation live, so a new write can
297
+ * never overtake an older one the sink is still holding (a write deferred
298
+ * because its identity isn't re-confirmed yet is held indefinitely, with
299
+ * nothing for the client's flush barrier to wait on).
300
+ *
301
+ * Optional: a sink that cannot answer never engages the ordering gate, so
302
+ * such a sink behaves exactly as before.
303
+ */
304
+ pending?: () => boolean;
305
+ }
306
+ /**
307
+ * One persisted query result in the durable read cache (Pillar 2). Keyed in the
308
+ * store by `shardKey + functionPath + argsKey`; the record carries everything
309
+ * needed to render offline on reload and to resume the live subscription.
310
+ */
311
+ interface CachedQuery {
312
+ /**
313
+ * Token-hash fingerprint of the bearer the value was cached under, when the
314
+ * entry was written by the identity the client currently advertises.
315
+ *
316
+ * The second half of the identity gate, and the half that makes the cache
317
+ * usable at all for a bearer-token app. `identity` settles on the resolved
318
+ * subject (`subj:<id>`) once the session resolves, but on the NEXT reload
319
+ * every adapter can only offer the stored token first — the subject arrives
320
+ * a round trip later, and offline it never arrives at all. Matching the
321
+ * credential the entry was written under is what lets the seed happen before
322
+ * (or without) that round trip. Absent when signed out, or when the value
323
+ * arrived over a socket authenticated as someone else.
324
+ */
325
+ credential?: string;
326
+ /**
327
+ * Issuing identity fingerprint (same shape the offline queue stamps). A
328
+ * cached value only hydrates when it matches the current identity, so a
329
+ * signed-out cache never leaks into a new session.
330
+ *
331
+ * `null` = cached by a client that had no subject to name — an app with no
332
+ * auth at all, or one the server answered "no session" to. It is never
333
+ * written while a session resolve is in flight, because a `null` written
334
+ * there belongs to a user the client was about to name, and every
335
+ * unidentified session would match it.
336
+ */
337
+ identity: string | null;
338
+ /**
339
+ * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
340
+ * on reconnect so the server can resume instead of re-snapshotting. Absent
341
+ * when the value predates CDC / no cursor was advertised.
342
+ */
343
+ serverCursor?: number;
344
+ /**
345
+ * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
346
+ * on reconnect so the server only resumes when the client is still on the
347
+ * same changelog timeline. Absent when no epoch was advertised.
348
+ */
349
+ serverEpoch?: string;
350
+ /** Wall-clock millis the value was written — drives LRU eviction. */
351
+ ts: number;
352
+ /** The full query result last seen from the server. */
353
+ value: unknown;
354
+ /**
355
+ * App/schema version stamped when persisted (from `LunoraClientOptions.persistenceVersion`).
356
+ * A cached value whose `version` doesn't match the current one is not hydrated —
357
+ * so a result of a now-changed shape from an older deploy can't render. Absent
358
+ * when no `persistenceVersion` is configured (no version gating).
359
+ */
360
+ version?: string;
361
+ }
362
+ /** A stored read-cache row: the {@link CachedQuery} plus the key it is stored under. */
363
+ interface StoredQuery extends CachedQuery {
364
+ key: string;
365
+ }
366
+ /**
367
+ * Durable store for the client read cache (Pillar 2): query results survive a
368
+ * reload so reads hydrate from disk and render immediately while the socket
369
+ * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
370
+ * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
371
+ * shape over the same IndexedDB plumbing.
372
+ */
373
+ interface QueryCacheAdapter {
374
+ /** Drop every cached query (e.g. on logout / identity change). */
375
+ clear: () => Promise<void>;
376
+ /** Load every cached query — called once at startup to hydrate reads. */
377
+ load: () => Promise<StoredQuery[]>;
378
+ /** Upsert one cached query by key (called when a subscription value advances). */
379
+ put: (key: string, entry: CachedQuery) => Promise<void>;
380
+ /** Remove one cached query by key. */
381
+ remove: (key: string) => Promise<void>;
382
+ }
383
+ /**
384
+ * Resolves the WS `?token=` credential fresh at every (re)connect — the channel
385
+ * for short-lived tokens (e.g. the ephemeral admin sub-token the worker mints
386
+ * at `POST /_lunora/admin/ws-token`) instead of a static secret in the URL.
387
+ * May return the token synchronously or as a Promise; returning `undefined`
388
+ * connects without a token. A thrown error / rejected Promise fails that
389
+ * connect attempt, and the client retries with its normal reconnect backoff.
390
+ */
391
+ type WsTokenProvider = () => Promise<string | undefined> | string | undefined;
392
+ interface LunoraClientOptions {
393
+ /**
394
+ * Base path the worker mounts better-auth at, used by the client's
395
+ * `getCurrentUser()` to reach the `get-session` route. Defaults to
396
+ * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
397
+ */
398
+ authBasePath?: string;
399
+ bookmarkStorage?: BookmarkStorage;
400
+ /**
401
+ * Stable per-client id backing the custom-mutator watermark. Sent on the
402
+ * `connect` envelope (so the server can scope this client's
403
+ * `__client_watermark`) and stamped onto every {@link OutboxMutation} the
404
+ * {@link LunoraClientOptions.outbox} sink persists, where it pairs with the
405
+ * monotonic mutation id to form the idempotency key. The `@lunora/db` path
406
+ * persists a stable id alongside the outbox and passes it here; omit for the
407
+ * standalone client, which generates an ephemeral per-session id.
408
+ */
409
+ clientId?: string;
410
+ /**
411
+ * Default app context sent in the `connect` envelope right after each socket
412
+ * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
413
+ * as `event.context`. A per-shard context registered via
414
+ * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
415
+ * hook needs connection context.
416
+ */
417
+ connectionContext?: Record<string, unknown>;
418
+ /**
419
+ * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
420
+ * handshake doesn't complete within this window — a hung dev proxy or a cold
421
+ * worker that never upgrades — the client force-closes the socket and routes
422
+ * through its normal reconnect/backoff (surfacing `offline` status) instead
423
+ * of leaving the live channel silently stuck on the browser's much longer
424
+ * default. Does not affect HTTP queries/mutations (those never ride the WS).
425
+ * Defaults to 10000 (10s); set to `0` (or negative) to disable.
426
+ */
427
+ connectTimeoutMs?: number;
428
+ /**
429
+ * When `true`, tabs sharing the same origin (and the same signed-in identity)
430
+ * coordinate via BroadcastChannel so only one tab — the "leader" — opens
431
+ * WebSocket connections to the server. Reduces simultaneous WS connections,
432
+ * bandwidth, and cross-tab state drift. Requires `BroadcastChannel`
433
+ * (browser-only); silently ignored otherwise. Defaults to `false`.
434
+ *
435
+ * **The channel is one-directional: leader → follower.** The leader
436
+ * broadcasts the values, errors, checkpoints and connection status of the
437
+ * subscriptions *it* holds; there is no frame with which a follower can ask
438
+ * the leader for anything.
439
+ *
440
+ * `subscribe` works on a follower and is how the relay delivers: the
441
+ * registration is what the leader's broadcast key is matched against, so a
442
+ * follower sees a value while the leader independently holds the same
443
+ * `(fn, args, shardKey)`.
444
+ *
445
+ * Nothing else is served, because the leader broadcasts nothing for it and a
446
+ * follower cannot ask. `subscribeShape` and `acquireConnectionContext` are
447
+ * inert on a follower — framework code (`@lunora/db`'s shape sync, every
448
+ * `usePresence` adapter) calls them from an effect the app cannot opt out
449
+ * of, so throwing would unwind the tab rather than degrade one feature.
450
+ * `whisper`, `whisperSubscribe`, `setConnectionContext` and `stream` are
451
+ * only ever called by app code, which can handle a failure, so those throw
452
+ * `NOT_IMPLEMENTED` rather than returning a handle that never fires. (The
453
+ * brief window every tab spends claiming leadership at startup is not a
454
+ * follower state: a lone tab self-promotes and its registered subscriptions
455
+ * are sent then.) HTTP surfaces — `query`, `mutation`, `action`, the offline
456
+ * queue's replay — are unaffected on every tab.
457
+ *
458
+ * So: enable this when your tabs run the SAME app views over plain
459
+ * `subscribe`, and leave it off if tabs can sit on different routes or you
460
+ * use shapes, whispers, streams, or connection context.
461
+ */
462
+ crossTabSync?: boolean;
463
+ fetch?: typeof fetch;
464
+ /**
465
+ * Interval (ms) between keepalive pings sent on each open subscription
466
+ * socket. The server answers them via the Durable Object's hibernation
467
+ * auto-response WITHOUT waking the DO, so an idle socket stays alive across
468
+ * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
469
+ * `0` (or a negative value) to disable the heartbeat entirely.
470
+ */
471
+ heartbeatIntervalMs?: number;
472
+ /**
473
+ * When `true` and a `queryCache` is active, React's `useQuery` holds its
474
+ * TanStack query disabled until the durable cache has finished loading
475
+ * (`whenReady()`), so its first enabled render can seed the cached value
476
+ * instead of issuing an HTTP read that the cache would immediately
477
+ * overwrite. Defaults to `false`.
478
+ *
479
+ * It is ONLY React's `useQuery` that defers — the Vue, Svelte, Solid and
480
+ * Angular hooks subscribe at mount regardless of this flag, and so does
481
+ * React's own subscription registry. They do not need the gate: a
482
+ * subscription opened before the load completes is seeded by the load
483
+ * itself, so a cached value reaches the first subscriber either way.
484
+ *
485
+ * Requires `queryCache` to be set (not `false`); silently ignored otherwise.
486
+ */
487
+ hydrateOnStart?: boolean;
488
+ offlineQueue?: OfflineQueueOptions;
489
+ /**
490
+ * Durable outbox seam for offline writes. When supplied (the `@lunora/db`
491
+ * path wires `createExecutorOutboxSink`), offline mutations are delegated to
492
+ * the sink and the built-in {@link PersistenceAdapter}-backed `OfflineQueue`
493
+ * is bypassed, so a db app has exactly one durable write path. Omit for the
494
+ * standalone client, which keeps using {@link LunoraClientOptions.persistence}.
495
+ */
496
+ outbox?: OutboxSink;
497
+ /**
498
+ * Durable store for the offline mutation queue. Tri-state — an explicit
499
+ * {@link PersistenceAdapter} is used as-is; `false` opts out (the queue stays
500
+ * in memory, lost on reload); omitted (the default) auto-probes a durable
501
+ * IndexedDB store when the `indexedDB` global is present (browsers), otherwise
502
+ * in-memory, so SSR/Node/React-Native keep the in-memory behaviour and only
503
+ * environments that can persist do. Pass `createAsyncStoragePersistence()` on
504
+ * React Native.
505
+ */
506
+ persistence?: false | PersistenceAdapter;
507
+ /**
508
+ * App/schema version stamped onto every persisted queued write and cached
509
+ * read. Bump it on a breaking change to a function signature or query shape:
510
+ * on the next boot, persisted writes / cached reads stamped with a different
511
+ * version are dropped (and purged) rather than replayed / hydrated against the
512
+ * new schema. Omit to disable version gating (records are never invalidated by
513
+ * version).
514
+ *
515
+ * **Adoption is itself an invalidation event:** records written before you set
516
+ * `persistenceVersion` carry no version, so the first boot after enabling it
517
+ * purges all currently-queued offline writes (and cached reads) as stale. Adopt
518
+ * it on a build where that clean slate is acceptable — typically the same
519
+ * breaking deploy you're protecting against — not purely speculatively.
520
+ */
521
+ persistenceVersion?: string;
522
+ /**
523
+ * HTTP polling fallback for live queries on a network that refuses WebSocket
524
+ * upgrades (a corporate proxy, a captive portal).
525
+ *
526
+ * One-shot `query`/`mutation`/`action` calls already ride HTTP POST, so such a
527
+ * network does not break them — it breaks reactivity, and only that. After a
528
+ * run of connect attempts that never reach `open`, the client re-runs each
529
+ * subscribed query over the batch-RPC endpoint on an interval and reports
530
+ * `"polling"` from the client's `connectionStatus()`.
531
+ *
532
+ * It is a degradation, not a second transport: shapes (`@lunora/db`
533
+ * collections), durable streams and whispers have no request/response form to
534
+ * re-run and stay unavailable until a socket opens. Freshness is bounded by
535
+ * the interval, and each tick costs a full re-run of every subscribed query.
536
+ *
537
+ * Defaults to polling every 5s after 3 consecutive failed opens. Set
538
+ * `intervalMs: 0` to disable it and keep the historical behaviour (live
539
+ * queries simply stop moving).
540
+ */
541
+ pollingFallback?: {
542
+ /** Consecutive connect attempts that must fail to reach `open` first. Default 3; `0` disables. */
543
+ afterFailedAttempts?: number;
544
+ /** Poll cadence in ms. Default 5000; `0` disables. */
545
+ intervalMs?: number;
546
+ };
547
+ /**
548
+ * Durable store for the read cache (Pillar 2). When active, query results
549
+ * are persisted as their subscriptions advance and hydrated on construction
550
+ * so a reload renders cached data before the socket reconnects, then resumes
551
+ * the live subscription from the persisted cursor. Tri-state — an explicit
552
+ * {@link QueryCacheAdapter} is used as-is; `false` opts out (reads stay in
553
+ * memory only); omitted (the default) auto-probes IndexedDB exactly like
554
+ * {@link LunoraClientOptions.persistence}.
555
+ */
556
+ queryCache?: QueryCacheAdapter | false;
557
+ reconnect?: ReconnectOptions;
558
+ url: string;
559
+ WebSocket?: typeof WebSocket;
560
+ /**
561
+ * Credential appended to the WebSocket URL as `?token=…`. The server matches
562
+ * it against `LUNORA_WS_BEARER` (to clear the upgrade gate) and/or
563
+ * `LUNORA_ADMIN_TOKEN` (to authorize `__lunora_admin__:*` subscriptions —
564
+ * what the studio supplies). Browsers can't set headers on the `WebSocket`
565
+ * constructor, so the query parameter is the only channel; it ends up in
566
+ * server logs and history, so prefer a short-lived rotating token in
567
+ * production over a static secret.
568
+ *
569
+ * Pass a {@link WsTokenProvider} function to resolve the token fresh at
570
+ * every (re)connect — the channel for short-lived credentials such as the
571
+ * ephemeral admin sub-token minted by `POST /_lunora/admin/ws-token`: the
572
+ * provider re-mints on each reconnect, including the one following a `4001`
573
+ * token-expired drop, so a static master token never has to ride the URL.
574
+ */
575
+ wsToken?: string | WsTokenProvider;
576
+ wsUrl?: string;
577
+ }
578
+ /** Wire envelope sent on `POST /_lunora/rpc`. */
579
+ interface RpcEnvelope {
580
+ args?: Record<string, unknown>;
581
+ /**
582
+ * Stable per-client identifier (custom-mutator push path). Pairs with
583
+ * {@link RpcEnvelope.mutationId} to form `idempotencyKey` and scope the
584
+ * server `__client_watermark`. Absent on plain `client.mutation` calls.
585
+ */
586
+ clientId?: string;
587
+ functionPath: string;
588
+ /**
589
+ * Idempotency key (`${clientId}:${mutationId}`) for the custom-mutator push
590
+ * path, mirrored into the `x-lunora-mutation-id` header. Absent on plain
591
+ * `client.mutation` calls.
592
+ */
593
+ idempotencyKey?: string;
594
+ /**
595
+ * Monotonic per-client mutation id (custom-mutator push path), backing the
596
+ * server-side per-client watermark: `id <= watermark` is a replay (skipped),
597
+ * `id == watermark + 1` runs authoritatively, `id > watermark + 1` halts the
598
+ * batch so the client resends from `watermark + 1`. Absent on plain
599
+ * `client.mutation` calls.
600
+ */
601
+ mutationId?: number;
602
+ shardKey?: string;
603
+ }
604
+ /**
605
+ * Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). A
606
+ * watermarked custom-mutator push additionally carries `lastMutationId` — the
607
+ * highest per-client sequence the DO has applied — which the client uses to keep
608
+ * its `clientSeq` generator monotonic across reloads (see `LunoraClient.callMutator`).
609
+ * A plain mutation on a CDC shard carries `commitCursor` — the cursor the write
610
+ * committed at — which gates the drop of a per-call optimistic layer.
611
+ */
612
+ type RpcResponseBody = {
613
+ error: {
614
+ code: string;
615
+ data?: unknown;
616
+ message: string;
617
+ };
618
+ } | {
619
+ commitCursor?: number;
620
+ lastMutationId?: number;
621
+ result: unknown;
622
+ };
623
+ /** Subscription protocol — client → server. */
624
+ interface ClientSubscribeMessage {
625
+ id: string;
626
+ /**
627
+ * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
628
+ * for this shard (Pillar 1b resume). Present only when a durable
629
+ * {@link QueryCacheAdapter} restored a cached value with a cursor; the
630
+ * server replies with a lightweight `resume` frame instead of a full
631
+ * snapshot when nothing the query reads changed since it. Absent on a
632
+ * first-time subscribe.
633
+ */
634
+ query: {
635
+ args?: Record<string, unknown>;
636
+ functionPath?: string;
637
+ sinceEpoch?: string;
638
+ sinceSeq?: number;
639
+ table?: string;
640
+ };
641
+ type: "subscribe";
642
+ }
643
+ interface ClientUnsubscribeMessage {
644
+ id: string;
645
+ type: "unsubscribe";
646
+ }
647
+ /**
648
+ * One-shot control frame sent right after the socket opens. Registers the
649
+ * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
650
+ * fires the `onConnect` lifecycle hooks; the same context is replayed to
651
+ * `onDisconnect` when the socket drops.
652
+ */
653
+ interface ClientConnectMessage {
654
+ /**
655
+ * Wire behaviours this client can handle that an older one cannot, so the
656
+ * server can use them without breaking clients that can't. Currently just
657
+ * `"pageDelta"`; see `shared/page-result.ts` for what it promises and why it
658
+ * must be announced rather than assumed. Omitting it is always safe.
659
+ */
660
+ caps?: ReadonlyArray<string>;
661
+ /**
662
+ * Stable per-client id (persisted alongside the outbox). Lets the server
663
+ * scope this connection's `__client_watermark` so custom-mutator pokes can
664
+ * echo the right per-client `lastMutationId`. Omitted by clients that don't
665
+ * use custom mutators.
666
+ */
667
+ clientId?: string;
668
+ context?: Record<string, unknown>;
669
+ id: string;
670
+ type: "connect";
671
+ }
672
+ /**
673
+ * Subscribe to a declarative **shape** — server-side partial replication scoped
674
+ * by `shardBy` + the shape's predicate + RLS. The client sends the shape *name*
675
+ * + validated `args`; the server resolves the trusted `where` (identity/RLS
676
+ * `baseWhere` the client can't forge) and streams the matching rowset, then live
677
+ * {@link ServerPokePartMessage} diffs. `id` namespaces the subscription and is
678
+ * echoed as `shapeId` on every poke part.
679
+ */
680
+ interface ClientShapeSubscribeMessage {
681
+ id: string;
682
+ shape: {
683
+ args?: Record<string, unknown>;
684
+ name: string;
685
+ };
686
+ /**
687
+ * Resume from this checkpoint (the `__cdc_log` cursor the client last
688
+ * applied for this shape). When absent or below the server's retained floor
689
+ * (`minCdcSeq`), the server re-seeds with a full insert-poke instead of a
690
+ * delta.
691
+ */
692
+ sinceCheckpoint?: number;
693
+ /**
694
+ * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
695
+ * to. A mismatch (forked changelog timeline) forces a full re-seed even when
696
+ * the cursor is numerically in range.
697
+ */
698
+ sinceEpoch?: string;
699
+ type: "shape_subscribe";
700
+ }
701
+ /** Cancel a shape subscription started with the same `id`. */
702
+ interface ClientShapeUnsubscribeMessage {
703
+ id: string;
704
+ type: "shape_unsubscribe";
705
+ }
706
+ interface ClientAckMessage {
707
+ id: string;
708
+ type: "ack";
709
+ }
710
+ /**
711
+ * Start a streaming query. The id namespaces a fresh stream and is echoed on
712
+ * every {@link ServerChunkMessage} the server pushes back. Cancel a running
713
+ * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
714
+ * subscription and stream id-spaces share the cancel channel; the prefix
715
+ * (`sub_*` vs `stream_*`) keeps the local registries searchable.
716
+ */
717
+ interface ClientStreamMessage {
718
+ /**
719
+ * Run generation the {@link ClientStreamMessage.sinceChunk} watermark
720
+ * belongs to: the `generation` stamp carried by the chunk frames this
721
+ * client already received, echoed back on a resume. The server refuses to
722
+ * splice a different run's tail onto the held prefix — a mismatch fails
723
+ * with `STREAM_INTERRUPTED` instead. Omitted on a first attach.
724
+ */
725
+ generation?: number;
726
+ id: string;
727
+ query: {
728
+ args?: Record<string, unknown>;
729
+ functionPath: string;
730
+ shardKey?: string;
731
+ };
732
+ /**
733
+ * Resume watermark: the highest chunk `seq` this client already received.
734
+ * Only meaningful for a stream the server declared `durable` — the run
735
+ * replays everything after it and then continues live, which is what turns
736
+ * a reconnect into a resume instead of a lost generation. Omitted on a
737
+ * first attach.
738
+ *
739
+ * Named `sinceChunk`, not `sinceSeq`, because a subscribe envelope already
740
+ * carries a `query.sinceSeq` meaning the CDC cursor.
741
+ */
742
+ sinceChunk?: number;
743
+ type: "stream";
744
+ }
745
+ /**
746
+ * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
747
+ * shard. While joined, the client receives every {@link ServerWhisperMessage}
748
+ * other members broadcast to the topic.
749
+ */
750
+ interface ClientWhisperSubscribeMessage {
751
+ topic: string;
752
+ type: "whisper_subscribe" | "whisper_unsubscribe";
753
+ }
754
+ /**
755
+ * Broadcast ephemeral `data` to the topic's other members on the shard. The
756
+ * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
757
+ * write) — for typing indicators, live cursors, presence pings. The sender does
758
+ * not receive its own whisper.
759
+ */
760
+ interface ClientWhisperMessage {
761
+ data?: unknown;
762
+ topic: string;
763
+ type: "whisper";
764
+ }
765
+ type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientShapeSubscribeMessage | ClientShapeUnsubscribeMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
766
+ /** Subscription protocol — server → client. */
767
+ interface ServerDataMessage {
768
+ /**
769
+ * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
770
+ * client persists it as the query's `serverCursor` and replays it as
771
+ * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
772
+ */
773
+ cursor?: number;
774
+ data?: unknown;
775
+ delta?: unknown;
776
+ /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
777
+ epoch?: string;
778
+ id: string;
779
+ /**
780
+ * The highest custom-mutator `mutationId` from this client the server has
781
+ * now applied (the per-client `__client_watermark`). Echoed so the client's
782
+ * outbox can drop confirmed pending mutations and let TanStack DB collapse
783
+ * the matching optimistic overlay. Absent on shards without custom mutators.
784
+ */
785
+ lastMutationId?: number;
786
+ type: "data" | "delta";
787
+ }
788
+ /**
789
+ * Lightweight resume acknowledgement (Pillar 1b): the server determined that
790
+ * nothing the subscription reads changed since the client's `sinceSeq`, so it
791
+ * skips re-sending the snapshot. The client keeps its cached value and only
792
+ * advances `serverCursor` to `cursor`.
793
+ */
794
+ interface ServerResumeMessage {
795
+ cursor?: number;
796
+ /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
797
+ epoch?: string;
798
+ id: string;
799
+ /** Per-client custom-mutator watermark (see {@link ServerDataMessage.lastMutationId}). */
800
+ lastMutationId?: number;
801
+ type: "resume";
802
+ }
803
+ /**
804
+ * Settled acknowledgement for a **list** subscription: a write touched one of
805
+ * the subscription's read tables but produced a byte-identical result, so the
806
+ * server suppressed the data frame. Sent ONLY to a `@lunora/db` custom-mutator
807
+ * client (one that announced a `clientId`, hence has a server-side
808
+ * `__client_watermark`) so its optimistic list overlay drops even when no data
809
+ * frame arrives. Plain `useQuery` subscribers never receive it, and an older
810
+ * client safely ignores the unknown frame.
811
+ */
812
+ interface ServerSettledMessage {
813
+ cursor?: number;
814
+ /** The CDC epoch this settled frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
815
+ epoch?: string;
816
+ id: string;
817
+ /**
818
+ * The highest custom-mutator `mutationId` from this client the server has
819
+ * now applied (the per-client `__client_watermark`). Forwarded to a
820
+ * collection's `onCheckpoint` so it can drop the overlay for the confirmed
821
+ * write whose result didn't change this list.
822
+ */
823
+ lastMutationId?: number;
824
+ type: "settled";
825
+ }
826
+ interface ServerErrorMessage {
827
+ error?: unknown;
828
+ id?: string;
829
+ message?: string;
830
+ type: "error";
831
+ }
832
+ interface ServerAckMessage {
833
+ id: string;
834
+ type: "ack";
835
+ }
836
+ interface ServerCompleteMessage {
837
+ id: string;
838
+ type: "complete";
839
+ }
840
+ /** One frame of a streaming query — `data` carries the user-yielded chunk. */
841
+ interface ServerChunkMessage {
842
+ data: unknown;
843
+ /**
844
+ * Generation stamp of the **durable** run this chunk belongs to. The client
845
+ * stores it beside {@link ServerChunkMessage.seq} and echoes it as
846
+ * {@link ClientStreamMessage.generation} on a resume, so the server can
847
+ * tell a genuine resume from an attempt to splice onto a different run
848
+ * under the same key. Absent on an ephemeral stream.
849
+ */
850
+ generation?: number;
851
+ id: string;
852
+ /**
853
+ * Monotonic position of this chunk within a **durable** run, starting at 1.
854
+ * The client stores the last one it saw and replays it as
855
+ * {@link ClientStreamMessage.sinceChunk} when the socket comes back. Absent
856
+ * on an ephemeral stream, which has nothing to resume from.
857
+ */
858
+ seq?: number;
859
+ type: "chunk";
860
+ }
861
+ /**
862
+ * An ephemeral whisper relayed from another member of `topic` on the same shard
863
+ * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
864
+ * is the sender's verified user id when known (absent for an anonymous sender).
865
+ * Never persisted server-side.
866
+ */
867
+ interface ServerWhisperMessage {
868
+ data: unknown;
869
+ from?: string;
870
+ topic: string;
871
+ type: "whisper";
872
+ }
873
+ /**
874
+ * The user the shard authenticated this socket as, sent in reply to every
875
+ * `connect` frame. `subject` is the resolved user id, or `null` when the socket
876
+ * is anonymous. A cookie-session client reads it to learn who it is — a
877
+ * sign-out or another user's sign-in changes nothing else it can see.
878
+ */
879
+ interface ServerIdentityMessage {
880
+ subject: null | string;
881
+ type: "identity";
882
+ }
883
+ /**
884
+ * One row-level change in a shape's replication stream — the wire form of the
885
+ * DO's `__cdc_log` `CdcChange`. `insert`/`update` carry the post-image in
886
+ * `value` (projected to the shape's `columns`); `delete` omits it, identifying
887
+ * the removed row by `key` alone. The client applies these to its local
888
+ * collection; an unknown `key` on a `delete` is a safe no-op (a row the client
889
+ * never had in this shape).
890
+ */
891
+ interface RowOp {
892
+ /** Row primary key (`_id`). */
893
+ key: string;
894
+ op: "delete" | "insert" | "update";
895
+ /** Logical table the row belongs to. */
896
+ table: string;
897
+ /** Post-image document for insert/update; absent on delete. */
898
+ value?: Record<string, unknown>;
899
+ }
900
+ /**
901
+ * Opens a **poke** — an atomically-applied batch of shape diffs (Zero's poke
902
+ * protocol). A `pokeStart` is followed by zero or more {@link ServerPokePartMessage}
903
+ * frames and closed by exactly one {@link ServerPokeEndMessage}; the client
904
+ * buffers every part and applies them in a single transaction at `pokeEnd`, so a
905
+ * socket that drops mid-poke simply re-seeds on reconnect (no torn view).
906
+ */
907
+ interface ServerPokeStartMessage {
908
+ /**
909
+ * Poke-level fallback base, stamped by single-part senders. Per-shape
910
+ * {@link ServerPokePartMessage.baseCheckpoint} takes precedence; this is what
911
+ * a part without its own base falls back to.
912
+ */
913
+ baseCheckpoint?: number;
914
+ /** CDC epoch this poke belongs to; a mismatch forces the client to re-seed rather than apply. */
915
+ epoch?: string;
916
+ /** Correlates this poke's `pokeStart`/`pokePart`/`pokeEnd` frames. */
917
+ pokeId: string;
918
+ type: "pokeStart";
919
+ }
920
+ /** One shape's slice of an in-flight poke: the row-ops to apply for `shapeId`. */
921
+ interface ServerPokePartMessage {
922
+ /**
923
+ * The checkpoint this shape's view must be at for `rowsPatch` to splice on
924
+ * cleanly. Per shape, because every shape on a socket has its own
925
+ * delivered-through cursor. Absent when the server cannot name a base — the
926
+ * gap check is then disarmed for this part, never guessed at.
927
+ */
928
+ baseCheckpoint?: number;
929
+ /** Per-client custom-mutator watermark carried with this slice (see {@link ServerSettledMessage.lastMutationId}). */
930
+ lastMutationId?: number;
931
+ pokeId: string;
932
+ /**
933
+ * `true` when `rowsPatch` is the shape's COMPLETE membership, not a diff (a
934
+ * full seed or re-seed). The client MUST drop its current view for this shape
935
+ * before applying: a seed is inserts-only, so merging it leaves any row that
936
+ * left the shape while the client was disconnected on screen forever.
937
+ *
938
+ * Never inferred from an absent {@link ServerPokePartMessage.baseCheckpoint} —
939
+ * most live poke paths legitimately carry no base.
940
+ */
941
+ reset?: boolean;
942
+ /** Ordered row-level changes for this shape, applied in sequence at `pokeEnd`. */
943
+ rowsPatch: RowOp[];
944
+ /** The {@link ClientShapeSubscribeMessage.id} these row-ops belong to. */
945
+ shapeId: string;
946
+ type: "pokePart";
947
+ }
948
+ /**
949
+ * Closes a poke: the client commits the buffered parts atomically and advances
950
+ * its checkpoint to {@link ServerPokeEndMessage.checkpoint} (the `__cdc_log`
951
+ * cursor high-watermark the view now reflects), replayed as `sinceCheckpoint` on
952
+ * the next reconnect.
953
+ */
954
+ interface ServerPokeEndMessage {
955
+ /** The `__cdc_log` cursor the view is at after applying this poke. */
956
+ checkpoint?: number;
957
+ /** CDC epoch the {@link ServerPokeEndMessage.checkpoint} belongs to. */
958
+ epoch?: string;
959
+ pokeId: string;
960
+ type: "pokeEnd";
961
+ }
962
+ type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
963
+ /**
964
+ * The authenticated user as exposed client-side, mirroring better-auth's
965
+ * `user` row (the `user` field of the `get-session` response). Kept minimal
966
+ * and structural — only `id` is guaranteed; the rest are the common better-auth
967
+ * fields, and the index signature carries any plugin-contributed extras.
968
+ */
969
+ interface User {
970
+ readonly createdAt?: NullableTimestamp;
971
+ readonly email?: null | string;
972
+ readonly emailVerified?: boolean | null;
973
+ readonly id: string;
974
+ readonly image?: null | string;
975
+ readonly name?: null | string;
976
+ readonly [key: string]: unknown;
977
+ readonly updatedAt?: NullableTimestamp;
978
+ }
979
+ /**
980
+ * Per-job retry policy carried on a {@link ScheduleRecord}. Mirrors
981
+ * `@lunora/scheduler`'s `RetryPolicy`; absent means the scheduler's defaults.
982
+ */
983
+ interface ScheduleRetryPolicy {
984
+ /** Backoff growth across attempts. Default `"exponential"`. */
985
+ backoff?: "exponential" | "linear";
986
+ /** Base delay in milliseconds for the first retry. Default `30_000`. */
987
+ baseMs?: number;
988
+ /** Maximum number of dispatch attempts before dead-lettering. Default `5`. */
989
+ maxAttempts?: number;
990
+ /** Optional ceiling clamping the computed backoff delay. */
991
+ maxMs?: number;
992
+ }
993
+ /**
994
+ * One pending scheduled function, as returned by the worker's
995
+ * `GET /_lunora/admin/scheduled` endpoint. The route is a byte-for-byte proxy of
996
+ * the SchedulerDO's own `/list`, so this mirrors `@lunora/scheduler`'s
997
+ * `ScheduleRecord` field-for-field — structurally, so the client carries no
998
+ * dependency on it. `packages/client/__tests__/structural-mirrors.test.ts` fails
999
+ * when the two drift.
1000
+ */
1001
+ interface ScheduleRecord {
1002
+ args: Record<string, unknown>;
1003
+ /**
1004
+ * Dispatch attempts already made. Absent (treated as 0) until the first
1005
+ * failure; on a dead-letter record it is the exhausted count (> the retry
1006
+ * budget). Surfaced so the studio can show how hard a job tried before it
1007
+ * was parked.
1008
+ */
1009
+ attempts?: number;
1010
+ enqueuedAt: number;
1011
+ /**
1012
+ * The `ns:fn` path dispatched on fire. Absent when the job targets a durable
1013
+ * workflow/agent instead — exactly one of `functionPath` /
1014
+ * {@link ScheduleRecord.workflow} is set, so a view rendering a job's target
1015
+ * must fall back to `workflow` rather than assuming a path.
1016
+ */
1017
+ functionPath?: string;
1018
+ id: string;
1019
+ /** Scheduler/workpool instance the job was enqueued through. Absent for the default instance. */
1020
+ instanceName?: string;
1021
+ /** Logical workpool the job is routed to (concurrency-gated), when any. */
1022
+ pool?: string;
1023
+ /** Per-job retry policy; absent means the scheduler's built-in defaults. */
1024
+ retry?: ScheduleRetryPolicy;
1025
+ scheduledFor: number;
1026
+ shardKey?: string;
1027
+ /**
1028
+ * The workflow/agent class name (its `ctx.exports` key) a fresh durable instance is started from
1029
+ * on fire (the {@link ScheduleRecord.args} become its `params`). Set instead
1030
+ * of {@link ScheduleRecord.functionPath}.
1031
+ */
1032
+ workflow?: string;
1033
+ }
1034
+ /**
1035
+ * One workpool's live backlog, as returned by the worker's
1036
+ * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
1037
+ * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
1038
+ */
1039
+ interface SchedulerPoolStatus {
1040
+ /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
1041
+ inFlight: number;
1042
+ /** The pool's concurrency cap. */
1043
+ maxConcurrency: number;
1044
+ /** The logical workpool name. */
1045
+ name: string;
1046
+ /** Pending jobs routed to this pool but not yet dispatched. */
1047
+ queued: number;
1048
+ }
1049
+ /**
1050
+ * The app-level scheduler backlog, as returned by the worker's
1051
+ * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
1052
+ * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
1053
+ * `inFlight` across every pool — the headline numbers for the studio SLO
1054
+ * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
1055
+ */
1056
+ interface SchedulerStatus {
1057
+ /** Sum of every pool's `queued` count — the total pending backlog. */
1058
+ backlog: number;
1059
+ /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
1060
+ inFlight: number;
1061
+ /** Per-pool backlog breakdown. */
1062
+ pools: SchedulerPoolStatus[];
1063
+ }
1064
+ /**
1065
+ * One shard's request volume, as returned by the worker's
1066
+ * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
1067
+ * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
1068
+ * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
1069
+ */
1070
+ interface ShardTrafficEntry {
1071
+ requests: number;
1072
+ shardKey: string;
1073
+ }
1074
+ /**
1075
+ * The whole-shard-set traffic distribution returned by the worker's
1076
+ * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
1077
+ * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
1078
+ * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
1079
+ * lint after the studio tags each entry with its sharded function `group`.
1080
+ */
1081
+ interface ShardTrafficResult {
1082
+ failed: number;
1083
+ ok: number;
1084
+ shards: ShardTrafficEntry[];
1085
+ }
1086
+ /**
1087
+ * One object in the storage bucket, as returned by the worker's
1088
+ * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
1089
+ * `R2ObjectLike` structurally.
1090
+ */
1091
+ interface StorageObject {
1092
+ customMetadata?: Record<string, string>;
1093
+ etag: string;
1094
+ httpMetadata?: {
1095
+ contentType?: string;
1096
+ };
1097
+ key: string;
1098
+ size: number;
1099
+ /**
1100
+ * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
1101
+ * ISO string over the wire; a mock may supply epoch ms — so consumers should
1102
+ * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
1103
+ */
1104
+ uploaded?: number | string;
1105
+ }
1106
+ /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
1107
+ interface StorageListPage {
1108
+ cursor?: string;
1109
+ objects: StorageObject[];
1110
+ }
1111
+ /**
1112
+ * One argument of a registered function, derived from its `v.*` validator by the
1113
+ * worker. A compact signature shape — enough to render a function's API without
1114
+ * the build-time codegen types.
1115
+ */
1116
+ interface FunctionArgumentDescriptor {
1117
+ /** Element validator kind for an `array` arg (one level), e.g. `string`. */
1118
+ element?: string;
1119
+ /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
1120
+ kind: string;
1121
+ /** The argument name. */
1122
+ name: string;
1123
+ /** True when the arg is wrapped in `v.optional(...)`. */
1124
+ optional: boolean;
1125
+ /** Target table for an `id` arg (`v.id("table")`). */
1126
+ table?: string;
1127
+ }
1128
+ /**
1129
+ * One registered function, as returned by the worker's
1130
+ * `GET /_lunora/admin/functions` endpoint: its `<file>:<function>` path, which
1131
+ * client method (`query` / `mutation` / `action`) invokes it, and its argument
1132
+ * signature. `args` is absent on responses from an older worker.
1133
+ */
1134
+ interface FunctionDescriptor {
1135
+ args?: FunctionArgumentDescriptor[];
1136
+ kind: "action" | "mutation" | "query";
1137
+ path: string;
1138
+ }
1139
+ /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
1140
+ interface GlobalTableInfo {
1141
+ name: string;
1142
+ rowCount: number;
1143
+ }
1144
+ /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
1145
+ interface GlobalTablePage {
1146
+ columns: string[];
1147
+ /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
1148
+ refs?: Record<string, string>;
1149
+ rows: Record<string, unknown>[];
1150
+ total: number;
1151
+ }
1152
+ /**
1153
+ * One equality constraint a facet-value click adds to the global browser's view
1154
+ * (`column = value`). `value` is the raw stored scalar the facet returned, sent
1155
+ * as-is and bound server-side, so it never injects SQL.
1156
+ */
1157
+ interface GlobalFilterClause {
1158
+ column: string;
1159
+ value: unknown;
1160
+ }
1161
+ /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
1162
+ interface GlobalFacetValue {
1163
+ count: number;
1164
+ value: unknown;
1165
+ }
1166
+ /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
1167
+ interface GlobalFacetResult {
1168
+ truncated: boolean;
1169
+ values: GlobalFacetValue[];
1170
+ }
1171
+ /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
1172
+ type NullableTimestamp = null | number | string;
1173
+ /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
1174
+ type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1175
+ /** The lifecycle mutations the status endpoint accepts. */
1176
+ type WorkflowInstanceAction = "pause" | "resume" | "terminate";
1177
+ /** One row of the workflow-instances list. */
1178
+ interface WorkflowInstanceSummary {
1179
+ createdOn?: string;
1180
+ endedOn?: string;
1181
+ id: string;
1182
+ startedOn?: string;
1183
+ status: WorkflowInstanceStatus;
1184
+ }
1185
+ /** One durable step of an instance's execution timeline. */
1186
+ interface WorkflowStepDetail {
1187
+ /** 1-based attempt count (`> 1` means the step retried). */
1188
+ attempts?: number;
1189
+ end?: string;
1190
+ error?: unknown;
1191
+ name: string;
1192
+ output?: unknown;
1193
+ start?: string;
1194
+ success?: boolean;
1195
+ /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
1196
+ type?: string;
1197
+ }
1198
+ /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
1199
+ interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
1200
+ error?: unknown;
1201
+ output?: unknown;
1202
+ params?: unknown;
1203
+ steps: WorkflowStepDetail[];
1204
+ }
1205
+ /** A page of workflow instances. */
1206
+ interface WorkflowInstancePage {
1207
+ /**
1208
+ * Whether workflow inspection is configured on the worker (a Cloudflare
1209
+ * account id + API token). `false` when the admin proxy reports it can't
1210
+ * inspect instances; omitted (treated as configured) otherwise. Lets a
1211
+ * caller render a "set credentials" state without a failed request.
1212
+ */
1213
+ configured?: boolean;
1214
+ instances: WorkflowInstanceSummary[];
1215
+ page: number;
1216
+ perPage: number;
1217
+ totalCount?: number;
1218
+ }
1219
+ type SubscriptionCallback = (data: unknown) => void;
1220
+ /**
1221
+ * The high-water marks a shape poke has now synced to the client: `checkpoint`
1222
+ * is the op-log cursor and `mutationId` the highest custom-mutator id the server
1223
+ * echoed for this client. A `@lunora/db` collection feeds these into its
1224
+ * checkpoint registry to drop optimistic overlays once the server's authoritative
1225
+ * rows have landed.
1226
+ */
1227
+ interface SyncWatermark {
1228
+ checkpoint?: number;
1229
+ mutationId?: number;
1230
+ /**
1231
+ * `true` only on the checkpoint a `data`/`delta` frame fires immediately
1232
+ * before that same frame's rowset callback — i.e. the one checkpoint whose
1233
+ * `mutationId` describes rows that are about to arrive.
1234
+ *
1235
+ * A `settled` frame (and a cross-tab `subscription-settled` relay) fires a
1236
+ * checkpoint with NO matching rowset, because the server suppressed a data
1237
+ * frame whose value didn't change. A consumer that stashes `mutationId` for
1238
+ * the next rowset to consume — `@lunora/db`'s `pendingFrameWatermark` — must
1239
+ * not stash those, or the value sits until some later unstamped frame eats
1240
+ * it and the checkpoint gate resolves at a stale watermark instead of
1241
+ * falling back to the RPC-ack compensator.
1242
+ */
1243
+ rowsFollow?: boolean;
1244
+ }
1245
+ /** A subscription-scoped error the server pushed for this subscription id. */
1246
+ interface SubscriptionError {
1247
+ /**
1248
+ * The coded reason, when the frame carried one. `LunoraErrorCodeInput`, not
1249
+ * `LunoraErrorCode`: the catalog codes autocomplete for a consumer branching
1250
+ * on this (the shard sends `BAD_SUBSCRIPTION_ARGS`, `TOO_MANY_SUBSCRIPTIONS`,
1251
+ * `SUBSCRIPTION_PERSIST_FAILED`, …; the client itself adds
1252
+ * `WIRE_DECODE_FAILED` for a frame `decodeWire` refuses), but this value is
1253
+ * read verbatim off the wire and nothing validates it against the catalog,
1254
+ * so narrowing it to `LunoraErrorCode` would be a lie a newer server tells.
1255
+ */
1256
+ code?: LunoraErrorCodeInput;
1257
+ message: string;
1258
+ }
1259
+ type SubscriptionErrorCallback = (error: SubscriptionError) => void;
1260
+ /**
1261
+ * One active per-call optimistic transform layered onto a subscription. The
1262
+ * displayed value is the authoritative {@link SubscriptionState.serverBase}
1263
+ * folded through every layer's `transform`, in order — so an incoming server
1264
+ * frame re-folds the still-pending layers onto the new base (rebasing) instead
1265
+ * of clobbering them. A layer is dropped — gaplessly — once a `data`/`delta`
1266
+ * frame whose `cursor >= commitCursor` arrives (its write is now reflected in
1267
+ * `serverBase`); `commitCursor` is the CDC cursor the server echoed on the
1268
+ * mutation's response, and stays `undefined` while the write is still queued/
1269
+ * in-flight (so the overlay survives unrelated deltas until confirmed).
1270
+ */
1271
+ interface OptimisticLayer {
1272
+ /**
1273
+ * Where this write's RPC resolved in the process-wide acknowledgement order
1274
+ * (see `acknowledgementMark`); `undefined` until confirmed. A polled snapshot
1275
+ * carries no cursor, so this is what lets it drop the layer instead.
1276
+ */
1277
+ acknowledgedAt?: number;
1278
+ /** The committed CDC cursor (from the mutation response); `undefined` until confirmed. */
1279
+ commitCursor?: number;
1280
+ readonly id: symbol;
1281
+ readonly transform: (current: unknown) => unknown;
1282
+ }
1283
+ interface SubscriptionState {
1284
+ /** True once the server has acked the subscription on the current socket. */
1285
+ acked: boolean;
1286
+ readonly args: Record<string, unknown>;
1287
+ /**
1288
+ * Stable wire-key of `args` (`stableWireKey`), computed once at subscribe
1289
+ * time. Cached so the optimistic-update fan-out can compare against a
1290
+ * mutation's args key without re-serializing every subscription's args on
1291
+ * every mutation.
1292
+ */
1293
+ readonly argsKey: string;
1294
+ readonly callbacks: Set<SubscriptionCallback>;
1295
+ /**
1296
+ * Notified when a `settled` frame advances this subscription's watermark — a
1297
+ * write touched the subscription's tables but the result was byte-identical,
1298
+ * so the server suppressed the data frame. A `@lunora/db` list collection
1299
+ * uses this to drop the optimistic overlay for the confirmed write.
1300
+ *
1301
+ * A SET (not a single slot) because `SubscriptionState` is SHARED across
1302
+ * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
1303
+ * collection may subscribe to a query a plain `useQuery` already opened, so
1304
+ * each subscriber registers its own callback (mirroring `callbacks` /
1305
+ * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
1306
+ * `useQuery` consumers register nothing, leaving the set empty.
1307
+ */
1308
+ readonly checkpointCallbacks: Set<(watermark: SyncWatermark) => void>;
1309
+ /** Notified when the server rejects this subscription (e.g. admin auth). */
1310
+ readonly errorCallbacks: Set<SubscriptionErrorCallback>;
1311
+ readonly fn: FunctionReference;
1312
+ readonly id: string;
1313
+ /**
1314
+ * The highest custom-mutator `mutationId` from this client the server has
1315
+ * applied, captured from the last `settled` frame (the suppressed-list-frame
1316
+ * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
1317
+ * Absent until a `settled` frame arrives.
1318
+ */
1319
+ lastMutationId?: number;
1320
+ /** Last known value, used to short-circuit `useQuery`-style consumers. */
1321
+ lastValue: unknown;
1322
+ /**
1323
+ * Active per-call optimistic layers, in application order (see
1324
+ * {@link OptimisticLayer}). Empty for subscriptions with no pending per-call
1325
+ * optimistic write — the common case, where `lastValue` tracks `serverBase`
1326
+ * exactly and behaviour is identical to a plain server-value assignment.
1327
+ */
1328
+ optimisticLayers: OptimisticLayer[];
1329
+ /**
1330
+ * The authoritative server value the optimistic layers fold onto — the value
1331
+ * with NO optimistic overlay. Tracks `lastValue` exactly whenever no layers
1332
+ * are active; diverges only while a per-call optimistic write is pending. A
1333
+ * server frame updates this (and re-folds the layers); the durable read cache
1334
+ * persists this, never the optimistic overlay.
1335
+ */
1336
+ serverBase: unknown;
1337
+ /**
1338
+ * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
1339
+ * captured from the last `data`/`delta`/`resume` frame. Persisted to the
1340
+ * durable read cache and replayed as `sinceSeq` on reconnect so the server
1341
+ * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
1342
+ * first cursor-stamped frame arrives.
1343
+ */
1344
+ serverCursor?: number;
1345
+ /**
1346
+ * The CDC `epoch` token the `serverCursor` belongs to, captured from the
1347
+ * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
1348
+ * only when the client is still on the same changelog timeline — a reset or
1349
+ * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
1350
+ * until the first epoch-stamped frame arrives.
1351
+ */
1352
+ serverEpoch?: string;
1353
+ readonly shardKey?: string;
1354
+ /**
1355
+ * The wire-encoded form of `args`, computed once at `subscribe` time (so an
1356
+ * unsupported value fails loud at the call site, not inside a reconnect's
1357
+ * open handler). Sent on every `subscribe` frame — identical to `args` for
1358
+ * pure JSON, tagged tokens for `bigint`/`Date`/bytes/… (the shard
1359
+ * `decodeWire`s them at its subscribe entry point).
1360
+ *
1361
+ * A SNAPSHOT, not a view: `args` is the caller's own object, retained by
1362
+ * reference and never copied, so a caller that mutates it after subscribing
1363
+ * would otherwise poison every later resubscribe. `encodeWire` rebuilds
1364
+ * every container, so this copy is immune to that.
1365
+ */
1366
+ readonly wireArgs: Record<string, unknown>;
1367
+ }
1368
+ /**
1369
+ * Active subscription registry. The client keys subscriptions by
1370
+ * `(functionPath, stableWireKey(args), shardKey)` so duplicate calls share a
1371
+ * single server-side registration. Args are stably encoded (keys sorted at every
1372
+ * depth) so two structurally-equal arg records constructed with a different key
1373
+ * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
1374
+ * duplicate subscription. Encoding the args' **wire form** keeps the key
1375
+ * byte-identical for pure-JSON args while giving wire-typed args (`bigint`,
1376
+ * `Date`, bytes, …) distinct stable tokens instead of a throw.
1377
+ */
1378
+ declare class SubscriptionRegistry {
1379
+ static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
1380
+ /**
1381
+ * The registry key of an already-registered state, from its cached
1382
+ * {@link SubscriptionState.argsKey}. Re-deriving it from `state.args` would
1383
+ * re-read the caller's own (mutable) args object, so a caller that mutated
1384
+ * its args after subscribing would compute a DIFFERENT key on unsubscribe
1385
+ * and leak the registration forever.
1386
+ */
1387
+ static keyOf(state: SubscriptionState): string;
1388
+ private readonly byKey;
1389
+ private readonly byId;
1390
+ get(key: string): SubscriptionState | undefined;
1391
+ getById(id: string): SubscriptionState | undefined;
1392
+ add(state: SubscriptionState): void;
1393
+ remove(state: SubscriptionState): void;
1394
+ all(): SubscriptionState[];
1395
+ /**
1396
+ * Drop every registration. Terminal — used by `LunoraClient.close()`, whose
1397
+ * whole point is to release the callback closures each {@link SubscriptionState}
1398
+ * holds (`callbacks`, `errorCallbacks`, `checkpointCallbacks` — React state
1399
+ * setters and `@lunora/db` collection closures), which otherwise outlive the
1400
+ * closed client for as long as the client object is reachable.
1401
+ */
1402
+ clear(): void;
1403
+ }
1404
+ /**
1405
+ * Read/write handle over the client's live query cache, handed to a mutation's
1406
+ * `withOptimisticUpdate` callback so a single mutation can optimistically patch
1407
+ * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
1408
+ *
1409
+ * `getQuery` reads the current value (server value or any still-pending
1410
+ * optimistic override) of a subscribed query; `setQuery` registers a constant
1411
+ * optimistic layer on top. The whole batch rebases onto incoming deltas and
1412
+ * settles together — confirmed on the mutation's commit cursor, or rolled back
1413
+ * on failure — the same per-subscription layer machinery the single-query
1414
+ * per-call `optimistic` transform uses, generalized to N queries.
1415
+ */
1416
+ interface OptimisticLocalStore {
1417
+ /**
1418
+ * Every loaded subscription on `function_`, regardless of args, paired with
1419
+ * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
1420
+ * when a write must patch every variant of a list query (all channels,
1421
+ * all filters) without enumerating their args up front.
1422
+ */
1423
+ getAllQueries: <F extends FunctionReference>(function_: F) => {
1424
+ args: ArgsOf<F>;
1425
+ value: ReturnOf<F> | undefined;
1426
+ }[];
1427
+ /**
1428
+ * Current cached value for the subscribed `(function_, args)` query, or
1429
+ * `undefined` when nothing is subscribed/loaded for it. Reflects any
1430
+ * optimistic override already written in this batch.
1431
+ */
1432
+ getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
1433
+ /**
1434
+ * Write an optimistic override for the subscribed `(function_, args)`
1435
+ * query. A no-op (returns without effect) when no subscription matches —
1436
+ * mirroring Convex, where you only patch queries the page is watching.
1437
+ */
1438
+ setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
1439
+ }
1440
+ /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
1441
+ type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
1442
+ /**
1443
+ * Build an {@link OptimisticLocalStore} bound to a subscription registry and the
1444
+ * mutation's shard key. Each `setQuery(value)` registers a constant-value layer
1445
+ * on its target subscription (via `applyOptimisticLayer`): the predicted value
1446
+ * survives incoming server deltas (re-clamped, masking concurrent changes to that
1447
+ * query — not merged) and drops gaplessly on the mutation's commit cursor, like
1448
+ * the single-query per-call `optimistic` path. Returns the store plus the ordered
1449
+ * `confirm` (success) and `rollback` (failure) closures every `setQuery` produced,
1450
+ * so the caller settles the whole batch when the mutation does.
1451
+ */
1452
+ declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined) => {
1453
+ confirms: ((commitCursor: number | undefined) => void)[];
1454
+ rollbacks: (() => void)[];
1455
+ store: OptimisticLocalStore;
1456
+ };
1457
+ declare const DEFAULT_MAX_BUFFER = 1024;
1458
+ interface StreamHandle<T = unknown> {
1459
+ /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
1460
+ readonly complete: () => void;
1461
+ /** Surface an error to any pending consumer; subsequent pushes are dropped. */
1462
+ readonly fail: (error: Error) => void;
1463
+ /**
1464
+ * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
1465
+ * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
1466
+ * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
1467
+ * the producer never sees a thrown exception.
1468
+ */
1469
+ readonly push: (value: T) => void;
1470
+ }
1471
+ interface StreamIterable<T> extends AsyncIterable<T> {
1472
+ /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
1473
+ cancel: () => void;
1474
+ }
1475
+ /**
1476
+ * Build a stream handle paired with an async-iterable. The handle is the
1477
+ * server-driven side (the WS dispatcher pushes chunks / completes / errors);
1478
+ * the iterable is what the user awaits. `onCancel` is invoked exactly once
1479
+ * when the consumer calls `.cancel()` (or `.return()`) so the client can
1480
+ * send a `{type:"unsubscribe"}` frame to the server.
1481
+ */
1482
+ declare const createStream: <T>(options: {
1483
+ maxBuffer?: number;
1484
+ onCancel: () => void;
1485
+ }) => {
1486
+ handle: StreamHandle<T>;
1487
+ iterable: StreamIterable<T>;
1488
+ };
1489
+ type WSState = "idle" | "connecting" | "open" | "closed";
1490
+ /**
1491
+ * Aggregate live-socket health across every shard connection, for a UI status
1492
+ * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
1493
+ * is (re)connecting and none is open; `connected` = at least one socket is open;
1494
+ * `polling` = no socket would open, so live queries are being refreshed over HTTP
1495
+ * instead (see {@link file://./polling-fallback.ts} — live but slower, and shapes
1496
+ * / streams / whispers are dark; mutations go over HTTP as they do while
1497
+ * connected); `offline` = sockets exist but all are down (between reconnect
1498
+ * attempts), and a poll could not reach the origin either.
1499
+ *
1500
+ * `polling` outranks `connecting`: while the fallback is running a reconnect is
1501
+ * still armed in the background, and reporting that attempt would flicker the
1502
+ * indicator between two states while data is in fact arriving on the slow path.
1503
+ */
1504
+ type ConnectionStatus = "connected" | "connecting" | "idle" | "offline" | "polling";
1505
+ /** One shard's socket + watermark state in a {@link LunoraClient.debug} snapshot. */
1506
+ interface ClientDebugShard {
1507
+ /**
1508
+ * Highest custom-mutator watermark the server has echoed for this client on this
1509
+ * shard. A write whose `clientSeq` is above this has been sent but not confirmed
1510
+ * — the first thing to check when an optimistic overlay won't clear.
1511
+ */
1512
+ confirmedMutationWatermark: number;
1513
+ /** Whether a `WebSocket` object currently exists (distinct from it being open). */
1514
+ hasSocket: boolean;
1515
+ /** `undefined` for the default (unsharded) connection. */
1516
+ shardKey: string | undefined;
1517
+ /** Whether this shard's socket has ever completed a handshake — gates offline queueing. */
1518
+ wasEverConnected: boolean;
1519
+ wsState: WSState;
1520
+ }
1521
+ /** One live query or shape subscription in a {@link LunoraClient.debug} snapshot. */
1522
+ interface ClientDebugSubscription {
1523
+ /** Whether the server has acknowledged the subscription on the current socket. */
1524
+ acked: boolean;
1525
+ /** `namespace:fn` for a query, `shape:<name>` for a replication shape. */
1526
+ functionPath: string;
1527
+ id: string;
1528
+ kind: "query" | "shape";
1529
+ /** Highest custom-mutator watermark echoed on THIS subscription (absent until a `settled`/poke frame arrives). */
1530
+ lastMutationId?: number;
1531
+ /** Per-call optimistic layers still folded onto this subscription's value — a non-zero count with no pending write is a leak. */
1532
+ pendingOptimisticLayers: number;
1533
+ /** Replicated rowset size (shapes only). */
1534
+ rowCount?: number;
1535
+ /** The `__cdc_log` cursor the current value reflects. */
1536
+ serverCursor?: number;
1537
+ shardKey: string | undefined;
1538
+ /** How many callers share this subscription (subscriptions are deduped by `(fn, args, shard)`). */
1539
+ subscriberCount: number;
1540
+ }
1541
+ /**
1542
+ * Everything the sync engine believes at one instant — see
1543
+ * {@link LunoraClient.debug} for why this exists.
1544
+ */
1545
+ interface ClientDebugSnapshot {
1546
+ /** The watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1547
+ clientId: string;
1548
+ closed: boolean;
1549
+ connectionStatus: ConnectionStatus;
1550
+ /** Writes waiting in the built-in offline queue (not the `@lunora/db` outbox). */
1551
+ pendingWrites: number;
1552
+ shards: ClientDebugShard[];
1553
+ subscriptions: ClientDebugSubscription[];
1554
+ }
1555
+ /**
1556
+ * Terminal verdict for a mutation that passed through the offline queue,
1557
+ * delivered to {@link LunoraClient.onMutationSettled}.
1558
+ *
1559
+ * Unlike the Promise returned by {@link LunoraClient.mutation} — which only the
1560
+ * original caller can await, and which no longer exists after a reload — this
1561
+ * fires for *every* queued write the server (or the queue) reaches a verdict on,
1562
+ * including writes restored from durable storage in a later session. It is the
1563
+ * channel a UI uses to tell the user "your queued change couldn't be saved"
1564
+ * instead of silently dropping a rolled-back optimistic row.
1565
+ *
1566
+ * `status: "rejected"` carries the failure `code` (e.g. `CONFLICT`,
1567
+ * `OFFLINE_QUEUE_OVERFLOW`, `OFFLINE_IDENTITY_CHANGED`) and the `error`.
1568
+ * `hadAwaiter` is `false` for a write whose original `mutation()` Promise is
1569
+ * gone (a hydrated/post-reload replay or an eviction), so a listener can tell
1570
+ * "the caller already saw this" apart from "nothing else will report this".
1571
+ */
1572
+ interface MutationSettledEvent {
1573
+ /** The write's args, so a listener can describe or re-offer the change. */
1574
+ readonly args: Record<string, unknown>;
1575
+ /**
1576
+ * Server/queue error code on `rejected` (e.g. `CONFLICT`), when present —
1577
+ * or `WIRE_DECODE_FAILED` on a `committed` write whose result could not be
1578
+ * decoded.
1579
+ */
1580
+ readonly code?: string;
1581
+ /** The rejection error on `status: "rejected"`, or the decode error of a `committed` write whose result could not be read. */
1582
+ readonly error?: unknown;
1583
+ /** The `<file>:<function>` reference of the mutation. */
1584
+ readonly functionPath: string;
1585
+ /** Whether a live caller was still awaiting this write's `mutation()` Promise. */
1586
+ readonly hadAwaiter: boolean;
1587
+ /** The write's stable id (idempotency key / queue id). */
1588
+ readonly id: string;
1589
+ /** Shard the write targeted, if any. */
1590
+ readonly shardKey?: string;
1591
+ /** Terminal outcome. */
1592
+ readonly status: "committed" | "rejected";
1593
+ }
1594
+ /**
1595
+ * Per-call options for {@link LunoraClient.action} — just `shardKey`, since an
1596
+ * action is not a write and carries none of the optimistic machinery. Exported
1597
+ * (at the end of this file) for the same reason {@link MutationCallOptions} is:
1598
+ * so the framework adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`,
1599
+ * `/angular`) type their `call(args, options?)` against one canonical
1600
+ * definition. Add an option here and every adapter forwards it; re-declare it
1601
+ * per adapter and they silently cannot.
1602
+ */
1603
+ interface ActionCallOptions {
1604
+ /** Route the call to a specific shard. */
1605
+ shardKey?: string;
1606
+ }
1607
+ /**
1608
+ * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
1609
+ * machinery plus `shardKey`. Exported (at the end of this file) so the framework
1610
+ * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
1611
+ * `mutate(args, options?)` against one canonical definition instead of
1612
+ * re-declaring it.
1613
+ */
1614
+ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
1615
+ /**
1616
+ * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
1617
+ * durable outbox replay a committed-but-unacked write under its *original* key
1618
+ * so the server dedups it instead of applying it twice. Omit for normal calls —
1619
+ * each then gets a fresh key.
1620
+ */
1621
+ mutationId?: string;
1622
+ /**
1623
+ * Single-query shortcut: the transform is layered onto the subscription
1624
+ * registered under **this write's own** `(functionPath, args, shardKey)`, and
1625
+ * nothing else. A client cannot know which queries a write affects, so the
1626
+ * targeting rule is "same reference, same args" — which makes this the
1627
+ * shorthand for a query and a mutation that share a path (a counter, a
1628
+ * document by id), and a silent no-op for anything else.
1629
+ *
1630
+ * **The general case — a `messages:send` mutation patching a `messages:list`
1631
+ * query — is {@link MutationCallOptions.optimisticUpdate}**, whose store names
1632
+ * its targets. Reach for that whenever the mutation and the query are
1633
+ * different functions, which is nearly always.
1634
+ *
1635
+ * The transform must be pure: it re-runs on every server frame while the write
1636
+ * is pending, so derive from `current` rather than closing over a value.
1637
+ */
1638
+ optimistic?: (current: TCurrent | undefined) => TValue;
1639
+ /**
1640
+ * Convex-parity multi-query optimistic update. Receives an
1641
+ * `OptimisticLocalStore` over the live subscription cache plus the
1642
+ * mutation's args, so one mutation can patch many subscribed queries at
1643
+ * once; every write is rolled back atomically if the mutation fails.
1644
+ */
1645
+ optimisticUpdate?: OptimisticUpdate<TArgs>;
1646
+ /**
1647
+ * Sync predicate evaluated just before the offline queue replays this
1648
+ * write on reconnect. When it returns `false` the mutation is dropped
1649
+ * instead of replayed — use it to guard against replaying writes whose
1650
+ * assumptions are no longer valid (e.g. the document it referred to was
1651
+ * deleted by another client while this tab was offline).
1652
+ */
1653
+ precondition?: () => boolean;
1654
+ /**
1655
+ * Pin this call's `.dropStalePatches()` baseline instead of sampling the
1656
+ * client's current view — the durable-replay counterpart to
1657
+ * {@link MutationCallOptions.mutationId}. See
1658
+ * {@link import("./types").OutboxMutation.baselineSeq} for why a replay must
1659
+ * hand back the cursor it was composed at.
1660
+ *
1661
+ * Tri-state, the same shape (and for the same reason) as the `identity` stamp
1662
+ * a queued write carries: `undefined` samples the current cursor, `null` pins
1663
+ * "composed with no baseline", and a number pins that cursor. A plain
1664
+ * `number | undefined` could not express the middle case, so every write
1665
+ * queued without a live subscription would have re-derived.
1666
+ *
1667
+ * Omit for normal calls.
1668
+ */
1669
+ replayBaseline?: null | number;
1670
+ /**
1671
+ * The credential a durable replay was judged under — the one
1672
+ * {@link LunoraClient.replayIdentityVerdict} returns with a `"match"`. The
1673
+ * request is sent with exactly the bearer that verdict was judged against,
1674
+ * never the live one: a `setAuthToken` landing between the verdict and the
1675
+ * send would otherwise put a write judged as one user's on the next user's
1676
+ * bearer, and a bearer request carries no subject for the worker to refuse it
1677
+ * on. Under a cookie session the request also names the user the write was
1678
+ * queued by, and the worker refuses it with `IDENTITY_MISMATCH` when the
1679
+ * cookie now belongs to someone else — the check the client cannot make,
1680
+ * because it cannot see the cookie.
1681
+ *
1682
+ * Single use, and only valid on the client that issued it. A replay refused
1683
+ * for its credential (`UNAUTHENTICATED` / `TOKEN_EXPIRED`) fires {@link LunoraClient.onTokenExpired} once per credential, and only
1684
+ * while that credential is still the current one. Omit for normal calls,
1685
+ * which always send the live token.
1686
+ */
1687
+ replayCredential?: ReplayCredential;
1688
+ shardKey?: string;
1689
+ }
1690
+ declare const replayCredentialBrand: unique symbol;
1691
+ /**
1692
+ * Opaque proof that a durable write was judged replayable, bound to the
1693
+ * credential it was judged under. Issued only by
1694
+ * {@link LunoraClient.replayIdentityVerdict}; pass it to
1695
+ * {@link MutationCallOptions.replayCredential}.
1696
+ */
1697
+ interface ReplayCredential {
1698
+ readonly [replayCredentialBrand]: true;
1699
+ }
1700
+ /** {@link LunoraClient.replayIdentityVerdict}'s answer: a `"match"` carries the credential the replay must be sent with. */
1701
+ type ReplayIdentityVerdict = {
1702
+ credential: ReplayCredential;
1703
+ verdict: "match";
1704
+ } | {
1705
+ verdict: "mismatch";
1706
+ } | {
1707
+ verdict: "unknown";
1708
+ };
1709
+ /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
1710
+ type ShapeCallback = (rows: Record<string, unknown>[]) => void;
1711
+ /**
1712
+ * An `Error` carrying the server's machine-readable `code` and (for a
1713
+ * `LunoraError`) structured `data`, plus an optional actionable `hint` (Markdown)
1714
+ * and `docsUrl` resolved from the central error catalog. The client's public
1715
+ * error contract for RPC/batch failures — a UI can render `hint`/`docsUrl` to
1716
+ * tell the user how to fix the error. The `(string & {})` arm keeps
1717
+ * forward-compat/unknown server codes assignable without losing autocomplete on
1718
+ * the known {@link LunoraErrorCode} union.
1719
+ */
1720
+ type LunoraClientError = Error & {
1721
+ code?: LunoraErrorCode | (string & {});
1722
+ data?: unknown;
1723
+ docsUrl?: string;
1724
+ hint?: string | string[];
1725
+ };
1726
+ /** One demuxed result slot of a {@link LunoraClient.batch} call (plan 088). */
1727
+ type BatchSlot = {
1728
+ error: LunoraClientError;
1729
+ ok: false;
1730
+ } | {
1731
+ ok: true;
1732
+ value: unknown;
1733
+ };
1734
+ /**
1735
+ * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
1736
+ * a single multiplexed WebSocket.
1737
+ *
1738
+ * Reconnect, offline queueing, and optimistic updates are all handled here;
1739
+ * see the package README for the wire protocol.
1740
+ */
1741
+ declare class LunoraClient {
1742
+ /** Hard cap on concurrently-buffered pokes — a backstop that reclaims buffers abandoned by a mid-poke disconnect (no `pokeEnd`). Far above any real concurrent-in-flight count. */
1743
+ private static readonly MAX_POKE_BUFFERS;
1744
+ /**
1745
+ * Create a typed {@link ClientQueryRef}. Convenience wrapper around
1746
+ * {@link createClientQuery} so you don't need a separate import.
1747
+ * @example
1748
+ * ```ts
1749
+ * const sidebarOpen = LunoraClient.createClientQuery("sidebarOpen", true);
1750
+ * ```
1751
+ */
1752
+ static createClientQuery<T>(key: string, defaultValue: T): ClientQueryRef<T>;
1753
+ readonly url: string;
1754
+ readonly wsUrl: string;
1755
+ /** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
1756
+ private readonly clientQueryStore;
1757
+ private wsToken;
1758
+ /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
1759
+ private readonly authBasePath;
1760
+ private readonly fetchImpl;
1761
+ private readonly WebSocketImpl;
1762
+ private readonly bookmark;
1763
+ private readonly reconnectOptions;
1764
+ /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
1765
+ private readonly connectTimeoutMs;
1766
+ /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
1767
+ private readonly heartbeatIntervalMs;
1768
+ /** Failed-open run that engages the HTTP polling fallback; `0` disables it. */
1769
+ private readonly pollingFallbackAfterFailedAttempts;
1770
+ /** Polling-fallback cadence (ms); `0` disables it. See {@link LunoraClientOptions.pollingFallback}. */
1771
+ private readonly pollingFallbackIntervalMs;
1772
+ private readonly offlineQueue;
1773
+ /**
1774
+ * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
1775
+ * set, offline writes are delegated here and the built-in {@link OfflineQueue}
1776
+ * is bypassed, so a db app has exactly one durable write path.
1777
+ */
1778
+ private readonly outbox;
1779
+ /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
1780
+ private readonly clientId;
1781
+ /**
1782
+ * Highest CDC cursor this client has seen a write commit at, per shard key
1783
+ * (`""` for the default shard) — the read-your-writes bookmark sent as
1784
+ * `x-lunora-min-seq`.
1785
+ *
1786
+ * In memory only, and deliberately: it exists to keep THIS session's reads
1787
+ * behind THIS session's writes. Persisting it across reloads would pin a
1788
+ * fresh page to a cursor it has no reason to require and force needless
1789
+ * fallbacks to the owner.
1790
+ */
1791
+ private readonly shardCursors;
1792
+ /**
1793
+ * The server's own name for the default shard (`defaultShardKey`), learned
1794
+ * from the first response to a call that named no shard. `undefined` until
1795
+ * then, which is why `cursorKeyFor` falls back to a placeholder entry that
1796
+ * `learnDefaultShardKey` folds in once the name arrives.
1797
+ */
1798
+ private defaultShardKey;
1799
+ /**
1800
+ * `true` when the constructor's hydration microtask has finished loading the
1801
+ * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
1802
+ * the cache is ready for synchronous `peekHydratedQuery` reads.
1803
+ */
1804
+ private readyResolved;
1805
+ /** Resolvers for `whenReady()` — called once hydration completes. */
1806
+ private readyResolve;
1807
+ /**
1808
+ * Promise that resolves once the durable read cache has been loaded. When
1809
+ * `hydrateOnStart` is not set or no query cache is configured, resolves
1810
+ * immediately (the constructor creates an already-resolved promise).
1811
+ */
1812
+ private readonly readyPromise;
1813
+ /**
1814
+ * Highest custom-mutator watermark the server has echoed for this client,
1815
+ * nested by identity fingerprint (`identityFingerprint() ?? ""`) then shard
1816
+ * bucket (`shardKey ?? ""`) — the DO tracks one `__client_watermark` per
1817
+ * `(identity, clientId)` pair, not per bucket alone, so a bucket-only key
1818
+ * would let a user switch claim the previous identity's sequence and wedge
1819
+ * every push on `OUT_OF_ORDER` until a reload (plan 316). A nested map
1820
+ * (rather than a single map composite-keyed by a joined string) is what a
1821
+ * previous fix here tried and got wrong: an identity fingerprint or a
1822
+ * `shardKey` is an arbitrary string, so any string delimiter — even one as
1823
+ * exotic as U+FFFD — can appear in one operand and collide with the other
1824
+ * (a fingerprint of `a<SEP>x` + bucket `y` joins to the same string as
1825
+ * a fingerprint of `a` + bucket `x<SEP>y`), mixing two identities' watermarks.
1826
+ * The nested map has no join step, so there is no delimiter to collide.
1827
+ * `callMutator` bumps it from every ack; the `@lunora/db` mutator runtime
1828
+ * seeds its `clientSeq` generator from it so a reload (which resets the
1829
+ * in-memory counter) never reissues a stale sequence the server would
1830
+ * silently swallow as a replay.
1831
+ */
1832
+ private readonly clientWatermarks;
1833
+ /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
1834
+ private outboxMutationCounter;
1835
+ private readonly onPersistenceError;
1836
+ private readonly persistence;
1837
+ /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
1838
+ private readonly persistenceVersion;
1839
+ /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
1840
+ private outboxLeaderRelease;
1841
+ /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
1842
+ private readonly queryCache;
1843
+ /**
1844
+ * Values restored from the `queryCache` at construction, keyed by the
1845
+ * read-cache key, awaiting the `subscribe()` that will consume them. A
1846
+ * key is consumed (deleted) the first time its subscription is created, so
1847
+ * the cache only ever seeds the initial value — live frames take over after.
1848
+ */
1849
+ private readonly hydratedQueryCache;
1850
+ /**
1851
+ * The read-cache entries currently ON DISPLAY in a live subscription, by the
1852
+ * same key — every entry consumed out of `hydratedQueryCache` and not yet
1853
+ * overwritten by a server frame.
1854
+ *
1855
+ * Gating the cache at read time only protects a value not handed over YET.
1856
+ * A credential can change while a cached value is already on screen (the
1857
+ * account-switch shape: an established subject, a token it was never checked
1858
+ * against), and the fingerprint does not move with it — so nothing else
1859
+ * would notice. `revokeCacheSeededValues` takes those values back off
1860
+ * screen and returns the entries to `hydratedQueryCache`, where the ordinary
1861
+ * identity gate decides whether they may ever be shown again.
1862
+ */
1863
+ private readonly cacheSeededQueries;
1864
+ /**
1865
+ * Coalesced read-cache writes: the latest value per key, flushed to
1866
+ * the `queryCache` on a short debounce so a burst of deltas persists once.
1867
+ */
1868
+ private readonly pendingCacheWrites;
1869
+ private cacheFlushTimer;
1870
+ private readonly subscriptions;
1871
+ /**
1872
+ * Cross-tab coordinator; created only when `crossTabSync: true`. When the
1873
+ * client is not the elected leader, all WebSocket operations are skipped.
1874
+ * Not `readonly` — `close()` clears it (mirrors `outboxLeaderRelease`).
1875
+ */
1876
+ private tabCoordinator;
1877
+ /**
1878
+ * The leader's last-broadcast aggregate {@link ConnectionStatus}, mirrored
1879
+ * on a follower tab — which owns no `ShardConnection` of its own to
1880
+ * compute a status from (see `computeStatus`). `undefined` until the
1881
+ * leader's first broadcast (falls back to `"idle"`), and reset back to
1882
+ * `undefined` whenever this tab stops being a follower of the CURRENT
1883
+ * leader (becomes leader itself, or the leader changes), so a stale
1884
+ * mirror from a previous leader never survives a leadership change.
1885
+ */
1886
+ private leaderStatus;
1887
+ /**
1888
+ * Sticky "has the mirrored leader status ever reported `connected`" flag —
1889
+ * the follower's counterpart to {@link ShardConnection.wasEverConnected},
1890
+ * since a follower has no `ShardConnection` of its own. Feeds the
1891
+ * offline-queue gate (see `mutation`) exactly like the real per-shard flag
1892
+ * does on the leader/single-tab path.
1893
+ */
1894
+ private leaderWasEverConnected;
1895
+ /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
1896
+ private readonly connections;
1897
+ /**
1898
+ * Shards whose socket was closed for being idle after it had connected (see
1899
+ * {@link LunoraClient.releaseIdleShard}). The connection record is gone, but the write
1900
+ * gate still needs to know the shard was reached — see `connectionGateState`.
1901
+ * Consumed when the shard's connection is recreated.
1902
+ */
1903
+ private readonly idleClosedShards;
1904
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
1905
+ private readonly defaultConnectionContext;
1906
+ /**
1907
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
1908
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
1909
+ * on every socket open so it replays across reconnects, and forwarded to the
1910
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
1911
+ * imperative (last-writer-wins) override; refcounted holders registered via
1912
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
1913
+ * precedence — see `effectiveConnectionContext`.
1914
+ */
1915
+ private readonly connectionContexts;
1916
+ /**
1917
+ * Per-shard stack of refcounted connection-context holders (keyed by
1918
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
1919
+ * is an opaque token carrying its `context`; the most-recently acquired
1920
+ * holder wins (last-writer-wins among live holders), and the context is only
1921
+ * cleared for a shard once its last holder releases — so two concurrently
1922
+ * mounted presence hooks on the same shard can't stomp each other's context
1923
+ * on cleanup. A holder is identified by reference identity so a release
1924
+ * removes exactly the right one regardless of stack position.
1925
+ */
1926
+ private readonly connectionContextHolders;
1927
+ private authToken;
1928
+ /**
1929
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
1930
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
1931
+ * like an identity change (which would discard queued writes). `undefined` =
1932
+ * not supplied, so identity falls back to a hash of the raw token. See
1933
+ * `setAuthToken` / `identityFingerprint`.
1934
+ */
1935
+ private authSubject;
1936
+ /**
1937
+ * The bearer token `authSubject` was last asserted against. A subject
1938
+ * is a claim about WHO a specific credential belongs to; once the token
1939
+ * rotates, the sticky label is carried forward on the assumption it is the
1940
+ * same user — but nothing has confirmed that yet, and the alternative (an
1941
+ * account switch) would replay one user's queued writes as another. While
1942
+ * this is out of step with `authToken` the identity counts as unconfirmed
1943
+ * and every replay verdict is `"unknown"` (hold), until the next session
1944
+ * resolve re-asserts the subject. Only used when a subject is established;
1945
+ * a token-hash identity is self-confirming.
1946
+ */
1947
+ private subjectToken;
1948
+ /**
1949
+ * How many `getCurrentUser()` round trips are in flight.
1950
+ *
1951
+ * The identity gates need to tell two `null` fingerprints apart. For an app
1952
+ * with no auth at all, and for a client the server has answered "no
1953
+ * session" to, `null` is a real and stable identity — nobody else holds it,
1954
+ * so a `null`-stamped queued write or cached read is this client's own and
1955
+ * may be used. While a resolve is IN FLIGHT it is neither: the fingerprint
1956
+ * may be one round trip away from `subj:<id>`, which is the window a cookie
1957
+ * app spends every page load in, and where `null === null` handed one
1958
+ * browser user's durable state to the next. Counted rather than flagged so
1959
+ * two overlapping resolves (a token change during a probe) both have to
1960
+ * finish before the gates reopen.
1961
+ */
1962
+ private sessionProbesInFlight;
1963
+ /**
1964
+ * Monotonic id stamped on each `/get-session` round trip, so only the
1965
+ * NEWEST one may write the shared identity.
1966
+ *
1967
+ * `adoptResolvedSubject`'s token check asks whether the credential the
1968
+ * answer is about is still the one in hand. On a cookie app there is no
1969
+ * credential to ask about: every probe captures `requestToken === null`, so
1970
+ * two overlapping probes both pass it and whichever lands LAST wins —
1971
+ * including an older one, which then replaces the subject a newer answer
1972
+ * already established. Comparing the generation instead asks the question
1973
+ * the token cannot: is this still the current question?
1974
+ */
1975
+ private sessionProbeGeneration;
1976
+ /**
1977
+ * Monotonic id of every question this client asks the server about who it
1978
+ * is: each `/get-session` probe, and each cookie-authenticated socket upgrade
1979
+ * (answered by the `identity` frame the shard sends on `connect`). Probes
1980
+ * take their `sessionProbeGeneration` from it, so both kinds of
1981
+ * answer share one order.
1982
+ */
1983
+ private identityQuestions;
1984
+ /**
1985
+ * The `identityQuestions` id of the newest answer adopted so far. A
1986
+ * cookie-session answer older than it describes an older cookie — a socket
1987
+ * upgraded before a probe that has since answered — and may not move the
1988
+ * identity back. See `adoptCookieSubject`.
1989
+ */
1990
+ private identityAnsweredAt;
1991
+ /** Unregisters this client from the page's session-change signal (`shared/session-change.ts`); set in the constructor. */
1992
+ private releaseSessionChangeListener;
1993
+ /** Whether the one-time `IDENTITY_MISMATCH` configuration warning has been logged (see `noteIdentityMismatch`). */
1994
+ private warnedIdentityDisagreement;
1995
+ /**
1996
+ * Whether anything resolves this client's identity at all.
1997
+ *
1998
+ * The gates need to tell an app with NO AUTH — whose `null` fingerprint is
1999
+ * settled forever and shared with nobody — from a cookie app that simply
2000
+ * has not asked yet. Nothing in the client's own configuration says which
2001
+ * it is (`authBasePath` has a default), so the answer is declared: a
2002
+ * `getCurrentUser()` call, or `@lunora/client/auth`'s identity store
2003
+ * attaching itself, is what makes `null` provisional. An app that does
2004
+ * neither keeps its read cache and its offline queue exactly as before.
2005
+ */
2006
+ private identityResolutionExpected;
2007
+ /**
2008
+ * Whether a `/get-session` round trip has ever produced an ANSWER — a user,
2009
+ * or an explicit "no session". Distinct from `sessionProbesInFlight`, which
2010
+ * only covers the request's own lifetime and so reopened the gates both
2011
+ * before the first probe started and after one failed to answer, leaving a
2012
+ * `null` fingerprint free to match the previous cookie user's cached rows
2013
+ * and queued writes in exactly the window the probe count was added to
2014
+ * close. A transport or parse failure never sets this: it learned nothing.
2015
+ */
2016
+ private identitySettled;
2017
+ /**
2018
+ * Identity stamp recorded against each queued offline mutation, keyed by
2019
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
2020
+ * in effect at the time, and re-checked at flush so a queued write can
2021
+ * never replay under a different identity than the one that issued it.
2022
+ * See `identityFingerprint` for the fingerprint shape.
2023
+ */
2024
+ private readonly queuedIdentities;
2025
+ /**
2026
+ * Distinct shard keys with a mutation currently sitting in `offlineQueue`
2027
+ * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
2028
+ * restored from durable storage (`hydratePersistedQueue`). A follower tab
2029
+ * has no per-shard `ShardConnection` to iterate when its mirrored leader
2030
+ * status turns `"connected"` (see the `onConnectionStatus` coordinator
2031
+ * option), so this is what that flush walks instead. Entries are never
2032
+ * removed — flushing an already-empty shard is a cheap no-op, and the set
2033
+ * is bounded by the app's own distinct shard-key cardinality.
2034
+ */
2035
+ private readonly queuedOfflineShardKeys;
2036
+ private closed;
2037
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
2038
+ private readonly authTokenListeners;
2039
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
2040
+ private readonly statusListeners;
2041
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
2042
+ private readonly tokenExpiredListeners;
2043
+ /** Subscribers notified when the previous identity's session is retired (see `onIdentityChange`). */
2044
+ private readonly identityChangeListeners;
2045
+ /** How many identities this client has retired (see `identityEpoch`). */
2046
+ private retiredIdentities;
2047
+ /** Token hash the last durable-replay auth refusal fired `onTokenExpired` for — see `noteReplayAuthRefusal`. */
2048
+ private authRefusalNotifiedFor;
2049
+ /** What each outstanding {@link ReplayCredential} was judged against — see `replayIdentityVerdict`. */
2050
+ private readonly replayCredentials;
2051
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
2052
+ private readonly mutationSettledListeners;
2053
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
2054
+ private readonly pendingChangeListeners;
2055
+ /**
2056
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
2057
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
2058
+ * (re)connect so a topic survives a socket bounce.
2059
+ */
2060
+ private readonly whisperHandlers;
2061
+ /** Last status broadcast, so we only notify listeners on an actual change. */
2062
+ private lastStatus;
2063
+ private nextSubId;
2064
+ private nextStreamId;
2065
+ /**
2066
+ * In-flight client-side stream readers, keyed by the stream id sent on the
2067
+ * wire. The handle drives the underlying iterator queue and `shardKey`
2068
+ * tells us which socket to push the cancel frame onto when the consumer
2069
+ * calls `.cancel()` or the iterator is garbage-collected.
2070
+ */
2071
+ private readonly streams;
2072
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
2073
+ /**
2074
+ * Teardown callbacks for the admin sockets {@link LunoraClient.subscribeScheduledJobs}
2075
+ * opens. Those run their own reconnect loop off a closure-local `closed`
2076
+ * flag rather than `this.closed` (they predate `ensureSocket`'s guard), so
2077
+ * without this registry a `close()` left every one of them reconnecting on
2078
+ * its backoff forever — re-minting an ephemeral admin sub-token on each
2079
+ * attempt when a `WsTokenProvider` is wired.
2080
+ */
2081
+ private readonly adminSocketTeardowns;
2082
+ /**
2083
+ * The in-flight offline-queue replay per shard (`connectionKey`), while one
2084
+ * is running. Two jobs:
2085
+ *
2086
+ * 1. It serializes overlapping flushes for the same shard — two reconnect
2087
+ * events in quick succession used to drain and replay concurrently.
2088
+ * 2. It is the barrier {@link LunoraClient.mutation} waits on before sending a FRESH
2089
+ * write directly. The socket's `open` handler flips `wsState` to `"open"`
2090
+ * first and calls the flush last, so from that instant `mutation()`'s
2091
+ * offline gate is false and a new write raced straight to `/rpc` against
2092
+ * the replay of the older, queued write for the same document — the newer
2093
+ * one could land first and then be overwritten by the older. Ordering
2094
+ * inside the replay (`replaySequential`) never covered this, because the
2095
+ * racing write was never in the queue.
2096
+ */
2097
+ private readonly offlineFlushes;
2098
+ /**
2099
+ * Per-shard replay backoff, keyed by {@link connectionKey} exactly as the
2100
+ * flushes and their timers are: `delayMs` is the longest hint the CURRENT
2101
+ * flush of that key was given (written by
2102
+ * {@link LunoraClient.noteReplayRetryDelay}, consumed once by
2103
+ * {@link LunoraClient.scheduleRateLimitedRetry} at the end of the drain), and
2104
+ * `attempts` counts its consecutive failed flushes, which is what the
2105
+ * hintless backoff ramps on.
2106
+ *
2107
+ * Keyed, not a single field: flushes are per shard key and run concurrently,
2108
+ * so one field means one limited shard sets the wait for every other shard
2109
+ * and two flushes overwrite — then consume — each other's delay, leaving one
2110
+ * of them with nothing scheduled at all. Evicted by
2111
+ * {@link LunoraClient.scheduleRateLimitedRetry} the moment a key has nothing
2112
+ * left to retry, so an app that shards per document does not accumulate an
2113
+ * entry per document it ever wrote.
2114
+ */
2115
+ private readonly replayRetryState;
2116
+ /** Pending rate-limit retry flushes, keyed by {@link connectionKey}, so `close()` can cancel them. */
2117
+ private readonly replayRetryTimers;
2118
+ private readonly shapeSubscriptions;
2119
+ /**
2120
+ * In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by
2121
+ * `<connectionKey>\u0000<pokeId>`.
2122
+ *
2123
+ * The connection has to be in the key: `pokeId` is a per-DO counter that also
2124
+ * resets on eviction, so a multi-shard client — one socket per shard, one map
2125
+ * here — sees two shards mint `poke-1` concurrently. Keyed by `pokeId` alone
2126
+ * their frames interleave into a single buffer: one shard applies the other's
2127
+ * epoch (spurious fork → view wiped) and the other finds no buffer for its
2128
+ * parts at all, silently dropping rows while the server's memo advances.
2129
+ */
2130
+ private readonly pokeBuffers;
2131
+ private nextShapeId;
2132
+ constructor(options: LunoraClientOptions);
2133
+ /**
2134
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
2135
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
2136
+ * sync across all mounted instances.
2137
+ *
2138
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
2139
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
2140
+ * doesn't read as an identity change and discard queued writes. The subject is
2141
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
2142
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
2143
+ * `setAuthToken(token, user.id)` retains the identity. Clearing the token
2144
+ * clears it too — a credential-less subject would let the NEXT sign-in
2145
+ * inherit the previous user's identity (and their queue and read cache).
2146
+ * Establishing the subject on an UNCHANGED token (e.g. the user id resolves a
2147
+ * tick after the token was set — see {@link getCurrentUser}, which does this
2148
+ * for every adapter) re-stamps any in-flight queued writes rather than
2149
+ * dropping them: same credential, just a more stable label. A real user
2150
+ * switch still drops the previous user's writes.
2151
+ *
2152
+ * A sticky subject carried across a token change is not re-confirmed until
2153
+ * the next session resolve says which user the NEW credential belongs to.
2154
+ * Queued writes are HELD (never sent, never dropped) for that window — see
2155
+ * {@link replayIdentityVerdict} — so a refresh can't replay them and an
2156
+ * account switch can't replay the previous user's writes as the new one.
2157
+ *
2158
+ * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
2159
+ * time and lives in the URL. To refresh live WS auth, call
2160
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
2161
+ * force a reconnect with the new credential.
2162
+ */
2163
+ setAuthToken(token: string | null, subject?: string | null): void;
2164
+ getAuthToken(): string | null;
2165
+ /**
2166
+ * The current identity fingerprint (the same stamp queued offline writes
2167
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
2168
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
2169
+ * can drop a persisted write whose captured `identity` no longer matches the
2170
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
2171
+ */
2172
+ currentIdentity(): string | null;
2173
+ /**
2174
+ * Declare that this client's identity is resolved by something — call it
2175
+ * before the first `getCurrentUser()`, not after.
2176
+ *
2177
+ * `@lunora/client/auth`'s identity store calls this when it attaches, which
2178
+ * is the moment an app becomes one that HAS auth. Until something says so,
2179
+ * a `null` fingerprint is taken to be the settled, unshared identity of an
2180
+ * app with no auth at all, because nothing else distinguishes the two: both
2181
+ * hold no token, both have never been answered, and `authBasePath` has a
2182
+ * default. That reading is right for the no-auth app and wrong for a cookie
2183
+ * app whose first `/get-session` has not started — the window where
2184
+ * `null === null` matched the PREVIOUS browser user's cached rows and
2185
+ * queued writes, before any probe was in flight to mark the fingerprint
2186
+ * provisional.
2187
+ *
2188
+ * Idempotent, and one-way: a client that resolves an identity keeps its
2189
+ * gates armed until a probe actually answers.
2190
+ */
2191
+ expectIdentityResolution(): void;
2192
+ /**
2193
+ * This client's current CDC baseline for `shardKey` — the cursor its live
2194
+ * queries have reached, which is what a write composed right now should be
2195
+ * judged against.
2196
+ *
2197
+ * Exposed for the same reason {@link currentIdentity} is: a durable
2198
+ * {@link OutboxSink} owns its own at-least-once replay outside the built-in
2199
+ * `OfflineQueue`, so it has to capture this at COMPOSE time and hand it back
2200
+ * through {@link MutationCallOptions.replayBaseline}. Sampling it inside the
2201
+ * replay instead reads the cursor this client has advanced to in the
2202
+ * meantime, which is the newer state the write must be judged against.
2203
+ *
2204
+ * `undefined` when no subscription on the shard carries a cursor yet.
2205
+ */
2206
+ currentBaseline(shardKey?: string): number | undefined;
2207
+ /**
2208
+ * Verdict on whether a durable write stamped with `stamped` may be replayed
2209
+ * now. The comparison a replay handler must NOT hand-roll.
2210
+ *
2211
+ * `"match"` is the same identity, or the same credential under a token hash
2212
+ * — which a late-resolving subject would otherwise make look different.
2213
+ *
2214
+ * `"unknown"` is nobody signed in *yet*. A durable replay starts when the
2215
+ * executor is constructed, before the app has resolved its session and
2216
+ * called {@link setAuthToken}, so this is the normal state on every reload.
2217
+ * There is no other identity to replay as, so such a write must be HELD,
2218
+ * never dropped — dropping here destroys the queuing user's own offline
2219
+ * writes. It is indistinguishable from an explicit sign-out (the fingerprint
2220
+ * is `null` for both), which is the safe conflation: holding a write for a
2221
+ * signed-out app costs a retry, dropping it costs the write.
2222
+ *
2223
+ * It also covers a `null` stamp against a `null` fingerprint — but only
2224
+ * while {@link identityUnresolved} says a session resolve is in flight.
2225
+ * Two `null`s are the same identity for an app with no auth at all (nobody
2226
+ * else shares that fingerprint, because nobody else exists) and for a
2227
+ * client the server has told there is no session; they are NOT the same
2228
+ * identity in the window where the fingerprint is about to become
2229
+ * `subj:<id>`, which is where one browser user's queued write went out on
2230
+ * the next one's cookie.
2231
+ *
2232
+ * A held write is not stranded: the hold ends when the resolve settles, and
2233
+ * both {@link setAuthToken} and {@link getCurrentUser} re-flush there. If
2234
+ * the identity that arrives is not the one that queued the write, the
2235
+ * verdict is then `"mismatch"` and the write is settled terminally.
2236
+ *
2237
+ * A sticky subject carried across a token change is `"unknown"` for the same
2238
+ * reason: the label says user A, the credential in hand has not been checked
2239
+ * against it, and the two answers (a refresh vs an account switch) call for
2240
+ * opposite verdicts. Hold until the next session resolve settles it.
2241
+ *
2242
+ * `"mismatch"` is a different identity signed in, and is the one that must be
2243
+ * terminal: replaying would attribute one user's write to another and pass
2244
+ * THEIR row-level security.
2245
+ *
2246
+ * A `"match"` carries the {@link ReplayCredential} the replay must be sent
2247
+ * with ({@link MutationCallOptions.replayCredential}): the bearer held right
2248
+ * now, which is the one this verdict judged. The replay goes out with it even
2249
+ * if the token changes before the send, and the outbox's next attempt judges
2250
+ * again against whatever is current then.
2251
+ */
2252
+ replayIdentityVerdict(stamped: null | string | undefined): ReplayIdentityVerdict;
2253
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
2254
+ clientIdentifier(): string;
2255
+ /**
2256
+ * The highest custom-mutator watermark the server has echoed for this client
2257
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
2258
+ * its `clientSeq` generator from this so a reload never reissues a sequence
2259
+ * the server has already applied (which it would swallow as a replay, silently
2260
+ * dropping the write).
2261
+ */
2262
+ confirmedMutationWatermark(shardKey?: string): number;
2263
+ /**
2264
+ * Push a custom mutator to its authoritative server impl over the watermark
2265
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
2266
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
2267
+ * client's `__client_watermark`.
2268
+ *
2269
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
2270
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
2271
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
2272
+ * A `false` verdict tells the caller to reissue above the now-known watermark
2273
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
2274
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
2275
+ *
2276
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
2277
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
2278
+ */
2279
+ callMutator(functionPath: string, args: Record<string, unknown>, options?: {
2280
+ clientSeq?: number;
2281
+ shardKey?: string;
2282
+ }): Promise<{
2283
+ applied: boolean;
2284
+ result: unknown;
2285
+ }>;
2286
+ /**
2287
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
2288
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
2289
+ * the current value.
2290
+ */
2291
+ onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
2292
+ /**
2293
+ * Subscribe to a user switch or sign-out: fired after {@link setAuthToken}
2294
+ * retires the previous identity's session, i.e. every live subscription has
2295
+ * just been blanked to `undefined` and its socket closed. Not fired when a
2296
+ * bearer identity is first established from signed-out (nothing is
2297
+ * retired), nor when a subject is attached to the same credential, nor on
2298
+ * a cookie session's first answer after page load.
2299
+ *
2300
+ * A cookie session fires it on every change the server reports — sign-out,
2301
+ * a sign-in after a known sign-out, a different user — whether the answer
2302
+ * came from {@link getCurrentUser} or from a socket's `identity` frame. Its
2303
+ * sign-out changes nothing the client can observe on its own; in a browser
2304
+ * the client also re-resolves whenever `@lunora/auth-ui` or the
2305
+ * `lunoraSessionSync()` better-auth plugin reports a session change.
2306
+ *
2307
+ * For caches layered on top of the client. A subscriber only hears the
2308
+ * blank for queries it still subscribes to, so a cache that keeps values for
2309
+ * unmounted queries must drop them here, or the next user can read the
2310
+ * previous user's rows from it.
2311
+ */
2312
+ onIdentityChange(listener: () => void): Unsubscribe;
2313
+ /**
2314
+ * How many identities this client has retired since it was constructed —
2315
+ * the number of times {@link onIdentityChange} has fired. Already moved when
2316
+ * those listeners run.
2317
+ *
2318
+ * A value rendered on the server (a `Preloaded` token) was read for whoever
2319
+ * was signed in when the page loaded, so it is only safe to show while this
2320
+ * is `0`: once a sign-out or user switch has retired that identity, a
2321
+ * component mounting later must not seed the previous user's rows.
2322
+ */
2323
+ identityEpoch(): number;
2324
+ /**
2325
+ * Fetch the currently authenticated user from better-auth's `get-session`
2326
+ * endpoint, returning the `user` record or `null` when signed out. Sends
2327
+ * the stored bearer token (if any) and `credentials: "include"` so a
2328
+ * cookie-session is also honoured.
2329
+ *
2330
+ * `null` means the **server answered** that there is no session — an empty
2331
+ * body, no `user` field, or a non-OK status such as 401. A network or parse
2332
+ * failure **rejects** instead, because "the endpoint was unreachable" is not
2333
+ * the same answer as "you are signed out": collapsing the two made an
2334
+ * offline reload with a valid stored token read as a sign-out in every
2335
+ * adapter's auth gate. Callers that cannot act on the difference can still
2336
+ * `.catch(() => null)`; `@lunora/client/auth`'s identity store maps the
2337
+ * rejection to the `"unreachable"` status instead.
2338
+ *
2339
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
2340
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
2341
+ *
2342
+ * A resolved user also ESTABLISHES the identity subject for the credential
2343
+ * that resolved it ({@link setAuthToken}'s second argument). This is the one
2344
+ * call every adapter's identity store already makes, and the only place that
2345
+ * knows the answer — leaving it to each adapter is what left the sticky-subject
2346
+ * contract unreached in every shipped one, so a routine JWT refresh read as a
2347
+ * user switch and discarded the user's own queued writes and read cache.
2348
+ *
2349
+ * Under a cookie session (no token held) the answer is adopted whatever it
2350
+ * is, "no session" included, and a change from the identity already known
2351
+ * retires the previous session — see {@link onIdentityChange}.
2352
+ */
2353
+ getCurrentUser(): Promise<User | null>;
2354
+ /**
2355
+ * Replace the token appended to WS upgrade URLs as `?token=…` and close
2356
+ * every open shard socket so the reconnect picks up the new value. Call
2357
+ * this whenever the user's WS credential changes (rotating the admin token
2358
+ * in the studio, switching workspaces, etc.). Accepts a static string or a
2359
+ * {@link WsTokenProvider} resolved fresh at every (re)connect — the channel
2360
+ * for short-lived credentials like the minted ephemeral admin sub-token.
2361
+ * Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
2362
+ */
2363
+ setWsToken(token: string | undefined | WsTokenProvider): void;
2364
+ /**
2365
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
2366
+ * envelope for a shard's socket, overriding the client-wide
2367
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
2368
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
2369
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
2370
+ * presence row is removed the instant the socket drops, with no TTL lag.
2371
+ *
2372
+ * Stored per shard and replayed on every (re)connect. When a socket for the
2373
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
2374
+ * server sees the new context without waiting for a reconnect.
2375
+ *
2376
+ * Not available on a `crossTabSync` FOLLOWER tab — the context rides the
2377
+ * `connect` envelope of a socket a follower does not own, so it would be
2378
+ * stored and never sent. Throws `NOT_IMPLEMENTED` there.
2379
+ */
2380
+ setConnectionContext(context: Record<string, unknown> | undefined, options?: {
2381
+ shardKey?: string;
2382
+ }): void;
2383
+ /**
2384
+ * Refcounted variant of {@link setConnectionContext}: register a connection
2385
+ * `context` for a shard and get back a release function. Unlike the imperative
2386
+ * setter, the context is only cleared once the *last* acquired holder releases
2387
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
2388
+ * shard no longer clobber each other's context when one of them unmounts. The
2389
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
2390
+ * the top holder falls back to the previous one rather than clearing.
2391
+ *
2392
+ * With a single holder the behaviour is identical to a
2393
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
2394
+ * Releasing more than once is a no-op (the holder is matched by reference, so
2395
+ * a double release can't drop a different holder).
2396
+ */
2397
+ acquireConnectionContext(context: Record<string, unknown>, options?: {
2398
+ shardKey?: string;
2399
+ }): Unsubscribe;
2400
+ /**
2401
+ * Join a whisper `topic` and receive every ephemeral message other members
2402
+ * broadcast to it on the same shard (typing indicators, live cursors,
2403
+ * presence pings). Whispers never touch the server's durable state — there's
2404
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
2405
+ * is left on the server once its last local handler unsubscribes.
2406
+ *
2407
+ * `handler` receives the raw `data` and the sender's verified `from` user id
2408
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
2409
+ * (the default shard when omitted) — use the same shard you target with the
2410
+ * matching queries/mutations so members land on the same Durable Object.
2411
+ *
2412
+ * Security: a whisper topic is access-controlled only if the app declares an
2413
+ * `onWhisper` authorizer server-side (`@lunora/server`). Without one, the
2414
+ * topic's only boundary is the shard — any client that can open a socket to it
2415
+ * can join, read, and inject on any topic name. `from` is server-stamped and
2416
+ * unforgeable either way, but never trust a whisper's `data` as authorization,
2417
+ * and remember that even an authorized topic is transient awareness with no
2418
+ * durable trace: anything privileged belongs behind a query/mutation with RLS.
2419
+ *
2420
+ * A denied join is silent — whispers are never acked, so nothing distinguishes
2421
+ * "denied" from "nobody is whispering". Gate the UI on a query you can read a
2422
+ * verdict from, not on whether whispers arrive.
2423
+ *
2424
+ * Not available on a `crossTabSync` FOLLOWER tab — whisper frames are not
2425
+ * relayed over the cross-tab channel, so this throws `NOT_IMPLEMENTED`
2426
+ * there rather than registering a handler nothing can ever reach. See
2427
+ * {@link LunoraClientOptions.crossTabSync}.
2428
+ */
2429
+ whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
2430
+ shardKey?: string;
2431
+ }): Unsubscribe;
2432
+ /**
2433
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
2434
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
2435
+ * dropped when the shard socket isn't open (whispers are transient, never
2436
+ * queued), and the server silently drops it if the sender exceeds its
2437
+ * whisper rate budget. The sender never receives its own whisper. Omitting
2438
+ * `data` delivers JSON `null` to receivers (not `undefined`).
2439
+ *
2440
+ * That best-effort drop is for a socket that is momentarily down. A
2441
+ * `crossTabSync` FOLLOWER tab has no socket and never will (see
2442
+ * {@link LunoraClientOptions.crossTabSync}), so every whisper from it would
2443
+ * be dropped forever — it throws `NOT_IMPLEMENTED` instead.
2444
+ *
2445
+ * A send the app's `onWhisper` authorizer denies is dropped the same silent
2446
+ * way, for the same reason: there is no ack frame to report it on. See
2447
+ * {@link whisperSubscribe} for the security model.
2448
+ */
2449
+ whisper(topic: string, data?: unknown, options?: {
2450
+ shardKey?: string;
2451
+ }): void;
2452
+ /**
2453
+ * Subscribe to token-expiry events: invoked whenever the server drops a
2454
+ * shard socket because the connection's credential lapsed (close code
2455
+ * `4001`). The client already reconnects automatically (re-resolving
2456
+ * identity from the cookie/token in effect); use this to refresh a
2457
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
2458
+ * with a freshly minted one. Returns an unsubscribe function.
2459
+ *
2460
+ * Also fired, once per credential, when a queued write's replay is refused
2461
+ * `TOKEN_EXPIRED` / `UNAUTHENTICATED`. The write is held for the refresh, and
2462
+ * survives it only if the identity is keyed on a `subject`: pass the same user
2463
+ * id with the new token, `setAuthToken(freshToken, user.id)` (or have passed
2464
+ * it before — the subject is sticky). With no subject the identity is the
2465
+ * token hash, so a refresh cannot be told from an account switch and the held
2466
+ * writes are rejected `OFFLINE_IDENTITY_CHANGED`. A cookie session has no
2467
+ * token to replace: renew the cookie, and the held write is re-sent on a
2468
+ * backoff with it.
2469
+ */
2470
+ onTokenExpired(listener: () => void): Unsubscribe;
2471
+ /**
2472
+ * Current aggregate live-socket status across all shard connections. See
2473
+ * {@link ConnectionStatus}.
2474
+ */
2475
+ connectionStatus(): ConnectionStatus;
2476
+ /**
2477
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
2478
+ * immediately with the current status, then on every transition. Returns an
2479
+ * unsubscribe function.
2480
+ */
2481
+ onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
2482
+ /**
2483
+ * Number of offline writes waiting in the built-in queue to be sent — the
2484
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
2485
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
2486
+ * A `@lunora/db` app whose writes ride the unified outbox should read
2487
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
2488
+ */
2489
+ pendingCount(): number;
2490
+ /**
2491
+ * A point-in-time snapshot of everything the sync engine believes right now:
2492
+ * per-shard sockets and watermarks, every live query and shape subscription with
2493
+ * its cursor and ack state, and the offline-queue depth.
2494
+ *
2495
+ * This exists because the alternative is `console.log`. When an optimistic
2496
+ * overlay doesn't clear, the questions are always the same — *is the socket open?
2497
+ * what watermark has the server confirmed for this shard? has this shape been
2498
+ * poked since my write? is anything stuck in the queue?* — and none of them were
2499
+ * answerable from outside the client, so every adopter ends up instrumenting the
2500
+ * library by hand or building a bespoke policy layer around a symptom.
2501
+ *
2502
+ * Read it from a devtools console, log it next to a bug report, or render it in a
2503
+ * debug panel. Pull-only and allocation-cheap; nothing here is reactive, so poll
2504
+ * it or read it on demand.
2505
+ *
2506
+ * ```ts
2507
+ * const { shards, subscriptions } = client.debug();
2508
+ * // shards: [{ shardKey: "user-1", wsState: "open", confirmedMutationWatermark: 42, … }]
2509
+ * ```
2510
+ */
2511
+ debug(): ClientDebugSnapshot;
2512
+ /**
2513
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
2514
+ * with the current count, then whenever the queue depth changes (a write is
2515
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
2516
+ */
2517
+ onPendingChange(listener: (pending: number) => void): Unsubscribe;
2518
+ /**
2519
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
2520
+ * fires once per queued write that commits or is rejected — including a write
2521
+ * restored from durable storage after a reload, whose original `mutation()`
2522
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
2523
+ * evicts on overflow or discards on an identity change. This is the durable
2524
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
2525
+ * mutation that never queued still surfaces through the Promise `mutation()`
2526
+ * returns. The listener is NOT invoked on registration. Returns an
2527
+ * unsubscribe function. See {@link MutationSettledEvent}.
2528
+ */
2529
+ onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
2530
+ /**
2531
+ * The `WebSocket` implementation this client was constructed with (an
2532
+ * explicit `options.WebSocket`, or the ambient global on platforms that have
2533
+ * one) — `undefined` if neither is available. This is the seam a feature
2534
+ * that opens its OWN socket outside the client's multiplexed connection
2535
+ * (e.g. a voice-agent hook) should default to, instead of reaching for
2536
+ * `globalThis.WebSocket` directly: on React Native the client wraps this
2537
+ * constructor to inject the auth-headers factory's credential onto the
2538
+ * upgrade request (`createLunoraClient`'s `withAuthWebSocket`), which a raw
2539
+ * `new globalThis.WebSocket(url)` would silently bypass.
2540
+ */
2541
+ getWebSocketImpl(): typeof WebSocket | undefined;
2542
+ /**
2543
+ * Read the current value for a {@link ClientQueryRef}. Returns
2544
+ * `ref.defaultValue` when no value has been explicitly set.
2545
+ */
2546
+ getClientQuery<T>(ref: ClientQueryRef<T>): T;
2547
+ /**
2548
+ * Set a new value for `ref` and notify every subscriber. Pass `undefined`
2549
+ * to reset the slot to `ref.defaultValue`.
2550
+ */
2551
+ setClientQuery<T>(ref: ClientQueryRef<T>, value: T): void;
2552
+ /**
2553
+ * Subscribe to changes for `ref`. The callback is NOT invoked on
2554
+ * registration — call {@link getClientQuery} for the current value.
2555
+ * Returns an unsubscribe function.
2556
+ */
2557
+ subscribeClientQuery(ref: ClientQueryRef, callback: (value: unknown) => void): Unsubscribe;
2558
+ /**
2559
+ * Reset a {@link ClientQueryRef} to its default value, notifying every
2560
+ * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
2561
+ * removes the stored entry so a future {@link getClientQuery} returns
2562
+ * the default rather than an explicitly-set value.
2563
+ */
2564
+ resetClientQuery(ref: ClientQueryRef): void;
2565
+ /**
2566
+ * Capture a snapshot of the current live query value at call time and
2567
+ * produce a `() => boolean` precondition that compares it against the
2568
+ * value at replay time (on queue drain / reconnect).
2569
+ *
2570
+ * Delegates to {@link createSnapshotPrecondition} with this client bound —
2571
+ * no need to pass `client` explicitly. The comparison semantics (including
2572
+ * how an absent subscription is treated) live there, in one place.
2573
+ * @example
2574
+ * ```ts
2575
+ * client.mutation(api.todos.update, { id, text }, {
2576
+ * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
2577
+ * });
2578
+ * ```
2579
+ */
2580
+ snapshotPrecondition(functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string): () => boolean;
2581
+ /**
2582
+ * Resolves once the durable read cache has been loaded into memory. When
2583
+ * `hydrateOnStart` is not configured or no query cache adapter is active,
2584
+ * returns an already-resolved promise so callers can always await it
2585
+ * unconditionally.
2586
+ *
2587
+ * Framework adapters (React, Vue, etc.) use this to gate the first
2588
+ * (enabled) render of a live query behind hydration, so the user sees
2589
+ * cached data instead of an undefined flash before the socket round-trip.
2590
+ */
2591
+ whenReady(): Promise<void>;
2592
+ /**
2593
+ * Synchronously reports whether {@link whenReady} has already resolved (the
2594
+ * durable read cache is loaded, or none is configured). Framework adapters
2595
+ * read this to seed the hydration-gate state on the first render without
2596
+ * awaiting, then subscribe via {@link whenReady} for the pending case.
2597
+ */
2598
+ get isReady(): boolean;
2599
+ /**
2600
+ * Synchronously peek at a value the durable read cache loaded for the given
2601
+ * function path + args + shard key. Returns `undefined` when:
2602
+ *
2603
+ * - No query cache adapter is configured.
2604
+ * - Hydration hasn't completed yet (race — await {@link whenReady} first).
2605
+ * - The cached value's identity fingerprint doesn't match the current auth.
2606
+ *
2607
+ * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
2608
+ * the cached entry stays in `hydratedQueryCache` so the subscription created
2609
+ * later by {@link subscribe} consumes it normally.
2610
+ */
2611
+ peekHydratedQuery(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
2612
+ /**
2613
+ * Peek at the **current live value** of an active subscription, reporting
2614
+ * whether one exists at all rather than just its value. `present` is `false`
2615
+ * when no subscription is open for the given `(functionPath, args, shardKey)`;
2616
+ * `value` is the subscription's `lastValue`, which includes any optimistic
2617
+ * overlay.
2618
+ *
2619
+ * The two are separate because a caller like the snapshot precondition has to
2620
+ * tell "no subscription is active, so this read knows nothing" apart from
2621
+ * "the subscription is active and its value is `undefined`" — collapsing both
2622
+ * into a bare `undefined` return makes an unmounted component look like a
2623
+ * changed value, and drops the queued write.
2624
+ *
2625
+ * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
2626
+ * and is independent of active subscriptions), this reflects the current
2627
+ * in-memory state of an already-opened subscription.
2628
+ */
2629
+ peekActiveQuerySnapshot(functionPath: string, args: Record<string, unknown>, shardKey?: string): {
2630
+ present: boolean;
2631
+ value: unknown;
2632
+ };
2633
+ query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
2634
+ shardKey?: string;
2635
+ }): Promise<ReturnOf<F>>;
2636
+ /**
2637
+ * Batch several independent calls into ONE round trip (plan 088). Each call is
2638
+ * dispatched server-side exactly as an individual RPC — per-shard
2639
+ * authorization, `(identity, mutationId)` idempotency, and custom-mutator
2640
+ * watermark ordering are all preserved — and the worker splits the batch by
2641
+ * shard so calls to different shards fan out to their own DOs. Results are
2642
+ * demuxed back in input order; a failing call does NOT fail the batch (its
2643
+ * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
2644
+ * a single call). Args/results ride the value codec (bytes/bigint survive).
2645
+ *
2646
+ * No promise pipelining and no capability passing — a call's args cannot
2647
+ * reference another call's result (see plan 088 §fence; capabilities are
2648
+ * incompatible with DO hibernation).
2649
+ */
2650
+ batch(calls: ReadonlyArray<{
2651
+ args?: Record<string, unknown>;
2652
+ fn: FunctionReference;
2653
+ shardKey?: string;
2654
+ }>): Promise<BatchSlot[]>;
2655
+ /**
2656
+ * Invoke a mutation. Errors propagate as rejections.
2657
+ *
2658
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
2659
+ * only when the targeted shard's socket was open at least once already
2660
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
2661
+ * Mutations issued before the very first WS connect to a shard fail fast.
2662
+ * Opt into queueing-before-first-connect via
2663
+ * `OfflineQueueOptions.queueBeforeFirstConnect`.
2664
+ *
2665
+ * **Return-value caveat — the queued paths do not carry the server's result.**
2666
+ * The declared `Promise<ReturnOf<F>>` only holds when the write goes straight
2667
+ * to the server. Once a write is queued:
2668
+ *
2669
+ * - with a durable `outbox` configured, this resolves **immediately with
2670
+ * `undefined`** (typed as `ReturnOf<F>`) the moment the write is handed to
2671
+ * the outbox — the replay happens later, out of band, with no awaiter;
2672
+ * - with the built-in offline queue, it stays pending until the replay lands
2673
+ * and then resolves with the replayed call's value.
2674
+ *
2675
+ * So `const id = await client.mutation(api.todos.create, …)` is `undefined`
2676
+ * for every write issued while offline under an outbox. Generate ids
2677
+ * client-side (or read them back from a subscription) rather than depending
2678
+ * on a mutation's return value in an offline-capable app —
2679
+ * {@link LunoraClient.importRows} documents the same caveat for its counts.
2680
+ */
2681
+ mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
2682
+ /**
2683
+ * Whether a {@link mutation} on `shardKey` would be queued (offline queue or
2684
+ * durable outbox) rather than fail when the network is down. `false` before
2685
+ * the shard's first connect (unless `queueBeforeFirstConnect` is set) and on
2686
+ * a client with no WebSocket. A caller that wants to hold a write until the
2687
+ * network returns must do so itself when this is `false`.
2688
+ */
2689
+ canQueueOffline(shardKey?: string): boolean;
2690
+ action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: ActionCallOptions): Promise<ReturnOf<F>>;
2691
+ /**
2692
+ * Bulk-import `rows` through a mutation that accepts a batch, chunked so a large
2693
+ * dataset lands in a bounded number of round-trips.
2694
+ *
2695
+ * **Queued chunks:** `imported` counts only rows the server committed. A chunk a
2696
+ * durable outbox took instead (offline, or behind older queued writes) is counted
2697
+ * in `queued`; the outbox replays it later under the same key. The built-in
2698
+ * offline queue holds the call until each chunk commits, so its rows land in
2699
+ * `imported`. Report "migration complete" only when `queued` is `0`.
2700
+ *
2701
+ * This is the one-shot migration / seed path: "I have 20k rows client-side and a
2702
+ * server mutation that inserts many at once". Doing it by hand goes wrong in two
2703
+ * predictable ways — a serial per-row loop pays one round-trip *and* one watermark
2704
+ * wait per row (a 200-row import becomes 200 sequential hops), while a single
2705
+ * giant call blows the DO's batch limit. So: chunk, send sequentially, and give
2706
+ * each chunk a stable idempotency key derived from `importId` + its index, so a
2707
+ * resumed or retried import doesn't double-insert the chunks that already landed
2708
+ * (for an anonymous caller only while the `clientId` is the same; see `importId`).
2709
+ *
2710
+ * The server mutation is yours (Lunora can't guess the table or the row shape);
2711
+ * back it with `ctx.db.insertMany(...)`, or `insertManyUnsafe(...)` for data you
2712
+ * vouch for. `chunkSize` defaults to 500, matching the DO's default batch cap.
2713
+ *
2714
+ * ```ts
2715
+ * await client.importRows(api.migrate.importNodes, nodes, {
2716
+ * importId: `migrate-${userId}`,
2717
+ * onProgress: ({ done, total }) => setProgress(done / total),
2718
+ * shardKey: userId,
2719
+ * toArgs: (chunk) => ({ nodes: chunk }),
2720
+ * });
2721
+ * ```
2722
+ */
2723
+ importRows(function_: FunctionReference, rows: ReadonlyArray<unknown>, options?: {
2724
+ /** Rows per call. Defaults to 500 — the DO's default batch cap. */
2725
+ chunkSize?: number;
2726
+ /**
2727
+ * Stable id for this import run. Each chunk is sent under
2728
+ * `${importId}:${chunkIndex}` as its mutation id, so re-running an import
2729
+ * that uses the SAME `chunkSize` re-sends each chunk under its prior key
2730
+ * and the server dedupes it instead of inserting twice.
2731
+ *
2732
+ * CAVEAT — the key is POSITIONAL, not content-based: it pins on the chunk
2733
+ * INDEX, not on the rows inside it. Resume or retry with a DIFFERENT
2734
+ * `chunkSize` (or a changed row ordering) and index N now covers different
2735
+ * rows than the first run's index N; the server sees a duplicate key and
2736
+ * SILENTLY DROPS those rows. Keep `chunkSize` (and the row order) identical
2737
+ * across resumes of the same `importId`. Omit `importId` only for a
2738
+ * throwaway import where double-insertion is acceptable.
2739
+ *
2740
+ * CAVEAT — anonymous callers: the server scopes the key to the signed-in
2741
+ * user, or to the client's `clientId` when nobody is signed in. A
2742
+ * `LunoraClient` mints a fresh `clientId` on every construction, so an
2743
+ * anonymous import resumed after a reload is not deduped and inserts the
2744
+ * landed chunks again. Pass a persisted `clientId` to the constructor to
2745
+ * resume anonymously, or run the import signed in.
2746
+ */
2747
+ importId?: string;
2748
+ /**
2749
+ * Called after each chunk is accepted — for a progress bar. `done` counts
2750
+ * committed and queued rows alike; the result separates them.
2751
+ */
2752
+ onProgress?: (progress: {
2753
+ done: number;
2754
+ total: number;
2755
+ }) => void;
2756
+ /** Routes every chunk to one shard's DO. */
2757
+ shardKey?: string;
2758
+ /** Build the mutation args for one chunk. Defaults to `{ rows: chunk }`. */
2759
+ toArgs?: (chunk: ReadonlyArray<unknown>) => Record<string, unknown>;
2760
+ }): Promise<{
2761
+ chunks: number;
2762
+ imported: number;
2763
+ queued: number;
2764
+ }>;
2765
+ /**
2766
+ * Read the cross-shard request distribution for a `.shardBy(...)` table —
2767
+ * the feed the studio's `hot_shard` advisor lint consumes. Hits the
2768
+ * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
2769
+ * cheap per-shard `getMetrics` read out across every live shard and returns
2770
+ * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
2771
+ * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
2772
+ * and `adminToken`, and this client's auth token to match; defaults any
2773
+ * absent field so an older worker yields an empty-but-valid shape.
2774
+ */
2775
+ shardTraffic(table: string): Promise<ShardTrafficResult>;
2776
+ /**
2777
+ * List the functions queued via `runAfter` / `runAt`, soonest-due last
2778
+ * (the worker returns them in storage order). Hits the admin-gated
2779
+ * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
2780
+ * `schedulerDO` namespace and `adminToken`, and this client's auth token
2781
+ * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
2782
+ */
2783
+ listScheduledJobs(): Promise<ScheduleRecord[]>;
2784
+ /**
2785
+ * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
2786
+ * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
2787
+ * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
2788
+ * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
2789
+ * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
2790
+ * namespace + `adminToken` on the worker and a matching auth token here).
2791
+ * Defaults any absent field so an older worker still yields a valid shape.
2792
+ */
2793
+ schedulerStatus(): Promise<SchedulerStatus>;
2794
+ /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
2795
+ cancelScheduledJob(id: string): Promise<{
2796
+ cancelled: boolean;
2797
+ }>;
2798
+ /**
2799
+ * List the dead-letter jobs: schedules that exhausted their retry budget
2800
+ * and were parked instead of dropped. These never appear in
2801
+ * {@link listScheduledJobs} (their live header is gone), so this is the only
2802
+ * way the studio surfaces a permanently-failed job. Hits the admin-gated
2803
+ * `GET /_lunora/admin/scheduled/dead`; same preconditions as
2804
+ * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
2805
+ */
2806
+ listDeadJobs(): Promise<ScheduleRecord[]>;
2807
+ /**
2808
+ * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
2809
+ * retry budget and fires on the next drain. Returns whether a parked record
2810
+ * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
2811
+ */
2812
+ retryDeadJob(id: string): Promise<{
2813
+ retried: boolean;
2814
+ }>;
2815
+ /**
2816
+ * Permanently drop a dead-letter job by id (the operator has decided not to
2817
+ * recover it). Returns whether a parked record was removed. Hits the
2818
+ * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
2819
+ */
2820
+ removeDeadJob(id: string): Promise<{
2821
+ removed: boolean;
2822
+ }>;
2823
+ /**
2824
+ * List a workflow's instances via the admin Workflows proxy
2825
+ * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
2826
+ * the `Workflow` binding can't expose. Requires the worker to be built with a
2827
+ * `workflowsClient` (Cloudflare account id + API token). When one isn't
2828
+ * configured this does NOT reject: the proxy returns a `200 { configured:
2829
+ * false }` sentinel, so the result resolves with `configured === false` and an
2830
+ * empty `instances` list — callers should branch on that flag rather than
2831
+ * try/catch. (The instance-detail / status endpoints still reject with 501.)
2832
+ * `name` is the deployed workflow name.
2833
+ */
2834
+ listWorkflowInstances(options: {
2835
+ name: string;
2836
+ page?: number;
2837
+ perPage?: number;
2838
+ status?: WorkflowInstanceStatus;
2839
+ }): Promise<WorkflowInstancePage>;
2840
+ /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
2841
+ getWorkflowInstance(options: {
2842
+ id: string;
2843
+ name: string;
2844
+ }): Promise<WorkflowInstanceDetail>;
2845
+ /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
2846
+ setWorkflowInstanceStatus(options: {
2847
+ action: WorkflowInstanceAction;
2848
+ id: string;
2849
+ name: string;
2850
+ }): Promise<{
2851
+ status: WorkflowInstanceStatus;
2852
+ }>;
2853
+ /**
2854
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
2855
+ * WebSocket. `onJobs` fires with the full list on connect and on every
2856
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
2857
+ * configured backoff. Requires `wsToken` to be set to an admin credential
2858
+ * (the browser can't send an `Authorization` header on a WS) — the master
2859
+ * token, or preferably a {@link WsTokenProvider} minting the ephemeral
2860
+ * sub-token so the master credential stays out of the URL. Returns an
2861
+ * unsubscribe function that closes the socket and stops reconnecting.
2862
+ */
2863
+ subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
2864
+ /**
2865
+ * List the registered public functions (queries / mutations / actions) with
2866
+ * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
2867
+ * the worker must be built with a `functions` registry and `adminToken`, and
2868
+ * this client's auth token must match. Powers `@lunora/studio`'s function
2869
+ * runner auto-discovery.
2870
+ */
2871
+ listFunctions(): Promise<FunctionDescriptor[]>;
2872
+ /**
2873
+ * List the code-defined cron triggers (the `cronJobs()` map injected on the
2874
+ * worker), each flattened to its firing `cron` expression. Hits the
2875
+ * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
2876
+ * built with a `cronJobs` map and `adminToken`, and this client's auth token
2877
+ * must match. These are static (Cloudflare exposes no runtime cron
2878
+ * introspection), so the studio renders them read-only alongside the dynamic
2879
+ * scheduler jobs.
2880
+ */
2881
+ getCronJobs(): Promise<CronJobInfo[]>;
2882
+ /**
2883
+ * Manually fire one code-defined cron job by name — the same dispatch the
2884
+ * scheduled trigger runs (dispatch the function, or start the durable
2885
+ * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
2886
+ * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
2887
+ * and this client's auth token must match. Resolves when the job has run (a
2888
+ * function job's shard response is 2xx, or the workflow instance was created)
2889
+ * and rejects with the dispatch error otherwise.
2890
+ */
2891
+ runCronJob(name: string): Promise<{
2892
+ name: string;
2893
+ ran: boolean;
2894
+ }>;
2895
+ /**
2896
+ * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
2897
+ * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
2898
+ * `openApiSpec` and `adminToken`, and this client's auth token must match.
2899
+ * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
2900
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
2901
+ * document (no `paths`), so callers can render a "not configured" state.
2902
+ */
2903
+ fetchOpenApi(): Promise<Record<string, unknown>>;
2904
+ /**
2905
+ * Fetch the generated architecture manifest (module catalog + static call
2906
+ * graph). Hits the admin-gated `GET /_lunora/admin/architecture` endpoint.
2907
+ * Codegen emits the manifest once the app declares a module
2908
+ * (`lunora/<dir>/module.ts`); until then the endpoint answers an empty one
2909
+ * (no modules, nodes or edges). Powers `@lunora/studio`'s Architecture view.
2910
+ */
2911
+ fetchArchitecture(): Promise<Record<string, unknown>>;
2912
+ /**
2913
+ * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
2914
+ * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
2915
+ * `openRpcSpec` and `adminToken`, and this client's auth token must match.
2916
+ * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
2917
+ * `POST /_lunora/rpc` transport); it documents the RPC functions only.
2918
+ * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
2919
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
2920
+ * document (no `methods`), so callers can render a "not configured" state.
2921
+ */
2922
+ fetchOpenRpc(): Promise<Record<string, unknown>>;
2923
+ /**
2924
+ * List objects in the storage bucket, optionally under a `prefix` and from a
2925
+ * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
2926
+ * endpoint — the worker must be built with a `storageList` function and
2927
+ * `adminToken`, and this client's auth token must match. Powers
2928
+ * `@lunora/studio`'s file browser.
2929
+ */
2930
+ listStorageObjects(options?: {
2931
+ bucket?: string;
2932
+ cursor?: string;
2933
+ limit?: number;
2934
+ prefix?: string;
2935
+ }): Promise<StorageListPage>;
2936
+ /**
2937
+ * Delete one object from the storage bucket by key. Hits the admin-gated
2938
+ * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
2939
+ * with a `storageDelete` function and `adminToken`. Powers the studio file
2940
+ * browser's per-row delete; resolves `{ deleted, key }`.
2941
+ *
2942
+ * An absent `deleted` field reads as `false`, matching every sibling admin
2943
+ * verb (`runCronJob`'s `ran`, …): the studio renders this value as the row's
2944
+ * outcome, so defaulting a missing field to success would report a delete
2945
+ * that a mismatched/older worker never performed.
2946
+ */
2947
+ deleteStorageObject(key: string, options?: {
2948
+ bucket?: string;
2949
+ }): Promise<{
2950
+ deleted: boolean;
2951
+ key: string;
2952
+ }>;
2953
+ /**
2954
+ * List the storage bucket names the worker exposes, for the studio file
2955
+ * browser's bucket picker. Hits the admin-gated
2956
+ * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
2957
+ * array when the worker configures no `storageBuckets`, i.e. single-bucket).
2958
+ */
2959
+ listStorageBuckets(): Promise<string[]>;
2960
+ /**
2961
+ * Upload one object to the storage bucket. Hits the admin-gated
2962
+ * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
2963
+ * optional `contentType` header — the worker must be built with a
2964
+ * `storageUpload` function and `adminToken`. Powers the studio file
2965
+ * browser's upload control; resolves `{ etag?, key }`.
2966
+ */
2967
+ uploadStorageObject(options: {
2968
+ body: ArrayBuffer | Blob;
2969
+ bucket?: string;
2970
+ contentType?: string;
2971
+ key: string;
2972
+ }): Promise<{
2973
+ etag?: string;
2974
+ key: string;
2975
+ }>;
2976
+ /**
2977
+ * Build a (signed or public) URL for one object. Hits the admin-gated
2978
+ * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
2979
+ * with a `storageSignedUrl` function and `adminToken`. Powers the studio
2980
+ * file browser's copy-URL action; resolves the URL string.
2981
+ *
2982
+ * `options.expiresInSeconds` requests a share-link lifetime, which is
2983
+ * validated/clamped server-side. The options object mirrors the worker's
2984
+ * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
2985
+ * as future fields there).
2986
+ */
2987
+ signedStorageUrl(key: string, options?: {
2988
+ bucket?: string;
2989
+ expiresInSeconds?: number;
2990
+ }): Promise<string>;
2991
+ /**
2992
+ * List the `.global()` (D1-backed) tables with their row counts. Hits the
2993
+ * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
2994
+ * be built with a `globalIntrospector` and `adminToken`. Powers the data
2995
+ * browser's global mode.
2996
+ */
2997
+ listGlobalTables(): Promise<GlobalTableInfo[]>;
2998
+ /**
2999
+ * Read a page of rows from one `.global()` table. `filters` AND-narrows the
3000
+ * page to rows matching each `column = value` eq constraint — the drill-down a
3001
+ * facet-value click applies; the array is wire-encoded, JSON-encoded into the
3002
+ * `filters` query param, and the values are bound server-side.
3003
+ *
3004
+ * The response is `decodeWire`d. The worker encodes it (`readGlobalTablePage`
3005
+ * in `@lunora/d1`) because JSON cannot carry a `v.bigint()` column at all and
3006
+ * silently flattens a `v.bytes()` one to `{}` — so without the decode here the
3007
+ * grid renders the raw 3-element tagged array instead of the value. The shard
3008
+ * browser's twin already pairs the same way through `rpc`; this is the global
3009
+ * half of that symmetry.
3010
+ */
3011
+ readGlobalTablePage(options: {
3012
+ filters?: GlobalFilterClause[];
3013
+ limit?: number;
3014
+ offset?: number;
3015
+ table: string;
3016
+ }): Promise<GlobalTablePage>;
3017
+ /**
3018
+ * Summarise the distinct values of one column in a `.global()` table over the
3019
+ * active view (the same eq `filters` the browser is previewing) — the global
3020
+ * twin of the shard browser's facet. Hits the admin-gated
3021
+ * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
3022
+ * server-side. Powers the global data browser's facet sidebar.
3023
+ *
3024
+ * Wire-encoded/decoded on both legs for the same reason
3025
+ * {@link LunoraClient.readGlobalTablePage} is: a facet over a BLOB column
3026
+ * returns bytes, which `Response.json` flattens to `{}` — and since a facet
3027
+ * value is exactly what a click sends back as a `filters` clause, that is a
3028
+ * broken drill-down rather than a display glitch.
3029
+ */
3030
+ facetGlobalColumn(options: {
3031
+ column: string;
3032
+ filters?: GlobalFilterClause[];
3033
+ limit?: number;
3034
+ table: string;
3035
+ }): Promise<GlobalFacetResult>;
3036
+ /**
3037
+ * List the schema's Vectorize indexes with their declared shape (table,
3038
+ * field, dimensions, metric, metadata) and live stats (vector count,
3039
+ * processing watermark) when the binding is reachable. Hits the admin-gated
3040
+ * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
3041
+ * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
3042
+ * browser. Vectorize can't enumerate indexes at runtime, so this list comes
3043
+ * from the generated `LUNORA_VECTOR_INDEXES` registry.
3044
+ */
3045
+ listVectorIndexes(): Promise<VectorIndexSummary[]>;
3046
+ /**
3047
+ * Run a nearest-neighbour similarity query against one vector index: the
3048
+ * worker embeds `text` via the index's embedder and returns the top matches.
3049
+ * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
3050
+ * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
3051
+ * wired (the index lists read-only).
3052
+ */
3053
+ queryVectorIndex(options: {
3054
+ name: string;
3055
+ text: string;
3056
+ topK?: number;
3057
+ }): Promise<VectorQueryMatch[]>;
3058
+ /**
3059
+ * Read one keyset-paginated page of the durable `ctx.log` archive that
3060
+ * `pipelineLogSink` writes to R2. Server-side only — the worker holds the R2
3061
+ * SQL credentials and runs the reader; the browser only sees the decoded
3062
+ * `{ rows, nextCursor }`. Pass the previous page's `nextCursor` as
3063
+ * `query.cursor` to page. Admin-gated. When the operator hasn't wired the
3064
+ * archive, `adminFetch` throws a `LunoraClientError` with `.code ===
3065
+ * "LOG_ARCHIVE_NOT_CONFIGURED"`, so a caller can render a "not configured"
3066
+ * state rather than an error.
3067
+ */
3068
+ queryLogArchive(query?: PipelineLogQuery): Promise<PipelineLogPage>;
3069
+ /**
3070
+ * List the worker's registered Workers KV namespaces (binding names). Hits
3071
+ * the admin-gated `GET /_lunora/admin/kv/namespaces` endpoint — the worker
3072
+ * must be built with a `kvIntrospector` and `adminToken`. Powers the
3073
+ * studio's KV browser.
3074
+ */
3075
+ listKvNamespaces(): Promise<KvNamespaceSummary[]>;
3076
+ /**
3077
+ * List keys in a KV namespace, optionally filtered by `prefix` and
3078
+ * paginated via `cursor`. Hits the admin-gated
3079
+ * `GET /_lunora/admin/kv/keys` endpoint.
3080
+ */
3081
+ listKvKeys(options: {
3082
+ cursor?: string;
3083
+ limit?: number;
3084
+ namespace: string;
3085
+ prefix?: string;
3086
+ }): Promise<KvKeyListResult>;
3087
+ /**
3088
+ * Read a KV value (as text) and its metadata. Hits the admin-gated
3089
+ * `GET /_lunora/admin/kv/value` endpoint. Returns `{ value: null, metadata: null }`
3090
+ * when the key is absent.
3091
+ */
3092
+ getKvValue(options: {
3093
+ key: string;
3094
+ namespace: string;
3095
+ }): Promise<KvValueResult>;
3096
+ /**
3097
+ * Write a string value to a KV namespace. Accepts an absolute `expiration`
3098
+ * (Unix seconds) or a relative `expirationTtl`, plus optional `metadata` —
3099
+ * re-send the loaded values on edit so a save preserves rather than clears
3100
+ * them. Hits the admin-gated `PUT /_lunora/admin/kv/value` endpoint.
3101
+ */
3102
+ putKvValue(options: {
3103
+ expiration?: number;
3104
+ expirationTtl?: number;
3105
+ key: string;
3106
+ metadata?: unknown;
3107
+ namespace: string;
3108
+ value: string;
3109
+ }): Promise<void>;
3110
+ /**
3111
+ * Delete a key from a KV namespace. No-op when the key is absent. Hits the
3112
+ * admin-gated `DELETE /_lunora/admin/kv/value` endpoint.
3113
+ */
3114
+ deleteKvKey(options: {
3115
+ key: string;
3116
+ namespace: string;
3117
+ }): Promise<void>;
3118
+ /**
3119
+ * List authenticated users, paged and optionally searched / filtered / sorted.
3120
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
3121
+ * must be built with an `authAdmin` and `adminToken`. Powers the studio's
3122
+ * users dashboard.
3123
+ */
3124
+ listAuthUsers(options?: {
3125
+ filterField?: string;
3126
+ filterValue?: string;
3127
+ limit?: number;
3128
+ offset?: number;
3129
+ search?: string;
3130
+ searchField?: string;
3131
+ sortBy?: string;
3132
+ sortDirection?: "asc" | "desc";
3133
+ }): Promise<AuthPage<AuthUser>>;
3134
+ /**
3135
+ * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
3136
+ * endpoint (requires the worker's `authAdmin` to implement `createUser`).
3137
+ * `data` carries any app-defined `user.additionalFields`.
3138
+ */
3139
+ createAuthUser(input: {
3140
+ data?: Record<string, unknown>;
3141
+ email: string;
3142
+ name: string;
3143
+ password?: string;
3144
+ role?: string | string[];
3145
+ }): Promise<AuthUser>;
3146
+ /** Set a user's role (string, or array joined comma-wise server-side). */
3147
+ setAuthUserRole(input: {
3148
+ role: string | string[];
3149
+ userId: string;
3150
+ }): Promise<AuthUser>;
3151
+ /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
3152
+ banAuthUser(input: {
3153
+ expiresInSeconds?: number;
3154
+ reason?: string;
3155
+ userId: string;
3156
+ }): Promise<AuthUser>;
3157
+ /** Lift a user's ban. */
3158
+ unbanAuthUser(input: {
3159
+ userId: string;
3160
+ }): Promise<AuthUser>;
3161
+ /** Set a user's password (admin override — no current-password challenge). */
3162
+ setAuthUserPassword(input: {
3163
+ newPassword: string;
3164
+ userId: string;
3165
+ }): Promise<void>;
3166
+ /** Permanently delete a user and revoke their sessions. */
3167
+ removeAuthUser(input: {
3168
+ userId: string;
3169
+ }): Promise<void>;
3170
+ /**
3171
+ * Mint an impersonation session for a user, returning its bearer `token`.
3172
+ * The caller is responsible for using the token (e.g. setting the session
3173
+ * cookie); the server performs no cookie round-trip.
3174
+ */
3175
+ impersonateAuthUser(input: {
3176
+ userId: string;
3177
+ }): Promise<AuthImpersonation>;
3178
+ /** Revoke a single session by its id (force sign-out of one device). */
3179
+ revokeAuthSession(input: {
3180
+ sessionId: string;
3181
+ }): Promise<void>;
3182
+ /** Revoke every session for a user (force sign-out everywhere). */
3183
+ revokeAuthUserSessions(input: {
3184
+ userId: string;
3185
+ }): Promise<void>;
3186
+ /**
3187
+ * Report which auth dashboard surfaces are available — derived server-side
3188
+ * from the enabled better-auth plugins. The studio renders only the panels
3189
+ * whose capability is `true`.
3190
+ */
3191
+ getAuthCapabilities(): Promise<AuthCapabilities>;
3192
+ /** Update a user's fields (name/email/app-defined `additionalFields`). */
3193
+ updateAuthUser(input: {
3194
+ data: Record<string, unknown>;
3195
+ userId: string;
3196
+ }): Promise<AuthUser>;
3197
+ /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
3198
+ listAuthAccounts(input: {
3199
+ userId: string;
3200
+ }): Promise<Record<string, unknown>[]>;
3201
+ /** Unlink a linked account from a user. */
3202
+ unlinkAuthAccount(input: {
3203
+ accountId: string;
3204
+ userId: string;
3205
+ }): Promise<void>;
3206
+ /** List a user's registered passkeys (requires the passkey plugin). */
3207
+ listAuthPasskeys(input: {
3208
+ userId: string;
3209
+ }): Promise<Record<string, unknown>[]>;
3210
+ /** Delete a passkey by id (requires the passkey plugin). */
3211
+ deleteAuthPasskey(input: {
3212
+ passkeyId: string;
3213
+ }): Promise<void>;
3214
+ /** Disable two-factor auth for a user (requires the two-factor plugin). */
3215
+ disableAuthTwoFactor(input: {
3216
+ userId: string;
3217
+ }): Promise<void>;
3218
+ /** List organizations, paged (requires the organization plugin). */
3219
+ listAuthOrganizations(options?: {
3220
+ limit?: number;
3221
+ offset?: number;
3222
+ }): Promise<AuthPage<Record<string, unknown>>>;
3223
+ /** List the members of an organization (requires the organization plugin). */
3224
+ listAuthOrgMembers(input: {
3225
+ limit?: number;
3226
+ offset?: number;
3227
+ organizationId: string;
3228
+ }): Promise<AuthPage<Record<string, unknown>>>;
3229
+ /** List an organization's pending invitations (requires the organization plugin). */
3230
+ listAuthOrgInvitations(input: {
3231
+ limit?: number;
3232
+ offset?: number;
3233
+ organizationId: string;
3234
+ }): Promise<AuthPage<Record<string, unknown>>>;
3235
+ /**
3236
+ * List sign-up invitations, newest first (requires the `inviteOnly` plugin).
3237
+ * Unfiltered: a row is pending when `acceptedAt` is null and `expiresAt` is in
3238
+ * the future, and the caller labels it — filtering server-side after the page
3239
+ * would let page 1 come back empty while pending rows sat on page 2.
3240
+ */
3241
+ listAuthSignUpInvitations(options?: {
3242
+ limit?: number;
3243
+ offset?: number;
3244
+ }): Promise<AuthPage<Record<string, unknown>>>;
3245
+ /** Invite an address to sign up, or refresh an existing invitation for it. */
3246
+ createAuthSignUpInvitation(input: {
3247
+ email: string;
3248
+ expiresInSeconds?: number;
3249
+ invitedBy?: string;
3250
+ }): Promise<Record<string, unknown>>;
3251
+ /** Withdraw a sign-up invitation. Not retroactive — an account already created keeps existing. */
3252
+ revokeAuthSignUpInvitation(input: {
3253
+ email: string;
3254
+ }): Promise<void>;
3255
+ /** Remove a member from an organization. */
3256
+ removeAuthOrgMember(input: {
3257
+ memberId: string;
3258
+ }): Promise<void>;
3259
+ /** Cancel a pending organization invitation. */
3260
+ cancelAuthOrgInvitation(input: {
3261
+ invitationId: string;
3262
+ }): Promise<void>;
3263
+ /**
3264
+ * Report the deployment's auth configuration — enabled plugins, sign-in
3265
+ * methods, user-settable create-user fields, organization sub-features
3266
+ * (teams / roles), and session / rate-limit policy. Drives the config panel
3267
+ * and the dynamic create-user form. Never carries a secret.
3268
+ */
3269
+ getAuthConfig(): Promise<AuthConfigInfo>;
3270
+ /** Create an organization; optionally seed an `owner` member for `ownerId`. */
3271
+ createAuthOrganization(input: {
3272
+ logo?: string;
3273
+ metadata?: Record<string, unknown>;
3274
+ name: string;
3275
+ ownerId?: string;
3276
+ slug?: string;
3277
+ }): Promise<Record<string, unknown>>;
3278
+ /** Update an organization's name/slug/logo/metadata. */
3279
+ updateAuthOrganization(input: {
3280
+ logo?: string;
3281
+ metadata?: Record<string, unknown>;
3282
+ name?: string;
3283
+ organizationId: string;
3284
+ slug?: string;
3285
+ }): Promise<Record<string, unknown>>;
3286
+ /** Delete an organization and cascade its members, invitations, teams, and custom roles. */
3287
+ deleteAuthOrganization(input: {
3288
+ organizationId: string;
3289
+ }): Promise<void>;
3290
+ /** Directly add an existing user to an organization (no invitation/acceptance). */
3291
+ addAuthOrgMember(input: {
3292
+ organizationId: string;
3293
+ role?: string;
3294
+ userId: string;
3295
+ }): Promise<Record<string, unknown>>;
3296
+ /** Create a pending email invitation to an organization. */
3297
+ inviteAuthOrgMember(input: {
3298
+ email: string;
3299
+ inviterId?: string;
3300
+ organizationId: string;
3301
+ role?: string;
3302
+ }): Promise<Record<string, unknown>>;
3303
+ /** Change a member's role. */
3304
+ setAuthOrgMemberRole(input: {
3305
+ memberId: string;
3306
+ role: string | string[];
3307
+ }): Promise<Record<string, unknown>>;
3308
+ /** List an organization's teams (requires the organization plugin with teams enabled). */
3309
+ listAuthOrgTeams(input: {
3310
+ limit?: number;
3311
+ offset?: number;
3312
+ organizationId: string;
3313
+ }): Promise<AuthPage<Record<string, unknown>>>;
3314
+ /** Create a team under an organization. */
3315
+ createAuthOrgTeam(input: {
3316
+ name: string;
3317
+ organizationId: string;
3318
+ }): Promise<Record<string, unknown>>;
3319
+ /** Rename a team. */
3320
+ updateAuthOrgTeam(input: {
3321
+ name: string;
3322
+ teamId: string;
3323
+ }): Promise<Record<string, unknown>>;
3324
+ /** Delete a team and its memberships. */
3325
+ removeAuthOrgTeam(input: {
3326
+ teamId: string;
3327
+ }): Promise<void>;
3328
+ /** List a team's members. */
3329
+ listAuthOrgTeamMembers(input: {
3330
+ limit?: number;
3331
+ offset?: number;
3332
+ teamId: string;
3333
+ }): Promise<AuthPage<Record<string, unknown>>>;
3334
+ /** Add a user to a team. */
3335
+ addAuthOrgTeamMember(input: {
3336
+ teamId: string;
3337
+ userId: string;
3338
+ }): Promise<Record<string, unknown>>;
3339
+ /** Remove a member from a team. */
3340
+ removeAuthOrgTeamMember(input: {
3341
+ teamMemberId: string;
3342
+ }): Promise<void>;
3343
+ /** List an organization's custom roles (requires the organization plugin with dynamic access control). */
3344
+ listAuthOrgRoles(input: {
3345
+ limit?: number;
3346
+ offset?: number;
3347
+ organizationId: string;
3348
+ }): Promise<AuthPage<Record<string, unknown>>>;
3349
+ /** Create a custom org role with a permission grant (a `resource -> actions[]` map). */
3350
+ createAuthOrgRole(input: {
3351
+ organizationId: string;
3352
+ permission: Record<string, string[]>;
3353
+ role: string;
3354
+ }): Promise<Record<string, unknown>>;
3355
+ /** Replace a custom org role's permission grant. */
3356
+ updateAuthOrgRole(input: {
3357
+ permission: Record<string, string[]>;
3358
+ roleId: string;
3359
+ }): Promise<Record<string, unknown>>;
3360
+ /** Delete a custom org role. */
3361
+ deleteAuthOrgRole(input: {
3362
+ roleId: string;
3363
+ }): Promise<void>;
3364
+ /** List auth sessions, paged and optionally filtered to one user. */
3365
+ listAuthSessions(options?: {
3366
+ limit?: number;
3367
+ offset?: number;
3368
+ userId?: string;
3369
+ }): Promise<AuthPage<AuthSession>>;
3370
+ /**
3371
+ * Subscribe to a live query. The callback fires with the current value (from
3372
+ * the durable read cache, when one is hydrated) and again on every server
3373
+ * frame; the returned function unsubscribes.
3374
+ *
3375
+ * Subscriptions are deduped by `(functionPath, args, shardKey)` — a second
3376
+ * `subscribe` for the same triple joins the existing registration and shares
3377
+ * its value, cursor and optimistic layers.
3378
+ *
3379
+ * Available on a `crossTabSync` FOLLOWER tab, unlike the other socket-backed
3380
+ * surfaces: registering here is exactly what lets the cross-tab relay deliver
3381
+ * the leader's broadcasts (see the note in the body). The caveat is that the
3382
+ * channel only carries the LEADER's own subscriptions outward, so a follower
3383
+ * sees this query's frames only while the leader holds it too — see
3384
+ * {@link LunoraClientOptions.crossTabSync}.
3385
+ */
3386
+ subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
3387
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3388
+ onError?: SubscriptionErrorCallback;
3389
+ shardKey?: string;
3390
+ }): Unsubscribe;
3391
+ /**
3392
+ * Subscribe to a declarative **shape** — server-side partial replication
3393
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
3394
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
3395
+ * validated `args` (never a `where` the client could forge), the server seeds
3396
+ * the current membership as an insert-poke and streams live membership diffs.
3397
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
3398
+ *
3399
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
3400
+ * (name, args): the server resolves them under the socket's verified identity,
3401
+ * so every call gets its own id + view. The returned function unsubscribes.
3402
+ *
3403
+ * Not available on a `crossTabSync` FOLLOWER tab: shape pokes are not part of
3404
+ * the leader→follower broadcast set, so a follower's shape could never
3405
+ * resolve. The returned handle is inert there, and `options.onError` is
3406
+ * invoked with `NOT_IMPLEMENTED` — see
3407
+ * {@link LunoraClientOptions.crossTabSync}. Reporting rather than throwing is
3408
+ * deliberate: `@lunora/db`'s shape-backed `createCollection` calls this from
3409
+ * its sync path, where a throw takes the collection out entirely, while
3410
+ * `onError` is the seam it already routes to `markReady()`.
3411
+ */
3412
+ subscribeShape(shape: {
3413
+ args?: Record<string, unknown>;
3414
+ name: string;
3415
+ }, callback: ShapeCallback, options?: {
3416
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3417
+ onError?: SubscriptionErrorCallback;
3418
+ shardKey?: string;
3419
+ }): Unsubscribe;
3420
+ /**
3421
+ * Open a streaming query. The function reference must be a
3422
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
3423
+ * the type constraint catches accidental use of a query/mutation/action
3424
+ * reference at compile time. The returned iterable yields one element per
3425
+ * chunk frame the server pushes, terminating when the server sends
3426
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
3427
+ * rejection on the next `next()`.
3428
+ *
3429
+ * Streams ride the same WS as subscriptions and share the unsubscribe
3430
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id on
3431
+ * the socket the stream runs over. For an ephemeral stream the DO aborts the
3432
+ * in-flight iterator. For a `durable` stream, cancelling detaches this
3433
+ * consumer and the run keeps going: it finishes and stays readable for the
3434
+ * next attach. A cancel made while the socket is down is dropped rather
3435
+ * than queued, because the server already detached every consumer on that
3436
+ * socket when it closed.
3437
+ *
3438
+ * Stream-start frames buffered while the socket is (re)connecting are
3439
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
3440
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
3441
+ * reconnect can't OOM the page.
3442
+ */
3443
+ stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
3444
+ durable?: boolean;
3445
+ maxBuffer?: number;
3446
+ shardKey?: string;
3447
+ }): StreamIterable<ReturnOf<F>>;
3448
+ /**
3449
+ * Open a typed **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`).
3450
+ * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
3451
+ * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
3452
+ * and parses the Server-Sent Events framing the route pump writes (`data:`
3453
+ * chunks, a final `event: complete`, an `event: error` on throw).
3454
+ *
3455
+ * The reference comes from the generated `httpStreams.*` registry, so the
3456
+ * yielded chunk type is the route handler's yielded type. Cancelling the
3457
+ * returned iterable (or aborting `options.signal`) aborts the fetch, which
3458
+ * the server handler observes via its `signal`. The client's bearer token
3459
+ * (when set) rides as an `authorization` header.
3460
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
3461
+ */
3462
+ httpStream<Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: {
3463
+ headers?: Record<string, string>;
3464
+ maxBuffer?: number;
3465
+ signal?: AbortSignal;
3466
+ }): StreamIterable<HttpStreamChunkOf<Ref>>;
3467
+ close(): void;
3468
+ /** Guard shared by every public entry point: a closed client accepts no further calls. */
3469
+ private assertOpen;
3470
+ /**
3471
+ * `true` when this tab is a cross-tab FOLLOWER of a live leader — i.e. it
3472
+ * will not open a socket of its own and another tab is known to hold one.
3473
+ *
3474
+ * Deliberately NOT just `!isLeader()`. Every `crossTabSync` client is a
3475
+ * non-leader for the first `leaderTimeout` of its life, while its
3476
+ * claim-leadership probe is outstanding; a lone tab self-promotes at the end
3477
+ * of that window and `onBecomeLeader` opens the sockets and replays every
3478
+ * registered subscription. That window is a legitimate, self-healing defer,
3479
+ * not a failure. A KNOWN leader on another tab is the state that never heals.
3480
+ */
3481
+ private followsAnotherTab;
3482
+ /**
3483
+ * Reject a call that needs a socket this tab will never have.
3484
+ *
3485
+ * The cross-tab protocol is one-directional: a leader broadcasts
3486
+ * `subscription-data` / `-error` / `-settled` / `connection-status` to
3487
+ * followers, and a follower has no frame with which to tell the leader what
3488
+ * it needs (see `cross-tab.ts`'s `WsFollowerMessage`, which is exactly
3489
+ * heartbeat / claim-leadership / yield-leadership). `subscribeShape` /
3490
+ * `whisper*` / `setConnectionContext` / `acquireConnectionContext` — none of
3491
+ * which the leader broadcasts at all — therefore never worked on a follower
3492
+ * under any circumstances: each returned a handle that looked live, fired no
3493
+ * callback, raised no error, and reported `connectionStatus() ===
3494
+ * "connected"` (mirrored from the leader).
3495
+ *
3496
+ * `subscribe` is deliberately NOT in that set. A follower's `subscribe`
3497
+ * registers the key the leader's broadcast is matched against, so it is the
3498
+ * mechanism the relay is built on rather than a surface that silently fails.
3499
+ * A follower sees a query only while the leader holds the same
3500
+ * `(fn, args, shardKey)` — that is the documented shape of the option, not a
3501
+ * defect.
3502
+ *
3503
+ * `subscribeShape` and `stream()` reach the same outcome by a different
3504
+ * route: they fail the handle they return rather than throwing at the call,
3505
+ * because both are driven from a sync/render path where a throw destroys the
3506
+ * caller instead of degrading it. See
3507
+ * {@link LunoraClientOptions.crossTabSync} for what the option does and does
3508
+ * not cover.
3509
+ */
3510
+ private assertLeaderOwnedSurface;
3511
+ /**
3512
+ * Clear every timer a {@link ShardConnection} can have armed.
3513
+ *
3514
+ * One function because both teardown paths must clear all three and a fourth
3515
+ * timer would otherwise have to be remembered in two places — which is how a
3516
+ * leak gets added rather than written.
3517
+ */
3518
+ private clearConnectionTimers;
3519
+ /**
3520
+ * Whether anything still needs `key`'s socket: a live or shape
3521
+ * subscription, a stream, a whisper topic, a connection context (presence
3522
+ * rides its `connect` envelope), or a write queued for or flushing to it.
3523
+ */
3524
+ private shardInUse;
3525
+ /**
3526
+ * Close a non-default shard's socket once nothing uses it, after
3527
+ * {@link IDLE_SHARD_CLOSE_MS} so a quick leave-and-return reuses it. The
3528
+ * connection record is dropped; the shard is remembered in
3529
+ * {@link idleClosedShards}, so writes to it keep the gating a connected shard
3530
+ * gets — sent over HTTP, and queued if the network is down (a queued write
3531
+ * reopens the socket to flush). A later subscription reconnects it.
3532
+ * Every release path calls this; the timer re-checks, so a shard picked up
3533
+ * again in the meantime stays open.
3534
+ */
3535
+ private releaseIdleShard;
3536
+ /** Forget a finished or cancelled stream; it may have been what held its shard open. */
3537
+ private forgetStream;
3538
+ /**
3539
+ * Tear down one {@link ShardConnection}'s live state: clear its reconnect/
3540
+ * connect timers, stop its heartbeat, and close its socket (if any).
3541
+ * Shared by `close()` (terminal) and the cross-tab `onStopBeingLeader`
3542
+ * handler (demoted, but still alive) so a demoted leader can't leak a
3543
+ * pending `reconnectTimer` or an open socket's `heartbeatTimer` the way
3544
+ * an inline `conn.socket?.close()` — which skips both — used to.
3545
+ *
3546
+ * Settles this shard's in-flight streams first. The teardown clears
3547
+ * `conn.socket` BEFORE the real `close` event fires, so that event trips
3548
+ * `openManagedSocket`'s identity guard (`conn.socket !== socket`) and
3549
+ * returns — meaning `handleDisconnect`, the only other place that settles a
3550
+ * shard's streams, never runs for this connection again. `close()` already
3551
+ * failed and cleared `this.streams` before it gets here, so this is a no-op
3552
+ * on that path; the cross-tab demotion path is the one where a consumer's
3553
+ * `for await` used to block forever with no error and no completion.
3554
+ */
3555
+ private teardownConnection;
3556
+ /**
3557
+ * Build (but do not start) this client's `TabCoordinator`. Extracted out of
3558
+ * the constructor so `setAuthToken` can rebuild it on an identity change —
3559
+ * the default channel name embeds the identity fingerprint (see below), so
3560
+ * a new identity needs a new coordinator on a new channel. The callback
3561
+ * bodies are the drift-sensitive region (a hand-merged identity guard on
3562
+ * the shard message listener sits ahead of an extracted `lastFrameAt`
3563
+ * stamp elsewhere in this file) — moved verbatim, not reflowed.
3564
+ */
3565
+ private createTabCoordinator;
3566
+ /** The body of {@link batch}, optionally abortable (the polling fallback's timeout). */
3567
+ private sendBatch;
3568
+ /**
3569
+ * The body of {@link mutation}, also saying whether the write committed. `committed` is
3570
+ * `false` only when a durable outbox took the write, which resolves at once
3571
+ * with no server result.
3572
+ */
3573
+ private runMutation;
3574
+ /**
3575
+ * Unwind a direct write's optimistic layers after its RPC threw — or keep
3576
+ * them, when it threw only because a COMMITTED result did not decode: the
3577
+ * write happened, so its predicted value stays until the confirming frame
3578
+ * supersedes it.
3579
+ */
3580
+ private settleFailedDirectWrite;
3581
+ /**
3582
+ * Persist a mutation that can't go out on the wire right now (offline, or
3583
+ * mid-reconnect after a prior connect). The optimistic update has already
3584
+ * been applied by `mutation`; this only chooses the durable write path and
3585
+ * rolls the optimistic write back if persistence is rejected.
3586
+ *
3587
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
3588
+ * owns persistence + at-least-once replay, so we delegate and return
3589
+ * optimistically (confirmation rides the synced view). Otherwise the
3590
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
3591
+ */
3592
+ private enqueueOfflineMutation;
3593
+ /**
3594
+ * Is a write for this shard still sitting in the durable path, waiting to
3595
+ * replay? Drives the FIFO gate in {@link mutation}: a live write must never
3596
+ * overtake one that is queued (or held) ahead of it.
3597
+ *
3598
+ * Whichever durable path is wired answers: the built-in {@link OfflineQueue}
3599
+ * knows its entries' shard keys, while an {@link OutboxSink} reports only a
3600
+ * process-wide depth (the executor's pending count is not shard-scoped) —
3601
+ * over-inclusion there costs a write a trip through the outbox it could have
3602
+ * skipped, which is the same trip the writes ahead of it are taking anyway.
3603
+ * A sink that reports nothing keeps the previous behaviour.
3604
+ */
3605
+ private hasPendingWriteAhead;
3606
+ /**
3607
+ * Restore offline mutations persisted in a prior session and open a socket
3608
+ * for each shard they target so they flush once the WS reconnects. Failures
3609
+ * are swallowed — a broken durable store must not stop the client booting.
3610
+ */
3611
+ private hydratePersistedQueue;
3612
+ /**
3613
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
3614
+ * persisted queue is shared across a profile's tabs; without coordination
3615
+ * every tab would re-queue and replay the same writes (correct only because
3616
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
3617
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
3618
+ * closes another tab acquires the lock and takes over. Falls back to
3619
+ * unconditional hydration where Web Locks are unavailable (React Native, older
3620
+ * browsers, SSR) — single-context there, so no coordination is needed.
3621
+ */
3622
+ private hydrateAsOutboxLeader;
3623
+ /**
3624
+ * Load every cached query so a `subscribe()` for the key seeds its initial
3625
+ * value off disk.
3626
+ *
3627
+ * The load is asynchronous but every framework adapter subscribes
3628
+ * SYNCHRONOUSLY at mount, so the subscriptions that most want the cache
3629
+ * already exist by the time it lands. Those are seeded here and their entry
3630
+ * is dropped: an entry that stayed in {@link hydratedQueryCache} behind a
3631
+ * live subscription would be consumed by the NEXT subscribe of the same key
3632
+ * (a remount after navigating away) and replay the previous session's value
3633
+ * over whatever the socket had since delivered. A cache entry therefore
3634
+ * never outlives a live subscription for its key — it is either handed to
3635
+ * that subscription or discarded.
3636
+ *
3637
+ * Only keys with no live subscription are held for a later `subscribe()`;
3638
+ * the identity gate applies to both paths, so a signed-out cache never leaks
3639
+ * into a new session.
3640
+ */
3641
+ private hydrateQueryCache;
3642
+ /**
3643
+ * Hand a loaded read-cache entry to a subscription that was opened before
3644
+ * the load resolved — the same value, cursor and epoch {@link subscribe}
3645
+ * would have taken from {@link takeHydratedCache} had the load finished
3646
+ * first, so the cursor still rides the `subscribe` frame as `sinceSeq` (that
3647
+ * frame only goes out once the socket opens, well after this microtask).
3648
+ *
3649
+ * A no-op once the socket has delivered anything for this key: a live value
3650
+ * always beats the cache. Identity-gated exactly like `takeHydratedCache`.
3651
+ */
3652
+ private seedSubscriptionFromCache;
3653
+ /**
3654
+ * Move the durable read cache in or out of view as the CREDENTIAL changes —
3655
+ * which the identity fingerprint does not track: a sticky subject rides
3656
+ * across a token change (the account-switch shape), leaving the label
3657
+ * unmoved, so `setAuthToken`'s identity-change block never runs for it.
3658
+ * Revoke while that pairing is unchecked, and hand the values back once the
3659
+ * next session resolve confirms the credential really is that subject's.
3660
+ */
3661
+ private syncReadCacheToCredential;
3662
+ /**
3663
+ * A server frame owns this key now, so the read cache may neither take its
3664
+ * seeded value back ({@link revokeCacheSeededValues}) nor hold an entry for
3665
+ * a later `subscribe()` of the same key to replay a stale session over.
3666
+ */
3667
+ private dropCacheSeed;
3668
+ /**
3669
+ * Hand a cache-seeded entry back to {@link hydratedQueryCache} when its last
3670
+ * subscriber detaches, so the NEXT `subscribe()` of the same key can seed
3671
+ * from it again.
3672
+ *
3673
+ * Without this the hydrated cache was one-shot per key: {@link takeHydratedCache}
3674
+ * consumes the entry, the final unsubscribe drops the state that held its
3675
+ * value, and nothing re-seeds. Navigating away from a route and back while
3676
+ * offline therefore rendered `undefined` for the rest of the offline
3677
+ * session even though the durable store still held the rows. React hid it
3678
+ * behind TanStack's `gcTime`; every other adapter showed it immediately.
3679
+ *
3680
+ * Only a seed still listed in {@link cacheSeededQueries} moves — a server
3681
+ * frame calls {@link dropCacheSeed}, which clears both maps, so an entry
3682
+ * that is still here has not been superseded and is the freshest value this
3683
+ * client has for the key. That is the same map-to-map move
3684
+ * {@link revokeCacheSeededValues} makes, and it keeps the two maps disjoint:
3685
+ * an entry is either on display or waiting, never both.
3686
+ */
3687
+ private returnCacheSeed;
3688
+ /**
3689
+ * Take every value the durable read cache is currently displaying back off
3690
+ * screen, and return its entry to {@link hydratedQueryCache} so the identity
3691
+ * gate — not this call — decides whether it is ever shown again. A
3692
+ * same-credential refresh gets its offline-first value back the moment the
3693
+ * next session resolve re-confirms the subject; a genuine account switch
3694
+ * never does, and {@link clearQueryCacheForIdentityChange} wipes it.
3695
+ *
3696
+ * Only cache-seeded values: a server frame has been delivered under a socket
3697
+ * whose own identity is pinned and checked ({@link persistQueryValue}), and
3698
+ * dropping those would blank a live query on every token refresh.
3699
+ */
3700
+ private revokeCacheSeededValues;
3701
+ /**
3702
+ * Consume the hydrated read-cache entry for a key (if any), gated on
3703
+ * identity ({@link cachedQueryMatchesIdentity}). A mismatch yields
3704
+ * `undefined`, so a cache written under a different identity never leaks
3705
+ * into a new session.
3706
+ *
3707
+ * Only a MATCH is removed. The cache seeds a subscription's first value
3708
+ * once, so consuming a match is right — but destroying a mismatch is what
3709
+ * made a late-resolving identity unrecoverable: the subject typically lands
3710
+ * a `/get-session` after the first `subscribe()`, and by then the entry that
3711
+ * would have matched was gone. Left in place, {@link reseedFromHydratedCache}
3712
+ * can still hand it over when the identity settles.
3713
+ */
3714
+ private takeHydratedCache;
3715
+ /**
3716
+ * Hand every still-held read-cache entry to the subscription that is open on
3717
+ * its key, now that the identity has settled onto a resolved subject.
3718
+ *
3719
+ * `subscribe()` runs long before `/get-session` answers, so on a reload the
3720
+ * gate is asked its question with only a raw token in hand. When the token
3721
+ * itself matches, {@link cachedQueryMatchesIdentity} already says yes there
3722
+ * and then; when it has been refreshed since the value was cached, the only
3723
+ * honest answer at that moment is "unknown" — and this is where it becomes
3724
+ * knowable. {@link seedSubscriptionFromCache} is a no-op for any subscription
3725
+ * the socket has already fed, so a live value always wins.
3726
+ */
3727
+ private reseedFromHydratedCache;
3728
+ /**
3729
+ * Queue a coalesced read-cache write for a subscription's current value.
3730
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
3731
+ * once. No-op when the read cache is disabled or the value is undefined
3732
+ * (nothing to render offline).
3733
+ */
3734
+ private persistQueryValue;
3735
+ /** Drain {@link pendingCacheWrites} to the durable store. */
3736
+ private flushQueryCacheWrites;
3737
+ /** Derive the aggregate status from the per-shard socket states. */
3738
+ private computeStatus;
3739
+ /**
3740
+ * The CDC cursor this client's view of `shardKey` is at — the highest
3741
+ * `serverCursor` any live subscription on that shard has advanced to.
3742
+ *
3743
+ * This is the baseline a `.dropStalePatches()` table judges a write against,
3744
+ * and the "highest" is what makes it sound: a cursor the client has reached on
3745
+ * ANY subscription means the shard's changelog up to that point has been
3746
+ * delivered here, so anything later is by definition something this client had
3747
+ * not seen when it composed the write.
3748
+ *
3749
+ * `undefined` when no subscription on the shard carries a cursor yet — a
3750
+ * client that has only ever issued one-shot RPCs, or a server with CDC off.
3751
+ * That is reported honestly rather than defaulted to `0`: a `0` baseline would
3752
+ * claim the client had seen NOTHING, which makes every field look changed and
3753
+ * would have the shard discard every patch it sends.
3754
+ */
3755
+ private baselineCursorFor;
3756
+ /**
3757
+ * One polling-fallback pass for a shard: re-run every live query bound to it
3758
+ * over the batch-RPC endpoint and feed each result into the same frame-apply
3759
+ * path a server `data` frame takes.
3760
+ *
3761
+ * Reusing {@link LunoraClient.batch} and {@link LunoraClient.handleDataMessage}
3762
+ * rather than forking either is the whole point. The apply path is where
3763
+ * optimistic layers rebase, the durable read cache is seeded, and subscriber
3764
+ * callbacks fan out; a second implementation of that would drift, and it would
3765
+ * drift into exactly the bugs the live path has already had fixed.
3766
+ *
3767
+ * The result is re-encoded on the way in because `batch` hands back a decoded
3768
+ * value while the frame path expects the wire form. `encodeWire` is identity
3769
+ * for JSON-safe data and lossless for the rest (that is the codec's contract),
3770
+ * so the round trip costs an allocation and changes nothing.
3771
+ *
3772
+ * **No cursor rides this path.** A poll is a full snapshot, so the frames it
3773
+ * synthesizes carry no `cursor`/`epoch` and cannot advance a subscription's
3774
+ * resume watermark — which is correct: the watermark describes what the CDC
3775
+ * log has delivered, and this delivered none of it. When the socket comes
3776
+ * back, the resubscribe resumes from the last cursor the SOCKET saw, and the
3777
+ * server re-snapshots whatever it needs to.
3778
+ *
3779
+ * A slot that failed is fanned to the subscription's error callbacks rather
3780
+ * than being swallowed: the whole point of the fallback is that the app keeps
3781
+ * working, and a query that is now failing (a permission change, a bad arg)
3782
+ * has to be visible.
3783
+ *
3784
+ * Resolves `false` when the request never reached the origin (`fetch` itself
3785
+ * rejected), which is how the fallback tells a device with no network from a
3786
+ * network that only refuses the upgrade. Any answer, an error envelope
3787
+ * included, resolves `true`.
3788
+ *
3789
+ * Optimistic layers need the same care without a cursor. The snapshot is taken
3790
+ * after the request is sent, so every write whose RPC had resolved before that
3791
+ * moment is already in it. Those layers are dropped against the acknowledgement
3792
+ * mark sampled before the send. A write acknowledged after the send may be
3793
+ * missing from the snapshot, so its layer stays.
3794
+ */
3795
+ private pollSubscriptions;
3796
+ /**
3797
+ * Whether a request reaches the origin at all: an empty batch, whose answer
3798
+ * (even a refusal) is the proof. `false` only when `fetch` itself rejects.
3799
+ */
3800
+ private probeOrigin;
3801
+ /** Recompute the aggregate status and notify listeners if it changed. */
3802
+ private emitConnectionStatus;
3803
+ /**
3804
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
3805
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
3806
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
3807
+ * is unreachable — present only to satisfy the optional queue-id type.
3808
+ */
3809
+ private emitItemSettled;
3810
+ /**
3811
+ * Apply an optimistic update to the subscription that matches the mutation's
3812
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
3813
+ * invoke if the mutation later fails.
3814
+ *
3815
+ * The registry is already indexed by exactly this triple via
3816
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
3817
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
3818
+ *
3819
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
3820
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
3821
+ * a shardKey correctly matches a subscription registered without one regardless
3822
+ * of whether the caller passed `undefined` or omitted the field.
3823
+ */
3824
+ private applyOptimisticUpdates;
3825
+ /**
3826
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
3827
+ * to the live subscription registry. Each `setQuery` registers a constant
3828
+ * optimistic LAYER on its target subscription (via the same engine the
3829
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
3830
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
3831
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
3832
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
3833
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
3834
+ * mutation or leave a partial patch live.
3835
+ */
3836
+ private applyOptimisticUpdate;
3837
+ private getConnection;
3838
+ /**
3839
+ * Send an unsubscribe frame (tagged with its wire type) on the shard's
3840
+ * socket, or queue it for the next reconnect when the send can't go out.
3841
+ */
3842
+ private sendOrQueueUnsubscribe;
3843
+ /**
3844
+ * The `(wsState, hasSocket, wasEverConnected, polling)` state `mutation()`'s
3845
+ * offline-queue gate reads. On the leader/single-tab path this is exactly
3846
+ * the real `ShardConnection`'s state (byte-identical to the pre-cross-tab
3847
+ * behavior). A follower has no `ShardConnection` of its own (see
3848
+ * `ensureSocket`), so it derives the same triple from the mirrored
3849
+ * `leaderStatus`/`leaderWasEverConnected` instead: `"connected"` maps to
3850
+ * `"open"` (queue-eligible once `wasEverConnected`), `"connecting"` stays
3851
+ * `"connecting"` (the mid-reconnect queue branch), anything else is
3852
+ * `"idle"`. `hasSocket` is always `false` for a follower — it never has
3853
+ * one.
3854
+ *
3855
+ * `polling` is `true` while the HTTP polling fallback is reaching the origin
3856
+ * (the leader's mirrored `"polling"` on a follower). Writes then go straight
3857
+ * over HTTP, as they do while connected, instead of queueing for a socket
3858
+ * that may never open.
3859
+ *
3860
+ * `idleClosed` is `true` for a shard whose socket this client closed because
3861
+ * nothing used it (see {@link releaseIdleShard}). It was connected, so it
3862
+ * stays queue-eligible (`wasEverConnected`), but its socket is not "down":
3863
+ * a write is tried over HTTP first, as it went while the socket was open,
3864
+ * and queued only if the network turns out to be unreachable.
3865
+ */
3866
+ private connectionGateState;
3867
+ private getOrCreateConnection;
3868
+ private wsUrlFor;
3869
+ /**
3870
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
3871
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
3872
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
3873
+ * rides both the direct send and any offline-queue replay of the same write,
3874
+ * so a mutation the server already committed returns its cached result
3875
+ * instead of running twice.
3876
+ */
3877
+ private rpcRequestHeaders;
3878
+ private rpc;
3879
+ /**
3880
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
3881
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
3882
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
3883
+ * mirroring {@link rpc} so callers see the same failure shape.
3884
+ */
3885
+ private adminFetch;
3886
+ /**
3887
+ * Resolve the effective connection context for a shard: the most-recently
3888
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
3889
+ * back to the imperative {@link setConnectionContext} override, then the
3890
+ * client-wide default. Returns `undefined` when none apply.
3891
+ */
3892
+ private effectiveConnectionContext;
3893
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
3894
+ private refreshConnectionContext;
3895
+ /**
3896
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
3897
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
3898
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
3899
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
3900
+ * hooks are registered, and answers with the socket's `identity` frame
3901
+ * (see `handleIdentityFrame`).
3902
+ *
3903
+ * The shard's registered context (or the client-wide default) rides along
3904
+ * when one is set — the DO records it on the attachment for replay to
3905
+ * `onDisconnect`. A socket with no registered context still announces itself;
3906
+ * the envelope simply omits `context`, which is optional on the wire.
3907
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
3908
+ * to the lifecycle dispatch.
3909
+ */
3910
+ private sendConnectEnvelope;
3911
+ /**
3912
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
3913
+ * socket. Each frame carries the shape's last applied checkpoint, so the
3914
+ * server resumes from it — or re-seeds when the cursor fell below CDC
3915
+ * retention or the epoch forked.
3916
+ */
3917
+ private resendShapeSubscriptions;
3918
+ private ensureSocket;
3919
+ /**
3920
+ * Resolve the {@link WsTokenProvider} and open the shard socket with the
3921
+ * minted token. The connection is already in the `connecting` state, so the
3922
+ * async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
3923
+ * competing connect that landed first all abandon this attempt. A provider
3924
+ * failure fails the attempt through {@link handleDisconnect}, which arms the
3925
+ * normal reconnect backoff — a broken mint endpoint degrades to retries, not
3926
+ * a silent tokenless socket the admin gate would reject.
3927
+ */
3928
+ private openSocketWithProvidedToken;
3929
+ /**
3930
+ * Construct one WebSocket connection attempt and wire the shared
3931
+ * lifecycle guarantees around it — the fail-fast connect-timeout, the
3932
+ * identity guard that stops a superseded attempt's late `open`/`message`/
3933
+ * `close`/`error` from touching a connection a newer attempt already
3934
+ * owns, and (once open) the keepalive heartbeat with its half-open
3935
+ * watchdog (plan 217). One call opens ONE attempt; the caller owns
3936
+ * reconnect scheduling from `onClose` — mirrors the shard's existing
3937
+ * `ensureSocket` / `handleDisconnect` split, now shared with
3938
+ * `subscribeScheduledJobs` so it stops re-living the bug that split
3939
+ * already fixed once (CLIENT-05).
3940
+ *
3941
+ * The identity guard is `conn.socket !== socket`, re-checked before every
3942
+ * action below. `conn.socket` is reassigned to a new attempt's socket
3943
+ * synchronously — right here, before `open` ever fires — so an older
3944
+ * attempt's guard trips the instant it's superseded, even if its
3945
+ * underlying socket only fires its real `close`/`error` much later. This
3946
+ * ordering is load-bearing: preserve it exactly.
3947
+ */
3948
+ private openManagedSocket;
3949
+ /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
3950
+ private openSocket;
3951
+ /**
3952
+ * Tear down a stream the consumer cancelled, telling the server when its
3953
+ * socket is up.
3954
+ */
3955
+ private cancelStream;
3956
+ private handleDisconnect;
3957
+ /**
3958
+ * Begin the keepalive heartbeat on an open connection attempt — the only
3959
+ * caller is {@link openManagedSocket}'s own `open` handler, so both the
3960
+ * shard socket and `subscribeScheduledJobs` share this one implementation
3961
+ * instead of each hand-rolling their own (plan 217, generalized).
3962
+ *
3963
+ * Each tick first checks the half-open watchdog (see
3964
+ * {@link ManagedSocketState.lastFrameAt}): if no frame at all has arrived
3965
+ * within `heartbeatIntervalMs * 2.5`, the far end has gone quiet without
3966
+ * the socket ever firing `close` — force it closed and report it through
3967
+ * `onWatchdogTrip` (the caller's `onClose`) so the normal reconnect/backoff
3968
+ * takes over instead of every live query on it silently staling forever.
3969
+ * Otherwise it sends a {@link WS_KEEPALIVE_PING} text frame the server
3970
+ * answers from its hibernation auto-response without waking the DO. A
3971
+ * no-op when the heartbeat is disabled (an interval of zero or less);
3972
+ * idempotent — any existing timer is cleared first so a reconnect can't
3973
+ * leak intervals.
3974
+ */
3975
+ private startHeartbeat;
3976
+ /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
3977
+ private stopHeartbeat;
3978
+ /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
3979
+ private markShardPendingAck;
3980
+ /**
3981
+ * Re-send `state`'s `subscribe` frame, but only once fewer than
3982
+ * {@link RESUBSCRIBE_CONCURRENCY} frames on this shard are still awaiting a
3983
+ * reply. Used by every path that resends MANY subscriptions at once — the
3984
+ * socket-open resubscribe and the cross-tab leader handover, which replays
3985
+ * every tab's subscriptions combined. A first subscribe (one frame, caller
3986
+ * paced) still goes straight out through {@link sendSubscribeIfOpen}.
3987
+ */
3988
+ private queueResubscribe;
3989
+ /**
3990
+ * Send queued `subscribe` frames until the in-flight window is full.
3991
+ *
3992
+ * Cannot wedge: a queued subscription whose frame does not actually go out
3993
+ * (socket closed, already acked, unsubscribed while queued) takes no slot,
3994
+ * every sent frame is released by the first server frame carrying its id
3995
+ * (see {@link handleServerMessage}) or by its own watchdog, and a disconnect
3996
+ * drops the queue wholesale — the next `open` re-queues every subscription
3997
+ * on the shard, because `markShardPendingAck` un-acked them all.
3998
+ */
3999
+ private drainResubscribeQueue;
4000
+ /** Free the in-flight slot `id` holds on `conn` (if any) and let the next queued subscribe go out. */
4001
+ private releaseResubscribeSlot;
4002
+ /**
4003
+ * Abandon this connection's paced resubscribe: clear every watchdog and
4004
+ * forget both the in-flight and the waiting entries. Called wherever the
4005
+ * socket they were sent on goes away — the server drops that socket's
4006
+ * subscriptions anyway, and the next `open` re-queues all of them.
4007
+ */
4008
+ private clearResubscribeQueue;
4009
+ /** Send `state`'s `subscribe` frame when the shard's socket can carry it; `true` when a frame actually went out. */
4010
+ private sendSubscribeIfOpen;
4011
+ private sendShapeSubscribeIfOpen;
4012
+ private handleServerMessage;
4013
+ private handleErrorMessage;
4014
+ /** Buffer key for an in-flight poke: `pokeId` is only unique per shard socket, so it is scoped by connection. */
4015
+ private pokeBufferKey;
4016
+ private handlePokeStart;
4017
+ private handlePokePart;
4018
+ private handlePokeEnd;
4019
+ /**
4020
+ * Commit one shape's slice of a poke, or refuse it and re-seed.
4021
+ *
4022
+ * Split out of {@link handlePokeEnd} because every decision here is PER SHAPE
4023
+ * — the reset flag, the base checkpoint, the watermark — while the poke
4024
+ * envelope around it is not.
4025
+ */
4026
+ private applyPokePart;
4027
+ /**
4028
+ * Force the server to re-send a full snapshot for `state`, leaving the
4029
+ * currently displayed value alone until it lands. Used when a delta frame
4030
+ * cannot be applied: dropping the resume cursor is what makes the resubscribe
4031
+ * a snapshot rather than a `resume`, and un-acking is what lets
4032
+ * `sendSubscribeIfOpen` put the frame on the wire at all. Mirrors the shape
4033
+ * path's re-seed on a diverged base.
4034
+ */
4035
+ private resnapshotSubscription;
4036
+ /** Materialize a shape's keyed view to an array and invoke its callbacks. */
4037
+ private emitShapeRows;
4038
+ /**
4039
+ * Apply one `data` frame. `snapshotMark` is set only for a frame synthesized
4040
+ * by a poll, which carries no cursor: see {@link pollSubscriptions}.
4041
+ */
4042
+ private handleDataMessage;
4043
+ /**
4044
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
4045
+ * subscription reads changed since our `sinceSeq`, so the cached value is
4046
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
4047
+ * the cursor (re-persisting so the next reconnect resumes from the newer
4048
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
4049
+ * already replayed the cached value to every consumer synchronously.
4050
+ */
4051
+ private handleResumeMessage;
4052
+ /**
4053
+ * Handle a `settled` frame: a write touched one of this subscription's read
4054
+ * tables but produced a byte-identical result, so the server suppressed the
4055
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
4056
+ * advance the resume position and re-persist — but we ALSO surface the echoed
4057
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
4058
+ * collection drops the optimistic overlay for the confirmed write (otherwise
4059
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
4060
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
4061
+ * `onCheckpoint` unset and this is a near no-op.
4062
+ */
4063
+ private handleSettledMessage;
4064
+ /**
4065
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
4066
+ * the cached position, advance the resume watermark and re-persist. Shared by
4067
+ * the `resume` and `settled` frame handlers — both acknowledge "nothing the
4068
+ * client must re-render changed, but the resume position may have moved".
4069
+ */
4070
+ private ackAndAdvanceCursor;
4071
+ /**
4072
+ * Resolve the value to publish for a `data`/`delta` frame.
4073
+ *
4074
+ * A `data` frame is an authoritative snapshot (the server re-execution path)
4075
+ * and always replaces the cached value wholesale. A `delta` frame carrying a
4076
+ * structured `MutationDelta` (the `broadcastDelta` row-change path) is
4077
+ * merged incrementally into the cached list — preserving order, no dup/loss —
4078
+ * so each subscription (including every paginated page) updates by delta
4079
+ * rather than a full re-send. We fall back to full replacement when the
4080
+ * delta isn't a recognisable row change, when there's no cached value yet,
4081
+ * or when it can't be applied cleanly against the current cached shape.
4082
+ */
4083
+ private resolveDataPayload;
4084
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
4085
+ private dispatchWhisper;
4086
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
4087
+ private notifyTokenExpired;
4088
+ /**
4089
+ * CLIENT-04: `type: "complete"` today is sent ONLY by `@lunora/do`'s
4090
+ * `handleStream` (see `shard-do.ts`), gated to the `stream` envelope type
4091
+ * and minting only `stream_*` ids — the `subscribe` path never sends it, so
4092
+ * a live SUBSCRIPTION provably never receives `complete` from the current
4093
+ * server. But `ServerCompleteMessage` is a generic `id`-keyed frame and
4094
+ * `ShardDO` is user-subclassable, so this stays defensive rather than
4095
+ * assuming a `sub_*` id can never reach here: unlike the historical
4096
+ * `subscriptions.remove(state)`, which dropped the state out of
4097
+ * `subscriptions.all()` — the set the reconnect resubscribe loop walks
4098
+ * (`ensureSocket`'s `open` handler) — and so froze the query forever across
4099
+ * every future reconnect, this fans a cancellation error to any listener
4100
+ * and marks the registration un-acked instead. Non-destructive: the state
4101
+ * stays in the registry, so the very next reconnect resubscribes it. The
4102
+ * two id-spaces don't overlap (`sub_*` vs `stream_*`), so the stream and
4103
+ * subscription lookups below are mutually exclusive.
4104
+ */
4105
+ private handleCompleteMessage;
4106
+ private unpersist;
4107
+ /**
4108
+ * Stable, non-reversible fingerprint of the current auth identity used to
4109
+ * stamp queued offline writes.
4110
+ *
4111
+ * `null` never matches a bearer-token fingerprint — but it is only an
4112
+ * IDENTITY of its own once this client knows no subject is coming. An app
4113
+ * with no auth at all, and a client the server has answered "no session"
4114
+ * to, both hold a `null` nobody else shares. A client mid-`/get-session`
4115
+ * holds a `null` that may be one round trip from `subj:<id>`, which is
4116
+ * every cookie app's page load: ask {@link identityUnresolved} before
4117
+ * treating it as an identity, or `null === null` matches two different
4118
+ * people. The raw token is never stored;
4119
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
4120
+ * without keeping the credential around in the queue map.
4121
+ */
4122
+ private identityFingerprint;
4123
+ /**
4124
+ * Stable token-hash fingerprint of a bearer token (the `<len>:<fnv>:<djb2>`
4125
+ * format a token-stamped queued write carries). Extracted so the replay gate
4126
+ * can recompute the hash of the current credential and recognise a write
4127
+ * stamped under it — even after the fingerprint was relabelled to a subject.
4128
+ *
4129
+ * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
4130
+ * two distinct equal-length tokens are astronomically unlikely to share a
4131
+ * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
4132
+ * pair — enough that, on a shared device, user B could hydrate A's cached
4133
+ * reads. Different algorithms (not the same FNV with a different seed, which
4134
+ * would be affine-related) keep the two passes genuinely independent.
4135
+ * Still synchronous (no crypto) and stable across surrogate pairs.
4136
+ */
4137
+ private hashToken;
4138
+ /**
4139
+ * The `credential` field a read-cache write carries: the token hash of the
4140
+ * bearer currently held, or nothing at all when signed out (there is no
4141
+ * credential to match against, and the `null` identity already covers it).
4142
+ */
4143
+ private credentialStamp;
4144
+ /**
4145
+ * Whether a read-cache entry belongs to the identity in effect right now —
4146
+ * the ONE gate the hydrated peek, the subscribe-time take and the late seed
4147
+ * all share.
4148
+ *
4149
+ * Three ways to be the same identity, because the label and the credential
4150
+ * resolve at different times:
4151
+ *
4152
+ * 1. The fingerprints are equal — the plain case.
4153
+ * 2. The entry is stamped under a token hash and the live identity has since
4154
+ * been relabelled to the subject that credential resolved to
4155
+ * ({@link isSameCredentialUnderTokenHash}).
4156
+ * 3. The entry is stamped under a subject and THIS session has only the raw
4157
+ * token so far, but it is byte-for-byte the credential the entry was written
4158
+ * under. This is the direction the strict comparison missed entirely, and it
4159
+ * is the normal shape of every reload: every adapter calls
4160
+ * `setAuthToken(token)` from storage and only learns the subject a
4161
+ * `/get-session` round trip later — which offline never completes at all.
4162
+ * Without it the durable read cache never seeded for a bearer-token app.
4163
+ *
4164
+ * All three want a credential this client actually HOLDS, which is why a
4165
+ * **cookie session seeds nothing on an offline cold start** — a documented
4166
+ * limitation, not a gap. The cookie is `HttpOnly`: the client can neither
4167
+ * read it nor prove it still has it, and offline the `/get-session` that
4168
+ * would resolve the subject never answers, so such entries (stamped
4169
+ * `subj:<id>`, no credential) have nothing to match. Seeding them on the
4170
+ * remembered subject LABEL would hand the rows to whoever opens the browser
4171
+ * profile with nothing evidencing they are that subject, and revoking on a
4172
+ * later mismatch does not repair it: that check can only run once
4173
+ * connectivity returns, which is exactly the state where the offline seed
4174
+ * was not needed. Offline-first reads require a bearer token.
4175
+ *
4176
+ * Case 1 is suspended while the subject awaits re-confirmation
4177
+ * ({@link subjectAwaitingReconfirm}): the fingerprint then labels a
4178
+ * credential nothing has checked it against, which is precisely the
4179
+ * account-switch shape — `setAuthToken(otherAccountsToken)` with no subject,
4180
+ * what every adapter does on a reload, still reading `subj:<previous user>`.
4181
+ * Matching on that label alone hands the new account the previous account's
4182
+ * cached rows. Cases 2 and 3 both PROVE the credential, so the reload this
4183
+ * gate exists for still seeds.
4184
+ */
4185
+ private cachedQueryMatchesIdentity;
4186
+ /**
4187
+ * True when `stamped` is a token-hash of the SAME credential still held now,
4188
+ * even though the live identity has since been relabelled to a subject. Covers
4189
+ * `setAuthToken(token, userId)` where the subject resolved a tick after the
4190
+ * token was set: a write persisted (or requeued) under the token hash must
4191
+ * still replay — the credential never changed, only its label — instead of
4192
+ * being dropped as an identity mismatch. This is the durable counterpart to
4193
+ * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
4194
+ * (consumed on the first flush) and never touches `item.identity` or the
4195
+ * persisted record, so a reload or a transient-failure requeue would otherwise
4196
+ * fall back to the stale token-hash and wrongly reject the same user's write.
4197
+ */
4198
+ private isSameCredentialUnderTokenHash;
4199
+ /**
4200
+ * Release one {@link sessionProbesInFlight} hold and re-flush the writes
4201
+ * that hold alone was holding.
4202
+ *
4203
+ * A resolve that names a user re-flushes through {@link setAuthToken} (the
4204
+ * identity changed). One that does not — signed out, or unreachable —
4205
+ * changes no identity and so fires no listener, and a write held only
4206
+ * because {@link identityUnresolved} said so would sit queued until the
4207
+ * next reconnect. Same connected-only gate as `setAuthToken`'s, so this
4208
+ * stays a re-flush of a live connection rather than a reason to replay an
4209
+ * offline queue.
4210
+ *
4211
+ * Only for a `null` fingerprint, which is the ONLY hold this probe owns:
4212
+ * {@link replayIdentityVerdict}'s unresolved-identity hold tests
4213
+ * `current === null`, while its other hold — a sticky subject awaiting
4214
+ * re-confirmation — requires an established subject and so a
4215
+ * `subj:<id>` fingerprint. That one is already on the `noteHeldRetryDelay`
4216
+ * backoff and must stay there.
4217
+ *
4218
+ * Re-flushing it from here instead was an unbounded loop, not a slow
4219
+ * backoff: `drainOfflineQueue` answers a subject-awaiting hold by probing
4220
+ * `getCurrentUser()` itself, whose release re-flushed, which drained, which
4221
+ * probed again — hundreds of round trips without a millisecond passing,
4222
+ * until the heap gave out. Narrowing to the `null` fingerprint makes the
4223
+ * cycle unreachable rather than merely rare: the branch that starts a probe
4224
+ * cannot be entered by a flush this guard lets through.
4225
+ */
4226
+ private releaseSessionProbe;
4227
+ /**
4228
+ * Whether this client's `null` identity fingerprint is still provisional —
4229
+ * a {@link getCurrentUser} resolve is in flight and may be about to name a
4230
+ * subject. The one question every identity gate asks before it is willing
4231
+ * to treat `null` as an identity rather than as an absence of one.
4232
+ */
4233
+ private identityUnresolved;
4234
+ /**
4235
+ * Key the offline-queue identity on the resolved user id rather than the
4236
+ * token bytes, so the NEXT token refresh keeps the same identity.
4237
+ *
4238
+ * Under a bearer token only a resolved user labels anything. A 401 or an
4239
+ * empty session resolves `null` for reasons that say nothing about who holds
4240
+ * the token, so the established label is left alone rather than cleared
4241
+ * (which would look like an identity change and drop the queue). A token
4242
+ * that rotated mid-flight belongs to a session this answer predates and is
4243
+ * ignored for the same reason.
4244
+ *
4245
+ * Under a cookie session (no token) the answer is the identity, `null`
4246
+ * included: nothing on the client changes when the user signs out, so "the
4247
+ * server found no session" is the only sign-out this client will ever see.
4248
+ * See {@link adoptCookieSubject}.
4249
+ *
4250
+ * A superseded probe is ignored too, and the token check cannot see it: on a
4251
+ * cookie app both `requestToken`s are `null`, so a slow answer from an OLDER
4252
+ * probe passed that check and overwrote the subject a newer one had already
4253
+ * established. `requestGeneration` is the question's id — it must still be
4254
+ * the current one at the moment of the write.
4255
+ */
4256
+ private adoptResolvedSubject;
4257
+ /**
4258
+ * Adopt the user a cookie session resolved to — `null` for nobody — as this
4259
+ * client's identity, from either source the server answers through: a
4260
+ * `/get-session` probe, or a socket's `identity` frame.
4261
+ *
4262
+ * Three states, told apart by `authSubject`: `undefined` is not known yet
4263
+ * (every page load until the first answer), `null` is known to be nobody,
4264
+ * and a string is that user. {@link setAuthToken} retires the previous
4265
+ * session on every change between two KNOWN states — `A → nobody`,
4266
+ * `nobody → B`, `A → B` — and on none out of `undefined`, so the first
4267
+ * answer after a page load never evicts what the page is already showing
4268
+ * for the session it was loaded under.
4269
+ *
4270
+ * `question` orders the answers: one older than the answer in force
4271
+ * describes an older cookie and is dropped. Returns whether it was adopted.
4272
+ */
4273
+ private adoptCookieSubject;
4274
+ /**
4275
+ * A cookie socket's `identity` frame: the user the shard authenticated this
4276
+ * socket as, sent in reply to every `connect`.
4277
+ *
4278
+ * Adopted like a probe's answer when it is the newest one
4279
+ * ({@link adoptCookieSubject}). An OLDER one that disagrees with the
4280
+ * identity in force means this socket was upgraded on a cookie that has
4281
+ * since changed hands, and is still delivering that user's rows: the
4282
+ * session it belongs to is retired, which replaces the socket.
4283
+ *
4284
+ * Ignored for a socket that authenticated with a token rather than the
4285
+ * cookie (see `ShardConnection.identityQuestion`) — its answer is about that
4286
+ * token, not about the cookie session this client's identity tracks.
4287
+ */
4288
+ private handleIdentityFrame;
4289
+ /**
4290
+ * The subject half of {@link setAuthToken}.
4291
+ *
4292
+ * Sticky: only an explicit value (incl. `null` = signed out) changes the
4293
+ * subject; omitting it keeps the established one. Two exceptions, both about
4294
+ * a subject that must not outlive the credential it described:
4295
+ *
4296
+ * - Clearing the token clears a user subject — see `setAuthToken`'s
4297
+ * docblock. A `null` one stays: a cookie session known to be nobody's is
4298
+ * still nobody's.
4299
+ * - A token arriving on a session known to be nobody's drops the `null`,
4300
+ * so the identity falls back to the token itself rather than staying
4301
+ * "nobody" while a credential is held.
4302
+ */
4303
+ private applySubject;
4304
+ /**
4305
+ * A cookie session the server has answered "nobody" for — see
4306
+ * {@link adoptCookieSubject}. Distinct from a subject not known YET
4307
+ * (`undefined`).
4308
+ */
4309
+ private isKnownNobody;
4310
+ /**
4311
+ * True while an established subject labels a credential it was never checked
4312
+ * against — see the `subjectToken` field. Every replay verdict is
4313
+ * `"unknown"` (hold) until the next session resolve re-asserts the subject.
4314
+ */
4315
+ private subjectAwaitingReconfirm;
4316
+ /**
4317
+ * The identity a queued write is stamped with. The live `queuedIdentities`
4318
+ * map is the source of truth for this session; a hydrated write whose id
4319
+ * isn't in it falls back to the stamp persisted with the record. `Map.get`
4320
+ * returns `undefined` for unstamped/hydrated ids and `item.identity` is
4321
+ * `undefined` for legacy records (persisted before stamps were durable),
4322
+ * while a persisted `null` (queued while signed out) is a real value that
4323
+ * must not collapse into `undefined` — hence `=== undefined`, not `??`.
4324
+ */
4325
+ private stampOf;
4326
+ /**
4327
+ * Warn when a token refused for a queued write is replaced with no subject
4328
+ * keyed: the likely refresh reads as a user switch, so the writes it was
4329
+ * meant to rescue were just rejected `OFFLINE_IDENTITY_CHANGED`. Dropping is
4330
+ * the safe default — a refresh and an account switch look the same without
4331
+ * a subject — so this only says how to keep them.
4332
+ */
4333
+ private warnRefreshWithoutSubject;
4334
+ /**
4335
+ * Reject the in-memory offline writes that can no longer replay under the
4336
+ * identity now signed in, dropping their durable records so a later
4337
+ * `hydrate` can't resurrect another user's writes.
4338
+ *
4339
+ * Per item, not wholesale: this runs on a plain sign-in too (`null` → a
4340
+ * signed-in identity is a credential change like any other), where the
4341
+ * queue is the *signing-in user's own* restored writes. Every stamp goes
4342
+ * through {@link replayIdentityVerdict}, the one comparison, and only
4343
+ * `"mismatch"` is terminal — `"match"` and `"unknown"` stay queued.
4344
+ *
4345
+ * The durable read cache is cleared only when there WAS a previous identity
4346
+ * to protect. Wiping it on a sign-in from signed-out would destroy the
4347
+ * offline-first cache on every cold boot, and buys nothing: cache entries
4348
+ * are identity-stamped and gated at every read.
4349
+ */
4350
+ private rejectQueuedForIdentityChange;
4351
+ /**
4352
+ * Move the identity stamp of every open shard socket from `from` to `to` —
4353
+ * the sibling of {@link restampQueuedIdentity} for the read cache. A socket
4354
+ * pins the identity it was upgraded under (see `ShardConnection.identity`)
4355
+ * and {@link persistQueryValue} stamps cached reads with it, deliberately,
4356
+ * so a still-open previous-user socket can't file frames under the new
4357
+ * user's stamp. A same-credential relabel is the one case where that pin is
4358
+ * stale rather than protective: without this, every read cached for the rest
4359
+ * of the session is filed under a fingerprint the next session's identity
4360
+ * gate rejects, and the durable read cache silently yields nothing.
4361
+ */
4362
+ private restampConnectionIdentity;
4363
+ /**
4364
+ * Migrate every identity stamp from `from` to `to` — used when the auth
4365
+ * identity label changes but the underlying credential (token) does NOT, e.g.
4366
+ * the user id resolves a tick after the token was set. The in-memory
4367
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
4368
+ * keeps the in-flight writes replayable under the new (more stable) identity
4369
+ * instead of the flush guard discarding them as a mismatch.
4370
+ *
4371
+ * That map alone was not enough: it is consumed and DELETED on the first
4372
+ * flush attempt (`replayIdentityVerdict`), while the queue entry and its
4373
+ * persisted record keep the original stamp. So a reload, or a requeue after a
4374
+ * transient failure, fell back to the old token hash — and once the token had
4375
+ * been refreshed, `isSameCredentialUnderTokenHash` no longer recognised it
4376
+ * and the write was rejected `OFFLINE_IDENTITY_CHANGED` for the very user
4377
+ * `setAuthToken`'s sticky-`subject` contract promises to protect. The queue's
4378
+ * own re-stamp covers both the entry and its durable record.
4379
+ */
4380
+ private restampQueuedIdentity;
4381
+ /**
4382
+ * Migrate the {@link clientWatermarks} bucket map nested under identity
4383
+ * `from` to identity `to` — the sibling of {@link restampQueuedIdentity},
4384
+ * for the same same-credential-subject-resolves case. Without this, a
4385
+ * bucket's watermark cached under the token-hash fingerprint would look
4386
+ * unset once the fingerprint relabels to `subj:…`, so the next push
4387
+ * re-derives `1` against a server watermark the DO already advanced — the
4388
+ * OUT_OF_ORDER wedge this cache-keying scheme exists to fix, reintroduced
4389
+ * by the fix itself. `to` may already hold a bucket map (switching back to
4390
+ * an identity that has its own cached watermarks); merge into it rather
4391
+ * than clobbering it, with `from`'s entries winning on a colliding bucket —
4392
+ * the same overwrite a plain `Map.set` would have done before this was a
4393
+ * nested map.
4394
+ */
4395
+ private restampWatermarks;
4396
+ /**
4397
+ * Drop the durable read cache on an identity change so a cached value stamped
4398
+ * under the previous identity can never hydrate into a new session. Clears
4399
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
4400
+ * the durable `clear()` is best-effort.
4401
+ */
4402
+ private clearQueryCacheForIdentityChange;
4403
+ /**
4404
+ * Retire everything the PREVIOUS identity left live on a genuine identity
4405
+ * change: the sockets it is authenticated on, and the rows they delivered.
4406
+ *
4407
+ * A WebSocket credential is pinned in its upgrade URL and cannot be rotated
4408
+ * in place, so `setAuthToken` alone left the previous user's socket open and
4409
+ * delivering — the consequence `ShardConnection.identity`'s docblock already
4410
+ * described, with "nothing" as the thing that closes it on a client without
4411
+ * `crossTabSync`. And each `SubscriptionState` keeps the last value that
4412
+ * socket delivered, which `subscribe()` replays synchronously to every new
4413
+ * subscriber, so the incoming user's first render was the outgoing user's
4414
+ * rows even after the socket did go.
4415
+ *
4416
+ * Both halves are needed: closing the socket without clearing the values
4417
+ * leaves them on screen until a frame replaces them (which never comes for a
4418
+ * query the new user cannot read), and clearing the values without closing
4419
+ * the socket lets the next frame put them straight back.
4420
+ */
4421
+ private evictPreviousIdentitySession;
4422
+ /**
4423
+ * Move this tab's cross-tab coordinator onto the channel the new identity
4424
+ * derives, after an identity change.
4425
+ *
4426
+ * The channel name embeds the identity fingerprint (see
4427
+ * {@link createTabCoordinator}), so without this the tab keeps
4428
+ * leading/following the PREVIOUS identity's group. BroadcastChannel names
4429
+ * are immutable, so a stop-old+construct-new is the only way to move
4430
+ * channels — but that means the fresh coordinator would otherwise sit
4431
+ * through the full claim-then-`leaderTimeout` dance (3s default) before any
4432
+ * tab opens a socket again, freezing every live query for that long on
4433
+ * EVERY identity change (including a routine JWT refresh for an app that
4434
+ * doesn't pass a stable `subject` — the documented reason to pass one). If
4435
+ * this tab was already the leader, it's overwhelmingly likely to remain the
4436
+ * sole tab on the new channel too, so promote it immediately instead of
4437
+ * waiting — `promoteImmediately`'s docblock covers the (self-healing) rare
4438
+ * case where another tab does the same at once.
4439
+ */
4440
+ private restartTabCoordinatorForIdentity;
4441
+ /**
4442
+ * Close every open shard socket so each reconnects carrying the credential
4443
+ * in effect now.
4444
+ *
4445
+ * Non-terminal, unlike {@link close}: the `ShardConnection` records and the
4446
+ * subscriptions riding them survive, and the registered `close` handler
4447
+ * (`handleDisconnect`) schedules the retry and replays the subscribes. This
4448
+ * is the only way to move a WS credential — it lives in the upgrade URL.
4449
+ */
4450
+ private bounceShardSockets;
4451
+ /**
4452
+ * Flush every shard with a mutation currently queued in `offlineQueue`
4453
+ * (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
4454
+ * mirrored leader status transitions to `"connected"` — a follower has no
4455
+ * per-shard `ShardConnection` reconnect event to hang the usual
4456
+ * single-shard `flushOfflineQueue(shardKey)` call off of (see the `onOpen`
4457
+ * callback that calls `flushOfflineQueue(shardKey)`), so this walks every
4458
+ * shard that might have something queued instead. Flushing an already-empty
4459
+ * shard is a cheap no-op (`flushOfflineQueue` returns immediately once
4460
+ * `drain` yields nothing), so over-inclusion here is harmless.
4461
+ */
4462
+ private flushAllOfflineQueues;
4463
+ /**
4464
+ * Replay a shard's queued writes, serialized per shard and published as
4465
+ * {@link offlineFlushes} so a concurrent `mutation()` can wait behind it.
4466
+ * Never rejects: every entry's outcome is settled individually inside
4467
+ * {@link drainOfflineQueue}, and a poisoned chain would strand every later
4468
+ * flush AND every write waiting on the barrier.
4469
+ */
4470
+ private flushOfflineQueue;
4471
+ private drainOfflineQueue;
4472
+ /**
4473
+ * Ask for another flush of this shard after a backoff, because every entry it
4474
+ * drained was HELD for an identity that is not re-confirmed yet.
4475
+ *
4476
+ * Same state and same timer as a rate-limited replay
4477
+ * ({@link LunoraClient.noteReplayRetryDelay}) — one pending flush per shard
4478
+ * key either way — only the reason differs: there is no error to read a
4479
+ * `Retry-After` off, so the hintless {@link defaultReplayRetryDelayMs} ramp
4480
+ * (1s doubling to a 60s ceiling, jittered) is the whole policy. It is a
4481
+ * ceiling on the rate, not a budget of attempts: a durable write is never
4482
+ * dropped for having waited too long, so a subject that never resolves leaves
4483
+ * the queue re-probing at ≤ 60s intervals with the writes intact and
4484
+ * {@link LunoraClient.pendingCount} non-zero for the app to surface. The
4485
+ * retries stop when the hold lifts (the queue drains), when the shard has
4486
+ * nothing queued, or at `close()`.
4487
+ *
4488
+ * Identity is re-read by the flush, never carried across the timer: the
4489
+ * retry re-enters {@link LunoraClient.drainOfflineQueue}, which re-runs
4490
+ * {@link LunoraClient.replayGateVerdict} per entry against the identity in
4491
+ * effect when it runs. A retry therefore cannot replay a write under an
4492
+ * identity that changed while the timer was pending — it re-holds it, or
4493
+ * rejects it as a mismatch, exactly as a reconnect-driven flush would.
4494
+ */
4495
+ private noteHeldRetryDelay;
4496
+ /**
4497
+ * Remember the longest delay this shard's flush was told (or worked out) to
4498
+ * wait, so the drain can honour it before trying again
4499
+ * ({@link LunoraClient.replayRetryState}). Counts the attempt either way:
4500
+ * that is what a hintless refusal backs off on.
4501
+ *
4502
+ * A credential refused under a cookie session (`authToken === null`) backs
4503
+ * off on the hintless ramp too. A bearer refusal waits for `setAuthToken`,
4504
+ * which re-flushes; a cookie is renewed in the browser, invisibly to this
4505
+ * client, so the only way to learn it was is to send again.
4506
+ */
4507
+ private noteReplayRetryDelay;
4508
+ /**
4509
+ * Consume this shard's retry delay and re-flush it once the delay has
4510
+ * elapsed.
4511
+ *
4512
+ * Two things record a delay for it to consume: a failure the server or an
4513
+ * edge ANSWERED (see {@link replayRetryDelayMs}) and a flush that HELD every
4514
+ * entry it drained (see {@link LunoraClient.noteHeldRetryDelay}). Both happen
4515
+ * over a socket that stays open, so without this the writes sit queued
4516
+ * indefinitely; a `fetch` that never landed records nothing, because the
4517
+ * reconnect that follows flushes the queue anyway. One pending timer per
4518
+ * shard; a second delay replaces it rather than stacking flushes.
4519
+ *
4520
+ * Nothing left to retry on this key (drained, closed, or no delay) drops its
4521
+ * backoff state, which is both the reset after progress and what bounds the
4522
+ * map.
4523
+ */
4524
+ private scheduleRateLimitedRetry;
4525
+ /**
4526
+ * Partition already-gated writes into the encodable ones (returned) and reject
4527
+ * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
4528
+ * or class instance in a `v.any()` field) can NEVER replay — the codec failure
4529
+ * is deterministic, not transient. Rejecting here is essential: otherwise
4530
+ * `encodeWire` throws mid-flush, is classified as transient (a codec error has
4531
+ * no `.code`), and re-queues forever — a silent hang where the caller's Promise
4532
+ * never settles and the optimistic write never rolls back. Encoding is cheap;
4533
+ * the flush is the slow reconnect path.
4534
+ */
4535
+ private encodableOrSettleTerminal;
4536
+ /**
4537
+ * The three-way comparison behind {@link replayIdentityVerdict} (documented
4538
+ * there), without a credential: the built-in queue sends with its own pinned token.
4539
+ */
4540
+ private identityVerdict;
4541
+ /**
4542
+ * Identity gate for one queued write about to replay: a write stamped under
4543
+ * one identity must never replay under another, and must never be DESTROYED
4544
+ * because the identity isn't known yet.
4545
+ *
4546
+ * The three-way verdict is {@link replayIdentityVerdict}'s, not a second
4547
+ * hand-rolled comparison — `@lunora/db`'s durable outbox holds on `"unknown"`
4548
+ * through the same call, and this path (the default for the standalone
4549
+ * client) used to drop there instead, purging the queuing user's own write
4550
+ * on every reload that opened its socket before the session resolved.
4551
+ *
4552
+ * `"send"` replays it and consumes the live stamp. `"hold"` leaves it queued
4553
+ * and persisted, stamp intact, for a later flush once an identity is
4554
+ * established (see `setAuthToken`). `"reject"` means a different identity is
4555
+ * signed in: settle it terminally `OFFLINE_IDENTITY_CHANGED` and purge the
4556
+ * durable record.
4557
+ */
4558
+ private replayGateVerdict;
4559
+ /** Settle a write that replayed successfully: confirm its optimistic layer against the echoed commit cursor BEFORE resolving, so the gapless drop is in place when the awaiter (and any confirming frame) observes the settle. */
4560
+ private settleReplaySuccess;
4561
+ /**
4562
+ * The entry a shard's cursor lives under.
4563
+ *
4564
+ * Only the server knows that an omitted `shardKey` and an explicit one
4565
+ * spelling out its configured default name are the same shard — the default
4566
+ * is server-side configuration the client never sees. Keying on what was
4567
+ * SENT would split one shard's cursor across two entries, so a write under
4568
+ * one spelling would stop constraining a read under the other. Resolving
4569
+ * `undefined` through the learned name is what keeps both spellings on one
4570
+ * entry.
4571
+ */
4572
+ private cursorKeyFor;
4573
+ /**
4574
+ * Learn the server's own name for the default shard from a response to a
4575
+ * call that named no shard.
4576
+ *
4577
+ * Any cursor recorded before the name was known sits under the placeholder
4578
+ * entry, so it is folded in rather than stranded — otherwise the requirement
4579
+ * from a client's first write would be lost exactly once, which is the kind
4580
+ * of gap that only shows up as a stale read under load.
4581
+ */
4582
+ private learnDefaultShardKey;
4583
+ /**
4584
+ * Record the cursor a write committed at as this shard's read-your-writes
4585
+ * requirement.
4586
+ *
4587
+ * Monotonic: responses can land out of order, and moving the requirement
4588
+ * BACKWARDS would let a later read be answered from a replica copy that
4589
+ * predates a write this client already saw.
4590
+ */
4591
+ private recordShardCursor;
4592
+ /**
4593
+ * Whether a replay failure leaves the durable write queued rather than
4594
+ * settling it terminally — the ONE classification the single-call, per-slot
4595
+ * and whole-batch paths share, so a write's fate never depends on how many
4596
+ * siblings rode along.
4597
+ *
4598
+ * {@link isTransientReplayFailure} answers the "no verdict was reached" half.
4599
+ * The other half is a refused CREDENTIAL ({@link isAuthReplayFailure}): the
4600
+ * queue flushes on the shard's `open` handler with whatever bearer survived
4601
+ * the offline window, so an expired token is the expected outcome of a long
4602
+ * disconnect, not a verdict on the write. Notifying {@link onTokenExpired}
4603
+ * here is what closes the loop — the HTTP replay path has no equivalent of
4604
+ * the WS `4001` close frame, so without this nothing tells the app to
4605
+ * refresh, and `setAuthToken` (which re-flushes) is never called.
4606
+ *
4607
+ * Notified once per credential, not once per write: a flush of a hundred
4608
+ * queued writes earns a hundred identical refusals, and firing the hook for
4609
+ * each would put a hundred token refreshes on the app. The stamp re-arms as
4610
+ * soon as the credential moves, which is the only thing that can change the
4611
+ * answer.
4612
+ */
4613
+ private shouldRequeueReplayFailure;
4614
+ /**
4615
+ * Whether `error` refused a replay's CREDENTIAL (`authToken`, the bearer it
4616
+ * was sent with), and if so tell {@link onTokenExpired} — once per
4617
+ * credential, and only while it is still the current one. A refusal of a
4618
+ * token the app has already replaced says nothing about the current one:
4619
+ * the next pass re-sends under it, so asking for another refresh would be
4620
+ * spurious.
4621
+ */
4622
+ private noteReplayAuthRefusal;
4623
+ /**
4624
+ * A request under `authToken` succeeded: if a refusal of that credential was
4625
+ * reported, its next refusal is news again. A bearer re-arms by changing; a
4626
+ * cookie session's `null` never does, so without this the app could be asked
4627
+ * to refresh a cookie only once per page.
4628
+ */
4629
+ private noteCredentialAccepted;
4630
+ /**
4631
+ * Redeem a {@link ReplayCredential} (single use) into the request flags it
4632
+ * pins (the judged bearer, and the subject a cookie replay names) and the
4633
+ * identity stamp it was judged for. Throws for a credential this client did
4634
+ * not issue or already redeemed.
4635
+ */
4636
+ private takeReplayCredential;
4637
+ /**
4638
+ * Whether `failure` is the worker's `IDENTITY_MISMATCH` refusal, and if so,
4639
+ * ask who is signed in now: the answer is what re-runs the replay gate
4640
+ * ({@link setAuthToken}), and nothing else would on a cookie session.
4641
+ */
4642
+ private noteIdentityMismatch;
4643
+ /**
4644
+ * Settle a write the server COMMITTED whose result does not decode. It is
4645
+ * `committed` — its optimistic layer confirms against the echoed cursor like
4646
+ * any success — but there is no value to hand the caller, so the awaiter is
4647
+ * rejected with the decode error and the settled event carries it.
4648
+ */
4649
+ private settleReplayUndecodable;
4650
+ /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
4651
+ private settleReplayTerminal;
4652
+ /**
4653
+ * Replay already-identity-gated writes one at a time on the single-call `/rpc`
4654
+ * path, preserving FIFO order (parallel `.then()` chains would race the
4655
+ * ordering callers depend on). Each replays under its stable `mutationId` so
4656
+ * the server dedups a write it already committed (exactly-once). A server verdict
4657
+ * drops the write; a transient failure ({@link isTransientReplayFailure} — a
4658
+ * transport error, a shard the worker couldn't reach, a rate-limit refusal, or a
4659
+ * non-2xx carrying no `{ error }` envelope) stops the flush and re-queues this
4660
+ * write and every unreplayed one for the next reconnect — their callers stay
4661
+ * pending, and the identity guard re-applies on retry via each record's persisted
4662
+ * stamp. The batch path classifies a slot by the same rule, so a durable write's
4663
+ * fate never depends on how many siblings happened to be queued alongside it.
4664
+ */
4665
+ private replaySequential;
4666
+ /**
4667
+ * Coalesce already-identity-gated writes for a single shard into ONE
4668
+ * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
4669
+ * them to the shard DO, which replays each through its single-call dispatch, so
4670
+ * per-entry `mutationId` idempotency and in-order application are inherited from
4671
+ * the proven path. Per-slot demux mirrors {@link replaySequential}'s
4672
+ * classification: success confirms the optimistic layer against the echoed
4673
+ * `commitCursor`; a coded application verdict is terminal; a failure
4674
+ * {@link shouldRequeueReplayFailure} keeps, a missing slot, or a whole-batch
4675
+ * transport failure re-queues for the next reconnect (never dropping a durable
4676
+ * write). A whole-batch coded rejection (a bad request the server reached a
4677
+ * verdict on) is terminal for every entry.
4678
+ *
4679
+ * The body is also held under {@link MAX_BATCH_BODY_BYTES}: the worker caps a
4680
+ * batch body at 1 MiB and answers `413`, which is ONE refusal covering every
4681
+ * write in the chunk. An over-budget chunk is halved before it is sent, and a
4682
+ * `413` for a chunk of more than one write halves it and retries rather than
4683
+ * settling the whole chunk terminally — so a backlog of large writes still
4684
+ * commits, one bisection deeper.
4685
+ *
4686
+ * Returns the writes that must be re-queued and `stop` — `true` when the whole
4687
+ * chunk failed at the transport level, so the caller leaves later chunks queued
4688
+ * rather than sending on. The caller re-queues once, in order, so requeuing is
4689
+ * NOT done here.
4690
+ */
4691
+ private replayBatched;
4692
+ /**
4693
+ * Classify a `/_lunora/rpc-batch` reply that carried no per-slot results — one
4694
+ * outcome covering every entry in the chunk. A code
4695
+ * {@link shouldRequeueReplayFailure} keeps (an unreachable shard, a
4696
+ * rate-limit refusal, a refused credential) or a {@link TransportError} (an
4697
+ * edge reply with no verdict in it) leaves every write durable for the next
4698
+ * attempt; anything else is a verdict reached on the request itself, and
4699
+ * settles all of them.
4700
+ */
4701
+ private settleWholeBatchError;
4702
+ /**
4703
+ * Split an over-large batch chunk in half and replay each half, preserving
4704
+ * FIFO order. Recurses through {@link replayBatched}, so a chunk keeps halving
4705
+ * until it fits (or reaches one write, which is then the server's verdict to
4706
+ * give). A `stop` on the first half leaves the second unsent and queued.
4707
+ */
4708
+ private replayBatchedHalves;
4709
+ /**
4710
+ * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
4711
+ * in input order. Each slot's envelope classifies its write the same way
4712
+ * {@link replaySequential} does: a success confirms the optimistic layer
4713
+ * against the echoed `commitCursor`; a coded application verdict is terminal;
4714
+ * a failure {@link shouldRequeueReplayFailure} keeps, or a slot the server
4715
+ * never returned, is returned for the caller to re-queue.
4716
+ *
4717
+ * A slot whose `error` key holds no readable envelope is in the same position
4718
+ * as one the server never returned — nothing came back about that entry that
4719
+ * can be read as a verdict — so it is kept, not settled.
4720
+ * @returns the writes that must be re-queued (kept slots), in input order
4721
+ */
4722
+ private settleReplayBatchSlots;
4723
+ /**
4724
+ * Settle one batch slot that answered with a result. Decoded per slot: one
4725
+ * result the codec refuses must not abandon the slots after it (committed
4726
+ * writes left pending and unsettled for the rest of the session), and its
4727
+ * own write DID commit.
4728
+ */
4729
+ private settleReplayBatchResult;
4730
+ }
4731
+ export { ServerMessage as $, ActionCallOptions as A, BookmarkStorage as B, ConnectionStatus as C, DEFAULT_MAX_BUFFER as D, OutboxMutation as E, FunctionArgumentDescriptor as F, GlobalFacetResult as G, HttpStreamRef as H, OutboxSink as I, PersistedMutation as J, ReplayCredential as K, LunoraClient as L, MutationCallOptions as M, ReplayIdentityVerdict as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReconnectOptions as R, SubscriptionError as S, RowOp as T, User as U, RpcEnvelope as V, RpcResponseBody as W, ScheduleRecord as X, ScheduleRetryPolicy as Y, SchedulerPoolStatus as Z, SchedulerStatus as _, Unsubscribe as a, ServerPokeEndMessage as a0, ServerPokePartMessage as a1, ServerPokeStartMessage as a2, ShardTrafficEntry as a3, ShardTrafficResult as a4, StorageListPage as a5, StorageObject as a6, StoredQuery as a7, StreamHandle as a8, SubscriptionCallback as a9, SubscriptionRegistry as aa, SubscriptionState as ab, SyncWatermark as ac, WorkflowInstanceAction as ad, WorkflowInstanceDetail as ae, WorkflowInstancePage as af, WorkflowInstanceStatus as ag, WorkflowInstanceSummary as ah, WorkflowStepDetail as ai, WsTokenProvider as aj, createClientQuery as ak, createLocalStore as al, createStream as am, SubscriptionErrorCallback as b, PersistenceAdapter as c, HttpStreamArgsOf as d, HttpStreamChunkOf as e, StreamIterable as f, BatchSlot as g, CachedQuery as h, ClientDebugShard as i, ClientDebugSnapshot as j, ClientDebugSubscription as k, ClientMessage as l, ClientQueryRef as m, ClientShapeSubscribeMessage as n, ClientShapeUnsubscribeMessage as o, FunctionDescriptor as p, GlobalFacetValue as q, GlobalFilterClause as r, GlobalTableInfo as s, GlobalTablePage as t, HttpStreamCallArgs as u, LunoraClientError as v, LunoraClientOptions as w, MutationSettledEvent as x, OptimisticLocalStore as y, OptimisticUpdate as z };