@lunora/client 1.0.0-alpha.22 → 1.0.0-alpha.221

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