@lunora/client 1.0.0-alpha.11 → 1.0.0-alpha.110

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 (91) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +16 -3
  3. package/dist/auth/index.d.mts +36 -12
  4. package/dist/auth/index.d.ts +36 -12
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +884 -273
  7. package/dist/index.d.ts +884 -273
  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-D4FH_fjY.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-BuHVa8B0.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-BFdXRTFz.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-Chmnq4DL.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-BjenEm3t.mjs +1 -0
  41. package/dist/packem_shared/lunora-client.d-CGR-MObo.d.ts +4007 -0
  42. package/dist/packem_shared/lunora-client.d-qVBwKXE1.d.mts +4007 -0
  43. package/dist/packem_shared/offline-queue-DSCpAxOp.mjs +1 -0
  44. package/dist/packem_shared/preload.d-0j8xgrYf.d.mts +21 -0
  45. package/dist/packem_shared/preload.d-DTpiMCut.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-6J-4BGWK.mjs +0 -2722
  69. package/dist/packem_shared/OfflineQueue-BI0FNNvc.mjs +0 -1
  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-DlFjWtOm.mjs +0 -117
  76. package/dist/packem_shared/createInMemoryQueryCache-4AkTV38-.mjs +0 -150
  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-CtklXrs2.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-Dm1BYq19.d.mts +0 -2206
  86. package/dist/packem_shared/lunora-client.d-Dm1BYq19.d.ts +0 -2206
  87. package/dist/packem_shared/offline-queue-7Wc4onA0.mjs +0 -164
  88. package/dist/packem_shared/preload.d-BfWzGJWV.d.mts +0 -20
  89. package/dist/packem_shared/preload.d-Sp_Ef-_u.d.ts +0 -20
  90. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  91. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
@@ -1,2722 +0,0 @@
1
- import { S as SubscriptionRegistry, s as stableStringify } from './subscription-C1Jy7HiF.mjs';
2
- import createInMemoryBookmarkStorage from './createInMemoryBookmarkStorage-BoN7a7TH.mjs';
3
- import { isMutationDelta, applyDelta } from './applyDelta-4jFGTPA3.mjs';
4
- import { a as applyOptimisticLayer, d as dropConfirmedLayers, n as notifySubscription, f as foldOptimistic, c as createLocalStore } from './local-store-BNgN3Dw3.mjs';
5
- import { O as OfflineQueue, n as nextId, i as isStaleVersion, r as reportPersistenceError } from './offline-queue-7Wc4onA0.mjs';
6
- import { resolvePersistenceAdapter } from './createInMemoryPersistence-DlFjWtOm.mjs';
7
- import { resolveQueryCacheAdapter, queryCacheKey } from './createInMemoryQueryCache-4AkTV38-.mjs';
8
- import { createReconnect } from './createReconnect-Di_-oHH7.mjs';
9
- import { createStream } from './DEFAULT_MAX_BUFFER-BDkqO5PW.mjs';
10
-
11
- class Listeners {
12
- listeners = /* @__PURE__ */ new Set();
13
- add(listener) {
14
- this.listeners.add(listener);
15
- return () => {
16
- this.listeners.delete(listener);
17
- };
18
- }
19
- // The conditional rest tuple makes `emit()` argument-free for a
20
- // `Listeners<void>` and one-argument for every other payload.
21
- // eslint-disable-next-line @typescript-eslint/no-invalid-void-type -- `[T] extends [void]` is the discriminant for the payload-free overload, not a value-position void
22
- emit(...args) {
23
- const [value] = args;
24
- for (const listener of this.listeners) {
25
- try {
26
- listener(value);
27
- } catch {
28
- }
29
- }
30
- }
31
- clear() {
32
- this.listeners.clear();
33
- }
34
- }
35
-
36
- const RPC_PATH = "/_lunora/rpc";
37
- const WS_PATH = "/_lunora/ws";
38
- const bucketQuery = (bucket) => bucket === void 0 || bucket === "" ? "" : `&bucket=${encodeURIComponent(bucket)}`;
39
- const rollbackOptimistic = (optimisticRollbacks) => {
40
- for (let index = optimisticRollbacks.length - 1; index >= 0; index -= 1) {
41
- optimisticRollbacks[index]?.();
42
- }
43
- };
44
- const applyRowOpsToView = (rows, ops) => {
45
- for (const op of ops) {
46
- if (op.op === "delete") {
47
- rows.delete(op.key);
48
- } else if (op.value !== void 0) {
49
- rows.set(op.key, op.value);
50
- }
51
- }
52
- };
53
- const WS_KEEPALIVE_PING = "lunora-ping";
54
- const DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
55
- const DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
56
- const QUERY_CACHE_DEBOUNCE_MS = 250;
57
- const MAX_PENDING_STREAMS = 64;
58
- const SHARD_TRAFFIC_PATH = "/_lunora/admin/shard-traffic";
59
- const SCHEDULED_PATH = "/_lunora/admin/scheduled";
60
- const SCHEDULED_STATUS_PATH = "/_lunora/admin/scheduled/status";
61
- const SCHEDULED_WS_PATH = "/_lunora/admin/scheduled/ws";
62
- const SCHEDULED_CANCEL_PATH = "/_lunora/admin/scheduled/cancel";
63
- const SCHEDULED_DEAD_PATH = "/_lunora/admin/scheduled/dead";
64
- const SCHEDULED_DEAD_RETRY_PATH = "/_lunora/admin/scheduled/dead/retry";
65
- const SCHEDULED_DEAD_CANCEL_PATH = "/_lunora/admin/scheduled/dead/cancel";
66
- const WORKFLOWS_INSTANCES_PATH = "/_lunora/admin/workflows/instances";
67
- const WORKFLOWS_INSTANCE_PATH = "/_lunora/admin/workflows/instance";
68
- const WORKFLOWS_STATUS_PATH = "/_lunora/admin/workflows/status";
69
- const STORAGE_PATH = "/_lunora/admin/storage";
70
- const STORAGE_URL_PATH = "/_lunora/admin/storage/url";
71
- const STORAGE_BUCKETS_PATH = "/_lunora/admin/storage/buckets";
72
- const FUNCTIONS_PATH = "/_lunora/admin/functions";
73
- const CRON_JOBS_PATH = "/_lunora/admin/cron-jobs";
74
- const CRON_JOBS_RUN_PATH = "/_lunora/admin/cron-jobs/run";
75
- const OPENAPI_PATH = "/_lunora/admin/openapi";
76
- const OPENRPC_PATH = "/_lunora/admin/openrpc";
77
- const GLOBAL_TABLES_PATH = "/_lunora/admin/global/tables";
78
- const GLOBAL_TABLE_PATH = "/_lunora/admin/global/table";
79
- const GLOBAL_FACET_PATH = "/_lunora/admin/global/facet";
80
- const VECTOR_INDEXES_PATH = "/_lunora/admin/vector/indexes";
81
- const VECTOR_QUERY_PATH = "/_lunora/admin/vector/query";
82
- const AUTH_USERS_PATH = "/_lunora/admin/auth/users";
83
- const AUTH_SESSIONS_PATH = "/_lunora/admin/auth/sessions";
84
- const AUTH_CREATE_USER_PATH = "/_lunora/admin/auth/users/create";
85
- const AUTH_SET_ROLE_PATH = "/_lunora/admin/auth/users/role";
86
- const AUTH_BAN_PATH = "/_lunora/admin/auth/users/ban";
87
- const AUTH_UNBAN_PATH = "/_lunora/admin/auth/users/unban";
88
- const AUTH_SET_PASSWORD_PATH = "/_lunora/admin/auth/users/password";
89
- const AUTH_REMOVE_USER_PATH = "/_lunora/admin/auth/users/remove";
90
- const AUTH_IMPERSONATE_PATH = "/_lunora/admin/auth/users/impersonate";
91
- const AUTH_REVOKE_SESSION_PATH = "/_lunora/admin/auth/sessions/revoke";
92
- const AUTH_REVOKE_SESSIONS_PATH = "/_lunora/admin/auth/sessions/revoke-all";
93
- const AUTH_CAPABILITIES_PATH = "/_lunora/admin/auth/capabilities";
94
- const AUTH_UPDATE_USER_PATH = "/_lunora/admin/auth/users/update";
95
- const AUTH_ACCOUNTS_PATH = "/_lunora/admin/auth/accounts";
96
- const AUTH_UNLINK_ACCOUNT_PATH = "/_lunora/admin/auth/accounts/unlink";
97
- const AUTH_PASSKEYS_PATH = "/_lunora/admin/auth/passkeys";
98
- const AUTH_DELETE_PASSKEY_PATH = "/_lunora/admin/auth/passkeys/delete";
99
- const AUTH_DISABLE_2FA_PATH = "/_lunora/admin/auth/two-factor/disable";
100
- const AUTH_ORGS_PATH = "/_lunora/admin/auth/organizations";
101
- const AUTH_ORG_MEMBERS_PATH = "/_lunora/admin/auth/organizations/members";
102
- const AUTH_ORG_INVITATIONS_PATH = "/_lunora/admin/auth/organizations/invitations";
103
- const AUTH_REMOVE_MEMBER_PATH = "/_lunora/admin/auth/organizations/members/remove";
104
- const AUTH_CANCEL_INVITATION_PATH = "/_lunora/admin/auth/organizations/invitations/cancel";
105
- const DEFAULT_AUTH_BASE_PATH = "/api/auth";
106
- const GET_SESSION_PATH = "/get-session";
107
- const deriveWsUrl = (url) => {
108
- if (url.startsWith("https://")) {
109
- return `wss://${url.slice("https://".length)}`;
110
- }
111
- if (url.startsWith("http://")) {
112
- return `ws://${url.slice("http://".length)}`;
113
- }
114
- return url;
115
- };
116
- const joinUrl = (base, path) => {
117
- const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;
118
- return `${trimmed}${path}`;
119
- };
120
- const withQuery = (path, params) => {
121
- const search = new URLSearchParams();
122
- for (const [key, value] of Object.entries(params)) {
123
- if (value !== void 0 && value !== "") {
124
- search.set(key, String(value));
125
- }
126
- }
127
- const query = search.toString();
128
- return query === "" ? path : `${path}?${query}`;
129
- };
130
- const connectionKey = (shardKey) => shardKey ?? "";
131
- const buildStreamError = (message) => {
132
- const errorEnvelope = message.error;
133
- const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
134
- const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
135
- const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "stream error";
136
- return Object.assign(new Error(messageText), code === void 0 ? void 0 : { code });
137
- };
138
- const buildSubscriptionError = (message) => {
139
- const errorEnvelope = message.error;
140
- const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
141
- const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
142
- const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "subscription error";
143
- return { message: messageText, ...code === void 0 ? {} : { code } };
144
- };
145
- const fanSubscriptionError = (callbacks, error) => {
146
- for (const errorCallback of callbacks) {
147
- try {
148
- errorCallback(error);
149
- } catch {
150
- }
151
- }
152
- };
153
- const sharedDecoder = new TextDecoder();
154
- const decodeServerFrame = (raw) => {
155
- if (typeof raw === "string") {
156
- return raw;
157
- }
158
- if (raw instanceof ArrayBuffer) {
159
- return sharedDecoder.decode(raw);
160
- }
161
- return void 0;
162
- };
163
- const sendOn = (conn, message) => {
164
- if (!conn.socket || conn.wsState !== "open") {
165
- return false;
166
- }
167
- try {
168
- conn.socket.send(JSON.stringify(message));
169
- return true;
170
- } catch {
171
- return false;
172
- }
173
- };
174
- class LunoraClient {
175
- /** 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. */
176
- static MAX_POKE_BUFFERS = 256;
177
- url;
178
- wsUrl;
179
- wsToken;
180
- /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
181
- authBasePath;
182
- fetchImpl;
183
- WebSocketImpl;
184
- bookmark;
185
- reconnectOptions;
186
- /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
187
- connectTimeoutMs;
188
- /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
189
- heartbeatIntervalMs;
190
- offlineQueue;
191
- /**
192
- * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
193
- * set, offline writes are delegated here and the built-in {@link OfflineQueue}
194
- * is bypassed, so a db app has exactly one durable write path.
195
- */
196
- outbox;
197
- /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
198
- clientId;
199
- /**
200
- * Highest custom-mutator watermark the server has echoed for this client,
201
- * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
202
- * `__client_watermark` per shard. `callMutator` bumps it from every
203
- * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
204
- * it so a reload (which resets the in-memory counter) never reissues a stale
205
- * sequence the server would silently swallow as a replay.
206
- */
207
- clientWatermarks = /* @__PURE__ */ new Map();
208
- /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
209
- outboxMutationCounter = 0;
210
- onPersistenceError;
211
- persistence;
212
- /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
213
- persistenceVersion;
214
- /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
215
- outboxLeaderRelease;
216
- /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
217
- queryCache;
218
- /**
219
- * Values restored from the `queryCache` at construction, keyed by the
220
- * read-cache key, awaiting the `subscribe()` that will consume them. A
221
- * key is consumed (deleted) the first time its subscription is created, so
222
- * the cache only ever seeds the initial value — live frames take over after.
223
- */
224
- hydratedQueryCache = /* @__PURE__ */ new Map();
225
- /**
226
- * Coalesced read-cache writes: the latest value per key, flushed to
227
- * the `queryCache` on a short debounce so a burst of deltas persists once.
228
- */
229
- pendingCacheWrites = /* @__PURE__ */ new Map();
230
- cacheFlushTimer;
231
- subscriptions = new SubscriptionRegistry();
232
- /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
233
- connections = /* @__PURE__ */ new Map();
234
- /** Default `connect`-envelope context applied to a shard with no explicit override. */
235
- defaultConnectionContext;
236
- /**
237
- * Per-shard `connect`-envelope context registered via `setConnectionContext`
238
- * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
239
- * on every socket open so it replays across reconnects, and forwarded to the
240
- * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
241
- * imperative (last-writer-wins) override; refcounted holders registered via
242
- * `acquireConnectionContext` live in `connectionContextHolders` and take
243
- * precedence — see `effectiveConnectionContext`.
244
- */
245
- connectionContexts = /* @__PURE__ */ new Map();
246
- /**
247
- * Per-shard stack of refcounted connection-context holders (keyed by
248
- * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
249
- * is an opaque token carrying its `context`; the most-recently acquired
250
- * holder wins (last-writer-wins among live holders), and the context is only
251
- * cleared for a shard once its last holder releases — so two concurrently
252
- * mounted presence hooks on the same shard can't stomp each other's context
253
- * on cleanup. A holder is identified by reference identity so a release
254
- * removes exactly the right one regardless of stack position.
255
- */
256
- connectionContextHolders = /* @__PURE__ */ new Map();
257
- // `null` is the public sentinel for "signed out" across getAuthToken /
258
- // setAuthToken / onAuthTokenChange — part of the exported API contract.
259
- // eslint-disable-next-line unicorn/no-null -- public auth-token contract sentinel
260
- authToken = null;
261
- /**
262
- * Optional STABLE identity subject (a user id), the basis of the offline-queue
263
- * identity stamp when supplied. Keeps a same-user token *refresh* from looking
264
- * like an identity change (which would discard queued writes). `undefined` =
265
- * not supplied, so identity falls back to a hash of the raw token. See
266
- * `setAuthToken` / `identityFingerprint`.
267
- */
268
- authSubject = void 0;
269
- /**
270
- * Identity stamp recorded against each queued offline mutation, keyed by
271
- * the queue-assigned mutation id. Captured at enqueue from the auth token
272
- * in effect at the time, and re-checked at flush so a queued write can
273
- * never replay under a different identity than the one that issued it.
274
- * See `identityFingerprint` for the fingerprint shape.
275
- */
276
- queuedIdentities = /* @__PURE__ */ new Map();
277
- closed = false;
278
- /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
279
- authTokenListeners = new Listeners();
280
- /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
281
- statusListeners = new Listeners();
282
- /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
283
- tokenExpiredListeners = new Listeners();
284
- /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
285
- mutationSettledListeners = new Listeners();
286
- /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
287
- pendingChangeListeners = new Listeners();
288
- /**
289
- * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
290
- * of callbacks. Membership doubles as the resubscribe set replayed on every
291
- * (re)connect so a topic survives a socket bounce.
292
- */
293
- whisperHandlers = /* @__PURE__ */ new Map();
294
- /** Last status broadcast, so we only notify listeners on an actual change. */
295
- lastStatus = "idle";
296
- nextSubId = 0;
297
- nextStreamId = 0;
298
- /**
299
- * In-flight client-side stream readers, keyed by the stream id sent on the
300
- * wire. The handle drives the underlying iterator queue and `shardKey`
301
- * tells us which socket to push the cancel frame onto when the consumer
302
- * calls `.cancel()` or the iterator is garbage-collected.
303
- */
304
- streams = /* @__PURE__ */ new Map();
305
- /** Live shape subscriptions (partial replication), keyed by their wire id. */
306
- shapeSubscriptions = /* @__PURE__ */ new Map();
307
- /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
308
- pokeBuffers = /* @__PURE__ */ new Map();
309
- nextShapeId = 0;
310
- constructor(options) {
311
- this.url = options.url;
312
- this.wsUrl = options.wsUrl ?? joinUrl(deriveWsUrl(options.url), WS_PATH);
313
- this.wsToken = options.wsToken;
314
- const authBase = options.authBasePath ?? DEFAULT_AUTH_BASE_PATH;
315
- this.authBasePath = authBase.endsWith("/") ? authBase.slice(0, -1) : authBase;
316
- this.fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch.bind(globalThis) : void 0);
317
- this.WebSocketImpl = options.WebSocket ?? (typeof WebSocket === "function" ? WebSocket : void 0);
318
- this.bookmark = options.bookmarkStorage ?? createInMemoryBookmarkStorage();
319
- this.reconnectOptions = options.reconnect;
320
- this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
321
- this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
322
- this.defaultConnectionContext = options.connectionContext;
323
- this.persistence = resolvePersistenceAdapter(options.persistence, options.outbox === void 0);
324
- this.persistenceVersion = options.persistenceVersion;
325
- this.queryCache = resolveQueryCacheAdapter(options.queryCache);
326
- this.onPersistenceError = options.offlineQueue?.onPersistenceError;
327
- this.offlineQueue = new OfflineQueue(options.offlineQueue, {
328
- onEvict: (entry, error) => {
329
- this.emitItemSettled(entry, "rejected", error);
330
- },
331
- onSizeChange: (size) => {
332
- this.pendingChangeListeners.emit(size);
333
- },
334
- persistence: this.persistence,
335
- version: options.persistenceVersion
336
- });
337
- this.outbox = options.outbox;
338
- this.clientId = options.clientId ?? `client-${nextId()}`;
339
- if (this.persistence) {
340
- queueMicrotask(() => {
341
- this.hydrateAsOutboxLeader();
342
- });
343
- }
344
- if (this.queryCache) {
345
- queueMicrotask(() => {
346
- this.hydrateQueryCache().catch(() => void 0);
347
- });
348
- }
349
- }
350
- // --- Auth helpers -------------------------------------------------------
351
- /**
352
- * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
353
- * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
354
- * sync across all mounted instances.
355
- *
356
- * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
357
- * it instead of the token bytes, so a token *refresh* (same user, new JWT)
358
- * doesn't read as an identity change and discard queued writes. The subject is
359
- * **sticky**: a later call that omits it (or passes `undefined`) keeps the
360
- * established subject — so `setAuthToken(refreshedToken)` after a prior
361
- * `setAuthToken(token, user.id)` retains the identity. Pass `null` to clear it
362
- * (an explicit sign-out). Establishing the subject for the first time on an
363
- * UNCHANGED token (e.g. the user id resolves a tick after the token was set)
364
- * re-stamps any in-flight queued writes rather than dropping them — same
365
- * credential, just a more stable label. A real user switch (the token AND
366
- * subject both change) still drops the previous user's writes.
367
- *
368
- * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
369
- * time and lives in the URL. To refresh live WS auth, call
370
- * {@link setWsToken} explicitly, which closes existing shard sockets to
371
- * force a reconnect with the new credential.
372
- */
373
- setAuthToken(token, subject) {
374
- const tokenChanged = this.authToken !== token;
375
- const previousIdentity = this.identityFingerprint();
376
- this.authToken = token;
377
- if (subject !== void 0) {
378
- this.authSubject = subject;
379
- }
380
- const newIdentity = this.identityFingerprint();
381
- if (newIdentity !== previousIdentity) {
382
- if (tokenChanged) {
383
- this.rejectQueuedForIdentityChange();
384
- } else {
385
- this.restampQueuedIdentity(previousIdentity, newIdentity);
386
- }
387
- }
388
- if (tokenChanged) {
389
- this.authTokenListeners.emit(token);
390
- }
391
- }
392
- getAuthToken() {
393
- return this.authToken;
394
- }
395
- /**
396
- * The current identity fingerprint (the same stamp queued offline writes
397
- * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
398
- * owns its own at-least-once replay outside the built-in `OfflineQueue` —
399
- * can drop a persisted write whose captured `identity` no longer matches the
400
- * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
401
- */
402
- currentIdentity() {
403
- return this.identityFingerprint();
404
- }
405
- /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
406
- clientIdentifier() {
407
- return this.clientId;
408
- }
409
- /**
410
- * The highest custom-mutator watermark the server has echoed for this client
411
- * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
412
- * its `clientSeq` generator from this so a reload never reissues a sequence
413
- * the server has already applied (which it would swallow as a replay, silently
414
- * dropping the write).
415
- */
416
- confirmedMutationWatermark(shardKey) {
417
- return this.clientWatermarks.get(shardKey ?? "") ?? 0;
418
- }
419
- /**
420
- * Push a custom mutator to its authoritative server impl over the watermark
421
- * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
422
- * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
423
- * client's `__client_watermark`.
424
- *
425
- * Returns the server `result` plus `applied`: `true` when the DO ran this push
426
- * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
427
- * was at or below the stored watermark — e.g. a stale sequence after a reload).
428
- * A `false` verdict tells the caller to reissue above the now-known watermark
429
- * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
430
- * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
431
- *
432
- * This is the online transport for `@lunora/db`'s client-mutator runtime; the
433
- * optimistic overlay + durable-outbox concerns live in that runtime, not here.
434
- */
435
- async callMutator(functionPath, args, options) {
436
- const clientSeq = options?.clientSeq;
437
- if (clientSeq !== void 0 && (!Number.isInteger(clientSeq) || clientSeq <= 0)) {
438
- throw new Error(`callMutator: clientSeq must be a positive integer, got ${String(clientSeq)}`);
439
- }
440
- const bucket = options?.shardKey ?? "";
441
- let ackWatermark;
442
- const result = await this.rpc(functionPath, args, options?.shardKey, {
443
- captureBookmark: true,
444
- clientId: this.clientId,
445
- clientSeq,
446
- onMutationAck: (lastMutationId) => {
447
- ackWatermark = lastMutationId;
448
- }
449
- });
450
- if (ackWatermark !== void 0 && ackWatermark > (this.clientWatermarks.get(bucket) ?? 0)) {
451
- this.clientWatermarks.set(bucket, ackWatermark);
452
- }
453
- const applied = ackWatermark === void 0 || ackWatermark === clientSeq;
454
- return { applied, result };
455
- }
456
- /**
457
- * Subscribe to auth-token changes. Returns an unsubscribe function. The
458
- * listener is NOT invoked on registration — use {@link getAuthToken} for
459
- * the current value.
460
- */
461
- onAuthTokenChange(listener) {
462
- return this.authTokenListeners.add(listener);
463
- }
464
- /**
465
- * Fetch the currently authenticated user from better-auth's `get-session`
466
- * endpoint, returning the `user` record or `null` when signed out. Sends
467
- * the stored bearer token (if any) and `credentials: "include"` so a
468
- * cookie-session is also honoured. A network/parse failure or a non-OK
469
- * response resolves to `null` rather than throwing — callers treat "couldn't
470
- * resolve identity" as "signed out".
471
- *
472
- * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
473
- * the token changes (that's what `@lunora/react`'s `useAuth` does).
474
- */
475
- async getCurrentUser() {
476
- if (this.closed || !this.fetchImpl) {
477
- return null;
478
- }
479
- const headers = {};
480
- if (this.authToken) {
481
- headers["authorization"] = `Bearer ${this.authToken}`;
482
- }
483
- try {
484
- const response = await this.fetchImpl(joinUrl(this.url, `${this.authBasePath}${GET_SESSION_PATH}`), {
485
- credentials: "include",
486
- headers,
487
- method: "GET"
488
- });
489
- if (!response.ok) {
490
- return null;
491
- }
492
- const body = await response.json();
493
- return body?.user ?? null;
494
- } catch {
495
- return null;
496
- }
497
- }
498
- /**
499
- * Replace the token appended to WS upgrade URLs as `?token=…` and close
500
- * every open shard socket so the reconnect picks up the new value. Call
501
- * this whenever the user's WS credential changes (rotating the admin token
502
- * in the studio, switching workspaces, etc.). Bearer tokens for HTTP
503
- * RPC are independent — see {@link setAuthToken}.
504
- */
505
- setWsToken(token) {
506
- if (this.wsToken === token) {
507
- return;
508
- }
509
- this.wsToken = token;
510
- for (const conn of this.connections.values()) {
511
- if (conn.socket) {
512
- try {
513
- conn.socket.close();
514
- } catch {
515
- }
516
- }
517
- }
518
- }
519
- /**
520
- * Register (or clear, with `undefined`) the app context sent in the `connect`
521
- * envelope for a shard's socket, overriding the client-wide
522
- * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
523
- * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
524
- * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
525
- * presence row is removed the instant the socket drops, with no TTL lag.
526
- *
527
- * Stored per shard and replayed on every (re)connect. When a socket for the
528
- * shard is already open, a fresh `connect` envelope is sent immediately so the
529
- * server sees the new context without waiting for a reconnect.
530
- */
531
- setConnectionContext(context, options = {}) {
532
- const key = connectionKey(options.shardKey);
533
- if (context === void 0) {
534
- this.connectionContexts.delete(key);
535
- } else {
536
- this.connectionContexts.set(key, context);
537
- }
538
- this.refreshConnectionContext(key);
539
- }
540
- /**
541
- * Refcounted variant of {@link setConnectionContext}: register a connection
542
- * `context` for a shard and get back a release function. Unlike the imperative
543
- * setter, the context is only cleared once the *last* acquired holder releases
544
- * it — so two components (e.g. two mounted `usePresence` hooks) on the same
545
- * shard no longer clobber each other's context when one of them unmounts. The
546
- * most-recently acquired live holder wins (last-writer-wins), and releasing
547
- * the top holder falls back to the previous one rather than clearing.
548
- *
549
- * With a single holder the behaviour is identical to a
550
- * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
551
- * Releasing more than once is a no-op (the holder is matched by reference, so
552
- * a double release can't drop a different holder).
553
- */
554
- acquireConnectionContext(context, options = {}) {
555
- const key = connectionKey(options.shardKey);
556
- const holder = { context };
557
- const holders = this.connectionContextHolders.get(key);
558
- if (holders) {
559
- holders.push(holder);
560
- } else {
561
- this.connectionContextHolders.set(key, [holder]);
562
- }
563
- this.refreshConnectionContext(key);
564
- let released = false;
565
- return () => {
566
- if (released) {
567
- return;
568
- }
569
- released = true;
570
- const live = this.connectionContextHolders.get(key);
571
- if (!live) {
572
- return;
573
- }
574
- const index = live.indexOf(holder);
575
- if (index !== -1) {
576
- live.splice(index, 1);
577
- }
578
- if (live.length === 0) {
579
- this.connectionContextHolders.delete(key);
580
- }
581
- this.refreshConnectionContext(key);
582
- };
583
- }
584
- // --- Whispering ---------------------------------------------------------
585
- /**
586
- * Join a whisper `topic` and receive every ephemeral message other members
587
- * broadcast to it on the same shard (typing indicators, live cursors,
588
- * presence pings). Whispers never touch the server's durable state — there's
589
- * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
590
- * is left on the server once its last local handler unsubscribes.
591
- *
592
- * `handler` receives the raw `data` and the sender's verified `from` user id
593
- * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
594
- * (the default shard when omitted) — use the same shard you target with the
595
- * matching queries/mutations so members land on the same Durable Object.
596
- *
597
- * Security: whisper topics are NOT access-controlled beyond the shard
598
- * boundary — any client that can open a socket to the shard can join, read,
599
- * and inject on any topic name. `from` is server-stamped and unforgeable, but
600
- * do not put data on a whisper topic that some shard members shouldn't see,
601
- * and don't trust a whisper's `data` as authorization. Use a query/mutation
602
- * (with RLS) for anything privileged; whispers are for transient awareness.
603
- */
604
- whisperSubscribe(topic, handler, options = {}) {
605
- const key = connectionKey(options.shardKey);
606
- let byTopic = this.whisperHandlers.get(key);
607
- if (!byTopic) {
608
- byTopic = /* @__PURE__ */ new Map();
609
- this.whisperHandlers.set(key, byTopic);
610
- }
611
- let handlers = byTopic.get(topic);
612
- const first = handlers === void 0;
613
- if (!handlers) {
614
- handlers = /* @__PURE__ */ new Set();
615
- byTopic.set(topic, handlers);
616
- }
617
- handlers.add(handler);
618
- this.ensureSocket(options.shardKey);
619
- if (first) {
620
- const conn = this.getConnection(options.shardKey);
621
- if (conn) {
622
- sendOn(conn, { topic, type: "whisper_subscribe" });
623
- }
624
- }
625
- return () => {
626
- const stillByTopic = this.whisperHandlers.get(key);
627
- const stillHandlers = stillByTopic?.get(topic);
628
- if (!stillHandlers?.delete(handler) || stillHandlers.size > 0) {
629
- return;
630
- }
631
- stillByTopic?.delete(topic);
632
- if (stillByTopic?.size === 0) {
633
- this.whisperHandlers.delete(key);
634
- }
635
- const conn = this.getConnection(options.shardKey);
636
- if (conn) {
637
- sendOn(conn, { topic, type: "whisper_unsubscribe" });
638
- }
639
- };
640
- }
641
- /**
642
- * Broadcast an ephemeral `data` payload to the other members of a whisper
643
- * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
644
- * dropped when the shard socket isn't open (whispers are transient, never
645
- * queued), and the server silently drops it if the sender exceeds its
646
- * whisper rate budget. The sender never receives its own whisper. Omitting
647
- * `data` delivers JSON `null` to receivers (not `undefined`).
648
- */
649
- whisper(topic, data, options = {}) {
650
- this.ensureSocket(options.shardKey);
651
- const conn = this.getConnection(options.shardKey);
652
- if (conn) {
653
- sendOn(conn, { data, topic, type: "whisper" });
654
- }
655
- }
656
- /**
657
- * Subscribe to token-expiry events: invoked whenever the server drops a
658
- * shard socket because the connection's credential lapsed (close code
659
- * `4001`). The client already reconnects automatically (re-resolving
660
- * identity from the cookie/token in effect); use this to refresh a
661
- * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
662
- * with a freshly minted one. Returns an unsubscribe function.
663
- */
664
- onTokenExpired(listener) {
665
- return this.tokenExpiredListeners.add(listener);
666
- }
667
- // --- Connection status --------------------------------------------------
668
- /**
669
- * Current aggregate live-socket status across all shard connections. See
670
- * {@link ConnectionStatus}.
671
- */
672
- connectionStatus() {
673
- return this.computeStatus();
674
- }
675
- /**
676
- * Subscribe to aggregate connection-status changes. Invokes `listener`
677
- * immediately with the current status, then on every transition. Returns an
678
- * unsubscribe function.
679
- */
680
- onConnectionStatus(listener) {
681
- const unsubscribe = this.statusListeners.add(listener);
682
- listener(this.computeStatus());
683
- return unsubscribe;
684
- }
685
- /**
686
- * Number of offline writes waiting in the built-in queue to be sent — the
687
- * depth for a "N changes waiting to sync" indicator. Counts writes that are
688
- * queued (offline / mid-reconnect), not ones already in flight on the wire.
689
- * A `@lunora/db` app whose writes ride the unified outbox should read
690
- * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
691
- */
692
- pendingCount() {
693
- return this.offlineQueue.size;
694
- }
695
- /**
696
- * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
697
- * with the current count, then whenever the queue depth changes (a write is
698
- * enqueued, flushed, or discarded). Returns an unsubscribe function.
699
- */
700
- onPendingChange(listener) {
701
- const unsubscribe = this.pendingChangeListeners.add(listener);
702
- listener(this.offlineQueue.size);
703
- return unsubscribe;
704
- }
705
- /**
706
- * Subscribe to terminal verdicts for offline-queued mutations. The listener
707
- * fires once per queued write that commits or is rejected — including a write
708
- * restored from durable storage after a reload, whose original `mutation()`
709
- * Promise no longer exists (`hadAwaiter: false`), and a write the queue
710
- * evicts on overflow or discards on an identity change. This is the durable
711
- * channel for surfacing a rolled-back optimistic write to the UI; an online
712
- * mutation that never queued still surfaces through the Promise `mutation()`
713
- * returns. The listener is NOT invoked on registration. Returns an
714
- * unsubscribe function. See {@link MutationSettledEvent}.
715
- */
716
- onMutationSettled(listener) {
717
- return this.mutationSettledListeners.add(listener);
718
- }
719
- // --- RPC ---------------------------------------------------------------
720
- async query(function_, args, options = {}) {
721
- if (this.closed) {
722
- throw new Error("LunoraClient is closed");
723
- }
724
- return await this.rpc(function_.__lunoraRef, args, options.shardKey, { attachBookmark: true });
725
- }
726
- /**
727
- * Invoke a mutation. Errors propagate as rejections.
728
- *
729
- * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
730
- * only when the targeted shard's socket was open at least once already
731
- * (`wasEverConnected`), so the registry / resubscribe handshake has run.
732
- * Mutations issued before the very first WS connect to a shard fail fast.
733
- * Opt into queueing-before-first-connect via
734
- * `OfflineQueueOptions.queueBeforeFirstConnect`.
735
- */
736
- async mutation(function_, args, options = {}) {
737
- if (this.closed) {
738
- throw new Error("LunoraClient is closed");
739
- }
740
- const argsRecord = args;
741
- const mutationId = options.mutationId ?? nextId();
742
- const { confirms: optimisticConfirms, rollbacks: optimisticRollbacks } = this.applyOptimisticUpdates(
743
- function_.__lunoraRef,
744
- argsRecord,
745
- options.shardKey,
746
- options.optimistic
747
- );
748
- if (options.optimisticUpdate) {
749
- this.applyOptimisticUpdate(options.optimisticUpdate, args, options.shardKey, optimisticRollbacks, optimisticConfirms);
750
- }
751
- const conn = this.getConnection(options.shardKey);
752
- const wsState = conn?.wsState ?? "idle";
753
- const hasSocket = conn?.socket !== void 0;
754
- const wasEverConnected = conn?.wasEverConnected ?? false;
755
- const { queueBeforeFirstConnect } = this.offlineQueue;
756
- const connectedGate = wasEverConnected || queueBeforeFirstConnect;
757
- const shouldQueueOffline = this.WebSocketImpl !== void 0 && connectedGate;
758
- const midReconnect = wsState === "connecting" && connectedGate;
759
- if (wsState !== "open" && !hasSocket && shouldQueueOffline || midReconnect) {
760
- return this.enqueueOfflineMutation(function_, argsRecord, options.shardKey, mutationId, optimisticRollbacks, optimisticConfirms);
761
- }
762
- try {
763
- let commitCursor;
764
- const result = await this.rpc(function_.__lunoraRef, argsRecord, options.shardKey, {
765
- captureBookmark: true,
766
- mutationId,
767
- onCommitCursor: (cursor) => {
768
- commitCursor = cursor;
769
- }
770
- });
771
- for (const confirm of optimisticConfirms) {
772
- confirm(commitCursor);
773
- }
774
- return result;
775
- } catch (error) {
776
- rollbackOptimistic(optimisticRollbacks);
777
- throw error;
778
- }
779
- }
780
- async action(function_, args, options = {}) {
781
- if (this.closed) {
782
- throw new Error("LunoraClient is closed");
783
- }
784
- return await this.rpc(function_.__lunoraRef, args, options.shardKey);
785
- }
786
- // --- Advisor admin ------------------------------------------------------
787
- /**
788
- * Read the cross-shard request distribution for a `.shardBy(...)` table —
789
- * the feed the studio's `hot_shard` advisor lint consumes. Hits the
790
- * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
791
- * cheap per-shard `getMetrics` read out across every live shard and returns
792
- * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
793
- * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
794
- * and `adminToken`, and this client's auth token to match; defaults any
795
- * absent field so an older worker yields an empty-but-valid shape.
796
- */
797
- async shardTraffic(table) {
798
- if (this.closed) {
799
- throw new Error("LunoraClient is closed");
800
- }
801
- const body = await this.adminFetch(SHARD_TRAFFIC_PATH, "POST", { table });
802
- return { failed: body.failed ?? 0, ok: body.ok ?? 0, shards: body.shards ?? [] };
803
- }
804
- // --- Scheduler admin ----------------------------------------------------
805
- /**
806
- * List the functions queued via `runAfter` / `runAt`, soonest-due last
807
- * (the worker returns them in storage order). Hits the admin-gated
808
- * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
809
- * `schedulerDO` namespace and `adminToken`, and this client's auth token
810
- * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
811
- */
812
- async listScheduledJobs() {
813
- if (this.closed) {
814
- throw new Error("LunoraClient is closed");
815
- }
816
- const body = await this.adminFetch(SCHEDULED_PATH, "GET");
817
- return body.records ?? [];
818
- }
819
- /**
820
- * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
821
- * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
822
- * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
823
- * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
824
- * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
825
- * namespace + `adminToken` on the worker and a matching auth token here).
826
- * Defaults any absent field so an older worker still yields a valid shape.
827
- */
828
- async schedulerStatus() {
829
- if (this.closed) {
830
- throw new Error("LunoraClient is closed");
831
- }
832
- const body = await this.adminFetch(SCHEDULED_STATUS_PATH, "GET");
833
- return {
834
- backlog: body.backlog ?? 0,
835
- inFlight: body.inFlight ?? 0,
836
- pools: body.pools ?? []
837
- };
838
- }
839
- /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
840
- async cancelScheduledJob(id) {
841
- if (this.closed) {
842
- throw new Error("LunoraClient is closed");
843
- }
844
- const body = await this.adminFetch(SCHEDULED_CANCEL_PATH, "POST", { id });
845
- return { cancelled: body.cancelled === true };
846
- }
847
- /**
848
- * List the dead-letter jobs: schedules that exhausted their retry budget
849
- * and were parked instead of dropped. These never appear in
850
- * {@link listScheduledJobs} (their live header is gone), so this is the only
851
- * way the studio surfaces a permanently-failed job. Hits the admin-gated
852
- * `GET /_lunora/admin/scheduled/dead`; same preconditions as
853
- * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
854
- */
855
- async listDeadJobs() {
856
- if (this.closed) {
857
- throw new Error("LunoraClient is closed");
858
- }
859
- const body = await this.adminFetch(SCHEDULED_DEAD_PATH, "GET");
860
- return body.records ?? [];
861
- }
862
- /**
863
- * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
864
- * retry budget and fires on the next drain. Returns whether a parked record
865
- * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
866
- */
867
- async retryDeadJob(id) {
868
- if (this.closed) {
869
- throw new Error("LunoraClient is closed");
870
- }
871
- const body = await this.adminFetch(SCHEDULED_DEAD_RETRY_PATH, "POST", { id });
872
- return { retried: body.retried === true };
873
- }
874
- /**
875
- * Permanently drop a dead-letter job by id (the operator has decided not to
876
- * recover it). Returns whether a parked record was removed. Hits the
877
- * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
878
- */
879
- async removeDeadJob(id) {
880
- if (this.closed) {
881
- throw new Error("LunoraClient is closed");
882
- }
883
- const body = await this.adminFetch(SCHEDULED_DEAD_CANCEL_PATH, "POST", { id });
884
- return { removed: body.removed === true };
885
- }
886
- /**
887
- * List a workflow's instances via the admin Workflows proxy
888
- * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
889
- * the `Workflow` binding can't expose. Requires the worker to be built with a
890
- * `workflowsClient` (Cloudflare account id + API token). When one isn't
891
- * configured this does NOT reject: the proxy returns a `200 { configured:
892
- * false }` sentinel, so the result resolves with `configured === false` and an
893
- * empty `instances` list — callers should branch on that flag rather than
894
- * try/catch. (The instance-detail / status endpoints still reject with 501.)
895
- * `name` is the deployed workflow name.
896
- */
897
- async listWorkflowInstances(options) {
898
- if (this.closed) {
899
- throw new Error("LunoraClient is closed");
900
- }
901
- const query = new URLSearchParams({ name: options.name });
902
- if (options.status !== void 0) {
903
- query.set("status", options.status);
904
- }
905
- if (options.page !== void 0) {
906
- query.set("page", String(options.page));
907
- }
908
- if (options.perPage !== void 0) {
909
- query.set("perPage", String(options.perPage));
910
- }
911
- const body = await this.adminFetch(`${WORKFLOWS_INSTANCES_PATH}?${query.toString()}`, "GET");
912
- return {
913
- configured: body.configured,
914
- instances: body.instances ?? [],
915
- page: body.page ?? 1,
916
- perPage: body.perPage ?? options.perPage ?? 0,
917
- totalCount: body.totalCount
918
- };
919
- }
920
- /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
921
- async getWorkflowInstance(options) {
922
- if (this.closed) {
923
- throw new Error("LunoraClient is closed");
924
- }
925
- const query = new URLSearchParams({ id: options.id, name: options.name });
926
- const body = await this.adminFetch(`${WORKFLOWS_INSTANCE_PATH}?${query.toString()}`, "GET");
927
- return {
928
- createdOn: body.createdOn,
929
- endedOn: body.endedOn,
930
- error: body.error,
931
- id: body.id ?? options.id,
932
- output: body.output,
933
- params: body.params,
934
- startedOn: body.startedOn,
935
- status: body.status ?? "unknown",
936
- steps: body.steps ?? []
937
- };
938
- }
939
- /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
940
- async setWorkflowInstanceStatus(options) {
941
- if (this.closed) {
942
- throw new Error("LunoraClient is closed");
943
- }
944
- const body = await this.adminFetch(WORKFLOWS_STATUS_PATH, "POST", { action: options.action, id: options.id, name: options.name });
945
- return { status: body.status ?? "unknown" };
946
- }
947
- /**
948
- * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
949
- * WebSocket. `onJobs` fires with the full list on connect and on every
950
- * change (schedule / cancel / alarm-fire). Reconnects with the client's
951
- * configured backoff. Requires `wsToken` to be set to the admin token (the
952
- * browser can't send an `Authorization` header on a WS). Returns an
953
- * unsubscribe function that closes the socket and stops reconnecting.
954
- */
955
- subscribeScheduledJobs(onJobs) {
956
- if (this.closed) {
957
- throw new Error("LunoraClient is closed");
958
- }
959
- if (this.WebSocketImpl === void 0) {
960
- return () => void 0;
961
- }
962
- const base = joinUrl(deriveWsUrl(this.url), SCHEDULED_WS_PATH);
963
- const reconnect = createReconnect(this.reconnectOptions);
964
- let socket;
965
- let timer;
966
- let closed = false;
967
- const connect = () => {
968
- if (closed || this.WebSocketImpl === void 0) {
969
- return;
970
- }
971
- const url = this.wsToken === void 0 ? base : `${base}?token=${encodeURIComponent(this.wsToken)}`;
972
- socket = new this.WebSocketImpl(url);
973
- socket.addEventListener("open", () => {
974
- reconnect.reset();
975
- });
976
- socket.addEventListener("message", (event) => {
977
- try {
978
- const message = JSON.parse(typeof event.data === "string" ? event.data : "");
979
- if (message.type === "jobs" && Array.isArray(message.records)) {
980
- onJobs(message.records);
981
- }
982
- } catch {
983
- }
984
- });
985
- socket.addEventListener("close", () => {
986
- socket = void 0;
987
- if (!closed) {
988
- timer = setTimeout(connect, reconnect.next());
989
- }
990
- });
991
- socket.addEventListener("error", () => {
992
- });
993
- };
994
- connect();
995
- return () => {
996
- closed = true;
997
- if (timer !== void 0) {
998
- clearTimeout(timer);
999
- }
1000
- socket?.close();
1001
- };
1002
- }
1003
- // --- Functions admin ----------------------------------------------------
1004
- /**
1005
- * List the registered public functions (queries / mutations / actions) with
1006
- * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1007
- * the worker must be built with a `functions` registry and `adminToken`, and
1008
- * this client's auth token must match. Powers `@lunora/studio`'s function
1009
- * runner auto-discovery.
1010
- */
1011
- async listFunctions() {
1012
- if (this.closed) {
1013
- throw new Error("LunoraClient is closed");
1014
- }
1015
- const body = await this.adminFetch(FUNCTIONS_PATH, "GET");
1016
- return body.functions ?? [];
1017
- }
1018
- /**
1019
- * List the code-defined cron triggers (the `cronJobs()` map injected on the
1020
- * worker), each flattened to its firing `cron` expression. Hits the
1021
- * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1022
- * built with a `cronJobs` map and `adminToken`, and this client's auth token
1023
- * must match. These are static (Cloudflare exposes no runtime cron
1024
- * introspection), so the studio renders them read-only alongside the dynamic
1025
- * scheduler jobs.
1026
- */
1027
- async getCronJobs() {
1028
- if (this.closed) {
1029
- throw new Error("LunoraClient is closed");
1030
- }
1031
- const body = await this.adminFetch(CRON_JOBS_PATH, "GET");
1032
- return body.jobs ?? [];
1033
- }
1034
- /**
1035
- * Manually fire one code-defined cron job by name — the same dispatch the
1036
- * scheduled trigger runs (dispatch the function, or start the durable
1037
- * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1038
- * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1039
- * and this client's auth token must match. Resolves when the job has run (a
1040
- * function job's shard response is 2xx, or the workflow instance was created)
1041
- * and rejects with the dispatch error otherwise.
1042
- */
1043
- async runCronJob(name) {
1044
- if (this.closed) {
1045
- throw new Error("LunoraClient is closed");
1046
- }
1047
- const body = await this.adminFetch(CRON_JOBS_RUN_PATH, "POST", { name });
1048
- return { name: body.name ?? name, ran: body.ran === true };
1049
- }
1050
- /**
1051
- * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1052
- * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1053
- * `openApiSpec` and `adminToken`, and this client's auth token must match.
1054
- * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1055
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1056
- * document (no `paths`), so callers can render a "not configured" state.
1057
- */
1058
- async fetchOpenApi() {
1059
- if (this.closed) {
1060
- throw new Error("LunoraClient is closed");
1061
- }
1062
- return await this.adminFetch(OPENAPI_PATH, "GET");
1063
- }
1064
- /**
1065
- * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1066
- * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1067
- * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1068
- * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1069
- * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1070
- * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1071
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1072
- * document (no `methods`), so callers can render a "not configured" state.
1073
- */
1074
- async fetchOpenRpc() {
1075
- if (this.closed) {
1076
- throw new Error("LunoraClient is closed");
1077
- }
1078
- return await this.adminFetch(OPENRPC_PATH, "GET");
1079
- }
1080
- // --- Storage admin ------------------------------------------------------
1081
- /**
1082
- * List objects in the storage bucket, optionally under a `prefix` and from a
1083
- * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1084
- * endpoint — the worker must be built with a `storageList` function and
1085
- * `adminToken`, and this client's auth token must match. Powers
1086
- * `@lunora/studio`'s file browser.
1087
- */
1088
- async listStorageObjects(options = {}) {
1089
- if (this.closed) {
1090
- throw new Error("LunoraClient is closed");
1091
- }
1092
- const params = new URLSearchParams();
1093
- if (options.prefix !== void 0 && options.prefix !== "") {
1094
- params.set("prefix", options.prefix);
1095
- }
1096
- if (options.cursor !== void 0 && options.cursor !== "") {
1097
- params.set("cursor", options.cursor);
1098
- }
1099
- if (options.limit !== void 0) {
1100
- params.set("limit", String(options.limit));
1101
- }
1102
- if (options.bucket !== void 0 && options.bucket !== "") {
1103
- params.set("bucket", options.bucket);
1104
- }
1105
- const query = params.toString();
1106
- const path = query === "" ? STORAGE_PATH : `${STORAGE_PATH}?${query}`;
1107
- const body = await this.adminFetch(path, "GET");
1108
- return { cursor: body.cursor, objects: body.objects ?? [] };
1109
- }
1110
- /**
1111
- * Delete one object from the storage bucket by key. Hits the admin-gated
1112
- * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1113
- * with a `storageDelete` function and `adminToken`. Powers the studio file
1114
- * browser's per-row delete; resolves `{ deleted, key }`.
1115
- */
1116
- async deleteStorageObject(key, options) {
1117
- if (this.closed) {
1118
- throw new Error("LunoraClient is closed");
1119
- }
1120
- const path = `${STORAGE_PATH}?key=${encodeURIComponent(key)}${bucketQuery(options?.bucket)}`;
1121
- const body = await this.adminFetch(path, "DELETE");
1122
- return { deleted: body.deleted ?? true, key: body.key ?? key };
1123
- }
1124
- /**
1125
- * List the storage bucket names the worker exposes, for the studio file
1126
- * browser's bucket picker. Hits the admin-gated
1127
- * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1128
- * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1129
- */
1130
- async listStorageBuckets() {
1131
- if (this.closed) {
1132
- throw new Error("LunoraClient is closed");
1133
- }
1134
- const body = await this.adminFetch(STORAGE_BUCKETS_PATH, "GET");
1135
- return body.buckets ?? [];
1136
- }
1137
- /**
1138
- * Upload one object to the storage bucket. Hits the admin-gated
1139
- * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1140
- * optional `contentType` header — the worker must be built with a
1141
- * `storageUpload` function and `adminToken`. Powers the studio file
1142
- * browser's upload control; resolves `{ etag?, key }`.
1143
- */
1144
- async uploadStorageObject(options) {
1145
- if (this.closed) {
1146
- throw new Error("LunoraClient is closed");
1147
- }
1148
- const path = `${STORAGE_PATH}?key=${encodeURIComponent(options.key)}${bucketQuery(options.bucket)}`;
1149
- const body = await this.adminFetch(path, "PUT", options.body, options.contentType);
1150
- return { etag: body.etag, key: body.key ?? options.key };
1151
- }
1152
- /**
1153
- * Build a (signed or public) URL for one object. Hits the admin-gated
1154
- * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1155
- * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1156
- * file browser's copy-URL action; resolves the URL string.
1157
- *
1158
- * `options.expiresInSeconds` requests a share-link lifetime, which is
1159
- * validated/clamped server-side. The options object mirrors the worker's
1160
- * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1161
- * as future fields there).
1162
- */
1163
- async signedStorageUrl(key, options) {
1164
- if (this.closed) {
1165
- throw new Error("LunoraClient is closed");
1166
- }
1167
- const expiresInSeconds = options?.expiresInSeconds;
1168
- const expiryQuery = expiresInSeconds === void 0 ? "" : `&expiresIn=${encodeURIComponent(expiresInSeconds.toString())}`;
1169
- const path = `${STORAGE_URL_PATH}?key=${encodeURIComponent(key)}${expiryQuery}${bucketQuery(options?.bucket)}`;
1170
- const body = await this.adminFetch(path, "GET");
1171
- if (typeof body.url !== "string") {
1172
- throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");
1173
- }
1174
- return body.url;
1175
- }
1176
- // --- Global (D1) tables admin -------------------------------------------
1177
- /**
1178
- * List the `.global()` (D1-backed) tables with their row counts. Hits the
1179
- * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1180
- * be built with a `globalIntrospector` and `adminToken`. Powers the data
1181
- * browser's global mode.
1182
- */
1183
- async listGlobalTables() {
1184
- if (this.closed) {
1185
- throw new Error("LunoraClient is closed");
1186
- }
1187
- return await this.adminFetch(GLOBAL_TABLES_PATH, "GET");
1188
- }
1189
- /**
1190
- * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1191
- * page to rows matching each `column = value` eq constraint — the drill-down a
1192
- * facet-value click applies; the array is JSON-encoded into the `filters`
1193
- * query param and the values are bound server-side.
1194
- */
1195
- async readGlobalTablePage(options) {
1196
- if (this.closed) {
1197
- throw new Error("LunoraClient is closed");
1198
- }
1199
- const params = new URLSearchParams({ table: options.table });
1200
- if (options.limit !== void 0) {
1201
- params.set("limit", String(options.limit));
1202
- }
1203
- if (options.offset !== void 0) {
1204
- params.set("offset", String(options.offset));
1205
- }
1206
- if (options.filters !== void 0 && options.filters.length > 0) {
1207
- params.set("filters", JSON.stringify(options.filters));
1208
- }
1209
- return await this.adminFetch(`${GLOBAL_TABLE_PATH}?${params.toString()}`, "GET");
1210
- }
1211
- /**
1212
- * Summarise the distinct values of one column in a `.global()` table over the
1213
- * active view (the same eq `filters` the browser is previewing) — the global
1214
- * twin of the shard browser's facet. Hits the admin-gated
1215
- * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1216
- * server-side. Powers the global data browser's facet sidebar.
1217
- */
1218
- async facetGlobalColumn(options) {
1219
- if (this.closed) {
1220
- throw new Error("LunoraClient is closed");
1221
- }
1222
- const params = new URLSearchParams({ column: options.column, table: options.table });
1223
- if (options.limit !== void 0) {
1224
- params.set("limit", String(options.limit));
1225
- }
1226
- if (options.filters !== void 0 && options.filters.length > 0) {
1227
- params.set("filters", JSON.stringify(options.filters));
1228
- }
1229
- return await this.adminFetch(`${GLOBAL_FACET_PATH}?${params.toString()}`, "GET");
1230
- }
1231
- // --- Vector indexes admin -----------------------------------------------
1232
- /**
1233
- * List the schema's Vectorize indexes with their declared shape (table,
1234
- * field, dimensions, metric, metadata) and live stats (vector count,
1235
- * processing watermark) when the binding is reachable. Hits the admin-gated
1236
- * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1237
- * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1238
- * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1239
- * from the generated `LUNORA_VECTOR_INDEXES` registry.
1240
- */
1241
- async listVectorIndexes() {
1242
- if (this.closed) {
1243
- throw new Error("LunoraClient is closed");
1244
- }
1245
- const body = await this.adminFetch(VECTOR_INDEXES_PATH, "GET");
1246
- return body.indexes ?? [];
1247
- }
1248
- /**
1249
- * Run a nearest-neighbour similarity query against one vector index: the
1250
- * worker embeds `text` via the index's embedder and returns the top matches.
1251
- * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1252
- * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1253
- * wired (the index lists read-only).
1254
- */
1255
- async queryVectorIndex(options) {
1256
- if (this.closed) {
1257
- throw new Error("LunoraClient is closed");
1258
- }
1259
- const body = await this.adminFetch(VECTOR_QUERY_PATH, "POST", options);
1260
- return body.matches ?? [];
1261
- }
1262
- // --- Auth admin ---------------------------------------------------------
1263
- /**
1264
- * List authenticated users, paged and optionally searched / filtered / sorted.
1265
- * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1266
- * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1267
- * users dashboard.
1268
- */
1269
- async listAuthUsers(options = {}) {
1270
- if (this.closed) {
1271
- throw new Error("LunoraClient is closed");
1272
- }
1273
- const path = withQuery(AUTH_USERS_PATH, {
1274
- filterField: options.filterField,
1275
- filterValue: options.filterValue,
1276
- limit: options.limit,
1277
- offset: options.offset,
1278
- search: options.search,
1279
- searchField: options.searchField,
1280
- sortBy: options.sortBy,
1281
- sortDirection: options.sortDirection
1282
- });
1283
- return await this.adminFetch(path, "GET");
1284
- }
1285
- /**
1286
- * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1287
- * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1288
- * `data` carries any app-defined `user.additionalFields`.
1289
- */
1290
- async createAuthUser(input) {
1291
- return await this.adminFetch(AUTH_CREATE_USER_PATH, "POST", input);
1292
- }
1293
- /** Set a user's role (string, or array joined comma-wise server-side). */
1294
- async setAuthUserRole(input) {
1295
- return await this.adminFetch(AUTH_SET_ROLE_PATH, "POST", input);
1296
- }
1297
- /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1298
- async banAuthUser(input) {
1299
- return await this.adminFetch(AUTH_BAN_PATH, "POST", input);
1300
- }
1301
- /** Lift a user's ban. */
1302
- async unbanAuthUser(input) {
1303
- return await this.adminFetch(AUTH_UNBAN_PATH, "POST", input);
1304
- }
1305
- /** Set a user's password (admin override — no current-password challenge). */
1306
- async setAuthUserPassword(input) {
1307
- await this.adminFetch(AUTH_SET_PASSWORD_PATH, "POST", input);
1308
- }
1309
- /** Permanently delete a user and revoke their sessions. */
1310
- async removeAuthUser(input) {
1311
- await this.adminFetch(AUTH_REMOVE_USER_PATH, "POST", input);
1312
- }
1313
- /**
1314
- * Mint an impersonation session for a user, returning its bearer `token`.
1315
- * The caller is responsible for using the token (e.g. setting the session
1316
- * cookie); the server performs no cookie round-trip.
1317
- */
1318
- async impersonateAuthUser(input) {
1319
- return await this.adminFetch(AUTH_IMPERSONATE_PATH, "POST", input);
1320
- }
1321
- /** Revoke a single session by its id (force sign-out of one device). */
1322
- async revokeAuthSession(input) {
1323
- await this.adminFetch(AUTH_REVOKE_SESSION_PATH, "POST", input);
1324
- }
1325
- /** Revoke every session for a user (force sign-out everywhere). */
1326
- async revokeAuthUserSessions(input) {
1327
- await this.adminFetch(AUTH_REVOKE_SESSIONS_PATH, "POST", input);
1328
- }
1329
- /**
1330
- * Report which auth dashboard surfaces are available — derived server-side
1331
- * from the enabled better-auth plugins. The studio renders only the panels
1332
- * whose capability is `true`.
1333
- */
1334
- async getAuthCapabilities() {
1335
- return await this.adminFetch(AUTH_CAPABILITIES_PATH, "GET");
1336
- }
1337
- /** Update a user's fields (name/email/app-defined `additionalFields`). */
1338
- async updateAuthUser(input) {
1339
- return await this.adminFetch(AUTH_UPDATE_USER_PATH, "POST", input);
1340
- }
1341
- /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1342
- async listAuthAccounts(input) {
1343
- return await this.adminFetch(withQuery(AUTH_ACCOUNTS_PATH, { userId: input.userId }), "GET");
1344
- }
1345
- /** Unlink a linked account from a user. */
1346
- async unlinkAuthAccount(input) {
1347
- await this.adminFetch(AUTH_UNLINK_ACCOUNT_PATH, "POST", input);
1348
- }
1349
- /** List a user's registered passkeys (requires the passkey plugin). */
1350
- async listAuthPasskeys(input) {
1351
- return await this.adminFetch(withQuery(AUTH_PASSKEYS_PATH, { userId: input.userId }), "GET");
1352
- }
1353
- /** Delete a passkey by id (requires the passkey plugin). */
1354
- async deleteAuthPasskey(input) {
1355
- await this.adminFetch(AUTH_DELETE_PASSKEY_PATH, "POST", input);
1356
- }
1357
- /** Disable two-factor auth for a user (requires the two-factor plugin). */
1358
- async disableAuthTwoFactor(input) {
1359
- await this.adminFetch(AUTH_DISABLE_2FA_PATH, "POST", input);
1360
- }
1361
- /** List organizations, paged (requires the organization plugin). */
1362
- async listAuthOrganizations(options = {}) {
1363
- return await this.adminFetch(withQuery(AUTH_ORGS_PATH, { limit: options.limit, offset: options.offset }), "GET");
1364
- }
1365
- /** List the members of an organization (requires the organization plugin). */
1366
- async listAuthOrgMembers(input) {
1367
- const path = withQuery(AUTH_ORG_MEMBERS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1368
- return await this.adminFetch(path, "GET");
1369
- }
1370
- /** List an organization's pending invitations (requires the organization plugin). */
1371
- async listAuthOrgInvitations(input) {
1372
- const path = withQuery(AUTH_ORG_INVITATIONS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1373
- return await this.adminFetch(path, "GET");
1374
- }
1375
- /** Remove a member from an organization. */
1376
- async removeAuthOrgMember(input) {
1377
- await this.adminFetch(AUTH_REMOVE_MEMBER_PATH, "POST", input);
1378
- }
1379
- /** Cancel a pending organization invitation. */
1380
- async cancelAuthOrgInvitation(input) {
1381
- await this.adminFetch(AUTH_CANCEL_INVITATION_PATH, "POST", input);
1382
- }
1383
- /** List auth sessions, paged and optionally filtered to one user. */
1384
- async listAuthSessions(options = {}) {
1385
- if (this.closed) {
1386
- throw new Error("LunoraClient is closed");
1387
- }
1388
- const params = new URLSearchParams();
1389
- if (options.userId !== void 0 && options.userId !== "") {
1390
- params.set("userId", options.userId);
1391
- }
1392
- if (options.limit !== void 0) {
1393
- params.set("limit", String(options.limit));
1394
- }
1395
- if (options.offset !== void 0) {
1396
- params.set("offset", String(options.offset));
1397
- }
1398
- const query = params.toString();
1399
- return await this.adminFetch(query === "" ? AUTH_SESSIONS_PATH : `${AUTH_SESSIONS_PATH}?${query}`, "GET");
1400
- }
1401
- // --- Subscriptions ------------------------------------------------------
1402
- subscribe(function_, args, callback, options = {}) {
1403
- if (this.closed) {
1404
- throw new Error("LunoraClient is closed");
1405
- }
1406
- const argsRecord = args ?? {};
1407
- const key = SubscriptionRegistry.key(function_.__lunoraRef, argsRecord, options.shardKey);
1408
- let state = this.subscriptions.get(key);
1409
- const subscriptionCallback = callback;
1410
- const errorCallback = options.onError;
1411
- if (!state) {
1412
- this.nextSubId += 1;
1413
- const id = `sub_${this.nextSubId.toString()}`;
1414
- const argsKey = stableStringify(argsRecord);
1415
- const cached = this.takeHydratedCache(function_.__lunoraRef, argsKey, options.shardKey);
1416
- state = {
1417
- acked: false,
1418
- args: argsRecord,
1419
- argsKey,
1420
- callbacks: /* @__PURE__ */ new Set(),
1421
- checkpointCallbacks: /* @__PURE__ */ new Set(),
1422
- errorCallbacks: /* @__PURE__ */ new Set(),
1423
- fn: function_,
1424
- id,
1425
- lastValue: cached?.value,
1426
- optimisticLayers: [],
1427
- serverBase: cached?.value,
1428
- serverCursor: cached?.serverCursor,
1429
- shardKey: options.shardKey,
1430
- ...cached?.serverEpoch === void 0 ? {} : { serverEpoch: cached.serverEpoch }
1431
- };
1432
- this.subscriptions.add(state);
1433
- }
1434
- state.callbacks.add(subscriptionCallback);
1435
- if (errorCallback) {
1436
- state.errorCallbacks.add(errorCallback);
1437
- }
1438
- if (options.onCheckpoint) {
1439
- state.checkpointCallbacks.add(options.onCheckpoint);
1440
- }
1441
- if (state.lastValue !== void 0) {
1442
- try {
1443
- subscriptionCallback(state.lastValue);
1444
- } catch {
1445
- }
1446
- }
1447
- this.ensureSocket(options.shardKey);
1448
- this.sendSubscribeIfOpen(state);
1449
- const subscriptionState = state;
1450
- return () => {
1451
- subscriptionState.callbacks.delete(subscriptionCallback);
1452
- if (errorCallback) {
1453
- subscriptionState.errorCallbacks.delete(errorCallback);
1454
- }
1455
- if (options.onCheckpoint) {
1456
- subscriptionState.checkpointCallbacks.delete(options.onCheckpoint);
1457
- }
1458
- if (subscriptionState.callbacks.size === 0) {
1459
- const conn = this.getConnection(subscriptionState.shardKey);
1460
- const ok = conn ? sendOn(conn, { id: subscriptionState.id, type: "unsubscribe" }) : false;
1461
- if (!ok && conn) {
1462
- conn.pendingUnsubscribes.push({ id: subscriptionState.id, type: "unsubscribe" });
1463
- }
1464
- this.subscriptions.remove(subscriptionState);
1465
- }
1466
- };
1467
- }
1468
- /**
1469
- * Subscribe to a declarative **shape** — server-side partial replication
1470
- * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
1471
- * {@link subscribe} for the poke protocol: the client sends the shape *name* +
1472
- * validated `args` (never a `where` the client could forge), the server seeds
1473
- * the current membership as an insert-poke and streams live membership diffs.
1474
- * Each applied poke materializes the shape's rowset and invokes `callback`.
1475
- *
1476
- * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
1477
- * (name, args): the server resolves them under the socket's verified identity,
1478
- * so every call gets its own id + view. The returned function unsubscribes.
1479
- */
1480
- subscribeShape(shape, callback, options = {}) {
1481
- if (this.closed) {
1482
- throw new Error("LunoraClient is closed");
1483
- }
1484
- this.nextShapeId += 1;
1485
- const id = `shape_${this.nextShapeId.toString()}`;
1486
- const state = {
1487
- args: shape.args,
1488
- callbacks: /* @__PURE__ */ new Set([callback]),
1489
- errorCallbacks: options.onError ? /* @__PURE__ */ new Set([options.onError]) : /* @__PURE__ */ new Set(),
1490
- id,
1491
- name: shape.name,
1492
- onCheckpoint: options.onCheckpoint,
1493
- rows: /* @__PURE__ */ new Map(),
1494
- shardKey: options.shardKey
1495
- };
1496
- this.shapeSubscriptions.set(id, state);
1497
- this.ensureSocket(options.shardKey);
1498
- this.sendShapeSubscribeIfOpen(state);
1499
- return () => {
1500
- this.shapeSubscriptions.delete(id);
1501
- const conn = this.getConnection(state.shardKey);
1502
- const ok = conn ? sendOn(conn, { id, type: "shape_unsubscribe" }) : false;
1503
- if (!ok && conn) {
1504
- conn.pendingUnsubscribes.push({ id, type: "shape_unsubscribe" });
1505
- }
1506
- };
1507
- }
1508
- /**
1509
- * Open a streaming query. The function reference must be a
1510
- * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1511
- * the type constraint catches accidental use of a query/mutation/action
1512
- * reference at compile time. The returned iterable yields one element per
1513
- * chunk frame the server pushes, terminating when the server sends
1514
- * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1515
- * rejection on the next `next()`.
1516
- *
1517
- * Streams ride the same WS as subscriptions and share the unsubscribe
1518
- * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1519
- * which the DO recognises as an abort signal for the in-flight iterator.
1520
- *
1521
- * Stream-start frames buffered while the socket is (re)connecting are
1522
- * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1523
- * cap drops the oldest queued frame (and fails its consumer) so a stuck
1524
- * reconnect can't OOM the page.
1525
- */
1526
- stream(function_, args, options = {}) {
1527
- if (this.closed) {
1528
- throw new Error("LunoraClient is closed");
1529
- }
1530
- if (this.WebSocketImpl === void 0) {
1531
- throw new Error("LunoraClient: streams require a WebSocket implementation");
1532
- }
1533
- this.nextStreamId += 1;
1534
- const id = `stream_${this.nextStreamId.toString()}`;
1535
- const { shardKey } = options;
1536
- const argsRecord = args ?? {};
1537
- const { handle, iterable } = createStream({
1538
- maxBuffer: options.maxBuffer,
1539
- onCancel: () => {
1540
- const conn2 = this.getConnection(shardKey);
1541
- if (conn2) {
1542
- sendOn(conn2, { id, type: "unsubscribe" });
1543
- }
1544
- this.streams.delete(id);
1545
- }
1546
- });
1547
- this.streams.set(id, { handle, shardKey });
1548
- this.ensureSocket(shardKey);
1549
- const conn = this.getConnection(shardKey);
1550
- const message = {
1551
- id,
1552
- query: { args: argsRecord, functionPath: function_.__lunoraRef, shardKey },
1553
- type: "stream"
1554
- };
1555
- const sentImmediately = conn?.wsState === "open" && sendOn(conn, message);
1556
- if (!sentImmediately && conn) {
1557
- conn.pendingStreams = conn.pendingStreams ?? [];
1558
- while (conn.pendingStreams.length >= MAX_PENDING_STREAMS) {
1559
- const dropped = conn.pendingStreams.shift();
1560
- const droppedId = dropped?.id;
1561
- const droppedStream = droppedId ? this.streams.get(droppedId) : void 0;
1562
- if (droppedStream) {
1563
- droppedStream.handle.fail(
1564
- Object.assign(new Error("stream-start frame evicted while socket was unreachable"), { code: "STREAM_QUEUE_OVERFLOW" })
1565
- );
1566
- this.streams.delete(droppedId);
1567
- }
1568
- }
1569
- conn.pendingStreams.push(message);
1570
- }
1571
- return iterable;
1572
- }
1573
- close() {
1574
- this.closed = true;
1575
- this.outboxLeaderRelease?.();
1576
- this.outboxLeaderRelease = void 0;
1577
- for (const stream of this.streams.values()) {
1578
- stream.handle.fail(Object.assign(new Error("LunoraClient closed"), { code: "CLIENT_CLOSED" }));
1579
- }
1580
- this.streams.clear();
1581
- for (const conn of this.connections.values()) {
1582
- if (conn.reconnectTimer !== void 0) {
1583
- clearTimeout(conn.reconnectTimer);
1584
- conn.reconnectTimer = void 0;
1585
- }
1586
- if (conn.connectTimer !== void 0) {
1587
- clearTimeout(conn.connectTimer);
1588
- conn.connectTimer = void 0;
1589
- }
1590
- this.stopHeartbeat(conn);
1591
- if (conn.socket) {
1592
- try {
1593
- conn.socket.close();
1594
- } catch {
1595
- }
1596
- conn.socket = void 0;
1597
- }
1598
- conn.wsState = "closed";
1599
- }
1600
- this.offlineQueue.clear();
1601
- this.queuedIdentities.clear();
1602
- if (this.cacheFlushTimer !== void 0) {
1603
- clearTimeout(this.cacheFlushTimer);
1604
- this.cacheFlushTimer = void 0;
1605
- }
1606
- if (this.pendingCacheWrites.size > 0) {
1607
- this.flushQueryCacheWrites().catch(() => void 0);
1608
- }
1609
- this.authTokenListeners.clear();
1610
- this.statusListeners.clear();
1611
- this.tokenExpiredListeners.clear();
1612
- this.mutationSettledListeners.clear();
1613
- this.pendingChangeListeners.clear();
1614
- this.whisperHandlers.clear();
1615
- this.shapeSubscriptions.clear();
1616
- this.pokeBuffers.clear();
1617
- }
1618
- // --- Internals ----------------------------------------------------------
1619
- /**
1620
- * Persist a mutation that can't go out on the wire right now (offline, or
1621
- * mid-reconnect after a prior connect). The optimistic update has already
1622
- * been applied by `mutation`; this only chooses the durable write path and
1623
- * rolls the optimistic write back if persistence is rejected.
1624
- *
1625
- * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
1626
- * owns persistence + at-least-once replay, so we delegate and return
1627
- * optimistically (confirmation rides the synced view). Otherwise the
1628
- * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
1629
- */
1630
- async enqueueOfflineMutation(function_, argsRecord, shardKey, mutationId, optimisticRollbacks, optimisticConfirms) {
1631
- const issuingIdentity = this.identityFingerprint();
1632
- if (this.outbox) {
1633
- this.outboxMutationCounter += 1;
1634
- const outboxMutationId = this.outboxMutationCounter;
1635
- try {
1636
- await this.outbox.enqueue({
1637
- args: argsRecord,
1638
- clientId: this.clientId,
1639
- functionPath: function_.__lunoraRef,
1640
- idempotencyKey: `${this.clientId}:${String(outboxMutationId)}`,
1641
- identity: issuingIdentity,
1642
- mutationId: outboxMutationId,
1643
- shardKey
1644
- });
1645
- } catch (error) {
1646
- rollbackOptimistic(optimisticRollbacks);
1647
- throw error instanceof Error ? error : new Error(String(error));
1648
- }
1649
- for (const confirm of optimisticConfirms) {
1650
- confirm(void 0);
1651
- }
1652
- return void 0;
1653
- }
1654
- return new Promise((resolve, reject) => {
1655
- const entry = {
1656
- args: argsRecord,
1657
- functionPath: function_.__lunoraRef,
1658
- // A live caller is awaiting this Promise, so a terminal verdict
1659
- // reaches them directly; the observer event carries
1660
- // `hadAwaiter: true`. Hydrated replays leave this unset.
1661
- liveAwaiter: true,
1662
- // Reuse the call's idempotency key as the queue id so the replay
1663
- // carries the same `x-lunora-mutation-id` the server dedups on.
1664
- id: mutationId,
1665
- // Persist the stamp alongside the record so a hydrated write can
1666
- // only replay under the identity that queued it.
1667
- identity: issuingIdentity,
1668
- // Confirm the per-call optimistic layer(s) against the commit cursor
1669
- // the flush replay echoes (see flushOfflineQueue).
1670
- onCommit: (commitCursor) => {
1671
- for (const confirm of optimisticConfirms) {
1672
- confirm(commitCursor);
1673
- }
1674
- },
1675
- reject: (error) => {
1676
- this.queuedIdentities.delete(mutationId);
1677
- rollbackOptimistic(optimisticRollbacks);
1678
- reject(error instanceof Error ? error : new Error(String(error)));
1679
- },
1680
- resolve,
1681
- shardKey
1682
- };
1683
- this.offlineQueue.enqueue(entry);
1684
- if (entry.id !== void 0) {
1685
- this.queuedIdentities.set(entry.id, issuingIdentity);
1686
- }
1687
- });
1688
- }
1689
- /**
1690
- * Restore offline mutations persisted in a prior session and open a socket
1691
- * for each shard they target so they flush once the WS reconnects. Failures
1692
- * are swallowed — a broken durable store must not stop the client booting.
1693
- */
1694
- async hydratePersistedQueue() {
1695
- try {
1696
- const shardKeys = await this.offlineQueue.hydrate();
1697
- for (const shardKey of shardKeys) {
1698
- this.ensureSocket(shardKey);
1699
- }
1700
- } catch {
1701
- }
1702
- }
1703
- /**
1704
- * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
1705
- * persisted queue is shared across a profile's tabs; without coordination
1706
- * every tab would re-queue and replay the same writes (correct only because
1707
- * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
1708
- * exactly one tab hydrate; it holds the lock for its lifetime, so when it
1709
- * closes another tab acquires the lock and takes over. Falls back to
1710
- * unconditional hydration where Web Locks are unavailable (React Native, older
1711
- * browsers, SSR) — single-context there, so no coordination is needed.
1712
- */
1713
- hydrateAsOutboxLeader() {
1714
- const hydrate = () => {
1715
- this.hydratePersistedQueue().catch(() => void 0);
1716
- };
1717
- const locks = globalThis.navigator?.locks;
1718
- if (!locks) {
1719
- hydrate();
1720
- return;
1721
- }
1722
- locks.request(`lunora:outbox-leader:${this.url}`, () => {
1723
- if (!this.closed) {
1724
- hydrate();
1725
- }
1726
- return new Promise((resolve) => {
1727
- if (this.closed) {
1728
- resolve();
1729
- return;
1730
- }
1731
- this.outboxLeaderRelease = resolve;
1732
- });
1733
- }).catch(hydrate);
1734
- }
1735
- /**
1736
- * Load every cached query into {@link hydratedQueryCache} so the next
1737
- * `subscribe()` for each key seeds its initial value off disk. A
1738
- * subscription created before this resolves simply misses the cache (it
1739
- * gets a live snapshot as before); the gate at seed time also drops any
1740
- * entry whose stamped identity no longer matches the current one.
1741
- */
1742
- async hydrateQueryCache() {
1743
- if (!this.queryCache) {
1744
- return;
1745
- }
1746
- try {
1747
- const entries = await this.queryCache.load();
1748
- for (const { key, ...entry } of entries) {
1749
- if (isStaleVersion(this.persistenceVersion, entry.version)) {
1750
- this.queryCache.remove(key).catch(() => void 0);
1751
- continue;
1752
- }
1753
- this.hydratedQueryCache.set(key, entry);
1754
- }
1755
- } catch {
1756
- }
1757
- }
1758
- /**
1759
- * Consume the hydrated read-cache entry for a key (if any), gated on
1760
- * identity. The entry is removed whether or not it matches — the cache only
1761
- * ever seeds a subscription's first value. A mismatch (the cache was written
1762
- * under a different identity) yields `undefined` so a signed-out cache never
1763
- * leaks into a new session.
1764
- */
1765
- takeHydratedCache(functionPath, argsKey, shardKey) {
1766
- const key = queryCacheKey(functionPath, argsKey, shardKey);
1767
- const entry = this.hydratedQueryCache.get(key);
1768
- if (entry === void 0) {
1769
- return void 0;
1770
- }
1771
- this.hydratedQueryCache.delete(key);
1772
- return entry.identity === this.identityFingerprint() ? entry : void 0;
1773
- }
1774
- /**
1775
- * Queue a coalesced read-cache write for a subscription's current value.
1776
- * Latest-wins per key; flushed on a short debounce so a delta burst writes
1777
- * once. No-op when the read cache is disabled or the value is undefined
1778
- * (nothing to render offline).
1779
- */
1780
- persistQueryValue(state) {
1781
- const authoritative = state.serverBase;
1782
- if (!this.queryCache || authoritative === void 0) {
1783
- return;
1784
- }
1785
- const key = queryCacheKey(state.fn.__lunoraRef, state.argsKey, state.shardKey);
1786
- this.pendingCacheWrites.set(key, {
1787
- identity: this.identityFingerprint(),
1788
- serverCursor: state.serverCursor,
1789
- ts: Date.now(),
1790
- value: authoritative,
1791
- ...state.serverEpoch === void 0 ? {} : { serverEpoch: state.serverEpoch },
1792
- ...this.persistenceVersion === void 0 ? {} : { version: this.persistenceVersion }
1793
- });
1794
- this.cacheFlushTimer ??= setTimeout(() => {
1795
- this.flushQueryCacheWrites().catch(() => void 0);
1796
- }, QUERY_CACHE_DEBOUNCE_MS);
1797
- }
1798
- /** Drain {@link pendingCacheWrites} to the durable store. */
1799
- async flushQueryCacheWrites() {
1800
- this.cacheFlushTimer = void 0;
1801
- const { queryCache } = this;
1802
- if (!queryCache) {
1803
- this.pendingCacheWrites.clear();
1804
- return;
1805
- }
1806
- const batch = [...this.pendingCacheWrites.entries()];
1807
- this.pendingCacheWrites.clear();
1808
- await Promise.allSettled(batch.map(([key, entry]) => queryCache.put(key, entry)));
1809
- }
1810
- /** Derive the aggregate status from the per-shard socket states. */
1811
- computeStatus() {
1812
- const conns = [...this.connections.values()];
1813
- if (conns.length === 0) {
1814
- return "idle";
1815
- }
1816
- if (conns.some((conn) => conn.wsState === "open")) {
1817
- return "connected";
1818
- }
1819
- if (conns.some((conn) => conn.wsState === "connecting")) {
1820
- return "connecting";
1821
- }
1822
- return "offline";
1823
- }
1824
- /** Recompute the aggregate status and notify listeners if it changed. */
1825
- emitConnectionStatus() {
1826
- const next = this.computeStatus();
1827
- if (next === this.lastStatus) {
1828
- return;
1829
- }
1830
- this.lastStatus = next;
1831
- this.statusListeners.emit(next);
1832
- }
1833
- /**
1834
- * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
1835
- * {@link onMutationSettled} channel. `item.id` is always assigned by the time
1836
- * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
1837
- * is unreachable — present only to satisfy the optional queue-id type.
1838
- */
1839
- emitItemSettled(item, status, error) {
1840
- this.mutationSettledListeners.emit({
1841
- args: item.args,
1842
- code: error === void 0 ? void 0 : error.code,
1843
- error,
1844
- functionPath: item.functionPath,
1845
- hadAwaiter: item.liveAwaiter ?? false,
1846
- id: item.id ?? "",
1847
- shardKey: item.shardKey,
1848
- status
1849
- });
1850
- }
1851
- /**
1852
- * Apply an optimistic update to the subscription that matches the mutation's
1853
- * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
1854
- * invoke if the mutation later fails.
1855
- *
1856
- * The registry is already indexed by exactly this triple via
1857
- * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
1858
- * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
1859
- *
1860
- * `shardKey` normalization: both `undefined` and `""` map to the empty string
1861
- * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
1862
- * a shardKey correctly matches a subscription registered without one regardless
1863
- * of whether the caller passed `undefined` or omitted the field.
1864
- */
1865
- applyOptimisticUpdates(functionRef, argsRecord, mutationShardKey, optimistic) {
1866
- const confirms = [];
1867
- const rollbacks = [];
1868
- if (!optimistic) {
1869
- return { confirms, rollbacks };
1870
- }
1871
- const matchKey = SubscriptionRegistry.key(functionRef, argsRecord, mutationShardKey);
1872
- const state = this.subscriptions.get(matchKey);
1873
- if (state) {
1874
- const handle = applyOptimisticLayer(state, optimistic);
1875
- if (handle) {
1876
- confirms.push(handle.confirm);
1877
- rollbacks.push(handle.rollback);
1878
- }
1879
- }
1880
- return { confirms, rollbacks };
1881
- }
1882
- /**
1883
- * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
1884
- * to the live subscription registry. Each `setQuery` registers a constant
1885
- * optimistic LAYER on its target subscription (via the same engine the
1886
- * per-call `optimistic` path uses), so the multi-query patch rebases onto
1887
- * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
1888
- * `rollback` closures are appended to the mutation's settle lists. A throwing
1889
- * callback unwinds its own partial writes — LIFO over just the rollbacks it
1890
- * produced — and is swallowed, so a buggy optimistic update can never fail the
1891
- * mutation or leave a partial patch live.
1892
- */
1893
- applyOptimisticUpdate(optimisticUpdate, args, shardKey, optimisticRollbacks, optimisticConfirms) {
1894
- const { confirms, rollbacks, store } = createLocalStore(this.subscriptions, shardKey, stableStringify);
1895
- try {
1896
- optimisticUpdate(store, args);
1897
- } catch {
1898
- for (let index = rollbacks.length - 1; index >= 0; index -= 1) {
1899
- rollbacks[index]?.();
1900
- }
1901
- return;
1902
- }
1903
- optimisticRollbacks.push(...rollbacks);
1904
- optimisticConfirms.push(...confirms);
1905
- }
1906
- getConnection(shardKey) {
1907
- return this.connections.get(connectionKey(shardKey));
1908
- }
1909
- getOrCreateConnection(shardKey) {
1910
- const key = connectionKey(shardKey);
1911
- let conn = this.connections.get(key);
1912
- if (!conn) {
1913
- conn = {
1914
- connectTimer: void 0,
1915
- heartbeatTimer: void 0,
1916
- pendingUnsubscribes: [],
1917
- reconnect: createReconnect(this.reconnectOptions),
1918
- reconnectTimer: void 0,
1919
- shardKey,
1920
- socket: void 0,
1921
- wasEverConnected: false,
1922
- wsState: "idle"
1923
- };
1924
- this.connections.set(key, conn);
1925
- }
1926
- return conn;
1927
- }
1928
- wsUrlFor(shardKey) {
1929
- const params = [];
1930
- if (shardKey !== void 0) {
1931
- params.push(`shard=${encodeURIComponent(shardKey)}`);
1932
- }
1933
- if (this.wsToken !== void 0) {
1934
- params.push(`token=${encodeURIComponent(this.wsToken)}`);
1935
- }
1936
- if (params.length === 0) {
1937
- return this.wsUrl;
1938
- }
1939
- const separator = this.wsUrl.includes("?") ? "&" : "?";
1940
- return `${this.wsUrl}${separator}${params.join("&")}`;
1941
- }
1942
- /**
1943
- * Build the outbound RPC headers: JSON content type, optional bearer auth,
1944
- * the optional mutation-replay idempotency key, and the D1 read-your-writes
1945
- * bookmark when the caller opted into `attachBookmark`. The mutation id
1946
- * rides both the direct send and any offline-queue replay of the same write,
1947
- * so a mutation the server already committed returns its cached result
1948
- * instead of running twice.
1949
- */
1950
- rpcRequestHeaders(flags) {
1951
- const headers = { "content-type": "application/json" };
1952
- if (this.authToken) {
1953
- headers["authorization"] = `Bearer ${this.authToken}`;
1954
- }
1955
- if (flags.mutationId) {
1956
- headers["x-lunora-mutation-id"] = flags.mutationId;
1957
- }
1958
- if (flags.clientId !== void 0) {
1959
- headers["x-lunora-client-id"] = flags.clientId;
1960
- }
1961
- if (flags.clientSeq !== void 0) {
1962
- headers["x-lunora-client-seq"] = flags.clientSeq.toString();
1963
- }
1964
- if (flags.attachBookmark) {
1965
- const bookmark = this.bookmark.get();
1966
- if (bookmark) {
1967
- headers["x-d1-bookmark"] = bookmark;
1968
- }
1969
- }
1970
- return headers;
1971
- }
1972
- async rpc(functionPath, args, shardKey, flags = {}) {
1973
- if (!this.fetchImpl) {
1974
- throw new Error("LunoraClient: no `fetch` implementation available");
1975
- }
1976
- const headers = this.rpcRequestHeaders(flags);
1977
- const response = await this.fetchImpl(joinUrl(this.url, RPC_PATH), {
1978
- body: JSON.stringify({ args, functionPath, shardKey }),
1979
- headers,
1980
- method: "POST"
1981
- });
1982
- if (flags.captureBookmark) {
1983
- const value = response.headers.get("x-d1-bookmark");
1984
- if (value) {
1985
- this.bookmark.set(value);
1986
- }
1987
- }
1988
- let body;
1989
- try {
1990
- body = await response.json();
1991
- } catch {
1992
- const statusText = response.statusText ? ` ${response.statusText}` : "";
1993
- throw new Error(`LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
1994
- }
1995
- if ("error" in body) {
1996
- const error = new Error(body.error.message);
1997
- error.code = body.error.code;
1998
- throw error;
1999
- }
2000
- if (!response.ok) {
2001
- const statusText = response.statusText ? ` ${response.statusText}` : "";
2002
- throw new Error(`LunoraClient: request failed (status ${response.status.toString()}${statusText})`);
2003
- }
2004
- flags.onMutationAck?.(body.lastMutationId);
2005
- flags.onCommitCursor?.(body.commitCursor);
2006
- return body.result;
2007
- }
2008
- /**
2009
- * Authenticated request to a non-RPC admin endpoint (the scheduler list /
2010
- * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
2011
- * worker's `{ error: { code, message } }` envelope as a coded `Error` —
2012
- * mirroring {@link rpc} so callers see the same failure shape.
2013
- */
2014
- async adminFetch(path, method, payload, contentType) {
2015
- if (!this.fetchImpl) {
2016
- throw new Error("LunoraClient: no `fetch` implementation available");
2017
- }
2018
- const headers = {};
2019
- if (this.authToken) {
2020
- headers["authorization"] = `Bearer ${this.authToken}`;
2021
- }
2022
- const isBinary = payload instanceof ArrayBuffer || payload instanceof Blob;
2023
- let requestBody;
2024
- if (payload === void 0) {
2025
- requestBody = void 0;
2026
- } else if (isBinary) {
2027
- requestBody = payload;
2028
- if (contentType !== void 0) {
2029
- headers["content-type"] = contentType;
2030
- }
2031
- } else {
2032
- requestBody = JSON.stringify(payload);
2033
- headers["content-type"] = "application/json";
2034
- }
2035
- const response = await this.fetchImpl(joinUrl(this.url, path), {
2036
- body: requestBody,
2037
- headers,
2038
- method
2039
- });
2040
- let body;
2041
- try {
2042
- body = await response.json();
2043
- } catch {
2044
- const statusText = response.statusText ? ` ${response.statusText}` : "";
2045
- throw new Error(`LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
2046
- }
2047
- if (typeof body === "object" && body !== null && "error" in body) {
2048
- const envelope = body.error;
2049
- const error = new Error(envelope.message ?? "admin request failed");
2050
- error.code = envelope.code;
2051
- throw error;
2052
- }
2053
- if (!response.ok) {
2054
- const statusText = response.statusText ? ` ${response.statusText}` : "";
2055
- throw new Error(`LunoraClient: admin request failed (status ${response.status.toString()}${statusText})`);
2056
- }
2057
- return body;
2058
- }
2059
- /**
2060
- * Resolve the effective connection context for a shard: the most-recently
2061
- * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
2062
- * back to the imperative {@link setConnectionContext} override, then the
2063
- * client-wide default. Returns `undefined` when none apply.
2064
- */
2065
- effectiveConnectionContext(key) {
2066
- const holders = this.connectionContextHolders.get(key);
2067
- if (holders && holders.length > 0) {
2068
- return holders[holders.length - 1]?.context;
2069
- }
2070
- return this.connectionContexts.get(key) ?? this.defaultConnectionContext;
2071
- }
2072
- /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
2073
- refreshConnectionContext(key) {
2074
- const conn = this.connections.get(key);
2075
- if (conn?.wsState === "open") {
2076
- this.sendConnectEnvelope(conn);
2077
- }
2078
- }
2079
- /**
2080
- * Send the one-shot `connect` envelope on an open shard socket. Always sent
2081
- * once per socket open, so the server's `onConnect` hooks fire symmetrically
2082
- * with `onDisconnect` (which the DO dispatches unconditionally at close for
2083
- * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
2084
- * hooks are registered, so the single frame costs nothing in the common case.
2085
- *
2086
- * The shard's registered context (or the client-wide default) rides along
2087
- * when one is set — the DO records it on the attachment for replay to
2088
- * `onDisconnect`. A socket with no registered context still announces itself;
2089
- * the envelope simply omits `context`, which is optional on the wire.
2090
- * Register a context — e.g. `setConnectionContext({})` — to attach app state
2091
- * to the lifecycle dispatch.
2092
- */
2093
- sendConnectEnvelope(conn) {
2094
- const context = this.effectiveConnectionContext(connectionKey(conn.shardKey));
2095
- sendOn(conn, {
2096
- // Lets the server scope this connection's `__client_watermark` so
2097
- // custom-mutator pokes can echo this client's `lastMutationId`.
2098
- clientId: this.clientId,
2099
- id: "connect",
2100
- type: "connect",
2101
- ...context === void 0 ? {} : { context }
2102
- });
2103
- }
2104
- /**
2105
- * Re-send every shape subscription bound to `shardKey` over its (now open)
2106
- * socket. Each frame carries the shape's last applied checkpoint, so the
2107
- * server resumes from it — or re-seeds when the cursor fell below CDC
2108
- * retention or the epoch forked.
2109
- */
2110
- resendShapeSubscriptions(shardKey) {
2111
- for (const state of this.shapeSubscriptions.values()) {
2112
- if (connectionKey(state.shardKey) === connectionKey(shardKey)) {
2113
- this.sendShapeSubscribeIfOpen(state);
2114
- }
2115
- }
2116
- }
2117
- ensureSocket(shardKey) {
2118
- if (this.closed || this.WebSocketImpl === void 0) {
2119
- return;
2120
- }
2121
- const conn = this.getOrCreateConnection(shardKey);
2122
- if (conn.wsState === "open" || conn.wsState === "connecting") {
2123
- return;
2124
- }
2125
- conn.wsState = "connecting";
2126
- this.emitConnectionStatus();
2127
- const socket = new this.WebSocketImpl(this.wsUrlFor(shardKey));
2128
- conn.socket = socket;
2129
- if (this.connectTimeoutMs > 0) {
2130
- conn.connectTimer = setTimeout(() => {
2131
- conn.connectTimer = void 0;
2132
- if (conn.socket !== socket || conn.wsState !== "connecting") {
2133
- return;
2134
- }
2135
- try {
2136
- socket.close();
2137
- } catch {
2138
- }
2139
- this.handleDisconnect(conn);
2140
- }, this.connectTimeoutMs);
2141
- }
2142
- socket.addEventListener("open", () => {
2143
- if (conn.socket !== socket) {
2144
- return;
2145
- }
2146
- if (conn.connectTimer !== void 0) {
2147
- clearTimeout(conn.connectTimer);
2148
- conn.connectTimer = void 0;
2149
- }
2150
- conn.wsState = "open";
2151
- conn.wasEverConnected = true;
2152
- conn.reconnect.reset();
2153
- this.emitConnectionStatus();
2154
- this.sendConnectEnvelope(conn);
2155
- this.markShardPendingAck(shardKey);
2156
- for (const state of this.subscriptions.all()) {
2157
- if (connectionKey(state.shardKey) === connectionKey(shardKey)) {
2158
- this.sendSubscribeIfOpen(state);
2159
- }
2160
- }
2161
- this.resendShapeSubscriptions(shardKey);
2162
- if (conn.pendingUnsubscribes.length > 0) {
2163
- const pending = conn.pendingUnsubscribes;
2164
- conn.pendingUnsubscribes = [];
2165
- for (const { id, type } of pending) {
2166
- sendOn(conn, { id, type });
2167
- }
2168
- }
2169
- if (conn.pendingStreams && conn.pendingStreams.length > 0) {
2170
- const pending = conn.pendingStreams;
2171
- conn.pendingStreams = [];
2172
- for (const message of pending) {
2173
- sendOn(conn, message);
2174
- }
2175
- }
2176
- const byTopic = this.whisperHandlers.get(connectionKey(shardKey));
2177
- if (byTopic) {
2178
- for (const topic of byTopic.keys()) {
2179
- sendOn(conn, { topic, type: "whisper_subscribe" });
2180
- }
2181
- }
2182
- this.flushOfflineQueue(shardKey).catch(() => void 0);
2183
- this.startHeartbeat(conn);
2184
- });
2185
- socket.addEventListener("message", (event) => {
2186
- this.handleServerMessage(event.data, shardKey);
2187
- });
2188
- socket.addEventListener("close", (event) => {
2189
- if (conn.socket !== socket) {
2190
- return;
2191
- }
2192
- if (event?.code === 4001) {
2193
- this.notifyTokenExpired();
2194
- }
2195
- this.handleDisconnect(conn);
2196
- });
2197
- socket.addEventListener("error", () => {
2198
- if (conn.socket !== socket) {
2199
- return;
2200
- }
2201
- if (conn.wsState === "connecting" || conn.wsState === "open") {
2202
- this.handleDisconnect(conn);
2203
- }
2204
- });
2205
- }
2206
- handleDisconnect(conn) {
2207
- if (this.closed) {
2208
- return;
2209
- }
2210
- if (conn.wsState === "idle" || conn.wsState === "closed") {
2211
- return;
2212
- }
2213
- this.stopHeartbeat(conn);
2214
- if (conn.connectTimer !== void 0) {
2215
- clearTimeout(conn.connectTimer);
2216
- conn.connectTimer = void 0;
2217
- }
2218
- conn.socket = void 0;
2219
- conn.wsState = "idle";
2220
- this.emitConnectionStatus();
2221
- this.markShardPendingAck(conn.shardKey);
2222
- if (this.WebSocketImpl === void 0) {
2223
- return;
2224
- }
2225
- const delay = conn.reconnect.next();
2226
- conn.reconnectTimer = setTimeout(() => {
2227
- conn.reconnectTimer = void 0;
2228
- this.ensureSocket(conn.shardKey);
2229
- }, delay);
2230
- }
2231
- /**
2232
- * Begin the keepalive heartbeat on an open connection. Each tick sends a
2233
- * {@link WS_KEEPALIVE_PING} text frame the server answers from its
2234
- * hibernation auto-response without waking the DO. A no-op when the
2235
- * heartbeat is disabled (an interval of zero or less); idempotent — any
2236
- * existing timer is cleared first so a reconnect can't leak intervals.
2237
- */
2238
- startHeartbeat(conn) {
2239
- this.stopHeartbeat(conn);
2240
- if (this.heartbeatIntervalMs <= 0) {
2241
- return;
2242
- }
2243
- conn.heartbeatTimer = setInterval(() => {
2244
- if (conn.wsState !== "open" || !conn.socket) {
2245
- return;
2246
- }
2247
- try {
2248
- conn.socket.send(WS_KEEPALIVE_PING);
2249
- } catch {
2250
- }
2251
- }, this.heartbeatIntervalMs);
2252
- }
2253
- /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
2254
- // eslint-disable-next-line class-methods-use-this -- cohesive connection helper; pairs with startHeartbeat
2255
- stopHeartbeat(conn) {
2256
- if (conn.heartbeatTimer !== void 0) {
2257
- clearInterval(conn.heartbeatTimer);
2258
- conn.heartbeatTimer = void 0;
2259
- }
2260
- }
2261
- /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
2262
- markShardPendingAck(shardKey) {
2263
- const key = connectionKey(shardKey);
2264
- for (const state of this.subscriptions.all()) {
2265
- if (connectionKey(state.shardKey) === key) {
2266
- state.acked = false;
2267
- }
2268
- }
2269
- }
2270
- sendSubscribeIfOpen(state) {
2271
- const conn = this.getConnection(state.shardKey);
2272
- if (conn?.wsState !== "open" || state.acked) {
2273
- return;
2274
- }
2275
- const table = state.fn.__lunoraTable ?? state.fn.__lunoraRef;
2276
- sendOn(conn, {
2277
- id: state.id,
2278
- // `sinceSeq` rides along when we hold a persisted cursor for this
2279
- // sub (a hydrated read or an earlier frame), so the server can
2280
- // resume instead of re-snapshotting. Omitted on a cold sub.
2281
- query: {
2282
- args: state.args,
2283
- functionPath: state.fn.__lunoraRef,
2284
- table,
2285
- ...state.serverCursor === void 0 ? {} : { sinceSeq: state.serverCursor },
2286
- ...state.serverEpoch === void 0 ? {} : { sinceEpoch: state.serverEpoch }
2287
- },
2288
- type: "subscribe"
2289
- });
2290
- }
2291
- sendShapeSubscribeIfOpen(state) {
2292
- const conn = this.getConnection(state.shardKey);
2293
- if (conn?.wsState !== "open") {
2294
- return;
2295
- }
2296
- sendOn(conn, {
2297
- id: state.id,
2298
- shape: { name: state.name, ...state.args === void 0 ? {} : { args: state.args } },
2299
- type: "shape_subscribe",
2300
- // Resume from the last applied checkpoint when we hold one; a cold
2301
- // subscribe omits it and the server seeds the full membership.
2302
- ...state.serverCursor === void 0 ? {} : { sinceCheckpoint: state.serverCursor },
2303
- ...state.serverEpoch === void 0 ? {} : { sinceEpoch: state.serverEpoch }
2304
- });
2305
- }
2306
- handleServerMessage(raw, shardKey) {
2307
- const text = decodeServerFrame(raw);
2308
- if (text === void 0) {
2309
- return;
2310
- }
2311
- let message;
2312
- try {
2313
- message = JSON.parse(text);
2314
- } catch {
2315
- return;
2316
- }
2317
- switch (message.type) {
2318
- case "ack": {
2319
- const state = this.subscriptions.getById(message.id);
2320
- if (state) {
2321
- state.acked = true;
2322
- }
2323
- return;
2324
- }
2325
- case "chunk": {
2326
- const { data, id } = message;
2327
- const stream = this.streams.get(id);
2328
- stream?.handle.push(data);
2329
- return;
2330
- }
2331
- case "complete": {
2332
- this.handleCompleteMessage(message.id);
2333
- return;
2334
- }
2335
- case "data":
2336
- case "delta": {
2337
- this.handleDataMessage(message);
2338
- return;
2339
- }
2340
- case "error": {
2341
- this.handleErrorMessage(message);
2342
- break;
2343
- }
2344
- case "pokeEnd": {
2345
- this.handlePokeEnd(message);
2346
- break;
2347
- }
2348
- case "pokePart": {
2349
- this.handlePokePart(message);
2350
- break;
2351
- }
2352
- case "pokeStart": {
2353
- this.handlePokeStart(message);
2354
- break;
2355
- }
2356
- case "resume": {
2357
- this.handleResumeMessage(message);
2358
- break;
2359
- }
2360
- case "settled": {
2361
- this.handleSettledMessage(message);
2362
- break;
2363
- }
2364
- case "whisper": {
2365
- this.dispatchWhisper(message, shardKey);
2366
- break;
2367
- }
2368
- }
2369
- }
2370
- handleErrorMessage(message) {
2371
- const errorCode = message.error?.code;
2372
- if (errorCode === "TOKEN_EXPIRED") {
2373
- this.notifyTokenExpired();
2374
- return;
2375
- }
2376
- const { id } = message;
2377
- const stream = id === void 0 ? void 0 : this.streams.get(id);
2378
- if (stream && id !== void 0) {
2379
- stream.handle.fail(buildStreamError(message));
2380
- this.streams.delete(id);
2381
- return;
2382
- }
2383
- const state = id === void 0 ? void 0 : this.subscriptions.getById(id);
2384
- if (state) {
2385
- fanSubscriptionError(state.errorCallbacks, buildSubscriptionError(message));
2386
- return;
2387
- }
2388
- const shapeState = id === void 0 ? void 0 : this.shapeSubscriptions.get(id);
2389
- if (shapeState) {
2390
- fanSubscriptionError(shapeState.errorCallbacks, buildSubscriptionError(message));
2391
- }
2392
- }
2393
- handlePokeStart(message) {
2394
- if (this.pokeBuffers.size >= LunoraClient.MAX_POKE_BUFFERS) {
2395
- const oldest = this.pokeBuffers.keys().next().value;
2396
- if (oldest !== void 0) {
2397
- this.pokeBuffers.delete(oldest);
2398
- }
2399
- }
2400
- this.pokeBuffers.set(message.pokeId, { baseCheckpoint: message.baseCheckpoint, epoch: message.epoch, lastMutationId: /* @__PURE__ */ new Map(), parts: /* @__PURE__ */ new Map() });
2401
- }
2402
- handlePokePart(message) {
2403
- const buffer = this.pokeBuffers.get(message.pokeId);
2404
- if (!buffer) {
2405
- return;
2406
- }
2407
- const existing = buffer.parts.get(message.shapeId) ?? [];
2408
- existing.push(...message.rowsPatch);
2409
- buffer.parts.set(message.shapeId, existing);
2410
- if (message.lastMutationId !== void 0) {
2411
- buffer.lastMutationId.set(message.shapeId, message.lastMutationId);
2412
- }
2413
- }
2414
- handlePokeEnd(message) {
2415
- const buffer = this.pokeBuffers.get(message.pokeId);
2416
- if (!buffer) {
2417
- return;
2418
- }
2419
- this.pokeBuffers.delete(message.pokeId);
2420
- for (const [shapeId, ops] of buffer.parts) {
2421
- const state = this.shapeSubscriptions.get(shapeId);
2422
- if (!state) {
2423
- continue;
2424
- }
2425
- const epochForked = buffer.epoch !== void 0 && state.serverEpoch !== void 0 && buffer.epoch !== state.serverEpoch;
2426
- const baseDiverged = buffer.baseCheckpoint !== void 0 && state.serverCursor !== void 0 && state.serverCursor !== buffer.baseCheckpoint;
2427
- if (epochForked || baseDiverged) {
2428
- state.rows.clear();
2429
- state.serverCursor = void 0;
2430
- state.serverEpoch = void 0;
2431
- this.emitShapeRows(state);
2432
- this.sendShapeSubscribeIfOpen(state);
2433
- continue;
2434
- }
2435
- applyRowOpsToView(state.rows, ops);
2436
- if (message.checkpoint !== void 0) {
2437
- state.serverCursor = message.checkpoint;
2438
- }
2439
- if (message.epoch !== void 0) {
2440
- state.serverEpoch = message.epoch;
2441
- }
2442
- const watermark = buffer.lastMutationId.get(shapeId);
2443
- if (watermark !== void 0) {
2444
- state.lastMutationId = watermark;
2445
- }
2446
- this.emitShapeRows(state);
2447
- state.onCheckpoint?.({ checkpoint: state.serverCursor, mutationId: state.lastMutationId });
2448
- }
2449
- }
2450
- /** Materialize a shape's keyed view to an array and invoke its callbacks. */
2451
- // eslint-disable-next-line class-methods-use-this -- a pure state→callback fan-out kept beside the shape-subscription pipeline it serves.
2452
- emitShapeRows(state) {
2453
- const rows = [...state.rows.values()];
2454
- for (const shapeCallback of state.callbacks) {
2455
- try {
2456
- shapeCallback(rows);
2457
- } catch {
2458
- }
2459
- }
2460
- }
2461
- handleDataMessage(message) {
2462
- const { id } = message;
2463
- const state = id ? this.subscriptions.getById(id) : void 0;
2464
- if (!state) {
2465
- return;
2466
- }
2467
- const payload = this.resolveDataPayload(message, state);
2468
- state.serverBase = payload;
2469
- if (message.cursor !== void 0) {
2470
- state.serverCursor = message.cursor;
2471
- }
2472
- if (message.epoch !== void 0) {
2473
- state.serverEpoch = message.epoch;
2474
- }
2475
- this.persistQueryValue(state);
2476
- dropConfirmedLayers(state, state.serverCursor);
2477
- notifySubscription(state, state.optimisticLayers.length === 0 ? payload : foldOptimistic(payload, state.optimisticLayers));
2478
- }
2479
- /**
2480
- * Handle a `resume` frame (Pillar 1b): the server proved nothing the
2481
- * subscription reads changed since our `sinceSeq`, so the cached value is
2482
- * still current. We keep `lastValue` as-is, mark the sub acked, and advance
2483
- * the cursor (re-persisting so the next reconnect resumes from the newer
2484
- * watermark). No callback fires — the value didn't change, and `subscribe()`
2485
- * already replayed the cached value to every consumer synchronously.
2486
- */
2487
- handleResumeMessage(message) {
2488
- const state = this.subscriptions.getById(message.id);
2489
- if (!state) {
2490
- return;
2491
- }
2492
- this.ackAndAdvanceCursor(state, message.cursor, message.epoch);
2493
- }
2494
- /**
2495
- * Handle a `settled` frame: a write touched one of this subscription's read
2496
- * tables but produced a byte-identical result, so the server suppressed the
2497
- * data frame. Like {@link handleResumeMessage} the value didn't change — we
2498
- * advance the resume position and re-persist — but we ALSO surface the echoed
2499
- * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
2500
- * collection drops the optimistic overlay for the confirmed write (otherwise
2501
- * its checkpoint gate, fed only by data frames, would hang forever). Sent
2502
- * only to custom-mutator clients; plain `useQuery` subscribers leave
2503
- * `onCheckpoint` unset and this is a near no-op.
2504
- */
2505
- handleSettledMessage(message) {
2506
- const state = this.subscriptions.getById(message.id);
2507
- if (!state) {
2508
- return;
2509
- }
2510
- this.ackAndAdvanceCursor(state, message.cursor, message.epoch);
2511
- if (message.lastMutationId !== void 0) {
2512
- state.lastMutationId = message.lastMutationId;
2513
- }
2514
- for (const onCheckpoint of state.checkpointCallbacks) {
2515
- onCheckpoint({ checkpoint: state.serverCursor, mutationId: state.lastMutationId });
2516
- }
2517
- }
2518
- /**
2519
- * Mark `state` acked and, when the frame carries a newer cursor/epoch than
2520
- * the cached position, advance the resume watermark and re-persist. Shared by
2521
- * the `resume` and `settled` frame handlers — both acknowledge "nothing the
2522
- * client must re-render changed, but the resume position may have moved".
2523
- */
2524
- ackAndAdvanceCursor(state, cursor, epoch) {
2525
- state.acked = true;
2526
- if (cursor !== void 0 && cursor !== state.serverCursor || epoch !== void 0 && epoch !== state.serverEpoch) {
2527
- if (cursor !== void 0) {
2528
- state.serverCursor = cursor;
2529
- }
2530
- if (epoch !== void 0) {
2531
- state.serverEpoch = epoch;
2532
- }
2533
- this.persistQueryValue(state);
2534
- if (dropConfirmedLayers(state, state.serverCursor)) {
2535
- notifySubscription(state, foldOptimistic(state.serverBase, state.optimisticLayers));
2536
- }
2537
- }
2538
- }
2539
- /**
2540
- * Resolve the value to publish for a `data`/`delta` frame.
2541
- *
2542
- * A `data` frame is an authoritative snapshot (the server re-execution path)
2543
- * and always replaces the cached value wholesale. A `delta` frame carrying a
2544
- * structured `MutationDelta` (the `broadcastDelta` row-change path) is
2545
- * merged incrementally into the cached list — preserving order, no dup/loss —
2546
- * so each subscription (including every paginated page) updates by delta
2547
- * rather than a full re-send. We fall back to full replacement when the
2548
- * delta isn't a recognisable row change, when there's no cached value yet,
2549
- * or when it can't be applied cleanly against the current cached shape.
2550
- */
2551
- // eslint-disable-next-line class-methods-use-this -- instance method for symmetry with the other message handlers; reads no shared client state
2552
- resolveDataPayload(message, state) {
2553
- if ("data" in message && message.data !== void 0) {
2554
- return message.data;
2555
- }
2556
- const { delta } = message;
2557
- if (isMutationDelta(delta) && state.serverBase !== void 0) {
2558
- const merged = applyDelta(state.serverBase, delta);
2559
- if (merged !== void 0) {
2560
- return merged;
2561
- }
2562
- }
2563
- return delta;
2564
- }
2565
- /** Route an inbound whisper to the topic's handlers on the originating shard. */
2566
- dispatchWhisper(message, shardKey) {
2567
- const handlers = this.whisperHandlers.get(connectionKey(shardKey))?.get(message.topic);
2568
- if (!handlers) {
2569
- return;
2570
- }
2571
- for (const handler of handlers) {
2572
- try {
2573
- handler(message.data, message.from);
2574
- } catch {
2575
- }
2576
- }
2577
- }
2578
- /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
2579
- notifyTokenExpired() {
2580
- this.tokenExpiredListeners.emit();
2581
- }
2582
- handleCompleteMessage(id) {
2583
- const stream = this.streams.get(id);
2584
- if (stream) {
2585
- stream.handle.complete();
2586
- this.streams.delete(id);
2587
- return;
2588
- }
2589
- const state = this.subscriptions.getById(id);
2590
- if (state) {
2591
- this.subscriptions.remove(state);
2592
- }
2593
- }
2594
- unpersist(id) {
2595
- if (id) {
2596
- this.persistence?.remove(id).catch((error) => {
2597
- reportPersistenceError(this.onPersistenceError, "remove", error, id);
2598
- });
2599
- }
2600
- }
2601
- /**
2602
- * Stable, non-reversible fingerprint of the current auth identity used to
2603
- * stamp queued offline writes. `null` (signed out) is its own identity and
2604
- * never matches a bearer-token fingerprint. The raw token is never stored;
2605
- * a length-prefixed FNV-1a hash is enough to detect an identity *change*
2606
- * without keeping the credential around in the queue map.
2607
- */
2608
- // `null` is the distinct "signed out" identity (separate from `undefined`,
2609
- // which means "not stamped / hydrated"); the two must not be conflated.
2610
- identityFingerprint() {
2611
- if (this.authSubject !== void 0) {
2612
- return this.authSubject === null ? null : `subj:${this.authSubject}`;
2613
- }
2614
- const token = this.authToken;
2615
- if (token === null) {
2616
- return null;
2617
- }
2618
- let hash = 2166136261;
2619
- for (let index = 0; index < token.length; index += 1) {
2620
- hash ^= token.charCodeAt(index);
2621
- hash = Math.imul(hash, 16777619);
2622
- }
2623
- return `${token.length.toString(36)}:${(hash >>> 0).toString(36)}`;
2624
- }
2625
- /**
2626
- * Drain every in-memory offline write and reject it because the auth
2627
- * identity changed. Durable entries are also dropped from persistence so a
2628
- * later `hydrate` can't resurrect another user's writes. Stamps are cleared
2629
- * alongside. Persisted entries restored without a live awaiter still get
2630
- * unpersisted here.
2631
- */
2632
- rejectQueuedForIdentityChange() {
2633
- const drained = this.offlineQueue.drain();
2634
- for (const item of drained) {
2635
- this.queuedIdentities.delete(item.id ?? "");
2636
- this.unpersist(item.id);
2637
- const error = new Error("offline mutation discarded: auth identity changed before replay");
2638
- error.code = "OFFLINE_IDENTITY_CHANGED";
2639
- item.reject(error);
2640
- this.emitItemSettled(item, "rejected", error);
2641
- }
2642
- this.clearQueryCacheForIdentityChange();
2643
- }
2644
- /**
2645
- * Migrate every live identity stamp from `from` to `to` — used when the auth
2646
- * identity label changes but the underlying credential (token) does NOT, e.g.
2647
- * the user id resolves a tick after the token was set. The in-memory
2648
- * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
2649
- * keeps the in-flight writes replayable under the new (more stable) identity
2650
- * instead of the flush guard discarding them as a mismatch.
2651
- */
2652
- restampQueuedIdentity(from, to) {
2653
- for (const [id, stamp] of this.queuedIdentities) {
2654
- if (stamp === from) {
2655
- this.queuedIdentities.set(id, to);
2656
- }
2657
- }
2658
- }
2659
- /**
2660
- * Drop the durable read cache on an identity change so a cached value stamped
2661
- * under the previous identity can never hydrate into a new session. Clears
2662
- * the in-flight write batch and the not-yet-consumed hydrated entries too;
2663
- * the durable `clear()` is best-effort.
2664
- */
2665
- clearQueryCacheForIdentityChange() {
2666
- if (this.cacheFlushTimer !== void 0) {
2667
- clearTimeout(this.cacheFlushTimer);
2668
- this.cacheFlushTimer = void 0;
2669
- }
2670
- this.pendingCacheWrites.clear();
2671
- this.hydratedQueryCache.clear();
2672
- this.queryCache?.clear().catch(() => void 0);
2673
- }
2674
- async flushOfflineQueue(shardKey) {
2675
- const key = connectionKey(shardKey);
2676
- const drained = this.offlineQueue.drain((item) => connectionKey(item.shardKey) === key);
2677
- for (let index = 0; index < drained.length; index += 1) {
2678
- const item = drained[index];
2679
- if (!item) {
2680
- continue;
2681
- }
2682
- const currentIdentity = this.identityFingerprint();
2683
- const liveStamp = item.id === void 0 ? void 0 : this.queuedIdentities.get(item.id);
2684
- const stamped = liveStamp === void 0 ? item.identity : liveStamp;
2685
- if (stamped !== void 0 && stamped !== currentIdentity) {
2686
- this.queuedIdentities.delete(item.id ?? "");
2687
- this.unpersist(item.id);
2688
- const error = new Error("offline mutation skipped: auth identity changed before replay");
2689
- error.code = "OFFLINE_IDENTITY_CHANGED";
2690
- item.reject(error);
2691
- this.emitItemSettled(item, "rejected", error);
2692
- continue;
2693
- }
2694
- this.queuedIdentities.delete(item.id ?? "");
2695
- try {
2696
- let commitCursor;
2697
- const value = await this.rpc(item.functionPath, item.args, item.shardKey, {
2698
- captureBookmark: true,
2699
- mutationId: item.id,
2700
- onCommitCursor: (cursor) => {
2701
- commitCursor = cursor;
2702
- }
2703
- });
2704
- this.unpersist(item.id);
2705
- item.onCommit?.(commitCursor);
2706
- item.resolve(value);
2707
- this.emitItemSettled(item, "committed");
2708
- } catch (error) {
2709
- if (error.code !== void 0) {
2710
- this.unpersist(item.id);
2711
- item.reject(error);
2712
- this.emitItemSettled(item, "rejected", error);
2713
- continue;
2714
- }
2715
- this.offlineQueue.requeue(drained.slice(index));
2716
- return;
2717
- }
2718
- }
2719
- }
2720
- }
2721
-
2722
- export { LunoraClient };