@lunora/client 1.0.0-alpha.11 → 1.0.0-alpha.110

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