@lunora/client 1.0.0-alpha.21 → 1.0.0-alpha.211

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