@lunora/client 1.0.0-alpha.7 → 1.0.0-alpha.70

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