@lunora/client 1.0.0-alpha.9 → 1.0.0-alpha.91

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