@lunora/client 1.0.0-alpha.13 → 1.0.0-alpha.131

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