@lunora/client 1.0.0-alpha.8 → 1.0.0-alpha.81

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