@lunora/client 1.0.0-alpha.15 → 1.0.0-alpha.150

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 (92) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +16 -3
  3. package/dist/auth/index.d.mts +43 -12
  4. package/dist/auth/index.d.ts +43 -12
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +895 -271
  7. package/dist/index.d.ts +895 -271
  8. package/dist/index.mjs +1 -15
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  10. package/dist/packem_shared/ClientServiceWorker-DXnBXeWK.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  12. package/dist/packem_shared/LunoraClient-DEEbBpNA.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-BWamzR6p.mjs +1 -0
  14. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  15. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  16. package/dist/packem_shared/SubscriptionRegistry-C3kLqped.mjs +1 -0
  17. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  18. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  19. package/dist/packem_shared/applyDelta-CIjpZ5h9.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStoragePersistence-CeUW9NTj.mjs +1 -0
  21. package/dist/packem_shared/createAsyncStorageQueryCache-Dpszf7UD.mjs +1 -0
  22. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  23. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  26. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  27. package/dist/packem_shared/createLocalStore-0ARUZ892.mjs +1 -0
  28. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  29. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  30. package/dist/packem_shared/createReply-CwFABEJs.mjs +1 -0
  31. package/dist/packem_shared/createServerClient-BQ5rqRDi.mjs +1 -0
  32. package/dist/packem_shared/createSnapshotPrecondition-5GQ_5fFu.mjs +1 -0
  33. package/dist/packem_shared/delta-merge-D_5ChS-C.mjs +1 -0
  34. package/dist/packem_shared/deserializePreloaded-Bffy70Wm.mjs +1 -0
  35. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  36. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  37. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  38. package/dist/packem_shared/httpStream-v4etRV7m.mjs +9 -0
  39. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  40. package/dist/packem_shared/local-store-DDppw8Qr.mjs +1 -0
  41. package/dist/packem_shared/lunora-client.d-BqcmL_p0.d.ts +4661 -0
  42. package/dist/packem_shared/lunora-client.d-mHTdWjff.d.mts +4661 -0
  43. package/dist/packem_shared/offline-queue-D_fr-uQ3.mjs +1 -0
  44. package/dist/packem_shared/preload.d-f9FxbP31.d.ts +21 -0
  45. package/dist/packem_shared/preload.d-wYfTr5NW.d.mts +21 -0
  46. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  47. package/dist/packem_shared/replay-CXXDZ1_h.mjs +1 -0
  48. package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
  49. package/dist/packem_shared/wire-codec-BeIi1K-T.mjs +1 -0
  50. package/dist/packem_shared/wire-key-DCPYV4t8.mjs +1 -0
  51. package/dist/pagination/index.d.mts +42 -42
  52. package/dist/pagination/index.d.ts +42 -42
  53. package/dist/pagination/index.mjs +1 -61
  54. package/dist/query/index.d.mts +111 -43
  55. package/dist/query/index.d.ts +111 -43
  56. package/dist/query/index.mjs +1 -1
  57. package/dist/service.d.mts +49 -0
  58. package/dist/service.d.ts +49 -0
  59. package/dist/service.mjs +1 -0
  60. package/dist/ssr/index.d.mts +109 -79
  61. package/dist/ssr/index.d.ts +109 -79
  62. package/dist/ssr/index.mjs +1 -4
  63. package/dist/upload.d.mts +35 -0
  64. package/dist/upload.d.ts +35 -0
  65. package/dist/upload.mjs +1 -0
  66. package/package.json +16 -1
  67. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  68. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  69. package/dist/packem_shared/LunoraClient-ClBd8JUG.mjs +0 -3301
  70. package/dist/packem_shared/OfflineQueue-GGYJRmhF.mjs +0 -1
  71. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  72. package/dist/packem_shared/SubscriptionRegistry-Cxr70og-.mjs +0 -1
  73. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  74. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  75. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  76. package/dist/packem_shared/createInMemoryPersistence-CY6F0ZvQ.mjs +0 -117
  77. package/dist/packem_shared/createInMemoryQueryCache-Bv4Ruv6n.mjs +0 -150
  78. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +0 -1
  79. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  80. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  81. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  82. package/dist/packem_shared/createServerClient-BUEYFHjp.mjs +0 -11
  83. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  84. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  85. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +0 -111
  86. package/dist/packem_shared/lunora-client.d-CtSRWJJ7.d.mts +0 -2360
  87. package/dist/packem_shared/lunora-client.d-CtSRWJJ7.d.ts +0 -2360
  88. package/dist/packem_shared/offline-queue-B9vfdSqp.mjs +0 -170
  89. package/dist/packem_shared/preload.d-GjXaOwY9.d.mts +0 -20
  90. package/dist/packem_shared/preload.d-NMFbch9j.d.ts +0 -20
  91. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  92. package/dist/packem_shared/subscription-DoyO04-2.mjs +0 -65
@@ -0,0 +1,4661 @@
1
+ import { LunoraErrorCodeInput, LunoraErrorCode } from '@lunora/errors';
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.js";
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_*` binding 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
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
1898
+ private readonly defaultConnectionContext;
1899
+ /**
1900
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
1901
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
1902
+ * on every socket open so it replays across reconnects, and forwarded to the
1903
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
1904
+ * imperative (last-writer-wins) override; refcounted holders registered via
1905
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
1906
+ * precedence — see `effectiveConnectionContext`.
1907
+ */
1908
+ private readonly connectionContexts;
1909
+ /**
1910
+ * Per-shard stack of refcounted connection-context holders (keyed by
1911
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
1912
+ * is an opaque token carrying its `context`; the most-recently acquired
1913
+ * holder wins (last-writer-wins among live holders), and the context is only
1914
+ * cleared for a shard once its last holder releases — so two concurrently
1915
+ * mounted presence hooks on the same shard can't stomp each other's context
1916
+ * on cleanup. A holder is identified by reference identity so a release
1917
+ * removes exactly the right one regardless of stack position.
1918
+ */
1919
+ private readonly connectionContextHolders;
1920
+ private authToken;
1921
+ /**
1922
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
1923
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
1924
+ * like an identity change (which would discard queued writes). `undefined` =
1925
+ * not supplied, so identity falls back to a hash of the raw token. See
1926
+ * `setAuthToken` / `identityFingerprint`.
1927
+ */
1928
+ private authSubject;
1929
+ /**
1930
+ * The bearer token `authSubject` was last asserted against. A subject
1931
+ * is a claim about WHO a specific credential belongs to; once the token
1932
+ * rotates, the sticky label is carried forward on the assumption it is the
1933
+ * same user — but nothing has confirmed that yet, and the alternative (an
1934
+ * account switch) would replay one user's queued writes as another. While
1935
+ * this is out of step with `authToken` the identity counts as unconfirmed
1936
+ * and every replay verdict is `"unknown"` (hold), until the next session
1937
+ * resolve re-asserts the subject. Only used when a subject is established;
1938
+ * a token-hash identity is self-confirming.
1939
+ */
1940
+ private subjectToken;
1941
+ /**
1942
+ * How many `getCurrentUser()` round trips are in flight.
1943
+ *
1944
+ * The identity gates need to tell two `null` fingerprints apart. For an app
1945
+ * with no auth at all, and for a client the server has answered "no
1946
+ * session" to, `null` is a real and stable identity — nobody else holds it,
1947
+ * so a `null`-stamped queued write or cached read is this client's own and
1948
+ * may be used. While a resolve is IN FLIGHT it is neither: the fingerprint
1949
+ * may be one round trip away from `subj:<id>`, which is the window a cookie
1950
+ * app spends every page load in, and where `null === null` handed one
1951
+ * browser user's durable state to the next. Counted rather than flagged so
1952
+ * two overlapping resolves (a token change during a probe) both have to
1953
+ * finish before the gates reopen.
1954
+ */
1955
+ private sessionProbesInFlight;
1956
+ /**
1957
+ * Monotonic id stamped on each `/get-session` round trip, so only the
1958
+ * NEWEST one may write the shared identity.
1959
+ *
1960
+ * `adoptResolvedSubject`'s token check asks whether the credential the
1961
+ * answer is about is still the one in hand. On a cookie app there is no
1962
+ * credential to ask about: every probe captures `requestToken === null`, so
1963
+ * two overlapping probes both pass it and whichever lands LAST wins —
1964
+ * including an older one, which then replaces the subject a newer answer
1965
+ * already established. Comparing the generation instead asks the question
1966
+ * the token cannot: is this still the current question?
1967
+ */
1968
+ private sessionProbeGeneration;
1969
+ /**
1970
+ * Monotonic id of every question this client asks the server about who it
1971
+ * is: each `/get-session` probe, and each cookie-authenticated socket upgrade
1972
+ * (answered by the `identity` frame the shard sends on `connect`). Probes
1973
+ * take their `sessionProbeGeneration` from it, so both kinds of
1974
+ * answer share one order.
1975
+ */
1976
+ private identityQuestions;
1977
+ /**
1978
+ * The `identityQuestions` id of the newest answer adopted so far. A
1979
+ * cookie-session answer older than it describes an older cookie — a socket
1980
+ * upgraded before a probe that has since answered — and may not move the
1981
+ * identity back. See `adoptCookieSubject`.
1982
+ */
1983
+ private identityAnsweredAt;
1984
+ /** Unregisters this client from the page's session-change signal (`shared/session-change.ts`); set in the constructor. */
1985
+ private releaseSessionChangeListener;
1986
+ /** Whether the one-time `IDENTITY_MISMATCH` configuration warning has been logged (see `noteIdentityMismatch`). */
1987
+ private warnedIdentityDisagreement;
1988
+ /**
1989
+ * Whether anything resolves this client's identity at all.
1990
+ *
1991
+ * The gates need to tell an app with NO AUTH — whose `null` fingerprint is
1992
+ * settled forever and shared with nobody — from a cookie app that simply
1993
+ * has not asked yet. Nothing in the client's own configuration says which
1994
+ * it is (`authBasePath` has a default), so the answer is declared: a
1995
+ * `getCurrentUser()` call, or `@lunora/client/auth`'s identity store
1996
+ * attaching itself, is what makes `null` provisional. An app that does
1997
+ * neither keeps its read cache and its offline queue exactly as before.
1998
+ */
1999
+ private identityResolutionExpected;
2000
+ /**
2001
+ * Whether a `/get-session` round trip has ever produced an ANSWER — a user,
2002
+ * or an explicit "no session". Distinct from `sessionProbesInFlight`, which
2003
+ * only covers the request's own lifetime and so reopened the gates both
2004
+ * before the first probe started and after one failed to answer, leaving a
2005
+ * `null` fingerprint free to match the previous cookie user's cached rows
2006
+ * and queued writes in exactly the window the probe count was added to
2007
+ * close. A transport or parse failure never sets this: it learned nothing.
2008
+ */
2009
+ private identitySettled;
2010
+ /**
2011
+ * Identity stamp recorded against each queued offline mutation, keyed by
2012
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
2013
+ * in effect at the time, and re-checked at flush so a queued write can
2014
+ * never replay under a different identity than the one that issued it.
2015
+ * See `identityFingerprint` for the fingerprint shape.
2016
+ */
2017
+ private readonly queuedIdentities;
2018
+ /**
2019
+ * Distinct shard keys with a mutation currently sitting in `offlineQueue`
2020
+ * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
2021
+ * restored from durable storage (`hydratePersistedQueue`). A follower tab
2022
+ * has no per-shard `ShardConnection` to iterate when its mirrored leader
2023
+ * status turns `"connected"` (see the `onConnectionStatus` coordinator
2024
+ * option), so this is what that flush walks instead. Entries are never
2025
+ * removed — flushing an already-empty shard is a cheap no-op, and the set
2026
+ * is bounded by the app's own distinct shard-key cardinality.
2027
+ */
2028
+ private readonly queuedOfflineShardKeys;
2029
+ private closed;
2030
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
2031
+ private readonly authTokenListeners;
2032
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
2033
+ private readonly statusListeners;
2034
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
2035
+ private readonly tokenExpiredListeners;
2036
+ /** Subscribers notified when the previous identity's session is retired (see `onIdentityChange`). */
2037
+ private readonly identityChangeListeners;
2038
+ /** How many identities this client has retired (see `identityEpoch`). */
2039
+ private retiredIdentities;
2040
+ /** Token hash the last durable-replay auth refusal fired `onTokenExpired` for — see `noteReplayAuthRefusal`. */
2041
+ private authRefusalNotifiedFor;
2042
+ /** What each outstanding {@link ReplayCredential} was judged against — see `replayIdentityVerdict`. */
2043
+ private readonly replayCredentials;
2044
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
2045
+ private readonly mutationSettledListeners;
2046
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
2047
+ private readonly pendingChangeListeners;
2048
+ /**
2049
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
2050
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
2051
+ * (re)connect so a topic survives a socket bounce.
2052
+ */
2053
+ private readonly whisperHandlers;
2054
+ /** Last status broadcast, so we only notify listeners on an actual change. */
2055
+ private lastStatus;
2056
+ private nextSubId;
2057
+ private nextStreamId;
2058
+ /**
2059
+ * In-flight client-side stream readers, keyed by the stream id sent on the
2060
+ * wire. The handle drives the underlying iterator queue and `shardKey`
2061
+ * tells us which socket to push the cancel frame onto when the consumer
2062
+ * calls `.cancel()` or the iterator is garbage-collected.
2063
+ */
2064
+ private readonly streams;
2065
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
2066
+ /**
2067
+ * Teardown callbacks for the admin sockets {@link LunoraClient.subscribeScheduledJobs}
2068
+ * opens. Those run their own reconnect loop off a closure-local `closed`
2069
+ * flag rather than `this.closed` (they predate `ensureSocket`'s guard), so
2070
+ * without this registry a `close()` left every one of them reconnecting on
2071
+ * its backoff forever — re-minting an ephemeral admin sub-token on each
2072
+ * attempt when a `WsTokenProvider` is wired.
2073
+ */
2074
+ private readonly adminSocketTeardowns;
2075
+ /**
2076
+ * The in-flight offline-queue replay per shard (`connectionKey`), while one
2077
+ * is running. Two jobs:
2078
+ *
2079
+ * 1. It serializes overlapping flushes for the same shard — two reconnect
2080
+ * events in quick succession used to drain and replay concurrently.
2081
+ * 2. It is the barrier {@link LunoraClient.mutation} waits on before sending a FRESH
2082
+ * write directly. The socket's `open` handler flips `wsState` to `"open"`
2083
+ * first and calls the flush last, so from that instant `mutation()`'s
2084
+ * offline gate is false and a new write raced straight to `/rpc` against
2085
+ * the replay of the older, queued write for the same document — the newer
2086
+ * one could land first and then be overwritten by the older. Ordering
2087
+ * inside the replay (`replaySequential`) never covered this, because the
2088
+ * racing write was never in the queue.
2089
+ */
2090
+ private readonly offlineFlushes;
2091
+ /**
2092
+ * Per-shard replay backoff, keyed by {@link connectionKey} exactly as the
2093
+ * flushes and their timers are: `delayMs` is the longest hint the CURRENT
2094
+ * flush of that key was given (written by
2095
+ * {@link LunoraClient.noteReplayRetryDelay}, consumed once by
2096
+ * {@link LunoraClient.scheduleRateLimitedRetry} at the end of the drain), and
2097
+ * `attempts` counts its consecutive failed flushes, which is what the
2098
+ * hintless backoff ramps on.
2099
+ *
2100
+ * Keyed, not a single field: flushes are per shard key and run concurrently,
2101
+ * so one field means one limited shard sets the wait for every other shard
2102
+ * and two flushes overwrite — then consume — each other's delay, leaving one
2103
+ * of them with nothing scheduled at all. Evicted by
2104
+ * {@link LunoraClient.scheduleRateLimitedRetry} the moment a key has nothing
2105
+ * left to retry, so an app that shards per document does not accumulate an
2106
+ * entry per document it ever wrote.
2107
+ */
2108
+ private readonly replayRetryState;
2109
+ /** Pending rate-limit retry flushes, keyed by {@link connectionKey}, so `close()` can cancel them. */
2110
+ private readonly replayRetryTimers;
2111
+ private readonly shapeSubscriptions;
2112
+ /**
2113
+ * In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by
2114
+ * `<connectionKey>\u0000<pokeId>`.
2115
+ *
2116
+ * The connection has to be in the key: `pokeId` is a per-DO counter that also
2117
+ * resets on eviction, so a multi-shard client — one socket per shard, one map
2118
+ * here — sees two shards mint `poke-1` concurrently. Keyed by `pokeId` alone
2119
+ * their frames interleave into a single buffer: one shard applies the other's
2120
+ * epoch (spurious fork → view wiped) and the other finds no buffer for its
2121
+ * parts at all, silently dropping rows while the server's memo advances.
2122
+ */
2123
+ private readonly pokeBuffers;
2124
+ private nextShapeId;
2125
+ constructor(options: LunoraClientOptions);
2126
+ /**
2127
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
2128
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
2129
+ * sync across all mounted instances.
2130
+ *
2131
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
2132
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
2133
+ * doesn't read as an identity change and discard queued writes. The subject is
2134
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
2135
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
2136
+ * `setAuthToken(token, user.id)` retains the identity. Clearing the token
2137
+ * clears it too — a credential-less subject would let the NEXT sign-in
2138
+ * inherit the previous user's identity (and their queue and read cache).
2139
+ * Establishing the subject on an UNCHANGED token (e.g. the user id resolves a
2140
+ * tick after the token was set — see {@link getCurrentUser}, which does this
2141
+ * for every adapter) re-stamps any in-flight queued writes rather than
2142
+ * dropping them: same credential, just a more stable label. A real user
2143
+ * switch still drops the previous user's writes.
2144
+ *
2145
+ * A sticky subject carried across a token change is not re-confirmed until
2146
+ * the next session resolve says which user the NEW credential belongs to.
2147
+ * Queued writes are HELD (never sent, never dropped) for that window — see
2148
+ * {@link replayIdentityVerdict} — so a refresh can't replay them and an
2149
+ * account switch can't replay the previous user's writes as the new one.
2150
+ *
2151
+ * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
2152
+ * time and lives in the URL. To refresh live WS auth, call
2153
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
2154
+ * force a reconnect with the new credential.
2155
+ */
2156
+ setAuthToken(token: string | null, subject?: string | null): void;
2157
+ getAuthToken(): string | null;
2158
+ /**
2159
+ * The current identity fingerprint (the same stamp queued offline writes
2160
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
2161
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
2162
+ * can drop a persisted write whose captured `identity` no longer matches the
2163
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
2164
+ */
2165
+ currentIdentity(): string | null;
2166
+ /**
2167
+ * Declare that this client's identity is resolved by something — call it
2168
+ * before the first `getCurrentUser()`, not after.
2169
+ *
2170
+ * `@lunora/client/auth`'s identity store calls this when it attaches, which
2171
+ * is the moment an app becomes one that HAS auth. Until something says so,
2172
+ * a `null` fingerprint is taken to be the settled, unshared identity of an
2173
+ * app with no auth at all, because nothing else distinguishes the two: both
2174
+ * hold no token, both have never been answered, and `authBasePath` has a
2175
+ * default. That reading is right for the no-auth app and wrong for a cookie
2176
+ * app whose first `/get-session` has not started — the window where
2177
+ * `null === null` matched the PREVIOUS browser user's cached rows and
2178
+ * queued writes, before any probe was in flight to mark the fingerprint
2179
+ * provisional.
2180
+ *
2181
+ * Idempotent, and one-way: a client that resolves an identity keeps its
2182
+ * gates armed until a probe actually answers.
2183
+ */
2184
+ expectIdentityResolution(): void;
2185
+ /**
2186
+ * This client's current CDC baseline for `shardKey` — the cursor its live
2187
+ * queries have reached, which is what a write composed right now should be
2188
+ * judged against.
2189
+ *
2190
+ * Exposed for the same reason {@link currentIdentity} is: a durable
2191
+ * {@link OutboxSink} owns its own at-least-once replay outside the built-in
2192
+ * `OfflineQueue`, so it has to capture this at COMPOSE time and hand it back
2193
+ * through {@link MutationCallOptions.replayBaseline}. Sampling it inside the
2194
+ * replay instead reads the cursor this client has advanced to in the
2195
+ * meantime, which is the newer state the write must be judged against.
2196
+ *
2197
+ * `undefined` when no subscription on the shard carries a cursor yet.
2198
+ */
2199
+ currentBaseline(shardKey?: string): number | undefined;
2200
+ /**
2201
+ * Verdict on whether a durable write stamped with `stamped` may be replayed
2202
+ * now. The comparison a replay handler must NOT hand-roll.
2203
+ *
2204
+ * `"match"` is the same identity, or the same credential under a token hash
2205
+ * — which a late-resolving subject would otherwise make look different.
2206
+ *
2207
+ * `"unknown"` is nobody signed in *yet*. A durable replay starts when the
2208
+ * executor is constructed, before the app has resolved its session and
2209
+ * called {@link setAuthToken}, so this is the normal state on every reload.
2210
+ * There is no other identity to replay as, so such a write must be HELD,
2211
+ * never dropped — dropping here destroys the queuing user's own offline
2212
+ * writes. It is indistinguishable from an explicit sign-out (the fingerprint
2213
+ * is `null` for both), which is the safe conflation: holding a write for a
2214
+ * signed-out app costs a retry, dropping it costs the write.
2215
+ *
2216
+ * It also covers a `null` stamp against a `null` fingerprint — but only
2217
+ * while {@link identityUnresolved} says a session resolve is in flight.
2218
+ * Two `null`s are the same identity for an app with no auth at all (nobody
2219
+ * else shares that fingerprint, because nobody else exists) and for a
2220
+ * client the server has told there is no session; they are NOT the same
2221
+ * identity in the window where the fingerprint is about to become
2222
+ * `subj:<id>`, which is where one browser user's queued write went out on
2223
+ * the next one's cookie.
2224
+ *
2225
+ * A held write is not stranded: the hold ends when the resolve settles, and
2226
+ * both {@link setAuthToken} and {@link getCurrentUser} re-flush there. If
2227
+ * the identity that arrives is not the one that queued the write, the
2228
+ * verdict is then `"mismatch"` and the write is settled terminally.
2229
+ *
2230
+ * A sticky subject carried across a token change is `"unknown"` for the same
2231
+ * reason: the label says user A, the credential in hand has not been checked
2232
+ * against it, and the two answers (a refresh vs an account switch) call for
2233
+ * opposite verdicts. Hold until the next session resolve settles it.
2234
+ *
2235
+ * `"mismatch"` is a different identity signed in, and is the one that must be
2236
+ * terminal: replaying would attribute one user's write to another and pass
2237
+ * THEIR row-level security.
2238
+ *
2239
+ * A `"match"` carries the {@link ReplayCredential} the replay must be sent
2240
+ * with ({@link MutationCallOptions.replayCredential}): the bearer held right
2241
+ * now, which is the one this verdict judged. The replay goes out with it even
2242
+ * if the token changes before the send, and the outbox's next attempt judges
2243
+ * again against whatever is current then.
2244
+ */
2245
+ replayIdentityVerdict(stamped: null | string | undefined): ReplayIdentityVerdict;
2246
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
2247
+ clientIdentifier(): string;
2248
+ /**
2249
+ * The highest custom-mutator watermark the server has echoed for this client
2250
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
2251
+ * its `clientSeq` generator from this so a reload never reissues a sequence
2252
+ * the server has already applied (which it would swallow as a replay, silently
2253
+ * dropping the write).
2254
+ */
2255
+ confirmedMutationWatermark(shardKey?: string): number;
2256
+ /**
2257
+ * Push a custom mutator to its authoritative server impl over the watermark
2258
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
2259
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
2260
+ * client's `__client_watermark`.
2261
+ *
2262
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
2263
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
2264
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
2265
+ * A `false` verdict tells the caller to reissue above the now-known watermark
2266
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
2267
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
2268
+ *
2269
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
2270
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
2271
+ */
2272
+ callMutator(functionPath: string, args: Record<string, unknown>, options?: {
2273
+ clientSeq?: number;
2274
+ shardKey?: string;
2275
+ }): Promise<{
2276
+ applied: boolean;
2277
+ result: unknown;
2278
+ }>;
2279
+ /**
2280
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
2281
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
2282
+ * the current value.
2283
+ */
2284
+ onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
2285
+ /**
2286
+ * Subscribe to a user switch or sign-out: fired after {@link setAuthToken}
2287
+ * retires the previous identity's session, i.e. every live subscription has
2288
+ * just been blanked to `undefined` and its socket closed. Not fired when a
2289
+ * bearer identity is first established from signed-out (nothing is
2290
+ * retired), nor when a subject is attached to the same credential, nor on
2291
+ * a cookie session's first answer after page load.
2292
+ *
2293
+ * A cookie session fires it on every change the server reports — sign-out,
2294
+ * a sign-in after a known sign-out, a different user — whether the answer
2295
+ * came from {@link getCurrentUser} or from a socket's `identity` frame. Its
2296
+ * sign-out changes nothing the client can observe on its own; in a browser
2297
+ * the client also re-resolves whenever `@lunora/auth-ui` or the
2298
+ * `lunoraSessionSync()` better-auth plugin reports a session change.
2299
+ *
2300
+ * For caches layered on top of the client. A subscriber only hears the
2301
+ * blank for queries it still subscribes to, so a cache that keeps values for
2302
+ * unmounted queries must drop them here, or the next user can read the
2303
+ * previous user's rows from it.
2304
+ */
2305
+ onIdentityChange(listener: () => void): Unsubscribe;
2306
+ /**
2307
+ * How many identities this client has retired since it was constructed —
2308
+ * the number of times {@link onIdentityChange} has fired. Already moved when
2309
+ * those listeners run.
2310
+ *
2311
+ * A value rendered on the server (a `Preloaded` token) was read for whoever
2312
+ * was signed in when the page loaded, so it is only safe to show while this
2313
+ * is `0`: once a sign-out or user switch has retired that identity, a
2314
+ * component mounting later must not seed the previous user's rows.
2315
+ */
2316
+ identityEpoch(): number;
2317
+ /**
2318
+ * Fetch the currently authenticated user from better-auth's `get-session`
2319
+ * endpoint, returning the `user` record or `null` when signed out. Sends
2320
+ * the stored bearer token (if any) and `credentials: "include"` so a
2321
+ * cookie-session is also honoured.
2322
+ *
2323
+ * `null` means the **server answered** that there is no session — an empty
2324
+ * body, no `user` field, or a non-OK status such as 401. A network or parse
2325
+ * failure **rejects** instead, because "the endpoint was unreachable" is not
2326
+ * the same answer as "you are signed out": collapsing the two made an
2327
+ * offline reload with a valid stored token read as a sign-out in every
2328
+ * adapter's auth gate. Callers that cannot act on the difference can still
2329
+ * `.catch(() => null)`; `@lunora/client/auth`'s identity store maps the
2330
+ * rejection to the `"unreachable"` status instead.
2331
+ *
2332
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
2333
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
2334
+ *
2335
+ * A resolved user also ESTABLISHES the identity subject for the credential
2336
+ * that resolved it ({@link setAuthToken}'s second argument). This is the one
2337
+ * call every adapter's identity store already makes, and the only place that
2338
+ * knows the answer — leaving it to each adapter is what left the sticky-subject
2339
+ * contract unreached in every shipped one, so a routine JWT refresh read as a
2340
+ * user switch and discarded the user's own queued writes and read cache.
2341
+ *
2342
+ * Under a cookie session (no token held) the answer is adopted whatever it
2343
+ * is, "no session" included, and a change from the identity already known
2344
+ * retires the previous session — see {@link onIdentityChange}.
2345
+ */
2346
+ getCurrentUser(): Promise<User | null>;
2347
+ /**
2348
+ * Replace the token appended to WS upgrade URLs as `?token=…` and close
2349
+ * every open shard socket so the reconnect picks up the new value. Call
2350
+ * this whenever the user's WS credential changes (rotating the admin token
2351
+ * in the studio, switching workspaces, etc.). Accepts a static string or a
2352
+ * {@link WsTokenProvider} resolved fresh at every (re)connect — the channel
2353
+ * for short-lived credentials like the minted ephemeral admin sub-token.
2354
+ * Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
2355
+ */
2356
+ setWsToken(token: string | undefined | WsTokenProvider): void;
2357
+ /**
2358
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
2359
+ * envelope for a shard's socket, overriding the client-wide
2360
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
2361
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
2362
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
2363
+ * presence row is removed the instant the socket drops, with no TTL lag.
2364
+ *
2365
+ * Stored per shard and replayed on every (re)connect. When a socket for the
2366
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
2367
+ * server sees the new context without waiting for a reconnect.
2368
+ *
2369
+ * Not available on a `crossTabSync` FOLLOWER tab — the context rides the
2370
+ * `connect` envelope of a socket a follower does not own, so it would be
2371
+ * stored and never sent. Throws `NOT_IMPLEMENTED` there.
2372
+ */
2373
+ setConnectionContext(context: Record<string, unknown> | undefined, options?: {
2374
+ shardKey?: string;
2375
+ }): void;
2376
+ /**
2377
+ * Refcounted variant of {@link setConnectionContext}: register a connection
2378
+ * `context` for a shard and get back a release function. Unlike the imperative
2379
+ * setter, the context is only cleared once the *last* acquired holder releases
2380
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
2381
+ * shard no longer clobber each other's context when one of them unmounts. The
2382
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
2383
+ * the top holder falls back to the previous one rather than clearing.
2384
+ *
2385
+ * With a single holder the behaviour is identical to a
2386
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
2387
+ * Releasing more than once is a no-op (the holder is matched by reference, so
2388
+ * a double release can't drop a different holder).
2389
+ */
2390
+ acquireConnectionContext(context: Record<string, unknown>, options?: {
2391
+ shardKey?: string;
2392
+ }): Unsubscribe;
2393
+ /**
2394
+ * Join a whisper `topic` and receive every ephemeral message other members
2395
+ * broadcast to it on the same shard (typing indicators, live cursors,
2396
+ * presence pings). Whispers never touch the server's durable state — there's
2397
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
2398
+ * is left on the server once its last local handler unsubscribes.
2399
+ *
2400
+ * `handler` receives the raw `data` and the sender's verified `from` user id
2401
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
2402
+ * (the default shard when omitted) — use the same shard you target with the
2403
+ * matching queries/mutations so members land on the same Durable Object.
2404
+ *
2405
+ * Security: a whisper topic is access-controlled only if the app declares an
2406
+ * `onWhisper` authorizer server-side (`@lunora/server`). Without one, the
2407
+ * topic's only boundary is the shard — any client that can open a socket to it
2408
+ * can join, read, and inject on any topic name. `from` is server-stamped and
2409
+ * unforgeable either way, but never trust a whisper's `data` as authorization,
2410
+ * and remember that even an authorized topic is transient awareness with no
2411
+ * durable trace: anything privileged belongs behind a query/mutation with RLS.
2412
+ *
2413
+ * A denied join is silent — whispers are never acked, so nothing distinguishes
2414
+ * "denied" from "nobody is whispering". Gate the UI on a query you can read a
2415
+ * verdict from, not on whether whispers arrive.
2416
+ *
2417
+ * Not available on a `crossTabSync` FOLLOWER tab — whisper frames are not
2418
+ * relayed over the cross-tab channel, so this throws `NOT_IMPLEMENTED`
2419
+ * there rather than registering a handler nothing can ever reach. See
2420
+ * {@link LunoraClientOptions.crossTabSync}.
2421
+ */
2422
+ whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
2423
+ shardKey?: string;
2424
+ }): Unsubscribe;
2425
+ /**
2426
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
2427
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
2428
+ * dropped when the shard socket isn't open (whispers are transient, never
2429
+ * queued), and the server silently drops it if the sender exceeds its
2430
+ * whisper rate budget. The sender never receives its own whisper. Omitting
2431
+ * `data` delivers JSON `null` to receivers (not `undefined`).
2432
+ *
2433
+ * That best-effort drop is for a socket that is momentarily down. A
2434
+ * `crossTabSync` FOLLOWER tab has no socket and never will (see
2435
+ * {@link LunoraClientOptions.crossTabSync}), so every whisper from it would
2436
+ * be dropped forever — it throws `NOT_IMPLEMENTED` instead.
2437
+ *
2438
+ * A send the app's `onWhisper` authorizer denies is dropped the same silent
2439
+ * way, for the same reason: there is no ack frame to report it on. See
2440
+ * {@link whisperSubscribe} for the security model.
2441
+ */
2442
+ whisper(topic: string, data?: unknown, options?: {
2443
+ shardKey?: string;
2444
+ }): void;
2445
+ /**
2446
+ * Subscribe to token-expiry events: invoked whenever the server drops a
2447
+ * shard socket because the connection's credential lapsed (close code
2448
+ * `4001`). The client already reconnects automatically (re-resolving
2449
+ * identity from the cookie/token in effect); use this to refresh a
2450
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
2451
+ * with a freshly minted one. Returns an unsubscribe function.
2452
+ */
2453
+ onTokenExpired(listener: () => void): Unsubscribe;
2454
+ /**
2455
+ * Current aggregate live-socket status across all shard connections. See
2456
+ * {@link ConnectionStatus}.
2457
+ */
2458
+ connectionStatus(): ConnectionStatus;
2459
+ /**
2460
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
2461
+ * immediately with the current status, then on every transition. Returns an
2462
+ * unsubscribe function.
2463
+ */
2464
+ onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
2465
+ /**
2466
+ * Number of offline writes waiting in the built-in queue to be sent — the
2467
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
2468
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
2469
+ * A `@lunora/db` app whose writes ride the unified outbox should read
2470
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
2471
+ */
2472
+ pendingCount(): number;
2473
+ /**
2474
+ * A point-in-time snapshot of everything the sync engine believes right now:
2475
+ * per-shard sockets and watermarks, every live query and shape subscription with
2476
+ * its cursor and ack state, and the offline-queue depth.
2477
+ *
2478
+ * This exists because the alternative is `console.log`. When an optimistic
2479
+ * overlay doesn't clear, the questions are always the same — *is the socket open?
2480
+ * what watermark has the server confirmed for this shard? has this shape been
2481
+ * poked since my write? is anything stuck in the queue?* — and none of them were
2482
+ * answerable from outside the client, so every adopter ends up instrumenting the
2483
+ * library by hand or building a bespoke policy layer around a symptom.
2484
+ *
2485
+ * Read it from a devtools console, log it next to a bug report, or render it in a
2486
+ * debug panel. Pull-only and allocation-cheap; nothing here is reactive, so poll
2487
+ * it or read it on demand.
2488
+ *
2489
+ * ```ts
2490
+ * const { shards, subscriptions } = client.debug();
2491
+ * // shards: [{ shardKey: "user-1", wsState: "open", confirmedMutationWatermark: 42, … }]
2492
+ * ```
2493
+ */
2494
+ debug(): ClientDebugSnapshot;
2495
+ /**
2496
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
2497
+ * with the current count, then whenever the queue depth changes (a write is
2498
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
2499
+ */
2500
+ onPendingChange(listener: (pending: number) => void): Unsubscribe;
2501
+ /**
2502
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
2503
+ * fires once per queued write that commits or is rejected — including a write
2504
+ * restored from durable storage after a reload, whose original `mutation()`
2505
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
2506
+ * evicts on overflow or discards on an identity change. This is the durable
2507
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
2508
+ * mutation that never queued still surfaces through the Promise `mutation()`
2509
+ * returns. The listener is NOT invoked on registration. Returns an
2510
+ * unsubscribe function. See {@link MutationSettledEvent}.
2511
+ */
2512
+ onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
2513
+ /**
2514
+ * The `WebSocket` implementation this client was constructed with (an
2515
+ * explicit `options.WebSocket`, or the ambient global on platforms that have
2516
+ * one) — `undefined` if neither is available. This is the seam a feature
2517
+ * that opens its OWN socket outside the client's multiplexed connection
2518
+ * (e.g. a voice-agent hook) should default to, instead of reaching for
2519
+ * `globalThis.WebSocket` directly: on React Native the client wraps this
2520
+ * constructor to inject the auth-headers factory's credential onto the
2521
+ * upgrade request (`createLunoraClient`'s `withAuthWebSocket`), which a raw
2522
+ * `new globalThis.WebSocket(url)` would silently bypass.
2523
+ */
2524
+ getWebSocketImpl(): typeof WebSocket | undefined;
2525
+ /**
2526
+ * Read the current value for a {@link ClientQueryRef}. Returns
2527
+ * `ref.defaultValue` when no value has been explicitly set.
2528
+ */
2529
+ getClientQuery<T>(ref: ClientQueryRef<T>): T;
2530
+ /**
2531
+ * Set a new value for `ref` and notify every subscriber. Pass `undefined`
2532
+ * to reset the slot to `ref.defaultValue`.
2533
+ */
2534
+ setClientQuery<T>(ref: ClientQueryRef<T>, value: T): void;
2535
+ /**
2536
+ * Subscribe to changes for `ref`. The callback is NOT invoked on
2537
+ * registration — call {@link getClientQuery} for the current value.
2538
+ * Returns an unsubscribe function.
2539
+ */
2540
+ subscribeClientQuery(ref: ClientQueryRef, callback: (value: unknown) => void): Unsubscribe;
2541
+ /**
2542
+ * Reset a {@link ClientQueryRef} to its default value, notifying every
2543
+ * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
2544
+ * removes the stored entry so a future {@link getClientQuery} returns
2545
+ * the default rather than an explicitly-set value.
2546
+ */
2547
+ resetClientQuery(ref: ClientQueryRef): void;
2548
+ /**
2549
+ * Capture a snapshot of the current live query value at call time and
2550
+ * produce a `() => boolean` precondition that compares it against the
2551
+ * value at replay time (on queue drain / reconnect).
2552
+ *
2553
+ * Delegates to {@link createSnapshotPrecondition} with this client bound —
2554
+ * no need to pass `client` explicitly. The comparison semantics (including
2555
+ * how an absent subscription is treated) live there, in one place.
2556
+ * @example
2557
+ * ```ts
2558
+ * client.mutation(api.todos.update, { id, text }, {
2559
+ * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
2560
+ * });
2561
+ * ```
2562
+ */
2563
+ snapshotPrecondition(functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string): () => boolean;
2564
+ /**
2565
+ * Resolves once the durable read cache has been loaded into memory. When
2566
+ * `hydrateOnStart` is not configured or no query cache adapter is active,
2567
+ * returns an already-resolved promise so callers can always await it
2568
+ * unconditionally.
2569
+ *
2570
+ * Framework adapters (React, Vue, etc.) use this to gate the first
2571
+ * (enabled) render of a live query behind hydration, so the user sees
2572
+ * cached data instead of an undefined flash before the socket round-trip.
2573
+ */
2574
+ whenReady(): Promise<void>;
2575
+ /**
2576
+ * Synchronously reports whether {@link whenReady} has already resolved (the
2577
+ * durable read cache is loaded, or none is configured). Framework adapters
2578
+ * read this to seed the hydration-gate state on the first render without
2579
+ * awaiting, then subscribe via {@link whenReady} for the pending case.
2580
+ */
2581
+ get isReady(): boolean;
2582
+ /**
2583
+ * Synchronously peek at a value the durable read cache loaded for the given
2584
+ * function path + args + shard key. Returns `undefined` when:
2585
+ *
2586
+ * - No query cache adapter is configured.
2587
+ * - Hydration hasn't completed yet (race — await {@link whenReady} first).
2588
+ * - The cached value's identity fingerprint doesn't match the current auth.
2589
+ *
2590
+ * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
2591
+ * the cached entry stays in `hydratedQueryCache` so the subscription created
2592
+ * later by {@link subscribe} consumes it normally.
2593
+ */
2594
+ peekHydratedQuery(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
2595
+ /**
2596
+ * Peek at the **current live value** of an active subscription, reporting
2597
+ * whether one exists at all rather than just its value. `present` is `false`
2598
+ * when no subscription is open for the given `(functionPath, args, shardKey)`;
2599
+ * `value` is the subscription's `lastValue`, which includes any optimistic
2600
+ * overlay.
2601
+ *
2602
+ * The two are separate because a caller like the snapshot precondition has to
2603
+ * tell "no subscription is active, so this read knows nothing" apart from
2604
+ * "the subscription is active and its value is `undefined`" — collapsing both
2605
+ * into a bare `undefined` return makes an unmounted component look like a
2606
+ * changed value, and drops the queued write.
2607
+ *
2608
+ * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
2609
+ * and is independent of active subscriptions), this reflects the current
2610
+ * in-memory state of an already-opened subscription.
2611
+ */
2612
+ peekActiveQuerySnapshot(functionPath: string, args: Record<string, unknown>, shardKey?: string): {
2613
+ present: boolean;
2614
+ value: unknown;
2615
+ };
2616
+ query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
2617
+ shardKey?: string;
2618
+ }): Promise<ReturnOf<F>>;
2619
+ /**
2620
+ * Batch several independent calls into ONE round trip (plan 088). Each call is
2621
+ * dispatched server-side exactly as an individual RPC — per-shard
2622
+ * authorization, `(identity, mutationId)` idempotency, and custom-mutator
2623
+ * watermark ordering are all preserved — and the worker splits the batch by
2624
+ * shard so calls to different shards fan out to their own DOs. Results are
2625
+ * demuxed back in input order; a failing call does NOT fail the batch (its
2626
+ * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
2627
+ * a single call). Args/results ride the value codec (bytes/bigint survive).
2628
+ *
2629
+ * No promise pipelining and no capability passing — a call's args cannot
2630
+ * reference another call's result (see plan 088 §fence; capabilities are
2631
+ * incompatible with DO hibernation).
2632
+ */
2633
+ batch(calls: ReadonlyArray<{
2634
+ args?: Record<string, unknown>;
2635
+ fn: FunctionReference;
2636
+ shardKey?: string;
2637
+ }>): Promise<BatchSlot[]>;
2638
+ /**
2639
+ * Invoke a mutation. Errors propagate as rejections.
2640
+ *
2641
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
2642
+ * only when the targeted shard's socket was open at least once already
2643
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
2644
+ * Mutations issued before the very first WS connect to a shard fail fast.
2645
+ * Opt into queueing-before-first-connect via
2646
+ * `OfflineQueueOptions.queueBeforeFirstConnect`.
2647
+ *
2648
+ * **Return-value caveat — the queued paths do not carry the server's result.**
2649
+ * The declared `Promise<ReturnOf<F>>` only holds when the write goes straight
2650
+ * to the server. Once a write is queued:
2651
+ *
2652
+ * - with a durable `outbox` configured, this resolves **immediately with
2653
+ * `undefined`** (typed as `ReturnOf<F>`) the moment the write is handed to
2654
+ * the outbox — the replay happens later, out of band, with no awaiter;
2655
+ * - with the built-in offline queue, it stays pending until the replay lands
2656
+ * and then resolves with the replayed call's value.
2657
+ *
2658
+ * So `const id = await client.mutation(api.todos.create, …)` is `undefined`
2659
+ * for every write issued while offline under an outbox. Generate ids
2660
+ * client-side (or read them back from a subscription) rather than depending
2661
+ * on a mutation's return value in an offline-capable app —
2662
+ * {@link LunoraClient.importRows} documents the same caveat for its counts.
2663
+ */
2664
+ mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
2665
+ /**
2666
+ * Whether a {@link mutation} on `shardKey` would be queued (offline queue or
2667
+ * durable outbox) rather than fail when the network is down. `false` before
2668
+ * the shard's first connect (unless `queueBeforeFirstConnect` is set) and on
2669
+ * a client with no WebSocket. A caller that wants to hold a write until the
2670
+ * network returns must do so itself when this is `false`.
2671
+ */
2672
+ canQueueOffline(shardKey?: string): boolean;
2673
+ action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: ActionCallOptions): Promise<ReturnOf<F>>;
2674
+ /**
2675
+ * Bulk-import `rows` through a mutation that accepts a batch, chunked so a large
2676
+ * dataset lands in a bounded number of round-trips.
2677
+ *
2678
+ * **Queued chunks:** `imported` counts only rows the server committed. A chunk a
2679
+ * durable outbox took instead (offline, or behind older queued writes) is counted
2680
+ * in `queued`; the outbox replays it later under the same key. The built-in
2681
+ * offline queue holds the call until each chunk commits, so its rows land in
2682
+ * `imported`. Report "migration complete" only when `queued` is `0`.
2683
+ *
2684
+ * This is the one-shot migration / seed path: "I have 20k rows client-side and a
2685
+ * server mutation that inserts many at once". Doing it by hand goes wrong in two
2686
+ * predictable ways — a serial per-row loop pays one round-trip *and* one watermark
2687
+ * wait per row (a 200-row import becomes 200 sequential hops), while a single
2688
+ * giant call blows the DO's batch limit. So: chunk, send sequentially, and give
2689
+ * each chunk a stable idempotency key derived from `importId` + its index, so a
2690
+ * resumed or retried import doesn't double-insert the chunks that already landed
2691
+ * (for an anonymous caller only while the `clientId` is the same; see `importId`).
2692
+ *
2693
+ * The server mutation is yours (Lunora can't guess the table or the row shape);
2694
+ * back it with `ctx.db.insertMany(...)`, or `insertManyUnsafe(...)` for data you
2695
+ * vouch for. `chunkSize` defaults to 500, matching the DO's default batch cap.
2696
+ *
2697
+ * ```ts
2698
+ * await client.importRows(api.migrate.importNodes, nodes, {
2699
+ * importId: `migrate-${userId}`,
2700
+ * onProgress: ({ done, total }) => setProgress(done / total),
2701
+ * shardKey: userId,
2702
+ * toArgs: (chunk) => ({ nodes: chunk }),
2703
+ * });
2704
+ * ```
2705
+ */
2706
+ importRows(function_: FunctionReference, rows: ReadonlyArray<unknown>, options?: {
2707
+ /** Rows per call. Defaults to 500 — the DO's default batch cap. */
2708
+ chunkSize?: number;
2709
+ /**
2710
+ * Stable id for this import run. Each chunk is sent under
2711
+ * `${importId}:${chunkIndex}` as its mutation id, so re-running an import
2712
+ * that uses the SAME `chunkSize` re-sends each chunk under its prior key
2713
+ * and the server dedupes it instead of inserting twice.
2714
+ *
2715
+ * CAVEAT — the key is POSITIONAL, not content-based: it pins on the chunk
2716
+ * INDEX, not on the rows inside it. Resume or retry with a DIFFERENT
2717
+ * `chunkSize` (or a changed row ordering) and index N now covers different
2718
+ * rows than the first run's index N; the server sees a duplicate key and
2719
+ * SILENTLY DROPS those rows. Keep `chunkSize` (and the row order) identical
2720
+ * across resumes of the same `importId`. Omit `importId` only for a
2721
+ * throwaway import where double-insertion is acceptable.
2722
+ *
2723
+ * CAVEAT — anonymous callers: the server scopes the key to the signed-in
2724
+ * user, or to the client's `clientId` when nobody is signed in. A
2725
+ * `LunoraClient` mints a fresh `clientId` on every construction, so an
2726
+ * anonymous import resumed after a reload is not deduped and inserts the
2727
+ * landed chunks again. Pass a persisted `clientId` to the constructor to
2728
+ * resume anonymously, or run the import signed in.
2729
+ */
2730
+ importId?: string;
2731
+ /**
2732
+ * Called after each chunk is accepted — for a progress bar. `done` counts
2733
+ * committed and queued rows alike; the result separates them.
2734
+ */
2735
+ onProgress?: (progress: {
2736
+ done: number;
2737
+ total: number;
2738
+ }) => void;
2739
+ /** Routes every chunk to one shard's DO. */
2740
+ shardKey?: string;
2741
+ /** Build the mutation args for one chunk. Defaults to `{ rows: chunk }`. */
2742
+ toArgs?: (chunk: ReadonlyArray<unknown>) => Record<string, unknown>;
2743
+ }): Promise<{
2744
+ chunks: number;
2745
+ imported: number;
2746
+ queued: number;
2747
+ }>;
2748
+ /**
2749
+ * Read the cross-shard request distribution for a `.shardBy(...)` table —
2750
+ * the feed the studio's `hot_shard` advisor lint consumes. Hits the
2751
+ * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
2752
+ * cheap per-shard `getMetrics` read out across every live shard and returns
2753
+ * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
2754
+ * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
2755
+ * and `adminToken`, and this client's auth token to match; defaults any
2756
+ * absent field so an older worker yields an empty-but-valid shape.
2757
+ */
2758
+ shardTraffic(table: string): Promise<ShardTrafficResult>;
2759
+ /**
2760
+ * List the functions queued via `runAfter` / `runAt`, soonest-due last
2761
+ * (the worker returns them in storage order). Hits the admin-gated
2762
+ * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
2763
+ * `schedulerDO` namespace and `adminToken`, and this client's auth token
2764
+ * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
2765
+ */
2766
+ listScheduledJobs(): Promise<ScheduleRecord[]>;
2767
+ /**
2768
+ * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
2769
+ * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
2770
+ * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
2771
+ * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
2772
+ * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
2773
+ * namespace + `adminToken` on the worker and a matching auth token here).
2774
+ * Defaults any absent field so an older worker still yields a valid shape.
2775
+ */
2776
+ schedulerStatus(): Promise<SchedulerStatus>;
2777
+ /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
2778
+ cancelScheduledJob(id: string): Promise<{
2779
+ cancelled: boolean;
2780
+ }>;
2781
+ /**
2782
+ * List the dead-letter jobs: schedules that exhausted their retry budget
2783
+ * and were parked instead of dropped. These never appear in
2784
+ * {@link listScheduledJobs} (their live header is gone), so this is the only
2785
+ * way the studio surfaces a permanently-failed job. Hits the admin-gated
2786
+ * `GET /_lunora/admin/scheduled/dead`; same preconditions as
2787
+ * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
2788
+ */
2789
+ listDeadJobs(): Promise<ScheduleRecord[]>;
2790
+ /**
2791
+ * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
2792
+ * retry budget and fires on the next drain. Returns whether a parked record
2793
+ * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
2794
+ */
2795
+ retryDeadJob(id: string): Promise<{
2796
+ retried: boolean;
2797
+ }>;
2798
+ /**
2799
+ * Permanently drop a dead-letter job by id (the operator has decided not to
2800
+ * recover it). Returns whether a parked record was removed. Hits the
2801
+ * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
2802
+ */
2803
+ removeDeadJob(id: string): Promise<{
2804
+ removed: boolean;
2805
+ }>;
2806
+ /**
2807
+ * List a workflow's instances via the admin Workflows proxy
2808
+ * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
2809
+ * the `Workflow` binding can't expose. Requires the worker to be built with a
2810
+ * `workflowsClient` (Cloudflare account id + API token). When one isn't
2811
+ * configured this does NOT reject: the proxy returns a `200 { configured:
2812
+ * false }` sentinel, so the result resolves with `configured === false` and an
2813
+ * empty `instances` list — callers should branch on that flag rather than
2814
+ * try/catch. (The instance-detail / status endpoints still reject with 501.)
2815
+ * `name` is the deployed workflow name.
2816
+ */
2817
+ listWorkflowInstances(options: {
2818
+ name: string;
2819
+ page?: number;
2820
+ perPage?: number;
2821
+ status?: WorkflowInstanceStatus;
2822
+ }): Promise<WorkflowInstancePage>;
2823
+ /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
2824
+ getWorkflowInstance(options: {
2825
+ id: string;
2826
+ name: string;
2827
+ }): Promise<WorkflowInstanceDetail>;
2828
+ /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
2829
+ setWorkflowInstanceStatus(options: {
2830
+ action: WorkflowInstanceAction;
2831
+ id: string;
2832
+ name: string;
2833
+ }): Promise<{
2834
+ status: WorkflowInstanceStatus;
2835
+ }>;
2836
+ /**
2837
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
2838
+ * WebSocket. `onJobs` fires with the full list on connect and on every
2839
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
2840
+ * configured backoff. Requires `wsToken` to be set to an admin credential
2841
+ * (the browser can't send an `Authorization` header on a WS) — the master
2842
+ * token, or preferably a {@link WsTokenProvider} minting the ephemeral
2843
+ * sub-token so the master credential stays out of the URL. Returns an
2844
+ * unsubscribe function that closes the socket and stops reconnecting.
2845
+ */
2846
+ subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
2847
+ /**
2848
+ * List the registered public functions (queries / mutations / actions) with
2849
+ * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
2850
+ * the worker must be built with a `functions` registry and `adminToken`, and
2851
+ * this client's auth token must match. Powers `@lunora/studio`'s function
2852
+ * runner auto-discovery.
2853
+ */
2854
+ listFunctions(): Promise<FunctionDescriptor[]>;
2855
+ /**
2856
+ * List the code-defined cron triggers (the `cronJobs()` map injected on the
2857
+ * worker), each flattened to its firing `cron` expression. Hits the
2858
+ * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
2859
+ * built with a `cronJobs` map and `adminToken`, and this client's auth token
2860
+ * must match. These are static (Cloudflare exposes no runtime cron
2861
+ * introspection), so the studio renders them read-only alongside the dynamic
2862
+ * scheduler jobs.
2863
+ */
2864
+ getCronJobs(): Promise<CronJobInfo[]>;
2865
+ /**
2866
+ * Manually fire one code-defined cron job by name — the same dispatch the
2867
+ * scheduled trigger runs (dispatch the function, or start the durable
2868
+ * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
2869
+ * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
2870
+ * and this client's auth token must match. Resolves when the job has run (a
2871
+ * function job's shard response is 2xx, or the workflow instance was created)
2872
+ * and rejects with the dispatch error otherwise.
2873
+ */
2874
+ runCronJob(name: string): Promise<{
2875
+ name: string;
2876
+ ran: boolean;
2877
+ }>;
2878
+ /**
2879
+ * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
2880
+ * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
2881
+ * `openApiSpec` and `adminToken`, and this client's auth token must match.
2882
+ * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
2883
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
2884
+ * document (no `paths`), so callers can render a "not configured" state.
2885
+ */
2886
+ fetchOpenApi(): Promise<Record<string, unknown>>;
2887
+ /**
2888
+ * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
2889
+ * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
2890
+ * `openRpcSpec` and `adminToken`, and this client's auth token must match.
2891
+ * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
2892
+ * `POST /_lunora/rpc` transport); it documents the RPC functions only.
2893
+ * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
2894
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
2895
+ * document (no `methods`), so callers can render a "not configured" state.
2896
+ */
2897
+ fetchOpenRpc(): Promise<Record<string, unknown>>;
2898
+ /**
2899
+ * List objects in the storage bucket, optionally under a `prefix` and from a
2900
+ * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
2901
+ * endpoint — the worker must be built with a `storageList` function and
2902
+ * `adminToken`, and this client's auth token must match. Powers
2903
+ * `@lunora/studio`'s file browser.
2904
+ */
2905
+ listStorageObjects(options?: {
2906
+ bucket?: string;
2907
+ cursor?: string;
2908
+ limit?: number;
2909
+ prefix?: string;
2910
+ }): Promise<StorageListPage>;
2911
+ /**
2912
+ * Delete one object from the storage bucket by key. Hits the admin-gated
2913
+ * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
2914
+ * with a `storageDelete` function and `adminToken`. Powers the studio file
2915
+ * browser's per-row delete; resolves `{ deleted, key }`.
2916
+ *
2917
+ * An absent `deleted` field reads as `false`, matching every sibling admin
2918
+ * verb (`runCronJob`'s `ran`, …): the studio renders this value as the row's
2919
+ * outcome, so defaulting a missing field to success would report a delete
2920
+ * that a mismatched/older worker never performed.
2921
+ */
2922
+ deleteStorageObject(key: string, options?: {
2923
+ bucket?: string;
2924
+ }): Promise<{
2925
+ deleted: boolean;
2926
+ key: string;
2927
+ }>;
2928
+ /**
2929
+ * List the storage bucket names the worker exposes, for the studio file
2930
+ * browser's bucket picker. Hits the admin-gated
2931
+ * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
2932
+ * array when the worker configures no `storageBuckets`, i.e. single-bucket).
2933
+ */
2934
+ listStorageBuckets(): Promise<string[]>;
2935
+ /**
2936
+ * Upload one object to the storage bucket. Hits the admin-gated
2937
+ * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
2938
+ * optional `contentType` header — the worker must be built with a
2939
+ * `storageUpload` function and `adminToken`. Powers the studio file
2940
+ * browser's upload control; resolves `{ etag?, key }`.
2941
+ */
2942
+ uploadStorageObject(options: {
2943
+ body: ArrayBuffer | Blob;
2944
+ bucket?: string;
2945
+ contentType?: string;
2946
+ key: string;
2947
+ }): Promise<{
2948
+ etag?: string;
2949
+ key: string;
2950
+ }>;
2951
+ /**
2952
+ * Build a (signed or public) URL for one object. Hits the admin-gated
2953
+ * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
2954
+ * with a `storageSignedUrl` function and `adminToken`. Powers the studio
2955
+ * file browser's copy-URL action; resolves the URL string.
2956
+ *
2957
+ * `options.expiresInSeconds` requests a share-link lifetime, which is
2958
+ * validated/clamped server-side. The options object mirrors the worker's
2959
+ * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
2960
+ * as future fields there).
2961
+ */
2962
+ signedStorageUrl(key: string, options?: {
2963
+ bucket?: string;
2964
+ expiresInSeconds?: number;
2965
+ }): Promise<string>;
2966
+ /**
2967
+ * List the `.global()` (D1-backed) tables with their row counts. Hits the
2968
+ * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
2969
+ * be built with a `globalIntrospector` and `adminToken`. Powers the data
2970
+ * browser's global mode.
2971
+ */
2972
+ listGlobalTables(): Promise<GlobalTableInfo[]>;
2973
+ /**
2974
+ * Read a page of rows from one `.global()` table. `filters` AND-narrows the
2975
+ * page to rows matching each `column = value` eq constraint — the drill-down a
2976
+ * facet-value click applies; the array is wire-encoded, JSON-encoded into the
2977
+ * `filters` query param, and the values are bound server-side.
2978
+ *
2979
+ * The response is `decodeWire`d. The worker encodes it (`readGlobalTablePage`
2980
+ * in `@lunora/d1`) because JSON cannot carry a `v.bigint()` column at all and
2981
+ * silently flattens a `v.bytes()` one to `{}` — so without the decode here the
2982
+ * grid renders the raw 3-element tagged array instead of the value. The shard
2983
+ * browser's twin already pairs the same way through `rpc`; this is the global
2984
+ * half of that symmetry.
2985
+ */
2986
+ readGlobalTablePage(options: {
2987
+ filters?: GlobalFilterClause[];
2988
+ limit?: number;
2989
+ offset?: number;
2990
+ table: string;
2991
+ }): Promise<GlobalTablePage>;
2992
+ /**
2993
+ * Summarise the distinct values of one column in a `.global()` table over the
2994
+ * active view (the same eq `filters` the browser is previewing) — the global
2995
+ * twin of the shard browser's facet. Hits the admin-gated
2996
+ * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
2997
+ * server-side. Powers the global data browser's facet sidebar.
2998
+ *
2999
+ * Wire-encoded/decoded on both legs for the same reason
3000
+ * {@link LunoraClient.readGlobalTablePage} is: a facet over a BLOB column
3001
+ * returns bytes, which `Response.json` flattens to `{}` — and since a facet
3002
+ * value is exactly what a click sends back as a `filters` clause, that is a
3003
+ * broken drill-down rather than a display glitch.
3004
+ */
3005
+ facetGlobalColumn(options: {
3006
+ column: string;
3007
+ filters?: GlobalFilterClause[];
3008
+ limit?: number;
3009
+ table: string;
3010
+ }): Promise<GlobalFacetResult>;
3011
+ /**
3012
+ * List the schema's Vectorize indexes with their declared shape (table,
3013
+ * field, dimensions, metric, metadata) and live stats (vector count,
3014
+ * processing watermark) when the binding is reachable. Hits the admin-gated
3015
+ * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
3016
+ * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
3017
+ * browser. Vectorize can't enumerate indexes at runtime, so this list comes
3018
+ * from the generated `LUNORA_VECTOR_INDEXES` registry.
3019
+ */
3020
+ listVectorIndexes(): Promise<VectorIndexSummary[]>;
3021
+ /**
3022
+ * Run a nearest-neighbour similarity query against one vector index: the
3023
+ * worker embeds `text` via the index's embedder and returns the top matches.
3024
+ * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
3025
+ * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
3026
+ * wired (the index lists read-only).
3027
+ */
3028
+ queryVectorIndex(options: {
3029
+ name: string;
3030
+ text: string;
3031
+ topK?: number;
3032
+ }): Promise<VectorQueryMatch[]>;
3033
+ /**
3034
+ * Read one keyset-paginated page of the durable `ctx.log` archive that
3035
+ * `pipelineLogSink` writes to R2. Server-side only — the worker holds the R2
3036
+ * SQL credentials and runs the reader; the browser only sees the decoded
3037
+ * `{ rows, nextCursor }`. Pass the previous page's `nextCursor` as
3038
+ * `query.cursor` to page. Admin-gated. When the operator hasn't wired the
3039
+ * archive, `adminFetch` throws a `LunoraClientError` with `.code ===
3040
+ * "LOG_ARCHIVE_NOT_CONFIGURED"`, so a caller can render a "not configured"
3041
+ * state rather than an error.
3042
+ */
3043
+ queryLogArchive(query?: PipelineLogQuery): Promise<PipelineLogPage>;
3044
+ /**
3045
+ * List the worker's registered Workers KV namespaces (binding names). Hits
3046
+ * the admin-gated `GET /_lunora/admin/kv/namespaces` endpoint — the worker
3047
+ * must be built with a `kvIntrospector` and `adminToken`. Powers the
3048
+ * studio's KV browser.
3049
+ */
3050
+ listKvNamespaces(): Promise<KvNamespaceSummary[]>;
3051
+ /**
3052
+ * List keys in a KV namespace, optionally filtered by `prefix` and
3053
+ * paginated via `cursor`. Hits the admin-gated
3054
+ * `GET /_lunora/admin/kv/keys` endpoint.
3055
+ */
3056
+ listKvKeys(options: {
3057
+ cursor?: string;
3058
+ limit?: number;
3059
+ namespace: string;
3060
+ prefix?: string;
3061
+ }): Promise<KvKeyListResult>;
3062
+ /**
3063
+ * Read a KV value (as text) and its metadata. Hits the admin-gated
3064
+ * `GET /_lunora/admin/kv/value` endpoint. Returns `{ value: null, metadata: null }`
3065
+ * when the key is absent.
3066
+ */
3067
+ getKvValue(options: {
3068
+ key: string;
3069
+ namespace: string;
3070
+ }): Promise<KvValueResult>;
3071
+ /**
3072
+ * Write a string value to a KV namespace. Accepts an absolute `expiration`
3073
+ * (Unix seconds) or a relative `expirationTtl`, plus optional `metadata` —
3074
+ * re-send the loaded values on edit so a save preserves rather than clears
3075
+ * them. Hits the admin-gated `PUT /_lunora/admin/kv/value` endpoint.
3076
+ */
3077
+ putKvValue(options: {
3078
+ expiration?: number;
3079
+ expirationTtl?: number;
3080
+ key: string;
3081
+ metadata?: unknown;
3082
+ namespace: string;
3083
+ value: string;
3084
+ }): Promise<void>;
3085
+ /**
3086
+ * Delete a key from a KV namespace. No-op when the key is absent. Hits the
3087
+ * admin-gated `DELETE /_lunora/admin/kv/value` endpoint.
3088
+ */
3089
+ deleteKvKey(options: {
3090
+ key: string;
3091
+ namespace: string;
3092
+ }): Promise<void>;
3093
+ /**
3094
+ * List authenticated users, paged and optionally searched / filtered / sorted.
3095
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
3096
+ * must be built with an `authAdmin` and `adminToken`. Powers the studio's
3097
+ * users dashboard.
3098
+ */
3099
+ listAuthUsers(options?: {
3100
+ filterField?: string;
3101
+ filterValue?: string;
3102
+ limit?: number;
3103
+ offset?: number;
3104
+ search?: string;
3105
+ searchField?: string;
3106
+ sortBy?: string;
3107
+ sortDirection?: "asc" | "desc";
3108
+ }): Promise<AuthPage<AuthUser>>;
3109
+ /**
3110
+ * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
3111
+ * endpoint (requires the worker's `authAdmin` to implement `createUser`).
3112
+ * `data` carries any app-defined `user.additionalFields`.
3113
+ */
3114
+ createAuthUser(input: {
3115
+ data?: Record<string, unknown>;
3116
+ email: string;
3117
+ name: string;
3118
+ password?: string;
3119
+ role?: string | string[];
3120
+ }): Promise<AuthUser>;
3121
+ /** Set a user's role (string, or array joined comma-wise server-side). */
3122
+ setAuthUserRole(input: {
3123
+ role: string | string[];
3124
+ userId: string;
3125
+ }): Promise<AuthUser>;
3126
+ /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
3127
+ banAuthUser(input: {
3128
+ expiresInSeconds?: number;
3129
+ reason?: string;
3130
+ userId: string;
3131
+ }): Promise<AuthUser>;
3132
+ /** Lift a user's ban. */
3133
+ unbanAuthUser(input: {
3134
+ userId: string;
3135
+ }): Promise<AuthUser>;
3136
+ /** Set a user's password (admin override — no current-password challenge). */
3137
+ setAuthUserPassword(input: {
3138
+ newPassword: string;
3139
+ userId: string;
3140
+ }): Promise<void>;
3141
+ /** Permanently delete a user and revoke their sessions. */
3142
+ removeAuthUser(input: {
3143
+ userId: string;
3144
+ }): Promise<void>;
3145
+ /**
3146
+ * Mint an impersonation session for a user, returning its bearer `token`.
3147
+ * The caller is responsible for using the token (e.g. setting the session
3148
+ * cookie); the server performs no cookie round-trip.
3149
+ */
3150
+ impersonateAuthUser(input: {
3151
+ userId: string;
3152
+ }): Promise<AuthImpersonation>;
3153
+ /** Revoke a single session by its id (force sign-out of one device). */
3154
+ revokeAuthSession(input: {
3155
+ sessionId: string;
3156
+ }): Promise<void>;
3157
+ /** Revoke every session for a user (force sign-out everywhere). */
3158
+ revokeAuthUserSessions(input: {
3159
+ userId: string;
3160
+ }): Promise<void>;
3161
+ /**
3162
+ * Report which auth dashboard surfaces are available — derived server-side
3163
+ * from the enabled better-auth plugins. The studio renders only the panels
3164
+ * whose capability is `true`.
3165
+ */
3166
+ getAuthCapabilities(): Promise<AuthCapabilities>;
3167
+ /** Update a user's fields (name/email/app-defined `additionalFields`). */
3168
+ updateAuthUser(input: {
3169
+ data: Record<string, unknown>;
3170
+ userId: string;
3171
+ }): Promise<AuthUser>;
3172
+ /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
3173
+ listAuthAccounts(input: {
3174
+ userId: string;
3175
+ }): Promise<Record<string, unknown>[]>;
3176
+ /** Unlink a linked account from a user. */
3177
+ unlinkAuthAccount(input: {
3178
+ accountId: string;
3179
+ userId: string;
3180
+ }): Promise<void>;
3181
+ /** List a user's registered passkeys (requires the passkey plugin). */
3182
+ listAuthPasskeys(input: {
3183
+ userId: string;
3184
+ }): Promise<Record<string, unknown>[]>;
3185
+ /** Delete a passkey by id (requires the passkey plugin). */
3186
+ deleteAuthPasskey(input: {
3187
+ passkeyId: string;
3188
+ }): Promise<void>;
3189
+ /** Disable two-factor auth for a user (requires the two-factor plugin). */
3190
+ disableAuthTwoFactor(input: {
3191
+ userId: string;
3192
+ }): Promise<void>;
3193
+ /** List organizations, paged (requires the organization plugin). */
3194
+ listAuthOrganizations(options?: {
3195
+ limit?: number;
3196
+ offset?: number;
3197
+ }): Promise<AuthPage<Record<string, unknown>>>;
3198
+ /** List the members of an organization (requires the organization plugin). */
3199
+ listAuthOrgMembers(input: {
3200
+ limit?: number;
3201
+ offset?: number;
3202
+ organizationId: string;
3203
+ }): Promise<AuthPage<Record<string, unknown>>>;
3204
+ /** List an organization's pending invitations (requires the organization plugin). */
3205
+ listAuthOrgInvitations(input: {
3206
+ limit?: number;
3207
+ offset?: number;
3208
+ organizationId: string;
3209
+ }): Promise<AuthPage<Record<string, unknown>>>;
3210
+ /**
3211
+ * List sign-up invitations, newest first (requires the `inviteOnly` plugin).
3212
+ * Unfiltered: a row is pending when `acceptedAt` is null and `expiresAt` is in
3213
+ * the future, and the caller labels it — filtering server-side after the page
3214
+ * would let page 1 come back empty while pending rows sat on page 2.
3215
+ */
3216
+ listAuthSignUpInvitations(options?: {
3217
+ limit?: number;
3218
+ offset?: number;
3219
+ }): Promise<AuthPage<Record<string, unknown>>>;
3220
+ /** Invite an address to sign up, or refresh an existing invitation for it. */
3221
+ createAuthSignUpInvitation(input: {
3222
+ email: string;
3223
+ expiresInSeconds?: number;
3224
+ invitedBy?: string;
3225
+ }): Promise<Record<string, unknown>>;
3226
+ /** Withdraw a sign-up invitation. Not retroactive — an account already created keeps existing. */
3227
+ revokeAuthSignUpInvitation(input: {
3228
+ email: string;
3229
+ }): Promise<void>;
3230
+ /** Remove a member from an organization. */
3231
+ removeAuthOrgMember(input: {
3232
+ memberId: string;
3233
+ }): Promise<void>;
3234
+ /** Cancel a pending organization invitation. */
3235
+ cancelAuthOrgInvitation(input: {
3236
+ invitationId: string;
3237
+ }): Promise<void>;
3238
+ /**
3239
+ * Report the deployment's auth configuration — enabled plugins, sign-in
3240
+ * methods, user-settable create-user fields, organization sub-features
3241
+ * (teams / roles), and session / rate-limit policy. Drives the config panel
3242
+ * and the dynamic create-user form. Never carries a secret.
3243
+ */
3244
+ getAuthConfig(): Promise<AuthConfigInfo>;
3245
+ /** Create an organization; optionally seed an `owner` member for `ownerId`. */
3246
+ createAuthOrganization(input: {
3247
+ logo?: string;
3248
+ metadata?: Record<string, unknown>;
3249
+ name: string;
3250
+ ownerId?: string;
3251
+ slug?: string;
3252
+ }): Promise<Record<string, unknown>>;
3253
+ /** Update an organization's name/slug/logo/metadata. */
3254
+ updateAuthOrganization(input: {
3255
+ logo?: string;
3256
+ metadata?: Record<string, unknown>;
3257
+ name?: string;
3258
+ organizationId: string;
3259
+ slug?: string;
3260
+ }): Promise<Record<string, unknown>>;
3261
+ /** Delete an organization and cascade its members, invitations, teams, and custom roles. */
3262
+ deleteAuthOrganization(input: {
3263
+ organizationId: string;
3264
+ }): Promise<void>;
3265
+ /** Directly add an existing user to an organization (no invitation/acceptance). */
3266
+ addAuthOrgMember(input: {
3267
+ organizationId: string;
3268
+ role?: string;
3269
+ userId: string;
3270
+ }): Promise<Record<string, unknown>>;
3271
+ /** Create a pending email invitation to an organization. */
3272
+ inviteAuthOrgMember(input: {
3273
+ email: string;
3274
+ inviterId?: string;
3275
+ organizationId: string;
3276
+ role?: string;
3277
+ }): Promise<Record<string, unknown>>;
3278
+ /** Change a member's role. */
3279
+ setAuthOrgMemberRole(input: {
3280
+ memberId: string;
3281
+ role: string | string[];
3282
+ }): Promise<Record<string, unknown>>;
3283
+ /** List an organization's teams (requires the organization plugin with teams enabled). */
3284
+ listAuthOrgTeams(input: {
3285
+ limit?: number;
3286
+ offset?: number;
3287
+ organizationId: string;
3288
+ }): Promise<AuthPage<Record<string, unknown>>>;
3289
+ /** Create a team under an organization. */
3290
+ createAuthOrgTeam(input: {
3291
+ name: string;
3292
+ organizationId: string;
3293
+ }): Promise<Record<string, unknown>>;
3294
+ /** Rename a team. */
3295
+ updateAuthOrgTeam(input: {
3296
+ name: string;
3297
+ teamId: string;
3298
+ }): Promise<Record<string, unknown>>;
3299
+ /** Delete a team and its memberships. */
3300
+ removeAuthOrgTeam(input: {
3301
+ teamId: string;
3302
+ }): Promise<void>;
3303
+ /** List a team's members. */
3304
+ listAuthOrgTeamMembers(input: {
3305
+ limit?: number;
3306
+ offset?: number;
3307
+ teamId: string;
3308
+ }): Promise<AuthPage<Record<string, unknown>>>;
3309
+ /** Add a user to a team. */
3310
+ addAuthOrgTeamMember(input: {
3311
+ teamId: string;
3312
+ userId: string;
3313
+ }): Promise<Record<string, unknown>>;
3314
+ /** Remove a member from a team. */
3315
+ removeAuthOrgTeamMember(input: {
3316
+ teamMemberId: string;
3317
+ }): Promise<void>;
3318
+ /** List an organization's custom roles (requires the organization plugin with dynamic access control). */
3319
+ listAuthOrgRoles(input: {
3320
+ limit?: number;
3321
+ offset?: number;
3322
+ organizationId: string;
3323
+ }): Promise<AuthPage<Record<string, unknown>>>;
3324
+ /** Create a custom org role with a permission grant (a `resource -> actions[]` map). */
3325
+ createAuthOrgRole(input: {
3326
+ organizationId: string;
3327
+ permission: Record<string, string[]>;
3328
+ role: string;
3329
+ }): Promise<Record<string, unknown>>;
3330
+ /** Replace a custom org role's permission grant. */
3331
+ updateAuthOrgRole(input: {
3332
+ permission: Record<string, string[]>;
3333
+ roleId: string;
3334
+ }): Promise<Record<string, unknown>>;
3335
+ /** Delete a custom org role. */
3336
+ deleteAuthOrgRole(input: {
3337
+ roleId: string;
3338
+ }): Promise<void>;
3339
+ /** List auth sessions, paged and optionally filtered to one user. */
3340
+ listAuthSessions(options?: {
3341
+ limit?: number;
3342
+ offset?: number;
3343
+ userId?: string;
3344
+ }): Promise<AuthPage<AuthSession>>;
3345
+ /**
3346
+ * Subscribe to a live query. The callback fires with the current value (from
3347
+ * the durable read cache, when one is hydrated) and again on every server
3348
+ * frame; the returned function unsubscribes.
3349
+ *
3350
+ * Subscriptions are deduped by `(functionPath, args, shardKey)` — a second
3351
+ * `subscribe` for the same triple joins the existing registration and shares
3352
+ * its value, cursor and optimistic layers.
3353
+ *
3354
+ * Available on a `crossTabSync` FOLLOWER tab, unlike the other socket-backed
3355
+ * surfaces: registering here is exactly what lets the cross-tab relay deliver
3356
+ * the leader's broadcasts (see the note in the body). The caveat is that the
3357
+ * channel only carries the LEADER's own subscriptions outward, so a follower
3358
+ * sees this query's frames only while the leader holds it too — see
3359
+ * {@link LunoraClientOptions.crossTabSync}.
3360
+ */
3361
+ subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
3362
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3363
+ onError?: SubscriptionErrorCallback;
3364
+ shardKey?: string;
3365
+ }): Unsubscribe;
3366
+ /**
3367
+ * Subscribe to a declarative **shape** — server-side partial replication
3368
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
3369
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
3370
+ * validated `args` (never a `where` the client could forge), the server seeds
3371
+ * the current membership as an insert-poke and streams live membership diffs.
3372
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
3373
+ *
3374
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
3375
+ * (name, args): the server resolves them under the socket's verified identity,
3376
+ * so every call gets its own id + view. The returned function unsubscribes.
3377
+ *
3378
+ * Not available on a `crossTabSync` FOLLOWER tab: shape pokes are not part of
3379
+ * the leader→follower broadcast set, so a follower's shape could never
3380
+ * resolve. The returned handle is inert there, and `options.onError` is
3381
+ * invoked with `NOT_IMPLEMENTED` — see
3382
+ * {@link LunoraClientOptions.crossTabSync}. Reporting rather than throwing is
3383
+ * deliberate: `@lunora/db`'s shape-backed `createCollection` calls this from
3384
+ * its sync path, where a throw takes the collection out entirely, while
3385
+ * `onError` is the seam it already routes to `markReady()`.
3386
+ */
3387
+ subscribeShape(shape: {
3388
+ args?: Record<string, unknown>;
3389
+ name: string;
3390
+ }, callback: ShapeCallback, options?: {
3391
+ onCheckpoint?: (watermark: SyncWatermark) => void;
3392
+ onError?: SubscriptionErrorCallback;
3393
+ shardKey?: string;
3394
+ }): Unsubscribe;
3395
+ /**
3396
+ * Open a streaming query. The function reference must be a
3397
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
3398
+ * the type constraint catches accidental use of a query/mutation/action
3399
+ * reference at compile time. The returned iterable yields one element per
3400
+ * chunk frame the server pushes, terminating when the server sends
3401
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
3402
+ * rejection on the next `next()`.
3403
+ *
3404
+ * Streams ride the same WS as subscriptions and share the unsubscribe
3405
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
3406
+ * which the DO recognises as an abort signal for the in-flight iterator.
3407
+ *
3408
+ * Stream-start frames buffered while the socket is (re)connecting are
3409
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
3410
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
3411
+ * reconnect can't OOM the page.
3412
+ */
3413
+ stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
3414
+ durable?: boolean;
3415
+ maxBuffer?: number;
3416
+ shardKey?: string;
3417
+ }): StreamIterable<ReturnOf<F>>;
3418
+ /**
3419
+ * Open a typed **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`).
3420
+ * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
3421
+ * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
3422
+ * and parses the Server-Sent Events framing the route pump writes (`data:`
3423
+ * chunks, a final `event: complete`, an `event: error` on throw).
3424
+ *
3425
+ * The reference comes from the generated `httpStreams.*` registry, so the
3426
+ * yielded chunk type is the route handler's yielded type. Cancelling the
3427
+ * returned iterable (or aborting `options.signal`) aborts the fetch, which
3428
+ * the server handler observes via its `signal`. The client's bearer token
3429
+ * (when set) rides as an `authorization` header.
3430
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
3431
+ */
3432
+ httpStream<Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: {
3433
+ headers?: Record<string, string>;
3434
+ maxBuffer?: number;
3435
+ signal?: AbortSignal;
3436
+ }): StreamIterable<HttpStreamChunkOf<Ref>>;
3437
+ close(): void;
3438
+ /** Guard shared by every public entry point: a closed client accepts no further calls. */
3439
+ private assertOpen;
3440
+ /**
3441
+ * `true` when this tab is a cross-tab FOLLOWER of a live leader — i.e. it
3442
+ * will not open a socket of its own and another tab is known to hold one.
3443
+ *
3444
+ * Deliberately NOT just `!isLeader()`. Every `crossTabSync` client is a
3445
+ * non-leader for the first `leaderTimeout` of its life, while its
3446
+ * claim-leadership probe is outstanding; a lone tab self-promotes at the end
3447
+ * of that window and `onBecomeLeader` opens the sockets and replays every
3448
+ * registered subscription. That window is a legitimate, self-healing defer,
3449
+ * not a failure. A KNOWN leader on another tab is the state that never heals.
3450
+ */
3451
+ private followsAnotherTab;
3452
+ /**
3453
+ * Reject a call that needs a socket this tab will never have.
3454
+ *
3455
+ * The cross-tab protocol is one-directional: a leader broadcasts
3456
+ * `subscription-data` / `-error` / `-settled` / `connection-status` to
3457
+ * followers, and a follower has no frame with which to tell the leader what
3458
+ * it needs (see `cross-tab.ts`'s `WsFollowerMessage`, which is exactly
3459
+ * heartbeat / claim-leadership / yield-leadership). `subscribeShape` /
3460
+ * `whisper*` / `setConnectionContext` / `acquireConnectionContext` — none of
3461
+ * which the leader broadcasts at all — therefore never worked on a follower
3462
+ * under any circumstances: each returned a handle that looked live, fired no
3463
+ * callback, raised no error, and reported `connectionStatus() ===
3464
+ * "connected"` (mirrored from the leader).
3465
+ *
3466
+ * `subscribe` is deliberately NOT in that set. A follower's `subscribe`
3467
+ * registers the key the leader's broadcast is matched against, so it is the
3468
+ * mechanism the relay is built on rather than a surface that silently fails.
3469
+ * A follower sees a query only while the leader holds the same
3470
+ * `(fn, args, shardKey)` — that is the documented shape of the option, not a
3471
+ * defect.
3472
+ *
3473
+ * `subscribeShape` and `stream()` reach the same outcome by a different
3474
+ * route: they fail the handle they return rather than throwing at the call,
3475
+ * because both are driven from a sync/render path where a throw destroys the
3476
+ * caller instead of degrading it. See
3477
+ * {@link LunoraClientOptions.crossTabSync} for what the option does and does
3478
+ * not cover.
3479
+ */
3480
+ private assertLeaderOwnedSurface;
3481
+ /**
3482
+ * Clear every timer a {@link ShardConnection} can have armed.
3483
+ *
3484
+ * One function because both teardown paths must clear all three and a fourth
3485
+ * timer would otherwise have to be remembered in two places — which is how a
3486
+ * leak gets added rather than written.
3487
+ */
3488
+ private clearConnectionTimers;
3489
+ /**
3490
+ * Tear down one {@link ShardConnection}'s live state: clear its reconnect/
3491
+ * connect timers, stop its heartbeat, and close its socket (if any).
3492
+ * Shared by `close()` (terminal) and the cross-tab `onStopBeingLeader`
3493
+ * handler (demoted, but still alive) so a demoted leader can't leak a
3494
+ * pending `reconnectTimer` or an open socket's `heartbeatTimer` the way
3495
+ * an inline `conn.socket?.close()` — which skips both — used to.
3496
+ *
3497
+ * Settles this shard's in-flight streams first. The teardown clears
3498
+ * `conn.socket` BEFORE the real `close` event fires, so that event trips
3499
+ * `openManagedSocket`'s identity guard (`conn.socket !== socket`) and
3500
+ * returns — meaning `handleDisconnect`, the only other place that settles a
3501
+ * shard's streams, never runs for this connection again. `close()` already
3502
+ * failed and cleared `this.streams` before it gets here, so this is a no-op
3503
+ * on that path; the cross-tab demotion path is the one where a consumer's
3504
+ * `for await` used to block forever with no error and no completion.
3505
+ */
3506
+ private teardownConnection;
3507
+ /**
3508
+ * Build (but do not start) this client's `TabCoordinator`. Extracted out of
3509
+ * the constructor so `setAuthToken` can rebuild it on an identity change —
3510
+ * the default channel name embeds the identity fingerprint (see below), so
3511
+ * a new identity needs a new coordinator on a new channel. The callback
3512
+ * bodies are the drift-sensitive region (a hand-merged identity guard on
3513
+ * the shard message listener sits ahead of an extracted `lastFrameAt`
3514
+ * stamp elsewhere in this file) — moved verbatim, not reflowed.
3515
+ */
3516
+ private createTabCoordinator;
3517
+ /** The body of {@link batch}, optionally abortable (the polling fallback's timeout). */
3518
+ private sendBatch;
3519
+ /**
3520
+ * The body of {@link mutation}, also saying whether the write committed. `committed` is
3521
+ * `false` only when a durable outbox took the write, which resolves at once
3522
+ * with no server result.
3523
+ */
3524
+ private runMutation;
3525
+ /**
3526
+ * Unwind a direct write's optimistic layers after its RPC threw — or keep
3527
+ * them, when it threw only because a COMMITTED result did not decode: the
3528
+ * write happened, so its predicted value stays until the confirming frame
3529
+ * supersedes it.
3530
+ */
3531
+ private settleFailedDirectWrite;
3532
+ /**
3533
+ * Persist a mutation that can't go out on the wire right now (offline, or
3534
+ * mid-reconnect after a prior connect). The optimistic update has already
3535
+ * been applied by `mutation`; this only chooses the durable write path and
3536
+ * rolls the optimistic write back if persistence is rejected.
3537
+ *
3538
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
3539
+ * owns persistence + at-least-once replay, so we delegate and return
3540
+ * optimistically (confirmation rides the synced view). Otherwise the
3541
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
3542
+ */
3543
+ private enqueueOfflineMutation;
3544
+ /**
3545
+ * Is a write for this shard still sitting in the durable path, waiting to
3546
+ * replay? Drives the FIFO gate in {@link mutation}: a live write must never
3547
+ * overtake one that is queued (or held) ahead of it.
3548
+ *
3549
+ * Whichever durable path is wired answers: the built-in {@link OfflineQueue}
3550
+ * knows its entries' shard keys, while an {@link OutboxSink} reports only a
3551
+ * process-wide depth (the executor's pending count is not shard-scoped) —
3552
+ * over-inclusion there costs a write a trip through the outbox it could have
3553
+ * skipped, which is the same trip the writes ahead of it are taking anyway.
3554
+ * A sink that reports nothing keeps the previous behaviour.
3555
+ */
3556
+ private hasPendingWriteAhead;
3557
+ /**
3558
+ * Restore offline mutations persisted in a prior session and open a socket
3559
+ * for each shard they target so they flush once the WS reconnects. Failures
3560
+ * are swallowed — a broken durable store must not stop the client booting.
3561
+ */
3562
+ private hydratePersistedQueue;
3563
+ /**
3564
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
3565
+ * persisted queue is shared across a profile's tabs; without coordination
3566
+ * every tab would re-queue and replay the same writes (correct only because
3567
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
3568
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
3569
+ * closes another tab acquires the lock and takes over. Falls back to
3570
+ * unconditional hydration where Web Locks are unavailable (React Native, older
3571
+ * browsers, SSR) — single-context there, so no coordination is needed.
3572
+ */
3573
+ private hydrateAsOutboxLeader;
3574
+ /**
3575
+ * Load every cached query so a `subscribe()` for the key seeds its initial
3576
+ * value off disk.
3577
+ *
3578
+ * The load is asynchronous but every framework adapter subscribes
3579
+ * SYNCHRONOUSLY at mount, so the subscriptions that most want the cache
3580
+ * already exist by the time it lands. Those are seeded here and their entry
3581
+ * is dropped: an entry that stayed in {@link hydratedQueryCache} behind a
3582
+ * live subscription would be consumed by the NEXT subscribe of the same key
3583
+ * (a remount after navigating away) and replay the previous session's value
3584
+ * over whatever the socket had since delivered. A cache entry therefore
3585
+ * never outlives a live subscription for its key — it is either handed to
3586
+ * that subscription or discarded.
3587
+ *
3588
+ * Only keys with no live subscription are held for a later `subscribe()`;
3589
+ * the identity gate applies to both paths, so a signed-out cache never leaks
3590
+ * into a new session.
3591
+ */
3592
+ private hydrateQueryCache;
3593
+ /**
3594
+ * Hand a loaded read-cache entry to a subscription that was opened before
3595
+ * the load resolved — the same value, cursor and epoch {@link subscribe}
3596
+ * would have taken from {@link takeHydratedCache} had the load finished
3597
+ * first, so the cursor still rides the `subscribe` frame as `sinceSeq` (that
3598
+ * frame only goes out once the socket opens, well after this microtask).
3599
+ *
3600
+ * A no-op once the socket has delivered anything for this key: a live value
3601
+ * always beats the cache. Identity-gated exactly like `takeHydratedCache`.
3602
+ */
3603
+ private seedSubscriptionFromCache;
3604
+ /**
3605
+ * Move the durable read cache in or out of view as the CREDENTIAL changes —
3606
+ * which the identity fingerprint does not track: a sticky subject rides
3607
+ * across a token change (the account-switch shape), leaving the label
3608
+ * unmoved, so `setAuthToken`'s identity-change block never runs for it.
3609
+ * Revoke while that pairing is unchecked, and hand the values back once the
3610
+ * next session resolve confirms the credential really is that subject's.
3611
+ */
3612
+ private syncReadCacheToCredential;
3613
+ /**
3614
+ * A server frame owns this key now, so the read cache may neither take its
3615
+ * seeded value back ({@link revokeCacheSeededValues}) nor hold an entry for
3616
+ * a later `subscribe()` of the same key to replay a stale session over.
3617
+ */
3618
+ private dropCacheSeed;
3619
+ /**
3620
+ * Hand a cache-seeded entry back to {@link hydratedQueryCache} when its last
3621
+ * subscriber detaches, so the NEXT `subscribe()` of the same key can seed
3622
+ * from it again.
3623
+ *
3624
+ * Without this the hydrated cache was one-shot per key: {@link takeHydratedCache}
3625
+ * consumes the entry, the final unsubscribe drops the state that held its
3626
+ * value, and nothing re-seeds. Navigating away from a route and back while
3627
+ * offline therefore rendered `undefined` for the rest of the offline
3628
+ * session even though the durable store still held the rows. React hid it
3629
+ * behind TanStack's `gcTime`; every other adapter showed it immediately.
3630
+ *
3631
+ * Only a seed still listed in {@link cacheSeededQueries} moves — a server
3632
+ * frame calls {@link dropCacheSeed}, which clears both maps, so an entry
3633
+ * that is still here has not been superseded and is the freshest value this
3634
+ * client has for the key. That is the same map-to-map move
3635
+ * {@link revokeCacheSeededValues} makes, and it keeps the two maps disjoint:
3636
+ * an entry is either on display or waiting, never both.
3637
+ */
3638
+ private returnCacheSeed;
3639
+ /**
3640
+ * Take every value the durable read cache is currently displaying back off
3641
+ * screen, and return its entry to {@link hydratedQueryCache} so the identity
3642
+ * gate — not this call — decides whether it is ever shown again. A
3643
+ * same-credential refresh gets its offline-first value back the moment the
3644
+ * next session resolve re-confirms the subject; a genuine account switch
3645
+ * never does, and {@link clearQueryCacheForIdentityChange} wipes it.
3646
+ *
3647
+ * Only cache-seeded values: a server frame has been delivered under a socket
3648
+ * whose own identity is pinned and checked ({@link persistQueryValue}), and
3649
+ * dropping those would blank a live query on every token refresh.
3650
+ */
3651
+ private revokeCacheSeededValues;
3652
+ /**
3653
+ * Consume the hydrated read-cache entry for a key (if any), gated on
3654
+ * identity ({@link cachedQueryMatchesIdentity}). A mismatch yields
3655
+ * `undefined`, so a cache written under a different identity never leaks
3656
+ * into a new session.
3657
+ *
3658
+ * Only a MATCH is removed. The cache seeds a subscription's first value
3659
+ * once, so consuming a match is right — but destroying a mismatch is what
3660
+ * made a late-resolving identity unrecoverable: the subject typically lands
3661
+ * a `/get-session` after the first `subscribe()`, and by then the entry that
3662
+ * would have matched was gone. Left in place, {@link reseedFromHydratedCache}
3663
+ * can still hand it over when the identity settles.
3664
+ */
3665
+ private takeHydratedCache;
3666
+ /**
3667
+ * Hand every still-held read-cache entry to the subscription that is open on
3668
+ * its key, now that the identity has settled onto a resolved subject.
3669
+ *
3670
+ * `subscribe()` runs long before `/get-session` answers, so on a reload the
3671
+ * gate is asked its question with only a raw token in hand. When the token
3672
+ * itself matches, {@link cachedQueryMatchesIdentity} already says yes there
3673
+ * and then; when it has been refreshed since the value was cached, the only
3674
+ * honest answer at that moment is "unknown" — and this is where it becomes
3675
+ * knowable. {@link seedSubscriptionFromCache} is a no-op for any subscription
3676
+ * the socket has already fed, so a live value always wins.
3677
+ */
3678
+ private reseedFromHydratedCache;
3679
+ /**
3680
+ * Queue a coalesced read-cache write for a subscription's current value.
3681
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
3682
+ * once. No-op when the read cache is disabled or the value is undefined
3683
+ * (nothing to render offline).
3684
+ */
3685
+ private persistQueryValue;
3686
+ /** Drain {@link pendingCacheWrites} to the durable store. */
3687
+ private flushQueryCacheWrites;
3688
+ /** Derive the aggregate status from the per-shard socket states. */
3689
+ private computeStatus;
3690
+ /**
3691
+ * The CDC cursor this client's view of `shardKey` is at — the highest
3692
+ * `serverCursor` any live subscription on that shard has advanced to.
3693
+ *
3694
+ * This is the baseline a `.dropStalePatches()` table judges a write against,
3695
+ * and the "highest" is what makes it sound: a cursor the client has reached on
3696
+ * ANY subscription means the shard's changelog up to that point has been
3697
+ * delivered here, so anything later is by definition something this client had
3698
+ * not seen when it composed the write.
3699
+ *
3700
+ * `undefined` when no subscription on the shard carries a cursor yet — a
3701
+ * client that has only ever issued one-shot RPCs, or a server with CDC off.
3702
+ * That is reported honestly rather than defaulted to `0`: a `0` baseline would
3703
+ * claim the client had seen NOTHING, which makes every field look changed and
3704
+ * would have the shard discard every patch it sends.
3705
+ */
3706
+ private baselineCursorFor;
3707
+ /**
3708
+ * One polling-fallback pass for a shard: re-run every live query bound to it
3709
+ * over the batch-RPC endpoint and feed each result into the same frame-apply
3710
+ * path a server `data` frame takes.
3711
+ *
3712
+ * Reusing {@link LunoraClient.batch} and {@link LunoraClient.handleDataMessage}
3713
+ * rather than forking either is the whole point. The apply path is where
3714
+ * optimistic layers rebase, the durable read cache is seeded, and subscriber
3715
+ * callbacks fan out; a second implementation of that would drift, and it would
3716
+ * drift into exactly the bugs the live path has already had fixed.
3717
+ *
3718
+ * The result is re-encoded on the way in because `batch` hands back a decoded
3719
+ * value while the frame path expects the wire form. `encodeWire` is identity
3720
+ * for JSON-safe data and lossless for the rest (that is the codec's contract),
3721
+ * so the round trip costs an allocation and changes nothing.
3722
+ *
3723
+ * **No cursor rides this path.** A poll is a full snapshot, so the frames it
3724
+ * synthesizes carry no `cursor`/`epoch` and cannot advance a subscription's
3725
+ * resume watermark — which is correct: the watermark describes what the CDC
3726
+ * log has delivered, and this delivered none of it. When the socket comes
3727
+ * back, the resubscribe resumes from the last cursor the SOCKET saw, and the
3728
+ * server re-snapshots whatever it needs to.
3729
+ *
3730
+ * A slot that failed is fanned to the subscription's error callbacks rather
3731
+ * than being swallowed: the whole point of the fallback is that the app keeps
3732
+ * working, and a query that is now failing (a permission change, a bad arg)
3733
+ * has to be visible.
3734
+ *
3735
+ * Resolves `false` when the request never reached the origin (`fetch` itself
3736
+ * rejected), which is how the fallback tells a device with no network from a
3737
+ * network that only refuses the upgrade. Any answer, an error envelope
3738
+ * included, resolves `true`.
3739
+ *
3740
+ * Optimistic layers need the same care without a cursor. The snapshot is taken
3741
+ * after the request is sent, so every write whose RPC had resolved before that
3742
+ * moment is already in it. Those layers are dropped against the acknowledgement
3743
+ * mark sampled before the send. A write acknowledged after the send may be
3744
+ * missing from the snapshot, so its layer stays.
3745
+ */
3746
+ private pollSubscriptions;
3747
+ /**
3748
+ * Whether a request reaches the origin at all: an empty batch, whose answer
3749
+ * (even a refusal) is the proof. `false` only when `fetch` itself rejects.
3750
+ */
3751
+ private probeOrigin;
3752
+ /** Recompute the aggregate status and notify listeners if it changed. */
3753
+ private emitConnectionStatus;
3754
+ /**
3755
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
3756
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
3757
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
3758
+ * is unreachable — present only to satisfy the optional queue-id type.
3759
+ */
3760
+ private emitItemSettled;
3761
+ /**
3762
+ * Apply an optimistic update to the subscription that matches the mutation's
3763
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
3764
+ * invoke if the mutation later fails.
3765
+ *
3766
+ * The registry is already indexed by exactly this triple via
3767
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
3768
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
3769
+ *
3770
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
3771
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
3772
+ * a shardKey correctly matches a subscription registered without one regardless
3773
+ * of whether the caller passed `undefined` or omitted the field.
3774
+ */
3775
+ private applyOptimisticUpdates;
3776
+ /**
3777
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
3778
+ * to the live subscription registry. Each `setQuery` registers a constant
3779
+ * optimistic LAYER on its target subscription (via the same engine the
3780
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
3781
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
3782
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
3783
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
3784
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
3785
+ * mutation or leave a partial patch live.
3786
+ */
3787
+ private applyOptimisticUpdate;
3788
+ private getConnection;
3789
+ /**
3790
+ * Send an unsubscribe frame (tagged with its wire type) on the shard's
3791
+ * socket, or queue it for the next reconnect when the send can't go out.
3792
+ */
3793
+ private sendOrQueueUnsubscribe;
3794
+ /**
3795
+ * The `(wsState, hasSocket, wasEverConnected, polling)` state `mutation()`'s
3796
+ * offline-queue gate reads. On the leader/single-tab path this is exactly
3797
+ * the real `ShardConnection`'s state (byte-identical to the pre-cross-tab
3798
+ * behavior). A follower has no `ShardConnection` of its own (see
3799
+ * `ensureSocket`), so it derives the same triple from the mirrored
3800
+ * `leaderStatus`/`leaderWasEverConnected` instead: `"connected"` maps to
3801
+ * `"open"` (queue-eligible once `wasEverConnected`), `"connecting"` stays
3802
+ * `"connecting"` (the mid-reconnect queue branch), anything else is
3803
+ * `"idle"`. `hasSocket` is always `false` for a follower — it never has
3804
+ * one.
3805
+ *
3806
+ * `polling` is `true` while the HTTP polling fallback is reaching the origin
3807
+ * (the leader's mirrored `"polling"` on a follower). Writes then go straight
3808
+ * over HTTP, as they do while connected, instead of queueing for a socket
3809
+ * that may never open.
3810
+ */
3811
+ private connectionGateState;
3812
+ private getOrCreateConnection;
3813
+ private wsUrlFor;
3814
+ /**
3815
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
3816
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
3817
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
3818
+ * rides both the direct send and any offline-queue replay of the same write,
3819
+ * so a mutation the server already committed returns its cached result
3820
+ * instead of running twice.
3821
+ */
3822
+ private rpcRequestHeaders;
3823
+ private rpc;
3824
+ /**
3825
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
3826
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
3827
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
3828
+ * mirroring {@link rpc} so callers see the same failure shape.
3829
+ */
3830
+ private adminFetch;
3831
+ /**
3832
+ * Resolve the effective connection context for a shard: the most-recently
3833
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
3834
+ * back to the imperative {@link setConnectionContext} override, then the
3835
+ * client-wide default. Returns `undefined` when none apply.
3836
+ */
3837
+ private effectiveConnectionContext;
3838
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
3839
+ private refreshConnectionContext;
3840
+ /**
3841
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
3842
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
3843
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
3844
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
3845
+ * hooks are registered, and answers with the socket's `identity` frame
3846
+ * (see `handleIdentityFrame`).
3847
+ *
3848
+ * The shard's registered context (or the client-wide default) rides along
3849
+ * when one is set — the DO records it on the attachment for replay to
3850
+ * `onDisconnect`. A socket with no registered context still announces itself;
3851
+ * the envelope simply omits `context`, which is optional on the wire.
3852
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
3853
+ * to the lifecycle dispatch.
3854
+ */
3855
+ private sendConnectEnvelope;
3856
+ /**
3857
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
3858
+ * socket. Each frame carries the shape's last applied checkpoint, so the
3859
+ * server resumes from it — or re-seeds when the cursor fell below CDC
3860
+ * retention or the epoch forked.
3861
+ */
3862
+ private resendShapeSubscriptions;
3863
+ private ensureSocket;
3864
+ /**
3865
+ * Resolve the {@link WsTokenProvider} and open the shard socket with the
3866
+ * minted token. The connection is already in the `connecting` state, so the
3867
+ * async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
3868
+ * competing connect that landed first all abandon this attempt. A provider
3869
+ * failure fails the attempt through {@link handleDisconnect}, which arms the
3870
+ * normal reconnect backoff — a broken mint endpoint degrades to retries, not
3871
+ * a silent tokenless socket the admin gate would reject.
3872
+ */
3873
+ private openSocketWithProvidedToken;
3874
+ /**
3875
+ * Construct one WebSocket connection attempt and wire the shared
3876
+ * lifecycle guarantees around it — the fail-fast connect-timeout, the
3877
+ * identity guard that stops a superseded attempt's late `open`/`message`/
3878
+ * `close`/`error` from touching a connection a newer attempt already
3879
+ * owns, and (once open) the keepalive heartbeat with its half-open
3880
+ * watchdog (plan 217). One call opens ONE attempt; the caller owns
3881
+ * reconnect scheduling from `onClose` — mirrors the shard's existing
3882
+ * `ensureSocket` / `handleDisconnect` split, now shared with
3883
+ * `subscribeScheduledJobs` so it stops re-living the bug that split
3884
+ * already fixed once (CLIENT-05).
3885
+ *
3886
+ * The identity guard is `conn.socket !== socket`, re-checked before every
3887
+ * action below. `conn.socket` is reassigned to a new attempt's socket
3888
+ * synchronously — right here, before `open` ever fires — so an older
3889
+ * attempt's guard trips the instant it's superseded, even if its
3890
+ * underlying socket only fires its real `close`/`error` much later. This
3891
+ * ordering is load-bearing: preserve it exactly.
3892
+ */
3893
+ private openManagedSocket;
3894
+ /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
3895
+ private openSocket;
3896
+ /**
3897
+ * Send the stream-start frames queued while the socket was (re)connecting,
3898
+ * marking each one that lands as started on the server.
3899
+ */
3900
+ private flushPendingStreams;
3901
+ /**
3902
+ * Tear down a stream the consumer cancelled, telling the server when the
3903
+ * server is the one still holding it.
3904
+ */
3905
+ private cancelStream;
3906
+ private handleDisconnect;
3907
+ /**
3908
+ * Begin the keepalive heartbeat on an open connection attempt — the only
3909
+ * caller is {@link openManagedSocket}'s own `open` handler, so both the
3910
+ * shard socket and `subscribeScheduledJobs` share this one implementation
3911
+ * instead of each hand-rolling their own (plan 217, generalized).
3912
+ *
3913
+ * Each tick first checks the half-open watchdog (see
3914
+ * {@link ManagedSocketState.lastFrameAt}): if no frame at all has arrived
3915
+ * within `heartbeatIntervalMs * 2.5`, the far end has gone quiet without
3916
+ * the socket ever firing `close` — force it closed and report it through
3917
+ * `onWatchdogTrip` (the caller's `onClose`) so the normal reconnect/backoff
3918
+ * takes over instead of every live query on it silently staling forever.
3919
+ * Otherwise it sends a {@link WS_KEEPALIVE_PING} text frame the server
3920
+ * answers from its hibernation auto-response without waking the DO. A
3921
+ * no-op when the heartbeat is disabled (an interval of zero or less);
3922
+ * idempotent — any existing timer is cleared first so a reconnect can't
3923
+ * leak intervals.
3924
+ */
3925
+ private startHeartbeat;
3926
+ /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
3927
+ private stopHeartbeat;
3928
+ /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
3929
+ private markShardPendingAck;
3930
+ /**
3931
+ * Re-send `state`'s `subscribe` frame, but only once fewer than
3932
+ * {@link RESUBSCRIBE_CONCURRENCY} frames on this shard are still awaiting a
3933
+ * reply. Used by every path that resends MANY subscriptions at once — the
3934
+ * socket-open resubscribe and the cross-tab leader handover, which replays
3935
+ * every tab's subscriptions combined. A first subscribe (one frame, caller
3936
+ * paced) still goes straight out through {@link sendSubscribeIfOpen}.
3937
+ */
3938
+ private queueResubscribe;
3939
+ /**
3940
+ * Send queued `subscribe` frames until the in-flight window is full.
3941
+ *
3942
+ * Cannot wedge: a queued subscription whose frame does not actually go out
3943
+ * (socket closed, already acked, unsubscribed while queued) takes no slot,
3944
+ * every sent frame is released by the first server frame carrying its id
3945
+ * (see {@link handleServerMessage}) or by its own watchdog, and a disconnect
3946
+ * drops the queue wholesale — the next `open` re-queues every subscription
3947
+ * on the shard, because `markShardPendingAck` un-acked them all.
3948
+ */
3949
+ private drainResubscribeQueue;
3950
+ /** Free the in-flight slot `id` holds on `conn` (if any) and let the next queued subscribe go out. */
3951
+ private releaseResubscribeSlot;
3952
+ /**
3953
+ * Abandon this connection's paced resubscribe: clear every watchdog and
3954
+ * forget both the in-flight and the waiting entries. Called wherever the
3955
+ * socket they were sent on goes away — the server drops that socket's
3956
+ * subscriptions anyway, and the next `open` re-queues all of them.
3957
+ */
3958
+ private clearResubscribeQueue;
3959
+ /** Send `state`'s `subscribe` frame when the shard's socket can carry it; `true` when a frame actually went out. */
3960
+ private sendSubscribeIfOpen;
3961
+ private sendShapeSubscribeIfOpen;
3962
+ private handleServerMessage;
3963
+ private handleErrorMessage;
3964
+ /** Buffer key for an in-flight poke: `pokeId` is only unique per shard socket, so it is scoped by connection. */
3965
+ private pokeBufferKey;
3966
+ private handlePokeStart;
3967
+ private handlePokePart;
3968
+ private handlePokeEnd;
3969
+ /**
3970
+ * Commit one shape's slice of a poke, or refuse it and re-seed.
3971
+ *
3972
+ * Split out of {@link handlePokeEnd} because every decision here is PER SHAPE
3973
+ * — the reset flag, the base checkpoint, the watermark — while the poke
3974
+ * envelope around it is not.
3975
+ */
3976
+ private applyPokePart;
3977
+ /**
3978
+ * Force the server to re-send a full snapshot for `state`, leaving the
3979
+ * currently displayed value alone until it lands. Used when a delta frame
3980
+ * cannot be applied: dropping the resume cursor is what makes the resubscribe
3981
+ * a snapshot rather than a `resume`, and un-acking is what lets
3982
+ * `sendSubscribeIfOpen` put the frame on the wire at all. Mirrors the shape
3983
+ * path's re-seed on a diverged base.
3984
+ */
3985
+ private resnapshotSubscription;
3986
+ /** Materialize a shape's keyed view to an array and invoke its callbacks. */
3987
+ private emitShapeRows;
3988
+ /**
3989
+ * Apply one `data` frame. `snapshotMark` is set only for a frame synthesized
3990
+ * by a poll, which carries no cursor: see {@link pollSubscriptions}.
3991
+ */
3992
+ private handleDataMessage;
3993
+ /**
3994
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
3995
+ * subscription reads changed since our `sinceSeq`, so the cached value is
3996
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
3997
+ * the cursor (re-persisting so the next reconnect resumes from the newer
3998
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
3999
+ * already replayed the cached value to every consumer synchronously.
4000
+ */
4001
+ private handleResumeMessage;
4002
+ /**
4003
+ * Handle a `settled` frame: a write touched one of this subscription's read
4004
+ * tables but produced a byte-identical result, so the server suppressed the
4005
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
4006
+ * advance the resume position and re-persist — but we ALSO surface the echoed
4007
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
4008
+ * collection drops the optimistic overlay for the confirmed write (otherwise
4009
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
4010
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
4011
+ * `onCheckpoint` unset and this is a near no-op.
4012
+ */
4013
+ private handleSettledMessage;
4014
+ /**
4015
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
4016
+ * the cached position, advance the resume watermark and re-persist. Shared by
4017
+ * the `resume` and `settled` frame handlers — both acknowledge "nothing the
4018
+ * client must re-render changed, but the resume position may have moved".
4019
+ */
4020
+ private ackAndAdvanceCursor;
4021
+ /**
4022
+ * Resolve the value to publish for a `data`/`delta` frame.
4023
+ *
4024
+ * A `data` frame is an authoritative snapshot (the server re-execution path)
4025
+ * and always replaces the cached value wholesale. A `delta` frame carrying a
4026
+ * structured `MutationDelta` (the `broadcastDelta` row-change path) is
4027
+ * merged incrementally into the cached list — preserving order, no dup/loss —
4028
+ * so each subscription (including every paginated page) updates by delta
4029
+ * rather than a full re-send. We fall back to full replacement when the
4030
+ * delta isn't a recognisable row change, when there's no cached value yet,
4031
+ * or when it can't be applied cleanly against the current cached shape.
4032
+ */
4033
+ private resolveDataPayload;
4034
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
4035
+ private dispatchWhisper;
4036
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
4037
+ private notifyTokenExpired;
4038
+ /**
4039
+ * CLIENT-04: `type: "complete"` today is sent ONLY by `@lunora/do`'s
4040
+ * `handleStream` (see `shard-do.ts`), gated to the `stream` envelope type
4041
+ * and minting only `stream_*` ids — the `subscribe` path never sends it, so
4042
+ * a live SUBSCRIPTION provably never receives `complete` from the current
4043
+ * server. But `ServerCompleteMessage` is a generic `id`-keyed frame and
4044
+ * `ShardDO` is user-subclassable, so this stays defensive rather than
4045
+ * assuming a `sub_*` id can never reach here: unlike the historical
4046
+ * `subscriptions.remove(state)`, which dropped the state out of
4047
+ * `subscriptions.all()` — the set the reconnect resubscribe loop walks
4048
+ * (`ensureSocket`'s `open` handler) — and so froze the query forever across
4049
+ * every future reconnect, this fans a cancellation error to any listener
4050
+ * and marks the registration un-acked instead. Non-destructive: the state
4051
+ * stays in the registry, so the very next reconnect resubscribes it. The
4052
+ * two id-spaces don't overlap (`sub_*` vs `stream_*`), so the stream and
4053
+ * subscription lookups below are mutually exclusive.
4054
+ */
4055
+ private handleCompleteMessage;
4056
+ private unpersist;
4057
+ /**
4058
+ * Stable, non-reversible fingerprint of the current auth identity used to
4059
+ * stamp queued offline writes.
4060
+ *
4061
+ * `null` never matches a bearer-token fingerprint — but it is only an
4062
+ * IDENTITY of its own once this client knows no subject is coming. An app
4063
+ * with no auth at all, and a client the server has answered "no session"
4064
+ * to, both hold a `null` nobody else shares. A client mid-`/get-session`
4065
+ * holds a `null` that may be one round trip from `subj:<id>`, which is
4066
+ * every cookie app's page load: ask {@link identityUnresolved} before
4067
+ * treating it as an identity, or `null === null` matches two different
4068
+ * people. The raw token is never stored;
4069
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
4070
+ * without keeping the credential around in the queue map.
4071
+ */
4072
+ private identityFingerprint;
4073
+ /**
4074
+ * Stable token-hash fingerprint of a bearer token (the `<len>:<fnv>:<djb2>`
4075
+ * format a token-stamped queued write carries). Extracted so the replay gate
4076
+ * can recompute the hash of the current credential and recognise a write
4077
+ * stamped under it — even after the fingerprint was relabelled to a subject.
4078
+ *
4079
+ * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
4080
+ * two distinct equal-length tokens are astronomically unlikely to share a
4081
+ * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
4082
+ * pair — enough that, on a shared device, user B could hydrate A's cached
4083
+ * reads. Different algorithms (not the same FNV with a different seed, which
4084
+ * would be affine-related) keep the two passes genuinely independent.
4085
+ * Still synchronous (no crypto) and stable across surrogate pairs.
4086
+ */
4087
+ private hashToken;
4088
+ /**
4089
+ * The `credential` field a read-cache write carries: the token hash of the
4090
+ * bearer currently held, or nothing at all when signed out (there is no
4091
+ * credential to match against, and the `null` identity already covers it).
4092
+ */
4093
+ private credentialStamp;
4094
+ /**
4095
+ * Whether a read-cache entry belongs to the identity in effect right now —
4096
+ * the ONE gate the hydrated peek, the subscribe-time take and the late seed
4097
+ * all share.
4098
+ *
4099
+ * Three ways to be the same identity, because the label and the credential
4100
+ * resolve at different times:
4101
+ *
4102
+ * 1. The fingerprints are equal — the plain case.
4103
+ * 2. The entry is stamped under a token hash and the live identity has since
4104
+ * been relabelled to the subject that credential resolved to
4105
+ * ({@link isSameCredentialUnderTokenHash}).
4106
+ * 3. The entry is stamped under a subject and THIS session has only the raw
4107
+ * token so far, but it is byte-for-byte the credential the entry was written
4108
+ * under. This is the direction the strict comparison missed entirely, and it
4109
+ * is the normal shape of every reload: every adapter calls
4110
+ * `setAuthToken(token)` from storage and only learns the subject a
4111
+ * `/get-session` round trip later — which offline never completes at all.
4112
+ * Without it the durable read cache never seeded for a bearer-token app.
4113
+ *
4114
+ * All three want a credential this client actually HOLDS, which is why a
4115
+ * **cookie session seeds nothing on an offline cold start** — a documented
4116
+ * limitation, not a gap. The cookie is `HttpOnly`: the client can neither
4117
+ * read it nor prove it still has it, and offline the `/get-session` that
4118
+ * would resolve the subject never answers, so such entries (stamped
4119
+ * `subj:<id>`, no credential) have nothing to match. Seeding them on the
4120
+ * remembered subject LABEL would hand the rows to whoever opens the browser
4121
+ * profile with nothing evidencing they are that subject, and revoking on a
4122
+ * later mismatch does not repair it: that check can only run once
4123
+ * connectivity returns, which is exactly the state where the offline seed
4124
+ * was not needed. Offline-first reads require a bearer token.
4125
+ *
4126
+ * Case 1 is suspended while the subject awaits re-confirmation
4127
+ * ({@link subjectAwaitingReconfirm}): the fingerprint then labels a
4128
+ * credential nothing has checked it against, which is precisely the
4129
+ * account-switch shape — `setAuthToken(otherAccountsToken)` with no subject,
4130
+ * what every adapter does on a reload, still reading `subj:<previous user>`.
4131
+ * Matching on that label alone hands the new account the previous account's
4132
+ * cached rows. Cases 2 and 3 both PROVE the credential, so the reload this
4133
+ * gate exists for still seeds.
4134
+ */
4135
+ private cachedQueryMatchesIdentity;
4136
+ /**
4137
+ * True when `stamped` is a token-hash of the SAME credential still held now,
4138
+ * even though the live identity has since been relabelled to a subject. Covers
4139
+ * `setAuthToken(token, userId)` where the subject resolved a tick after the
4140
+ * token was set: a write persisted (or requeued) under the token hash must
4141
+ * still replay — the credential never changed, only its label — instead of
4142
+ * being dropped as an identity mismatch. This is the durable counterpart to
4143
+ * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
4144
+ * (consumed on the first flush) and never touches `item.identity` or the
4145
+ * persisted record, so a reload or a transient-failure requeue would otherwise
4146
+ * fall back to the stale token-hash and wrongly reject the same user's write.
4147
+ */
4148
+ private isSameCredentialUnderTokenHash;
4149
+ /**
4150
+ * Release one {@link sessionProbesInFlight} hold and re-flush the writes
4151
+ * that hold alone was holding.
4152
+ *
4153
+ * A resolve that names a user re-flushes through {@link setAuthToken} (the
4154
+ * identity changed). One that does not — signed out, or unreachable —
4155
+ * changes no identity and so fires no listener, and a write held only
4156
+ * because {@link identityUnresolved} said so would sit queued until the
4157
+ * next reconnect. Same connected-only gate as `setAuthToken`'s, so this
4158
+ * stays a re-flush of a live connection rather than a reason to replay an
4159
+ * offline queue.
4160
+ *
4161
+ * Only for a `null` fingerprint, which is the ONLY hold this probe owns:
4162
+ * {@link replayIdentityVerdict}'s unresolved-identity hold tests
4163
+ * `current === null`, while its other hold — a sticky subject awaiting
4164
+ * re-confirmation — requires an established subject and so a
4165
+ * `subj:<id>` fingerprint. That one is already on the `noteHeldRetryDelay`
4166
+ * backoff and must stay there.
4167
+ *
4168
+ * Re-flushing it from here instead was an unbounded loop, not a slow
4169
+ * backoff: `drainOfflineQueue` answers a subject-awaiting hold by probing
4170
+ * `getCurrentUser()` itself, whose release re-flushed, which drained, which
4171
+ * probed again — hundreds of round trips without a millisecond passing,
4172
+ * until the heap gave out. Narrowing to the `null` fingerprint makes the
4173
+ * cycle unreachable rather than merely rare: the branch that starts a probe
4174
+ * cannot be entered by a flush this guard lets through.
4175
+ */
4176
+ private releaseSessionProbe;
4177
+ /**
4178
+ * Whether this client's `null` identity fingerprint is still provisional —
4179
+ * a {@link getCurrentUser} resolve is in flight and may be about to name a
4180
+ * subject. The one question every identity gate asks before it is willing
4181
+ * to treat `null` as an identity rather than as an absence of one.
4182
+ */
4183
+ private identityUnresolved;
4184
+ /**
4185
+ * Key the offline-queue identity on the resolved user id rather than the
4186
+ * token bytes, so the NEXT token refresh keeps the same identity.
4187
+ *
4188
+ * Under a bearer token only a resolved user labels anything. A 401 or an
4189
+ * empty session resolves `null` for reasons that say nothing about who holds
4190
+ * the token, so the established label is left alone rather than cleared
4191
+ * (which would look like an identity change and drop the queue). A token
4192
+ * that rotated mid-flight belongs to a session this answer predates and is
4193
+ * ignored for the same reason.
4194
+ *
4195
+ * Under a cookie session (no token) the answer is the identity, `null`
4196
+ * included: nothing on the client changes when the user signs out, so "the
4197
+ * server found no session" is the only sign-out this client will ever see.
4198
+ * See {@link adoptCookieSubject}.
4199
+ *
4200
+ * A superseded probe is ignored too, and the token check cannot see it: on a
4201
+ * cookie app both `requestToken`s are `null`, so a slow answer from an OLDER
4202
+ * probe passed that check and overwrote the subject a newer one had already
4203
+ * established. `requestGeneration` is the question's id — it must still be
4204
+ * the current one at the moment of the write.
4205
+ */
4206
+ private adoptResolvedSubject;
4207
+ /**
4208
+ * Adopt the user a cookie session resolved to — `null` for nobody — as this
4209
+ * client's identity, from either source the server answers through: a
4210
+ * `/get-session` probe, or a socket's `identity` frame.
4211
+ *
4212
+ * Three states, told apart by `authSubject`: `undefined` is not known yet
4213
+ * (every page load until the first answer), `null` is known to be nobody,
4214
+ * and a string is that user. {@link setAuthToken} retires the previous
4215
+ * session on every change between two KNOWN states — `A → nobody`,
4216
+ * `nobody → B`, `A → B` — and on none out of `undefined`, so the first
4217
+ * answer after a page load never evicts what the page is already showing
4218
+ * for the session it was loaded under.
4219
+ *
4220
+ * `question` orders the answers: one older than the answer in force
4221
+ * describes an older cookie and is dropped. Returns whether it was adopted.
4222
+ */
4223
+ private adoptCookieSubject;
4224
+ /**
4225
+ * A cookie socket's `identity` frame: the user the shard authenticated this
4226
+ * socket as, sent in reply to every `connect`.
4227
+ *
4228
+ * Adopted like a probe's answer when it is the newest one
4229
+ * ({@link adoptCookieSubject}). An OLDER one that disagrees with the
4230
+ * identity in force means this socket was upgraded on a cookie that has
4231
+ * since changed hands, and is still delivering that user's rows: the
4232
+ * session it belongs to is retired, which replaces the socket.
4233
+ *
4234
+ * Ignored for a socket that authenticated with a token rather than the
4235
+ * cookie (see `ShardConnection.identityQuestion`) — its answer is about that
4236
+ * token, not about the cookie session this client's identity tracks.
4237
+ */
4238
+ private handleIdentityFrame;
4239
+ /**
4240
+ * The subject half of {@link setAuthToken}.
4241
+ *
4242
+ * Sticky: only an explicit value (incl. `null` = signed out) changes the
4243
+ * subject; omitting it keeps the established one. Two exceptions, both about
4244
+ * a subject that must not outlive the credential it described:
4245
+ *
4246
+ * - Clearing the token clears a user subject — see `setAuthToken`'s
4247
+ * docblock. A `null` one stays: a cookie session known to be nobody's is
4248
+ * still nobody's.
4249
+ * - A token arriving on a session known to be nobody's drops the `null`,
4250
+ * so the identity falls back to the token itself rather than staying
4251
+ * "nobody" while a credential is held.
4252
+ */
4253
+ private applySubject;
4254
+ /**
4255
+ * A cookie session the server has answered "nobody" for — see
4256
+ * {@link adoptCookieSubject}. Distinct from a subject not known YET
4257
+ * (`undefined`).
4258
+ */
4259
+ private isKnownNobody;
4260
+ /**
4261
+ * True while an established subject labels a credential it was never checked
4262
+ * against — see the `subjectToken` field. Every replay verdict is
4263
+ * `"unknown"` (hold) until the next session resolve re-asserts the subject.
4264
+ */
4265
+ private subjectAwaitingReconfirm;
4266
+ /**
4267
+ * The identity a queued write is stamped with. The live `queuedIdentities`
4268
+ * map is the source of truth for this session; a hydrated write whose id
4269
+ * isn't in it falls back to the stamp persisted with the record. `Map.get`
4270
+ * returns `undefined` for unstamped/hydrated ids and `item.identity` is
4271
+ * `undefined` for legacy records (persisted before stamps were durable),
4272
+ * while a persisted `null` (queued while signed out) is a real value that
4273
+ * must not collapse into `undefined` — hence `=== undefined`, not `??`.
4274
+ */
4275
+ private stampOf;
4276
+ /**
4277
+ * Reject the in-memory offline writes that can no longer replay under the
4278
+ * identity now signed in, dropping their durable records so a later
4279
+ * `hydrate` can't resurrect another user's writes.
4280
+ *
4281
+ * Per item, not wholesale: this runs on a plain sign-in too (`null` → a
4282
+ * signed-in identity is a credential change like any other), where the
4283
+ * queue is the *signing-in user's own* restored writes. Every stamp goes
4284
+ * through {@link replayIdentityVerdict}, the one comparison, and only
4285
+ * `"mismatch"` is terminal — `"match"` and `"unknown"` stay queued.
4286
+ *
4287
+ * The durable read cache is cleared only when there WAS a previous identity
4288
+ * to protect. Wiping it on a sign-in from signed-out would destroy the
4289
+ * offline-first cache on every cold boot, and buys nothing: cache entries
4290
+ * are identity-stamped and gated at every read.
4291
+ */
4292
+ private rejectQueuedForIdentityChange;
4293
+ /**
4294
+ * Move the identity stamp of every open shard socket from `from` to `to` —
4295
+ * the sibling of {@link restampQueuedIdentity} for the read cache. A socket
4296
+ * pins the identity it was upgraded under (see `ShardConnection.identity`)
4297
+ * and {@link persistQueryValue} stamps cached reads with it, deliberately,
4298
+ * so a still-open previous-user socket can't file frames under the new
4299
+ * user's stamp. A same-credential relabel is the one case where that pin is
4300
+ * stale rather than protective: without this, every read cached for the rest
4301
+ * of the session is filed under a fingerprint the next session's identity
4302
+ * gate rejects, and the durable read cache silently yields nothing.
4303
+ */
4304
+ private restampConnectionIdentity;
4305
+ /**
4306
+ * Migrate every identity stamp from `from` to `to` — used when the auth
4307
+ * identity label changes but the underlying credential (token) does NOT, e.g.
4308
+ * the user id resolves a tick after the token was set. The in-memory
4309
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
4310
+ * keeps the in-flight writes replayable under the new (more stable) identity
4311
+ * instead of the flush guard discarding them as a mismatch.
4312
+ *
4313
+ * That map alone was not enough: it is consumed and DELETED on the first
4314
+ * flush attempt (`replayIdentityVerdict`), while the queue entry and its
4315
+ * persisted record keep the original stamp. So a reload, or a requeue after a
4316
+ * transient failure, fell back to the old token hash — and once the token had
4317
+ * been refreshed, `isSameCredentialUnderTokenHash` no longer recognised it
4318
+ * and the write was rejected `OFFLINE_IDENTITY_CHANGED` for the very user
4319
+ * `setAuthToken`'s sticky-`subject` contract promises to protect. The queue's
4320
+ * own re-stamp covers both the entry and its durable record.
4321
+ */
4322
+ private restampQueuedIdentity;
4323
+ /**
4324
+ * Migrate the {@link clientWatermarks} bucket map nested under identity
4325
+ * `from` to identity `to` — the sibling of {@link restampQueuedIdentity},
4326
+ * for the same same-credential-subject-resolves case. Without this, a
4327
+ * bucket's watermark cached under the token-hash fingerprint would look
4328
+ * unset once the fingerprint relabels to `subj:…`, so the next push
4329
+ * re-derives `1` against a server watermark the DO already advanced — the
4330
+ * OUT_OF_ORDER wedge this cache-keying scheme exists to fix, reintroduced
4331
+ * by the fix itself. `to` may already hold a bucket map (switching back to
4332
+ * an identity that has its own cached watermarks); merge into it rather
4333
+ * than clobbering it, with `from`'s entries winning on a colliding bucket —
4334
+ * the same overwrite a plain `Map.set` would have done before this was a
4335
+ * nested map.
4336
+ */
4337
+ private restampWatermarks;
4338
+ /**
4339
+ * Drop the durable read cache on an identity change so a cached value stamped
4340
+ * under the previous identity can never hydrate into a new session. Clears
4341
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
4342
+ * the durable `clear()` is best-effort.
4343
+ */
4344
+ private clearQueryCacheForIdentityChange;
4345
+ /**
4346
+ * Retire everything the PREVIOUS identity left live on a genuine identity
4347
+ * change: the sockets it is authenticated on, and the rows they delivered.
4348
+ *
4349
+ * A WebSocket credential is pinned in its upgrade URL and cannot be rotated
4350
+ * in place, so `setAuthToken` alone left the previous user's socket open and
4351
+ * delivering — the consequence `ShardConnection.identity`'s docblock already
4352
+ * described, with "nothing" as the thing that closes it on a client without
4353
+ * `crossTabSync`. And each `SubscriptionState` keeps the last value that
4354
+ * socket delivered, which `subscribe()` replays synchronously to every new
4355
+ * subscriber, so the incoming user's first render was the outgoing user's
4356
+ * rows even after the socket did go.
4357
+ *
4358
+ * Both halves are needed: closing the socket without clearing the values
4359
+ * leaves them on screen until a frame replaces them (which never comes for a
4360
+ * query the new user cannot read), and clearing the values without closing
4361
+ * the socket lets the next frame put them straight back.
4362
+ */
4363
+ private evictPreviousIdentitySession;
4364
+ /**
4365
+ * Move this tab's cross-tab coordinator onto the channel the new identity
4366
+ * derives, after an identity change.
4367
+ *
4368
+ * The channel name embeds the identity fingerprint (see
4369
+ * {@link createTabCoordinator}), so without this the tab keeps
4370
+ * leading/following the PREVIOUS identity's group. BroadcastChannel names
4371
+ * are immutable, so a stop-old+construct-new is the only way to move
4372
+ * channels — but that means the fresh coordinator would otherwise sit
4373
+ * through the full claim-then-`leaderTimeout` dance (3s default) before any
4374
+ * tab opens a socket again, freezing every live query for that long on
4375
+ * EVERY identity change (including a routine JWT refresh for an app that
4376
+ * doesn't pass a stable `subject` — the documented reason to pass one). If
4377
+ * this tab was already the leader, it's overwhelmingly likely to remain the
4378
+ * sole tab on the new channel too, so promote it immediately instead of
4379
+ * waiting — `promoteImmediately`'s docblock covers the (self-healing) rare
4380
+ * case where another tab does the same at once.
4381
+ */
4382
+ private restartTabCoordinatorForIdentity;
4383
+ /**
4384
+ * Close every open shard socket so each reconnects carrying the credential
4385
+ * in effect now.
4386
+ *
4387
+ * Non-terminal, unlike {@link close}: the `ShardConnection` records and the
4388
+ * subscriptions riding them survive, and the registered `close` handler
4389
+ * (`handleDisconnect`) schedules the retry and replays the subscribes. This
4390
+ * is the only way to move a WS credential — it lives in the upgrade URL.
4391
+ */
4392
+ private bounceShardSockets;
4393
+ /**
4394
+ * Flush every shard with a mutation currently queued in `offlineQueue`
4395
+ * (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
4396
+ * mirrored leader status transitions to `"connected"` — a follower has no
4397
+ * per-shard `ShardConnection` reconnect event to hang the usual
4398
+ * single-shard `flushOfflineQueue(shardKey)` call off of (see the `onOpen`
4399
+ * callback that calls `flushOfflineQueue(shardKey)`), so this walks every
4400
+ * shard that might have something queued instead. Flushing an already-empty
4401
+ * shard is a cheap no-op (`flushOfflineQueue` returns immediately once
4402
+ * `drain` yields nothing), so over-inclusion here is harmless.
4403
+ */
4404
+ private flushAllOfflineQueues;
4405
+ /**
4406
+ * Replay a shard's queued writes, serialized per shard and published as
4407
+ * {@link offlineFlushes} so a concurrent `mutation()` can wait behind it.
4408
+ * Never rejects: every entry's outcome is settled individually inside
4409
+ * {@link drainOfflineQueue}, and a poisoned chain would strand every later
4410
+ * flush AND every write waiting on the barrier.
4411
+ */
4412
+ private flushOfflineQueue;
4413
+ private drainOfflineQueue;
4414
+ /**
4415
+ * Ask for another flush of this shard after a backoff, because every entry it
4416
+ * drained was HELD for an identity that is not re-confirmed yet.
4417
+ *
4418
+ * Same state and same timer as a rate-limited replay
4419
+ * ({@link LunoraClient.noteReplayRetryDelay}) — one pending flush per shard
4420
+ * key either way — only the reason differs: there is no error to read a
4421
+ * `Retry-After` off, so the hintless {@link defaultReplayRetryDelayMs} ramp
4422
+ * (1s doubling to a 60s ceiling, jittered) is the whole policy. It is a
4423
+ * ceiling on the rate, not a budget of attempts: a durable write is never
4424
+ * dropped for having waited too long, so a subject that never resolves leaves
4425
+ * the queue re-probing at ≤ 60s intervals with the writes intact and
4426
+ * {@link LunoraClient.pendingCount} non-zero for the app to surface. The
4427
+ * retries stop when the hold lifts (the queue drains), when the shard has
4428
+ * nothing queued, or at `close()`.
4429
+ *
4430
+ * Identity is re-read by the flush, never carried across the timer: the
4431
+ * retry re-enters {@link LunoraClient.drainOfflineQueue}, which re-runs
4432
+ * {@link LunoraClient.replayGateVerdict} per entry against the identity in
4433
+ * effect when it runs. A retry therefore cannot replay a write under an
4434
+ * identity that changed while the timer was pending — it re-holds it, or
4435
+ * rejects it as a mismatch, exactly as a reconnect-driven flush would.
4436
+ */
4437
+ private noteHeldRetryDelay;
4438
+ /**
4439
+ * Remember the longest delay this shard's flush was told (or worked out) to
4440
+ * wait, so the drain can honour it before trying again
4441
+ * ({@link LunoraClient.replayRetryState}). Counts the attempt either way:
4442
+ * that is what a hintless refusal backs off on.
4443
+ */
4444
+ private noteReplayRetryDelay;
4445
+ /**
4446
+ * Consume this shard's retry delay and re-flush it once the delay has
4447
+ * elapsed.
4448
+ *
4449
+ * Two things record a delay for it to consume: a failure the server or an
4450
+ * edge ANSWERED (see {@link replayRetryDelayMs}) and a flush that HELD every
4451
+ * entry it drained (see {@link LunoraClient.noteHeldRetryDelay}). Both happen
4452
+ * over a socket that stays open, so without this the writes sit queued
4453
+ * indefinitely; a `fetch` that never landed records nothing, because the
4454
+ * reconnect that follows flushes the queue anyway. One pending timer per
4455
+ * shard; a second delay replaces it rather than stacking flushes.
4456
+ *
4457
+ * Nothing left to retry on this key (drained, closed, or no delay) drops its
4458
+ * backoff state, which is both the reset after progress and what bounds the
4459
+ * map.
4460
+ */
4461
+ private scheduleRateLimitedRetry;
4462
+ /**
4463
+ * Partition already-gated writes into the encodable ones (returned) and reject
4464
+ * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
4465
+ * or class instance in a `v.any()` field) can NEVER replay — the codec failure
4466
+ * is deterministic, not transient. Rejecting here is essential: otherwise
4467
+ * `encodeWire` throws mid-flush, is classified as transient (a codec error has
4468
+ * no `.code`), and re-queues forever — a silent hang where the caller's Promise
4469
+ * never settles and the optimistic write never rolls back. Encoding is cheap;
4470
+ * the flush is the slow reconnect path.
4471
+ */
4472
+ private encodableOrSettleTerminal;
4473
+ /**
4474
+ * The three-way comparison behind {@link replayIdentityVerdict} (documented
4475
+ * there), without a credential: the built-in queue sends with its own pinned token.
4476
+ */
4477
+ private identityVerdict;
4478
+ /**
4479
+ * Identity gate for one queued write about to replay: a write stamped under
4480
+ * one identity must never replay under another, and must never be DESTROYED
4481
+ * because the identity isn't known yet.
4482
+ *
4483
+ * The three-way verdict is {@link replayIdentityVerdict}'s, not a second
4484
+ * hand-rolled comparison — `@lunora/db`'s durable outbox holds on `"unknown"`
4485
+ * through the same call, and this path (the default for the standalone
4486
+ * client) used to drop there instead, purging the queuing user's own write
4487
+ * on every reload that opened its socket before the session resolved.
4488
+ *
4489
+ * `"send"` replays it and consumes the live stamp. `"hold"` leaves it queued
4490
+ * and persisted, stamp intact, for a later flush once an identity is
4491
+ * established (see `setAuthToken`). `"reject"` means a different identity is
4492
+ * signed in: settle it terminally `OFFLINE_IDENTITY_CHANGED` and purge the
4493
+ * durable record.
4494
+ */
4495
+ private replayGateVerdict;
4496
+ /** 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. */
4497
+ private settleReplaySuccess;
4498
+ /**
4499
+ * The entry a shard's cursor lives under.
4500
+ *
4501
+ * Only the server knows that an omitted `shardKey` and an explicit one
4502
+ * spelling out its configured default name are the same shard — the default
4503
+ * is server-side configuration the client never sees. Keying on what was
4504
+ * SENT would split one shard's cursor across two entries, so a write under
4505
+ * one spelling would stop constraining a read under the other. Resolving
4506
+ * `undefined` through the learned name is what keeps both spellings on one
4507
+ * entry.
4508
+ */
4509
+ private cursorKeyFor;
4510
+ /**
4511
+ * Learn the server's own name for the default shard from a response to a
4512
+ * call that named no shard.
4513
+ *
4514
+ * Any cursor recorded before the name was known sits under the placeholder
4515
+ * entry, so it is folded in rather than stranded — otherwise the requirement
4516
+ * from a client's first write would be lost exactly once, which is the kind
4517
+ * of gap that only shows up as a stale read under load.
4518
+ */
4519
+ private learnDefaultShardKey;
4520
+ /**
4521
+ * Record the cursor a write committed at as this shard's read-your-writes
4522
+ * requirement.
4523
+ *
4524
+ * Monotonic: responses can land out of order, and moving the requirement
4525
+ * BACKWARDS would let a later read be answered from a replica copy that
4526
+ * predates a write this client already saw.
4527
+ */
4528
+ private recordShardCursor;
4529
+ /**
4530
+ * Whether a replay failure leaves the durable write queued rather than
4531
+ * settling it terminally — the ONE classification the single-call, per-slot
4532
+ * and whole-batch paths share, so a write's fate never depends on how many
4533
+ * siblings rode along.
4534
+ *
4535
+ * {@link isTransientReplayFailure} answers the "no verdict was reached" half.
4536
+ * The other half is a refused CREDENTIAL ({@link isAuthReplayFailure}): the
4537
+ * queue flushes on the shard's `open` handler with whatever bearer survived
4538
+ * the offline window, so an expired token is the expected outcome of a long
4539
+ * disconnect, not a verdict on the write. Notifying {@link onTokenExpired}
4540
+ * here is what closes the loop — the HTTP replay path has no equivalent of
4541
+ * the WS `4001` close frame, so without this nothing tells the app to
4542
+ * refresh, and `setAuthToken` (which re-flushes) is never called.
4543
+ *
4544
+ * Notified once per credential, not once per write: a flush of a hundred
4545
+ * queued writes earns a hundred identical refusals, and firing the hook for
4546
+ * each would put a hundred token refreshes on the app. The stamp re-arms as
4547
+ * soon as the credential moves, which is the only thing that can change the
4548
+ * answer.
4549
+ */
4550
+ private shouldRequeueReplayFailure;
4551
+ /**
4552
+ * Whether `error` refused a replay's CREDENTIAL (`authToken`, the bearer it
4553
+ * was sent with), and if so tell {@link onTokenExpired} — once per
4554
+ * credential, and only while it is still the current one. A refusal of a
4555
+ * token the app has already replaced says nothing about the current one:
4556
+ * the next pass re-sends under it, so asking for another refresh would be
4557
+ * spurious.
4558
+ */
4559
+ private noteReplayAuthRefusal;
4560
+ /**
4561
+ * Redeem a {@link ReplayCredential} (single use) into the request flags it
4562
+ * pins (the judged bearer, and the subject a cookie replay names) and the
4563
+ * identity stamp it was judged for. Throws for a credential this client did
4564
+ * not issue or already redeemed.
4565
+ */
4566
+ private takeReplayCredential;
4567
+ /**
4568
+ * Whether `failure` is the worker's `IDENTITY_MISMATCH` refusal, and if so,
4569
+ * ask who is signed in now: the answer is what re-runs the replay gate
4570
+ * ({@link setAuthToken}), and nothing else would on a cookie session.
4571
+ */
4572
+ private noteIdentityMismatch;
4573
+ /**
4574
+ * Settle a write the server COMMITTED whose result does not decode. It is
4575
+ * `committed` — its optimistic layer confirms against the echoed cursor like
4576
+ * any success — but there is no value to hand the caller, so the awaiter is
4577
+ * rejected with the decode error and the settled event carries it.
4578
+ */
4579
+ private settleReplayUndecodable;
4580
+ /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
4581
+ private settleReplayTerminal;
4582
+ /**
4583
+ * Replay already-identity-gated writes one at a time on the single-call `/rpc`
4584
+ * path, preserving FIFO order (parallel `.then()` chains would race the
4585
+ * ordering callers depend on). Each replays under its stable `mutationId` so
4586
+ * the server dedups a write it already committed (exactly-once). A server verdict
4587
+ * drops the write; a transient failure ({@link isTransientReplayFailure} — a
4588
+ * transport error, a shard the worker couldn't reach, a rate-limit refusal, or a
4589
+ * non-2xx carrying no `{ error }` envelope) stops the flush and re-queues this
4590
+ * write and every unreplayed one for the next reconnect — their callers stay
4591
+ * pending, and the identity guard re-applies on retry via each record's persisted
4592
+ * stamp. The batch path classifies a slot by the same rule, so a durable write's
4593
+ * fate never depends on how many siblings happened to be queued alongside it.
4594
+ */
4595
+ private replaySequential;
4596
+ /**
4597
+ * Coalesce already-identity-gated writes for a single shard into ONE
4598
+ * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
4599
+ * them to the shard DO, which replays each through its single-call dispatch, so
4600
+ * per-entry `mutationId` idempotency and in-order application are inherited from
4601
+ * the proven path. Per-slot demux mirrors {@link replaySequential}'s
4602
+ * classification: success confirms the optimistic layer against the echoed
4603
+ * `commitCursor`; a coded application verdict is terminal; a failure
4604
+ * {@link shouldRequeueReplayFailure} keeps, a missing slot, or a whole-batch
4605
+ * transport failure re-queues for the next reconnect (never dropping a durable
4606
+ * write). A whole-batch coded rejection (a bad request the server reached a
4607
+ * verdict on) is terminal for every entry.
4608
+ *
4609
+ * The body is also held under {@link MAX_BATCH_BODY_BYTES}: the worker caps a
4610
+ * batch body at 1 MiB and answers `413`, which is ONE refusal covering every
4611
+ * write in the chunk. An over-budget chunk is halved before it is sent, and a
4612
+ * `413` for a chunk of more than one write halves it and retries rather than
4613
+ * settling the whole chunk terminally — so a backlog of large writes still
4614
+ * commits, one bisection deeper.
4615
+ *
4616
+ * Returns the writes that must be re-queued and `stop` — `true` when the whole
4617
+ * chunk failed at the transport level, so the caller leaves later chunks queued
4618
+ * rather than sending on. The caller re-queues once, in order, so requeuing is
4619
+ * NOT done here.
4620
+ */
4621
+ private replayBatched;
4622
+ /**
4623
+ * Classify a `/_lunora/rpc-batch` reply that carried no per-slot results — one
4624
+ * outcome covering every entry in the chunk. A code
4625
+ * {@link shouldRequeueReplayFailure} keeps (an unreachable shard, a
4626
+ * rate-limit refusal, a refused credential) or a {@link TransportError} (an
4627
+ * edge reply with no verdict in it) leaves every write durable for the next
4628
+ * attempt; anything else is a verdict reached on the request itself, and
4629
+ * settles all of them.
4630
+ */
4631
+ private settleWholeBatchError;
4632
+ /**
4633
+ * Split an over-large batch chunk in half and replay each half, preserving
4634
+ * FIFO order. Recurses through {@link replayBatched}, so a chunk keeps halving
4635
+ * until it fits (or reaches one write, which is then the server's verdict to
4636
+ * give). A `stop` on the first half leaves the second unsent and queued.
4637
+ */
4638
+ private replayBatchedHalves;
4639
+ /**
4640
+ * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
4641
+ * in input order. Each slot's envelope classifies its write the same way
4642
+ * {@link replaySequential} does: a success confirms the optimistic layer
4643
+ * against the echoed `commitCursor`; a coded application verdict is terminal;
4644
+ * a failure {@link shouldRequeueReplayFailure} keeps, or a slot the server
4645
+ * never returned, is returned for the caller to re-queue.
4646
+ *
4647
+ * A slot whose `error` key holds no readable envelope is in the same position
4648
+ * as one the server never returned — nothing came back about that entry that
4649
+ * can be read as a verdict — so it is kept, not settled.
4650
+ * @returns the writes that must be re-queued (kept slots), in input order
4651
+ */
4652
+ private settleReplayBatchSlots;
4653
+ /**
4654
+ * Settle one batch slot that answered with a result. Decoded per slot: one
4655
+ * result the codec refuses must not abandon the slots after it (committed
4656
+ * writes left pending and unsettled for the rest of the session), and its
4657
+ * own write DID commit.
4658
+ */
4659
+ private settleReplayBatchResult;
4660
+ }
4661
+ 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 };