@lunora/client 1.0.0-alpha.24 → 1.0.0-alpha.26

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.
@@ -1,2836 +0,0 @@
1
- import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
2
- /**
3
- * Reactive key-value store for local-only client state.
4
- *
5
- * Unlike a server {@link SubscriptionState} (which tracks a live WS connection,
6
- * an `acked` flag, `serverBase`, optimistic layers, and the full subscription
7
- * machinery), a `ClientQueryRef` is purely local — no server round-trip, no
8
- * WebSocket, no persistence. It exists so framework adapters can offer a
9
- * `useClientQuery` hook whose values survive component remounts and are shared
10
- * across every consumer of the same ref, with none of the ceremony or coupling
11
- * of a dedicated context provider.
12
- *
13
- * The store lives inside `LunoraClient` (a private field) and is surfaced through
14
- * `client.getClientQuery(ref)` / `setClientQuery(ref, value)` /
15
- * `subscribeClientQuery(ref, callback)`.
16
- */
17
- /** Opaque handle for a typed client-local query slot. */
18
- interface ClientQueryRef<T = unknown> {
19
- /** Default value when no value has been set explicitly. */
20
- readonly defaultValue: T;
21
- /** Stable identity for the slot. Must be unique within a client instance. */
22
- readonly key: string;
23
- }
24
- /** A subscriber callback for value changes to a {@link ClientQueryRef}. */
25
-
26
- /**
27
- * Create a typed {@link ClientQueryRef}. Call once per slot at module scope
28
- * (or inside a component module) — the ref object is the stable identity.
29
- * @example
30
- * ```ts
31
- * // lunora/client-queries.ts
32
- * import { createClientQuery } from "@lunora/client";
33
- *
34
- * export const sidebarOpen = createClientQuery("sidebarOpen", true);
35
- * export const selectedMessageId = createClientQuery("selectedMessageId", undefined as string | undefined);
36
- * ```
37
- */
38
- declare const createClientQuery: <T>(key: string, defaultValue: T) => ClientQueryRef<T>;
39
- /**
40
- * The machine-readable error codes a client can observe on a failed
41
- * RPC/batch/subscription. Mirrors the server's `CODE_STATUS` keys
42
- * (`@lunora/server`'s `error.ts`) by hand — the client is framework-neutral and
43
- * must never import the server package (wrong dependency direction / would pull
44
- * the server into the browser bundle). Keep this list in sync when a server code
45
- * is added or removed (see the drift-guard note in the plan/maintenance docs).
46
- */
47
- 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"];
48
- /** A machine-readable error `code` the client may observe. Mirror of the server's `LunoraErrorCode`. */
49
- type LunoraErrorCode = (typeof LUNORA_ERROR_CODES)[number];
50
- /** Error code the server uses for optimistic-concurrency conflicts (HTTP 409). */
51
- declare const CONFLICT_ERROR_CODE = "CONFLICT";
52
- /**
53
- * Whether an unknown rejection is an optimistic-concurrency conflict — the
54
- * server lost a write race and the caller should refetch and retry (or surface
55
- * the conflict). Structural check on the `code` property the client attaches
56
- * when decoding the worker's `{ error: { code, message } }` envelope.
57
- */
58
- declare const isConflictError: (error: unknown) => error is Error & {
59
- code: "CONFLICT";
60
- };
61
- /**
62
- * Whether a rejection is an RLS/policy denial (`FORBIDDEN`, HTTP 403) — the
63
- * caller is authenticated but not permitted to read/write the row. The most
64
- * common per-call error a UI must handle in an RLS-first app.
65
- */
66
- declare const isForbiddenError: (error: unknown) => error is Error & {
67
- code: "FORBIDDEN";
68
- };
69
- /** Whether a rejection is an authentication failure (`UNAUTHORIZED`, HTTP 401) — no/invalid identity. */
70
- declare const isUnauthorizedError: (error: unknown) => error is Error & {
71
- code: "UNAUTHORIZED";
72
- };
73
- /**
74
- * Whether a rejection is a rate-limit denial (`TOO_MANY_REQUESTS`, HTTP 429).
75
- * The retry hint (if the server sent one) is read with {@link getRetryAfterMs}.
76
- */
77
- declare const isRateLimitedError: (error: unknown) => error is Error & {
78
- code: "TOO_MANY_REQUESTS";
79
- };
80
- /**
81
- * Read the server's machine-readable `code` off a rejection, narrowed to the
82
- * known {@link LunoraErrorCode} union. Returns `undefined` for a non-`Error`, a
83
- * missing code, or an unrecognized code string (forward-compat server codes read
84
- * as `undefined` here rather than being falsely narrowed).
85
- */
86
- declare const getErrorCode: (error: unknown) => LunoraErrorCode | undefined;
87
- /**
88
- * Read the rate-limit retry hint (`data.retryAfterMs`) off a
89
- * `TOO_MANY_REQUESTS` rejection without hand-casting the `unknown` `data`
90
- * payload. Returns the finite millisecond value the server sent, or `undefined`
91
- * when absent/non-numeric. Pair with {@link isRateLimitedError}.
92
- */
93
- declare const getRetryAfterMs: (error: unknown) => number | undefined;
94
- /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
95
- type FunctionKind = "action" | "mutation" | "query" | "stream";
96
- /**
97
- * Opaque reference to a registered function emitted by `@lunora/codegen`.
98
- *
99
- * At runtime it carries the `&lt;file>:&lt;function>` identifier in `__lunoraRef`.
100
- * Generated declarations decorate this with phantom type parameters so the
101
- * client can infer args / return values per call site.
102
- */
103
- interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
104
- /**
105
- * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
106
- * inference. Never present at runtime; declared as a covariant (output)
107
- * position so a concrete reference stays assignable to a widened one.
108
- */
109
- readonly __lunoraPhantom?: {
110
- args: Args;
111
- kind: Kind;
112
- returns: Return;
113
- };
114
- readonly __lunoraRef: string;
115
- }
116
- /** Extract the args type from a {@link FunctionReference}. */
117
- type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
118
- /** Extract the return type from a {@link FunctionReference}. */
119
- type ReturnOf<F> = F extends FunctionReference<infer _K, infer _A, infer R> ? R : never;
120
- /**
121
- * Typed reference to an HTTP-SSE stream route (`httpRoute.&lt;verb>(path).stream()`)
122
- * emitted by `@lunora/codegen` as `httpStreams.&lt;namespace>.&lt;name>`.
123
- *
124
- * Distinct from {@link FunctionReference}: this is the **HTTP-SSE route stream**
125
- * (opened with `fetch` + `ReadableStream` against the route's own URL), not the
126
- * WS procedure stream (`kind: "stream"`). At runtime it carries the HTTP verb
127
- * and the route path; the phantom marker carries the chunk / searchParams /
128
- * params types so `httpStream` (and the framework hooks over it) infer the
129
- * chunk type end-to-end.
130
- * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
131
- */
132
- interface HttpStreamRef<Chunk = unknown, SearchParams = unknown, Params = unknown> {
133
- /**
134
- * Phantom marker carrying the `Chunk`/`SearchParams`/`Params` type
135
- * parameters for inference. Never present at runtime; declared in a
136
- * covariant (output) position so a concrete reference stays assignable to
137
- * a widened one.
138
- */
139
- readonly __lunoraHttpStream?: {
140
- chunk: Chunk;
141
- params: Params;
142
- searchParams: SearchParams;
143
- };
144
- /** HTTP verb the route binds to (uppercased), e.g. `"GET"`. */
145
- readonly method: string;
146
- /** The route path as declared, e.g. `/api/tokens/:id` — `:name` segments are filled from `params`. */
147
- readonly path: string;
148
- }
149
- /**
150
- * The call-side args of an HTTP-SSE stream route: `:name` path params plus URL query params.
151
- * @experimental Part of the HTTP-SSE stream surface.
152
- */
153
- interface HttpStreamCallArgs<SearchParams = unknown, Params = unknown> {
154
- /** Values for the route path's `:name` segments. */
155
- params?: Params;
156
- /** URL query params, appended to the request URL (undefined entries are skipped). */
157
- searchParams?: SearchParams;
158
- }
159
- /**
160
- * Extract the chunk type from a {@link HttpStreamRef}.
161
- * @experimental Part of the HTTP-SSE stream surface.
162
- */
163
- type HttpStreamChunkOf<R> = R extends HttpStreamRef<infer Chunk, infer _S, infer _P> ? Chunk : never;
164
- /**
165
- * Extract the call-side args type from a {@link HttpStreamRef}.
166
- * @experimental Part of the HTTP-SSE stream surface.
167
- */
168
- type HttpStreamArgsOf<R> = R extends HttpStreamRef<infer _C, infer S, infer P> ? HttpStreamCallArgs<S, P> : never;
169
- type Unsubscribe = () => void;
170
- /**
171
- * Serializable result of `preloadQuery`. Produced on the server during SSR,
172
- * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
173
- * client so the first render shows the server value with no loading flash
174
- * before a live subscription attaches. Every field survives `JSON.stringify`.
175
- */
176
- interface Preloaded<T = unknown> {
177
- readonly __lunoraPreloaded: true;
178
- readonly args: Record<string, unknown>;
179
- readonly functionPath: string;
180
- readonly shardKey?: string;
181
- readonly value: T;
182
- }
183
- /**
184
- * Pluggable storage for the `x-d1-bookmark` value used to provide
185
- * read-your-writes between a mutation and subsequent queries.
186
- */
187
- interface BookmarkStorage {
188
- get: () => string | null;
189
- set: (value: string | null) => void;
190
- }
191
- interface ReconnectOptions {
192
- initialDelayMs?: number;
193
- jitter?: boolean;
194
- maxDelayMs?: number;
195
- }
196
- /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
197
- type PersistenceOperation = "append" | "clear" | "load" | "remove";
198
- /** Context handed to a persistence-error handler. */
199
- interface PersistenceErrorContext {
200
- readonly error: unknown;
201
- /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
202
- readonly mutationId?: string;
203
- readonly operation: PersistenceOperation;
204
- }
205
- interface OfflineQueueOptions {
206
- maxItems?: number;
207
- /**
208
- * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
209
- * exceeded). Without a handler, failures are logged via `console.warn` so they
210
- * are never fully silent. Note: a failed `append` means the write is queued in
211
- * memory but NOT durable — it will not survive a reload.
212
- */
213
- onPersistenceError?: (context: PersistenceErrorContext) => void;
214
- /**
215
- * Queue mutations issued before a shard's first successful WebSocket
216
- * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
217
- * `mutation()`) queues only when the targeted shard has been connected at
218
- * least once (`wasEverConnected`), so the registry / resubscribe handshake
219
- * has run. Set this to `true` for offline-first apps that want to enqueue
220
- * writes on the very first session before the WS is up.
221
- */
222
- queueBeforeFirstConnect?: boolean;
223
- }
224
- /**
225
- * Serializable shape of an offline mutation, durably stored by a
226
- * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
227
- * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
228
- * persisted — a restored mutation is replayed with no original awaiter.
229
- */
230
- interface PersistedMutation {
231
- args: Record<string, unknown>;
232
- functionPath: string;
233
- id: string;
234
- /**
235
- * Issuing identity fingerprint, persisted so a hydrated write replays only
236
- * under the identity that queued it (`null` = queued while signed out).
237
- * Absent on records written by older client versions, which replay under
238
- * the ambient identity for back-compat.
239
- */
240
- identity?: string | null;
241
- shardKey?: string;
242
- /**
243
- * App/schema version stamped at enqueue (from `LunoraClientOptions.persistenceVersion`).
244
- * On hydrate, a record whose `version` doesn't match the current one is dropped
245
- * and purged rather than replayed — so a write persisted by an older deploy
246
- * (with a now-changed function signature) can't replay against the new schema.
247
- * Absent when no `persistenceVersion` is configured (no version gating).
248
- */
249
- version?: string;
250
- }
251
- /**
252
- * Durable store for the offline mutation queue. The default client keeps the
253
- * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
254
- * makes queued writes survive a page reload. Implementations must preserve FIFO
255
- * (enqueue) order in `PersistenceAdapter.load`.
256
- *
257
- * Replay semantics are at-least-once: a mutation is removed only after the
258
- * server confirms (or rejects) it, so a crash between commit and `remove` can
259
- * replay it again on the next load.
260
- */
261
- interface PersistenceAdapter {
262
- /** Append a mutation to durable storage (called on enqueue). */
263
- append: (mutation: PersistedMutation) => Promise<void>;
264
- /** Drop every persisted mutation (e.g. on logout). */
265
- clear: () => Promise<void>;
266
- /** Load all persisted mutations in FIFO order — called once at startup. */
267
- load: () => Promise<PersistedMutation[]>;
268
- /** Remove a mutation by id once it has been replayed (resolved or rejected). */
269
- remove: (id: string) => Promise<void>;
270
- }
271
- /**
272
- * One write handed to an {@link OutboxSink}. Mirrors {@link PersistedMutation}
273
- * plus the custom-mutator identity (`clientId`/`mutationId`/`idempotencyKey`)
274
- * the durable outbox needs to dedupe and watermark replays.
275
- */
276
- interface OutboxMutation {
277
- args: Record<string, unknown>;
278
- /** Stable per-client id; pairs with {@link OutboxMutation.mutationId} as `idempotencyKey`. */
279
- clientId: string;
280
- functionPath: string;
281
- /** `${clientId}:${mutationId}` — sent as `x-lunora-mutation-id` so a replay is server-idempotent. */
282
- idempotencyKey: string;
283
- /** Issuing identity fingerprint (`null` = signed out); drives the sink's identity guard. */
284
- identity: string | null;
285
- /** Monotonic per-client mutation id, backing the server `__client_watermark`. */
286
- mutationId: number;
287
- shardKey?: string;
288
- }
289
- /**
290
- * Pluggable durable outbox seam. When set on {@link LunoraClientOptions.outbox},
291
- * the client delegates offline write durability + at-least-once replay to this
292
- * sink instead of its built-in {@link PersistenceAdapter}-backed `OfflineQueue`.
293
- * `@lunora/db` supplies the blessed implementation (`createExecutorOutboxSink`,
294
- * backed by the TanStack `OfflineExecutor`); the interface itself is
295
- * dependency-free so `@lunora/client` stays TanStack-free.
296
- */
297
- interface OutboxSink {
298
- /**
299
- * Persist and schedule a write for replay. Rejects with an
300
- * `OFFLINE_QUEUE_OVERFLOW`-coded error when the sink's cap is exceeded, so
301
- * the caller can surface back-pressure to the issuing mutation.
302
- */
303
- enqueue: (mutation: OutboxMutation) => Promise<void>;
304
- }
305
- /**
306
- * One persisted query result in the durable read cache (Pillar 2). Keyed in the
307
- * store by `shardKey + functionPath + argsKey`; the record carries everything
308
- * needed to render offline on reload and to resume the live subscription.
309
- */
310
- interface CachedQuery {
311
- /**
312
- * Issuing identity fingerprint (same shape the offline queue stamps). A
313
- * cached value only hydrates when it matches the current identity, so a
314
- * signed-out cache never leaks into a new session. `null` = cached while
315
- * signed out.
316
- */
317
- identity: string | null;
318
- /**
319
- * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
320
- * on reconnect so the server can resume instead of re-snapshotting. Absent
321
- * when the value predates CDC / no cursor was advertised.
322
- */
323
- serverCursor?: number;
324
- /**
325
- * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
326
- * on reconnect so the server only resumes when the client is still on the
327
- * same changelog timeline. Absent when no epoch was advertised.
328
- */
329
- serverEpoch?: string;
330
- /** Wall-clock millis the value was written — drives LRU eviction. */
331
- ts: number;
332
- /** The full query result last seen from the server. */
333
- value: unknown;
334
- /**
335
- * App/schema version stamped when persisted (from `LunoraClientOptions.persistenceVersion`).
336
- * A cached value whose `version` doesn't match the current one is not hydrated —
337
- * so a result of a now-changed shape from an older deploy can't render. Absent
338
- * when no `persistenceVersion` is configured (no version gating).
339
- */
340
- version?: string;
341
- }
342
- /**
343
- * Durable store for the client read cache (Pillar 2): query results survive a
344
- * reload so reads hydrate from disk and render immediately while the socket
345
- * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
346
- * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
347
- * shape over the same IndexedDB plumbing.
348
- */
349
- interface QueryCacheAdapter {
350
- /** Drop every cached query (e.g. on logout / identity change). */
351
- clear: () => Promise<void>;
352
- /** Load every cached query — called once at startup to hydrate reads. */
353
- load: () => Promise<(CachedQuery & {
354
- key: string;
355
- })[]>;
356
- /** Upsert one cached query by key (called when a subscription value advances). */
357
- put: (key: string, entry: CachedQuery) => Promise<void>;
358
- /** Remove one cached query by key. */
359
- remove: (key: string) => Promise<void>;
360
- }
361
- /**
362
- * Resolves the WS `?token=` credential fresh at every (re)connect — the channel
363
- * for short-lived tokens (e.g. the ephemeral admin sub-token the worker mints
364
- * at `POST /_lunora/admin/ws-token`) instead of a static secret in the URL.
365
- * May return the token synchronously or as a Promise; returning `undefined`
366
- * connects without a token. A thrown error / rejected Promise fails that
367
- * connect attempt, and the client retries with its normal reconnect backoff.
368
- */
369
- type WsTokenProvider = () => Promise<string | undefined> | string | undefined;
370
- interface LunoraClientOptions {
371
- /**
372
- * Base path the worker mounts better-auth at, used by the client's
373
- * `getCurrentUser()` to reach the `get-session` route. Defaults to
374
- * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
375
- */
376
- authBasePath?: string;
377
- bookmarkStorage?: BookmarkStorage;
378
- /**
379
- * Stable per-client id backing the custom-mutator watermark. Sent on the
380
- * `connect` envelope (so the server can scope this client's
381
- * `__client_watermark`) and stamped onto every {@link OutboxMutation} the
382
- * {@link LunoraClientOptions.outbox} sink persists, where it pairs with the
383
- * monotonic mutation id to form the idempotency key. The `@lunora/db` path
384
- * persists a stable id alongside the outbox and passes it here; omit for the
385
- * standalone client, which generates an ephemeral per-session id.
386
- */
387
- clientId?: string;
388
- /**
389
- * Default app context sent in the `connect` envelope right after each socket
390
- * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
391
- * as `event.context`. A per-shard context registered via
392
- * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
393
- * hook needs connection context.
394
- */
395
- connectionContext?: Record<string, unknown>;
396
- /**
397
- * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
398
- * handshake doesn't complete within this window — a hung dev proxy or a cold
399
- * worker that never upgrades — the client force-closes the socket and routes
400
- * through its normal reconnect/backoff (surfacing `offline` status) instead
401
- * of leaving the live channel silently stuck on the browser's much longer
402
- * default. Does not affect HTTP queries/mutations (those never ride the WS).
403
- * Defaults to 10000 (10s); set to `0` (or negative) to disable.
404
- */
405
- connectTimeoutMs?: number;
406
- /**
407
- * When `true`, tabs sharing the same origin coordinate via BroadcastChannel
408
- * so only one tab (the "leader") opens WebSocket connections to the server.
409
- * Follower tabs receive subscription data through the channel instead.
410
- *
411
- * Reduces simultaneous WS connections, bandwidth, and cross-tab state drift.
412
- * Requires `BroadcastChannel` (browser-only); silently ignored otherwise.
413
- * Defaults to `false`.
414
- */
415
- crossTabSync?: boolean;
416
- fetch?: typeof fetch;
417
- /**
418
- * Interval (ms) between keepalive pings sent on each open subscription
419
- * socket. The server answers them via the Durable Object's hibernation
420
- * auto-response WITHOUT waking the DO, so an idle socket stays alive across
421
- * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
422
- * `0` (or a negative value) to disable the heartbeat entirely.
423
- */
424
- heartbeatIntervalMs?: number;
425
- /**
426
- * When `true` and a `queryCache` is active, framework hooks (React, Vue, …)
427
- * wait for the durable cache to finish hydrating before their first render
428
- * with an enabled subscription, so users see cached data instead of an
429
- * undefined flash before the socket round-trip. Defaults to `false`.
430
- *
431
- * Requires `queryCache` to be set (not `false`); silently ignored otherwise.
432
- */
433
- hydrateOnStart?: boolean;
434
- offlineQueue?: OfflineQueueOptions;
435
- /**
436
- * Durable outbox seam for offline writes. When supplied (the `@lunora/db`
437
- * path wires `createExecutorOutboxSink`), offline mutations are delegated to
438
- * the sink and the built-in {@link PersistenceAdapter}-backed `OfflineQueue`
439
- * is bypassed, so a db app has exactly one durable write path. Omit for the
440
- * standalone client, which keeps using {@link LunoraClientOptions.persistence}.
441
- */
442
- outbox?: OutboxSink;
443
- /**
444
- * Durable store for the offline mutation queue. Tri-state — an explicit
445
- * {@link PersistenceAdapter} is used as-is; `false` opts out (the queue stays
446
- * in memory, lost on reload); omitted (the default) auto-probes a durable
447
- * IndexedDB store when the `indexedDB` global is present (browsers), otherwise
448
- * in-memory, so SSR/Node/React-Native keep the in-memory behaviour and only
449
- * environments that can persist do. Pass `createAsyncStoragePersistence()` on
450
- * React Native.
451
- */
452
- persistence?: false | PersistenceAdapter;
453
- /**
454
- * App/schema version stamped onto every persisted queued write and cached
455
- * read. Bump it on a breaking change to a function signature or query shape:
456
- * on the next boot, persisted writes / cached reads stamped with a different
457
- * version are dropped (and purged) rather than replayed / hydrated against the
458
- * new schema. Omit to disable version gating (records are never invalidated by
459
- * version).
460
- *
461
- * **Adoption is itself an invalidation event:** records written before you set
462
- * `persistenceVersion` carry no version, so the first boot after enabling it
463
- * purges all currently-queued offline writes (and cached reads) as stale. Adopt
464
- * it on a build where that clean slate is acceptable — typically the same
465
- * breaking deploy you're protecting against — not purely speculatively.
466
- */
467
- persistenceVersion?: string;
468
- /**
469
- * Durable store for the read cache (Pillar 2). When active, query results
470
- * are persisted as their subscriptions advance and hydrated on construction
471
- * so a reload renders cached data before the socket reconnects, then resumes
472
- * the live subscription from the persisted cursor. Tri-state — an explicit
473
- * {@link QueryCacheAdapter} is used as-is; `false` opts out (reads stay in
474
- * memory only); omitted (the default) auto-probes IndexedDB exactly like
475
- * {@link LunoraClientOptions.persistence}.
476
- */
477
- queryCache?: QueryCacheAdapter | false;
478
- reconnect?: ReconnectOptions;
479
- url: string;
480
- WebSocket?: typeof WebSocket;
481
- /**
482
- * Credential appended to the WebSocket URL as `?token=…`. The server matches
483
- * it against `LUNORA_WS_BEARER` (to clear the upgrade gate) and/or
484
- * `LUNORA_ADMIN_TOKEN` (to authorize `__lunora_admin__:*` subscriptions —
485
- * what the studio supplies). Browsers can't set headers on the `WebSocket`
486
- * constructor, so the query parameter is the only channel; it ends up in
487
- * server logs and history, so prefer a short-lived rotating token in
488
- * production over a static secret.
489
- *
490
- * Pass a {@link WsTokenProvider} function to resolve the token fresh at
491
- * every (re)connect — the channel for short-lived credentials such as the
492
- * ephemeral admin sub-token minted by `POST /_lunora/admin/ws-token`: the
493
- * provider re-mints on each reconnect, including the one following a `4001`
494
- * token-expired drop, so a static master token never has to ride the URL.
495
- */
496
- wsToken?: string | WsTokenProvider;
497
- wsUrl?: string;
498
- }
499
- /** Wire envelope sent on `POST /_lunora/rpc`. */
500
- interface RpcEnvelope {
501
- args?: Record<string, unknown>;
502
- /**
503
- * Stable per-client identifier (custom-mutator push path). Pairs with
504
- * {@link RpcEnvelope.mutationId} to form `idempotencyKey` and scope the
505
- * server `__client_watermark`. Absent on plain `client.mutation` calls.
506
- */
507
- clientId?: string;
508
- functionPath: string;
509
- /**
510
- * Idempotency key (`${clientId}:${mutationId}`) for the custom-mutator push
511
- * path, mirrored into the `x-lunora-mutation-id` header. Absent on plain
512
- * `client.mutation` calls.
513
- */
514
- idempotencyKey?: string;
515
- /**
516
- * Monotonic per-client mutation id (custom-mutator push path), backing the
517
- * server-side per-client watermark: `id &lt;= watermark` is a replay (skipped),
518
- * `id == watermark + 1` runs authoritatively, `id > watermark + 1` halts the
519
- * batch so the client resends from `watermark + 1`. Absent on plain
520
- * `client.mutation` calls.
521
- */
522
- mutationId?: number;
523
- shardKey?: string;
524
- }
525
- /**
526
- * Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). A
527
- * watermarked custom-mutator push additionally carries `lastMutationId` — the
528
- * highest per-client sequence the DO has applied — which the client uses to keep
529
- * its `clientSeq` generator monotonic across reloads (see `LunoraClient.callMutator`).
530
- * A plain mutation on a CDC shard carries `commitCursor` — the cursor the write
531
- * committed at — which gates the drop of a per-call optimistic layer.
532
- */
533
- type RpcResponseBody = {
534
- error: {
535
- code: string;
536
- data?: unknown;
537
- message: string;
538
- };
539
- } | {
540
- commitCursor?: number;
541
- lastMutationId?: number;
542
- result: unknown;
543
- };
544
- /** Subscription protocol — client → server. */
545
- interface ClientSubscribeMessage {
546
- id: string;
547
- /**
548
- * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
549
- * for this shard (Pillar 1b resume). Present only when a durable
550
- * {@link QueryCacheAdapter} restored a cached value with a cursor; the
551
- * server replies with a lightweight `resume` frame instead of a full
552
- * snapshot when nothing the query reads changed since it. Absent on a
553
- * first-time subscribe.
554
- */
555
- query: {
556
- args?: Record<string, unknown>;
557
- functionPath?: string;
558
- sinceEpoch?: string;
559
- sinceSeq?: number;
560
- table?: string;
561
- };
562
- type: "subscribe";
563
- }
564
- interface ClientUnsubscribeMessage {
565
- id: string;
566
- type: "unsubscribe";
567
- }
568
- /**
569
- * One-shot control frame sent right after the socket opens. Registers the
570
- * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
571
- * fires the `onConnect` lifecycle hooks; the same context is replayed to
572
- * `onDisconnect` when the socket drops.
573
- */
574
- interface ClientConnectMessage {
575
- /**
576
- * Stable per-client id (persisted alongside the outbox). Lets the server
577
- * scope this connection's `__client_watermark` so custom-mutator pokes can
578
- * echo the right per-client `lastMutationId`. Omitted by clients that don't
579
- * use custom mutators.
580
- */
581
- clientId?: string;
582
- context?: Record<string, unknown>;
583
- id: string;
584
- type: "connect";
585
- }
586
- /**
587
- * Subscribe to a declarative **shape** — server-side partial replication scoped
588
- * by `shardBy` + the shape's predicate + RLS. The client sends the shape *name*
589
- * + validated `args`; the server resolves the trusted `where` (identity/RLS
590
- * `baseWhere` the client can't forge) and streams the matching rowset, then live
591
- * {@link ServerPokePartMessage} diffs. `id` namespaces the subscription and is
592
- * echoed as `shapeId` on every poke part.
593
- */
594
- interface ClientShapeSubscribeMessage {
595
- id: string;
596
- shape: {
597
- args?: Record<string, unknown>;
598
- name: string;
599
- };
600
- /**
601
- * Resume from this checkpoint (the `__cdc_log` cursor the client last
602
- * applied for this shape). When absent or below the server's retained floor
603
- * (`minCdcSeq`), the server re-seeds with a full insert-poke instead of a
604
- * delta.
605
- */
606
- sinceCheckpoint?: number;
607
- /**
608
- * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
609
- * to. A mismatch (forked changelog timeline) forces a full re-seed even when
610
- * the cursor is numerically in range.
611
- */
612
- sinceEpoch?: string;
613
- type: "shape_subscribe";
614
- }
615
- /** Cancel a shape subscription started with the same `id`. */
616
- interface ClientShapeUnsubscribeMessage {
617
- id: string;
618
- type: "shape_unsubscribe";
619
- }
620
- interface ClientAckMessage {
621
- id: string;
622
- type: "ack";
623
- }
624
- /**
625
- * Start a streaming query. The id namespaces a fresh stream and is echoed on
626
- * every {@link ServerChunkMessage} the server pushes back. Cancel a running
627
- * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
628
- * subscription and stream id-spaces share the cancel channel; the prefix
629
- * (`sub_*` vs `stream_*`) keeps the local registries searchable.
630
- */
631
- interface ClientStreamMessage {
632
- id: string;
633
- query: {
634
- args?: Record<string, unknown>;
635
- functionPath: string;
636
- shardKey?: string;
637
- };
638
- type: "stream";
639
- }
640
- /**
641
- * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
642
- * shard. While joined, the client receives every {@link ServerWhisperMessage}
643
- * other members broadcast to the topic.
644
- */
645
- interface ClientWhisperSubscribeMessage {
646
- topic: string;
647
- type: "whisper_subscribe" | "whisper_unsubscribe";
648
- }
649
- /**
650
- * Broadcast ephemeral `data` to the topic's other members on the shard. The
651
- * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
652
- * write) — for typing indicators, live cursors, presence pings. The sender does
653
- * not receive its own whisper.
654
- */
655
- interface ClientWhisperMessage {
656
- data?: unknown;
657
- topic: string;
658
- type: "whisper";
659
- }
660
- type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientShapeSubscribeMessage | ClientShapeUnsubscribeMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
661
- /** Subscription protocol — server → client. */
662
- interface ServerDataMessage {
663
- /**
664
- * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
665
- * client persists it as the query's `serverCursor` and replays it as
666
- * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
667
- */
668
- cursor?: number;
669
- data?: unknown;
670
- delta?: unknown;
671
- /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
672
- epoch?: string;
673
- id: string;
674
- /**
675
- * The highest custom-mutator `mutationId` from this client the server has
676
- * now applied (the per-client `__client_watermark`). Echoed so the client's
677
- * outbox can drop confirmed pending mutations and let TanStack DB collapse
678
- * the matching optimistic overlay. Absent on shards without custom mutators.
679
- */
680
- lastMutationId?: number;
681
- type: "data" | "delta";
682
- }
683
- /**
684
- * Lightweight resume acknowledgement (Pillar 1b): the server determined that
685
- * nothing the subscription reads changed since the client's `sinceSeq`, so it
686
- * skips re-sending the snapshot. The client keeps its cached value and only
687
- * advances `serverCursor` to `cursor`.
688
- */
689
- interface ServerResumeMessage {
690
- cursor?: number;
691
- /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
692
- epoch?: string;
693
- id: string;
694
- /** Per-client custom-mutator watermark (see {@link ServerDataMessage.lastMutationId}). */
695
- lastMutationId?: number;
696
- type: "resume";
697
- }
698
- /**
699
- * Settled acknowledgement for a **list** subscription: a write touched one of
700
- * the subscription's read tables but produced a byte-identical result, so the
701
- * server suppressed the data frame. Sent ONLY to a `@lunora/db` custom-mutator
702
- * client (one that announced a `clientId`, hence has a server-side
703
- * `__client_watermark`) so its optimistic list overlay drops even when no data
704
- * frame arrives. Plain `useQuery` subscribers never receive it, and an older
705
- * client safely ignores the unknown frame.
706
- */
707
- interface ServerSettledMessage {
708
- cursor?: number;
709
- /** The CDC epoch this settled frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
710
- epoch?: string;
711
- id: string;
712
- /**
713
- * The highest custom-mutator `mutationId` from this client the server has
714
- * now applied (the per-client `__client_watermark`). Forwarded to a
715
- * collection's `onCheckpoint` so it can drop the overlay for the confirmed
716
- * write whose result didn't change this list.
717
- */
718
- lastMutationId?: number;
719
- type: "settled";
720
- }
721
- interface ServerErrorMessage {
722
- error?: unknown;
723
- id?: string;
724
- message?: string;
725
- type: "error";
726
- }
727
- interface ServerAckMessage {
728
- id: string;
729
- type: "ack";
730
- }
731
- interface ServerCompleteMessage {
732
- id: string;
733
- type: "complete";
734
- }
735
- /** One frame of a streaming query — `data` carries the user-yielded chunk. */
736
- interface ServerChunkMessage {
737
- data: unknown;
738
- id: string;
739
- type: "chunk";
740
- }
741
- /**
742
- * An ephemeral whisper relayed from another member of `topic` on the same shard
743
- * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
744
- * is the sender's verified user id when known (absent for an anonymous sender).
745
- * Never persisted server-side.
746
- */
747
- interface ServerWhisperMessage {
748
- data: unknown;
749
- from?: string;
750
- topic: string;
751
- type: "whisper";
752
- }
753
- /**
754
- * One row-level change in a shape's replication stream — the wire form of the
755
- * DO's `__cdc_log` `CdcChange`. `insert`/`update` carry the post-image in
756
- * `value` (projected to the shape's `columns`); `delete` omits it, identifying
757
- * the removed row by `key` alone. The client applies these to its local
758
- * collection; an unknown `key` on a `delete` is a safe no-op (a row the client
759
- * never had in this shape).
760
- */
761
- interface RowOp {
762
- /** Row primary key (`_id`). */
763
- key: string;
764
- op: "delete" | "insert" | "update";
765
- /** Logical table the row belongs to. */
766
- table: string;
767
- /** Post-image document for insert/update; absent on delete. */
768
- value?: Record<string, unknown>;
769
- }
770
- /**
771
- * Opens a **poke** — an atomically-applied batch of shape diffs (Zero's poke
772
- * protocol). A `pokeStart` is followed by zero or more {@link ServerPokePartMessage}
773
- * frames and closed by exactly one {@link ServerPokeEndMessage}; the client
774
- * buffers every part and applies them in a single transaction at `pokeEnd`, so a
775
- * socket that drops mid-poke simply re-seeds on reconnect (no torn view).
776
- */
777
- interface ServerPokeStartMessage {
778
- /** The checkpoint the client's view is expected to be at before this poke applies (for ordering/gap detection). */
779
- baseCheckpoint?: number;
780
- /** CDC epoch this poke belongs to; a mismatch forces the client to re-seed rather than apply. */
781
- epoch?: string;
782
- /** Correlates this poke's `pokeStart`/`pokePart`/`pokeEnd` frames. */
783
- pokeId: string;
784
- type: "pokeStart";
785
- }
786
- /** One shape's slice of an in-flight poke: the row-ops to apply for `shapeId`. */
787
- interface ServerPokePartMessage {
788
- /** Per-client custom-mutator watermark carried with this slice (see {@link ServerSettledMessage.lastMutationId}). */
789
- lastMutationId?: number;
790
- pokeId: string;
791
- /** Ordered row-level changes for this shape, applied in sequence at `pokeEnd`. */
792
- rowsPatch: RowOp[];
793
- /** The {@link ClientShapeSubscribeMessage.id} these row-ops belong to. */
794
- shapeId: string;
795
- type: "pokePart";
796
- }
797
- /**
798
- * Closes a poke: the client commits the buffered parts atomically and advances
799
- * its checkpoint to {@link ServerPokeEndMessage.checkpoint} (the `__cdc_log`
800
- * cursor high-watermark the view now reflects), replayed as `sinceCheckpoint` on
801
- * the next reconnect.
802
- */
803
- interface ServerPokeEndMessage {
804
- /** The `__cdc_log` cursor the view is at after applying this poke. */
805
- checkpoint?: number;
806
- /** CDC epoch the {@link ServerPokeEndMessage.checkpoint} belongs to. */
807
- epoch?: string;
808
- pokeId: string;
809
- type: "pokeEnd";
810
- }
811
- type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
812
- /**
813
- * The authenticated user as exposed client-side, mirroring better-auth's
814
- * `user` row (the `user` field of the `get-session` response). Kept minimal
815
- * and structural — only `id` is guaranteed; the rest are the common better-auth
816
- * fields, and the index signature carries any plugin-contributed extras.
817
- */
818
- interface User {
819
- readonly createdAt?: NullableTimestamp;
820
- readonly email?: null | string;
821
- readonly emailVerified?: boolean | null;
822
- readonly id: string;
823
- readonly image?: null | string;
824
- readonly name?: null | string;
825
- readonly [key: string]: unknown;
826
- readonly updatedAt?: NullableTimestamp;
827
- }
828
- /**
829
- * One pending scheduled function, as returned by the worker's
830
- * `GET /_lunora/admin/scheduled` endpoint. Mirrors `@lunora/scheduler`'s
831
- * `ScheduleRecord` structurally so the client carries no dependency on it.
832
- */
833
- interface ScheduleRecord {
834
- args: Record<string, unknown>;
835
- /**
836
- * Dispatch attempts already made. Absent (treated as 0) until the first
837
- * failure; on a dead-letter record it is the exhausted count (> the retry
838
- * budget). Surfaced so the studio can show how hard a job tried before it
839
- * was parked.
840
- */
841
- attempts?: number;
842
- enqueuedAt: number;
843
- functionPath: string;
844
- id: string;
845
- /** Logical workpool the job is routed to (concurrency-gated), when any. */
846
- pool?: string;
847
- scheduledFor: number;
848
- shardKey?: string;
849
- }
850
- /**
851
- * One workpool's live backlog, as returned by the worker's
852
- * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
853
- * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
854
- */
855
- interface SchedulerPoolStatus {
856
- /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
857
- inFlight: number;
858
- /** The pool's concurrency cap. */
859
- maxConcurrency: number;
860
- /** The logical workpool name. */
861
- name: string;
862
- /** Pending jobs routed to this pool but not yet dispatched. */
863
- queued: number;
864
- }
865
- /**
866
- * The app-level scheduler backlog, as returned by the worker's
867
- * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
868
- * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
869
- * `inFlight` across every pool — the headline numbers for the studio SLO
870
- * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
871
- */
872
- interface SchedulerStatus {
873
- /** Sum of every pool's `queued` count — the total pending backlog. */
874
- backlog: number;
875
- /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
876
- inFlight: number;
877
- /** Per-pool backlog breakdown. */
878
- pools: SchedulerPoolStatus[];
879
- }
880
- /**
881
- * One shard's request volume, as returned by the worker's
882
- * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
883
- * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
884
- * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
885
- */
886
- interface ShardTrafficEntry {
887
- requests: number;
888
- shardKey: string;
889
- }
890
- /**
891
- * The whole-shard-set traffic distribution returned by the worker's
892
- * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
893
- * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
894
- * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
895
- * lint after the studio tags each entry with its sharded function `group`.
896
- */
897
- interface ShardTrafficResult {
898
- failed: number;
899
- ok: number;
900
- shards: ShardTrafficEntry[];
901
- }
902
- /**
903
- * One object in the storage bucket, as returned by the worker's
904
- * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
905
- * `R2ObjectLike` structurally.
906
- */
907
- interface StorageObject {
908
- customMetadata?: Record<string, string>;
909
- etag: string;
910
- httpMetadata?: {
911
- contentType?: string;
912
- };
913
- key: string;
914
- size: number;
915
- /**
916
- * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
917
- * ISO string over the wire; a mock may supply epoch ms — so consumers should
918
- * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
919
- */
920
- uploaded?: number | string;
921
- }
922
- /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
923
- interface StorageListPage {
924
- cursor?: string;
925
- objects: StorageObject[];
926
- }
927
- /**
928
- * One argument of a registered function, derived from its `v.*` validator by the
929
- * worker. A compact signature shape — enough to render a function's API without
930
- * the build-time codegen types.
931
- */
932
- interface FunctionArgumentDescriptor {
933
- /** Element validator kind for an `array` arg (one level), e.g. `string`. */
934
- element?: string;
935
- /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
936
- kind: string;
937
- /** The argument name. */
938
- name: string;
939
- /** True when the arg is wrapped in `v.optional(...)`. */
940
- optional: boolean;
941
- /** Target table for an `id` arg (`v.id("table")`). */
942
- table?: string;
943
- }
944
- /**
945
- * One registered function, as returned by the worker's
946
- * `GET /_lunora/admin/functions` endpoint: its `&lt;file>:&lt;function>` path, which
947
- * client method (`query` / `mutation` / `action`) invokes it, and its argument
948
- * signature. `args` is absent on responses from an older worker.
949
- */
950
- interface FunctionDescriptor {
951
- args?: FunctionArgumentDescriptor[];
952
- kind: "action" | "mutation" | "query";
953
- path: string;
954
- }
955
- /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
956
- interface GlobalTableInfo {
957
- name: string;
958
- rowCount: number;
959
- }
960
- /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
961
- interface GlobalTablePage {
962
- columns: string[];
963
- /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
964
- refs?: Record<string, string>;
965
- rows: Record<string, unknown>[];
966
- total: number;
967
- }
968
- /**
969
- * One equality constraint a facet-value click adds to the global browser's view
970
- * (`column = value`). `value` is the raw stored scalar the facet returned, sent
971
- * as-is and bound server-side, so it never injects SQL.
972
- */
973
- interface GlobalFilterClause {
974
- column: string;
975
- value: unknown;
976
- }
977
- /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
978
- interface GlobalFacetValue {
979
- count: number;
980
- value: unknown;
981
- }
982
- /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
983
- interface GlobalFacetResult {
984
- truncated: boolean;
985
- values: GlobalFacetValue[];
986
- }
987
- /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
988
- type NullableTimestamp = null | number | string;
989
- /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
990
- type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
991
- /** The lifecycle mutations the status endpoint accepts. */
992
- type WorkflowInstanceAction = "pause" | "resume" | "terminate";
993
- /** One row of the workflow-instances list. */
994
- interface WorkflowInstanceSummary {
995
- createdOn?: string;
996
- endedOn?: string;
997
- id: string;
998
- startedOn?: string;
999
- status: WorkflowInstanceStatus;
1000
- }
1001
- /** One durable step of an instance's execution timeline. */
1002
- interface WorkflowStepDetail {
1003
- /** 1-based attempt count (`> 1` means the step retried). */
1004
- attempts?: number;
1005
- end?: string;
1006
- error?: unknown;
1007
- name: string;
1008
- output?: unknown;
1009
- start?: string;
1010
- success?: boolean;
1011
- /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
1012
- type?: string;
1013
- }
1014
- /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
1015
- interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
1016
- error?: unknown;
1017
- output?: unknown;
1018
- params?: unknown;
1019
- steps: WorkflowStepDetail[];
1020
- }
1021
- /** A page of workflow instances. */
1022
- interface WorkflowInstancePage {
1023
- /**
1024
- * Whether workflow inspection is configured on the worker (a Cloudflare
1025
- * account id + API token). `false` when the admin proxy reports it can't
1026
- * inspect instances; omitted (treated as configured) otherwise. Lets a
1027
- * caller render a "set credentials" state without a failed request.
1028
- */
1029
- configured?: boolean;
1030
- instances: WorkflowInstanceSummary[];
1031
- page: number;
1032
- perPage: number;
1033
- totalCount?: number;
1034
- }
1035
- type SubscriptionCallback = (data: unknown) => void;
1036
- /** A subscription-scoped error the server pushed for this subscription id. */
1037
- interface SubscriptionError {
1038
- code?: string;
1039
- message: string;
1040
- }
1041
- type SubscriptionErrorCallback = (error: SubscriptionError) => void;
1042
- /**
1043
- * One active per-call optimistic transform layered onto a subscription. The
1044
- * displayed value is the authoritative {@link SubscriptionState.serverBase}
1045
- * folded through every layer's `transform`, in order — so an incoming server
1046
- * frame re-folds the still-pending layers onto the new base (rebasing) instead
1047
- * of clobbering them. A layer is dropped — gaplessly — once a `data`/`delta`
1048
- * frame whose `cursor >= commitCursor` arrives (its write is now reflected in
1049
- * `serverBase`); `commitCursor` is the CDC cursor the server echoed on the
1050
- * mutation's response, and stays `undefined` while the write is still queued/
1051
- * in-flight (so the overlay survives unrelated deltas until confirmed).
1052
- */
1053
- interface OptimisticLayer {
1054
- /** The committed CDC cursor (from the mutation response); `undefined` until confirmed. */
1055
- commitCursor?: number;
1056
- readonly id: symbol;
1057
- readonly transform: (current: unknown) => unknown;
1058
- }
1059
- interface SubscriptionState {
1060
- /** True once the server has acked the subscription on the current socket. */
1061
- acked: boolean;
1062
- readonly args: Record<string, unknown>;
1063
- /**
1064
- * Stable wire-key of `args` (`stableWireKey`), computed once at subscribe
1065
- * time. Cached so the optimistic-update fan-out can compare against a
1066
- * mutation's args key without re-serializing every subscription's args on
1067
- * every mutation.
1068
- */
1069
- readonly argsKey: string;
1070
- readonly callbacks: Set<SubscriptionCallback>;
1071
- /**
1072
- * Notified when a `settled` frame advances this subscription's watermark — a
1073
- * write touched the subscription's tables but the result was byte-identical,
1074
- * so the server suppressed the data frame. A `@lunora/db` list collection
1075
- * uses this to drop the optimistic overlay for the confirmed write.
1076
- *
1077
- * A SET (not a single slot) because `SubscriptionState` is SHARED across
1078
- * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
1079
- * collection may subscribe to a query a plain `useQuery` already opened, so
1080
- * each subscriber registers its own callback (mirroring `callbacks` /
1081
- * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
1082
- * `useQuery` consumers register nothing, leaving the set empty.
1083
- */
1084
- readonly checkpointCallbacks: Set<(watermark: {
1085
- checkpoint?: number;
1086
- mutationId?: number;
1087
- }) => void>;
1088
- /** Notified when the server rejects this subscription (e.g. admin auth). */
1089
- readonly errorCallbacks: Set<SubscriptionErrorCallback>;
1090
- readonly fn: FunctionReference;
1091
- readonly id: string;
1092
- /**
1093
- * The highest custom-mutator `mutationId` from this client the server has
1094
- * applied, captured from the last `settled` frame (the suppressed-list-frame
1095
- * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
1096
- * Absent until a `settled` frame arrives.
1097
- */
1098
- lastMutationId?: number;
1099
- /** Last known value, used to short-circuit `useQuery`-style consumers. */
1100
- lastValue: unknown;
1101
- /**
1102
- * Active per-call optimistic layers, in application order (see
1103
- * {@link OptimisticLayer}). Empty for subscriptions with no pending per-call
1104
- * optimistic write — the common case, where `lastValue` tracks `serverBase`
1105
- * exactly and behaviour is identical to a plain server-value assignment.
1106
- */
1107
- optimisticLayers: OptimisticLayer[];
1108
- /**
1109
- * The authoritative server value the optimistic layers fold onto — the value
1110
- * with NO optimistic overlay. Tracks `lastValue` exactly whenever no layers
1111
- * are active; diverges only while a per-call optimistic write is pending. A
1112
- * server frame updates this (and re-folds the layers); the durable read cache
1113
- * persists this, never the optimistic overlay.
1114
- */
1115
- serverBase: unknown;
1116
- /**
1117
- * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
1118
- * captured from the last `data`/`delta`/`resume` frame. Persisted to the
1119
- * durable read cache and replayed as `sinceSeq` on reconnect so the server
1120
- * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
1121
- * first cursor-stamped frame arrives.
1122
- */
1123
- serverCursor?: number;
1124
- /**
1125
- * The CDC `epoch` token the `serverCursor` belongs to, captured from the
1126
- * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
1127
- * only when the client is still on the same changelog timeline — a reset or
1128
- * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
1129
- * until the first epoch-stamped frame arrives.
1130
- */
1131
- serverEpoch?: string;
1132
- readonly shardKey?: string;
1133
- }
1134
- /**
1135
- * Active subscription registry. The client keys subscriptions by
1136
- * `(functionPath, stableWireKey(args), shardKey)` so duplicate calls share a
1137
- * single server-side registration. Args are stably encoded (keys sorted at every
1138
- * depth) so two structurally-equal arg records constructed with a different key
1139
- * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
1140
- * duplicate subscription. Encoding the args' **wire form** keeps the key
1141
- * byte-identical for pure-JSON args while giving wire-typed args (`bigint`,
1142
- * `Date`, bytes, …) distinct stable tokens instead of a throw.
1143
- */
1144
- declare class SubscriptionRegistry {
1145
- static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
1146
- private readonly byKey;
1147
- private readonly byId;
1148
- get(key: string): SubscriptionState | undefined;
1149
- getById(id: string): SubscriptionState | undefined;
1150
- add(state: SubscriptionState): void;
1151
- remove(state: SubscriptionState): void;
1152
- all(): SubscriptionState[];
1153
- }
1154
- /**
1155
- * Read/write handle over the client's live query cache, handed to a mutation's
1156
- * `withOptimisticUpdate` callback so a single mutation can optimistically patch
1157
- * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
1158
- *
1159
- * `getQuery` reads the current value (server value or any still-pending
1160
- * optimistic override) of a subscribed query; `setQuery` registers a constant
1161
- * optimistic layer on top. The whole batch rebases onto incoming deltas and
1162
- * settles together — confirmed on the mutation's commit cursor, or rolled back
1163
- * on failure — the same per-subscription layer machinery the single-query
1164
- * per-call `optimistic` transform uses, generalized to N queries.
1165
- */
1166
- interface OptimisticLocalStore {
1167
- /**
1168
- * Every loaded subscription on `function_`, regardless of args, paired with
1169
- * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
1170
- * when a write must patch every variant of a list query (all channels,
1171
- * all filters) without enumerating their args up front.
1172
- */
1173
- getAllQueries: <F extends FunctionReference>(function_: F) => {
1174
- args: ArgsOf<F>;
1175
- value: ReturnOf<F> | undefined;
1176
- }[];
1177
- /**
1178
- * Current cached value for the subscribed `(function_, args)` query, or
1179
- * `undefined` when nothing is subscribed/loaded for it. Reflects any
1180
- * optimistic override already written in this batch.
1181
- */
1182
- getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
1183
- /**
1184
- * Write an optimistic override for the subscribed `(function_, args)`
1185
- * query. A no-op (returns without effect) when no subscription matches —
1186
- * mirroring Convex, where you only patch queries the page is watching.
1187
- */
1188
- setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
1189
- }
1190
- /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
1191
- type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
1192
- /**
1193
- * Build an {@link OptimisticLocalStore} bound to a subscription registry and the
1194
- * mutation's shard key. Each `setQuery(value)` registers a constant-value layer
1195
- * on its target subscription (via `applyOptimisticLayer`): the predicted value
1196
- * survives incoming server deltas (re-clamped, masking concurrent changes to that
1197
- * query — not merged) and drops gaplessly on the mutation's commit cursor, like
1198
- * the single-query per-call `optimistic` path. Returns the store plus the ordered
1199
- * `confirm` (success) and `rollback` (failure) closures every `setQuery` produced,
1200
- * so the caller settles the whole batch when the mutation does.
1201
- */
1202
- declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined) => {
1203
- confirms: ((commitCursor: number | undefined) => void)[];
1204
- rollbacks: (() => void)[];
1205
- store: OptimisticLocalStore;
1206
- };
1207
- declare const DEFAULT_MAX_BUFFER = 1024;
1208
- interface StreamHandle<T = unknown> {
1209
- /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
1210
- readonly complete: () => void;
1211
- /** Surface an error to any pending consumer; subsequent pushes are dropped. */
1212
- readonly fail: (error: Error) => void;
1213
- /**
1214
- * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
1215
- * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
1216
- * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
1217
- * the producer never sees a thrown exception.
1218
- */
1219
- readonly push: (value: T) => void;
1220
- }
1221
- interface StreamIterable<T> extends AsyncIterable<T> {
1222
- /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
1223
- cancel: () => void;
1224
- }
1225
- /**
1226
- * Build a stream handle paired with an async-iterable. The handle is the
1227
- * server-driven side (the WS dispatcher pushes chunks / completes / errors);
1228
- * the iterable is what the user awaits. `onCancel` is invoked exactly once
1229
- * when the consumer calls `.cancel()` (or `.return()`) so the client can
1230
- * send a `{type:"unsubscribe"}` frame to the server.
1231
- */
1232
- declare const createStream: <T>(options: {
1233
- maxBuffer?: number;
1234
- onCancel: () => void;
1235
- }) => {
1236
- handle: StreamHandle<T>;
1237
- iterable: StreamIterable<T>;
1238
- };
1239
- /**
1240
- * Aggregate live-socket health across every shard connection, for a UI status
1241
- * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
1242
- * is (re)connecting and none is open; `connected` = at least one socket is open;
1243
- * `offline` = sockets exist but all are down (between reconnect attempts).
1244
- */
1245
- type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
1246
- /**
1247
- * Terminal verdict for a mutation that passed through the offline queue,
1248
- * delivered to {@link LunoraClient.onMutationSettled}.
1249
- *
1250
- * Unlike the Promise returned by {@link LunoraClient.mutation} — which only the
1251
- * original caller can await, and which no longer exists after a reload — this
1252
- * fires for *every* queued write the server (or the queue) reaches a verdict on,
1253
- * including writes restored from durable storage in a later session. It is the
1254
- * channel a UI uses to tell the user "your queued change couldn't be saved"
1255
- * instead of silently dropping a rolled-back optimistic row.
1256
- *
1257
- * `status: "rejected"` carries the failure `code` (e.g. `CONFLICT`,
1258
- * `OFFLINE_QUEUE_OVERFLOW`, `OFFLINE_IDENTITY_CHANGED`) and the `error`.
1259
- * `hadAwaiter` is `false` for a write whose original `mutation()` Promise is
1260
- * gone (a hydrated/post-reload replay or an eviction), so a listener can tell
1261
- * "the caller already saw this" apart from "nothing else will report this".
1262
- */
1263
- interface MutationSettledEvent {
1264
- /** The write's args, so a listener can describe or re-offer the change. */
1265
- readonly args: Record<string, unknown>;
1266
- /** Server/queue error code on `rejected` (e.g. `CONFLICT`), when present. */
1267
- readonly code?: string;
1268
- /** The rejection error on `status: "rejected"`. */
1269
- readonly error?: unknown;
1270
- /** The `&lt;file>:&lt;function>` reference of the mutation. */
1271
- readonly functionPath: string;
1272
- /** Whether a live caller was still awaiting this write's `mutation()` Promise. */
1273
- readonly hadAwaiter: boolean;
1274
- /** The write's stable id (idempotency key / queue id). */
1275
- readonly id: string;
1276
- /** Shard the write targeted, if any. */
1277
- readonly shardKey?: string;
1278
- /** Terminal outcome. */
1279
- readonly status: "committed" | "rejected";
1280
- }
1281
- /**
1282
- * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
1283
- * machinery plus `shardKey`. Exported (at the end of this file) so the framework
1284
- * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
1285
- * `mutate(args, options?)` against one canonical definition instead of
1286
- * re-declaring it.
1287
- */
1288
- interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
1289
- /**
1290
- * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
1291
- * durable outbox replay a committed-but-unacked write under its *original* key
1292
- * so the server dedups it instead of applying it twice. Omit for normal calls —
1293
- * each then gets a fresh key.
1294
- */
1295
- mutationId?: string;
1296
- optimistic?: (current: TCurrent | undefined) => TValue;
1297
- /**
1298
- * Convex-parity multi-query optimistic update. Receives an
1299
- * `OptimisticLocalStore` over the live subscription cache plus the
1300
- * mutation's args, so one mutation can patch many subscribed queries at
1301
- * once; every write is rolled back atomically if the mutation fails.
1302
- */
1303
- optimisticUpdate?: OptimisticUpdate<TArgs>;
1304
- /**
1305
- * Sync predicate evaluated just before the offline queue replays this
1306
- * write on reconnect. When it returns `false` the mutation is dropped
1307
- * instead of replayed — use it to guard against replaying writes whose
1308
- * assumptions are no longer valid (e.g. the document it referred to was
1309
- * deleted by another client while this tab was offline).
1310
- */
1311
- precondition?: () => boolean;
1312
- shardKey?: string;
1313
- }
1314
- /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
1315
- type ShapeCallback = (rows: Record<string, unknown>[]) => void;
1316
- /**
1317
- * The high-water marks a shape poke has now synced to the client: `checkpoint`
1318
- * is the op-log cursor and `mutationId` the highest custom-mutator id the server
1319
- * echoed for this client. A `@lunora/db` collection feeds these into its
1320
- * checkpoint registry to drop optimistic overlays once the server's authoritative
1321
- * rows have landed.
1322
- */
1323
- interface SyncWatermark {
1324
- checkpoint?: number;
1325
- mutationId?: number;
1326
- }
1327
- /**
1328
- * An `Error` carrying the server's machine-readable `code` and (for a
1329
- * `LunoraError`) structured `data`, plus an optional actionable `hint` (Markdown)
1330
- * and `docsUrl` resolved from the central error catalog. The client's public
1331
- * error contract for RPC/batch failures — a UI can render `hint`/`docsUrl` to
1332
- * tell the user how to fix the error. The `(string & {})` arm keeps
1333
- * forward-compat/unknown server codes assignable without losing autocomplete on
1334
- * the known {@link LunoraErrorCode} union.
1335
- */
1336
- type LunoraClientError = Error & {
1337
- code?: LunoraErrorCode | (string & {});
1338
- data?: unknown;
1339
- docsUrl?: string;
1340
- hint?: string | string[];
1341
- };
1342
- /** One demuxed result slot of a {@link LunoraClient.batch} call (plan 088). */
1343
- type BatchSlot = {
1344
- error: LunoraClientError;
1345
- ok: false;
1346
- } | {
1347
- ok: true;
1348
- value: unknown;
1349
- };
1350
- /**
1351
- * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
1352
- * a single multiplexed WebSocket.
1353
- *
1354
- * Reconnect, offline queueing, and optimistic updates are all handled here;
1355
- * see the package README for the wire protocol.
1356
- */
1357
- declare class LunoraClient {
1358
- /** 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. */
1359
- private static readonly MAX_POKE_BUFFERS;
1360
- /**
1361
- * Create a typed {@link ClientQueryRef}. Convenience wrapper around
1362
- * {@link createClientQuery} so you don't need a separate import.
1363
- * @example
1364
- * ```ts
1365
- * const sidebarOpen = LunoraClient.createClientQuery("sidebarOpen", true);
1366
- * ```
1367
- */
1368
- static createClientQuery<T>(key: string, defaultValue: T): ClientQueryRef<T>;
1369
- readonly url: string;
1370
- readonly wsUrl: string;
1371
- /** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
1372
- private readonly clientQueryStore;
1373
- private wsToken;
1374
- /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
1375
- private readonly authBasePath;
1376
- private readonly fetchImpl;
1377
- private readonly WebSocketImpl;
1378
- private readonly bookmark;
1379
- private readonly reconnectOptions;
1380
- /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
1381
- private readonly connectTimeoutMs;
1382
- /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
1383
- private readonly heartbeatIntervalMs;
1384
- private readonly offlineQueue;
1385
- /**
1386
- * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
1387
- * set, offline writes are delegated here and the built-in {@link OfflineQueue}
1388
- * is bypassed, so a db app has exactly one durable write path.
1389
- */
1390
- private readonly outbox;
1391
- /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
1392
- private readonly clientId;
1393
- /**
1394
- * `true` when the constructor's hydration microtask has finished loading the
1395
- * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
1396
- * the cache is ready for synchronous `peekHydratedQuery` reads.
1397
- */
1398
- private readyResolved;
1399
- /** Resolvers for `whenReady()` — called once hydration completes. */
1400
- private readyResolve;
1401
- /**
1402
- * Promise that resolves once the durable read cache has been loaded. When
1403
- * `hydrateOnStart` is not set or no query cache is configured, resolves
1404
- * immediately (the constructor creates an already-resolved promise).
1405
- */
1406
- private readonly readyPromise;
1407
- /**
1408
- * Highest custom-mutator watermark the server has echoed for this client,
1409
- * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
1410
- * `__client_watermark` per shard. `callMutator` bumps it from every
1411
- * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
1412
- * it so a reload (which resets the in-memory counter) never reissues a stale
1413
- * sequence the server would silently swallow as a replay.
1414
- */
1415
- private readonly clientWatermarks;
1416
- /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
1417
- private outboxMutationCounter;
1418
- private readonly onPersistenceError;
1419
- private readonly persistence;
1420
- /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
1421
- private readonly persistenceVersion;
1422
- /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
1423
- private outboxLeaderRelease;
1424
- /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
1425
- private readonly queryCache;
1426
- /**
1427
- * Values restored from the `queryCache` at construction, keyed by the
1428
- * read-cache key, awaiting the `subscribe()` that will consume them. A
1429
- * key is consumed (deleted) the first time its subscription is created, so
1430
- * the cache only ever seeds the initial value — live frames take over after.
1431
- */
1432
- private readonly hydratedQueryCache;
1433
- /**
1434
- * Coalesced read-cache writes: the latest value per key, flushed to
1435
- * the `queryCache` on a short debounce so a burst of deltas persists once.
1436
- */
1437
- private readonly pendingCacheWrites;
1438
- private cacheFlushTimer;
1439
- private readonly subscriptions;
1440
- /**
1441
- * Cross-tab coordinator; created only when `crossTabSync: true`. When the
1442
- * client is not the elected leader, all WebSocket operations are skipped.
1443
- * Not `readonly` — `close()` clears it (mirrors `outboxLeaderRelease`).
1444
- */
1445
- private tabCoordinator;
1446
- /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
1447
- private readonly connections;
1448
- /** Default `connect`-envelope context applied to a shard with no explicit override. */
1449
- private readonly defaultConnectionContext;
1450
- /**
1451
- * Per-shard `connect`-envelope context registered via `setConnectionContext`
1452
- * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
1453
- * on every socket open so it replays across reconnects, and forwarded to the
1454
- * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
1455
- * imperative (last-writer-wins) override; refcounted holders registered via
1456
- * `acquireConnectionContext` live in `connectionContextHolders` and take
1457
- * precedence — see `effectiveConnectionContext`.
1458
- */
1459
- private readonly connectionContexts;
1460
- /**
1461
- * Per-shard stack of refcounted connection-context holders (keyed by
1462
- * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
1463
- * is an opaque token carrying its `context`; the most-recently acquired
1464
- * holder wins (last-writer-wins among live holders), and the context is only
1465
- * cleared for a shard once its last holder releases — so two concurrently
1466
- * mounted presence hooks on the same shard can't stomp each other's context
1467
- * on cleanup. A holder is identified by reference identity so a release
1468
- * removes exactly the right one regardless of stack position.
1469
- */
1470
- private readonly connectionContextHolders;
1471
- private authToken;
1472
- /**
1473
- * Optional STABLE identity subject (a user id), the basis of the offline-queue
1474
- * identity stamp when supplied. Keeps a same-user token *refresh* from looking
1475
- * like an identity change (which would discard queued writes). `undefined` =
1476
- * not supplied, so identity falls back to a hash of the raw token. See
1477
- * `setAuthToken` / `identityFingerprint`.
1478
- */
1479
- private authSubject;
1480
- /**
1481
- * Identity stamp recorded against each queued offline mutation, keyed by
1482
- * the queue-assigned mutation id. Captured at enqueue from the auth token
1483
- * in effect at the time, and re-checked at flush so a queued write can
1484
- * never replay under a different identity than the one that issued it.
1485
- * See `identityFingerprint` for the fingerprint shape.
1486
- */
1487
- private readonly queuedIdentities;
1488
- private closed;
1489
- /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
1490
- private readonly authTokenListeners;
1491
- /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
1492
- private readonly statusListeners;
1493
- /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
1494
- private readonly tokenExpiredListeners;
1495
- /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
1496
- private readonly mutationSettledListeners;
1497
- /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
1498
- private readonly pendingChangeListeners;
1499
- /**
1500
- * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
1501
- * of callbacks. Membership doubles as the resubscribe set replayed on every
1502
- * (re)connect so a topic survives a socket bounce.
1503
- */
1504
- private readonly whisperHandlers;
1505
- /** Last status broadcast, so we only notify listeners on an actual change. */
1506
- private lastStatus;
1507
- private nextSubId;
1508
- private nextStreamId;
1509
- /**
1510
- * In-flight client-side stream readers, keyed by the stream id sent on the
1511
- * wire. The handle drives the underlying iterator queue and `shardKey`
1512
- * tells us which socket to push the cancel frame onto when the consumer
1513
- * calls `.cancel()` or the iterator is garbage-collected.
1514
- */
1515
- private readonly streams;
1516
- /** Live shape subscriptions (partial replication), keyed by their wire id. */
1517
- private readonly shapeSubscriptions;
1518
- /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
1519
- private readonly pokeBuffers;
1520
- private nextShapeId;
1521
- constructor(options: LunoraClientOptions);
1522
- /**
1523
- * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
1524
- * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
1525
- * sync across all mounted instances.
1526
- *
1527
- * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
1528
- * it instead of the token bytes, so a token *refresh* (same user, new JWT)
1529
- * doesn't read as an identity change and discard queued writes. The subject is
1530
- * **sticky**: a later call that omits it (or passes `undefined`) keeps the
1531
- * established subject — so `setAuthToken(refreshedToken)` after a prior
1532
- * `setAuthToken(token, user.id)` retains the identity. Pass `null` to clear it
1533
- * (an explicit sign-out). Establishing the subject for the first time on an
1534
- * UNCHANGED token (e.g. the user id resolves a tick after the token was set)
1535
- * re-stamps any in-flight queued writes rather than dropping them — same
1536
- * credential, just a more stable label. A real user switch (the token AND
1537
- * subject both change) still drops the previous user's writes.
1538
- *
1539
- * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
1540
- * time and lives in the URL. To refresh live WS auth, call
1541
- * {@link setWsToken} explicitly, which closes existing shard sockets to
1542
- * force a reconnect with the new credential.
1543
- */
1544
- setAuthToken(token: string | null, subject?: string | null): void;
1545
- getAuthToken(): string | null;
1546
- /**
1547
- * The current identity fingerprint (the same stamp queued offline writes
1548
- * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
1549
- * owns its own at-least-once replay outside the built-in `OfflineQueue` —
1550
- * can drop a persisted write whose captured `identity` no longer matches the
1551
- * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
1552
- */
1553
- currentIdentity(): string | null;
1554
- /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1555
- clientIdentifier(): string;
1556
- /**
1557
- * The highest custom-mutator watermark the server has echoed for this client
1558
- * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
1559
- * its `clientSeq` generator from this so a reload never reissues a sequence
1560
- * the server has already applied (which it would swallow as a replay, silently
1561
- * dropping the write).
1562
- */
1563
- confirmedMutationWatermark(shardKey?: string): number;
1564
- /**
1565
- * Push a custom mutator to its authoritative server impl over the watermark
1566
- * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
1567
- * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
1568
- * client's `__client_watermark`.
1569
- *
1570
- * Returns the server `result` plus `applied`: `true` when the DO ran this push
1571
- * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
1572
- * was at or below the stored watermark — e.g. a stale sequence after a reload).
1573
- * A `false` verdict tells the caller to reissue above the now-known watermark
1574
- * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
1575
- * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
1576
- *
1577
- * This is the online transport for `@lunora/db`'s client-mutator runtime; the
1578
- * optimistic overlay + durable-outbox concerns live in that runtime, not here.
1579
- */
1580
- callMutator(functionPath: string, args: Record<string, unknown>, options?: {
1581
- clientSeq?: number;
1582
- shardKey?: string;
1583
- }): Promise<{
1584
- applied: boolean;
1585
- result: unknown;
1586
- }>;
1587
- /**
1588
- * Subscribe to auth-token changes. Returns an unsubscribe function. The
1589
- * listener is NOT invoked on registration — use {@link getAuthToken} for
1590
- * the current value.
1591
- */
1592
- onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
1593
- /**
1594
- * Fetch the currently authenticated user from better-auth's `get-session`
1595
- * endpoint, returning the `user` record or `null` when signed out. Sends
1596
- * the stored bearer token (if any) and `credentials: "include"` so a
1597
- * cookie-session is also honoured. A network/parse failure or a non-OK
1598
- * response resolves to `null` rather than throwing — callers treat "couldn't
1599
- * resolve identity" as "signed out".
1600
- *
1601
- * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
1602
- * the token changes (that's what `@lunora/react`'s `useAuth` does).
1603
- */
1604
- getCurrentUser(): Promise<User | null>;
1605
- /**
1606
- * Replace the token appended to WS upgrade URLs as `?token=…` and close
1607
- * every open shard socket so the reconnect picks up the new value. Call
1608
- * this whenever the user's WS credential changes (rotating the admin token
1609
- * in the studio, switching workspaces, etc.). Accepts a static string or a
1610
- * {@link WsTokenProvider} resolved fresh at every (re)connect — the channel
1611
- * for short-lived credentials like the minted ephemeral admin sub-token.
1612
- * Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
1613
- */
1614
- setWsToken(token: string | undefined | WsTokenProvider): void;
1615
- /**
1616
- * Register (or clear, with `undefined`) the app context sent in the `connect`
1617
- * envelope for a shard's socket, overriding the client-wide
1618
- * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
1619
- * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
1620
- * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
1621
- * presence row is removed the instant the socket drops, with no TTL lag.
1622
- *
1623
- * Stored per shard and replayed on every (re)connect. When a socket for the
1624
- * shard is already open, a fresh `connect` envelope is sent immediately so the
1625
- * server sees the new context without waiting for a reconnect.
1626
- */
1627
- setConnectionContext(context: Record<string, unknown> | undefined, options?: {
1628
- shardKey?: string;
1629
- }): void;
1630
- /**
1631
- * Refcounted variant of {@link setConnectionContext}: register a connection
1632
- * `context` for a shard and get back a release function. Unlike the imperative
1633
- * setter, the context is only cleared once the *last* acquired holder releases
1634
- * it — so two components (e.g. two mounted `usePresence` hooks) on the same
1635
- * shard no longer clobber each other's context when one of them unmounts. The
1636
- * most-recently acquired live holder wins (last-writer-wins), and releasing
1637
- * the top holder falls back to the previous one rather than clearing.
1638
- *
1639
- * With a single holder the behaviour is identical to a
1640
- * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
1641
- * Releasing more than once is a no-op (the holder is matched by reference, so
1642
- * a double release can't drop a different holder).
1643
- */
1644
- acquireConnectionContext(context: Record<string, unknown>, options?: {
1645
- shardKey?: string;
1646
- }): Unsubscribe;
1647
- /**
1648
- * Join a whisper `topic` and receive every ephemeral message other members
1649
- * broadcast to it on the same shard (typing indicators, live cursors,
1650
- * presence pings). Whispers never touch the server's durable state — there's
1651
- * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
1652
- * is left on the server once its last local handler unsubscribes.
1653
- *
1654
- * `handler` receives the raw `data` and the sender's verified `from` user id
1655
- * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
1656
- * (the default shard when omitted) — use the same shard you target with the
1657
- * matching queries/mutations so members land on the same Durable Object.
1658
- *
1659
- * Security: whisper topics are NOT access-controlled beyond the shard
1660
- * boundary — any client that can open a socket to the shard can join, read,
1661
- * and inject on any topic name. `from` is server-stamped and unforgeable, but
1662
- * do not put data on a whisper topic that some shard members shouldn't see,
1663
- * and don't trust a whisper's `data` as authorization. Use a query/mutation
1664
- * (with RLS) for anything privileged; whispers are for transient awareness.
1665
- */
1666
- whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
1667
- shardKey?: string;
1668
- }): Unsubscribe;
1669
- /**
1670
- * Broadcast an ephemeral `data` payload to the other members of a whisper
1671
- * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
1672
- * dropped when the shard socket isn't open (whispers are transient, never
1673
- * queued), and the server silently drops it if the sender exceeds its
1674
- * whisper rate budget. The sender never receives its own whisper. Omitting
1675
- * `data` delivers JSON `null` to receivers (not `undefined`).
1676
- */
1677
- whisper(topic: string, data?: unknown, options?: {
1678
- shardKey?: string;
1679
- }): void;
1680
- /**
1681
- * Subscribe to token-expiry events: invoked whenever the server drops a
1682
- * shard socket because the connection's credential lapsed (close code
1683
- * `4001`). The client already reconnects automatically (re-resolving
1684
- * identity from the cookie/token in effect); use this to refresh a
1685
- * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
1686
- * with a freshly minted one. Returns an unsubscribe function.
1687
- */
1688
- onTokenExpired(listener: () => void): Unsubscribe;
1689
- /**
1690
- * Current aggregate live-socket status across all shard connections. See
1691
- * {@link ConnectionStatus}.
1692
- */
1693
- connectionStatus(): ConnectionStatus;
1694
- /**
1695
- * Subscribe to aggregate connection-status changes. Invokes `listener`
1696
- * immediately with the current status, then on every transition. Returns an
1697
- * unsubscribe function.
1698
- */
1699
- onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
1700
- /**
1701
- * Number of offline writes waiting in the built-in queue to be sent — the
1702
- * depth for a "N changes waiting to sync" indicator. Counts writes that are
1703
- * queued (offline / mid-reconnect), not ones already in flight on the wire.
1704
- * A `@lunora/db` app whose writes ride the unified outbox should read
1705
- * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
1706
- */
1707
- pendingCount(): number;
1708
- /**
1709
- * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
1710
- * with the current count, then whenever the queue depth changes (a write is
1711
- * enqueued, flushed, or discarded). Returns an unsubscribe function.
1712
- */
1713
- onPendingChange(listener: (pending: number) => void): Unsubscribe;
1714
- /**
1715
- * Subscribe to terminal verdicts for offline-queued mutations. The listener
1716
- * fires once per queued write that commits or is rejected — including a write
1717
- * restored from durable storage after a reload, whose original `mutation()`
1718
- * Promise no longer exists (`hadAwaiter: false`), and a write the queue
1719
- * evicts on overflow or discards on an identity change. This is the durable
1720
- * channel for surfacing a rolled-back optimistic write to the UI; an online
1721
- * mutation that never queued still surfaces through the Promise `mutation()`
1722
- * returns. The listener is NOT invoked on registration. Returns an
1723
- * unsubscribe function. See {@link MutationSettledEvent}.
1724
- */
1725
- onMutationSettled(listener: (event: MutationSettledEvent) => void): Unsubscribe;
1726
- /**
1727
- * The `WebSocket` implementation this client was constructed with (an
1728
- * explicit `options.WebSocket`, or the ambient global on platforms that have
1729
- * one) — `undefined` if neither is available. This is the seam a feature
1730
- * that opens its OWN socket outside the client's multiplexed connection
1731
- * (e.g. a voice-agent hook) should default to, instead of reaching for
1732
- * `globalThis.WebSocket` directly: on React Native the client wraps this
1733
- * constructor to inject the auth-headers factory's credential onto the
1734
- * upgrade request (`createLunoraClient`'s `withAuthWebSocket`), which a raw
1735
- * `new globalThis.WebSocket(url)` would silently bypass.
1736
- */
1737
- getWebSocketImpl(): typeof WebSocket | undefined;
1738
- /**
1739
- * Read the current value for a {@link ClientQueryRef}. Returns
1740
- * `ref.defaultValue` when no value has been explicitly set.
1741
- */
1742
- getClientQuery<T>(ref: ClientQueryRef<T>): T;
1743
- /**
1744
- * Set a new value for `ref` and notify every subscriber. Pass `undefined`
1745
- * to reset the slot to `ref.defaultValue`.
1746
- */
1747
- setClientQuery<T>(ref: ClientQueryRef<T>, value: T): void;
1748
- /**
1749
- * Subscribe to changes for `ref`. The callback is NOT invoked on
1750
- * registration — call {@link getClientQuery} for the current value.
1751
- * Returns an unsubscribe function.
1752
- */
1753
- subscribeClientQuery(ref: ClientQueryRef, callback: (value: unknown) => void): Unsubscribe;
1754
- /**
1755
- * Reset a {@link ClientQueryRef} to its default value, notifying every
1756
- * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
1757
- * removes the stored entry so a future {@link getClientQuery} returns
1758
- * the default rather than an explicitly-set value.
1759
- */
1760
- resetClientQuery(ref: ClientQueryRef): void;
1761
- /**
1762
- * Capture a snapshot of the current live query value at call time and
1763
- * produce a `() => boolean` precondition that compares it against the
1764
- * value at replay time (on queue drain / reconnect).
1765
- *
1766
- * When the precondition is checked it re-reads the query's current value
1767
- * via `peekActiveQueryValue`. If the value differs from what was
1768
- * captured at call time the precondition returns `false` and the offline
1769
- * mutation is dropped as stale.
1770
- *
1771
- * This is a method wrapper around `createSnapshotPrecondition` that
1772
- * binds the client instance for you — no need to pass `client` explicitly.
1773
- * @example
1774
- * ```ts
1775
- * client.mutation(api.todos.update, { id, text }, {
1776
- * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
1777
- * });
1778
- * ```
1779
- */
1780
- snapshotPrecondition(functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string): () => boolean;
1781
- /**
1782
- * Resolves once the durable read cache has been loaded into memory. When
1783
- * `hydrateOnStart` is not configured or no query cache adapter is active,
1784
- * returns an already-resolved promise so callers can always await it
1785
- * unconditionally.
1786
- *
1787
- * Framework adapters (React, Vue, etc.) use this to gate the first
1788
- * (enabled) render of a live query behind hydration, so the user sees
1789
- * cached data instead of an undefined flash before the socket round-trip.
1790
- */
1791
- whenReady(): Promise<void>;
1792
- /**
1793
- * Synchronously reports whether {@link whenReady} has already resolved (the
1794
- * durable read cache is loaded, or none is configured). Framework adapters
1795
- * read this to seed the hydration-gate state on the first render without
1796
- * awaiting, then subscribe via {@link whenReady} for the pending case.
1797
- */
1798
- get isReady(): boolean;
1799
- /**
1800
- * Synchronously peek at a value the durable read cache loaded for the given
1801
- * function path + args + shard key. Returns `undefined` when:
1802
- *
1803
- * - No query cache adapter is configured.
1804
- * - Hydration hasn't completed yet (race — await {@link whenReady} first).
1805
- * - The cached value's identity fingerprint doesn't match the current auth.
1806
- *
1807
- * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
1808
- * the cached entry stays in `hydratedQueryCache` so the subscription created
1809
- * later by {@link subscribe} consumes it normally.
1810
- */
1811
- peekHydratedQuery(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
1812
- /**
1813
- * Peek at the **current live value** of an active subscription, if one
1814
- * exists. Returns the subscription's `lastValue` (which includes any
1815
- * optimistic overlay) or `undefined` if no subscription is active for the
1816
- * given `(functionPath, args, shardKey)`.
1817
- *
1818
- * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
1819
- * and is independent of active subscriptions), this method reflects the
1820
- * current in-memory state of an already-opened subscription — useful for
1821
- * offline mutation preconditions that need to snapshot the value at call time
1822
- * and compare it at replay time.
1823
- */
1824
- peekActiveQueryValue(functionPath: string, args: Record<string, unknown>, shardKey?: string): unknown;
1825
- query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1826
- shardKey?: string;
1827
- }): Promise<ReturnOf<F>>;
1828
- /**
1829
- * Batch several independent calls into ONE round trip (plan 088). Each call is
1830
- * dispatched server-side exactly as an individual RPC — per-shard
1831
- * authorization, `(identity, mutationId)` idempotency, and custom-mutator
1832
- * watermark ordering are all preserved — and the worker splits the batch by
1833
- * shard so calls to different shards fan out to their own DOs. Results are
1834
- * demuxed back in input order; a failing call does NOT fail the batch (its
1835
- * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
1836
- * a single call). Args/results ride the value codec (bytes/bigint survive).
1837
- *
1838
- * No promise pipelining and no capability passing — a call's args cannot
1839
- * reference another call's result (see plan 088 §fence; capabilities are
1840
- * incompatible with DO hibernation).
1841
- */
1842
- batch(calls: ReadonlyArray<{
1843
- args?: Record<string, unknown>;
1844
- fn: FunctionReference;
1845
- shardKey?: string;
1846
- }>): Promise<BatchSlot[]>;
1847
- /**
1848
- * Invoke a mutation. Errors propagate as rejections.
1849
- *
1850
- * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
1851
- * only when the targeted shard's socket was open at least once already
1852
- * (`wasEverConnected`), so the registry / resubscribe handshake has run.
1853
- * Mutations issued before the very first WS connect to a shard fail fast.
1854
- * Opt into queueing-before-first-connect via
1855
- * `OfflineQueueOptions.queueBeforeFirstConnect`.
1856
- */
1857
- mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
1858
- action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1859
- shardKey?: string;
1860
- }): Promise<ReturnOf<F>>;
1861
- /**
1862
- * Read the cross-shard request distribution for a `.shardBy(...)` table —
1863
- * the feed the studio's `hot_shard` advisor lint consumes. Hits the
1864
- * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
1865
- * cheap per-shard `getMetrics` read out across every live shard and returns
1866
- * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
1867
- * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
1868
- * and `adminToken`, and this client's auth token to match; defaults any
1869
- * absent field so an older worker yields an empty-but-valid shape.
1870
- */
1871
- shardTraffic(table: string): Promise<ShardTrafficResult>;
1872
- /**
1873
- * List the functions queued via `runAfter` / `runAt`, soonest-due last
1874
- * (the worker returns them in storage order). Hits the admin-gated
1875
- * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
1876
- * `schedulerDO` namespace and `adminToken`, and this client's auth token
1877
- * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
1878
- */
1879
- listScheduledJobs(): Promise<ScheduleRecord[]>;
1880
- /**
1881
- * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
1882
- * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
1883
- * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
1884
- * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
1885
- * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
1886
- * namespace + `adminToken` on the worker and a matching auth token here).
1887
- * Defaults any absent field so an older worker still yields a valid shape.
1888
- */
1889
- schedulerStatus(): Promise<SchedulerStatus>;
1890
- /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
1891
- cancelScheduledJob(id: string): Promise<{
1892
- cancelled: boolean;
1893
- }>;
1894
- /**
1895
- * List the dead-letter jobs: schedules that exhausted their retry budget
1896
- * and were parked instead of dropped. These never appear in
1897
- * {@link listScheduledJobs} (their live header is gone), so this is the only
1898
- * way the studio surfaces a permanently-failed job. Hits the admin-gated
1899
- * `GET /_lunora/admin/scheduled/dead`; same preconditions as
1900
- * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
1901
- */
1902
- listDeadJobs(): Promise<ScheduleRecord[]>;
1903
- /**
1904
- * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
1905
- * retry budget and fires on the next drain. Returns whether a parked record
1906
- * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
1907
- */
1908
- retryDeadJob(id: string): Promise<{
1909
- retried: boolean;
1910
- }>;
1911
- /**
1912
- * Permanently drop a dead-letter job by id (the operator has decided not to
1913
- * recover it). Returns whether a parked record was removed. Hits the
1914
- * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
1915
- */
1916
- removeDeadJob(id: string): Promise<{
1917
- removed: boolean;
1918
- }>;
1919
- /**
1920
- * List a workflow's instances via the admin Workflows proxy
1921
- * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
1922
- * the `Workflow` binding can't expose. Requires the worker to be built with a
1923
- * `workflowsClient` (Cloudflare account id + API token). When one isn't
1924
- * configured this does NOT reject: the proxy returns a `200 { configured:
1925
- * false }` sentinel, so the result resolves with `configured === false` and an
1926
- * empty `instances` list — callers should branch on that flag rather than
1927
- * try/catch. (The instance-detail / status endpoints still reject with 501.)
1928
- * `name` is the deployed workflow name.
1929
- */
1930
- listWorkflowInstances(options: {
1931
- name: string;
1932
- page?: number;
1933
- perPage?: number;
1934
- status?: WorkflowInstanceStatus;
1935
- }): Promise<WorkflowInstancePage>;
1936
- /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
1937
- getWorkflowInstance(options: {
1938
- id: string;
1939
- name: string;
1940
- }): Promise<WorkflowInstanceDetail>;
1941
- /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
1942
- setWorkflowInstanceStatus(options: {
1943
- action: WorkflowInstanceAction;
1944
- id: string;
1945
- name: string;
1946
- }): Promise<{
1947
- status: WorkflowInstanceStatus;
1948
- }>;
1949
- /**
1950
- * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
1951
- * WebSocket. `onJobs` fires with the full list on connect and on every
1952
- * change (schedule / cancel / alarm-fire). Reconnects with the client's
1953
- * configured backoff. Requires `wsToken` to be set to an admin credential
1954
- * (the browser can't send an `Authorization` header on a WS) — the master
1955
- * token, or preferably a {@link WsTokenProvider} minting the ephemeral
1956
- * sub-token so the master credential stays out of the URL. Returns an
1957
- * unsubscribe function that closes the socket and stops reconnecting.
1958
- */
1959
- subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
1960
- /**
1961
- * List the registered public functions (queries / mutations / actions) with
1962
- * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1963
- * the worker must be built with a `functions` registry and `adminToken`, and
1964
- * this client's auth token must match. Powers `@lunora/studio`'s function
1965
- * runner auto-discovery.
1966
- */
1967
- listFunctions(): Promise<FunctionDescriptor[]>;
1968
- /**
1969
- * List the code-defined cron triggers (the `cronJobs()` map injected on the
1970
- * worker), each flattened to its firing `cron` expression. Hits the
1971
- * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1972
- * built with a `cronJobs` map and `adminToken`, and this client's auth token
1973
- * must match. These are static (Cloudflare exposes no runtime cron
1974
- * introspection), so the studio renders them read-only alongside the dynamic
1975
- * scheduler jobs.
1976
- */
1977
- getCronJobs(): Promise<CronJobInfo[]>;
1978
- /**
1979
- * Manually fire one code-defined cron job by name — the same dispatch the
1980
- * scheduled trigger runs (dispatch the function, or start the durable
1981
- * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1982
- * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1983
- * and this client's auth token must match. Resolves when the job has run (a
1984
- * function job's shard response is 2xx, or the workflow instance was created)
1985
- * and rejects with the dispatch error otherwise.
1986
- */
1987
- runCronJob(name: string): Promise<{
1988
- name: string;
1989
- ran: boolean;
1990
- }>;
1991
- /**
1992
- * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1993
- * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1994
- * `openApiSpec` and `adminToken`, and this client's auth token must match.
1995
- * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1996
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1997
- * document (no `paths`), so callers can render a "not configured" state.
1998
- */
1999
- fetchOpenApi(): Promise<Record<string, unknown>>;
2000
- /**
2001
- * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
2002
- * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
2003
- * `openRpcSpec` and `adminToken`, and this client's auth token must match.
2004
- * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
2005
- * `POST /_lunora/rpc` transport); it documents the RPC functions only.
2006
- * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
2007
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
2008
- * document (no `methods`), so callers can render a "not configured" state.
2009
- */
2010
- fetchOpenRpc(): Promise<Record<string, unknown>>;
2011
- /**
2012
- * List objects in the storage bucket, optionally under a `prefix` and from a
2013
- * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
2014
- * endpoint — the worker must be built with a `storageList` function and
2015
- * `adminToken`, and this client's auth token must match. Powers
2016
- * `@lunora/studio`'s file browser.
2017
- */
2018
- listStorageObjects(options?: {
2019
- bucket?: string;
2020
- cursor?: string;
2021
- limit?: number;
2022
- prefix?: string;
2023
- }): Promise<StorageListPage>;
2024
- /**
2025
- * Delete one object from the storage bucket by key. Hits the admin-gated
2026
- * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
2027
- * with a `storageDelete` function and `adminToken`. Powers the studio file
2028
- * browser's per-row delete; resolves `{ deleted, key }`.
2029
- */
2030
- deleteStorageObject(key: string, options?: {
2031
- bucket?: string;
2032
- }): Promise<{
2033
- deleted: boolean;
2034
- key: string;
2035
- }>;
2036
- /**
2037
- * List the storage bucket names the worker exposes, for the studio file
2038
- * browser's bucket picker. Hits the admin-gated
2039
- * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
2040
- * array when the worker configures no `storageBuckets`, i.e. single-bucket).
2041
- */
2042
- listStorageBuckets(): Promise<string[]>;
2043
- /**
2044
- * Upload one object to the storage bucket. Hits the admin-gated
2045
- * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
2046
- * optional `contentType` header — the worker must be built with a
2047
- * `storageUpload` function and `adminToken`. Powers the studio file
2048
- * browser's upload control; resolves `{ etag?, key }`.
2049
- */
2050
- uploadStorageObject(options: {
2051
- body: ArrayBuffer | Blob;
2052
- bucket?: string;
2053
- contentType?: string;
2054
- key: string;
2055
- }): Promise<{
2056
- etag?: string;
2057
- key: string;
2058
- }>;
2059
- /**
2060
- * Build a (signed or public) URL for one object. Hits the admin-gated
2061
- * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
2062
- * with a `storageSignedUrl` function and `adminToken`. Powers the studio
2063
- * file browser's copy-URL action; resolves the URL string.
2064
- *
2065
- * `options.expiresInSeconds` requests a share-link lifetime, which is
2066
- * validated/clamped server-side. The options object mirrors the worker's
2067
- * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
2068
- * as future fields there).
2069
- */
2070
- signedStorageUrl(key: string, options?: {
2071
- bucket?: string;
2072
- expiresInSeconds?: number;
2073
- }): Promise<string>;
2074
- /**
2075
- * List the `.global()` (D1-backed) tables with their row counts. Hits the
2076
- * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
2077
- * be built with a `globalIntrospector` and `adminToken`. Powers the data
2078
- * browser's global mode.
2079
- */
2080
- listGlobalTables(): Promise<GlobalTableInfo[]>;
2081
- /**
2082
- * Read a page of rows from one `.global()` table. `filters` AND-narrows the
2083
- * page to rows matching each `column = value` eq constraint — the drill-down a
2084
- * facet-value click applies; the array is JSON-encoded into the `filters`
2085
- * query param and the values are bound server-side.
2086
- */
2087
- readGlobalTablePage(options: {
2088
- filters?: GlobalFilterClause[];
2089
- limit?: number;
2090
- offset?: number;
2091
- table: string;
2092
- }): Promise<GlobalTablePage>;
2093
- /**
2094
- * Summarise the distinct values of one column in a `.global()` table over the
2095
- * active view (the same eq `filters` the browser is previewing) — the global
2096
- * twin of the shard browser's facet. Hits the admin-gated
2097
- * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
2098
- * server-side. Powers the global data browser's facet sidebar.
2099
- */
2100
- facetGlobalColumn(options: {
2101
- column: string;
2102
- filters?: GlobalFilterClause[];
2103
- limit?: number;
2104
- table: string;
2105
- }): Promise<GlobalFacetResult>;
2106
- /**
2107
- * List the schema's Vectorize indexes with their declared shape (table,
2108
- * field, dimensions, metric, metadata) and live stats (vector count,
2109
- * processing watermark) when the binding is reachable. Hits the admin-gated
2110
- * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
2111
- * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
2112
- * browser. Vectorize can't enumerate indexes at runtime, so this list comes
2113
- * from the generated `LUNORA_VECTOR_INDEXES` registry.
2114
- */
2115
- listVectorIndexes(): Promise<VectorIndexSummary[]>;
2116
- /**
2117
- * Run a nearest-neighbour similarity query against one vector index: the
2118
- * worker embeds `text` via the index's embedder and returns the top matches.
2119
- * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
2120
- * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
2121
- * wired (the index lists read-only).
2122
- */
2123
- queryVectorIndex(options: {
2124
- name: string;
2125
- text: string;
2126
- topK?: number;
2127
- }): Promise<VectorQueryMatch[]>;
2128
- /**
2129
- * List the worker's registered Workers KV namespaces (binding names). Hits
2130
- * the admin-gated `GET /_lunora/admin/kv/namespaces` endpoint — the worker
2131
- * must be built with a `kvIntrospector` and `adminToken`. Powers the
2132
- * studio's KV browser.
2133
- */
2134
- listKvNamespaces(): Promise<KvNamespaceSummary[]>;
2135
- /**
2136
- * List keys in a KV namespace, optionally filtered by `prefix` and
2137
- * paginated via `cursor`. Hits the admin-gated
2138
- * `GET /_lunora/admin/kv/keys` endpoint.
2139
- */
2140
- listKvKeys(options: {
2141
- cursor?: string;
2142
- limit?: number;
2143
- namespace: string;
2144
- prefix?: string;
2145
- }): Promise<KvKeyListResult>;
2146
- /**
2147
- * Read a KV value (as text) and its metadata. Hits the admin-gated
2148
- * `GET /_lunora/admin/kv/value` endpoint. Returns `{ value: null, metadata: null }`
2149
- * when the key is absent.
2150
- */
2151
- getKvValue(options: {
2152
- key: string;
2153
- namespace: string;
2154
- }): Promise<KvValueResult>;
2155
- /**
2156
- * Write a string value to a KV namespace. Accepts an absolute `expiration`
2157
- * (Unix seconds) or a relative `expirationTtl`, plus optional `metadata` —
2158
- * re-send the loaded values on edit so a save preserves rather than clears
2159
- * them. Hits the admin-gated `PUT /_lunora/admin/kv/value` endpoint.
2160
- */
2161
- putKvValue(options: {
2162
- expiration?: number;
2163
- expirationTtl?: number;
2164
- key: string;
2165
- metadata?: unknown;
2166
- namespace: string;
2167
- value: string;
2168
- }): Promise<void>;
2169
- /**
2170
- * Delete a key from a KV namespace. No-op when the key is absent. Hits the
2171
- * admin-gated `DELETE /_lunora/admin/kv/value` endpoint.
2172
- */
2173
- deleteKvKey(options: {
2174
- key: string;
2175
- namespace: string;
2176
- }): Promise<void>;
2177
- /**
2178
- * List authenticated users, paged and optionally searched / filtered / sorted.
2179
- * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
2180
- * must be built with an `authAdmin` and `adminToken`. Powers the studio's
2181
- * users dashboard.
2182
- */
2183
- listAuthUsers(options?: {
2184
- filterField?: string;
2185
- filterValue?: string;
2186
- limit?: number;
2187
- offset?: number;
2188
- search?: string;
2189
- searchField?: string;
2190
- sortBy?: string;
2191
- sortDirection?: "asc" | "desc";
2192
- }): Promise<AuthPage<AuthUser>>;
2193
- /**
2194
- * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
2195
- * endpoint (requires the worker's `authAdmin` to implement `createUser`).
2196
- * `data` carries any app-defined `user.additionalFields`.
2197
- */
2198
- createAuthUser(input: {
2199
- data?: Record<string, unknown>;
2200
- email: string;
2201
- name: string;
2202
- password?: string;
2203
- role?: string | string[];
2204
- }): Promise<AuthUser>;
2205
- /** Set a user's role (string, or array joined comma-wise server-side). */
2206
- setAuthUserRole(input: {
2207
- role: string | string[];
2208
- userId: string;
2209
- }): Promise<AuthUser>;
2210
- /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
2211
- banAuthUser(input: {
2212
- expiresInSeconds?: number;
2213
- reason?: string;
2214
- userId: string;
2215
- }): Promise<AuthUser>;
2216
- /** Lift a user's ban. */
2217
- unbanAuthUser(input: {
2218
- userId: string;
2219
- }): Promise<AuthUser>;
2220
- /** Set a user's password (admin override — no current-password challenge). */
2221
- setAuthUserPassword(input: {
2222
- newPassword: string;
2223
- userId: string;
2224
- }): Promise<void>;
2225
- /** Permanently delete a user and revoke their sessions. */
2226
- removeAuthUser(input: {
2227
- userId: string;
2228
- }): Promise<void>;
2229
- /**
2230
- * Mint an impersonation session for a user, returning its bearer `token`.
2231
- * The caller is responsible for using the token (e.g. setting the session
2232
- * cookie); the server performs no cookie round-trip.
2233
- */
2234
- impersonateAuthUser(input: {
2235
- userId: string;
2236
- }): Promise<AuthImpersonation>;
2237
- /** Revoke a single session by its id (force sign-out of one device). */
2238
- revokeAuthSession(input: {
2239
- sessionId: string;
2240
- }): Promise<void>;
2241
- /** Revoke every session for a user (force sign-out everywhere). */
2242
- revokeAuthUserSessions(input: {
2243
- userId: string;
2244
- }): Promise<void>;
2245
- /**
2246
- * Report which auth dashboard surfaces are available — derived server-side
2247
- * from the enabled better-auth plugins. The studio renders only the panels
2248
- * whose capability is `true`.
2249
- */
2250
- getAuthCapabilities(): Promise<AuthCapabilities>;
2251
- /** Update a user's fields (name/email/app-defined `additionalFields`). */
2252
- updateAuthUser(input: {
2253
- data: Record<string, unknown>;
2254
- userId: string;
2255
- }): Promise<AuthUser>;
2256
- /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
2257
- listAuthAccounts(input: {
2258
- userId: string;
2259
- }): Promise<Record<string, unknown>[]>;
2260
- /** Unlink a linked account from a user. */
2261
- unlinkAuthAccount(input: {
2262
- accountId: string;
2263
- userId: string;
2264
- }): Promise<void>;
2265
- /** List a user's registered passkeys (requires the passkey plugin). */
2266
- listAuthPasskeys(input: {
2267
- userId: string;
2268
- }): Promise<Record<string, unknown>[]>;
2269
- /** Delete a passkey by id (requires the passkey plugin). */
2270
- deleteAuthPasskey(input: {
2271
- passkeyId: string;
2272
- }): Promise<void>;
2273
- /** Disable two-factor auth for a user (requires the two-factor plugin). */
2274
- disableAuthTwoFactor(input: {
2275
- userId: string;
2276
- }): Promise<void>;
2277
- /** List organizations, paged (requires the organization plugin). */
2278
- listAuthOrganizations(options?: {
2279
- limit?: number;
2280
- offset?: number;
2281
- }): Promise<AuthPage<Record<string, unknown>>>;
2282
- /** List the members of an organization (requires the organization plugin). */
2283
- listAuthOrgMembers(input: {
2284
- limit?: number;
2285
- offset?: number;
2286
- organizationId: string;
2287
- }): Promise<AuthPage<Record<string, unknown>>>;
2288
- /** List an organization's pending invitations (requires the organization plugin). */
2289
- listAuthOrgInvitations(input: {
2290
- limit?: number;
2291
- offset?: number;
2292
- organizationId: string;
2293
- }): Promise<AuthPage<Record<string, unknown>>>;
2294
- /** Remove a member from an organization. */
2295
- removeAuthOrgMember(input: {
2296
- memberId: string;
2297
- }): Promise<void>;
2298
- /** Cancel a pending organization invitation. */
2299
- cancelAuthOrgInvitation(input: {
2300
- invitationId: string;
2301
- }): Promise<void>;
2302
- /**
2303
- * Report the deployment's auth configuration — enabled plugins, sign-in
2304
- * methods, user-settable create-user fields, organization sub-features
2305
- * (teams / roles), and session / rate-limit policy. Drives the config panel
2306
- * and the dynamic create-user form. Never carries a secret.
2307
- */
2308
- getAuthConfig(): Promise<AuthConfigInfo>;
2309
- /** Create an organization; optionally seed an `owner` member for `ownerId`. */
2310
- createAuthOrganization(input: {
2311
- logo?: string;
2312
- metadata?: Record<string, unknown>;
2313
- name: string;
2314
- ownerId?: string;
2315
- slug?: string;
2316
- }): Promise<Record<string, unknown>>;
2317
- /** Update an organization's name/slug/logo/metadata. */
2318
- updateAuthOrganization(input: {
2319
- logo?: string;
2320
- metadata?: Record<string, unknown>;
2321
- name?: string;
2322
- organizationId: string;
2323
- slug?: string;
2324
- }): Promise<Record<string, unknown>>;
2325
- /** Delete an organization and cascade its members, invitations, teams, and custom roles. */
2326
- deleteAuthOrganization(input: {
2327
- organizationId: string;
2328
- }): Promise<void>;
2329
- /** Directly add an existing user to an organization (no invitation/acceptance). */
2330
- addAuthOrgMember(input: {
2331
- organizationId: string;
2332
- role?: string;
2333
- userId: string;
2334
- }): Promise<Record<string, unknown>>;
2335
- /** Create a pending email invitation to an organization. */
2336
- inviteAuthOrgMember(input: {
2337
- email: string;
2338
- inviterId?: string;
2339
- organizationId: string;
2340
- role?: string;
2341
- }): Promise<Record<string, unknown>>;
2342
- /** Change a member's role. */
2343
- setAuthOrgMemberRole(input: {
2344
- memberId: string;
2345
- role: string | string[];
2346
- }): Promise<Record<string, unknown>>;
2347
- /** List an organization's teams (requires the organization plugin with teams enabled). */
2348
- listAuthOrgTeams(input: {
2349
- limit?: number;
2350
- offset?: number;
2351
- organizationId: string;
2352
- }): Promise<AuthPage<Record<string, unknown>>>;
2353
- /** Create a team under an organization. */
2354
- createAuthOrgTeam(input: {
2355
- name: string;
2356
- organizationId: string;
2357
- }): Promise<Record<string, unknown>>;
2358
- /** Rename a team. */
2359
- updateAuthOrgTeam(input: {
2360
- name: string;
2361
- teamId: string;
2362
- }): Promise<Record<string, unknown>>;
2363
- /** Delete a team and its memberships. */
2364
- removeAuthOrgTeam(input: {
2365
- teamId: string;
2366
- }): Promise<void>;
2367
- /** List a team's members. */
2368
- listAuthOrgTeamMembers(input: {
2369
- limit?: number;
2370
- offset?: number;
2371
- teamId: string;
2372
- }): Promise<AuthPage<Record<string, unknown>>>;
2373
- /** Add a user to a team. */
2374
- addAuthOrgTeamMember(input: {
2375
- teamId: string;
2376
- userId: string;
2377
- }): Promise<Record<string, unknown>>;
2378
- /** Remove a member from a team. */
2379
- removeAuthOrgTeamMember(input: {
2380
- teamMemberId: string;
2381
- }): Promise<void>;
2382
- /** List an organization's custom roles (requires the organization plugin with dynamic access control). */
2383
- listAuthOrgRoles(input: {
2384
- limit?: number;
2385
- offset?: number;
2386
- organizationId: string;
2387
- }): Promise<AuthPage<Record<string, unknown>>>;
2388
- /** Create a custom org role with a permission grant (a `resource -> actions[]` map). */
2389
- createAuthOrgRole(input: {
2390
- organizationId: string;
2391
- permission: Record<string, string[]>;
2392
- role: string;
2393
- }): Promise<Record<string, unknown>>;
2394
- /** Replace a custom org role's permission grant. */
2395
- updateAuthOrgRole(input: {
2396
- permission: Record<string, string[]>;
2397
- roleId: string;
2398
- }): Promise<Record<string, unknown>>;
2399
- /** Delete a custom org role. */
2400
- deleteAuthOrgRole(input: {
2401
- roleId: string;
2402
- }): Promise<void>;
2403
- /** List auth sessions, paged and optionally filtered to one user. */
2404
- listAuthSessions(options?: {
2405
- limit?: number;
2406
- offset?: number;
2407
- userId?: string;
2408
- }): Promise<AuthPage<AuthSession>>;
2409
- subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
2410
- onCheckpoint?: (watermark: SyncWatermark) => void;
2411
- onError?: SubscriptionErrorCallback;
2412
- shardKey?: string;
2413
- }): Unsubscribe;
2414
- /**
2415
- * Subscribe to a declarative **shape** — server-side partial replication
2416
- * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
2417
- * {@link subscribe} for the poke protocol: the client sends the shape *name* +
2418
- * validated `args` (never a `where` the client could forge), the server seeds
2419
- * the current membership as an insert-poke and streams live membership diffs.
2420
- * Each applied poke materializes the shape's rowset and invokes `callback`.
2421
- *
2422
- * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
2423
- * (name, args): the server resolves them under the socket's verified identity,
2424
- * so every call gets its own id + view. The returned function unsubscribes.
2425
- */
2426
- subscribeShape(shape: {
2427
- args?: Record<string, unknown>;
2428
- name: string;
2429
- }, callback: ShapeCallback, options?: {
2430
- onCheckpoint?: (watermark: SyncWatermark) => void;
2431
- onError?: SubscriptionErrorCallback;
2432
- shardKey?: string;
2433
- }): Unsubscribe;
2434
- /**
2435
- * Open a streaming query. The function reference must be a
2436
- * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
2437
- * the type constraint catches accidental use of a query/mutation/action
2438
- * reference at compile time. The returned iterable yields one element per
2439
- * chunk frame the server pushes, terminating when the server sends
2440
- * `complete` or the consumer calls `.cancel()`. Errors arrive as a
2441
- * rejection on the next `next()`.
2442
- *
2443
- * Streams ride the same WS as subscriptions and share the unsubscribe
2444
- * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
2445
- * which the DO recognises as an abort signal for the in-flight iterator.
2446
- *
2447
- * Stream-start frames buffered while the socket is (re)connecting are
2448
- * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
2449
- * cap drops the oldest queued frame (and fails its consumer) so a stuck
2450
- * reconnect can't OOM the page.
2451
- */
2452
- stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
2453
- maxBuffer?: number;
2454
- shardKey?: string;
2455
- }): StreamIterable<ReturnOf<F>>;
2456
- /**
2457
- * Open a typed **HTTP-SSE route stream** (`httpRoute.&lt;verb>(path).stream()`).
2458
- * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
2459
- * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
2460
- * and parses the Server-Sent Events framing the route pump writes (`data:`
2461
- * chunks, a final `event: complete`, an `event: error` on throw).
2462
- *
2463
- * The reference comes from the generated `httpStreams.*` registry, so the
2464
- * yielded chunk type is the route handler's yielded type. Cancelling the
2465
- * returned iterable (or aborting `options.signal`) aborts the fetch, which
2466
- * the server handler observes via its `signal`. The client's bearer token
2467
- * (when set) rides as an `authorization` header.
2468
- * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
2469
- */
2470
- httpStream<Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: {
2471
- headers?: Record<string, string>;
2472
- maxBuffer?: number;
2473
- signal?: AbortSignal;
2474
- }): StreamIterable<HttpStreamChunkOf<Ref>>;
2475
- close(): void;
2476
- /**
2477
- * Persist a mutation that can't go out on the wire right now (offline, or
2478
- * mid-reconnect after a prior connect). The optimistic update has already
2479
- * been applied by `mutation`; this only chooses the durable write path and
2480
- * rolls the optimistic write back if persistence is rejected.
2481
- *
2482
- * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
2483
- * owns persistence + at-least-once replay, so we delegate and return
2484
- * optimistically (confirmation rides the synced view). Otherwise the
2485
- * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
2486
- */
2487
- private enqueueOfflineMutation;
2488
- /**
2489
- * Restore offline mutations persisted in a prior session and open a socket
2490
- * for each shard they target so they flush once the WS reconnects. Failures
2491
- * are swallowed — a broken durable store must not stop the client booting.
2492
- */
2493
- private hydratePersistedQueue;
2494
- /**
2495
- * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
2496
- * persisted queue is shared across a profile's tabs; without coordination
2497
- * every tab would re-queue and replay the same writes (correct only because
2498
- * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
2499
- * exactly one tab hydrate; it holds the lock for its lifetime, so when it
2500
- * closes another tab acquires the lock and takes over. Falls back to
2501
- * unconditional hydration where Web Locks are unavailable (React Native, older
2502
- * browsers, SSR) — single-context there, so no coordination is needed.
2503
- */
2504
- private hydrateAsOutboxLeader;
2505
- /**
2506
- * Load every cached query into {@link hydratedQueryCache} so the next
2507
- * `subscribe()` for each key seeds its initial value off disk. A
2508
- * subscription created before this resolves simply misses the cache (it
2509
- * gets a live snapshot as before); the gate at seed time also drops any
2510
- * entry whose stamped identity no longer matches the current one.
2511
- */
2512
- private hydrateQueryCache;
2513
- /**
2514
- * Consume the hydrated read-cache entry for a key (if any), gated on
2515
- * identity. The entry is removed whether or not it matches — the cache only
2516
- * ever seeds a subscription's first value. A mismatch (the cache was written
2517
- * under a different identity) yields `undefined` so a signed-out cache never
2518
- * leaks into a new session.
2519
- */
2520
- private takeHydratedCache;
2521
- /**
2522
- * Queue a coalesced read-cache write for a subscription's current value.
2523
- * Latest-wins per key; flushed on a short debounce so a delta burst writes
2524
- * once. No-op when the read cache is disabled or the value is undefined
2525
- * (nothing to render offline).
2526
- */
2527
- private persistQueryValue;
2528
- /** Drain {@link pendingCacheWrites} to the durable store. */
2529
- private flushQueryCacheWrites;
2530
- /** Derive the aggregate status from the per-shard socket states. */
2531
- private computeStatus;
2532
- /** Recompute the aggregate status and notify listeners if it changed. */
2533
- private emitConnectionStatus;
2534
- /**
2535
- * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
2536
- * {@link onMutationSettled} channel. `item.id` is always assigned by the time
2537
- * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
2538
- * is unreachable — present only to satisfy the optional queue-id type.
2539
- */
2540
- private emitItemSettled;
2541
- /**
2542
- * Apply an optimistic update to the subscription that matches the mutation's
2543
- * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
2544
- * invoke if the mutation later fails.
2545
- *
2546
- * The registry is already indexed by exactly this triple via
2547
- * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
2548
- * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
2549
- *
2550
- * `shardKey` normalization: both `undefined` and `""` map to the empty string
2551
- * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
2552
- * a shardKey correctly matches a subscription registered without one regardless
2553
- * of whether the caller passed `undefined` or omitted the field.
2554
- */
2555
- private applyOptimisticUpdates;
2556
- /**
2557
- * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
2558
- * to the live subscription registry. Each `setQuery` registers a constant
2559
- * optimistic LAYER on its target subscription (via the same engine the
2560
- * per-call `optimistic` path uses), so the multi-query patch rebases onto
2561
- * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
2562
- * `rollback` closures are appended to the mutation's settle lists. A throwing
2563
- * callback unwinds its own partial writes — LIFO over just the rollbacks it
2564
- * produced — and is swallowed, so a buggy optimistic update can never fail the
2565
- * mutation or leave a partial patch live.
2566
- */
2567
- private applyOptimisticUpdate;
2568
- private getConnection;
2569
- private getOrCreateConnection;
2570
- private wsUrlFor;
2571
- /**
2572
- * Build the outbound RPC headers: JSON content type, optional bearer auth,
2573
- * the optional mutation-replay idempotency key, and the D1 read-your-writes
2574
- * bookmark when the caller opted into `attachBookmark`. The mutation id
2575
- * rides both the direct send and any offline-queue replay of the same write,
2576
- * so a mutation the server already committed returns its cached result
2577
- * instead of running twice.
2578
- */
2579
- private rpcRequestHeaders;
2580
- private rpc;
2581
- /**
2582
- * Authenticated request to a non-RPC admin endpoint (the scheduler list /
2583
- * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
2584
- * worker's `{ error: { code, message } }` envelope as a coded `Error` —
2585
- * mirroring {@link rpc} so callers see the same failure shape.
2586
- */
2587
- private adminFetch;
2588
- /**
2589
- * Resolve the effective connection context for a shard: the most-recently
2590
- * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
2591
- * back to the imperative {@link setConnectionContext} override, then the
2592
- * client-wide default. Returns `undefined` when none apply.
2593
- */
2594
- private effectiveConnectionContext;
2595
- /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
2596
- private refreshConnectionContext;
2597
- /**
2598
- * Send the one-shot `connect` envelope on an open shard socket. Always sent
2599
- * once per socket open, so the server's `onConnect` hooks fire symmetrically
2600
- * with `onDisconnect` (which the DO dispatches unconditionally at close for
2601
- * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
2602
- * hooks are registered, so the single frame costs nothing in the common case.
2603
- *
2604
- * The shard's registered context (or the client-wide default) rides along
2605
- * when one is set — the DO records it on the attachment for replay to
2606
- * `onDisconnect`. A socket with no registered context still announces itself;
2607
- * the envelope simply omits `context`, which is optional on the wire.
2608
- * Register a context — e.g. `setConnectionContext({})` — to attach app state
2609
- * to the lifecycle dispatch.
2610
- */
2611
- private sendConnectEnvelope;
2612
- /**
2613
- * Re-send every shape subscription bound to `shardKey` over its (now open)
2614
- * socket. Each frame carries the shape's last applied checkpoint, so the
2615
- * server resumes from it — or re-seeds when the cursor fell below CDC
2616
- * retention or the epoch forked.
2617
- */
2618
- private resendShapeSubscriptions;
2619
- private ensureSocket;
2620
- /**
2621
- * Resolve the {@link WsTokenProvider} and open the shard socket with the
2622
- * minted token. The connection is already in the `connecting` state, so the
2623
- * async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
2624
- * competing connect that landed first all abandon this attempt. A provider
2625
- * failure fails the attempt through {@link handleDisconnect}, which arms the
2626
- * normal reconnect backoff — a broken mint endpoint degrades to retries, not
2627
- * a silent tokenless socket the admin gate would reject.
2628
- */
2629
- private openSocketWithProvidedToken;
2630
- /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
2631
- private openSocket;
2632
- private handleDisconnect;
2633
- /**
2634
- * Begin the keepalive heartbeat on an open connection. Each tick sends a
2635
- * {@link WS_KEEPALIVE_PING} text frame the server answers from its
2636
- * hibernation auto-response without waking the DO. A no-op when the
2637
- * heartbeat is disabled (an interval of zero or less); idempotent — any
2638
- * existing timer is cleared first so a reconnect can't leak intervals.
2639
- */
2640
- private startHeartbeat;
2641
- /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
2642
- private stopHeartbeat;
2643
- /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
2644
- private markShardPendingAck;
2645
- private sendSubscribeIfOpen;
2646
- private sendShapeSubscribeIfOpen;
2647
- private handleServerMessage;
2648
- private handleErrorMessage;
2649
- private handlePokeStart;
2650
- private handlePokePart;
2651
- private handlePokeEnd;
2652
- /** Materialize a shape's keyed view to an array and invoke its callbacks. */
2653
- private emitShapeRows;
2654
- private handleDataMessage;
2655
- /**
2656
- * Handle a `resume` frame (Pillar 1b): the server proved nothing the
2657
- * subscription reads changed since our `sinceSeq`, so the cached value is
2658
- * still current. We keep `lastValue` as-is, mark the sub acked, and advance
2659
- * the cursor (re-persisting so the next reconnect resumes from the newer
2660
- * watermark). No callback fires — the value didn't change, and `subscribe()`
2661
- * already replayed the cached value to every consumer synchronously.
2662
- */
2663
- private handleResumeMessage;
2664
- /**
2665
- * Handle a `settled` frame: a write touched one of this subscription's read
2666
- * tables but produced a byte-identical result, so the server suppressed the
2667
- * data frame. Like {@link handleResumeMessage} the value didn't change — we
2668
- * advance the resume position and re-persist — but we ALSO surface the echoed
2669
- * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
2670
- * collection drops the optimistic overlay for the confirmed write (otherwise
2671
- * its checkpoint gate, fed only by data frames, would hang forever). Sent
2672
- * only to custom-mutator clients; plain `useQuery` subscribers leave
2673
- * `onCheckpoint` unset and this is a near no-op.
2674
- */
2675
- private handleSettledMessage;
2676
- /**
2677
- * Mark `state` acked and, when the frame carries a newer cursor/epoch than
2678
- * the cached position, advance the resume watermark and re-persist. Shared by
2679
- * the `resume` and `settled` frame handlers — both acknowledge "nothing the
2680
- * client must re-render changed, but the resume position may have moved".
2681
- */
2682
- private ackAndAdvanceCursor;
2683
- /**
2684
- * Resolve the value to publish for a `data`/`delta` frame.
2685
- *
2686
- * A `data` frame is an authoritative snapshot (the server re-execution path)
2687
- * and always replaces the cached value wholesale. A `delta` frame carrying a
2688
- * structured `MutationDelta` (the `broadcastDelta` row-change path) is
2689
- * merged incrementally into the cached list — preserving order, no dup/loss —
2690
- * so each subscription (including every paginated page) updates by delta
2691
- * rather than a full re-send. We fall back to full replacement when the
2692
- * delta isn't a recognisable row change, when there's no cached value yet,
2693
- * or when it can't be applied cleanly against the current cached shape.
2694
- */
2695
- private resolveDataPayload;
2696
- /** Route an inbound whisper to the topic's handlers on the originating shard. */
2697
- private dispatchWhisper;
2698
- /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
2699
- private notifyTokenExpired;
2700
- private handleCompleteMessage;
2701
- private unpersist;
2702
- /**
2703
- * Stable, non-reversible fingerprint of the current auth identity used to
2704
- * stamp queued offline writes. `null` (signed out) is its own identity and
2705
- * never matches a bearer-token fingerprint. The raw token is never stored;
2706
- * a length-prefixed FNV-1a hash is enough to detect an identity *change*
2707
- * without keeping the credential around in the queue map.
2708
- */
2709
- private identityFingerprint;
2710
- /**
2711
- * Stable token-hash fingerprint of a bearer token (the `&lt;len>:&lt;fnv>:&lt;djb2>`
2712
- * format a token-stamped queued write carries). Extracted so the replay gate
2713
- * can recompute the hash of the current credential and recognise a write
2714
- * stamped under it — even after the fingerprint was relabelled to a subject.
2715
- *
2716
- * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
2717
- * two distinct equal-length tokens are astronomically unlikely to share a
2718
- * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
2719
- * pair — enough that, on a shared device, user B could hydrate A's cached
2720
- * reads. Different algorithms (not the same FNV with a different seed, which
2721
- * would be affine-related) keep the two passes genuinely independent.
2722
- * Still synchronous (no crypto) and stable across surrogate pairs.
2723
- */
2724
- private hashToken;
2725
- /**
2726
- * True when `stamped` is a token-hash of the SAME credential still held now,
2727
- * even though the live identity has since been relabelled to a subject. Covers
2728
- * `setAuthToken(token, userId)` where the subject resolved a tick after the
2729
- * token was set: a write persisted (or requeued) under the token hash must
2730
- * still replay — the credential never changed, only its label — instead of
2731
- * being dropped as an identity mismatch. This is the durable counterpart to
2732
- * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
2733
- * (consumed on the first flush) and never touches `item.identity` or the
2734
- * persisted record, so a reload or a transient-failure requeue would otherwise
2735
- * fall back to the stale token-hash and wrongly reject the same user's write.
2736
- */
2737
- private isSameCredentialUnderTokenHash;
2738
- /**
2739
- * Drain every in-memory offline write and reject it because the auth
2740
- * identity changed. Durable entries are also dropped from persistence so a
2741
- * later `hydrate` can't resurrect another user's writes. Stamps are cleared
2742
- * alongside. Persisted entries restored without a live awaiter still get
2743
- * unpersisted here.
2744
- */
2745
- private rejectQueuedForIdentityChange;
2746
- /**
2747
- * Migrate every live identity stamp from `from` to `to` — used when the auth
2748
- * identity label changes but the underlying credential (token) does NOT, e.g.
2749
- * the user id resolves a tick after the token was set. The in-memory
2750
- * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
2751
- * keeps the in-flight writes replayable under the new (more stable) identity
2752
- * instead of the flush guard discarding them as a mismatch.
2753
- */
2754
- private restampQueuedIdentity;
2755
- /**
2756
- * Drop the durable read cache on an identity change so a cached value stamped
2757
- * under the previous identity can never hydrate into a new session. Clears
2758
- * the in-flight write batch and the not-yet-consumed hydrated entries too;
2759
- * the durable `clear()` is best-effort.
2760
- */
2761
- private clearQueryCacheForIdentityChange;
2762
- private flushOfflineQueue;
2763
- /**
2764
- * Partition already-gated writes into the encodable ones (returned) and reject
2765
- * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
2766
- * or class instance in a `v.any()` field) can NEVER replay — the codec failure
2767
- * is deterministic, not transient. Rejecting here is essential: otherwise
2768
- * `encodeWire` throws mid-flush, is classified as transient (a codec error has
2769
- * no `.code`), and re-queues forever — a silent hang where the caller's Promise
2770
- * never settles and the optimistic write never rolls back. Encoding is cheap;
2771
- * the flush is the slow reconnect path.
2772
- */
2773
- private encodableOrSettleTerminal;
2774
- /**
2775
- * Identity guard for one queued write about to replay: a write stamped under
2776
- * one identity must never replay under another. The live `queuedIdentities`
2777
- * map is the source of truth for the current session; a hydrated write whose
2778
- * id isn't in the map falls back to the stamp persisted with the record
2779
- * (`item.identity`), so a reload can't replay another user's queued writes.
2780
- * Only legacy records (persisted before stamps were durable —
2781
- * `item.identity === undefined`) replay under whatever identity is current.
2782
- *
2783
- * `Map.get` returns `undefined` for unstamped/hydrated ids and `item.identity`
2784
- * is `undefined` for legacy records; a persisted `null` (queued while signed
2785
- * out) is a real value that must not collapse into `undefined` — hence the
2786
- * explicit `=== undefined` check rather than `??`. Returns `true` when the
2787
- * write may replay; otherwise settles it `OFFLINE_IDENTITY_CHANGED` and returns
2788
- * `false`. Either way the live stamp is consumed.
2789
- */
2790
- private passesReplayIdentityGate;
2791
- /** 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. */
2792
- private settleReplaySuccess;
2793
- /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
2794
- private settleReplayTerminal;
2795
- /**
2796
- * Replay already-identity-gated writes one at a time on the single-call `/rpc`
2797
- * path, preserving FIFO order (parallel `.then()` chains would race the
2798
- * ordering callers depend on). Each replays under its stable `mutationId` so
2799
- * the server dedups a write it already committed (exactly-once). A coded error
2800
- * is a server verdict (drop it); a codeless (transport/transient) failure stops
2801
- * the flush and re-queues this write and every unreplayed one for the next
2802
- * reconnect — their callers stay pending, and the identity guard re-applies on
2803
- * retry via each record's persisted stamp.
2804
- */
2805
- private replaySequential;
2806
- /**
2807
- * Coalesce already-identity-gated writes for a single shard into ONE
2808
- * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
2809
- * them to the shard DO, which replays each through its single-call dispatch, so
2810
- * per-entry `mutationId` idempotency and in-order application are inherited from
2811
- * the proven path. Per-slot demux mirrors {@link replaySequential}'s
2812
- * classification: success confirms the optimistic layer against the echoed
2813
- * `commitCursor`; a coded application verdict is terminal; a transient shard
2814
- * failure (`SHARD_UNAVAILABLE`/`SHARD_ERROR`), a missing slot, or a whole-batch
2815
- * transport failure re-queues for the next reconnect (never dropping a durable
2816
- * write). A whole-batch coded rejection (bad request / authorization denial the
2817
- * server reached a verdict on) is terminal for every entry.
2818
- *
2819
- * Returns the writes that must be re-queued and `stop` — `true` when the whole
2820
- * chunk failed at the transport level, so the caller leaves later chunks queued
2821
- * rather than sending on. The caller re-queues once, in order, so requeuing is
2822
- * NOT done here.
2823
- */
2824
- private replayBatched;
2825
- /**
2826
- * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
2827
- * in input order. Each slot's envelope classifies its write the same way
2828
- * {@link replaySequential} does: a success confirms the optimistic layer
2829
- * against the echoed `commitCursor`; a coded application verdict is terminal;
2830
- * a transient shard failure ({@link TRANSIENT_BATCH_ERROR_CODES}) or a slot the
2831
- * server never returned is returned for the caller to re-queue.
2832
- * @returns the writes that must be re-queued (transient slots), in input order
2833
- */
2834
- private settleReplayBatchSlots;
2835
- }
2836
- export { ServerPokePartMessage as $, ArgsOf as A, BookmarkStorage as B, CONFLICT_ERROR_CODE as C, DEFAULT_MAX_BUFFER as D, OptimisticUpdate as E, FunctionReference as F, GlobalFacetResult as G, HttpStreamRef as H, OutboxMutation as I, OutboxSink as J, PersistedMutation as K, LunoraClient as L, MutationCallOptions as M, RowOp as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, SubscriptionError as S, RpcEnvelope as T, User as U, RpcResponseBody as V, ScheduleRecord as W, SchedulerPoolStatus as X, SchedulerStatus as Y, ServerMessage as Z, ServerPokeEndMessage as _, Unsubscribe as a, ServerPokeStartMessage as a0, ShardTrafficEntry as a1, ShardTrafficResult as a2, StorageListPage as a3, StorageObject as a4, StreamHandle as a5, SubscriptionCallback as a6, SubscriptionRegistry as a7, SubscriptionState as a8, SyncWatermark as a9, WorkflowInstanceAction as aa, WorkflowInstanceDetail as ab, WorkflowInstancePage as ac, WorkflowInstanceStatus as ad, WorkflowInstanceSummary as ae, WorkflowStepDetail as af, WsTokenProvider as ag, createClientQuery as ah, createLocalStore as ai, createStream as aj, getErrorCode as ak, getRetryAfterMs as al, isConflictError as am, isForbiddenError as an, isRateLimitedError as ao, isUnauthorizedError as ap, SubscriptionErrorCallback as b, PersistenceAdapter as c, HttpStreamArgsOf as d, HttpStreamChunkOf as e, StreamIterable as f, ReconnectOptions as g, BatchSlot as h, CachedQuery as i, ClientMessage as j, ClientQueryRef as k, ClientShapeSubscribeMessage as l, ClientShapeUnsubscribeMessage as m, ConnectionStatus as n, FunctionArgumentDescriptor as o, FunctionDescriptor as p, GlobalFacetValue as q, GlobalFilterClause as r, GlobalTableInfo as s, GlobalTablePage as t, HttpStreamCallArgs as u, LunoraClientError as v, LunoraClientOptions as w, LunoraErrorCode as x, MutationSettledEvent as y, OptimisticLocalStore as z };