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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/auth/index.d.mts +12 -10
  3. package/dist/auth/index.d.ts +12 -10
  4. package/dist/auth/index.mjs +1 -60
  5. package/dist/index.d.mts +878 -230
  6. package/dist/index.d.ts +878 -230
  7. package/dist/index.mjs +1 -15
  8. package/dist/packem_shared/CONFLICT_ERROR_CODE-CDDneB-G.mjs +1 -0
  9. package/dist/packem_shared/ClientServiceWorker-DXnBXeWK.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  11. package/dist/packem_shared/LunoraClient-B9UMg5lY.mjs +1 -0
  12. package/dist/packem_shared/OfflineQueue-B6IWyX5W.mjs +1 -0
  13. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  14. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  15. package/dist/packem_shared/SubscriptionRegistry-BQPU90ST.mjs +1 -0
  16. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  17. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  18. package/dist/packem_shared/applyDelta-BiegnbZR.mjs +1 -0
  19. package/dist/packem_shared/createAsyncStoragePersistence-CNdM5o1u.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStorageQueryCache-MoM77Nwg.mjs +1 -0
  21. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  22. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryPersistence-C0qm7c47.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  26. package/dist/packem_shared/createLocalStore-v6oiATqG.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  29. package/dist/packem_shared/createReply-CwFABEJs.mjs +1 -0
  30. package/dist/packem_shared/createServerClient-BevCicNQ.mjs +1 -0
  31. package/dist/packem_shared/createSnapshotPrecondition-C4bSgHkg.mjs +1 -0
  32. package/dist/packem_shared/delta-merge-BPM4sFID.mjs +1 -0
  33. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  34. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  35. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  36. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  37. package/dist/packem_shared/httpStream-x6q-x4yK.mjs +11 -0
  38. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  39. package/dist/packem_shared/local-store-CNgeGW02.mjs +1 -0
  40. package/dist/packem_shared/lunora-client.d-BSNUC85h.d.mts +3491 -0
  41. package/dist/packem_shared/lunora-client.d-BkDgDzTg.d.ts +3491 -0
  42. package/dist/packem_shared/offline-queue-8mpNPwG8.mjs +1 -0
  43. package/dist/packem_shared/preload.d-Do17SOqk.d.ts +21 -0
  44. package/dist/packem_shared/preload.d-XsWPDlX6.d.mts +21 -0
  45. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  46. package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
  47. package/dist/packem_shared/wire-codec-BfIZrTJe.mjs +1 -0
  48. package/dist/packem_shared/wire-key-C9UKT-C3.mjs +1 -0
  49. package/dist/pagination/index.d.mts +42 -42
  50. package/dist/pagination/index.d.ts +42 -42
  51. package/dist/pagination/index.mjs +1 -61
  52. package/dist/query/index.d.mts +111 -43
  53. package/dist/query/index.d.ts +111 -43
  54. package/dist/query/index.mjs +1 -1
  55. package/dist/service.d.mts +49 -0
  56. package/dist/service.d.ts +49 -0
  57. package/dist/service.mjs +1 -0
  58. package/dist/ssr/index.d.mts +100 -79
  59. package/dist/ssr/index.d.ts +100 -79
  60. package/dist/ssr/index.mjs +1 -4
  61. package/dist/upload.d.mts +35 -0
  62. package/dist/upload.d.ts +35 -0
  63. package/dist/upload.mjs +1 -0
  64. package/package.json +16 -1
  65. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  66. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  67. package/dist/packem_shared/LunoraClient-Bsv8immC.mjs +0 -2546
  68. package/dist/packem_shared/OfflineQueue-D-ASeqL7.mjs +0 -131
  69. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  70. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  71. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  72. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  73. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  74. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  75. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  76. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  77. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  78. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  79. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  80. package/dist/packem_shared/createServerClient-DucOyOz3.mjs +0 -11
  81. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  82. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  83. package/dist/packem_shared/lunora-client.d-DLbxPGH9.d.mts +0 -2006
  84. package/dist/packem_shared/lunora-client.d-DLbxPGH9.d.ts +0 -2006
  85. package/dist/packem_shared/preload.d-BAT6GeSD.d.mts +0 -20
  86. package/dist/packem_shared/preload.d-CSkjbfEq.d.ts +0 -20
  87. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  88. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
@@ -1,2006 +0,0 @@
1
- import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthSession } from '@lunora/runtime';
2
- /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
3
- type FunctionKind = "action" | "mutation" | "query" | "stream";
4
- /**
5
- * Opaque reference to a registered function emitted by `@lunora/codegen`.
6
- *
7
- * At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
8
- * Generated declarations decorate this with phantom type parameters so the
9
- * client can infer args / return values per call site.
10
- */
11
- interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
12
- /**
13
- * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
14
- * inference. Never present at runtime; declared as a covariant (output)
15
- * position so a concrete reference stays assignable to a widened one.
16
- */
17
- readonly __lunoraPhantom?: {
18
- args: Args;
19
- kind: Kind;
20
- returns: Return;
21
- };
22
- readonly __lunoraRef: string;
23
- }
24
- /** Extract the args type from a {@link FunctionReference}. */
25
- type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
26
- /** Extract the return type from a {@link FunctionReference}. */
27
- type ReturnOf<F> = F extends FunctionReference<infer _K, infer _A, infer R> ? R : never;
28
- type Unsubscribe = () => void;
29
- /**
30
- * Serializable result of `preloadQuery`. Produced on the server during SSR,
31
- * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
32
- * client so the first render shows the server value with no loading flash
33
- * before a live subscription attaches. Every field survives `JSON.stringify`.
34
- */
35
- interface Preloaded<T = unknown> {
36
- readonly __lunoraPreloaded: true;
37
- readonly args: Record<string, unknown>;
38
- readonly functionPath: string;
39
- readonly shardKey?: string;
40
- readonly value: T;
41
- }
42
- /**
43
- * Pluggable storage for the `x-d1-bookmark` value used to provide
44
- * read-your-writes between a mutation and subsequent queries.
45
- */
46
- interface BookmarkStorage {
47
- get: () => string | null;
48
- set: (value: string | null) => void;
49
- }
50
- interface ReconnectOptions {
51
- initialDelayMs?: number;
52
- jitter?: boolean;
53
- maxDelayMs?: number;
54
- }
55
- /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
56
- type PersistenceOperation = "append" | "clear" | "load" | "remove";
57
- /** Context handed to a persistence-error handler. */
58
- interface PersistenceErrorContext {
59
- readonly error: unknown;
60
- /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
61
- readonly mutationId?: string;
62
- readonly operation: PersistenceOperation;
63
- }
64
- interface OfflineQueueOptions {
65
- maxItems?: number;
66
- /**
67
- * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
68
- * exceeded). Without a handler, failures are logged via `console.warn` so they
69
- * are never fully silent. Note: a failed `append` means the write is queued in
70
- * memory but NOT durable — it will not survive a reload.
71
- */
72
- onPersistenceError?: (context: PersistenceErrorContext) => void;
73
- /**
74
- * Queue mutations issued before a shard's first successful WebSocket
75
- * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
76
- * `mutation()`) queues only when the targeted shard has been connected at
77
- * least once (`wasEverConnected`), so the registry / resubscribe handshake
78
- * has run. Set this to `true` for offline-first apps that want to enqueue
79
- * writes on the very first session before the WS is up.
80
- */
81
- queueBeforeFirstConnect?: boolean;
82
- }
83
- /**
84
- * Serializable shape of an offline mutation, durably stored by a
85
- * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
86
- * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
87
- * persisted — a restored mutation is replayed with no original awaiter.
88
- */
89
- interface PersistedMutation {
90
- args: Record<string, unknown>;
91
- functionPath: string;
92
- id: string;
93
- /**
94
- * Issuing identity fingerprint, persisted so a hydrated write replays only
95
- * under the identity that queued it (`null` = queued while signed out).
96
- * Absent on records written by older client versions, which replay under
97
- * the ambient identity for back-compat.
98
- */
99
- identity?: string | null;
100
- shardKey?: string;
101
- }
102
- /**
103
- * Durable store for the offline mutation queue. The default client keeps the
104
- * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
105
- * makes queued writes survive a page reload. Implementations must preserve FIFO
106
- * (enqueue) order in `PersistenceAdapter.load`.
107
- *
108
- * Replay semantics are at-least-once: a mutation is removed only after the
109
- * server confirms (or rejects) it, so a crash between commit and `remove` can
110
- * replay it again on the next load.
111
- */
112
- interface PersistenceAdapter {
113
- /** Append a mutation to durable storage (called on enqueue). */
114
- append: (mutation: PersistedMutation) => Promise<void>;
115
- /** Drop every persisted mutation (e.g. on logout). */
116
- clear: () => Promise<void>;
117
- /** Load all persisted mutations in FIFO order — called once at startup. */
118
- load: () => Promise<PersistedMutation[]>;
119
- /** Remove a mutation by id once it has been replayed (resolved or rejected). */
120
- remove: (id: string) => Promise<void>;
121
- }
122
- /**
123
- * One write handed to an {@link OutboxSink}. Mirrors {@link PersistedMutation}
124
- * plus the custom-mutator identity (`clientId`/`mutationId`/`idempotencyKey`)
125
- * the durable outbox needs to dedupe and watermark replays.
126
- */
127
- interface OutboxMutation {
128
- args: Record<string, unknown>;
129
- /** Stable per-client id; pairs with {@link OutboxMutation.mutationId} as `idempotencyKey`. */
130
- clientId: string;
131
- functionPath: string;
132
- /** `${clientId}:${mutationId}` — sent as `x-lunora-mutation-id` so a replay is server-idempotent. */
133
- idempotencyKey: string;
134
- /** Issuing identity fingerprint (`null` = signed out); drives the sink's identity guard. */
135
- identity: string | null;
136
- /** Monotonic per-client mutation id, backing the server `__client_watermark`. */
137
- mutationId: number;
138
- shardKey?: string;
139
- }
140
- /**
141
- * Pluggable durable outbox seam. When set on {@link LunoraClientOptions.outbox},
142
- * the client delegates offline write durability + at-least-once replay to this
143
- * sink instead of its built-in {@link PersistenceAdapter}-backed `OfflineQueue`.
144
- * `@lunora/db` supplies the blessed implementation (`createExecutorOutboxSink`,
145
- * backed by the TanStack `OfflineExecutor`); the interface itself is
146
- * dependency-free so `@lunora/client` stays TanStack-free.
147
- */
148
- interface OutboxSink {
149
- /**
150
- * Persist and schedule a write for replay. Rejects with an
151
- * `OFFLINE_QUEUE_OVERFLOW`-coded error when the sink's cap is exceeded, so
152
- * the caller can surface back-pressure to the issuing mutation.
153
- */
154
- enqueue: (mutation: OutboxMutation) => Promise<void>;
155
- }
156
- /**
157
- * One persisted query result in the durable read cache (Pillar 2). Keyed in the
158
- * store by `shardKey + functionPath + argsKey`; the record carries everything
159
- * needed to render offline on reload and to resume the live subscription.
160
- */
161
- interface CachedQuery {
162
- /**
163
- * Issuing identity fingerprint (same shape the offline queue stamps). A
164
- * cached value only hydrates when it matches the current identity, so a
165
- * signed-out cache never leaks into a new session. `null` = cached while
166
- * signed out.
167
- */
168
- identity: string | null;
169
- /**
170
- * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
171
- * on reconnect so the server can resume instead of re-snapshotting. Absent
172
- * when the value predates CDC / no cursor was advertised.
173
- */
174
- serverCursor?: number;
175
- /**
176
- * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
177
- * on reconnect so the server only resumes when the client is still on the
178
- * same changelog timeline. Absent when no epoch was advertised.
179
- */
180
- serverEpoch?: string;
181
- /** Wall-clock millis the value was written — drives LRU eviction. */
182
- ts: number;
183
- /** The full query result last seen from the server. */
184
- value: unknown;
185
- }
186
- /**
187
- * Durable store for the client read cache (Pillar 2): query results survive a
188
- * reload so reads hydrate from disk and render immediately while the socket
189
- * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
190
- * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
191
- * shape over the same IndexedDB plumbing.
192
- */
193
- interface QueryCacheAdapter {
194
- /** Drop every cached query (e.g. on logout / identity change). */
195
- clear: () => Promise<void>;
196
- /** Load every cached query — called once at startup to hydrate reads. */
197
- load: () => Promise<(CachedQuery & {
198
- key: string;
199
- })[]>;
200
- /** Upsert one cached query by key (called when a subscription value advances). */
201
- put: (key: string, entry: CachedQuery) => Promise<void>;
202
- /** Remove one cached query by key. */
203
- remove: (key: string) => Promise<void>;
204
- }
205
- interface LunoraClientOptions {
206
- /**
207
- * Base path the worker mounts better-auth at, used by the client's
208
- * `getCurrentUser()` to reach the `get-session` route. Defaults to
209
- * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
210
- */
211
- authBasePath?: string;
212
- bookmarkStorage?: BookmarkStorage;
213
- /**
214
- * Stable per-client id backing the custom-mutator watermark. Sent on the
215
- * `connect` envelope (so the server can scope this client's
216
- * `__client_watermark`) and stamped onto every {@link OutboxMutation} the
217
- * {@link LunoraClientOptions.outbox} sink persists, where it pairs with the
218
- * monotonic mutation id to form the idempotency key. The `@lunora/db` path
219
- * persists a stable id alongside the outbox and passes it here; omit for the
220
- * standalone client, which generates an ephemeral per-session id.
221
- */
222
- clientId?: string;
223
- /**
224
- * Default app context sent in the `connect` envelope right after each socket
225
- * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
226
- * as `event.context`. A per-shard context registered via
227
- * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
228
- * hook needs connection context.
229
- */
230
- connectionContext?: Record<string, unknown>;
231
- /**
232
- * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
233
- * handshake doesn't complete within this window — a hung dev proxy or a cold
234
- * worker that never upgrades — the client force-closes the socket and routes
235
- * through its normal reconnect/backoff (surfacing `offline` status) instead
236
- * of leaving the live channel silently stuck on the browser's much longer
237
- * default. Does not affect HTTP queries/mutations (those never ride the WS).
238
- * Defaults to 10000 (10s); set to `0` (or negative) to disable.
239
- */
240
- connectTimeoutMs?: number;
241
- fetch?: typeof fetch;
242
- /**
243
- * Interval (ms) between keepalive pings sent on each open subscription
244
- * socket. The server answers them via the Durable Object's hibernation
245
- * auto-response WITHOUT waking the DO, so an idle socket stays alive across
246
- * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
247
- * `0` (or a negative value) to disable the heartbeat entirely.
248
- */
249
- heartbeatIntervalMs?: number;
250
- offlineQueue?: OfflineQueueOptions;
251
- /**
252
- * Durable outbox seam for offline writes. When supplied (the `@lunora/db`
253
- * path wires `createExecutorOutboxSink`), offline mutations are delegated to
254
- * the sink and the built-in {@link PersistenceAdapter}-backed `OfflineQueue`
255
- * is bypassed, so a db app has exactly one durable write path. Omit for the
256
- * standalone client, which keeps using {@link LunoraClientOptions.persistence}.
257
- */
258
- outbox?: OutboxSink;
259
- /** Durable store for the offline mutation queue; omit to keep it in memory. */
260
- persistence?: PersistenceAdapter;
261
- /**
262
- * Durable store for the read cache (Pillar 2). When supplied, query results
263
- * are persisted as their subscriptions advance and hydrated on construction
264
- * so a reload renders cached data before the socket reconnects, then resumes
265
- * the live subscription from the persisted cursor. Omit (or pass `false`) to
266
- * keep reads in memory only — the default, unchanged behaviour.
267
- */
268
- queryCache?: QueryCacheAdapter | false;
269
- reconnect?: ReconnectOptions;
270
- url: string;
271
- WebSocket?: typeof WebSocket;
272
- /**
273
- * Token appended to the WebSocket URL as `?token=…`. The server matches it
274
- * against `LUNORA_WS_BEARER` (to clear the upgrade gate) and/or
275
- * `LUNORA_ADMIN_TOKEN` (to authorize `__lunora_admin__:*` subscriptions —
276
- * what the studio sets it to). Browsers can't set headers on the
277
- * `WebSocket` constructor, so the query parameter is the only channel; it
278
- * ends up in server logs and history, so prefer a short-lived rotating
279
- * token in production.
280
- */
281
- wsToken?: string;
282
- wsUrl?: string;
283
- }
284
- /** Wire envelope sent on `POST /_lunora/rpc`. */
285
- interface RpcEnvelope {
286
- args?: Record<string, unknown>;
287
- /**
288
- * Stable per-client identifier (custom-mutator push path). Pairs with
289
- * {@link RpcEnvelope.mutationId} to form `idempotencyKey` and scope the
290
- * server `__client_watermark`. Absent on plain `client.mutation` calls.
291
- */
292
- clientId?: string;
293
- functionPath: string;
294
- /**
295
- * Idempotency key (`${clientId}:${mutationId}`) for the custom-mutator push
296
- * path, mirrored into the `x-lunora-mutation-id` header. Absent on plain
297
- * `client.mutation` calls.
298
- */
299
- idempotencyKey?: string;
300
- /**
301
- * Monotonic per-client mutation id (custom-mutator push path), backing the
302
- * server-side per-client watermark: `id &lt;= watermark` is a replay (skipped),
303
- * `id == watermark + 1` runs authoritatively, `id > watermark + 1` halts the
304
- * batch so the client resends from `watermark + 1`. Absent on plain
305
- * `client.mutation` calls.
306
- */
307
- mutationId?: number;
308
- shardKey?: string;
309
- }
310
- /**
311
- * Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). A
312
- * watermarked custom-mutator push additionally carries `lastMutationId` — the
313
- * highest per-client sequence the DO has applied — which the client uses to keep
314
- * its `clientSeq` generator monotonic across reloads (see `LunoraClient.callMutator`).
315
- */
316
- type RpcResponseBody = {
317
- error: {
318
- code: string;
319
- message: string;
320
- };
321
- } | {
322
- lastMutationId?: number;
323
- result: unknown;
324
- };
325
- /** Subscription protocol — client → server. */
326
- interface ClientSubscribeMessage {
327
- id: string;
328
- /**
329
- * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
330
- * for this shard (Pillar 1b resume). Present only when a durable
331
- * {@link QueryCacheAdapter} restored a cached value with a cursor; the
332
- * server replies with a lightweight `resume` frame instead of a full
333
- * snapshot when nothing the query reads changed since it. Absent on a
334
- * first-time subscribe.
335
- */
336
- query: {
337
- args?: Record<string, unknown>;
338
- functionPath?: string;
339
- sinceEpoch?: string;
340
- sinceSeq?: number;
341
- table?: string;
342
- };
343
- type: "subscribe";
344
- }
345
- interface ClientUnsubscribeMessage {
346
- id: string;
347
- type: "unsubscribe";
348
- }
349
- /**
350
- * One-shot control frame sent right after the socket opens. Registers the
351
- * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
352
- * fires the `onConnect` lifecycle hooks; the same context is replayed to
353
- * `onDisconnect` when the socket drops.
354
- */
355
- interface ClientConnectMessage {
356
- /**
357
- * Stable per-client id (persisted alongside the outbox). Lets the server
358
- * scope this connection's `__client_watermark` so custom-mutator pokes can
359
- * echo the right per-client `lastMutationId`. Omitted by clients that don't
360
- * use custom mutators.
361
- */
362
- clientId?: string;
363
- context?: Record<string, unknown>;
364
- id: string;
365
- type: "connect";
366
- }
367
- /**
368
- * Subscribe to a declarative **shape** — server-side partial replication scoped
369
- * by `shardBy` + the shape's predicate + RLS. The client sends the shape *name*
370
- * + validated `args`; the server resolves the trusted `where` (identity/RLS
371
- * `baseWhere` the client can't forge) and streams the matching rowset, then live
372
- * {@link ServerPokePartMessage} diffs. `id` namespaces the subscription and is
373
- * echoed as `shapeId` on every poke part.
374
- */
375
- interface ClientShapeSubscribeMessage {
376
- id: string;
377
- shape: {
378
- args?: Record<string, unknown>;
379
- name: string;
380
- };
381
- /**
382
- * Resume from this checkpoint (the `__cdc_log` cursor the client last
383
- * applied for this shape). When absent or below the server's retained floor
384
- * (`minCdcSeq`), the server re-seeds with a full insert-poke instead of a
385
- * delta.
386
- */
387
- sinceCheckpoint?: number;
388
- /**
389
- * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
390
- * to. A mismatch (forked changelog timeline) forces a full re-seed even when
391
- * the cursor is numerically in range.
392
- */
393
- sinceEpoch?: string;
394
- type: "shape_subscribe";
395
- }
396
- /** Cancel a shape subscription started with the same `id`. */
397
- interface ClientShapeUnsubscribeMessage {
398
- id: string;
399
- type: "shape_unsubscribe";
400
- }
401
- interface ClientAckMessage {
402
- id: string;
403
- type: "ack";
404
- }
405
- /**
406
- * Start a streaming query. The id namespaces a fresh stream and is echoed on
407
- * every {@link ServerChunkMessage} the server pushes back. Cancel a running
408
- * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
409
- * subscription and stream id-spaces share the cancel channel; the prefix
410
- * (`sub_*` vs `stream_*`) keeps the local registries searchable.
411
- */
412
- interface ClientStreamMessage {
413
- id: string;
414
- query: {
415
- args?: Record<string, unknown>;
416
- functionPath: string;
417
- shardKey?: string;
418
- };
419
- type: "stream";
420
- }
421
- /**
422
- * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
423
- * shard. While joined, the client receives every {@link ServerWhisperMessage}
424
- * other members broadcast to the topic.
425
- */
426
- interface ClientWhisperSubscribeMessage {
427
- topic: string;
428
- type: "whisper_subscribe" | "whisper_unsubscribe";
429
- }
430
- /**
431
- * Broadcast ephemeral `data` to the topic's other members on the shard. The
432
- * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
433
- * write) — for typing indicators, live cursors, presence pings. The sender does
434
- * not receive its own whisper.
435
- */
436
- interface ClientWhisperMessage {
437
- data?: unknown;
438
- topic: string;
439
- type: "whisper";
440
- }
441
- type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientShapeSubscribeMessage | ClientShapeUnsubscribeMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
442
- /** Subscription protocol — server → client. */
443
- interface ServerDataMessage {
444
- /**
445
- * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
446
- * client persists it as the query's `serverCursor` and replays it as
447
- * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
448
- */
449
- cursor?: number;
450
- data?: unknown;
451
- delta?: unknown;
452
- /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
453
- epoch?: string;
454
- id: string;
455
- type: "data" | "delta";
456
- }
457
- /**
458
- * Lightweight resume acknowledgement (Pillar 1b): the server determined that
459
- * nothing the subscription reads changed since the client's `sinceSeq`, so it
460
- * skips re-sending the snapshot. The client keeps its cached value and only
461
- * advances `serverCursor` to `cursor`.
462
- */
463
- interface ServerResumeMessage {
464
- cursor?: number;
465
- /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
466
- epoch?: string;
467
- id: string;
468
- type: "resume";
469
- }
470
- /**
471
- * Settled acknowledgement for a **list** subscription: a write touched one of
472
- * the subscription's read tables but produced a byte-identical result, so the
473
- * server suppressed the data frame. Sent ONLY to a `@lunora/db` custom-mutator
474
- * client (one that announced a `clientId`, hence has a server-side
475
- * `__client_watermark`) so its optimistic list overlay drops even when no data
476
- * frame arrives. Plain `useQuery` subscribers never receive it, and an older
477
- * client safely ignores the unknown frame.
478
- */
479
- interface ServerSettledMessage {
480
- cursor?: number;
481
- /** The CDC epoch this settled frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
482
- epoch?: string;
483
- id: string;
484
- /**
485
- * The highest custom-mutator `mutationId` from this client the server has
486
- * now applied (the per-client `__client_watermark`). Forwarded to a
487
- * collection's `onCheckpoint` so it can drop the overlay for the confirmed
488
- * write whose result didn't change this list.
489
- */
490
- lastMutationId?: number;
491
- type: "settled";
492
- }
493
- interface ServerErrorMessage {
494
- error?: unknown;
495
- id?: string;
496
- message?: string;
497
- type: "error";
498
- }
499
- interface ServerAckMessage {
500
- id: string;
501
- type: "ack";
502
- }
503
- interface ServerCompleteMessage {
504
- id: string;
505
- type: "complete";
506
- }
507
- /** One frame of a streaming query — `data` carries the user-yielded chunk. */
508
- interface ServerChunkMessage {
509
- data: unknown;
510
- id: string;
511
- type: "chunk";
512
- }
513
- /**
514
- * An ephemeral whisper relayed from another member of `topic` on the same shard
515
- * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
516
- * is the sender's verified user id when known (absent for an anonymous sender).
517
- * Never persisted server-side.
518
- */
519
- interface ServerWhisperMessage {
520
- data: unknown;
521
- from?: string;
522
- topic: string;
523
- type: "whisper";
524
- }
525
- /**
526
- * One row-level change in a shape's replication stream — the wire form of the
527
- * DO's `__cdc_log` `CdcChange`. `insert`/`update` carry the post-image in
528
- * `value` (projected to the shape's `columns`); `delete` omits it, identifying
529
- * the removed row by `key` alone. The client applies these to its local
530
- * collection; an unknown `key` on a `delete` is a safe no-op (a row the client
531
- * never had in this shape).
532
- */
533
- interface RowOp {
534
- /** Row primary key (`_id`). */
535
- key: string;
536
- op: "delete" | "insert" | "update";
537
- /** Logical table the row belongs to. */
538
- table: string;
539
- /** Post-image document for insert/update; absent on delete. */
540
- value?: Record<string, unknown>;
541
- }
542
- /**
543
- * Opens a **poke** — an atomically-applied batch of shape diffs (Zero's poke
544
- * protocol). A `pokeStart` is followed by zero or more {@link ServerPokePartMessage}
545
- * frames and closed by exactly one {@link ServerPokeEndMessage}; the client
546
- * buffers every part and applies them in a single transaction at `pokeEnd`, so a
547
- * socket that drops mid-poke simply re-seeds on reconnect (no torn view).
548
- */
549
- interface ServerPokeStartMessage {
550
- /** The checkpoint the client's view is expected to be at before this poke applies (for ordering/gap detection). */
551
- baseCheckpoint?: number;
552
- /** CDC epoch this poke belongs to; a mismatch forces the client to re-seed rather than apply. */
553
- epoch?: string;
554
- /** Correlates this poke's `pokeStart`/`pokePart`/`pokeEnd` frames. */
555
- pokeId: string;
556
- type: "pokeStart";
557
- }
558
- /** One shape's slice of an in-flight poke: the row-ops to apply for `shapeId`. */
559
- interface ServerPokePartMessage {
560
- /** Per-client custom-mutator watermark carried with this slice (see {@link ServerSettledMessage.lastMutationId}). */
561
- lastMutationId?: number;
562
- pokeId: string;
563
- /** Ordered row-level changes for this shape, applied in sequence at `pokeEnd`. */
564
- rowsPatch: RowOp[];
565
- /** The {@link ClientShapeSubscribeMessage.id} these row-ops belong to. */
566
- shapeId: string;
567
- type: "pokePart";
568
- }
569
- /**
570
- * Closes a poke: the client commits the buffered parts atomically and advances
571
- * its checkpoint to {@link ServerPokeEndMessage.checkpoint} (the `__cdc_log`
572
- * cursor high-watermark the view now reflects), replayed as `sinceCheckpoint` on
573
- * the next reconnect.
574
- */
575
- interface ServerPokeEndMessage {
576
- /** The `__cdc_log` cursor the view is at after applying this poke. */
577
- checkpoint?: number;
578
- /** CDC epoch the {@link ServerPokeEndMessage.checkpoint} belongs to. */
579
- epoch?: string;
580
- pokeId: string;
581
- type: "pokeEnd";
582
- }
583
- type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
584
- /**
585
- * The authenticated user as exposed client-side, mirroring better-auth's
586
- * `user` row (the `user` field of the `get-session` response). Kept minimal
587
- * and structural — only `id` is guaranteed; the rest are the common better-auth
588
- * fields, and the index signature carries any plugin-contributed extras.
589
- */
590
- interface User {
591
- readonly createdAt?: NullableTimestamp;
592
- readonly email?: null | string;
593
- readonly emailVerified?: boolean | null;
594
- readonly id: string;
595
- readonly image?: null | string;
596
- readonly name?: null | string;
597
- readonly [key: string]: unknown;
598
- readonly updatedAt?: NullableTimestamp;
599
- }
600
- /**
601
- * One pending scheduled function, as returned by the worker's
602
- * `GET /_lunora/admin/scheduled` endpoint. Mirrors `@lunora/scheduler`'s
603
- * `ScheduleRecord` structurally so the client carries no dependency on it.
604
- */
605
- interface ScheduleRecord {
606
- args: Record<string, unknown>;
607
- /**
608
- * Dispatch attempts already made. Absent (treated as 0) until the first
609
- * failure; on a dead-letter record it is the exhausted count (> the retry
610
- * budget). Surfaced so the studio can show how hard a job tried before it
611
- * was parked.
612
- */
613
- attempts?: number;
614
- enqueuedAt: number;
615
- functionPath: string;
616
- id: string;
617
- /** Logical workpool the job is routed to (concurrency-gated), when any. */
618
- pool?: string;
619
- scheduledFor: number;
620
- shardKey?: string;
621
- }
622
- /**
623
- * One workpool's live backlog, as returned by the worker's
624
- * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
625
- * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
626
- */
627
- interface SchedulerPoolStatus {
628
- /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
629
- inFlight: number;
630
- /** The pool's concurrency cap. */
631
- maxConcurrency: number;
632
- /** The logical workpool name. */
633
- name: string;
634
- /** Pending jobs routed to this pool but not yet dispatched. */
635
- queued: number;
636
- }
637
- /**
638
- * The app-level scheduler backlog, as returned by the worker's
639
- * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
640
- * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
641
- * `inFlight` across every pool — the headline numbers for the studio SLO
642
- * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
643
- */
644
- interface SchedulerStatus {
645
- /** Sum of every pool's `queued` count — the total pending backlog. */
646
- backlog: number;
647
- /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
648
- inFlight: number;
649
- /** Per-pool backlog breakdown. */
650
- pools: SchedulerPoolStatus[];
651
- }
652
- /**
653
- * One shard's request volume, as returned by the worker's
654
- * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
655
- * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
656
- * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
657
- */
658
- interface ShardTrafficEntry {
659
- requests: number;
660
- shardKey: string;
661
- }
662
- /**
663
- * The whole-shard-set traffic distribution returned by the worker's
664
- * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
665
- * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
666
- * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
667
- * lint after the studio tags each entry with its sharded function `group`.
668
- */
669
- interface ShardTrafficResult {
670
- failed: number;
671
- ok: number;
672
- shards: ShardTrafficEntry[];
673
- }
674
- /**
675
- * One object in the storage bucket, as returned by the worker's
676
- * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
677
- * `R2ObjectLike` structurally.
678
- */
679
- interface StorageObject {
680
- customMetadata?: Record<string, string>;
681
- etag: string;
682
- httpMetadata?: {
683
- contentType?: string;
684
- };
685
- key: string;
686
- size: number;
687
- /**
688
- * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
689
- * ISO string over the wire; a mock may supply epoch ms — so consumers should
690
- * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
691
- */
692
- uploaded?: number | string;
693
- }
694
- /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
695
- interface StorageListPage {
696
- cursor?: string;
697
- objects: StorageObject[];
698
- }
699
- /**
700
- * One argument of a registered function, derived from its `v.*` validator by the
701
- * worker. A compact signature shape — enough to render a function's API without
702
- * the build-time codegen types.
703
- */
704
- interface FunctionArgumentDescriptor {
705
- /** Element validator kind for an `array` arg (one level), e.g. `string`. */
706
- element?: string;
707
- /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
708
- kind: string;
709
- /** The argument name. */
710
- name: string;
711
- /** True when the arg is wrapped in `v.optional(...)`. */
712
- optional: boolean;
713
- /** Target table for an `id` arg (`v.id("table")`). */
714
- table?: string;
715
- }
716
- /**
717
- * One registered function, as returned by the worker's
718
- * `GET /_lunora/admin/functions` endpoint: its `&lt;file>:&lt;function>` path, which
719
- * client method (`query` / `mutation` / `action`) invokes it, and its argument
720
- * signature. `args` is absent on responses from an older worker.
721
- */
722
- interface FunctionDescriptor {
723
- args?: FunctionArgumentDescriptor[];
724
- kind: "action" | "mutation" | "query";
725
- path: string;
726
- }
727
- /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
728
- interface GlobalTableInfo {
729
- name: string;
730
- rowCount: number;
731
- }
732
- /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
733
- interface GlobalTablePage {
734
- columns: string[];
735
- /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
736
- refs?: Record<string, string>;
737
- rows: Record<string, unknown>[];
738
- total: number;
739
- }
740
- /**
741
- * One equality constraint a facet-value click adds to the global browser's view
742
- * (`column = value`). `value` is the raw stored scalar the facet returned, sent
743
- * as-is and bound server-side, so it never injects SQL.
744
- */
745
- interface GlobalFilterClause {
746
- column: string;
747
- value: unknown;
748
- }
749
- /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
750
- interface GlobalFacetValue {
751
- count: number;
752
- value: unknown;
753
- }
754
- /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
755
- interface GlobalFacetResult {
756
- truncated: boolean;
757
- values: GlobalFacetValue[];
758
- }
759
- /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
760
- type NullableTimestamp = null | number | string;
761
- /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
762
- type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
763
- /** The lifecycle mutations the status endpoint accepts. */
764
- type WorkflowInstanceAction = "pause" | "resume" | "terminate";
765
- /** One row of the workflow-instances list. */
766
- interface WorkflowInstanceSummary {
767
- createdOn?: string;
768
- endedOn?: string;
769
- id: string;
770
- startedOn?: string;
771
- status: WorkflowInstanceStatus;
772
- }
773
- /** One durable step of an instance's execution timeline. */
774
- interface WorkflowStepDetail {
775
- /** 1-based attempt count (`> 1` means the step retried). */
776
- attempts?: number;
777
- end?: string;
778
- error?: unknown;
779
- name: string;
780
- output?: unknown;
781
- start?: string;
782
- success?: boolean;
783
- /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
784
- type?: string;
785
- }
786
- /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
787
- interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
788
- error?: unknown;
789
- output?: unknown;
790
- params?: unknown;
791
- steps: WorkflowStepDetail[];
792
- }
793
- /** A page of workflow instances. */
794
- interface WorkflowInstancePage {
795
- /**
796
- * Whether workflow inspection is configured on the worker (a Cloudflare
797
- * account id + API token). `false` when the admin proxy reports it can't
798
- * inspect instances; omitted (treated as configured) otherwise. Lets a
799
- * caller render a "set credentials" state without a failed request.
800
- */
801
- configured?: boolean;
802
- instances: WorkflowInstanceSummary[];
803
- page: number;
804
- perPage: number;
805
- totalCount?: number;
806
- }
807
- type SubscriptionCallback = (data: unknown) => void;
808
- /** A subscription-scoped error the server pushed for this subscription id. */
809
- interface SubscriptionError {
810
- code?: string;
811
- message: string;
812
- }
813
- type SubscriptionErrorCallback = (error: SubscriptionError) => void;
814
- interface SubscriptionState {
815
- /** True once the server has acked the subscription on the current socket. */
816
- acked: boolean;
817
- readonly args: Record<string, unknown>;
818
- /**
819
- * Stable-stringified `args`, computed once at subscribe time. Cached so the
820
- * optimistic-update fan-out can compare against a mutation's args key without
821
- * re-serializing every subscription's args on every mutation.
822
- */
823
- readonly argsKey: string;
824
- readonly callbacks: Set<SubscriptionCallback>;
825
- /**
826
- * Notified when a `settled` frame advances this subscription's watermark — a
827
- * write touched the subscription's tables but the result was byte-identical,
828
- * so the server suppressed the data frame. A `@lunora/db` list collection
829
- * uses this to drop the optimistic overlay for the confirmed write.
830
- *
831
- * A SET (not a single slot) because `SubscriptionState` is SHARED across
832
- * every subscriber to the same `(fn, args, shardKey)`: a `@lunora/db`
833
- * collection may subscribe to a query a plain `useQuery` already opened, so
834
- * each subscriber registers its own callback (mirroring `callbacks` /
835
- * `errorCallbacks`) and a `settled` frame fans out to all of them. Plain
836
- * `useQuery` consumers register nothing, leaving the set empty.
837
- */
838
- readonly checkpointCallbacks: Set<(watermark: {
839
- checkpoint?: number;
840
- mutationId?: number;
841
- }) => void>;
842
- /** Notified when the server rejects this subscription (e.g. admin auth). */
843
- readonly errorCallbacks: Set<SubscriptionErrorCallback>;
844
- readonly fn: FunctionReference;
845
- readonly id: string;
846
- /**
847
- * The highest custom-mutator `mutationId` from this client the server has
848
- * applied, captured from the last `settled` frame (the suppressed-list-frame
849
- * watermark). Forwarded to {@link SubscriptionState.checkpointCallbacks}.
850
- * Absent until a `settled` frame arrives.
851
- */
852
- lastMutationId?: number;
853
- /** Last known value, used to short-circuit `useQuery`-style consumers. */
854
- lastValue: unknown;
855
- /**
856
- * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
857
- * captured from the last `data`/`delta`/`resume` frame. Persisted to the
858
- * durable read cache and replayed as `sinceSeq` on reconnect so the server
859
- * can resume instead of re-snapshotting (Pillar 1b/2). Absent until the
860
- * first cursor-stamped frame arrives.
861
- */
862
- serverCursor?: number;
863
- /**
864
- * The CDC `epoch` token the `serverCursor` belongs to, captured from the
865
- * same frame. Replayed as `sinceEpoch` on reconnect so the server resumes
866
- * only when the client is still on the same changelog timeline — a reset or
867
- * recycled shard advertises a new epoch, forcing a fresh snapshot. Absent
868
- * until the first epoch-stamped frame arrives.
869
- */
870
- serverEpoch?: string;
871
- /**
872
- * Monotonic counter incremented on every server-pushed delta or data.
873
- * Used by optimistic-update rollback to detect whether the server has
874
- * already moved past the value we'd otherwise restore.
875
- */
876
- serverVersion: number;
877
- readonly shardKey?: string;
878
- }
879
- /**
880
- * Active subscription registry. The client keys subscriptions by
881
- * `(functionPath, stableStringify(args), shardKey)` so duplicate calls share a
882
- * single server-side registration. Args are stably encoded (keys sorted at every
883
- * depth) so two structurally-equal arg records constructed with a different key
884
- * order (`{ a, b }` vs `{ b, a }`) collapse to the same key instead of leaking a
885
- * duplicate subscription.
886
- */
887
- declare class SubscriptionRegistry {
888
- static key(functionPath: string, args: Record<string, unknown>, shardKey?: string): string;
889
- private readonly byKey;
890
- private readonly byId;
891
- get(key: string): SubscriptionState | undefined;
892
- getById(id: string): SubscriptionState | undefined;
893
- add(state: SubscriptionState): void;
894
- remove(state: SubscriptionState): void;
895
- all(): SubscriptionState[];
896
- }
897
- /**
898
- * Read/write handle over the client's live query cache, handed to a mutation's
899
- * `withOptimisticUpdate` callback so a single mutation can optimistically patch
900
- * many subscribed queries at once (Convex's `OptimisticLocalStore` model).
901
- *
902
- * `getQuery` reads the current value (server value or any still-pending
903
- * optimistic override) of a subscribed query; `setQuery` writes an optimistic
904
- * override on top. Every write is collected as a rollback closure so the whole
905
- * batch unwinds atomically when the mutation settles or the server advances
906
- * past it — the same per-subscription rollback machinery the legacy
907
- * per-call `optimistic` transform uses, generalized to N queries.
908
- */
909
- interface OptimisticLocalStore {
910
- /**
911
- * Every loaded subscription on `function_`, regardless of args, paired with
912
- * the args it was subscribed under. Mirrors Convex's `getAllQueries` — handy
913
- * when a write must patch every variant of a list query (all channels,
914
- * all filters) without enumerating their args up front.
915
- */
916
- getAllQueries: <F extends FunctionReference>(function_: F) => {
917
- args: ArgsOf<F>;
918
- value: ReturnOf<F> | undefined;
919
- }[];
920
- /**
921
- * Current cached value for the subscribed `(function_, args)` query, or
922
- * `undefined` when nothing is subscribed/loaded for it. Reflects any
923
- * optimistic override already written in this batch.
924
- */
925
- getQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>) => ReturnOf<F> | undefined;
926
- /**
927
- * Write an optimistic override for the subscribed `(function_, args)`
928
- * query. A no-op (returns without effect) when no subscription matches —
929
- * mirroring Convex, where you only patch queries the page is watching.
930
- */
931
- setQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, value: ReturnOf<F> | undefined) => void;
932
- }
933
- /** A mutation's multi-query optimistic update: read/write the cache via `localStore`. */
934
- type OptimisticUpdate<Args> = (localStore: OptimisticLocalStore, args: Args) => void;
935
- /**
936
- * Build an {@link OptimisticLocalStore} bound to a subscription registry, the
937
- * mutation's shard key, and the `writeOptimisticToState` primitive. Returns the
938
- * store plus the ordered rollback closures every `setQuery` produced, so the
939
- * caller can unwind the whole batch (LIFO) if the mutation later fails — and
940
- * leave them in place to be GC'd alongside the subscription on success.
941
- */
942
- declare const createLocalStore: (subscriptions: SubscriptionRegistry, shardKey: string | undefined, write: (state: SubscriptionState, next: unknown) => () => void, stableStringify: (value: unknown) => string) => {
943
- rollbacks: (() => void)[];
944
- store: OptimisticLocalStore;
945
- };
946
- /**
947
- * Bounded async-iterator queue backing `LunoraClient.stream`.
948
- *
949
- * The server pushes one server `chunk` message per yielded value while the
950
- * client iterates with `for await (const chunk of stream)`. A producer that
951
- * outruns its consumer would otherwise OOM the page, so the buffer is bounded
952
- * — exceeding {@link DEFAULT_MAX_BUFFER} surfaces a `STREAM_BACKPRESSURE`
953
- * error to the iterator (and to the server-side cancel path).
954
- *
955
- * The queue is closed exactly once via {@link StreamHandle.complete} (success)
956
- * or {@link StreamHandle.fail} (transport / server error). Subsequent calls
957
- * are silent no-ops so a duplicate `complete` frame after a cancel doesn't
958
- * crash the page.
959
- */
960
- declare const DEFAULT_MAX_BUFFER = 1024;
961
- interface StreamHandle<T = unknown> {
962
- /** Mark the stream complete (no more chunks); resolves any pending consumer to `done:true`. */
963
- readonly complete: () => void;
964
- /** Surface an error to any pending consumer; subsequent pushes are dropped. */
965
- readonly fail: (error: Error) => void;
966
- /**
967
- * Push one chunk. Silent no-op once the stream is `complete`, `fail`-ed,
968
- * or `cancel`-ed. When the buffer is already at `maxBuffer`, the stream
969
- * is failed with a `STREAM_BACKPRESSURE` error and the push is dropped —
970
- * the producer never sees a thrown exception.
971
- */
972
- readonly push: (value: T) => void;
973
- }
974
- interface StreamIterable<T> extends AsyncIterable<T> {
975
- /** Cancel the stream from the consumer side: closes the iterator and notifies the registered canceller. */
976
- cancel: () => void;
977
- }
978
- /**
979
- * Build a stream handle paired with an async-iterable. The handle is the
980
- * server-driven side (the WS dispatcher pushes chunks / completes / errors);
981
- * the iterable is what the user awaits. `onCancel` is invoked exactly once
982
- * when the consumer calls `.cancel()` (or `.return()`) so the client can
983
- * send a `{type:"unsubscribe"}` frame to the server.
984
- */
985
- declare const createStream: <T>(options: {
986
- maxBuffer?: number;
987
- onCancel: () => void;
988
- }) => {
989
- handle: StreamHandle<T>;
990
- iterable: StreamIterable<T>;
991
- };
992
- /**
993
- * Aggregate live-socket health across every shard connection, for a UI status
994
- * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
995
- * is (re)connecting and none is open; `connected` = at least one socket is open;
996
- * `offline` = sockets exist but all are down (between reconnect attempts).
997
- */
998
- type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
999
- /**
1000
- * Per-call options for {@link LunoraClient.mutation} — the optimistic-update
1001
- * machinery plus `shardKey`. Exported (at the end of this file) so the framework
1002
- * adapters (`@lunora/react`, `/solid`, `/svelte`, `/vue`) can type their
1003
- * `mutate(args, options?)` against one canonical definition instead of
1004
- * re-declaring it.
1005
- */
1006
- interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
1007
- /**
1008
- * Override the auto-generated idempotency key (`x-lunora-mutation-id`). Lets a
1009
- * durable outbox replay a committed-but-unacked write under its *original* key
1010
- * so the server dedups it instead of applying it twice. Omit for normal calls —
1011
- * each then gets a fresh key.
1012
- */
1013
- mutationId?: string;
1014
- optimistic?: (current: TCurrent | undefined) => TValue;
1015
- /**
1016
- * Convex-parity multi-query optimistic update. Receives an
1017
- * `OptimisticLocalStore` over the live subscription cache plus the
1018
- * mutation's args, so one mutation can patch many subscribed queries at
1019
- * once; every write is rolled back atomically if the mutation fails.
1020
- */
1021
- optimisticUpdate?: OptimisticUpdate<TArgs>;
1022
- shardKey?: string;
1023
- }
1024
- /** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
1025
- type ShapeCallback = (rows: Record<string, unknown>[]) => void;
1026
- /**
1027
- * The high-water marks a shape poke has now synced to the client: `checkpoint`
1028
- * is the op-log cursor and `mutationId` the highest custom-mutator id the server
1029
- * echoed for this client. A `@lunora/db` collection feeds these into its
1030
- * checkpoint registry to drop optimistic overlays once the server's authoritative
1031
- * rows have landed.
1032
- */
1033
- interface SyncWatermark {
1034
- checkpoint?: number;
1035
- mutationId?: number;
1036
- }
1037
- /**
1038
- * Lunora browser/edge client. Talks RPC over HTTP and real-time deltas over
1039
- * a single multiplexed WebSocket.
1040
- *
1041
- * Reconnect, offline queueing, and optimistic updates are all handled here;
1042
- * see the package README for the wire protocol.
1043
- */
1044
- declare class LunoraClient {
1045
- /** 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. */
1046
- private static readonly MAX_POKE_BUFFERS;
1047
- readonly url: string;
1048
- readonly wsUrl: string;
1049
- private wsToken;
1050
- /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
1051
- private readonly authBasePath;
1052
- private readonly fetchImpl;
1053
- private readonly WebSocketImpl;
1054
- private readonly bookmark;
1055
- private readonly reconnectOptions;
1056
- /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
1057
- private readonly connectTimeoutMs;
1058
- /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
1059
- private readonly heartbeatIntervalMs;
1060
- private readonly offlineQueue;
1061
- /**
1062
- * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
1063
- * set, offline writes are delegated here and the built-in {@link OfflineQueue}
1064
- * is bypassed, so a db app has exactly one durable write path.
1065
- */
1066
- private readonly outbox;
1067
- /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
1068
- private readonly clientId;
1069
- /**
1070
- * Highest custom-mutator watermark the server has echoed for this client,
1071
- * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
1072
- * `__client_watermark` per shard. `callMutator` bumps it from every
1073
- * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
1074
- * it so a reload (which resets the in-memory counter) never reissues a stale
1075
- * sequence the server would silently swallow as a replay.
1076
- */
1077
- private readonly clientWatermarks;
1078
- /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
1079
- private outboxMutationCounter;
1080
- private readonly onPersistenceError;
1081
- private readonly persistence;
1082
- /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
1083
- private readonly queryCache;
1084
- /**
1085
- * Values restored from the `queryCache` at construction, keyed by the
1086
- * read-cache key, awaiting the `subscribe()` that will consume them. A
1087
- * key is consumed (deleted) the first time its subscription is created, so
1088
- * the cache only ever seeds the initial value — live frames take over after.
1089
- */
1090
- private readonly hydratedQueryCache;
1091
- /**
1092
- * Coalesced read-cache writes: the latest value per key, flushed to
1093
- * the `queryCache` on a short debounce so a burst of deltas persists once.
1094
- */
1095
- private readonly pendingCacheWrites;
1096
- private cacheFlushTimer;
1097
- private readonly subscriptions;
1098
- /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
1099
- private readonly connections;
1100
- /** Default `connect`-envelope context applied to a shard with no explicit override. */
1101
- private readonly defaultConnectionContext;
1102
- /**
1103
- * Per-shard `connect`-envelope context registered via `setConnectionContext`
1104
- * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
1105
- * on every socket open so it replays across reconnects, and forwarded to the
1106
- * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
1107
- * imperative (last-writer-wins) override; refcounted holders registered via
1108
- * `acquireConnectionContext` live in `connectionContextHolders` and take
1109
- * precedence — see `effectiveConnectionContext`.
1110
- */
1111
- private readonly connectionContexts;
1112
- /**
1113
- * Per-shard stack of refcounted connection-context holders (keyed by
1114
- * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
1115
- * is an opaque token carrying its `context`; the most-recently acquired
1116
- * holder wins (last-writer-wins among live holders), and the context is only
1117
- * cleared for a shard once its last holder releases — so two concurrently
1118
- * mounted presence hooks on the same shard can't stomp each other's context
1119
- * on cleanup. A holder is identified by reference identity so a release
1120
- * removes exactly the right one regardless of stack position.
1121
- */
1122
- private readonly connectionContextHolders;
1123
- private authToken;
1124
- /**
1125
- * Identity stamp recorded against each queued offline mutation, keyed by
1126
- * the queue-assigned mutation id. Captured at enqueue from the auth token
1127
- * in effect at the time, and re-checked at flush so a queued write can
1128
- * never replay under a different identity than the one that issued it.
1129
- * See `identityFingerprint` for the fingerprint shape.
1130
- */
1131
- private readonly queuedIdentities;
1132
- private closed;
1133
- /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
1134
- private readonly authTokenListeners;
1135
- /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
1136
- private readonly statusListeners;
1137
- /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
1138
- private readonly tokenExpiredListeners;
1139
- /**
1140
- * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
1141
- * of callbacks. Membership doubles as the resubscribe set replayed on every
1142
- * (re)connect so a topic survives a socket bounce.
1143
- */
1144
- private readonly whisperHandlers;
1145
- /** Last status broadcast, so we only notify listeners on an actual change. */
1146
- private lastStatus;
1147
- private nextSubId;
1148
- private nextStreamId;
1149
- /**
1150
- * In-flight client-side stream readers, keyed by the stream id sent on the
1151
- * wire. The handle drives the underlying iterator queue and `shardKey`
1152
- * tells us which socket to push the cancel frame onto when the consumer
1153
- * calls `.cancel()` or the iterator is garbage-collected.
1154
- */
1155
- private readonly streams;
1156
- /** Live shape subscriptions (partial replication), keyed by their wire id. */
1157
- private readonly shapeSubscriptions;
1158
- /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
1159
- private readonly pokeBuffers;
1160
- private nextShapeId;
1161
- constructor(options: LunoraClientOptions);
1162
- /**
1163
- * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
1164
- * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
1165
- * sync across all mounted instances.
1166
- *
1167
- * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
1168
- * time and lives in the URL. To refresh live WS auth, call
1169
- * {@link setWsToken} explicitly, which closes existing shard sockets to
1170
- * force a reconnect with the new credential.
1171
- */
1172
- setAuthToken(token: string | null): void;
1173
- getAuthToken(): string | null;
1174
- /**
1175
- * The current identity fingerprint (the same stamp queued offline writes
1176
- * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
1177
- * owns its own at-least-once replay outside the built-in `OfflineQueue` —
1178
- * can drop a persisted write whose captured `identity` no longer matches the
1179
- * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
1180
- */
1181
- currentIdentity(): string | null;
1182
- /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1183
- clientIdentifier(): string;
1184
- /**
1185
- * The highest custom-mutator watermark the server has echoed for this client
1186
- * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
1187
- * its `clientSeq` generator from this so a reload never reissues a sequence
1188
- * the server has already applied (which it would swallow as a replay, silently
1189
- * dropping the write).
1190
- */
1191
- confirmedMutationWatermark(shardKey?: string): number;
1192
- /**
1193
- * Push a custom mutator to its authoritative server impl over the watermark
1194
- * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
1195
- * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
1196
- * client's `__client_watermark`.
1197
- *
1198
- * Returns the server `result` plus `applied`: `true` when the DO ran this push
1199
- * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
1200
- * was at or below the stored watermark — e.g. a stale sequence after a reload).
1201
- * A `false` verdict tells the caller to reissue above the now-known watermark
1202
- * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
1203
- * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
1204
- *
1205
- * This is the online transport for `@lunora/db`'s client-mutator runtime; the
1206
- * optimistic overlay + durable-outbox concerns live in that runtime, not here.
1207
- */
1208
- callMutator(functionPath: string, args: Record<string, unknown>, options?: {
1209
- clientSeq?: number;
1210
- shardKey?: string;
1211
- }): Promise<{
1212
- applied: boolean;
1213
- result: unknown;
1214
- }>;
1215
- /**
1216
- * Subscribe to auth-token changes. Returns an unsubscribe function. The
1217
- * listener is NOT invoked on registration — use {@link getAuthToken} for
1218
- * the current value.
1219
- */
1220
- onAuthTokenChange(listener: (token: string | null) => void): Unsubscribe;
1221
- /**
1222
- * Fetch the currently authenticated user from better-auth's `get-session`
1223
- * endpoint, returning the `user` record or `null` when signed out. Sends
1224
- * the stored bearer token (if any) and `credentials: "include"` so a
1225
- * cookie-session is also honoured. A network/parse failure or a non-OK
1226
- * response resolves to `null` rather than throwing — callers treat "couldn't
1227
- * resolve identity" as "signed out".
1228
- *
1229
- * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
1230
- * the token changes (that's what `@lunora/react`'s `useAuth` does).
1231
- */
1232
- getCurrentUser(): Promise<User | null>;
1233
- /**
1234
- * Replace the token appended to WS upgrade URLs as `?token=…` and close
1235
- * every open shard socket so the reconnect picks up the new value. Call
1236
- * this whenever the user's WS credential changes (rotating the admin token
1237
- * in the studio, switching workspaces, etc.). Bearer tokens for HTTP
1238
- * RPC are independent — see {@link setAuthToken}.
1239
- */
1240
- setWsToken(token: string | undefined): void;
1241
- /**
1242
- * Register (or clear, with `undefined`) the app context sent in the `connect`
1243
- * envelope for a shard's socket, overriding the client-wide
1244
- * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
1245
- * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
1246
- * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
1247
- * presence row is removed the instant the socket drops, with no TTL lag.
1248
- *
1249
- * Stored per shard and replayed on every (re)connect. When a socket for the
1250
- * shard is already open, a fresh `connect` envelope is sent immediately so the
1251
- * server sees the new context without waiting for a reconnect.
1252
- */
1253
- setConnectionContext(context: Record<string, unknown> | undefined, options?: {
1254
- shardKey?: string;
1255
- }): void;
1256
- /**
1257
- * Refcounted variant of {@link setConnectionContext}: register a connection
1258
- * `context` for a shard and get back a release function. Unlike the imperative
1259
- * setter, the context is only cleared once the *last* acquired holder releases
1260
- * it — so two components (e.g. two mounted `usePresence` hooks) on the same
1261
- * shard no longer clobber each other's context when one of them unmounts. The
1262
- * most-recently acquired live holder wins (last-writer-wins), and releasing
1263
- * the top holder falls back to the previous one rather than clearing.
1264
- *
1265
- * With a single holder the behaviour is identical to a
1266
- * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
1267
- * Releasing more than once is a no-op (the holder is matched by reference, so
1268
- * a double release can't drop a different holder).
1269
- */
1270
- acquireConnectionContext(context: Record<string, unknown>, options?: {
1271
- shardKey?: string;
1272
- }): Unsubscribe;
1273
- /**
1274
- * Join a whisper `topic` and receive every ephemeral message other members
1275
- * broadcast to it on the same shard (typing indicators, live cursors,
1276
- * presence pings). Whispers never touch the server's durable state — there's
1277
- * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
1278
- * is left on the server once its last local handler unsubscribes.
1279
- *
1280
- * `handler` receives the raw `data` and the sender's verified `from` user id
1281
- * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
1282
- * (the default shard when omitted) — use the same shard you target with the
1283
- * matching queries/mutations so members land on the same Durable Object.
1284
- *
1285
- * Security: whisper topics are NOT access-controlled beyond the shard
1286
- * boundary — any client that can open a socket to the shard can join, read,
1287
- * and inject on any topic name. `from` is server-stamped and unforgeable, but
1288
- * do not put data on a whisper topic that some shard members shouldn't see,
1289
- * and don't trust a whisper's `data` as authorization. Use a query/mutation
1290
- * (with RLS) for anything privileged; whispers are for transient awareness.
1291
- */
1292
- whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
1293
- shardKey?: string;
1294
- }): Unsubscribe;
1295
- /**
1296
- * Broadcast an ephemeral `data` payload to the other members of a whisper
1297
- * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
1298
- * dropped when the shard socket isn't open (whispers are transient, never
1299
- * queued), and the server silently drops it if the sender exceeds its
1300
- * whisper rate budget. The sender never receives its own whisper. Omitting
1301
- * `data` delivers JSON `null` to receivers (not `undefined`).
1302
- */
1303
- whisper(topic: string, data?: unknown, options?: {
1304
- shardKey?: string;
1305
- }): void;
1306
- /**
1307
- * Subscribe to token-expiry events: invoked whenever the server drops a
1308
- * shard socket because the connection's credential lapsed (close code
1309
- * `4001`). The client already reconnects automatically (re-resolving
1310
- * identity from the cookie/token in effect); use this to refresh a
1311
- * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
1312
- * with a freshly minted one. Returns an unsubscribe function.
1313
- */
1314
- onTokenExpired(listener: () => void): Unsubscribe;
1315
- /**
1316
- * Current aggregate live-socket status across all shard connections. See
1317
- * {@link ConnectionStatus}.
1318
- */
1319
- connectionStatus(): ConnectionStatus;
1320
- /**
1321
- * Subscribe to aggregate connection-status changes. Invokes `listener`
1322
- * immediately with the current status, then on every transition. Returns an
1323
- * unsubscribe function.
1324
- */
1325
- onConnectionStatus(listener: (status: ConnectionStatus) => void): Unsubscribe;
1326
- query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1327
- shardKey?: string;
1328
- }): Promise<ReturnOf<F>>;
1329
- /**
1330
- * Invoke a mutation. Errors propagate as rejections.
1331
- *
1332
- * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
1333
- * only when the targeted shard's socket was open at least once already
1334
- * (`wasEverConnected`), so the registry / resubscribe handshake has run.
1335
- * Mutations issued before the very first WS connect to a shard fail fast.
1336
- * Opt into queueing-before-first-connect via
1337
- * `OfflineQueueOptions.queueBeforeFirstConnect`.
1338
- */
1339
- mutation<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>): Promise<ReturnOf<F>>;
1340
- action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1341
- shardKey?: string;
1342
- }): Promise<ReturnOf<F>>;
1343
- /**
1344
- * Read the cross-shard request distribution for a `.shardBy(...)` table —
1345
- * the feed the studio's `hot_shard` advisor lint consumes. Hits the
1346
- * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
1347
- * cheap per-shard `getMetrics` read out across every live shard and returns
1348
- * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
1349
- * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
1350
- * and `adminToken`, and this client's auth token to match; defaults any
1351
- * absent field so an older worker yields an empty-but-valid shape.
1352
- */
1353
- shardTraffic(table: string): Promise<ShardTrafficResult>;
1354
- /**
1355
- * List the functions queued via `runAfter` / `runAt`, soonest-due last
1356
- * (the worker returns them in storage order). Hits the admin-gated
1357
- * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
1358
- * `schedulerDO` namespace and `adminToken`, and this client's auth token
1359
- * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
1360
- */
1361
- listScheduledJobs(): Promise<ScheduleRecord[]>;
1362
- /**
1363
- * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
1364
- * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
1365
- * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
1366
- * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
1367
- * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
1368
- * namespace + `adminToken` on the worker and a matching auth token here).
1369
- * Defaults any absent field so an older worker still yields a valid shape.
1370
- */
1371
- schedulerStatus(): Promise<SchedulerStatus>;
1372
- /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
1373
- cancelScheduledJob(id: string): Promise<{
1374
- cancelled: boolean;
1375
- }>;
1376
- /**
1377
- * List the dead-letter jobs: schedules that exhausted their retry budget
1378
- * and were parked instead of dropped. These never appear in
1379
- * {@link listScheduledJobs} (their live header is gone), so this is the only
1380
- * way the studio surfaces a permanently-failed job. Hits the admin-gated
1381
- * `GET /_lunora/admin/scheduled/dead`; same preconditions as
1382
- * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
1383
- */
1384
- listDeadJobs(): Promise<ScheduleRecord[]>;
1385
- /**
1386
- * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
1387
- * retry budget and fires on the next drain. Returns whether a parked record
1388
- * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
1389
- */
1390
- retryDeadJob(id: string): Promise<{
1391
- retried: boolean;
1392
- }>;
1393
- /**
1394
- * Permanently drop a dead-letter job by id (the operator has decided not to
1395
- * recover it). Returns whether a parked record was removed. Hits the
1396
- * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
1397
- */
1398
- removeDeadJob(id: string): Promise<{
1399
- removed: boolean;
1400
- }>;
1401
- /**
1402
- * List a workflow's instances via the admin Workflows proxy
1403
- * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
1404
- * the `Workflow` binding can't expose. Requires the worker to be built with a
1405
- * `workflowsClient` (Cloudflare account id + API token). When one isn't
1406
- * configured this does NOT reject: the proxy returns a `200 { configured:
1407
- * false }` sentinel, so the result resolves with `configured === false` and an
1408
- * empty `instances` list — callers should branch on that flag rather than
1409
- * try/catch. (The instance-detail / status endpoints still reject with 501.)
1410
- * `name` is the deployed workflow name.
1411
- */
1412
- listWorkflowInstances(options: {
1413
- name: string;
1414
- page?: number;
1415
- perPage?: number;
1416
- status?: WorkflowInstanceStatus;
1417
- }): Promise<WorkflowInstancePage>;
1418
- /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
1419
- getWorkflowInstance(options: {
1420
- id: string;
1421
- name: string;
1422
- }): Promise<WorkflowInstanceDetail>;
1423
- /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
1424
- setWorkflowInstanceStatus(options: {
1425
- action: WorkflowInstanceAction;
1426
- id: string;
1427
- name: string;
1428
- }): Promise<{
1429
- status: WorkflowInstanceStatus;
1430
- }>;
1431
- /**
1432
- * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
1433
- * WebSocket. `onJobs` fires with the full list on connect and on every
1434
- * change (schedule / cancel / alarm-fire). Reconnects with the client's
1435
- * configured backoff. Requires `wsToken` to be set to the admin token (the
1436
- * browser can't send an `Authorization` header on a WS). Returns an
1437
- * unsubscribe function that closes the socket and stops reconnecting.
1438
- */
1439
- subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
1440
- /**
1441
- * List the registered public functions (queries / mutations / actions) with
1442
- * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1443
- * the worker must be built with a `functions` registry and `adminToken`, and
1444
- * this client's auth token must match. Powers `@lunora/studio`'s function
1445
- * runner auto-discovery.
1446
- */
1447
- listFunctions(): Promise<FunctionDescriptor[]>;
1448
- /**
1449
- * List the code-defined cron triggers (the `cronJobs()` map injected on the
1450
- * worker), each flattened to its firing `cron` expression. Hits the
1451
- * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1452
- * built with a `cronJobs` map and `adminToken`, and this client's auth token
1453
- * must match. These are static (Cloudflare exposes no runtime cron
1454
- * introspection), so the studio renders them read-only alongside the dynamic
1455
- * scheduler jobs.
1456
- */
1457
- getCronJobs(): Promise<CronJobInfo[]>;
1458
- /**
1459
- * Manually fire one code-defined cron job by name — the same dispatch the
1460
- * scheduled trigger runs (dispatch the function, or start the durable
1461
- * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1462
- * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1463
- * and this client's auth token must match. Resolves when the job has run (a
1464
- * function job's shard response is 2xx, or the workflow instance was created)
1465
- * and rejects with the dispatch error otherwise.
1466
- */
1467
- runCronJob(name: string): Promise<{
1468
- name: string;
1469
- ran: boolean;
1470
- }>;
1471
- /**
1472
- * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1473
- * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1474
- * `openApiSpec` and `adminToken`, and this client's auth token must match.
1475
- * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1476
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1477
- * document (no `paths`), so callers can render a "not configured" state.
1478
- */
1479
- fetchOpenApi(): Promise<Record<string, unknown>>;
1480
- /**
1481
- * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1482
- * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1483
- * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1484
- * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1485
- * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1486
- * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1487
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1488
- * document (no `methods`), so callers can render a "not configured" state.
1489
- */
1490
- fetchOpenRpc(): Promise<Record<string, unknown>>;
1491
- /**
1492
- * List objects in the storage bucket, optionally under a `prefix` and from a
1493
- * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1494
- * endpoint — the worker must be built with a `storageList` function and
1495
- * `adminToken`, and this client's auth token must match. Powers
1496
- * `@lunora/studio`'s file browser.
1497
- */
1498
- listStorageObjects(options?: {
1499
- bucket?: string;
1500
- cursor?: string;
1501
- limit?: number;
1502
- prefix?: string;
1503
- }): Promise<StorageListPage>;
1504
- /**
1505
- * Delete one object from the storage bucket by key. Hits the admin-gated
1506
- * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1507
- * with a `storageDelete` function and `adminToken`. Powers the studio file
1508
- * browser's per-row delete; resolves `{ deleted, key }`.
1509
- */
1510
- deleteStorageObject(key: string, options?: {
1511
- bucket?: string;
1512
- }): Promise<{
1513
- deleted: boolean;
1514
- key: string;
1515
- }>;
1516
- /**
1517
- * List the storage bucket names the worker exposes, for the studio file
1518
- * browser's bucket picker. Hits the admin-gated
1519
- * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1520
- * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1521
- */
1522
- listStorageBuckets(): Promise<string[]>;
1523
- /**
1524
- * Upload one object to the storage bucket. Hits the admin-gated
1525
- * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1526
- * optional `contentType` header — the worker must be built with a
1527
- * `storageUpload` function and `adminToken`. Powers the studio file
1528
- * browser's upload control; resolves `{ etag?, key }`.
1529
- */
1530
- uploadStorageObject(options: {
1531
- body: ArrayBuffer | Blob;
1532
- bucket?: string;
1533
- contentType?: string;
1534
- key: string;
1535
- }): Promise<{
1536
- etag?: string;
1537
- key: string;
1538
- }>;
1539
- /**
1540
- * Build a (signed or public) URL for one object. Hits the admin-gated
1541
- * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1542
- * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1543
- * file browser's copy-URL action; resolves the URL string.
1544
- *
1545
- * `options.expiresInSeconds` requests a share-link lifetime, which is
1546
- * validated/clamped server-side. The options object mirrors the worker's
1547
- * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1548
- * as future fields there).
1549
- */
1550
- signedStorageUrl(key: string, options?: {
1551
- bucket?: string;
1552
- expiresInSeconds?: number;
1553
- }): Promise<string>;
1554
- /**
1555
- * List the `.global()` (D1-backed) tables with their row counts. Hits the
1556
- * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1557
- * be built with a `globalIntrospector` and `adminToken`. Powers the data
1558
- * browser's global mode.
1559
- */
1560
- listGlobalTables(): Promise<GlobalTableInfo[]>;
1561
- /**
1562
- * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1563
- * page to rows matching each `column = value` eq constraint — the drill-down a
1564
- * facet-value click applies; the array is JSON-encoded into the `filters`
1565
- * query param and the values are bound server-side.
1566
- */
1567
- readGlobalTablePage(options: {
1568
- filters?: GlobalFilterClause[];
1569
- limit?: number;
1570
- offset?: number;
1571
- table: string;
1572
- }): Promise<GlobalTablePage>;
1573
- /**
1574
- * Summarise the distinct values of one column in a `.global()` table over the
1575
- * active view (the same eq `filters` the browser is previewing) — the global
1576
- * twin of the shard browser's facet. Hits the admin-gated
1577
- * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1578
- * server-side. Powers the global data browser's facet sidebar.
1579
- */
1580
- facetGlobalColumn(options: {
1581
- column: string;
1582
- filters?: GlobalFilterClause[];
1583
- limit?: number;
1584
- table: string;
1585
- }): Promise<GlobalFacetResult>;
1586
- /**
1587
- * List the schema's Vectorize indexes with their declared shape (table,
1588
- * field, dimensions, metric, metadata) and live stats (vector count,
1589
- * processing watermark) when the binding is reachable. Hits the admin-gated
1590
- * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1591
- * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1592
- * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1593
- * from the generated `LUNORA_VECTOR_INDEXES` registry.
1594
- */
1595
- listVectorIndexes(): Promise<VectorIndexSummary[]>;
1596
- /**
1597
- * Run a nearest-neighbour similarity query against one vector index: the
1598
- * worker embeds `text` via the index's embedder and returns the top matches.
1599
- * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1600
- * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1601
- * wired (the index lists read-only).
1602
- */
1603
- queryVectorIndex(options: {
1604
- name: string;
1605
- text: string;
1606
- topK?: number;
1607
- }): Promise<VectorQueryMatch[]>;
1608
- /**
1609
- * List authenticated users, paged and optionally searched / filtered / sorted.
1610
- * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1611
- * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1612
- * users dashboard.
1613
- */
1614
- listAuthUsers(options?: {
1615
- filterField?: string;
1616
- filterValue?: string;
1617
- limit?: number;
1618
- offset?: number;
1619
- search?: string;
1620
- searchField?: string;
1621
- sortBy?: string;
1622
- sortDirection?: "asc" | "desc";
1623
- }): Promise<AuthPage<AuthUser>>;
1624
- /**
1625
- * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1626
- * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1627
- * `data` carries any app-defined `user.additionalFields`.
1628
- */
1629
- createAuthUser(input: {
1630
- data?: Record<string, unknown>;
1631
- email: string;
1632
- name: string;
1633
- password?: string;
1634
- role?: string | string[];
1635
- }): Promise<AuthUser>;
1636
- /** Set a user's role (string, or array joined comma-wise server-side). */
1637
- setAuthUserRole(input: {
1638
- role: string | string[];
1639
- userId: string;
1640
- }): Promise<AuthUser>;
1641
- /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1642
- banAuthUser(input: {
1643
- expiresInSeconds?: number;
1644
- reason?: string;
1645
- userId: string;
1646
- }): Promise<AuthUser>;
1647
- /** Lift a user's ban. */
1648
- unbanAuthUser(input: {
1649
- userId: string;
1650
- }): Promise<AuthUser>;
1651
- /** Set a user's password (admin override — no current-password challenge). */
1652
- setAuthUserPassword(input: {
1653
- newPassword: string;
1654
- userId: string;
1655
- }): Promise<void>;
1656
- /** Permanently delete a user and revoke their sessions. */
1657
- removeAuthUser(input: {
1658
- userId: string;
1659
- }): Promise<void>;
1660
- /**
1661
- * Mint an impersonation session for a user, returning its bearer `token`.
1662
- * The caller is responsible for using the token (e.g. setting the session
1663
- * cookie); the server performs no cookie round-trip.
1664
- */
1665
- impersonateAuthUser(input: {
1666
- userId: string;
1667
- }): Promise<AuthImpersonation>;
1668
- /** Revoke a single session by its id (force sign-out of one device). */
1669
- revokeAuthSession(input: {
1670
- sessionId: string;
1671
- }): Promise<void>;
1672
- /** Revoke every session for a user (force sign-out everywhere). */
1673
- revokeAuthUserSessions(input: {
1674
- userId: string;
1675
- }): Promise<void>;
1676
- /**
1677
- * Report which auth dashboard surfaces are available — derived server-side
1678
- * from the enabled better-auth plugins. The studio renders only the panels
1679
- * whose capability is `true`.
1680
- */
1681
- getAuthCapabilities(): Promise<AuthCapabilities>;
1682
- /** Update a user's fields (name/email/app-defined `additionalFields`). */
1683
- updateAuthUser(input: {
1684
- data: Record<string, unknown>;
1685
- userId: string;
1686
- }): Promise<AuthUser>;
1687
- /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1688
- listAuthAccounts(input: {
1689
- userId: string;
1690
- }): Promise<Record<string, unknown>[]>;
1691
- /** Unlink a linked account from a user. */
1692
- unlinkAuthAccount(input: {
1693
- accountId: string;
1694
- userId: string;
1695
- }): Promise<void>;
1696
- /** List a user's registered passkeys (requires the passkey plugin). */
1697
- listAuthPasskeys(input: {
1698
- userId: string;
1699
- }): Promise<Record<string, unknown>[]>;
1700
- /** Delete a passkey by id (requires the passkey plugin). */
1701
- deleteAuthPasskey(input: {
1702
- passkeyId: string;
1703
- }): Promise<void>;
1704
- /** Disable two-factor auth for a user (requires the two-factor plugin). */
1705
- disableAuthTwoFactor(input: {
1706
- userId: string;
1707
- }): Promise<void>;
1708
- /** List organizations, paged (requires the organization plugin). */
1709
- listAuthOrganizations(options?: {
1710
- limit?: number;
1711
- offset?: number;
1712
- }): Promise<AuthPage<Record<string, unknown>>>;
1713
- /** List the members of an organization (requires the organization plugin). */
1714
- listAuthOrgMembers(input: {
1715
- limit?: number;
1716
- offset?: number;
1717
- organizationId: string;
1718
- }): Promise<AuthPage<Record<string, unknown>>>;
1719
- /** List an organization's pending invitations (requires the organization plugin). */
1720
- listAuthOrgInvitations(input: {
1721
- limit?: number;
1722
- offset?: number;
1723
- organizationId: string;
1724
- }): Promise<AuthPage<Record<string, unknown>>>;
1725
- /** Remove a member from an organization. */
1726
- removeAuthOrgMember(input: {
1727
- memberId: string;
1728
- }): Promise<void>;
1729
- /** Cancel a pending organization invitation. */
1730
- cancelAuthOrgInvitation(input: {
1731
- invitationId: string;
1732
- }): Promise<void>;
1733
- /** List auth sessions, paged and optionally filtered to one user. */
1734
- listAuthSessions(options?: {
1735
- limit?: number;
1736
- offset?: number;
1737
- userId?: string;
1738
- }): Promise<AuthPage<AuthSession>>;
1739
- subscribe<F extends FunctionReference>(function_: F, args: ArgsOf<F>, callback: (data: ReturnOf<F>) => void, options?: {
1740
- onCheckpoint?: (watermark: SyncWatermark) => void;
1741
- onError?: SubscriptionErrorCallback;
1742
- shardKey?: string;
1743
- }): Unsubscribe;
1744
- /**
1745
- * Subscribe to a declarative **shape** — server-side partial replication
1746
- * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
1747
- * {@link subscribe} for the poke protocol: the client sends the shape *name* +
1748
- * validated `args` (never a `where` the client could forge), the server seeds
1749
- * the current membership as an insert-poke and streams live membership diffs.
1750
- * Each applied poke materializes the shape's rowset and invokes `callback`.
1751
- *
1752
- * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
1753
- * (name, args): the server resolves them under the socket's verified identity,
1754
- * so every call gets its own id + view. The returned function unsubscribes.
1755
- */
1756
- subscribeShape(shape: {
1757
- args?: Record<string, unknown>;
1758
- name: string;
1759
- }, callback: ShapeCallback, options?: {
1760
- onCheckpoint?: (watermark: SyncWatermark) => void;
1761
- onError?: SubscriptionErrorCallback;
1762
- shardKey?: string;
1763
- }): Unsubscribe;
1764
- /**
1765
- * Open a streaming query. The function reference must be a
1766
- * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1767
- * the type constraint catches accidental use of a query/mutation/action
1768
- * reference at compile time. The returned iterable yields one element per
1769
- * chunk frame the server pushes, terminating when the server sends
1770
- * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1771
- * rejection on the next `next()`.
1772
- *
1773
- * Streams ride the same WS as subscriptions and share the unsubscribe
1774
- * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1775
- * which the DO recognises as an abort signal for the in-flight iterator.
1776
- *
1777
- * Stream-start frames buffered while the socket is (re)connecting are
1778
- * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1779
- * cap drops the oldest queued frame (and fails its consumer) so a stuck
1780
- * reconnect can't OOM the page.
1781
- */
1782
- stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
1783
- maxBuffer?: number;
1784
- shardKey?: string;
1785
- }): StreamIterable<ReturnOf<F>>;
1786
- close(): void;
1787
- /**
1788
- * Persist a mutation that can't go out on the wire right now (offline, or
1789
- * mid-reconnect after a prior connect). The optimistic update has already
1790
- * been applied by `mutation`; this only chooses the durable write path and
1791
- * rolls the optimistic write back if persistence is rejected.
1792
- *
1793
- * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
1794
- * owns persistence + at-least-once replay, so we delegate and return
1795
- * optimistically (confirmation rides the synced view). Otherwise the
1796
- * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
1797
- */
1798
- private enqueueOfflineMutation;
1799
- /**
1800
- * Restore offline mutations persisted in a prior session and open a socket
1801
- * for each shard they target so they flush once the WS reconnects. Failures
1802
- * are swallowed — a broken durable store must not stop the client booting.
1803
- */
1804
- private hydratePersistedQueue;
1805
- /**
1806
- * Load every cached query into {@link hydratedQueryCache} so the next
1807
- * `subscribe()` for each key seeds its initial value off disk. A
1808
- * subscription created before this resolves simply misses the cache (it
1809
- * gets a live snapshot as before); the gate at seed time also drops any
1810
- * entry whose stamped identity no longer matches the current one.
1811
- */
1812
- private hydrateQueryCache;
1813
- /**
1814
- * Consume the hydrated read-cache entry for a key (if any), gated on
1815
- * identity. The entry is removed whether or not it matches — the cache only
1816
- * ever seeds a subscription's first value. A mismatch (the cache was written
1817
- * under a different identity) yields `undefined` so a signed-out cache never
1818
- * leaks into a new session.
1819
- */
1820
- private takeHydratedCache;
1821
- /**
1822
- * Queue a coalesced read-cache write for a subscription's current value.
1823
- * Latest-wins per key; flushed on a short debounce so a delta burst writes
1824
- * once. No-op when the read cache is disabled or the value is undefined
1825
- * (nothing to render offline).
1826
- */
1827
- private persistQueryValue;
1828
- /** Drain {@link pendingCacheWrites} to the durable store. */
1829
- private flushQueryCacheWrites;
1830
- /** Derive the aggregate status from the per-shard socket states. */
1831
- private computeStatus;
1832
- /** Recompute the aggregate status and notify listeners if it changed. */
1833
- private emitConnectionStatus;
1834
- /**
1835
- * Apply an optimistic update to the subscription that matches the mutation's
1836
- * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
1837
- * invoke if the mutation later fails.
1838
- *
1839
- * The registry is already indexed by exactly this triple via
1840
- * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
1841
- * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
1842
- *
1843
- * `shardKey` normalization: both `undefined` and `""` map to the empty string
1844
- * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
1845
- * a shardKey correctly matches a subscription registered without one regardless
1846
- * of whether the caller passed `undefined` or omitted the field.
1847
- */
1848
- private applyOptimisticUpdates;
1849
- /**
1850
- * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
1851
- * to the live subscription registry, appending each `setQuery` write's
1852
- * rollback to `optimisticRollbacks` (the same LIFO list the legacy path uses,
1853
- * unwound on settle/error). A throwing callback unwinds its own partial
1854
- * writes — LIFO over just the rollbacks it produced — and is swallowed, so a
1855
- * buggy optimistic update can never fail the mutation or leave a partial
1856
- * patch live, mirroring the legacy transform's throw handling.
1857
- */
1858
- private applyOptimisticUpdate;
1859
- private getConnection;
1860
- private getOrCreateConnection;
1861
- private wsUrlFor;
1862
- /**
1863
- * Build the outbound RPC headers: JSON content type, optional bearer auth,
1864
- * the optional mutation-replay idempotency key, and the D1 read-your-writes
1865
- * bookmark when the caller opted into `attachBookmark`. The mutation id
1866
- * rides both the direct send and any offline-queue replay of the same write,
1867
- * so a mutation the server already committed returns its cached result
1868
- * instead of running twice.
1869
- */
1870
- private rpcRequestHeaders;
1871
- private rpc;
1872
- /**
1873
- * Authenticated request to a non-RPC admin endpoint (the scheduler list /
1874
- * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
1875
- * worker's `{ error: { code, message } }` envelope as a coded `Error` —
1876
- * mirroring {@link rpc} so callers see the same failure shape.
1877
- */
1878
- private adminFetch;
1879
- /**
1880
- * Resolve the effective connection context for a shard: the most-recently
1881
- * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
1882
- * back to the imperative {@link setConnectionContext} override, then the
1883
- * client-wide default. Returns `undefined` when none apply.
1884
- */
1885
- private effectiveConnectionContext;
1886
- /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
1887
- private refreshConnectionContext;
1888
- /**
1889
- * Send the one-shot `connect` envelope on an open shard socket. Always sent
1890
- * once per socket open, so the server's `onConnect` hooks fire symmetrically
1891
- * with `onDisconnect` (which the DO dispatches unconditionally at close for
1892
- * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
1893
- * hooks are registered, so the single frame costs nothing in the common case.
1894
- *
1895
- * The shard's registered context (or the client-wide default) rides along
1896
- * when one is set — the DO records it on the attachment for replay to
1897
- * `onDisconnect`. A socket with no registered context still announces itself;
1898
- * the envelope simply omits `context`, which is optional on the wire.
1899
- * Register a context — e.g. `setConnectionContext({})` — to attach app state
1900
- * to the lifecycle dispatch.
1901
- */
1902
- private sendConnectEnvelope;
1903
- /**
1904
- * Re-send every shape subscription bound to `shardKey` over its (now open)
1905
- * socket. Each frame carries the shape's last applied checkpoint, so the
1906
- * server resumes from it — or re-seeds when the cursor fell below CDC
1907
- * retention or the epoch forked.
1908
- */
1909
- private resendShapeSubscriptions;
1910
- private ensureSocket;
1911
- private handleDisconnect;
1912
- /**
1913
- * Begin the keepalive heartbeat on an open connection. Each tick sends a
1914
- * {@link WS_KEEPALIVE_PING} text frame the server answers from its
1915
- * hibernation auto-response without waking the DO. A no-op when the
1916
- * heartbeat is disabled (an interval of zero or less); idempotent — any
1917
- * existing timer is cleared first so a reconnect can't leak intervals.
1918
- */
1919
- private startHeartbeat;
1920
- /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
1921
- private stopHeartbeat;
1922
- /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
1923
- private markShardPendingAck;
1924
- private sendSubscribeIfOpen;
1925
- private sendShapeSubscribeIfOpen;
1926
- private handleServerMessage;
1927
- private handleErrorMessage;
1928
- private handlePokeStart;
1929
- private handlePokePart;
1930
- private handlePokeEnd;
1931
- /** Materialize a shape's keyed view to an array and invoke its callbacks. */
1932
- private emitShapeRows;
1933
- private handleDataMessage;
1934
- /**
1935
- * Handle a `resume` frame (Pillar 1b): the server proved nothing the
1936
- * subscription reads changed since our `sinceSeq`, so the cached value is
1937
- * still current. We keep `lastValue` as-is, mark the sub acked, and advance
1938
- * the cursor (re-persisting so the next reconnect resumes from the newer
1939
- * watermark). No callback fires — the value didn't change, and `subscribe()`
1940
- * already replayed the cached value to every consumer synchronously.
1941
- */
1942
- private handleResumeMessage;
1943
- /**
1944
- * Handle a `settled` frame: a write touched one of this subscription's read
1945
- * tables but produced a byte-identical result, so the server suppressed the
1946
- * data frame. Like {@link handleResumeMessage} the value didn't change — we
1947
- * advance the resume position and re-persist — but we ALSO surface the echoed
1948
- * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
1949
- * collection drops the optimistic overlay for the confirmed write (otherwise
1950
- * its checkpoint gate, fed only by data frames, would hang forever). Sent
1951
- * only to custom-mutator clients; plain `useQuery` subscribers leave
1952
- * `onCheckpoint` unset and this is a near no-op.
1953
- */
1954
- private handleSettledMessage;
1955
- /**
1956
- * Mark `state` acked and, when the frame carries a newer cursor/epoch than
1957
- * the cached position, advance the resume watermark and re-persist. Shared by
1958
- * the `resume` and `settled` frame handlers — both acknowledge "nothing the
1959
- * client must re-render changed, but the resume position may have moved".
1960
- */
1961
- private ackAndAdvanceCursor;
1962
- /**
1963
- * Resolve the value to publish for a `data`/`delta` frame.
1964
- *
1965
- * A `data` frame is an authoritative snapshot (the server re-execution path)
1966
- * and always replaces the cached value wholesale. A `delta` frame carrying a
1967
- * structured `MutationDelta` (the `broadcastDelta` row-change path) is
1968
- * merged incrementally into the cached list — preserving order, no dup/loss —
1969
- * so each subscription (including every paginated page) updates by delta
1970
- * rather than a full re-send. We fall back to full replacement when the
1971
- * delta isn't a recognisable row change, when there's no cached value yet,
1972
- * or when it can't be applied cleanly against the current cached shape.
1973
- */
1974
- private resolveDataPayload;
1975
- /** Route an inbound whisper to the topic's handlers on the originating shard. */
1976
- private dispatchWhisper;
1977
- /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
1978
- private notifyTokenExpired;
1979
- private handleCompleteMessage;
1980
- private unpersist;
1981
- /**
1982
- * Stable, non-reversible fingerprint of the current auth identity used to
1983
- * stamp queued offline writes. `null` (signed out) is its own identity and
1984
- * never matches a bearer-token fingerprint. The raw token is never stored;
1985
- * a length-prefixed FNV-1a hash is enough to detect an identity *change*
1986
- * without keeping the credential around in the queue map.
1987
- */
1988
- private identityFingerprint;
1989
- /**
1990
- * Drain every in-memory offline write and reject it because the auth
1991
- * identity changed. Durable entries are also dropped from persistence so a
1992
- * later `hydrate` can't resurrect another user's writes. Stamps are cleared
1993
- * alongside. Persisted entries restored without a live awaiter still get
1994
- * unpersisted here.
1995
- */
1996
- private rejectQueuedForIdentityChange;
1997
- /**
1998
- * Drop the durable read cache on an identity change so a cached value stamped
1999
- * under the previous identity can never hydrate into a new session. Clears
2000
- * the in-flight write batch and the not-yet-consumed hydrated entries too;
2001
- * the durable `clear()` is best-effort.
2002
- */
2003
- private clearQueryCacheForIdentityChange;
2004
- private flushOfflineQueue;
2005
- }
2006
- export { SyncWatermark as $, ArgsOf as A, BookmarkStorage as B, CachedQuery as C, DEFAULT_MAX_BUFFER as D, ServerMessage as E, FunctionReference as F, GlobalFacetResult as G, ServerPokeEndMessage as H, ServerPokePartMessage as I, ServerPokeStartMessage as J, ShardTrafficEntry as K, LunoraClient as L, MutationCallOptions as M, ShardTrafficResult as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, SubscriptionError as S, StorageListPage as T, User as U, StorageObject as V, StreamHandle as W, StreamIterable as X, SubscriptionCallback as Y, SubscriptionRegistry as Z, SubscriptionState as _, Unsubscribe as a, WorkflowInstanceAction as a0, WorkflowInstanceDetail as a1, WorkflowInstancePage as a2, WorkflowInstanceStatus as a3, WorkflowInstanceSummary as a4, WorkflowStepDetail as a5, createLocalStore as a6, createStream as a7, SubscriptionErrorCallback as b, PersistenceAdapter as c, ReconnectOptions as d, ClientMessage as e, ClientShapeSubscribeMessage as f, ClientShapeUnsubscribeMessage as g, ConnectionStatus as h, FunctionArgumentDescriptor as i, FunctionDescriptor as j, GlobalFacetValue as k, GlobalFilterClause as l, GlobalTableInfo as m, GlobalTablePage as n, LunoraClientOptions as o, OptimisticLocalStore as p, OptimisticUpdate as q, OutboxMutation as r, OutboxSink as s, PersistedMutation as t, RowOp as u, RpcEnvelope as v, RpcResponseBody as w, ScheduleRecord as x, SchedulerPoolStatus as y, SchedulerStatus as z };