@lunora/client 1.0.0-alpha.9 → 1.0.0-alpha.90

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