@lunora/client 1.0.0-alpha.5 → 1.0.0-alpha.50

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 (86) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/auth/index.d.mts +11 -10
  3. package/dist/auth/index.d.ts +11 -10
  4. package/dist/auth/index.mjs +1 -60
  5. package/dist/index.d.mts +696 -216
  6. package/dist/index.d.ts +696 -216
  7. package/dist/index.mjs +1 -15
  8. package/dist/packem_shared/CONFLICT_ERROR_CODE-LjU7z0mB.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-CWDiiVcr.mjs +1 -0
  12. package/dist/packem_shared/OfflineQueue-CoRNJFKm.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-D5Xu-a39.mjs +1 -0
  16. package/dist/packem_shared/TabCoordinator-DVKG2RlZ.mjs +1 -0
  17. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  18. package/dist/packem_shared/applyDelta-DGqMpi3N.mjs +1 -0
  19. package/dist/packem_shared/createAsyncStoragePersistence-yBu2KWAp.mjs +1 -0
  20. package/dist/packem_shared/createClientQuery-TKD_52cT.mjs +1 -0
  21. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  22. package/dist/packem_shared/createInMemoryPersistence-BPdQiujT.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryQueryCache-HMIq2XtS.mjs +1 -0
  24. package/dist/packem_shared/createLocalStore-C_UKH_Ok.mjs +1 -0
  25. package/dist/packem_shared/createMutationRunner-C0i1P5RS.mjs +1 -0
  26. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  27. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  28. package/dist/packem_shared/createReply-CwFABEJs.mjs +1 -0
  29. package/dist/packem_shared/createServerClient-BxPCzuUt.mjs +1 -0
  30. package/dist/packem_shared/createSnapshotPrecondition-CP3e1HVS.mjs +1 -0
  31. package/dist/packem_shared/delta-merge-BoVuM-rE.mjs +1 -0
  32. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  33. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  34. package/dist/packem_shared/httpStream-x6q-x4yK.mjs +11 -0
  35. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  36. package/dist/packem_shared/local-store-BD0RFD7A.mjs +1 -0
  37. package/dist/packem_shared/lunora-client.d-BOmxvSrG.d.mts +2251 -0
  38. package/dist/packem_shared/lunora-client.d-K16SL8Tj.d.ts +2251 -0
  39. package/dist/packem_shared/offline-queue-BdQFXDz_.mjs +1 -0
  40. package/dist/packem_shared/preload.d-BprjXhJi.d.mts +21 -0
  41. package/dist/packem_shared/preload.d-CM8-Mg2A.d.ts +21 -0
  42. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  43. package/dist/packem_shared/types.d-CsuRAQvb.d.mts +976 -0
  44. package/dist/packem_shared/types.d-CsuRAQvb.d.ts +976 -0
  45. package/dist/packem_shared/wire-codec-D4iww4NV.mjs +1 -0
  46. package/dist/packem_shared/wire-key-BEmRM5ls.mjs +1 -0
  47. package/dist/pagination/index.d.mts +42 -42
  48. package/dist/pagination/index.d.ts +42 -42
  49. package/dist/pagination/index.mjs +1 -61
  50. package/dist/query/index.d.mts +110 -43
  51. package/dist/query/index.d.ts +110 -43
  52. package/dist/query/index.mjs +1 -1
  53. package/dist/service.d.mts +49 -0
  54. package/dist/service.d.ts +49 -0
  55. package/dist/service.mjs +1 -0
  56. package/dist/ssr/index.d.mts +100 -79
  57. package/dist/ssr/index.d.ts +100 -79
  58. package/dist/ssr/index.mjs +1 -4
  59. package/dist/upload.d.mts +35 -0
  60. package/dist/upload.d.ts +35 -0
  61. package/dist/upload.mjs +1 -0
  62. package/package.json +13 -1
  63. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  64. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  65. package/dist/packem_shared/LunoraClient-BPQx0T7W.mjs +0 -2497
  66. package/dist/packem_shared/OfflineQueue-D-ASeqL7.mjs +0 -131
  67. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  68. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  69. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  70. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  71. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  72. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  73. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  74. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  75. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  76. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  77. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  78. package/dist/packem_shared/createServerClient-BgzEOQ46.mjs +0 -11
  79. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  80. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  81. package/dist/packem_shared/lunora-client.d-CL9inoxa.d.mts +0 -1941
  82. package/dist/packem_shared/lunora-client.d-CL9inoxa.d.ts +0 -1941
  83. package/dist/packem_shared/preload.d-B0O7Zm9z.d.ts +0 -20
  84. package/dist/packem_shared/preload.d-Da_yjk6L.d.mts +0 -20
  85. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  86. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
@@ -0,0 +1,2251 @@
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-CsuRAQvb.mjs";
2
+ import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
+ /**
4
+ * Reactive key-value store for local-only client state.
5
+ *
6
+ * Unlike a server {@link SubscriptionState} (which tracks a live WS connection,
7
+ * an `acked` flag, `serverBase`, optimistic layers, and the full subscription
8
+ * machinery), a `ClientQueryRef` is purely local — no server round-trip, no
9
+ * WebSocket, no persistence. It exists so framework adapters can offer a
10
+ * `useClientQuery` hook whose values survive component remounts and are shared
11
+ * across every consumer of the same ref, with none of the ceremony or coupling
12
+ * of a dedicated context provider.
13
+ *
14
+ * The store lives inside `LunoraClient` (a private field) and is surfaced through
15
+ * `client.getClientQuery(ref)` / `setClientQuery(ref, value)` /
16
+ * `subscribeClientQuery(ref, callback)`.
17
+ */
18
+ /** Opaque handle for a typed client-local query slot. */
19
+ interface ClientQueryRef<T = unknown> {
20
+ /** Default value when no value has been set explicitly. */
21
+ readonly defaultValue: T;
22
+ /** Stable identity for the slot. Must be unique within a client instance. */
23
+ readonly key: string;
24
+ }
25
+ /**
26
+ * Create a typed {@link ClientQueryRef}. Call once per slot at module scope
27
+ * (or inside a component module) — the ref object is the stable identity.
28
+ * @example
29
+ * ```ts
30
+ * // lunora/client-queries.ts
31
+ * import { createClientQuery } from "@lunora/client";
32
+ *
33
+ * export const sidebarOpen = createClientQuery("sidebarOpen", true);
34
+ * export const selectedMessageId = createClientQuery("selectedMessageId", undefined as string | undefined);
35
+ * ```
36
+ */
37
+ declare const createClientQuery: <T>(key: string, defaultValue: T) => ClientQueryRef<T>;
38
+ /**
39
+ * The machine-readable error codes a client can observe on a failed
40
+ * RPC/batch/subscription. Mirrors the server's `CODE_STATUS` keys
41
+ * (`@lunora/server`'s `error.ts`) by hand — the client is framework-neutral and
42
+ * must never import the server package (wrong dependency direction / would pull
43
+ * the server into the browser bundle). Keep this list in sync when a server code
44
+ * is added or removed (see the drift-guard note in the plan/maintenance docs).
45
+ */
46
+ declare const LUNORA_ERROR_CODES: readonly ["BAD_REQUEST", "CONFLICT", "COUNT_RLS_UNSUPPORTED", "FORBIDDEN", "INTERNAL_SERVER_ERROR", "MASK_UNSUPPORTED", "NOT_FOUND", "NOT_IMPLEMENTED", "RELATION_PREDICATE_UNSUPPORTED", "TOO_MANY_REQUESTS", "UNAUTHORIZED", "UNPROCESSABLE"];
47
+ /** A machine-readable error `code` the client may observe. Mirror of the server's `LunoraErrorCode`. */
48
+ type LunoraErrorCode = (typeof LUNORA_ERROR_CODES)[number];
49
+ /** Error code the server uses for optimistic-concurrency conflicts (HTTP 409). */
50
+ declare const CONFLICT_ERROR_CODE = "CONFLICT";
51
+ /**
52
+ * Whether an unknown rejection is an optimistic-concurrency conflict — the
53
+ * server lost a write race and the caller should refetch and retry (or surface
54
+ * the conflict). Structural check on the `code` property the client attaches
55
+ * when decoding the worker's `{ error: { code, message } }` envelope.
56
+ */
57
+ declare const isConflictError: (error: unknown) => error is Error & {
58
+ code: "CONFLICT";
59
+ };
60
+ /**
61
+ * Whether a rejection is an RLS/policy denial (`FORBIDDEN`, HTTP 403) — the
62
+ * caller is authenticated but not permitted to read/write the row. The most
63
+ * common per-call error a UI must handle in an RLS-first app.
64
+ */
65
+ declare const isForbiddenError: (error: unknown) => error is Error & {
66
+ code: "FORBIDDEN";
67
+ };
68
+ /** Whether a rejection is an authentication failure (`UNAUTHORIZED`, HTTP 401) — no/invalid identity. */
69
+ declare const isUnauthorizedError: (error: unknown) => error is Error & {
70
+ code: "UNAUTHORIZED";
71
+ };
72
+ /**
73
+ * Whether a rejection is a rate-limit denial (`TOO_MANY_REQUESTS`, HTTP 429).
74
+ * The retry hint (if the server sent one) is read with {@link getRetryAfterMs}.
75
+ */
76
+ declare const isRateLimitedError: (error: unknown) => error is Error & {
77
+ code: "TOO_MANY_REQUESTS";
78
+ };
79
+ /**
80
+ * Read the server's machine-readable `code` off a rejection, narrowed to the
81
+ * known {@link LunoraErrorCode} union. Returns `undefined` for a non-`Error`, a
82
+ * missing code, or an unrecognized code string (forward-compat server codes read
83
+ * as `undefined` here rather than being falsely narrowed).
84
+ */
85
+ declare const getErrorCode: (error: unknown) => LunoraErrorCode | undefined;
86
+ /**
87
+ * Read the rate-limit retry hint (`data.retryAfterMs`) off a
88
+ * `TOO_MANY_REQUESTS` rejection without hand-casting the `unknown` `data`
89
+ * payload. Returns the finite millisecond value the server sent, or `undefined`
90
+ * when absent/non-numeric. Pair with {@link isRateLimitedError}.
91
+ */
92
+ declare const getRetryAfterMs: (error: unknown) => number | undefined;
93
+ type SubscriptionCallback = (data: unknown) => void;
94
+ /** A subscription-scoped error the server pushed for this subscription id. */
95
+ interface SubscriptionError {
96
+ code?: string;
97
+ message: string;
98
+ }
99
+ type SubscriptionErrorCallback = (error: SubscriptionError) => void;
100
+ /**
101
+ * One active per-call optimistic transform layered onto a subscription. The
102
+ * displayed value is the authoritative {@link SubscriptionState.serverBase}
103
+ * folded through every layer's `transform`, in order — so an incoming server
104
+ * frame re-folds the still-pending layers onto the new base (rebasing) instead
105
+ * of clobbering them. A layer is dropped — gaplessly — once a `data`/`delta`
106
+ * frame whose `cursor >= commitCursor` arrives (its write is now reflected in
107
+ * `serverBase`); `commitCursor` is the CDC cursor the server echoed on the
108
+ * mutation's response, and stays `undefined` while the write is still queued/
109
+ * in-flight (so the overlay survives unrelated deltas until confirmed).
110
+ */
111
+ interface OptimisticLayer {
112
+ /** The committed CDC cursor (from the mutation response); `undefined` until confirmed. */
113
+ commitCursor?: number;
114
+ readonly id: symbol;
115
+ readonly transform: (current: unknown) => unknown;
116
+ }
117
+ interface SubscriptionState {
118
+ /** True once the server has acked the subscription on the current socket. */
119
+ acked: boolean;
120
+ readonly args: Record<string, unknown>;
121
+ /**
122
+ * Stable wire-key of `args` (`stableWireKey`), computed once at subscribe
123
+ * time. Cached so the optimistic-update fan-out can compare against a
124
+ * mutation's args key without re-serializing every subscription's args on
125
+ * every mutation.
126
+ */
127
+ readonly argsKey: string;
128
+ readonly callbacks: Set<SubscriptionCallback>;
129
+ /**
130
+ * Notified when a `settled` frame advances this subscription's watermark — a
131
+ * write touched the subscription's tables but the result was byte-identical,
132
+ * so the server suppressed the data frame. A `@lunora/db` list collection
133
+ * uses this to drop the optimistic overlay for the confirmed write.
134
+ *
135
+ * A SET (not a single slot) because `SubscriptionState` is SHARED across
136
+ * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
137
+ * collection may subscribe to a query a plain `useQuery` already opened, so
138
+ * each subscriber registers its own callback (mirroring `callbacks` /
139
+ * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
140
+ * `useQuery` consumers register nothing, leaving the set empty.
141
+ */
142
+ readonly checkpointCallbacks: Set<(watermark: {
143
+ checkpoint?: number;
144
+ mutationId?: number;
145
+ }) => void>;
146
+ /** Notified when the server rejects this subscription (e.g. admin auth). */
147
+ readonly errorCallbacks: Set<SubscriptionErrorCallback>;
148
+ readonly fn: FunctionReference;
149
+ readonly id: string;
150
+ /**
151
+ * The highest custom-mutator `mutationId` from this client the server has
152
+ * applied, captured from the last `settled` frame (the suppressed-list-frame
153
+ * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
154
+ * Absent until a `settled` frame arrives.
155
+ */
156
+ lastMutationId?: number;
157
+ /** Last known value, used to short-circuit `useQuery`-style consumers. */
158
+ lastValue: unknown;
159
+ /**
160
+ * Active per-call optimistic layers, in application order (see
161
+ * {@link OptimisticLayer}). Empty for subscriptions with no pending per-call
162
+ * optimistic write — the common case, where `lastValue` tracks `serverBase`
163
+ * exactly and behaviour is identical to a plain server-value assignment.
164
+ */
165
+ optimisticLayers: OptimisticLayer[];
166
+ /**
167
+ * The authoritative server value the optimistic layers fold onto — the value
168
+ * with NO optimistic overlay. Tracks `lastValue` exactly whenever no layers
169
+ * are active; diverges only while a per-call optimistic write is pending. A
170
+ * server frame updates this (and re-folds the layers); the durable read cache
171
+ * persists this, never the optimistic overlay.
172
+ */
173
+ serverBase: unknown;
174
+ /**
175
+ * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
176
+ * captured from the last `data`/`delta`/`resume` frame. Persisted to the
177
+ * durable read cache and replayed as `sinceSeq` on reconnect so the server
178
+ * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
179
+ * first cursor-stamped frame arrives.
180
+ */
181
+ serverCursor?: number;
182
+ /**
183
+ * The CDC `epoch` token the `serverCursor` belongs to, captured from the
184
+ * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
185
+ * only when the client is still on the same changelog timeline — a reset or
186
+ * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
187
+ * until the first epoch-stamped frame arrives.
188
+ */
189
+ serverEpoch?: string;
190
+ readonly shardKey?: string;
191
+ }
192
+ /**
193
+ * Active subscription registry. The client keys subscriptions by
194
+ * `(functionPath, stableWireKey(args), shardKey)` so duplicate calls share a
195
+ * single server-side registration. Args are stably encoded (keys sorted at every
196
+ * depth) so two structurally-equal arg records constructed with a different key
197
+ * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
198
+ * duplicate subscription. Encoding the args' **wire form** keeps the key
199
+ * byte-identical for pure-JSON args while giving wire-typed args (`bigint`,
200
+ * `Date`, bytes, …) distinct stable tokens instead of a throw.
201
+ */
202
+ declare class SubscriptionRegistry {
203
+ static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
204
+ private readonly byKey;
205
+ private readonly byId;
206
+ get(key: string): SubscriptionState | undefined;
207
+ getById(id: string): SubscriptionState | undefined;
208
+ add(state: SubscriptionState): void;
209
+ remove(state: SubscriptionState): void;
210
+ all(): SubscriptionState[];
211
+ }
212
+ /**
213
+ * Read/write handle over the client's live query cache, handed to a mutation's
214
+ * `withOptimisticUpdate` callback so a single mutation can optimistically patch
215
+ * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
216
+ *
217
+ * `getQuery` reads the current value (server value or any still-pending
218
+ * optimistic override) of a subscribed query; `setQuery` registers a constant
219
+ * optimistic layer on top. The whole batch rebases onto incoming deltas and
220
+ * settles together — confirmed on the mutation's commit cursor, or rolled back
221
+ * on failure — the same per-subscription layer machinery the single-query
222
+ * per-call `optimistic` transform uses, generalized to N queries.
223
+ */
224
+ interface OptimisticLocalStore {
225
+ /**
226
+ * Every loaded subscription on `function_`, regardless of args, paired with
227
+ * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
228
+ * when a write must patch every variant of a list query (all channels,
229
+ * all filters) without enumerating their args up front.
230
+ */
231
+ getAllQueries: <F extends FunctionReference>(function_: F) => {
232
+ args: ArgsOf<F>;
233
+ value: ReturnOf<F> | undefined;
234
+ }[];
235
+ /**
236
+ * Current cached value for the subscribed `(function_, args)` query, or
237
+ * `undefined` when nothing is subscribed/loaded for it. Reflects any
238
+ * optimistic override already written in this batch.
239
+ */
240
+ getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
241
+ /**
242
+ * Write an optimistic override for the subscribed `(function_, args)`
243
+ * query. A no-op (returns without effect) when no subscription matches —
244
+ * mirroring Convex, where you only patch queries the page is watching.
245
+ */
246
+ setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
247
+ }
248
+ /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
249
+ type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
250
+ /**
251
+ * Build an {@link OptimisticLocalStore} bound to a subscription registry and the
252
+ * mutation's shard key. Each `setQuery(value)` registers a constant-value layer
253
+ * on its target subscription (via `applyOptimisticLayer`): the predicted value
254
+ * survives incoming server deltas (re-clamped, masking concurrent changes to that
255
+ * query — not merged) and drops gaplessly on the mutation's commit cursor, like
256
+ * the single-query per-call `optimistic` path. Returns the store plus the ordered
257
+ * `confirm` (success) and `rollback` (failure) closures every `setQuery` produced,
258
+ * so the caller settles the whole batch when the mutation does.
259
+ */
260
+ declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined) => {
261
+ confirms: ((commitCursor: number | undefined) => void)[];
262
+ rollbacks: (() => void)[];
263
+ store: OptimisticLocalStore;
264
+ };
265
+ declare const DEFAULT_MAX_BUFFER = 1024;
266
+ interface StreamHandle<T = unknown> {
267
+ /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
268
+ readonly complete: () => void;
269
+ /** Surface an error to any pending consumer; subsequent pushes are dropped. */
270
+ readonly fail: (error: Error) => void;
271
+ /**
272
+ * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
273
+ * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
274
+ * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
275
+ * the producer never sees a thrown exception.
276
+ */
277
+ readonly push: (value: T) => void;
278
+ }
279
+ interface StreamIterable<T> extends AsyncIterable<T> {
280
+ /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
281
+ cancel: () => void;
282
+ }
283
+ /**
284
+ * Build a stream handle paired with an async-iterable. The handle is the
285
+ * server-driven side (the WS dispatcher pushes chunks / completes / errors);
286
+ * the iterable is what the user awaits. `onCancel` is invoked exactly once
287
+ * when the consumer calls `.cancel()` (or `.return()`) so the client can
288
+ * send a `{type:"unsubscribe"}` frame to the server.
289
+ */
290
+ declare const createStream: <T>(options: {
291
+ maxBuffer?: number;
292
+ onCancel: () => void;
293
+ }) => {
294
+ handle: StreamHandle<T>;
295
+ iterable: StreamIterable<T>;
296
+ };
297
+ type WSState = "idle" | "connecting" | "open" | "closed";
298
+ /**
299
+ * Aggregate live-socket health across every shard connection, for a UI status
300
+ * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
301
+ * is (re)connecting and none is open; `connected` = at least one socket is open;
302
+ * `offline` = sockets exist but all are down (between reconnect attempts).
303
+ */
304
+ type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
305
+ /** One shard's socket + watermark state in a {@link LunoraClient.debug} snapshot. */
306
+ interface ClientDebugShard {
307
+ /**
308
+ * Highest custom-mutator watermark the server has echoed for this client on this
309
+ * shard. A write whose `clientSeq` is above this has been sent but not confirmed
310
+ * — the first thing to check when an optimistic overlay won't clear.
311
+ */
312
+ confirmedMutationWatermark: number;
313
+ /** Whether a `WebSocket` object currently exists (distinct from it being open). */
314
+ hasSocket: boolean;
315
+ /** `undefined` for the default (unsharded) connection. */
316
+ shardKey: string | undefined;
317
+ /** Whether this shard's socket has ever completed a handshake — gates offline queueing. */
318
+ wasEverConnected: boolean;
319
+ wsState: WSState;
320
+ }
321
+ /** One live query or shape subscription in a {@link LunoraClient.debug} snapshot. */
322
+ interface ClientDebugSubscription {
323
+ /** Whether the server has acknowledged the subscription on the current socket. */
324
+ acked: boolean;
325
+ /** `namespace:fn` for a query, `shape:<name>` for a replication shape. */
326
+ functionPath: string;
327
+ id: string;
328
+ kind: "query" | "shape";
329
+ /** Highest custom-mutator watermark echoed on THIS subscription (absent until a `settled`/poke frame arrives). */
330
+ lastMutationId?: number;
331
+ /** Per-call optimistic layers still folded onto this subscription's value — a non-zero count with no pending write is a leak. */
332
+ pendingOptimisticLayers: number;
333
+ /** Replicated rowset size (shapes only). */
334
+ rowCount?: number;
335
+ /** The `__cdc_log` cursor the current value reflects. */
336
+ serverCursor?: number;
337
+ shardKey: string | undefined;
338
+ /** How many callers share this subscription (subscriptions are deduped by `(fn, args, shard)`). */
339
+ subscriberCount: number;
340
+ }
341
+ /**
342
+ * Everything the sync engine believes at one instant — see
343
+ * {@link LunoraClient.debug} for why this exists.
344
+ */
345
+ interface ClientDebugSnapshot {
346
+ /** The watermark key the server's custom-mutator protocol advances per `clientSeq`. */
347
+ clientId: string;
348
+ closed: boolean;
349
+ connectionStatus: ConnectionStatus;
350
+ /** Writes waiting in the built-in offline queue (not the `@lunora/db` outbox). */
351
+ pendingWrites: number;
352
+ shards: ClientDebugShard[];
353
+ subscriptions: ClientDebugSubscription[];
354
+ }
355
+ /**
356
+ * Terminal verdict for a mutation that passed through the offline queue,
357
+ * delivered to {@link LunoraClient.onMutationSettled}.
358
+ *
359
+ * Unlike the Promise returned by {@link LunoraClient.mutation} — which only the
360
+ * original caller can await, and which no longer exists after a reload — this
361
+ * fires for *every* queued write the server (or the queue) reaches a verdict on,
362
+ * including writes restored from durable storage in a later session. It is the
363
+ * channel a UI uses to tell the user "your queued change couldn't be saved"
364
+ * instead of silently dropping a rolled-back optimistic row.
365
+ *
366
+ * `status: "rejected"` carries the failure `code` (e.g. `CONFLICT`,
367
+ * `OFFLINE_QUEUE_OVERFLOW`, `OFFLINE_IDENTITY_CHANGED`) and the `error`.
368
+ * `hadAwaiter` is `false` for a write whose original `mutation()` Promise is
369
+ * gone (a hydrated/post-reload replay or an eviction), so a listener can tell
370
+ * "the caller already saw this" apart from "nothing else will report this".
371
+ */
372
+ interface MutationSettledEvent {
373
+ /** The write's args, so a listener can describe or re-offer the change. */
374
+ readonly args: Record<string, unknown>;
375
+ /** Server/queue error code on `rejected` (e.g. `CONFLICT`), when present. */
376
+ readonly code?: string;
377
+ /** The rejection error on `status: "rejected"`. */
378
+ readonly error?: unknown;
379
+ /** The `<file>:<function>` reference of the mutation. */
380
+ readonly functionPath: string;
381
+ /** Whether a live caller was still awaiting this write's `mutation()` Promise. */
382
+ readonly hadAwaiter: boolean;
383
+ /** The write's stable id (idempotency key / queue id). */
384
+ readonly id: string;
385
+ /** Shard the write targeted, if any. */
386
+ readonly shardKey?: string;
387
+ /** Terminal outcome. */
388
+ readonly status: "committed" | "rejected";
389
+ }
390
+ /**
391
+ * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
392
+ * machinery plus `shardKey`. Exported (at the end of this file) so the framework
393
+ * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
394
+ * `mutate(args, options?)` against one canonical definition instead of
395
+ * re-declaring it.
396
+ */
397
+ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
398
+ /**
399
+ * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
400
+ * durable outbox replay a committed-but-unacked write under its *original* key
401
+ * so the server dedups it instead of applying it twice. Omit for normal calls —
402
+ * each then gets a fresh key.
403
+ */
404
+ mutationId?: string;
405
+ optimistic?: (current: TCurrent | undefined) => TValue;
406
+ /**
407
+ * Convex-parity multi-query optimistic update. Receives an
408
+ * `OptimisticLocalStore` over the live subscription cache plus the
409
+ * mutation's args, so one mutation can patch many subscribed queries at
410
+ * once; every write is rolled back atomically if the mutation fails.
411
+ */
412
+ optimisticUpdate?: OptimisticUpdate<TArgs>;
413
+ /**
414
+ * Sync predicate evaluated just before the offline queue replays this
415
+ * write on reconnect. When it returns `false` the mutation is dropped
416
+ * instead of replayed — use it to guard against replaying writes whose
417
+ * assumptions are no longer valid (e.g. the document it referred to was
418
+ * deleted by another client while this tab was offline).
419
+ */
420
+ precondition?: () => boolean;
421
+ shardKey?: string;
422
+ }
423
+ /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
424
+ type ShapeCallback = (rows: Record<string, unknown>[]) => void;
425
+ /**
426
+ * The high-water marks a shape poke has now synced to the client: `checkpoint`
427
+ * is the op-log cursor and `mutationId` the highest custom-mutator id the server
428
+ * echoed for this client. A `@lunora/db` collection feeds these into its
429
+ * checkpoint registry to drop optimistic overlays once the server's authoritative
430
+ * rows have landed.
431
+ */
432
+ interface SyncWatermark {
433
+ checkpoint?: number;
434
+ mutationId?: number;
435
+ }
436
+ /**
437
+ * An `Error` carrying the server's machine-readable `code` and (for a
438
+ * `LunoraError`) structured `data`, plus an optional actionable `hint` (Markdown)
439
+ * and `docsUrl` resolved from the central error catalog. The client's public
440
+ * error contract for RPC/batch failures — a UI can render `hint`/`docsUrl` to
441
+ * tell the user how to fix the error. The `(string & {})` arm keeps
442
+ * forward-compat/unknown server codes assignable without losing autocomplete on
443
+ * the known {@link LunoraErrorCode} union.
444
+ */
445
+ type LunoraClientError = Error & {
446
+ code?: LunoraErrorCode | (string & {});
447
+ data?: unknown;
448
+ docsUrl?: string;
449
+ hint?: string | string[];
450
+ };
451
+ /** One demuxed result slot of a {@link LunoraClient.batch} call (plan 088). */
452
+ type BatchSlot = {
453
+ error: LunoraClientError;
454
+ ok: false;
455
+ } | {
456
+ ok: true;
457
+ value: unknown;
458
+ };
459
+ /**
460
+ * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
461
+ * a single multiplexed WebSocket.
462
+ *
463
+ * Reconnect, offline queueing, and optimistic updates are all handled here;
464
+ * see the package README for the wire protocol.
465
+ */
466
+ declare class LunoraClient {
467
+ /** 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. */
468
+ private static readonly MAX_POKE_BUFFERS;
469
+ /**
470
+ * Create a typed {@link ClientQueryRef}. Convenience wrapper around
471
+ * {@link createClientQuery} so you don't need a separate import.
472
+ * @example
473
+ * ```ts
474
+ * const sidebarOpen = LunoraClient.createClientQuery("sidebarOpen", true);
475
+ * ```
476
+ */
477
+ static createClientQuery<T>(key: string, defaultValue: T): ClientQueryRef<T>;
478
+ readonly url: string;
479
+ readonly wsUrl: string;
480
+ /** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
481
+ private readonly clientQueryStore;
482
+ private wsToken;
483
+ /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
484
+ private readonly authBasePath;
485
+ private readonly fetchImpl;
486
+ private readonly WebSocketImpl;
487
+ private readonly bookmark;
488
+ private readonly reconnectOptions;
489
+ /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
490
+ private readonly connectTimeoutMs;
491
+ /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
492
+ private readonly heartbeatIntervalMs;
493
+ private readonly offlineQueue;
494
+ /**
495
+ * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
496
+ * set, offline writes are delegated here and the built-in {@link OfflineQueue}
497
+ * is bypassed, so a db app has exactly one durable write path.
498
+ */
499
+ private readonly outbox;
500
+ /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
501
+ private readonly clientId;
502
+ /**
503
+ * Highest CDC cursor this client has seen a write commit at, per shard key
504
+ * (`""` for the default shard) — the read-your-writes bookmark sent as
505
+ * `x-lunora-min-seq`.
506
+ *
507
+ * In memory only, and deliberately: it exists to keep THIS session's reads
508
+ * behind THIS session's writes. Persisting it across reloads would pin a
509
+ * fresh page to a cursor it has no reason to require and force needless
510
+ * fallbacks to the owner.
511
+ */
512
+ private readonly shardCursors;
513
+ /**
514
+ * The server's own name for the default shard (`defaultShardKey`), learned
515
+ * from the first response to a call that named no shard. `undefined` until
516
+ * then, which is why `cursorKeyFor` falls back to a placeholder entry that
517
+ * `learnDefaultShardKey` folds in once the name arrives.
518
+ */
519
+ private defaultShardKey;
520
+ /**
521
+ * `true` when the constructor's hydration microtask has finished loading the
522
+ * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
523
+ * the cache is ready for synchronous `peekHydratedQuery` reads.
524
+ */
525
+ private readyResolved;
526
+ /** Resolvers for `whenReady()` — called once hydration completes. */
527
+ private readyResolve;
528
+ /**
529
+ * Promise that resolves once the durable read cache has been loaded. When
530
+ * `hydrateOnStart` is not set or no query cache is configured, resolves
531
+ * immediately (the constructor creates an already-resolved promise).
532
+ */
533
+ private readonly readyPromise;
534
+ /**
535
+ * Highest custom-mutator watermark the server has echoed for this client,
536
+ * nested by identity fingerprint (`identityFingerprint() ?? ""`) then shard
537
+ * bucket (`shardKey ?? ""`) — the DO tracks one `__client_watermark` per
538
+ * `(identity, clientId)` pair, not per bucket alone, so a bucket-only key
539
+ * would let a user switch claim the previous identity's sequence and wedge
540
+ * every push on `OUT_OF_ORDER` until a reload (plan 316). A nested map
541
+ * (rather than a single map composite-keyed by a joined string) is what a
542
+ * previous fix here tried and got wrong: an identity fingerprint or a
543
+ * `shardKey` is an arbitrary string, so any string delimiter — even one as
544
+ * exotic as U+FFFD — can appear in one operand and collide with the other
545
+ * (a fingerprint of `a<SEP>x` + bucket `y` joins to the same string as
546
+ * a fingerprint of `a` + bucket `x<SEP>y`), mixing two identities' watermarks.
547
+ * The nested map has no join step, so there is no delimiter to collide.
548
+ * `callMutator` bumps it from every ack; the `@lunora/db` mutator runtime
549
+ * seeds its `clientSeq` generator from it so a reload (which resets the
550
+ * in-memory counter) never reissues a stale sequence the server would
551
+ * silently swallow as a replay.
552
+ */
553
+ private readonly clientWatermarks;
554
+ /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
555
+ private outboxMutationCounter;
556
+ private readonly onPersistenceError;
557
+ private readonly persistence;
558
+ /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
559
+ private readonly persistenceVersion;
560
+ /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
561
+ private outboxLeaderRelease;
562
+ /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
563
+ private readonly queryCache;
564
+ /**
565
+ * Values restored from the `queryCache` at construction, keyed by the
566
+ * read-cache key, awaiting the `subscribe()` that will consume them. A
567
+ * key is consumed (deleted) the first time its subscription is created, so
568
+ * the cache only ever seeds the initial value — live frames take over after.
569
+ */
570
+ private readonly hydratedQueryCache;
571
+ /**
572
+ * Coalesced read-cache writes: the latest value per key, flushed to
573
+ * the `queryCache` on a short debounce so a burst of deltas persists once.
574
+ */
575
+ private readonly pendingCacheWrites;
576
+ private cacheFlushTimer;
577
+ private readonly subscriptions;
578
+ /**
579
+ * Cross-tab coordinator; created only when `crossTabSync: true`. When the
580
+ * client is not the elected leader, all WebSocket operations are skipped.
581
+ * Not `readonly` — `close()` clears it (mirrors `outboxLeaderRelease`).
582
+ */
583
+ private tabCoordinator;
584
+ /**
585
+ * The leader's last-broadcast aggregate {@link ConnectionStatus}, mirrored
586
+ * on a follower tab — which owns no `ShardConnection` of its own to
587
+ * compute a status from (see `computeStatus`). `undefined` until the
588
+ * leader's first broadcast (falls back to `"idle"`), and reset back to
589
+ * `undefined` whenever this tab stops being a follower of the CURRENT
590
+ * leader (becomes leader itself, or the leader changes), so a stale
591
+ * mirror from a previous leader never survives a leadership change.
592
+ */
593
+ private leaderStatus;
594
+ /**
595
+ * Sticky "has the mirrored leader status ever reported `connected`" flag —
596
+ * the follower's counterpart to {@link ShardConnection.wasEverConnected},
597
+ * since a follower has no `ShardConnection` of its own. Feeds the
598
+ * offline-queue gate (see `mutation`) exactly like the real per-shard flag
599
+ * does on the leader/single-tab path.
600
+ */
601
+ private leaderWasEverConnected;
602
+ /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
603
+ private readonly connections;
604
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
605
+ private readonly defaultConnectionContext;
606
+ /**
607
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
608
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
609
+ * on every socket open so it replays across reconnects, and forwarded to the
610
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
611
+ * imperative (last-writer-wins) override; refcounted holders registered via
612
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
613
+ * precedence — see `effectiveConnectionContext`.
614
+ */
615
+ private readonly connectionContexts;
616
+ /**
617
+ * Per-shard stack of refcounted connection-context holders (keyed by
618
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
619
+ * is an opaque token carrying its `context`; the most-recently acquired
620
+ * holder wins (last-writer-wins among live holders), and the context is only
621
+ * cleared for a shard once its last holder releases — so two concurrently
622
+ * mounted presence hooks on the same shard can't stomp each other's context
623
+ * on cleanup. A holder is identified by reference identity so a release
624
+ * removes exactly the right one regardless of stack position.
625
+ */
626
+ private readonly connectionContextHolders;
627
+ private authToken;
628
+ /**
629
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
630
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
631
+ * like an identity change (which would discard queued writes). `undefined` =
632
+ * not supplied, so identity falls back to a hash of the raw token. See
633
+ * `setAuthToken` / `identityFingerprint`.
634
+ */
635
+ private authSubject;
636
+ /**
637
+ * Identity stamp recorded against each queued offline mutation, keyed by
638
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
639
+ * in effect at the time, and re-checked at flush so a queued write can
640
+ * never replay under a different identity than the one that issued it.
641
+ * See `identityFingerprint` for the fingerprint shape.
642
+ */
643
+ private readonly queuedIdentities;
644
+ /**
645
+ * Distinct shard keys with a mutation currently sitting in `offlineQueue`
646
+ * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
647
+ * restored from durable storage (`hydratePersistedQueue`). A follower tab
648
+ * has no per-shard `ShardConnection` to iterate when its mirrored leader
649
+ * status turns `"connected"` (see the `onConnectionStatus` coordinator
650
+ * option), so this is what that flush walks instead. Entries are never
651
+ * removed — flushing an already-empty shard is a cheap no-op, and the set
652
+ * is bounded by the app's own distinct shard-key cardinality.
653
+ */
654
+ private readonly queuedOfflineShardKeys;
655
+ private closed;
656
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
657
+ private readonly authTokenListeners;
658
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
659
+ private readonly statusListeners;
660
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
661
+ private readonly tokenExpiredListeners;
662
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
663
+ private readonly mutationSettledListeners;
664
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
665
+ private readonly pendingChangeListeners;
666
+ /**
667
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
668
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
669
+ * (re)connect so a topic survives a socket bounce.
670
+ */
671
+ private readonly whisperHandlers;
672
+ /** Last status broadcast, so we only notify listeners on an actual change. */
673
+ private lastStatus;
674
+ private nextSubId;
675
+ private nextStreamId;
676
+ /**
677
+ * In-flight client-side stream readers, keyed by the stream id sent on the
678
+ * wire. The handle drives the underlying iterator queue and `shardKey`
679
+ * tells us which socket to push the cancel frame onto when the consumer
680
+ * calls `.cancel()` or the iterator is garbage-collected.
681
+ */
682
+ private readonly streams;
683
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
684
+ private readonly shapeSubscriptions;
685
+ /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
686
+ private readonly pokeBuffers;
687
+ private nextShapeId;
688
+ constructor(options: LunoraClientOptions);
689
+ /**
690
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
691
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
692
+ * sync across all mounted instances.
693
+ *
694
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
695
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
696
+ * doesn't read as an identity change and discard queued writes. The subject is
697
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
698
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
699
+ * `setAuthToken(token, user.id)` retains the identity. Pass `null` to clear it
700
+ * (an explicit sign-out). Establishing the subject for the first time on an
701
+ * UNCHANGED token (e.g. the user id resolves a tick after the token was set)
702
+ * re-stamps any in-flight queued writes rather than dropping them — same
703
+ * credential, just a more stable label. A real user switch (the token AND
704
+ * subject both change) still drops the previous user's writes.
705
+ *
706
+ * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
707
+ * time and lives in the URL. To refresh live WS auth, call
708
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
709
+ * force a reconnect with the new credential.
710
+ */
711
+ setAuthToken(token: string | null, subject?: string | null): void;
712
+ getAuthToken(): string | null;
713
+ /**
714
+ * The current identity fingerprint (the same stamp queued offline writes
715
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
716
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
717
+ * can drop a persisted write whose captured `identity` no longer matches the
718
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
719
+ */
720
+ currentIdentity(): string | null;
721
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
722
+ clientIdentifier(): string;
723
+ /**
724
+ * The highest custom-mutator watermark the server has echoed for this client
725
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
726
+ * its `clientSeq` generator from this so a reload never reissues a sequence
727
+ * the server has already applied (which it would swallow as a replay, silently
728
+ * dropping the write).
729
+ */
730
+ confirmedMutationWatermark(shardKey?: string): number;
731
+ /**
732
+ * Push a custom mutator to its authoritative server impl over the watermark
733
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
734
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
735
+ * client's `__client_watermark`.
736
+ *
737
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
738
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
739
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
740
+ * A `false` verdict tells the caller to reissue above the now-known watermark
741
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
742
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
743
+ *
744
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
745
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
746
+ */
747
+ callMutator(functionPath: string, args: Record<string, unknown>, options?: {
748
+ clientSeq?: number;
749
+ shardKey?: string;
750
+ }): Promise<{
751
+ applied: boolean;
752
+ result: unknown;
753
+ }>;
754
+ /**
755
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
756
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
757
+ * the current value.
758
+ */
759
+ onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
760
+ /**
761
+ * Fetch the currently authenticated user from better-auth's `get-session`
762
+ * endpoint, returning the `user` record or `null` when signed out. Sends
763
+ * the stored bearer token (if any) and `credentials: "include"` so a
764
+ * cookie-session is also honoured. A network/parse failure or a non-OK
765
+ * response resolves to `null` rather than throwing — callers treat "couldn't
766
+ * resolve identity" as "signed out".
767
+ *
768
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
769
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
770
+ */
771
+ getCurrentUser(): Promise<User | null>;
772
+ /**
773
+ * Replace the token appended to WS upgrade URLs as `?token=…` and close
774
+ * every open shard socket so the reconnect picks up the new value. Call
775
+ * this whenever the user's WS credential changes (rotating the admin token
776
+ * in the studio, switching workspaces, etc.). Accepts a static string or a
777
+ * {@link WsTokenProvider} resolved fresh at every (re)connect — the channel
778
+ * for short-lived credentials like the minted ephemeral admin sub-token.
779
+ * Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
780
+ */
781
+ setWsToken(token: string | undefined | WsTokenProvider): void;
782
+ /**
783
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
784
+ * envelope for a shard's socket, overriding the client-wide
785
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
786
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
787
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
788
+ * presence row is removed the instant the socket drops, with no TTL lag.
789
+ *
790
+ * Stored per shard and replayed on every (re)connect. When a socket for the
791
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
792
+ * server sees the new context without waiting for a reconnect.
793
+ */
794
+ setConnectionContext(context: Record<string, unknown> | undefined, options?: {
795
+ shardKey?: string;
796
+ }): void;
797
+ /**
798
+ * Refcounted variant of {@link setConnectionContext}: register a connection
799
+ * `context` for a shard and get back a release function. Unlike the imperative
800
+ * setter, the context is only cleared once the *last* acquired holder releases
801
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
802
+ * shard no longer clobber each other's context when one of them unmounts. The
803
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
804
+ * the top holder falls back to the previous one rather than clearing.
805
+ *
806
+ * With a single holder the behaviour is identical to a
807
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
808
+ * Releasing more than once is a no-op (the holder is matched by reference, so
809
+ * a double release can't drop a different holder).
810
+ */
811
+ acquireConnectionContext(context: Record<string, unknown>, options?: {
812
+ shardKey?: string;
813
+ }): Unsubscribe;
814
+ /**
815
+ * Join a whisper `topic` and receive every ephemeral message other members
816
+ * broadcast to it on the same shard (typing indicators, live cursors,
817
+ * presence pings). Whispers never touch the server's durable state — there's
818
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
819
+ * is left on the server once its last local handler unsubscribes.
820
+ *
821
+ * `handler` receives the raw `data` and the sender's verified `from` user id
822
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
823
+ * (the default shard when omitted) — use the same shard you target with the
824
+ * matching queries/mutations so members land on the same Durable Object.
825
+ *
826
+ * Security: whisper topics are NOT access-controlled beyond the shard
827
+ * boundary — any client that can open a socket to the shard can join, read,
828
+ * and inject on any topic name. `from` is server-stamped and unforgeable, but
829
+ * do not put data on a whisper topic that some shard members shouldn't see,
830
+ * and don't trust a whisper's `data` as authorization. Use a query/mutation
831
+ * (with RLS) for anything privileged; whispers are for transient awareness.
832
+ */
833
+ whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
834
+ shardKey?: string;
835
+ }): Unsubscribe;
836
+ /**
837
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
838
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
839
+ * dropped when the shard socket isn't open (whispers are transient, never
840
+ * queued), and the server silently drops it if the sender exceeds its
841
+ * whisper rate budget. The sender never receives its own whisper. Omitting
842
+ * `data` delivers JSON `null` to receivers (not `undefined`).
843
+ */
844
+ whisper(topic: string, data?: unknown, options?: {
845
+ shardKey?: string;
846
+ }): void;
847
+ /**
848
+ * Subscribe to token-expiry events: invoked whenever the server drops a
849
+ * shard socket because the connection's credential lapsed (close code
850
+ * `4001`). The client already reconnects automatically (re-resolving
851
+ * identity from the cookie/token in effect); use this to refresh a
852
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
853
+ * with a freshly minted one. Returns an unsubscribe function.
854
+ */
855
+ onTokenExpired(listener: () => void): Unsubscribe;
856
+ /**
857
+ * Current aggregate live-socket status across all shard connections. See
858
+ * {@link ConnectionStatus}.
859
+ */
860
+ connectionStatus(): ConnectionStatus;
861
+ /**
862
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
863
+ * immediately with the current status, then on every transition. Returns an
864
+ * unsubscribe function.
865
+ */
866
+ onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
867
+ /**
868
+ * Number of offline writes waiting in the built-in queue to be sent — the
869
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
870
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
871
+ * A `@lunora/db` app whose writes ride the unified outbox should read
872
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
873
+ */
874
+ pendingCount(): number;
875
+ /**
876
+ * A point-in-time snapshot of everything the sync engine believes right now:
877
+ * per-shard sockets and watermarks, every live query and shape subscription with
878
+ * its cursor and ack state, and the offline-queue depth.
879
+ *
880
+ * This exists because the alternative is `console.log`. When an optimistic
881
+ * overlay doesn't clear, the questions are always the same — *is the socket open?
882
+ * what watermark has the server confirmed for this shard? has this shape been
883
+ * poked since my write? is anything stuck in the queue?* — and none of them were
884
+ * answerable from outside the client, so every adopter ends up instrumenting the
885
+ * library by hand or building a bespoke policy layer around a symptom.
886
+ *
887
+ * Read it from a devtools console, log it next to a bug report, or render it in a
888
+ * debug panel. Pull-only and allocation-cheap; nothing here is reactive, so poll
889
+ * it or read it on demand.
890
+ *
891
+ * ```ts
892
+ * const { shards, subscriptions } = client.debug();
893
+ * // shards: [{ shardKey: "user-1", wsState: "open", confirmedMutationWatermark: 42, … }]
894
+ * ```
895
+ */
896
+ debug(): ClientDebugSnapshot;
897
+ /**
898
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
899
+ * with the current count, then whenever the queue depth changes (a write is
900
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
901
+ */
902
+ onPendingChange(listener: (pending: number) => void): Unsubscribe;
903
+ /**
904
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
905
+ * fires once per queued write that commits or is rejected — including a write
906
+ * restored from durable storage after a reload, whose original `mutation()`
907
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
908
+ * evicts on overflow or discards on an identity change. This is the durable
909
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
910
+ * mutation that never queued still surfaces through the Promise `mutation()`
911
+ * returns. The listener is NOT invoked on registration. Returns an
912
+ * unsubscribe function. See {@link MutationSettledEvent}.
913
+ */
914
+ onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
915
+ /**
916
+ * The `WebSocket` implementation this client was constructed with (an
917
+ * explicit `options.WebSocket`, or the ambient global on platforms that have
918
+ * one) — `undefined` if neither is available. This is the seam a feature
919
+ * that opens its OWN socket outside the client's multiplexed connection
920
+ * (e.g. a voice-agent hook) should default to, instead of reaching for
921
+ * `globalThis.WebSocket` directly: on React Native the client wraps this
922
+ * constructor to inject the auth-headers factory's credential onto the
923
+ * upgrade request (`createLunoraClient`'s `withAuthWebSocket`), which a raw
924
+ * `new globalThis.WebSocket(url)` would silently bypass.
925
+ */
926
+ getWebSocketImpl(): typeof WebSocket | undefined;
927
+ /**
928
+ * Read the current value for a {@link ClientQueryRef}. Returns
929
+ * `ref.defaultValue` when no value has been explicitly set.
930
+ */
931
+ getClientQuery<T>(ref: ClientQueryRef<T>): T;
932
+ /**
933
+ * Set a new value for `ref` and notify every subscriber. Pass `undefined`
934
+ * to reset the slot to `ref.defaultValue`.
935
+ */
936
+ setClientQuery<T>(ref: ClientQueryRef<T>, value: T): void;
937
+ /**
938
+ * Subscribe to changes for `ref`. The callback is NOT invoked on
939
+ * registration — call {@link getClientQuery} for the current value.
940
+ * Returns an unsubscribe function.
941
+ */
942
+ subscribeClientQuery(ref: ClientQueryRef, callback: (value: unknown) => void): Unsubscribe;
943
+ /**
944
+ * Reset a {@link ClientQueryRef} to its default value, notifying every
945
+ * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
946
+ * removes the stored entry so a future {@link getClientQuery} returns
947
+ * the default rather than an explicitly-set value.
948
+ */
949
+ resetClientQuery(ref: ClientQueryRef): void;
950
+ /**
951
+ * Capture a snapshot of the current live query value at call time and
952
+ * produce a `() => boolean` precondition that compares it against the
953
+ * value at replay time (on queue drain / reconnect).
954
+ *
955
+ * When the precondition is checked it re-reads the query's current value
956
+ * via `peekActiveQueryValue`. If the value differs from what was
957
+ * captured at call time the precondition returns `false` and the offline
958
+ * mutation is dropped as stale.
959
+ *
960
+ * This is a method wrapper around `createSnapshotPrecondition` that
961
+ * binds the client instance for you — no need to pass `client` explicitly.
962
+ * @example
963
+ * ```ts
964
+ * client.mutation(api.todos.update, { id, text }, {
965
+ * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
966
+ * });
967
+ * ```
968
+ */
969
+ snapshotPrecondition(functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string): () => boolean;
970
+ /**
971
+ * Resolves once the durable read cache has been loaded into memory. When
972
+ * `hydrateOnStart` is not configured or no query cache adapter is active,
973
+ * returns an already-resolved promise so callers can always await it
974
+ * unconditionally.
975
+ *
976
+ * Framework adapters (React, Vue, etc.) use this to gate the first
977
+ * (enabled) render of a live query behind hydration, so the user sees
978
+ * cached data instead of an undefined flash before the socket round-trip.
979
+ */
980
+ whenReady(): Promise<void>;
981
+ /**
982
+ * Synchronously reports whether {@link whenReady} has already resolved (the
983
+ * durable read cache is loaded, or none is configured). Framework adapters
984
+ * read this to seed the hydration-gate state on the first render without
985
+ * awaiting, then subscribe via {@link whenReady} for the pending case.
986
+ */
987
+ get isReady(): boolean;
988
+ /**
989
+ * Synchronously peek at a value the durable read cache loaded for the given
990
+ * function path + args + shard key. Returns `undefined` when:
991
+ *
992
+ * - No query cache adapter is configured.
993
+ * - Hydration hasn't completed yet (race — await {@link whenReady} first).
994
+ * - The cached value's identity fingerprint doesn't match the current auth.
995
+ *
996
+ * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
997
+ * the cached entry stays in `hydratedQueryCache` so the subscription created
998
+ * later by {@link subscribe} consumes it normally.
999
+ */
1000
+ peekHydratedQuery(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
1001
+ /**
1002
+ * Peek at the **current live value** of an active subscription, if one
1003
+ * exists. Returns the subscription's `lastValue` (which includes any
1004
+ * optimistic overlay) or `undefined` if no subscription is active for the
1005
+ * given `(functionPath, args, shardKey)`.
1006
+ *
1007
+ * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
1008
+ * and is independent of active subscriptions), this method reflects the
1009
+ * current in-memory state of an already-opened subscription — useful for
1010
+ * offline mutation preconditions that need to snapshot the value at call time
1011
+ * and compare it at replay time.
1012
+ */
1013
+ peekActiveQueryValue(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
1014
+ query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1015
+ shardKey?: string;
1016
+ }): Promise<ReturnOf<F>>;
1017
+ /**
1018
+ * Batch several independent calls into ONE round trip (plan 088). Each call is
1019
+ * dispatched server-side exactly as an individual RPC — per-shard
1020
+ * authorization, `(identity, mutationId)` idempotency, and custom-mutator
1021
+ * watermark ordering are all preserved — and the worker splits the batch by
1022
+ * shard so calls to different shards fan out to their own DOs. Results are
1023
+ * demuxed back in input order; a failing call does NOT fail the batch (its
1024
+ * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
1025
+ * a single call). Args/results ride the value codec (bytes/bigint survive).
1026
+ *
1027
+ * No promise pipelining and no capability passing — a call's args cannot
1028
+ * reference another call's result (see plan 088 §fence; capabilities are
1029
+ * incompatible with DO hibernation).
1030
+ */
1031
+ batch(calls: ReadonlyArray<{
1032
+ args?: Record<string, unknown>;
1033
+ fn: FunctionReference;
1034
+ shardKey?: string;
1035
+ }>): Promise<BatchSlot[]>;
1036
+ /**
1037
+ * Invoke a mutation. Errors propagate as rejections.
1038
+ *
1039
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
1040
+ * only when the targeted shard's socket was open at least once already
1041
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
1042
+ * Mutations issued before the very first WS connect to a shard fail fast.
1043
+ * Opt into queueing-before-first-connect via
1044
+ * `OfflineQueueOptions.queueBeforeFirstConnect`.
1045
+ */
1046
+ mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
1047
+ action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1048
+ shardKey?: string;
1049
+ }): Promise<ReturnOf<F>>;
1050
+ /**
1051
+ * Bulk-import `rows` through a mutation that accepts a batch, chunked so a large
1052
+ * dataset lands in a bounded number of round-trips.
1053
+ *
1054
+ * **Offline caveat:** each chunk is sent with {@link LunoraClient.mutation}, which
1055
+ * resolves once the write is durably queued rather than once the server has applied
1056
+ * it. So an import run while offline resolves `{ chunks, imported }` with nothing
1057
+ * committed yet — the counts describe what was *handed over*, and the outbox
1058
+ * replays them on reconnect. Don't report "migration complete" on this alone.
1059
+ *
1060
+ * This is the one-shot migration / seed path: "I have 20k rows client-side and a
1061
+ * server mutation that inserts many at once". Doing it by hand goes wrong in two
1062
+ * predictable ways — a serial per-row loop pays one round-trip *and* one watermark
1063
+ * wait per row (a 200-row import becomes 200 sequential hops), while a single
1064
+ * giant call blows the DO's batch limit. So: chunk, send sequentially, and give
1065
+ * each chunk a stable idempotency key derived from `importId` + its index, so a
1066
+ * resumed or retried import doesn't double-insert the chunks that already landed.
1067
+ *
1068
+ * The server mutation is yours (Lunora can't guess the table or the row shape);
1069
+ * back it with `ctx.db.insertMany(...)`, or `insertManyUnsafe(...)` for data you
1070
+ * vouch for. `chunkSize` defaults to 500, matching the DO's default batch cap.
1071
+ *
1072
+ * ```ts
1073
+ * await client.importRows(api.migrate.importNodes, nodes, {
1074
+ * importId: `migrate-${userId}`,
1075
+ * onProgress: ({ done, total }) => setProgress(done / total),
1076
+ * shardKey: userId,
1077
+ * toArgs: (chunk) => ({ nodes: chunk }),
1078
+ * });
1079
+ * ```
1080
+ */
1081
+ importRows(function_: FunctionReference, rows: ReadonlyArray<unknown>, options?: {
1082
+ /** Rows per call. Defaults to 500 — the DO's default batch cap. */
1083
+ chunkSize?: number;
1084
+ /**
1085
+ * Stable id for this import run. Each chunk is sent under
1086
+ * `${importId}:${chunkIndex}` as its mutation id, so re-running an import
1087
+ * that uses the SAME `chunkSize` re-sends each chunk under its prior key
1088
+ * and the server dedupes it instead of inserting twice.
1089
+ *
1090
+ * CAVEAT — the key is POSITIONAL, not content-based: it pins on the chunk
1091
+ * INDEX, not on the rows inside it. Resume or retry with a DIFFERENT
1092
+ * `chunkSize` (or a changed row ordering) and index N now covers different
1093
+ * rows than the first run's index N; the server sees a duplicate key and
1094
+ * SILENTLY DROPS those rows. Keep `chunkSize` (and the row order) identical
1095
+ * across resumes of the same `importId`. Omit `importId` only for a
1096
+ * throwaway import where double-insertion is acceptable.
1097
+ */
1098
+ importId?: string;
1099
+ /**
1100
+ * Called after each chunk is accepted — for a progress bar.
1101
+ *
1102
+ * "Accepted" is not always "committed": while offline (or mid-reconnect) a
1103
+ * `mutation` resolves as soon as the write is durably **queued**, so a fully
1104
+ * offline import reports completion with nothing yet applied server-side.
1105
+ * Gate a migration's "done" state on connectivity, not just on this.
1106
+ */
1107
+ onProgress?: (progress: {
1108
+ done: number;
1109
+ total: number;
1110
+ }) => void;
1111
+ /** Routes every chunk to one shard's DO. */
1112
+ shardKey?: string;
1113
+ /** Build the mutation args for one chunk. Defaults to `{ rows: chunk }`. */
1114
+ toArgs?: (chunk: ReadonlyArray<unknown>) => Record<string, unknown>;
1115
+ }): Promise<{
1116
+ chunks: number;
1117
+ imported: number;
1118
+ }>;
1119
+ /**
1120
+ * Read the cross-shard request distribution for a `.shardBy(...)` table —
1121
+ * the feed the studio's `hot_shard` advisor lint consumes. Hits the
1122
+ * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
1123
+ * cheap per-shard `getMetrics` read out across every live shard and returns
1124
+ * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
1125
+ * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
1126
+ * and `adminToken`, and this client's auth token to match; defaults any
1127
+ * absent field so an older worker yields an empty-but-valid shape.
1128
+ */
1129
+ shardTraffic(table: string): Promise<ShardTrafficResult>;
1130
+ /**
1131
+ * List the functions queued via `runAfter` / `runAt`, soonest-due last
1132
+ * (the worker returns them in storage order). Hits the admin-gated
1133
+ * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
1134
+ * `schedulerDO` namespace and `adminToken`, and this client's auth token
1135
+ * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
1136
+ */
1137
+ listScheduledJobs(): Promise<ScheduleRecord[]>;
1138
+ /**
1139
+ * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
1140
+ * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
1141
+ * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
1142
+ * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
1143
+ * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
1144
+ * namespace + `adminToken` on the worker and a matching auth token here).
1145
+ * Defaults any absent field so an older worker still yields a valid shape.
1146
+ */
1147
+ schedulerStatus(): Promise<SchedulerStatus>;
1148
+ /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
1149
+ cancelScheduledJob(id: string): Promise<{
1150
+ cancelled: boolean;
1151
+ }>;
1152
+ /**
1153
+ * List the dead-letter jobs: schedules that exhausted their retry budget
1154
+ * and were parked instead of dropped. These never appear in
1155
+ * {@link listScheduledJobs} (their live header is gone), so this is the only
1156
+ * way the studio surfaces a permanently-failed job. Hits the admin-gated
1157
+ * `GET /_lunora/admin/scheduled/dead`; same preconditions as
1158
+ * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
1159
+ */
1160
+ listDeadJobs(): Promise<ScheduleRecord[]>;
1161
+ /**
1162
+ * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
1163
+ * retry budget and fires on the next drain. Returns whether a parked record
1164
+ * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
1165
+ */
1166
+ retryDeadJob(id: string): Promise<{
1167
+ retried: boolean;
1168
+ }>;
1169
+ /**
1170
+ * Permanently drop a dead-letter job by id (the operator has decided not to
1171
+ * recover it). Returns whether a parked record was removed. Hits the
1172
+ * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
1173
+ */
1174
+ removeDeadJob(id: string): Promise<{
1175
+ removed: boolean;
1176
+ }>;
1177
+ /**
1178
+ * List a workflow's instances via the admin Workflows proxy
1179
+ * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
1180
+ * the `Workflow` binding can't expose. Requires the worker to be built with a
1181
+ * `workflowsClient` (Cloudflare account id + API token). When one isn't
1182
+ * configured this does NOT reject: the proxy returns a `200 { configured:
1183
+ * false }` sentinel, so the result resolves with `configured === false` and an
1184
+ * empty `instances` list — callers should branch on that flag rather than
1185
+ * try/catch. (The instance-detail / status endpoints still reject with 501.)
1186
+ * `name` is the deployed workflow name.
1187
+ */
1188
+ listWorkflowInstances(options: {
1189
+ name: string;
1190
+ page?: number;
1191
+ perPage?: number;
1192
+ status?: WorkflowInstanceStatus;
1193
+ }): Promise<WorkflowInstancePage>;
1194
+ /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
1195
+ getWorkflowInstance(options: {
1196
+ id: string;
1197
+ name: string;
1198
+ }): Promise<WorkflowInstanceDetail>;
1199
+ /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
1200
+ setWorkflowInstanceStatus(options: {
1201
+ action: WorkflowInstanceAction;
1202
+ id: string;
1203
+ name: string;
1204
+ }): Promise<{
1205
+ status: WorkflowInstanceStatus;
1206
+ }>;
1207
+ /**
1208
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
1209
+ * WebSocket. `onJobs` fires with the full list on connect and on every
1210
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
1211
+ * configured backoff. Requires `wsToken` to be set to an admin credential
1212
+ * (the browser can't send an `Authorization` header on a WS) — the master
1213
+ * token, or preferably a {@link WsTokenProvider} minting the ephemeral
1214
+ * sub-token so the master credential stays out of the URL. Returns an
1215
+ * unsubscribe function that closes the socket and stops reconnecting.
1216
+ */
1217
+ subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
1218
+ /**
1219
+ * List the registered public functions (queries / mutations / actions) with
1220
+ * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1221
+ * the worker must be built with a `functions` registry and `adminToken`, and
1222
+ * this client's auth token must match. Powers `@lunora/studio`'s function
1223
+ * runner auto-discovery.
1224
+ */
1225
+ listFunctions(): Promise<FunctionDescriptor[]>;
1226
+ /**
1227
+ * List the code-defined cron triggers (the `cronJobs()` map injected on the
1228
+ * worker), each flattened to its firing `cron` expression. Hits the
1229
+ * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1230
+ * built with a `cronJobs` map and `adminToken`, and this client's auth token
1231
+ * must match. These are static (Cloudflare exposes no runtime cron
1232
+ * introspection), so the studio renders them read-only alongside the dynamic
1233
+ * scheduler jobs.
1234
+ */
1235
+ getCronJobs(): Promise<CronJobInfo[]>;
1236
+ /**
1237
+ * Manually fire one code-defined cron job by name — the same dispatch the
1238
+ * scheduled trigger runs (dispatch the function, or start the durable
1239
+ * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1240
+ * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1241
+ * and this client's auth token must match. Resolves when the job has run (a
1242
+ * function job's shard response is 2xx, or the workflow instance was created)
1243
+ * and rejects with the dispatch error otherwise.
1244
+ */
1245
+ runCronJob(name: string): Promise<{
1246
+ name: string;
1247
+ ran: boolean;
1248
+ }>;
1249
+ /**
1250
+ * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1251
+ * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1252
+ * `openApiSpec` and `adminToken`, and this client's auth token must match.
1253
+ * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1254
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1255
+ * document (no `paths`), so callers can render a "not configured" state.
1256
+ */
1257
+ fetchOpenApi(): Promise<Record<string, unknown>>;
1258
+ /**
1259
+ * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1260
+ * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1261
+ * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1262
+ * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1263
+ * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1264
+ * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1265
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1266
+ * document (no `methods`), so callers can render a "not configured" state.
1267
+ */
1268
+ fetchOpenRpc(): Promise<Record<string, unknown>>;
1269
+ /**
1270
+ * List objects in the storage bucket, optionally under a `prefix` and from a
1271
+ * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1272
+ * endpoint — the worker must be built with a `storageList` function and
1273
+ * `adminToken`, and this client's auth token must match. Powers
1274
+ * `@lunora/studio`'s file browser.
1275
+ */
1276
+ listStorageObjects(options?: {
1277
+ bucket?: string;
1278
+ cursor?: string;
1279
+ limit?: number;
1280
+ prefix?: string;
1281
+ }): Promise<StorageListPage>;
1282
+ /**
1283
+ * Delete one object from the storage bucket by key. Hits the admin-gated
1284
+ * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1285
+ * with a `storageDelete` function and `adminToken`. Powers the studio file
1286
+ * browser's per-row delete; resolves `{ deleted, key }`.
1287
+ */
1288
+ deleteStorageObject(key: string, options?: {
1289
+ bucket?: string;
1290
+ }): Promise<{
1291
+ deleted: boolean;
1292
+ key: string;
1293
+ }>;
1294
+ /**
1295
+ * List the storage bucket names the worker exposes, for the studio file
1296
+ * browser's bucket picker. Hits the admin-gated
1297
+ * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1298
+ * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1299
+ */
1300
+ listStorageBuckets(): Promise<string[]>;
1301
+ /**
1302
+ * Upload one object to the storage bucket. Hits the admin-gated
1303
+ * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1304
+ * optional `contentType` header — the worker must be built with a
1305
+ * `storageUpload` function and `adminToken`. Powers the studio file
1306
+ * browser's upload control; resolves `{ etag?, key }`.
1307
+ */
1308
+ uploadStorageObject(options: {
1309
+ body: ArrayBuffer | Blob;
1310
+ bucket?: string;
1311
+ contentType?: string;
1312
+ key: string;
1313
+ }): Promise<{
1314
+ etag?: string;
1315
+ key: string;
1316
+ }>;
1317
+ /**
1318
+ * Build a (signed or public) URL for one object. Hits the admin-gated
1319
+ * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1320
+ * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1321
+ * file browser's copy-URL action; resolves the URL string.
1322
+ *
1323
+ * `options.expiresInSeconds` requests a share-link lifetime, which is
1324
+ * validated/clamped server-side. The options object mirrors the worker's
1325
+ * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1326
+ * as future fields there).
1327
+ */
1328
+ signedStorageUrl(key: string, options?: {
1329
+ bucket?: string;
1330
+ expiresInSeconds?: number;
1331
+ }): Promise<string>;
1332
+ /**
1333
+ * List the `.global()` (D1-backed) tables with their row counts. Hits the
1334
+ * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1335
+ * be built with a `globalIntrospector` and `adminToken`. Powers the data
1336
+ * browser's global mode.
1337
+ */
1338
+ listGlobalTables(): Promise<GlobalTableInfo[]>;
1339
+ /**
1340
+ * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1341
+ * page to rows matching each `column = value` eq constraint — the drill-down a
1342
+ * facet-value click applies; the array is JSON-encoded into the `filters`
1343
+ * query param and the values are bound server-side.
1344
+ */
1345
+ readGlobalTablePage(options: {
1346
+ filters?: GlobalFilterClause[];
1347
+ limit?: number;
1348
+ offset?: number;
1349
+ table: string;
1350
+ }): Promise<GlobalTablePage>;
1351
+ /**
1352
+ * Summarise the distinct values of one column in a `.global()` table over the
1353
+ * active view (the same eq `filters` the browser is previewing) — the global
1354
+ * twin of the shard browser's facet. Hits the admin-gated
1355
+ * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1356
+ * server-side. Powers the global data browser's facet sidebar.
1357
+ */
1358
+ facetGlobalColumn(options: {
1359
+ column: string;
1360
+ filters?: GlobalFilterClause[];
1361
+ limit?: number;
1362
+ table: string;
1363
+ }): Promise<GlobalFacetResult>;
1364
+ /**
1365
+ * List the schema's Vectorize indexes with their declared shape (table,
1366
+ * field, dimensions, metric, metadata) and live stats (vector count,
1367
+ * processing watermark) when the binding is reachable. Hits the admin-gated
1368
+ * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1369
+ * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1370
+ * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1371
+ * from the generated `LUNORA_VECTOR_INDEXES` registry.
1372
+ */
1373
+ listVectorIndexes(): Promise<VectorIndexSummary[]>;
1374
+ /**
1375
+ * Run a nearest-neighbour similarity query against one vector index: the
1376
+ * worker embeds `text` via the index's embedder and returns the top matches.
1377
+ * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1378
+ * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1379
+ * wired (the index lists read-only).
1380
+ */
1381
+ queryVectorIndex(options: {
1382
+ name: string;
1383
+ text: string;
1384
+ topK?: number;
1385
+ }): Promise<VectorQueryMatch[]>;
1386
+ /**
1387
+ * Read one keyset-paginated page of the durable `ctx.log` archive that
1388
+ * `pipelineLogSink` writes to R2. Server-side only — the worker holds the R2
1389
+ * SQL credentials and runs the reader; the browser only sees the decoded
1390
+ * `{ rows, nextCursor }`. Pass the previous page's `nextCursor` as
1391
+ * `query.cursor` to page. Admin-gated. When the operator hasn't wired the
1392
+ * archive, `adminFetch` throws a `LunoraClientError` with `.code ===
1393
+ * "LOG_ARCHIVE_NOT_CONFIGURED"`, so a caller can render a "not configured"
1394
+ * state rather than an error.
1395
+ */
1396
+ queryLogArchive(query?: PipelineLogQuery): Promise<PipelineLogPage>;
1397
+ /**
1398
+ * List the worker's registered Workers KV namespaces (binding names). Hits
1399
+ * the admin-gated `GET /_lunora/admin/kv/namespaces` endpoint — the worker
1400
+ * must be built with a `kvIntrospector` and `adminToken`. Powers the
1401
+ * studio's KV browser.
1402
+ */
1403
+ listKvNamespaces(): Promise<KvNamespaceSummary[]>;
1404
+ /**
1405
+ * List keys in a KV namespace, optionally filtered by `prefix` and
1406
+ * paginated via `cursor`. Hits the admin-gated
1407
+ * `GET /_lunora/admin/kv/keys` endpoint.
1408
+ */
1409
+ listKvKeys(options: {
1410
+ cursor?: string;
1411
+ limit?: number;
1412
+ namespace: string;
1413
+ prefix?: string;
1414
+ }): Promise<KvKeyListResult>;
1415
+ /**
1416
+ * Read a KV value (as text) and its metadata. Hits the admin-gated
1417
+ * `GET /_lunora/admin/kv/value` endpoint. Returns `{ value: null, metadata: null }`
1418
+ * when the key is absent.
1419
+ */
1420
+ getKvValue(options: {
1421
+ key: string;
1422
+ namespace: string;
1423
+ }): Promise<KvValueResult>;
1424
+ /**
1425
+ * Write a string value to a KV namespace. Accepts an absolute `expiration`
1426
+ * (Unix seconds) or a relative `expirationTtl`, plus optional `metadata` —
1427
+ * re-send the loaded values on edit so a save preserves rather than clears
1428
+ * them. Hits the admin-gated `PUT /_lunora/admin/kv/value` endpoint.
1429
+ */
1430
+ putKvValue(options: {
1431
+ expiration?: number;
1432
+ expirationTtl?: number;
1433
+ key: string;
1434
+ metadata?: unknown;
1435
+ namespace: string;
1436
+ value: string;
1437
+ }): Promise<void>;
1438
+ /**
1439
+ * Delete a key from a KV namespace. No-op when the key is absent. Hits the
1440
+ * admin-gated `DELETE /_lunora/admin/kv/value` endpoint.
1441
+ */
1442
+ deleteKvKey(options: {
1443
+ key: string;
1444
+ namespace: string;
1445
+ }): Promise<void>;
1446
+ /**
1447
+ * List authenticated users, paged and optionally searched / filtered / sorted.
1448
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1449
+ * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1450
+ * users dashboard.
1451
+ */
1452
+ listAuthUsers(options?: {
1453
+ filterField?: string;
1454
+ filterValue?: string;
1455
+ limit?: number;
1456
+ offset?: number;
1457
+ search?: string;
1458
+ searchField?: string;
1459
+ sortBy?: string;
1460
+ sortDirection?: "asc" | "desc";
1461
+ }): Promise<AuthPage<AuthUser>>;
1462
+ /**
1463
+ * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1464
+ * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1465
+ * `data` carries any app-defined `user.additionalFields`.
1466
+ */
1467
+ createAuthUser(input: {
1468
+ data?: Record<string, unknown>;
1469
+ email: string;
1470
+ name: string;
1471
+ password?: string;
1472
+ role?: string | string[];
1473
+ }): Promise<AuthUser>;
1474
+ /** Set a user's role (string, or array joined comma-wise server-side). */
1475
+ setAuthUserRole(input: {
1476
+ role: string | string[];
1477
+ userId: string;
1478
+ }): Promise<AuthUser>;
1479
+ /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1480
+ banAuthUser(input: {
1481
+ expiresInSeconds?: number;
1482
+ reason?: string;
1483
+ userId: string;
1484
+ }): Promise<AuthUser>;
1485
+ /** Lift a user's ban. */
1486
+ unbanAuthUser(input: {
1487
+ userId: string;
1488
+ }): Promise<AuthUser>;
1489
+ /** Set a user's password (admin override — no current-password challenge). */
1490
+ setAuthUserPassword(input: {
1491
+ newPassword: string;
1492
+ userId: string;
1493
+ }): Promise<void>;
1494
+ /** Permanently delete a user and revoke their sessions. */
1495
+ removeAuthUser(input: {
1496
+ userId: string;
1497
+ }): Promise<void>;
1498
+ /**
1499
+ * Mint an impersonation session for a user, returning its bearer `token`.
1500
+ * The caller is responsible for using the token (e.g. setting the session
1501
+ * cookie); the server performs no cookie round-trip.
1502
+ */
1503
+ impersonateAuthUser(input: {
1504
+ userId: string;
1505
+ }): Promise<AuthImpersonation>;
1506
+ /** Revoke a single session by its id (force sign-out of one device). */
1507
+ revokeAuthSession(input: {
1508
+ sessionId: string;
1509
+ }): Promise<void>;
1510
+ /** Revoke every session for a user (force sign-out everywhere). */
1511
+ revokeAuthUserSessions(input: {
1512
+ userId: string;
1513
+ }): Promise<void>;
1514
+ /**
1515
+ * Report which auth dashboard surfaces are available — derived server-side
1516
+ * from the enabled better-auth plugins. The studio renders only the panels
1517
+ * whose capability is `true`.
1518
+ */
1519
+ getAuthCapabilities(): Promise<AuthCapabilities>;
1520
+ /** Update a user's fields (name/email/app-defined `additionalFields`). */
1521
+ updateAuthUser(input: {
1522
+ data: Record<string, unknown>;
1523
+ userId: string;
1524
+ }): Promise<AuthUser>;
1525
+ /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1526
+ listAuthAccounts(input: {
1527
+ userId: string;
1528
+ }): Promise<Record<string, unknown>[]>;
1529
+ /** Unlink a linked account from a user. */
1530
+ unlinkAuthAccount(input: {
1531
+ accountId: string;
1532
+ userId: string;
1533
+ }): Promise<void>;
1534
+ /** List a user's registered passkeys (requires the passkey plugin). */
1535
+ listAuthPasskeys(input: {
1536
+ userId: string;
1537
+ }): Promise<Record<string, unknown>[]>;
1538
+ /** Delete a passkey by id (requires the passkey plugin). */
1539
+ deleteAuthPasskey(input: {
1540
+ passkeyId: string;
1541
+ }): Promise<void>;
1542
+ /** Disable two-factor auth for a user (requires the two-factor plugin). */
1543
+ disableAuthTwoFactor(input: {
1544
+ userId: string;
1545
+ }): Promise<void>;
1546
+ /** List organizations, paged (requires the organization plugin). */
1547
+ listAuthOrganizations(options?: {
1548
+ limit?: number;
1549
+ offset?: number;
1550
+ }): Promise<AuthPage<Record<string, unknown>>>;
1551
+ /** List the members of an organization (requires the organization plugin). */
1552
+ listAuthOrgMembers(input: {
1553
+ limit?: number;
1554
+ offset?: number;
1555
+ organizationId: string;
1556
+ }): Promise<AuthPage<Record<string, unknown>>>;
1557
+ /** List an organization's pending invitations (requires the organization plugin). */
1558
+ listAuthOrgInvitations(input: {
1559
+ limit?: number;
1560
+ offset?: number;
1561
+ organizationId: string;
1562
+ }): Promise<AuthPage<Record<string, unknown>>>;
1563
+ /** Remove a member from an organization. */
1564
+ removeAuthOrgMember(input: {
1565
+ memberId: string;
1566
+ }): Promise<void>;
1567
+ /** Cancel a pending organization invitation. */
1568
+ cancelAuthOrgInvitation(input: {
1569
+ invitationId: string;
1570
+ }): Promise<void>;
1571
+ /**
1572
+ * Report the deployment's auth configuration — enabled plugins, sign-in
1573
+ * methods, user-settable create-user fields, organization sub-features
1574
+ * (teams / roles), and session / rate-limit policy. Drives the config panel
1575
+ * and the dynamic create-user form. Never carries a secret.
1576
+ */
1577
+ getAuthConfig(): Promise<AuthConfigInfo>;
1578
+ /** Create an organization; optionally seed an `owner` member for `ownerId`. */
1579
+ createAuthOrganization(input: {
1580
+ logo?: string;
1581
+ metadata?: Record<string, unknown>;
1582
+ name: string;
1583
+ ownerId?: string;
1584
+ slug?: string;
1585
+ }): Promise<Record<string, unknown>>;
1586
+ /** Update an organization's name/slug/logo/metadata. */
1587
+ updateAuthOrganization(input: {
1588
+ logo?: string;
1589
+ metadata?: Record<string, unknown>;
1590
+ name?: string;
1591
+ organizationId: string;
1592
+ slug?: string;
1593
+ }): Promise<Record<string, unknown>>;
1594
+ /** Delete an organization and cascade its members, invitations, teams, and custom roles. */
1595
+ deleteAuthOrganization(input: {
1596
+ organizationId: string;
1597
+ }): Promise<void>;
1598
+ /** Directly add an existing user to an organization (no invitation/acceptance). */
1599
+ addAuthOrgMember(input: {
1600
+ organizationId: string;
1601
+ role?: string;
1602
+ userId: string;
1603
+ }): Promise<Record<string, unknown>>;
1604
+ /** Create a pending email invitation to an organization. */
1605
+ inviteAuthOrgMember(input: {
1606
+ email: string;
1607
+ inviterId?: string;
1608
+ organizationId: string;
1609
+ role?: string;
1610
+ }): Promise<Record<string, unknown>>;
1611
+ /** Change a member's role. */
1612
+ setAuthOrgMemberRole(input: {
1613
+ memberId: string;
1614
+ role: string | string[];
1615
+ }): Promise<Record<string, unknown>>;
1616
+ /** List an organization's teams (requires the organization plugin with teams enabled). */
1617
+ listAuthOrgTeams(input: {
1618
+ limit?: number;
1619
+ offset?: number;
1620
+ organizationId: string;
1621
+ }): Promise<AuthPage<Record<string, unknown>>>;
1622
+ /** Create a team under an organization. */
1623
+ createAuthOrgTeam(input: {
1624
+ name: string;
1625
+ organizationId: string;
1626
+ }): Promise<Record<string, unknown>>;
1627
+ /** Rename a team. */
1628
+ updateAuthOrgTeam(input: {
1629
+ name: string;
1630
+ teamId: string;
1631
+ }): Promise<Record<string, unknown>>;
1632
+ /** Delete a team and its memberships. */
1633
+ removeAuthOrgTeam(input: {
1634
+ teamId: string;
1635
+ }): Promise<void>;
1636
+ /** List a team's members. */
1637
+ listAuthOrgTeamMembers(input: {
1638
+ limit?: number;
1639
+ offset?: number;
1640
+ teamId: string;
1641
+ }): Promise<AuthPage<Record<string, unknown>>>;
1642
+ /** Add a user to a team. */
1643
+ addAuthOrgTeamMember(input: {
1644
+ teamId: string;
1645
+ userId: string;
1646
+ }): Promise<Record<string, unknown>>;
1647
+ /** Remove a member from a team. */
1648
+ removeAuthOrgTeamMember(input: {
1649
+ teamMemberId: string;
1650
+ }): Promise<void>;
1651
+ /** List an organization's custom roles (requires the organization plugin with dynamic access control). */
1652
+ listAuthOrgRoles(input: {
1653
+ limit?: number;
1654
+ offset?: number;
1655
+ organizationId: string;
1656
+ }): Promise<AuthPage<Record<string, unknown>>>;
1657
+ /** Create a custom org role with a permission grant (a `resource -> actions[]` map). */
1658
+ createAuthOrgRole(input: {
1659
+ organizationId: string;
1660
+ permission: Record<string, string[]>;
1661
+ role: string;
1662
+ }): Promise<Record<string, unknown>>;
1663
+ /** Replace a custom org role's permission grant. */
1664
+ updateAuthOrgRole(input: {
1665
+ permission: Record<string, string[]>;
1666
+ roleId: string;
1667
+ }): Promise<Record<string, unknown>>;
1668
+ /** Delete a custom org role. */
1669
+ deleteAuthOrgRole(input: {
1670
+ roleId: string;
1671
+ }): Promise<void>;
1672
+ /** List auth sessions, paged and optionally filtered to one user. */
1673
+ listAuthSessions(options?: {
1674
+ limit?: number;
1675
+ offset?: number;
1676
+ userId?: string;
1677
+ }): Promise<AuthPage<AuthSession>>;
1678
+ subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
1679
+ onCheckpoint?: (watermark: SyncWatermark) => void;
1680
+ onError?: SubscriptionErrorCallback;
1681
+ shardKey?: string;
1682
+ }): Unsubscribe;
1683
+ /**
1684
+ * Subscribe to a declarative **shape** — server-side partial replication
1685
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
1686
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
1687
+ * validated `args` (never a `where` the client could forge), the server seeds
1688
+ * the current membership as an insert-poke and streams live membership diffs.
1689
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
1690
+ *
1691
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
1692
+ * (name, args): the server resolves them under the socket's verified identity,
1693
+ * so every call gets its own id + view. The returned function unsubscribes.
1694
+ */
1695
+ subscribeShape(shape: {
1696
+ args?: Record<string, unknown>;
1697
+ name: string;
1698
+ }, callback: ShapeCallback, options?: {
1699
+ onCheckpoint?: (watermark: SyncWatermark) => void;
1700
+ onError?: SubscriptionErrorCallback;
1701
+ shardKey?: string;
1702
+ }): Unsubscribe;
1703
+ /**
1704
+ * Open a streaming query. The function reference must be a
1705
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1706
+ * the type constraint catches accidental use of a query/mutation/action
1707
+ * reference at compile time. The returned iterable yields one element per
1708
+ * chunk frame the server pushes, terminating when the server sends
1709
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1710
+ * rejection on the next `next()`.
1711
+ *
1712
+ * Streams ride the same WS as subscriptions and share the unsubscribe
1713
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1714
+ * which the DO recognises as an abort signal for the in-flight iterator.
1715
+ *
1716
+ * Stream-start frames buffered while the socket is (re)connecting are
1717
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1718
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
1719
+ * reconnect can't OOM the page.
1720
+ */
1721
+ stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
1722
+ durable?: boolean;
1723
+ maxBuffer?: number;
1724
+ shardKey?: string;
1725
+ }): StreamIterable<ReturnOf<F>>;
1726
+ /**
1727
+ * Open a typed **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`).
1728
+ * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
1729
+ * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
1730
+ * and parses the Server-Sent Events framing the route pump writes (`data:`
1731
+ * chunks, a final `event: complete`, an `event: error` on throw).
1732
+ *
1733
+ * The reference comes from the generated `httpStreams.*` registry, so the
1734
+ * yielded chunk type is the route handler's yielded type. Cancelling the
1735
+ * returned iterable (or aborting `options.signal`) aborts the fetch, which
1736
+ * the server handler observes via its `signal`. The client's bearer token
1737
+ * (when set) rides as an `authorization` header.
1738
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
1739
+ */
1740
+ httpStream<Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: {
1741
+ headers?: Record<string, string>;
1742
+ maxBuffer?: number;
1743
+ signal?: AbortSignal;
1744
+ }): StreamIterable<HttpStreamChunkOf<Ref>>;
1745
+ close(): void;
1746
+ /** Guard shared by every public entry point: a closed client accepts no further calls. */
1747
+ private assertOpen;
1748
+ /**
1749
+ * Tear down one {@link ShardConnection}'s live state: clear its reconnect/
1750
+ * connect timers, stop its heartbeat, and close its socket (if any).
1751
+ * Shared by `close()` (terminal) and the cross-tab `onStopBeingLeader`
1752
+ * handler (demoted, but still alive) so a demoted leader can't leak a
1753
+ * pending `reconnectTimer` or an open socket's `heartbeatTimer` the way
1754
+ * an inline `conn.socket?.close()` — which skips both — used to.
1755
+ */
1756
+ private teardownConnection;
1757
+ /**
1758
+ * Build (but do not start) this client's `TabCoordinator`. Extracted out of
1759
+ * the constructor so `setAuthToken` can rebuild it on an identity change —
1760
+ * the default channel name embeds the identity fingerprint (see below), so
1761
+ * a new identity needs a new coordinator on a new channel. The callback
1762
+ * bodies are the drift-sensitive region (a hand-merged identity guard on
1763
+ * the shard message listener sits ahead of an extracted `lastFrameAt`
1764
+ * stamp elsewhere in this file) — moved verbatim, not reflowed.
1765
+ */
1766
+ private createTabCoordinator;
1767
+ /**
1768
+ * Persist a mutation that can't go out on the wire right now (offline, or
1769
+ * mid-reconnect after a prior connect). The optimistic update has already
1770
+ * been applied by `mutation`; this only chooses the durable write path and
1771
+ * rolls the optimistic write back if persistence is rejected.
1772
+ *
1773
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
1774
+ * owns persistence + at-least-once replay, so we delegate and return
1775
+ * optimistically (confirmation rides the synced view). Otherwise the
1776
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
1777
+ */
1778
+ private enqueueOfflineMutation;
1779
+ /**
1780
+ * Restore offline mutations persisted in a prior session and open a socket
1781
+ * for each shard they target so they flush once the WS reconnects. Failures
1782
+ * are swallowed — a broken durable store must not stop the client booting.
1783
+ */
1784
+ private hydratePersistedQueue;
1785
+ /**
1786
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
1787
+ * persisted queue is shared across a profile's tabs; without coordination
1788
+ * every tab would re-queue and replay the same writes (correct only because
1789
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
1790
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
1791
+ * closes another tab acquires the lock and takes over. Falls back to
1792
+ * unconditional hydration where Web Locks are unavailable (React Native, older
1793
+ * browsers, SSR) — single-context there, so no coordination is needed.
1794
+ */
1795
+ private hydrateAsOutboxLeader;
1796
+ /**
1797
+ * Load every cached query into {@link hydratedQueryCache} so the next
1798
+ * `subscribe()` for each key seeds its initial value off disk. A
1799
+ * subscription created before this resolves simply misses the cache (it
1800
+ * gets a live snapshot as before); the gate at seed time also drops any
1801
+ * entry whose stamped identity no longer matches the current one.
1802
+ */
1803
+ private hydrateQueryCache;
1804
+ /**
1805
+ * Consume the hydrated read-cache entry for a key (if any), gated on
1806
+ * identity. The entry is removed whether or not it matches — the cache only
1807
+ * ever seeds a subscription's first value. A mismatch (the cache was written
1808
+ * under a different identity) yields `undefined` so a signed-out cache never
1809
+ * leaks into a new session.
1810
+ */
1811
+ private takeHydratedCache;
1812
+ /**
1813
+ * Queue a coalesced read-cache write for a subscription's current value.
1814
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
1815
+ * once. No-op when the read cache is disabled or the value is undefined
1816
+ * (nothing to render offline).
1817
+ */
1818
+ private persistQueryValue;
1819
+ /** Drain {@link pendingCacheWrites} to the durable store. */
1820
+ private flushQueryCacheWrites;
1821
+ /** Derive the aggregate status from the per-shard socket states. */
1822
+ private computeStatus;
1823
+ /** Recompute the aggregate status and notify listeners if it changed. */
1824
+ private emitConnectionStatus;
1825
+ /**
1826
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
1827
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
1828
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
1829
+ * is unreachable — present only to satisfy the optional queue-id type.
1830
+ */
1831
+ private emitItemSettled;
1832
+ /**
1833
+ * Apply an optimistic update to the subscription that matches the mutation's
1834
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
1835
+ * invoke if the mutation later fails.
1836
+ *
1837
+ * The registry is already indexed by exactly this triple via
1838
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
1839
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
1840
+ *
1841
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
1842
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
1843
+ * a shardKey correctly matches a subscription registered without one regardless
1844
+ * of whether the caller passed `undefined` or omitted the field.
1845
+ */
1846
+ private applyOptimisticUpdates;
1847
+ /**
1848
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
1849
+ * to the live subscription registry. Each `setQuery` registers a constant
1850
+ * optimistic LAYER on its target subscription (via the same engine the
1851
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
1852
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
1853
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
1854
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
1855
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
1856
+ * mutation or leave a partial patch live.
1857
+ */
1858
+ private applyOptimisticUpdate;
1859
+ private getConnection;
1860
+ /**
1861
+ * Send an unsubscribe frame (tagged with its wire type) on the shard's
1862
+ * socket, or queue it for the next reconnect when the send can't go out.
1863
+ */
1864
+ private sendOrQueueUnsubscribe;
1865
+ /**
1866
+ * The `(wsState, hasSocket, wasEverConnected)` triple `mutation()`'s
1867
+ * offline-queue gate reads. On the leader/single-tab path this is exactly
1868
+ * the real `ShardConnection`'s state (byte-identical to the pre-cross-tab
1869
+ * behavior). A follower has no `ShardConnection` of its own (see
1870
+ * `ensureSocket`), so it derives the same triple from the mirrored
1871
+ * `leaderStatus`/`leaderWasEverConnected` instead: `"connected"` maps to
1872
+ * `"open"` (queue-eligible once `wasEverConnected`), `"connecting"` stays
1873
+ * `"connecting"` (the mid-reconnect queue branch), anything else is
1874
+ * `"idle"`. `hasSocket` is always `false` for a follower — it never has
1875
+ * one.
1876
+ */
1877
+ private connectionGateState;
1878
+ private getOrCreateConnection;
1879
+ private wsUrlFor;
1880
+ /**
1881
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
1882
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
1883
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
1884
+ * rides both the direct send and any offline-queue replay of the same write,
1885
+ * so a mutation the server already committed returns its cached result
1886
+ * instead of running twice.
1887
+ */
1888
+ private rpcRequestHeaders;
1889
+ private rpc;
1890
+ /**
1891
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
1892
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
1893
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
1894
+ * mirroring {@link rpc} so callers see the same failure shape.
1895
+ */
1896
+ private adminFetch;
1897
+ /**
1898
+ * Resolve the effective connection context for a shard: the most-recently
1899
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
1900
+ * back to the imperative {@link setConnectionContext} override, then the
1901
+ * client-wide default. Returns `undefined` when none apply.
1902
+ */
1903
+ private effectiveConnectionContext;
1904
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
1905
+ private refreshConnectionContext;
1906
+ /**
1907
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
1908
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
1909
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
1910
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
1911
+ * hooks are registered, so the single frame costs nothing in the common case.
1912
+ *
1913
+ * The shard's registered context (or the client-wide default) rides along
1914
+ * when one is set — the DO records it on the attachment for replay to
1915
+ * `onDisconnect`. A socket with no registered context still announces itself;
1916
+ * the envelope simply omits `context`, which is optional on the wire.
1917
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
1918
+ * to the lifecycle dispatch.
1919
+ */
1920
+ private sendConnectEnvelope;
1921
+ /**
1922
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
1923
+ * socket. Each frame carries the shape's last applied checkpoint, so the
1924
+ * server resumes from it — or re-seeds when the cursor fell below CDC
1925
+ * retention or the epoch forked.
1926
+ */
1927
+ private resendShapeSubscriptions;
1928
+ private ensureSocket;
1929
+ /**
1930
+ * Resolve the {@link WsTokenProvider} and open the shard socket with the
1931
+ * minted token. The connection is already in the `connecting` state, so the
1932
+ * async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
1933
+ * competing connect that landed first all abandon this attempt. A provider
1934
+ * failure fails the attempt through {@link handleDisconnect}, which arms the
1935
+ * normal reconnect backoff — a broken mint endpoint degrades to retries, not
1936
+ * a silent tokenless socket the admin gate would reject.
1937
+ */
1938
+ private openSocketWithProvidedToken;
1939
+ /**
1940
+ * Construct one WebSocket connection attempt and wire the shared
1941
+ * lifecycle guarantees around it — the fail-fast connect-timeout, the
1942
+ * identity guard that stops a superseded attempt's late `open`/`message`/
1943
+ * `close`/`error` from touching a connection a newer attempt already
1944
+ * owns, and (once open) the keepalive heartbeat with its half-open
1945
+ * watchdog (plan 217). One call opens ONE attempt; the caller owns
1946
+ * reconnect scheduling from `onClose` — mirrors the shard's existing
1947
+ * `ensureSocket` / `handleDisconnect` split, now shared with
1948
+ * `subscribeScheduledJobs` so it stops re-living the bug that split
1949
+ * already fixed once (CLIENT-05).
1950
+ *
1951
+ * The identity guard is `conn.socket !== socket`, re-checked before every
1952
+ * action below. `conn.socket` is reassigned to a new attempt's socket
1953
+ * synchronously — right here, before `open` ever fires — so an older
1954
+ * attempt's guard trips the instant it's superseded, even if its
1955
+ * underlying socket only fires its real `close`/`error` much later. This
1956
+ * ordering is load-bearing: preserve it exactly.
1957
+ */
1958
+ private openManagedSocket;
1959
+ /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
1960
+ private openSocket;
1961
+ private handleDisconnect;
1962
+ /**
1963
+ * Begin the keepalive heartbeat on an open connection attempt — the only
1964
+ * caller is {@link openManagedSocket}'s own `open` handler, so both the
1965
+ * shard socket and `subscribeScheduledJobs` share this one implementation
1966
+ * instead of each hand-rolling their own (plan 217, generalized).
1967
+ *
1968
+ * Each tick first checks the half-open watchdog (see
1969
+ * {@link ManagedSocketState.lastFrameAt}): if no frame at all has arrived
1970
+ * within `heartbeatIntervalMs * 2.5`, the far end has gone quiet without
1971
+ * the socket ever firing `close` — force it closed and report it through
1972
+ * `onWatchdogTrip` (the caller's `onClose`) so the normal reconnect/backoff
1973
+ * takes over instead of every live query on it silently staling forever.
1974
+ * Otherwise it sends a {@link WS_KEEPALIVE_PING} text frame the server
1975
+ * answers from its hibernation auto-response without waking the DO. A
1976
+ * no-op when the heartbeat is disabled (an interval of zero or less);
1977
+ * idempotent — any existing timer is cleared first so a reconnect can't
1978
+ * leak intervals.
1979
+ */
1980
+ private startHeartbeat;
1981
+ /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
1982
+ private stopHeartbeat;
1983
+ /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
1984
+ private markShardPendingAck;
1985
+ private sendSubscribeIfOpen;
1986
+ private sendShapeSubscribeIfOpen;
1987
+ private handleServerMessage;
1988
+ private handleErrorMessage;
1989
+ private handlePokeStart;
1990
+ private handlePokePart;
1991
+ private handlePokeEnd;
1992
+ /** Materialize a shape's keyed view to an array and invoke its callbacks. */
1993
+ private emitShapeRows;
1994
+ private handleDataMessage;
1995
+ /**
1996
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
1997
+ * subscription reads changed since our `sinceSeq`, so the cached value is
1998
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
1999
+ * the cursor (re-persisting so the next reconnect resumes from the newer
2000
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
2001
+ * already replayed the cached value to every consumer synchronously.
2002
+ */
2003
+ private handleResumeMessage;
2004
+ /**
2005
+ * Handle a `settled` frame: a write touched one of this subscription's read
2006
+ * tables but produced a byte-identical result, so the server suppressed the
2007
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
2008
+ * advance the resume position and re-persist — but we ALSO surface the echoed
2009
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
2010
+ * collection drops the optimistic overlay for the confirmed write (otherwise
2011
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
2012
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
2013
+ * `onCheckpoint` unset and this is a near no-op.
2014
+ */
2015
+ private handleSettledMessage;
2016
+ /**
2017
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
2018
+ * the cached position, advance the resume watermark and re-persist. Shared by
2019
+ * the `resume` and `settled` frame handlers — both acknowledge "nothing the
2020
+ * client must re-render changed, but the resume position may have moved".
2021
+ */
2022
+ private ackAndAdvanceCursor;
2023
+ /**
2024
+ * Resolve the value to publish for a `data`/`delta` frame.
2025
+ *
2026
+ * A `data` frame is an authoritative snapshot (the server re-execution path)
2027
+ * and always replaces the cached value wholesale. A `delta` frame carrying a
2028
+ * structured `MutationDelta` (the `broadcastDelta` row-change path) is
2029
+ * merged incrementally into the cached list — preserving order, no dup/loss —
2030
+ * so each subscription (including every paginated page) updates by delta
2031
+ * rather than a full re-send. We fall back to full replacement when the
2032
+ * delta isn't a recognisable row change, when there's no cached value yet,
2033
+ * or when it can't be applied cleanly against the current cached shape.
2034
+ */
2035
+ private resolveDataPayload;
2036
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
2037
+ private dispatchWhisper;
2038
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
2039
+ private notifyTokenExpired;
2040
+ /**
2041
+ * CLIENT-04: `type: "complete"` today is sent ONLY by `@lunora/do`'s
2042
+ * `handleStream` (see `shard-do.ts`), gated to the `stream` envelope type
2043
+ * and minting only `stream_*` ids — the `subscribe` path never sends it, so
2044
+ * a live SUBSCRIPTION provably never receives `complete` from the current
2045
+ * server. But `ServerCompleteMessage` is a generic `id`-keyed frame and
2046
+ * `ShardDO` is user-subclassable, so this stays defensive rather than
2047
+ * assuming a `sub_*` id can never reach here: unlike the historical
2048
+ * `subscriptions.remove(state)`, which dropped the state out of
2049
+ * `subscriptions.all()` — the set the reconnect resubscribe loop walks
2050
+ * (`ensureSocket`'s `open` handler) — and so froze the query forever across
2051
+ * every future reconnect, this fans a cancellation error to any listener
2052
+ * and marks the registration un-acked instead. Non-destructive: the state
2053
+ * stays in the registry, so the very next reconnect resubscribes it. The
2054
+ * two id-spaces don't overlap (`sub_*` vs `stream_*`), so the stream and
2055
+ * subscription lookups below are mutually exclusive.
2056
+ */
2057
+ private handleCompleteMessage;
2058
+ private unpersist;
2059
+ /**
2060
+ * Stable, non-reversible fingerprint of the current auth identity used to
2061
+ * stamp queued offline writes. `null` (signed out) is its own identity and
2062
+ * never matches a bearer-token fingerprint. The raw token is never stored;
2063
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
2064
+ * without keeping the credential around in the queue map.
2065
+ */
2066
+ private identityFingerprint;
2067
+ /**
2068
+ * Stable token-hash fingerprint of a bearer token (the `<len>:<fnv>:<djb2>`
2069
+ * format a token-stamped queued write carries). Extracted so the replay gate
2070
+ * can recompute the hash of the current credential and recognise a write
2071
+ * stamped under it — even after the fingerprint was relabelled to a subject.
2072
+ *
2073
+ * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
2074
+ * two distinct equal-length tokens are astronomically unlikely to share a
2075
+ * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
2076
+ * pair — enough that, on a shared device, user B could hydrate A's cached
2077
+ * reads. Different algorithms (not the same FNV with a different seed, which
2078
+ * would be affine-related) keep the two passes genuinely independent.
2079
+ * Still synchronous (no crypto) and stable across surrogate pairs.
2080
+ */
2081
+ private hashToken;
2082
+ /**
2083
+ * True when `stamped` is a token-hash of the SAME credential still held now,
2084
+ * even though the live identity has since been relabelled to a subject. Covers
2085
+ * `setAuthToken(token, userId)` where the subject resolved a tick after the
2086
+ * token was set: a write persisted (or requeued) under the token hash must
2087
+ * still replay — the credential never changed, only its label — instead of
2088
+ * being dropped as an identity mismatch. This is the durable counterpart to
2089
+ * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
2090
+ * (consumed on the first flush) and never touches `item.identity` or the
2091
+ * persisted record, so a reload or a transient-failure requeue would otherwise
2092
+ * fall back to the stale token-hash and wrongly reject the same user's write.
2093
+ */
2094
+ private isSameCredentialUnderTokenHash;
2095
+ /**
2096
+ * Drain every in-memory offline write and reject it because the auth
2097
+ * identity changed. Durable entries are also dropped from persistence so a
2098
+ * later `hydrate` can't resurrect another user's writes. Stamps are cleared
2099
+ * alongside. Persisted entries restored without a live awaiter still get
2100
+ * unpersisted here.
2101
+ */
2102
+ private rejectQueuedForIdentityChange;
2103
+ /**
2104
+ * Migrate every live identity stamp from `from` to `to` — used when the auth
2105
+ * identity label changes but the underlying credential (token) does NOT, e.g.
2106
+ * the user id resolves a tick after the token was set. The in-memory
2107
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
2108
+ * keeps the in-flight writes replayable under the new (more stable) identity
2109
+ * instead of the flush guard discarding them as a mismatch.
2110
+ */
2111
+ private restampQueuedIdentity;
2112
+ /**
2113
+ * Migrate the {@link clientWatermarks} bucket map nested under identity
2114
+ * `from` to identity `to` — the sibling of {@link restampQueuedIdentity},
2115
+ * for the same same-credential-subject-resolves case. Without this, a
2116
+ * bucket's watermark cached under the token-hash fingerprint would look
2117
+ * unset once the fingerprint relabels to `subj:…`, so the next push
2118
+ * re-derives `1` against a server watermark the DO already advanced — the
2119
+ * OUT_OF_ORDER wedge this cache-keying scheme exists to fix, reintroduced
2120
+ * by the fix itself. `to` may already hold a bucket map (switching back to
2121
+ * an identity that has its own cached watermarks); merge into it rather
2122
+ * than clobbering it, with `from`'s entries winning on a colliding bucket —
2123
+ * the same overwrite a plain `Map.set` would have done before this was a
2124
+ * nested map.
2125
+ */
2126
+ private restampWatermarks;
2127
+ /**
2128
+ * Drop the durable read cache on an identity change so a cached value stamped
2129
+ * under the previous identity can never hydrate into a new session. Clears
2130
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
2131
+ * the durable `clear()` is best-effort.
2132
+ */
2133
+ private clearQueryCacheForIdentityChange;
2134
+ /**
2135
+ * Flush every shard with a mutation currently queued in `offlineQueue`
2136
+ * (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
2137
+ * mirrored leader status transitions to `"connected"` — a follower has no
2138
+ * per-shard `ShardConnection` reconnect event to hang the usual
2139
+ * single-shard `flushOfflineQueue(shardKey)` call off of (see the
2140
+ * `handleConnect` call site), so this walks every shard that might have
2141
+ * something queued instead. Flushing an already-empty shard is a cheap
2142
+ * no-op (`flushOfflineQueue` returns immediately once `drain` yields
2143
+ * nothing), so over-inclusion here is harmless.
2144
+ */
2145
+ private flushAllOfflineQueues;
2146
+ private flushOfflineQueue;
2147
+ /**
2148
+ * Partition already-gated writes into the encodable ones (returned) and reject
2149
+ * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
2150
+ * or class instance in a `v.any()` field) can NEVER replay — the codec failure
2151
+ * is deterministic, not transient. Rejecting here is essential: otherwise
2152
+ * `encodeWire` throws mid-flush, is classified as transient (a codec error has
2153
+ * no `.code`), and re-queues forever — a silent hang where the caller's Promise
2154
+ * never settles and the optimistic write never rolls back. Encoding is cheap;
2155
+ * the flush is the slow reconnect path.
2156
+ */
2157
+ private encodableOrSettleTerminal;
2158
+ /**
2159
+ * Identity guard for one queued write about to replay: a write stamped under
2160
+ * one identity must never replay under another. The live `queuedIdentities`
2161
+ * map is the source of truth for the current session; a hydrated write whose
2162
+ * id isn't in the map falls back to the stamp persisted with the record
2163
+ * (`item.identity`), so a reload can't replay another user's queued writes.
2164
+ * Only legacy records (persisted before stamps were durable —
2165
+ * `item.identity === undefined`) replay under whatever identity is current.
2166
+ *
2167
+ * `Map.get` returns `undefined` for unstamped/hydrated ids and `item.identity`
2168
+ * is `undefined` for legacy records; a persisted `null` (queued while signed
2169
+ * out) is a real value that must not collapse into `undefined` — hence the
2170
+ * explicit `=== undefined` check rather than `??`. Returns `true` when the
2171
+ * write may replay; otherwise settles it `OFFLINE_IDENTITY_CHANGED` and returns
2172
+ * `false`. Either way the live stamp is consumed.
2173
+ */
2174
+ private passesReplayIdentityGate;
2175
+ /** 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. */
2176
+ private settleReplaySuccess;
2177
+ /**
2178
+ * The entry a shard's cursor lives under.
2179
+ *
2180
+ * Only the server knows that an omitted `shardKey` and an explicit one
2181
+ * spelling out its configured default name are the same shard — the default
2182
+ * is server-side configuration the client never sees. Keying on what was
2183
+ * SENT would split one shard's cursor across two entries, so a write under
2184
+ * one spelling would stop constraining a read under the other. Resolving
2185
+ * `undefined` through the learned name is what keeps both spellings on one
2186
+ * entry.
2187
+ */
2188
+ private cursorKeyFor;
2189
+ /**
2190
+ * Learn the server's own name for the default shard from a response to a
2191
+ * call that named no shard.
2192
+ *
2193
+ * Any cursor recorded before the name was known sits under the placeholder
2194
+ * entry, so it is folded in rather than stranded — otherwise the requirement
2195
+ * from a client's first write would be lost exactly once, which is the kind
2196
+ * of gap that only shows up as a stale read under load.
2197
+ */
2198
+ private learnDefaultShardKey;
2199
+ /**
2200
+ * Record the cursor a write committed at as this shard's read-your-writes
2201
+ * requirement.
2202
+ *
2203
+ * Monotonic: responses can land out of order, and moving the requirement
2204
+ * BACKWARDS would let a later read be answered from a replica copy that
2205
+ * predates a write this client already saw.
2206
+ */
2207
+ private recordShardCursor;
2208
+ /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
2209
+ private settleReplayTerminal;
2210
+ /**
2211
+ * Replay already-identity-gated writes one at a time on the single-call `/rpc`
2212
+ * path, preserving FIFO order (parallel `.then()` chains would race the
2213
+ * ordering callers depend on). Each replays under its stable `mutationId` so
2214
+ * the server dedups a write it already committed (exactly-once). A coded error
2215
+ * is a server verdict (drop it); a codeless (transport/transient) failure stops
2216
+ * the flush and re-queues this write and every unreplayed one for the next
2217
+ * reconnect — their callers stay pending, and the identity guard re-applies on
2218
+ * retry via each record's persisted stamp.
2219
+ */
2220
+ private replaySequential;
2221
+ /**
2222
+ * Coalesce already-identity-gated writes for a single shard into ONE
2223
+ * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
2224
+ * them to the shard DO, which replays each through its single-call dispatch, so
2225
+ * per-entry `mutationId` idempotency and in-order application are inherited from
2226
+ * the proven path. Per-slot demux mirrors {@link replaySequential}'s
2227
+ * classification: success confirms the optimistic layer against the echoed
2228
+ * `commitCursor`; a coded application verdict is terminal; a transient shard
2229
+ * failure (`SHARD_UNAVAILABLE`/`SHARD_ERROR`), a missing slot, or a whole-batch
2230
+ * transport failure re-queues for the next reconnect (never dropping a durable
2231
+ * write). A whole-batch coded rejection (bad request / authorization denial the
2232
+ * server reached a verdict on) is terminal for every entry.
2233
+ *
2234
+ * Returns the writes that must be re-queued and `stop` — `true` when the whole
2235
+ * chunk failed at the transport level, so the caller leaves later chunks queued
2236
+ * rather than sending on. The caller re-queues once, in order, so requeuing is
2237
+ * NOT done here.
2238
+ */
2239
+ private replayBatched;
2240
+ /**
2241
+ * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
2242
+ * in input order. Each slot's envelope classifies its write the same way
2243
+ * {@link replaySequential} does: a success confirms the optimistic layer
2244
+ * against the echoed `commitCursor`; a coded application verdict is terminal;
2245
+ * a transient shard failure ({@link TRANSIENT_BATCH_ERROR_CODES}) or a slot the
2246
+ * server never returned is returned for the caller to re-queue.
2247
+ * @returns the writes that must be re-queued (transient slots), in input order
2248
+ */
2249
+ private settleReplayBatchSlots;
2250
+ }
2251
+ export { BatchSlot as B, ConnectionStatus as C, DEFAULT_MAX_BUFFER as D, LunoraClient as L, MutationCallOptions as M, OptimisticLocalStore as O, SubscriptionError as S, SubscriptionErrorCallback as a, StreamIterable as b, CONFLICT_ERROR_CODE as c, ClientDebugShard as d, ClientDebugSnapshot as e, ClientDebugSubscription as f, ClientQueryRef as g, LunoraClientError as h, LunoraErrorCode as i, MutationSettledEvent as j, OptimisticUpdate as k, StreamHandle as l, SubscriptionCallback as m, SubscriptionRegistry as n, SubscriptionState as o, SyncWatermark as p, createClientQuery as q, createLocalStore as r, createStream as s, getErrorCode as t, getRetryAfterMs as u, isConflictError as v, isForbiddenError as w, isRateLimitedError as x, isUnauthorizedError as y };