@lunora/client 1.0.0-alpha.4 → 1.0.0-alpha.40

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 (85) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/dist/auth/index.d.mts +11 -10
  4. package/dist/auth/index.d.ts +11 -10
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +736 -172
  7. package/dist/index.d.ts +736 -172
  8. package/dist/index.mjs +1 -14
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs +1 -0
  10. package/dist/packem_shared/ClientServiceWorker-CRQ5yl7-.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs +1 -0
  12. package/dist/packem_shared/LunoraClient-Cz-RavLT.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-y4mymc5n.mjs +1 -0
  14. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs +1 -0
  15. package/dist/packem_shared/SKIP-CArzT3Vl.mjs +1 -0
  16. package/dist/packem_shared/SubscriptionRegistry-C72rCp44.mjs +1 -0
  17. package/dist/packem_shared/TabCoordinator-CMFYQCL-.mjs +1 -0
  18. package/dist/packem_shared/anyApi-BD4dgvDY.mjs +1 -0
  19. package/dist/packem_shared/applyDelta-DXqQORbM.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs +1 -0
  21. package/dist/packem_shared/createClientQuery-CrdRoicO.mjs +1 -0
  22. package/dist/packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryPersistence-CQYXy8UP.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs +1 -0
  25. package/dist/packem_shared/createLocalStore-CwuKPK9x.mjs +1 -0
  26. package/dist/packem_shared/createMutationRunner-lQXH8Amk.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-BVzo0FBZ.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CFT7YRSR.mjs +1 -0
  29. package/dist/packem_shared/createReply-DF0jRsv-.mjs +1 -0
  30. package/dist/packem_shared/createServerClient-CQf6XOk3.mjs +1 -0
  31. package/dist/packem_shared/createSnapshotPrecondition-CKvCNKyD.mjs +1 -0
  32. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  33. package/dist/packem_shared/getServerSession-CGjgRBAE.mjs +1 -0
  34. package/dist/packem_shared/httpStream-Cz4_QyjV.mjs +11 -0
  35. package/dist/packem_shared/idb-utility-C-DR8nG1.mjs +1 -0
  36. package/dist/packem_shared/local-store-DFMSEM2j.mjs +1 -0
  37. package/dist/packem_shared/lunora-client.d-B23myJYW.d.ts +2168 -0
  38. package/dist/packem_shared/lunora-client.d-BRXKXo0T.d.mts +2168 -0
  39. package/dist/packem_shared/offline-queue-BeWay5u5.mjs +1 -0
  40. package/dist/packem_shared/preload.d-BgoF8JQZ.d.mts +21 -0
  41. package/dist/packem_shared/preload.d-cq7evweX.d.ts +21 -0
  42. package/dist/packem_shared/preloadQuery-DjwSjFwt.mjs +1 -0
  43. package/dist/packem_shared/types.d-CA7ZeJm9.d.mts +942 -0
  44. package/dist/packem_shared/types.d-CA7ZeJm9.d.ts +942 -0
  45. package/dist/packem_shared/wire-codec-D_fiax9d.mjs +1 -0
  46. package/dist/packem_shared/wire-key-j8BZ65HQ.mjs +1 -0
  47. package/dist/pagination/index.d.mts +42 -42
  48. package/dist/pagination/index.d.ts +42 -42
  49. package/dist/pagination/index.mjs +1 -61
  50. package/dist/query/index.d.mts +43 -42
  51. package/dist/query/index.d.ts +43 -42
  52. package/dist/query/index.mjs +1 -1
  53. package/dist/service.d.mts +49 -0
  54. package/dist/service.d.ts +49 -0
  55. package/dist/service.mjs +1 -0
  56. package/dist/ssr/index.d.mts +80 -79
  57. package/dist/ssr/index.d.ts +80 -79
  58. package/dist/ssr/index.mjs +1 -4
  59. package/dist/upload.d.mts +35 -0
  60. package/dist/upload.d.ts +35 -0
  61. package/dist/upload.mjs +1 -0
  62. package/package.json +13 -1
  63. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  64. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  65. package/dist/packem_shared/LunoraClient-DHMV-94j.mjs +0 -2198
  66. package/dist/packem_shared/OfflineQueue-D5p_QgF_.mjs +0 -127
  67. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  68. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  69. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  70. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  71. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  72. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  73. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  74. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  75. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  76. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  77. package/dist/packem_shared/createServerClient-DMh-2UDv.mjs +0 -11
  78. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  79. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  80. package/dist/packem_shared/lunora-client.d-CbnxmuqG.d.mts +0 -1623
  81. package/dist/packem_shared/lunora-client.d-CbnxmuqG.d.ts +0 -1623
  82. package/dist/packem_shared/preload.d-Bhq6DBSe.d.mts +0 -20
  83. package/dist/packem_shared/preload.d-C73DT6bL.d.ts +0 -20
  84. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  85. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
@@ -1,2198 +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 { createLocalStore } from './createLocalStore-DSUfoLqY.mjs';
5
- import { OfflineQueue, nextId, reportPersistenceError } from './OfflineQueue-D5p_QgF_.mjs';
6
- import { queryCacheKey } from './createInMemoryQueryCache-B1PQ9Twl.mjs';
7
- import { createReconnect } from './createReconnect-Di_-oHH7.mjs';
8
- import { createStream } from './DEFAULT_MAX_BUFFER-BDkqO5PW.mjs';
9
-
10
- const RPC_PATH = "/_lunora/rpc";
11
- const WS_PATH = "/_lunora/ws";
12
- const bucketQuery = (bucket) => bucket === void 0 || bucket === "" ? "" : `&bucket=${encodeURIComponent(bucket)}`;
13
- const WS_KEEPALIVE_PING = "lunora-ping";
14
- const DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
15
- const DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
16
- const QUERY_CACHE_DEBOUNCE_MS = 250;
17
- const MAX_PENDING_STREAMS = 64;
18
- const SHARD_TRAFFIC_PATH = "/_lunora/admin/shard-traffic";
19
- const SCHEDULED_PATH = "/_lunora/admin/scheduled";
20
- const SCHEDULED_STATUS_PATH = "/_lunora/admin/scheduled/status";
21
- const SCHEDULED_WS_PATH = "/_lunora/admin/scheduled/ws";
22
- const SCHEDULED_CANCEL_PATH = "/_lunora/admin/scheduled/cancel";
23
- const SCHEDULED_DEAD_PATH = "/_lunora/admin/scheduled/dead";
24
- const SCHEDULED_DEAD_RETRY_PATH = "/_lunora/admin/scheduled/dead/retry";
25
- const SCHEDULED_DEAD_CANCEL_PATH = "/_lunora/admin/scheduled/dead/cancel";
26
- const WORKFLOWS_INSTANCES_PATH = "/_lunora/admin/workflows/instances";
27
- const WORKFLOWS_INSTANCE_PATH = "/_lunora/admin/workflows/instance";
28
- const WORKFLOWS_STATUS_PATH = "/_lunora/admin/workflows/status";
29
- const STORAGE_PATH = "/_lunora/admin/storage";
30
- const STORAGE_URL_PATH = "/_lunora/admin/storage/url";
31
- const STORAGE_BUCKETS_PATH = "/_lunora/admin/storage/buckets";
32
- const FUNCTIONS_PATH = "/_lunora/admin/functions";
33
- const CRON_JOBS_PATH = "/_lunora/admin/cron-jobs";
34
- const CRON_JOBS_RUN_PATH = "/_lunora/admin/cron-jobs/run";
35
- const OPENAPI_PATH = "/_lunora/admin/openapi";
36
- const OPENRPC_PATH = "/_lunora/admin/openrpc";
37
- const GLOBAL_TABLES_PATH = "/_lunora/admin/global/tables";
38
- const GLOBAL_TABLE_PATH = "/_lunora/admin/global/table";
39
- const GLOBAL_FACET_PATH = "/_lunora/admin/global/facet";
40
- const VECTOR_INDEXES_PATH = "/_lunora/admin/vector/indexes";
41
- const VECTOR_QUERY_PATH = "/_lunora/admin/vector/query";
42
- const AUTH_USERS_PATH = "/_lunora/admin/auth/users";
43
- const AUTH_SESSIONS_PATH = "/_lunora/admin/auth/sessions";
44
- const AUTH_CREATE_USER_PATH = "/_lunora/admin/auth/users/create";
45
- const AUTH_SET_ROLE_PATH = "/_lunora/admin/auth/users/role";
46
- const AUTH_BAN_PATH = "/_lunora/admin/auth/users/ban";
47
- const AUTH_UNBAN_PATH = "/_lunora/admin/auth/users/unban";
48
- const AUTH_SET_PASSWORD_PATH = "/_lunora/admin/auth/users/password";
49
- const AUTH_REMOVE_USER_PATH = "/_lunora/admin/auth/users/remove";
50
- const AUTH_IMPERSONATE_PATH = "/_lunora/admin/auth/users/impersonate";
51
- const AUTH_REVOKE_SESSION_PATH = "/_lunora/admin/auth/sessions/revoke";
52
- const AUTH_REVOKE_SESSIONS_PATH = "/_lunora/admin/auth/sessions/revoke-all";
53
- const AUTH_CAPABILITIES_PATH = "/_lunora/admin/auth/capabilities";
54
- const AUTH_UPDATE_USER_PATH = "/_lunora/admin/auth/users/update";
55
- const AUTH_ACCOUNTS_PATH = "/_lunora/admin/auth/accounts";
56
- const AUTH_UNLINK_ACCOUNT_PATH = "/_lunora/admin/auth/accounts/unlink";
57
- const AUTH_PASSKEYS_PATH = "/_lunora/admin/auth/passkeys";
58
- const AUTH_DELETE_PASSKEY_PATH = "/_lunora/admin/auth/passkeys/delete";
59
- const AUTH_DISABLE_2FA_PATH = "/_lunora/admin/auth/two-factor/disable";
60
- const AUTH_ORGS_PATH = "/_lunora/admin/auth/organizations";
61
- const AUTH_ORG_MEMBERS_PATH = "/_lunora/admin/auth/organizations/members";
62
- const AUTH_ORG_INVITATIONS_PATH = "/_lunora/admin/auth/organizations/invitations";
63
- const AUTH_REMOVE_MEMBER_PATH = "/_lunora/admin/auth/organizations/members/remove";
64
- const AUTH_CANCEL_INVITATION_PATH = "/_lunora/admin/auth/organizations/invitations/cancel";
65
- const DEFAULT_AUTH_BASE_PATH = "/api/auth";
66
- const GET_SESSION_PATH = "/get-session";
67
- const deriveWsUrl = (url) => {
68
- if (url.startsWith("https://")) {
69
- return `wss://${url.slice("https://".length)}`;
70
- }
71
- if (url.startsWith("http://")) {
72
- return `ws://${url.slice("http://".length)}`;
73
- }
74
- return url;
75
- };
76
- const joinUrl = (base, path) => {
77
- const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;
78
- return `${trimmed}${path}`;
79
- };
80
- const withQuery = (path, params) => {
81
- const search = new URLSearchParams();
82
- for (const [key, value] of Object.entries(params)) {
83
- if (value !== void 0 && value !== "") {
84
- search.set(key, String(value));
85
- }
86
- }
87
- const query = search.toString();
88
- return query === "" ? path : `${path}?${query}`;
89
- };
90
- const connectionKey = (shardKey) => shardKey ?? "";
91
- const writeOptimisticToState = (state, next) => {
92
- const previous = state.lastValue;
93
- const versionAtApply = state.serverVersion;
94
- state.lastValue = next;
95
- for (const callback of state.callbacks) {
96
- try {
97
- callback(next);
98
- } catch {
99
- }
100
- }
101
- return () => {
102
- if (state.serverVersion > versionAtApply) {
103
- return;
104
- }
105
- if (state.lastValue !== next) {
106
- return;
107
- }
108
- state.lastValue = previous;
109
- for (const callback of state.callbacks) {
110
- try {
111
- callback(previous);
112
- } catch {
113
- }
114
- }
115
- };
116
- };
117
- const applyOptimisticToState = (state, optimistic) => {
118
- let next;
119
- try {
120
- next = optimistic(state.lastValue);
121
- } catch {
122
- return void 0;
123
- }
124
- return writeOptimisticToState(state, next);
125
- };
126
- const buildStreamError = (message) => {
127
- const errorEnvelope = message.error;
128
- const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
129
- const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
130
- const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "stream error";
131
- return Object.assign(new Error(messageText), code === void 0 ? void 0 : { code });
132
- };
133
- const buildSubscriptionError = (message) => {
134
- const errorEnvelope = message.error;
135
- const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
136
- const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
137
- const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "subscription error";
138
- return { message: messageText, ...code === void 0 ? {} : { code } };
139
- };
140
- const sharedDecoder = new TextDecoder();
141
- const decodeServerFrame = (raw) => {
142
- if (typeof raw === "string") {
143
- return raw;
144
- }
145
- if (raw instanceof ArrayBuffer) {
146
- return sharedDecoder.decode(raw);
147
- }
148
- return void 0;
149
- };
150
- const sendOn = (conn, message) => {
151
- if (!conn.socket || conn.wsState !== "open") {
152
- return false;
153
- }
154
- try {
155
- conn.socket.send(JSON.stringify(message));
156
- return true;
157
- } catch {
158
- return false;
159
- }
160
- };
161
- class LunoraClient {
162
- url;
163
- wsUrl;
164
- wsToken;
165
- /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
166
- authBasePath;
167
- fetchImpl;
168
- WebSocketImpl;
169
- bookmark;
170
- reconnectOptions;
171
- /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
172
- connectTimeoutMs;
173
- /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
174
- heartbeatIntervalMs;
175
- offlineQueue;
176
- onPersistenceError;
177
- persistence;
178
- /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
179
- queryCache;
180
- /**
181
- * Values restored from the `queryCache` at construction, keyed by the
182
- * read-cache key, awaiting the `subscribe()` that will consume them. A
183
- * key is consumed (deleted) the first time its subscription is created, so
184
- * the cache only ever seeds the initial value — live frames take over after.
185
- */
186
- hydratedQueryCache = /* @__PURE__ */ new Map();
187
- /**
188
- * Coalesced read-cache writes: the latest value per key, flushed to
189
- * the `queryCache` on a short debounce so a burst of deltas persists once.
190
- */
191
- pendingCacheWrites = /* @__PURE__ */ new Map();
192
- cacheFlushTimer;
193
- subscriptions = new SubscriptionRegistry();
194
- /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
195
- connections = /* @__PURE__ */ new Map();
196
- /** Default `connect`-envelope context applied to a shard with no explicit override. */
197
- defaultConnectionContext;
198
- /**
199
- * Per-shard `connect`-envelope context registered via `setConnectionContext`
200
- * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
201
- * on every socket open so it replays across reconnects, and forwarded to the
202
- * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
203
- * imperative (last-writer-wins) override; refcounted holders registered via
204
- * `acquireConnectionContext` live in `connectionContextHolders` and take
205
- * precedence — see `effectiveConnectionContext`.
206
- */
207
- connectionContexts = /* @__PURE__ */ new Map();
208
- /**
209
- * Per-shard stack of refcounted connection-context holders (keyed by
210
- * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
211
- * is an opaque token carrying its `context`; the most-recently acquired
212
- * holder wins (last-writer-wins among live holders), and the context is only
213
- * cleared for a shard once its last holder releases — so two concurrently
214
- * mounted presence hooks on the same shard can't stomp each other's context
215
- * on cleanup. A holder is identified by reference identity so a release
216
- * removes exactly the right one regardless of stack position.
217
- */
218
- connectionContextHolders = /* @__PURE__ */ new Map();
219
- // `null` is the public sentinel for "signed out" across getAuthToken /
220
- // setAuthToken / onAuthTokenChange — part of the exported API contract.
221
- // eslint-disable-next-line unicorn/no-null -- public auth-token contract sentinel
222
- authToken = null;
223
- /**
224
- * Identity stamp recorded against each queued offline mutation, keyed by
225
- * the queue-assigned mutation id. Captured at enqueue from the auth token
226
- * in effect at the time, and re-checked at flush so a queued write can
227
- * never replay under a different identity than the one that issued it.
228
- * See `identityFingerprint` for the fingerprint shape.
229
- */
230
- queuedIdentities = /* @__PURE__ */ new Map();
231
- closed = false;
232
- /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
233
- authTokenListeners = /* @__PURE__ */ new Set();
234
- /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
235
- statusListeners = /* @__PURE__ */ new Set();
236
- /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
237
- tokenExpiredListeners = /* @__PURE__ */ new Set();
238
- /**
239
- * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
240
- * of callbacks. Membership doubles as the resubscribe set replayed on every
241
- * (re)connect so a topic survives a socket bounce.
242
- */
243
- whisperHandlers = /* @__PURE__ */ new Map();
244
- /** Last status broadcast, so we only notify listeners on an actual change. */
245
- lastStatus = "idle";
246
- nextSubId = 0;
247
- nextStreamId = 0;
248
- /**
249
- * In-flight client-side stream readers, keyed by the stream id sent on the
250
- * wire. The handle drives the underlying iterator queue and `shardKey`
251
- * tells us which socket to push the cancel frame onto when the consumer
252
- * calls `.cancel()` or the iterator is garbage-collected.
253
- */
254
- streams = /* @__PURE__ */ new Map();
255
- constructor(options) {
256
- this.url = options.url;
257
- this.wsUrl = options.wsUrl ?? joinUrl(deriveWsUrl(options.url), WS_PATH);
258
- this.wsToken = options.wsToken;
259
- const authBase = options.authBasePath ?? DEFAULT_AUTH_BASE_PATH;
260
- this.authBasePath = authBase.endsWith("/") ? authBase.slice(0, -1) : authBase;
261
- this.fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch.bind(globalThis) : void 0);
262
- this.WebSocketImpl = options.WebSocket ?? (typeof WebSocket === "function" ? WebSocket : void 0);
263
- this.bookmark = options.bookmarkStorage ?? createInMemoryBookmarkStorage();
264
- this.reconnectOptions = options.reconnect;
265
- this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
266
- this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
267
- this.defaultConnectionContext = options.connectionContext;
268
- this.persistence = options.persistence;
269
- this.queryCache = options.queryCache === false ? void 0 : options.queryCache;
270
- this.onPersistenceError = options.offlineQueue?.onPersistenceError;
271
- this.offlineQueue = new OfflineQueue(options.offlineQueue, options.persistence);
272
- if (this.persistence) {
273
- queueMicrotask(() => {
274
- this.hydratePersistedQueue().catch(() => void 0);
275
- });
276
- }
277
- if (this.queryCache) {
278
- queueMicrotask(() => {
279
- this.hydrateQueryCache().catch(() => void 0);
280
- });
281
- }
282
- }
283
- // --- Auth helpers -------------------------------------------------------
284
- /**
285
- * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
286
- * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
287
- * sync across all mounted instances.
288
- *
289
- * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
290
- * time and lives in the URL. To refresh live WS auth, call
291
- * {@link setWsToken} explicitly, which closes existing shard sockets to
292
- * force a reconnect with the new credential.
293
- */
294
- setAuthToken(token) {
295
- if (this.authToken === token) {
296
- return;
297
- }
298
- this.authToken = token;
299
- this.rejectQueuedForIdentityChange();
300
- for (const listener of this.authTokenListeners) {
301
- try {
302
- listener(token);
303
- } catch {
304
- }
305
- }
306
- }
307
- getAuthToken() {
308
- return this.authToken;
309
- }
310
- /**
311
- * Subscribe to auth-token changes. Returns an unsubscribe function. The
312
- * listener is NOT invoked on registration — use {@link getAuthToken} for
313
- * the current value.
314
- */
315
- onAuthTokenChange(listener) {
316
- this.authTokenListeners.add(listener);
317
- return () => {
318
- this.authTokenListeners.delete(listener);
319
- };
320
- }
321
- /**
322
- * Fetch the currently authenticated user from better-auth's `get-session`
323
- * endpoint, returning the `user` record or `null` when signed out. Sends
324
- * the stored bearer token (if any) and `credentials: "include"` so a
325
- * cookie-session is also honoured. A network/parse failure or a non-OK
326
- * response resolves to `null` rather than throwing — callers treat "couldn't
327
- * resolve identity" as "signed out".
328
- *
329
- * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
330
- * the token changes (that's what `@lunora/react`'s `useAuth` does).
331
- */
332
- async getCurrentUser() {
333
- if (this.closed || !this.fetchImpl) {
334
- return null;
335
- }
336
- const headers = {};
337
- if (this.authToken) {
338
- headers["authorization"] = `Bearer ${this.authToken}`;
339
- }
340
- try {
341
- const response = await this.fetchImpl(joinUrl(this.url, `${this.authBasePath}${GET_SESSION_PATH}`), {
342
- credentials: "include",
343
- headers,
344
- method: "GET"
345
- });
346
- if (!response.ok) {
347
- return null;
348
- }
349
- const body = await response.json();
350
- return body?.user ?? null;
351
- } catch {
352
- return null;
353
- }
354
- }
355
- /**
356
- * Replace the token appended to WS upgrade URLs as `?token=…` and close
357
- * every open shard socket so the reconnect picks up the new value. Call
358
- * this whenever the user's WS credential changes (rotating the admin token
359
- * in the studio, switching workspaces, etc.). Bearer tokens for HTTP
360
- * RPC are independent — see {@link setAuthToken}.
361
- */
362
- setWsToken(token) {
363
- if (this.wsToken === token) {
364
- return;
365
- }
366
- this.wsToken = token;
367
- for (const conn of this.connections.values()) {
368
- if (conn.socket) {
369
- try {
370
- conn.socket.close();
371
- } catch {
372
- }
373
- }
374
- }
375
- }
376
- /**
377
- * Register (or clear, with `undefined`) the app context sent in the `connect`
378
- * envelope for a shard's socket, overriding the client-wide
379
- * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
380
- * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
381
- * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
382
- * presence row is removed the instant the socket drops, with no TTL lag.
383
- *
384
- * Stored per shard and replayed on every (re)connect. When a socket for the
385
- * shard is already open, a fresh `connect` envelope is sent immediately so the
386
- * server sees the new context without waiting for a reconnect.
387
- */
388
- setConnectionContext(context, options = {}) {
389
- const key = connectionKey(options.shardKey);
390
- if (context === void 0) {
391
- this.connectionContexts.delete(key);
392
- } else {
393
- this.connectionContexts.set(key, context);
394
- }
395
- this.refreshConnectionContext(key);
396
- }
397
- /**
398
- * Refcounted variant of {@link setConnectionContext}: register a connection
399
- * `context` for a shard and get back a release function. Unlike the imperative
400
- * setter, the context is only cleared once the *last* acquired holder releases
401
- * it — so two components (e.g. two mounted `usePresence` hooks) on the same
402
- * shard no longer clobber each other's context when one of them unmounts. The
403
- * most-recently acquired live holder wins (last-writer-wins), and releasing
404
- * the top holder falls back to the previous one rather than clearing.
405
- *
406
- * With a single holder the behaviour is identical to a
407
- * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
408
- * Releasing more than once is a no-op (the holder is matched by reference, so
409
- * a double release can't drop a different holder).
410
- */
411
- acquireConnectionContext(context, options = {}) {
412
- const key = connectionKey(options.shardKey);
413
- const holder = { context };
414
- const holders = this.connectionContextHolders.get(key);
415
- if (holders) {
416
- holders.push(holder);
417
- } else {
418
- this.connectionContextHolders.set(key, [holder]);
419
- }
420
- this.refreshConnectionContext(key);
421
- let released = false;
422
- return () => {
423
- if (released) {
424
- return;
425
- }
426
- released = true;
427
- const live = this.connectionContextHolders.get(key);
428
- if (!live) {
429
- return;
430
- }
431
- const index = live.indexOf(holder);
432
- if (index !== -1) {
433
- live.splice(index, 1);
434
- }
435
- if (live.length === 0) {
436
- this.connectionContextHolders.delete(key);
437
- }
438
- this.refreshConnectionContext(key);
439
- };
440
- }
441
- // --- Whispering ---------------------------------------------------------
442
- /**
443
- * Join a whisper `topic` and receive every ephemeral message other members
444
- * broadcast to it on the same shard (typing indicators, live cursors,
445
- * presence pings). Whispers never touch the server's durable state — there's
446
- * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
447
- * is left on the server once its last local handler unsubscribes.
448
- *
449
- * `handler` receives the raw `data` and the sender's verified `from` user id
450
- * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
451
- * (the default shard when omitted) — use the same shard you target with the
452
- * matching queries/mutations so members land on the same Durable Object.
453
- *
454
- * Security: whisper topics are NOT access-controlled beyond the shard
455
- * boundary — any client that can open a socket to the shard can join, read,
456
- * and inject on any topic name. `from` is server-stamped and unforgeable, but
457
- * do not put data on a whisper topic that some shard members shouldn't see,
458
- * and don't trust a whisper's `data` as authorization. Use a query/mutation
459
- * (with RLS) for anything privileged; whispers are for transient awareness.
460
- */
461
- whisperSubscribe(topic, handler, options = {}) {
462
- const key = connectionKey(options.shardKey);
463
- let byTopic = this.whisperHandlers.get(key);
464
- if (!byTopic) {
465
- byTopic = /* @__PURE__ */ new Map();
466
- this.whisperHandlers.set(key, byTopic);
467
- }
468
- let handlers = byTopic.get(topic);
469
- const first = handlers === void 0;
470
- if (!handlers) {
471
- handlers = /* @__PURE__ */ new Set();
472
- byTopic.set(topic, handlers);
473
- }
474
- handlers.add(handler);
475
- this.ensureSocket(options.shardKey);
476
- if (first) {
477
- const conn = this.getConnection(options.shardKey);
478
- if (conn) {
479
- sendOn(conn, { topic, type: "whisper_subscribe" });
480
- }
481
- }
482
- return () => {
483
- const stillByTopic = this.whisperHandlers.get(key);
484
- const stillHandlers = stillByTopic?.get(topic);
485
- if (!stillHandlers?.delete(handler) || stillHandlers.size > 0) {
486
- return;
487
- }
488
- stillByTopic?.delete(topic);
489
- if (stillByTopic?.size === 0) {
490
- this.whisperHandlers.delete(key);
491
- }
492
- const conn = this.getConnection(options.shardKey);
493
- if (conn) {
494
- sendOn(conn, { topic, type: "whisper_unsubscribe" });
495
- }
496
- };
497
- }
498
- /**
499
- * Broadcast an ephemeral `data` payload to the other members of a whisper
500
- * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
501
- * dropped when the shard socket isn't open (whispers are transient, never
502
- * queued), and the server silently drops it if the sender exceeds its
503
- * whisper rate budget. The sender never receives its own whisper. Omitting
504
- * `data` delivers JSON `null` to receivers (not `undefined`).
505
- */
506
- whisper(topic, data, options = {}) {
507
- this.ensureSocket(options.shardKey);
508
- const conn = this.getConnection(options.shardKey);
509
- if (conn) {
510
- sendOn(conn, { data, topic, type: "whisper" });
511
- }
512
- }
513
- /**
514
- * Subscribe to token-expiry events: invoked whenever the server drops a
515
- * shard socket because the connection's credential lapsed (close code
516
- * `4001`). The client already reconnects automatically (re-resolving
517
- * identity from the cookie/token in effect); use this to refresh a
518
- * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
519
- * with a freshly minted one. Returns an unsubscribe function.
520
- */
521
- onTokenExpired(listener) {
522
- this.tokenExpiredListeners.add(listener);
523
- return () => {
524
- this.tokenExpiredListeners.delete(listener);
525
- };
526
- }
527
- // --- Connection status --------------------------------------------------
528
- /**
529
- * Current aggregate live-socket status across all shard connections. See
530
- * {@link ConnectionStatus}.
531
- */
532
- connectionStatus() {
533
- return this.computeStatus();
534
- }
535
- /**
536
- * Subscribe to aggregate connection-status changes. Invokes `listener`
537
- * immediately with the current status, then on every transition. Returns an
538
- * unsubscribe function.
539
- */
540
- onConnectionStatus(listener) {
541
- this.statusListeners.add(listener);
542
- listener(this.computeStatus());
543
- return () => {
544
- this.statusListeners.delete(listener);
545
- };
546
- }
547
- // --- RPC ---------------------------------------------------------------
548
- async query(function_, args, options = {}) {
549
- if (this.closed) {
550
- throw new Error("LunoraClient is closed");
551
- }
552
- return await this.rpc(function_.__lunoraRef, args, options.shardKey, { attachBookmark: true });
553
- }
554
- /**
555
- * Invoke a mutation. Errors propagate as rejections.
556
- *
557
- * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
558
- * only when the targeted shard's socket was open at least once already
559
- * (`wasEverConnected`), so the registry / resubscribe handshake has run.
560
- * Mutations issued before the very first WS connect to a shard fail fast.
561
- * Opt into queueing-before-first-connect via
562
- * `OfflineQueueOptions.queueBeforeFirstConnect`.
563
- */
564
- async mutation(function_, args, options = {}) {
565
- if (this.closed) {
566
- throw new Error("LunoraClient is closed");
567
- }
568
- const argsRecord = args;
569
- const mutationId = nextId();
570
- const optimisticRollbacks = this.applyOptimisticUpdates(function_.__lunoraRef, argsRecord, options.shardKey, options.optimistic);
571
- if (options.optimisticUpdate) {
572
- this.applyOptimisticUpdate(options.optimisticUpdate, args, options.shardKey, optimisticRollbacks);
573
- }
574
- const conn = this.getConnection(options.shardKey);
575
- const wsState = conn?.wsState ?? "idle";
576
- const hasSocket = conn?.socket !== void 0;
577
- const wasEverConnected = conn?.wasEverConnected ?? false;
578
- const { queueBeforeFirstConnect } = this.offlineQueue;
579
- const connectedGate = wasEverConnected || queueBeforeFirstConnect;
580
- const shouldQueueOffline = this.WebSocketImpl !== void 0 && connectedGate;
581
- const midReconnect = wsState === "connecting" && connectedGate;
582
- if (wsState !== "open" && !hasSocket && shouldQueueOffline || midReconnect) {
583
- const issuingIdentity = this.identityFingerprint();
584
- return new Promise((resolve, reject) => {
585
- const entry = {
586
- args: argsRecord,
587
- functionPath: function_.__lunoraRef,
588
- // Reuse the call's idempotency key as the queue id so the
589
- // replay carries the same `x-lunora-mutation-id` the server
590
- // dedups on.
591
- id: mutationId,
592
- // Persist the stamp alongside the record so a hydrated write
593
- // can only replay under the identity that queued it.
594
- identity: issuingIdentity,
595
- reject: (error) => {
596
- this.queuedIdentities.delete(mutationId);
597
- for (let index = optimisticRollbacks.length - 1; index >= 0; index -= 1) {
598
- optimisticRollbacks[index]?.();
599
- }
600
- reject(error instanceof Error ? error : new Error(String(error)));
601
- },
602
- resolve,
603
- shardKey: options.shardKey
604
- };
605
- this.offlineQueue.enqueue(entry);
606
- if (entry.id !== void 0) {
607
- this.queuedIdentities.set(entry.id, issuingIdentity);
608
- }
609
- });
610
- }
611
- try {
612
- return await this.rpc(function_.__lunoraRef, argsRecord, options.shardKey, { captureBookmark: true, mutationId });
613
- } catch (error) {
614
- for (let index = optimisticRollbacks.length - 1; index >= 0; index -= 1) {
615
- optimisticRollbacks[index]?.();
616
- }
617
- throw error;
618
- }
619
- }
620
- async action(function_, args, options = {}) {
621
- if (this.closed) {
622
- throw new Error("LunoraClient is closed");
623
- }
624
- return await this.rpc(function_.__lunoraRef, args, options.shardKey);
625
- }
626
- // --- Advisor admin ------------------------------------------------------
627
- /**
628
- * Read the cross-shard request distribution for a `.shardBy(...)` table —
629
- * the feed the studio's `hot_shard` advisor lint consumes. Hits the
630
- * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
631
- * cheap per-shard `getMetrics` read out across every live shard and returns
632
- * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
633
- * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
634
- * and `adminToken`, and this client's auth token to match; defaults any
635
- * absent field so an older worker yields an empty-but-valid shape.
636
- */
637
- async shardTraffic(table) {
638
- if (this.closed) {
639
- throw new Error("LunoraClient is closed");
640
- }
641
- const body = await this.adminFetch(SHARD_TRAFFIC_PATH, "POST", { table });
642
- return { failed: body.failed ?? 0, ok: body.ok ?? 0, shards: body.shards ?? [] };
643
- }
644
- // --- Scheduler admin ----------------------------------------------------
645
- /**
646
- * List the functions queued via `runAfter` / `runAt`, soonest-due last
647
- * (the worker returns them in storage order). Hits the admin-gated
648
- * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
649
- * `schedulerDO` namespace and `adminToken`, and this client's auth token
650
- * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
651
- */
652
- async listScheduledJobs() {
653
- if (this.closed) {
654
- throw new Error("LunoraClient is closed");
655
- }
656
- const body = await this.adminFetch(SCHEDULED_PATH, "GET");
657
- return body.records ?? [];
658
- }
659
- /**
660
- * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
661
- * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
662
- * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
663
- * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
664
- * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
665
- * namespace + `adminToken` on the worker and a matching auth token here).
666
- * Defaults any absent field so an older worker still yields a valid shape.
667
- */
668
- async schedulerStatus() {
669
- if (this.closed) {
670
- throw new Error("LunoraClient is closed");
671
- }
672
- const body = await this.adminFetch(SCHEDULED_STATUS_PATH, "GET");
673
- return {
674
- backlog: body.backlog ?? 0,
675
- inFlight: body.inFlight ?? 0,
676
- pools: body.pools ?? []
677
- };
678
- }
679
- /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
680
- async cancelScheduledJob(id) {
681
- if (this.closed) {
682
- throw new Error("LunoraClient is closed");
683
- }
684
- const body = await this.adminFetch(SCHEDULED_CANCEL_PATH, "POST", { id });
685
- return { cancelled: body.cancelled === true };
686
- }
687
- /**
688
- * List the dead-letter jobs: schedules that exhausted their retry budget
689
- * and were parked instead of dropped. These never appear in
690
- * {@link listScheduledJobs} (their live header is gone), so this is the only
691
- * way the studio surfaces a permanently-failed job. Hits the admin-gated
692
- * `GET /_lunora/admin/scheduled/dead`; same preconditions as
693
- * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
694
- */
695
- async listDeadJobs() {
696
- if (this.closed) {
697
- throw new Error("LunoraClient is closed");
698
- }
699
- const body = await this.adminFetch(SCHEDULED_DEAD_PATH, "GET");
700
- return body.records ?? [];
701
- }
702
- /**
703
- * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
704
- * retry budget and fires on the next drain. Returns whether a parked record
705
- * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
706
- */
707
- async retryDeadJob(id) {
708
- if (this.closed) {
709
- throw new Error("LunoraClient is closed");
710
- }
711
- const body = await this.adminFetch(SCHEDULED_DEAD_RETRY_PATH, "POST", { id });
712
- return { retried: body.retried === true };
713
- }
714
- /**
715
- * Permanently drop a dead-letter job by id (the operator has decided not to
716
- * recover it). Returns whether a parked record was removed. Hits the
717
- * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
718
- */
719
- async removeDeadJob(id) {
720
- if (this.closed) {
721
- throw new Error("LunoraClient is closed");
722
- }
723
- const body = await this.adminFetch(SCHEDULED_DEAD_CANCEL_PATH, "POST", { id });
724
- return { removed: body.removed === true };
725
- }
726
- /**
727
- * List a workflow's instances via the admin Workflows proxy
728
- * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
729
- * the `Workflow` binding can't expose. Requires the worker to be built with a
730
- * `workflowsClient` (Cloudflare account id + API token). When one isn't
731
- * configured this does NOT reject: the proxy returns a `200 { configured:
732
- * false }` sentinel, so the result resolves with `configured === false` and an
733
- * empty `instances` list — callers should branch on that flag rather than
734
- * try/catch. (The instance-detail / status endpoints still reject with 501.)
735
- * `name` is the deployed workflow name.
736
- */
737
- async listWorkflowInstances(options) {
738
- if (this.closed) {
739
- throw new Error("LunoraClient is closed");
740
- }
741
- const query = new URLSearchParams({ name: options.name });
742
- if (options.status !== void 0) {
743
- query.set("status", options.status);
744
- }
745
- if (options.page !== void 0) {
746
- query.set("page", String(options.page));
747
- }
748
- if (options.perPage !== void 0) {
749
- query.set("perPage", String(options.perPage));
750
- }
751
- const body = await this.adminFetch(`${WORKFLOWS_INSTANCES_PATH}?${query.toString()}`, "GET");
752
- return {
753
- configured: body.configured,
754
- instances: body.instances ?? [],
755
- page: body.page ?? 1,
756
- perPage: body.perPage ?? options.perPage ?? 0,
757
- totalCount: body.totalCount
758
- };
759
- }
760
- /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
761
- async getWorkflowInstance(options) {
762
- if (this.closed) {
763
- throw new Error("LunoraClient is closed");
764
- }
765
- const query = new URLSearchParams({ id: options.id, name: options.name });
766
- const body = await this.adminFetch(`${WORKFLOWS_INSTANCE_PATH}?${query.toString()}`, "GET");
767
- return {
768
- createdOn: body.createdOn,
769
- endedOn: body.endedOn,
770
- error: body.error,
771
- id: body.id ?? options.id,
772
- output: body.output,
773
- params: body.params,
774
- startedOn: body.startedOn,
775
- status: body.status ?? "unknown",
776
- steps: body.steps ?? []
777
- };
778
- }
779
- /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
780
- async setWorkflowInstanceStatus(options) {
781
- if (this.closed) {
782
- throw new Error("LunoraClient is closed");
783
- }
784
- const body = await this.adminFetch(WORKFLOWS_STATUS_PATH, "POST", { action: options.action, id: options.id, name: options.name });
785
- return { status: body.status ?? "unknown" };
786
- }
787
- /**
788
- * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
789
- * WebSocket. `onJobs` fires with the full list on connect and on every
790
- * change (schedule / cancel / alarm-fire). Reconnects with the client's
791
- * configured backoff. Requires `wsToken` to be set to the admin token (the
792
- * browser can't send an `Authorization` header on a WS). Returns an
793
- * unsubscribe function that closes the socket and stops reconnecting.
794
- */
795
- subscribeScheduledJobs(onJobs) {
796
- if (this.closed) {
797
- throw new Error("LunoraClient is closed");
798
- }
799
- if (this.WebSocketImpl === void 0) {
800
- return () => void 0;
801
- }
802
- const base = joinUrl(deriveWsUrl(this.url), SCHEDULED_WS_PATH);
803
- const reconnect = createReconnect(this.reconnectOptions);
804
- let socket;
805
- let timer;
806
- let closed = false;
807
- const connect = () => {
808
- if (closed || this.WebSocketImpl === void 0) {
809
- return;
810
- }
811
- const url = this.wsToken === void 0 ? base : `${base}?token=${encodeURIComponent(this.wsToken)}`;
812
- socket = new this.WebSocketImpl(url);
813
- socket.addEventListener("open", () => {
814
- reconnect.reset();
815
- });
816
- socket.addEventListener("message", (event) => {
817
- try {
818
- const message = JSON.parse(typeof event.data === "string" ? event.data : "");
819
- if (message.type === "jobs" && Array.isArray(message.records)) {
820
- onJobs(message.records);
821
- }
822
- } catch {
823
- }
824
- });
825
- socket.addEventListener("close", () => {
826
- socket = void 0;
827
- if (!closed) {
828
- timer = setTimeout(connect, reconnect.next());
829
- }
830
- });
831
- socket.addEventListener("error", () => {
832
- });
833
- };
834
- connect();
835
- return () => {
836
- closed = true;
837
- if (timer !== void 0) {
838
- clearTimeout(timer);
839
- }
840
- socket?.close();
841
- };
842
- }
843
- // --- Functions admin ----------------------------------------------------
844
- /**
845
- * List the registered public functions (queries / mutations / actions) with
846
- * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
847
- * the worker must be built with a `functions` registry and `adminToken`, and
848
- * this client's auth token must match. Powers `@lunora/studio`'s function
849
- * runner auto-discovery.
850
- */
851
- async listFunctions() {
852
- if (this.closed) {
853
- throw new Error("LunoraClient is closed");
854
- }
855
- const body = await this.adminFetch(FUNCTIONS_PATH, "GET");
856
- return body.functions ?? [];
857
- }
858
- /**
859
- * List the code-defined cron triggers (the `cronJobs()` map injected on the
860
- * worker), each flattened to its firing `cron` expression. Hits the
861
- * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
862
- * built with a `cronJobs` map and `adminToken`, and this client's auth token
863
- * must match. These are static (Cloudflare exposes no runtime cron
864
- * introspection), so the studio renders them read-only alongside the dynamic
865
- * scheduler jobs.
866
- */
867
- async getCronJobs() {
868
- if (this.closed) {
869
- throw new Error("LunoraClient is closed");
870
- }
871
- const body = await this.adminFetch(CRON_JOBS_PATH, "GET");
872
- return body.jobs ?? [];
873
- }
874
- /**
875
- * Manually fire one code-defined cron job by name — the same dispatch the
876
- * scheduled trigger runs (dispatch the function, or start the durable
877
- * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
878
- * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
879
- * and this client's auth token must match. Resolves when the job has run (a
880
- * function job's shard response is 2xx, or the workflow instance was created)
881
- * and rejects with the dispatch error otherwise.
882
- */
883
- async runCronJob(name) {
884
- if (this.closed) {
885
- throw new Error("LunoraClient is closed");
886
- }
887
- const body = await this.adminFetch(CRON_JOBS_RUN_PATH, "POST", { name });
888
- return { name: body.name ?? name, ran: body.ran === true };
889
- }
890
- /**
891
- * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
892
- * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
893
- * `openApiSpec` and `adminToken`, and this client's auth token must match.
894
- * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
895
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
896
- * document (no `paths`), so callers can render a "not configured" state.
897
- */
898
- async fetchOpenApi() {
899
- if (this.closed) {
900
- throw new Error("LunoraClient is closed");
901
- }
902
- return await this.adminFetch(OPENAPI_PATH, "GET");
903
- }
904
- /**
905
- * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
906
- * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
907
- * `openRpcSpec` and `adminToken`, and this client's auth token must match.
908
- * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
909
- * `POST /_lunora/rpc` transport); it documents the RPC functions only.
910
- * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
911
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
912
- * document (no `methods`), so callers can render a "not configured" state.
913
- */
914
- async fetchOpenRpc() {
915
- if (this.closed) {
916
- throw new Error("LunoraClient is closed");
917
- }
918
- return await this.adminFetch(OPENRPC_PATH, "GET");
919
- }
920
- // --- Storage admin ------------------------------------------------------
921
- /**
922
- * List objects in the storage bucket, optionally under a `prefix` and from a
923
- * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
924
- * endpoint — the worker must be built with a `storageList` function and
925
- * `adminToken`, and this client's auth token must match. Powers
926
- * `@lunora/studio`'s file browser.
927
- */
928
- async listStorageObjects(options = {}) {
929
- if (this.closed) {
930
- throw new Error("LunoraClient is closed");
931
- }
932
- const params = new URLSearchParams();
933
- if (options.prefix !== void 0 && options.prefix !== "") {
934
- params.set("prefix", options.prefix);
935
- }
936
- if (options.cursor !== void 0 && options.cursor !== "") {
937
- params.set("cursor", options.cursor);
938
- }
939
- if (options.limit !== void 0) {
940
- params.set("limit", String(options.limit));
941
- }
942
- if (options.bucket !== void 0 && options.bucket !== "") {
943
- params.set("bucket", options.bucket);
944
- }
945
- const query = params.toString();
946
- const path = query === "" ? STORAGE_PATH : `${STORAGE_PATH}?${query}`;
947
- const body = await this.adminFetch(path, "GET");
948
- return { cursor: body.cursor, objects: body.objects ?? [] };
949
- }
950
- /**
951
- * Delete one object from the storage bucket by key. Hits the admin-gated
952
- * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
953
- * with a `storageDelete` function and `adminToken`. Powers the studio file
954
- * browser's per-row delete; resolves `{ deleted, key }`.
955
- */
956
- async deleteStorageObject(key, options) {
957
- if (this.closed) {
958
- throw new Error("LunoraClient is closed");
959
- }
960
- const path = `${STORAGE_PATH}?key=${encodeURIComponent(key)}${bucketQuery(options?.bucket)}`;
961
- const body = await this.adminFetch(path, "DELETE");
962
- return { deleted: body.deleted ?? true, key: body.key ?? key };
963
- }
964
- /**
965
- * List the storage bucket names the worker exposes, for the studio file
966
- * browser's bucket picker. Hits the admin-gated
967
- * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
968
- * array when the worker configures no `storageBuckets`, i.e. single-bucket).
969
- */
970
- async listStorageBuckets() {
971
- if (this.closed) {
972
- throw new Error("LunoraClient is closed");
973
- }
974
- const body = await this.adminFetch(STORAGE_BUCKETS_PATH, "GET");
975
- return body.buckets ?? [];
976
- }
977
- /**
978
- * Upload one object to the storage bucket. Hits the admin-gated
979
- * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
980
- * optional `contentType` header — the worker must be built with a
981
- * `storageUpload` function and `adminToken`. Powers the studio file
982
- * browser's upload control; resolves `{ etag?, key }`.
983
- */
984
- async uploadStorageObject(options) {
985
- if (this.closed) {
986
- throw new Error("LunoraClient is closed");
987
- }
988
- const path = `${STORAGE_PATH}?key=${encodeURIComponent(options.key)}${bucketQuery(options.bucket)}`;
989
- const body = await this.adminFetch(path, "PUT", options.body, options.contentType);
990
- return { etag: body.etag, key: body.key ?? options.key };
991
- }
992
- /**
993
- * Build a (signed or public) URL for one object. Hits the admin-gated
994
- * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
995
- * with a `storageSignedUrl` function and `adminToken`. Powers the studio
996
- * file browser's copy-URL action; resolves the URL string.
997
- *
998
- * `options.expiresInSeconds` requests a share-link lifetime, which is
999
- * validated/clamped server-side. The options object mirrors the worker's
1000
- * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1001
- * as future fields there).
1002
- */
1003
- async signedStorageUrl(key, options) {
1004
- if (this.closed) {
1005
- throw new Error("LunoraClient is closed");
1006
- }
1007
- const expiresInSeconds = options?.expiresInSeconds;
1008
- const expiryQuery = expiresInSeconds === void 0 ? "" : `&expiresIn=${encodeURIComponent(expiresInSeconds.toString())}`;
1009
- const path = `${STORAGE_URL_PATH}?key=${encodeURIComponent(key)}${expiryQuery}${bucketQuery(options?.bucket)}`;
1010
- const body = await this.adminFetch(path, "GET");
1011
- if (typeof body.url !== "string") {
1012
- throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");
1013
- }
1014
- return body.url;
1015
- }
1016
- // --- Global (D1) tables admin -------------------------------------------
1017
- /**
1018
- * List the `.global()` (D1-backed) tables with their row counts. Hits the
1019
- * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1020
- * be built with a `globalIntrospector` and `adminToken`. Powers the data
1021
- * browser's global mode.
1022
- */
1023
- async listGlobalTables() {
1024
- if (this.closed) {
1025
- throw new Error("LunoraClient is closed");
1026
- }
1027
- return await this.adminFetch(GLOBAL_TABLES_PATH, "GET");
1028
- }
1029
- /**
1030
- * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1031
- * page to rows matching each `column = value` eq constraint — the drill-down a
1032
- * facet-value click applies; the array is JSON-encoded into the `filters`
1033
- * query param and the values are bound server-side.
1034
- */
1035
- async readGlobalTablePage(options) {
1036
- if (this.closed) {
1037
- throw new Error("LunoraClient is closed");
1038
- }
1039
- const params = new URLSearchParams({ table: options.table });
1040
- if (options.limit !== void 0) {
1041
- params.set("limit", String(options.limit));
1042
- }
1043
- if (options.offset !== void 0) {
1044
- params.set("offset", String(options.offset));
1045
- }
1046
- if (options.filters !== void 0 && options.filters.length > 0) {
1047
- params.set("filters", JSON.stringify(options.filters));
1048
- }
1049
- return await this.adminFetch(`${GLOBAL_TABLE_PATH}?${params.toString()}`, "GET");
1050
- }
1051
- /**
1052
- * Summarise the distinct values of one column in a `.global()` table over the
1053
- * active view (the same eq `filters` the browser is previewing) — the global
1054
- * twin of the shard browser's facet. Hits the admin-gated
1055
- * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1056
- * server-side. Powers the global data browser's facet sidebar.
1057
- */
1058
- async facetGlobalColumn(options) {
1059
- if (this.closed) {
1060
- throw new Error("LunoraClient is closed");
1061
- }
1062
- const params = new URLSearchParams({ column: options.column, table: options.table });
1063
- if (options.limit !== void 0) {
1064
- params.set("limit", String(options.limit));
1065
- }
1066
- if (options.filters !== void 0 && options.filters.length > 0) {
1067
- params.set("filters", JSON.stringify(options.filters));
1068
- }
1069
- return await this.adminFetch(`${GLOBAL_FACET_PATH}?${params.toString()}`, "GET");
1070
- }
1071
- // --- Vector indexes admin -----------------------------------------------
1072
- /**
1073
- * List the schema's Vectorize indexes with their declared shape (table,
1074
- * field, dimensions, metric, metadata) and live stats (vector count,
1075
- * processing watermark) when the binding is reachable. Hits the admin-gated
1076
- * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1077
- * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1078
- * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1079
- * from the generated `LUNORA_VECTOR_INDEXES` registry.
1080
- */
1081
- async listVectorIndexes() {
1082
- if (this.closed) {
1083
- throw new Error("LunoraClient is closed");
1084
- }
1085
- const body = await this.adminFetch(VECTOR_INDEXES_PATH, "GET");
1086
- return body.indexes ?? [];
1087
- }
1088
- /**
1089
- * Run a nearest-neighbour similarity query against one vector index: the
1090
- * worker embeds `text` via the index's embedder and returns the top matches.
1091
- * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1092
- * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1093
- * wired (the index lists read-only).
1094
- */
1095
- async queryVectorIndex(options) {
1096
- if (this.closed) {
1097
- throw new Error("LunoraClient is closed");
1098
- }
1099
- const body = await this.adminFetch(VECTOR_QUERY_PATH, "POST", options);
1100
- return body.matches ?? [];
1101
- }
1102
- // --- Auth admin ---------------------------------------------------------
1103
- /**
1104
- * List authenticated users, paged and optionally searched / filtered / sorted.
1105
- * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1106
- * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1107
- * users dashboard.
1108
- */
1109
- async listAuthUsers(options = {}) {
1110
- if (this.closed) {
1111
- throw new Error("LunoraClient is closed");
1112
- }
1113
- const path = withQuery(AUTH_USERS_PATH, {
1114
- filterField: options.filterField,
1115
- filterValue: options.filterValue,
1116
- limit: options.limit,
1117
- offset: options.offset,
1118
- search: options.search,
1119
- searchField: options.searchField,
1120
- sortBy: options.sortBy,
1121
- sortDirection: options.sortDirection
1122
- });
1123
- return await this.adminFetch(path, "GET");
1124
- }
1125
- /**
1126
- * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1127
- * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1128
- * `data` carries any app-defined `user.additionalFields`.
1129
- */
1130
- async createAuthUser(input) {
1131
- return await this.adminFetch(AUTH_CREATE_USER_PATH, "POST", input);
1132
- }
1133
- /** Set a user's role (string, or array joined comma-wise server-side). */
1134
- async setAuthUserRole(input) {
1135
- return await this.adminFetch(AUTH_SET_ROLE_PATH, "POST", input);
1136
- }
1137
- /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1138
- async banAuthUser(input) {
1139
- return await this.adminFetch(AUTH_BAN_PATH, "POST", input);
1140
- }
1141
- /** Lift a user's ban. */
1142
- async unbanAuthUser(input) {
1143
- return await this.adminFetch(AUTH_UNBAN_PATH, "POST", input);
1144
- }
1145
- /** Set a user's password (admin override — no current-password challenge). */
1146
- async setAuthUserPassword(input) {
1147
- await this.adminFetch(AUTH_SET_PASSWORD_PATH, "POST", input);
1148
- }
1149
- /** Permanently delete a user and revoke their sessions. */
1150
- async removeAuthUser(input) {
1151
- await this.adminFetch(AUTH_REMOVE_USER_PATH, "POST", input);
1152
- }
1153
- /**
1154
- * Mint an impersonation session for a user, returning its bearer `token`.
1155
- * The caller is responsible for using the token (e.g. setting the session
1156
- * cookie); the server performs no cookie round-trip.
1157
- */
1158
- async impersonateAuthUser(input) {
1159
- return await this.adminFetch(AUTH_IMPERSONATE_PATH, "POST", input);
1160
- }
1161
- /** Revoke a single session by its id (force sign-out of one device). */
1162
- async revokeAuthSession(input) {
1163
- await this.adminFetch(AUTH_REVOKE_SESSION_PATH, "POST", input);
1164
- }
1165
- /** Revoke every session for a user (force sign-out everywhere). */
1166
- async revokeAuthUserSessions(input) {
1167
- await this.adminFetch(AUTH_REVOKE_SESSIONS_PATH, "POST", input);
1168
- }
1169
- /**
1170
- * Report which auth dashboard surfaces are available — derived server-side
1171
- * from the enabled better-auth plugins. The studio renders only the panels
1172
- * whose capability is `true`.
1173
- */
1174
- async getAuthCapabilities() {
1175
- return await this.adminFetch(AUTH_CAPABILITIES_PATH, "GET");
1176
- }
1177
- /** Update a user's fields (name/email/app-defined `additionalFields`). */
1178
- async updateAuthUser(input) {
1179
- return await this.adminFetch(AUTH_UPDATE_USER_PATH, "POST", input);
1180
- }
1181
- /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1182
- async listAuthAccounts(input) {
1183
- return await this.adminFetch(withQuery(AUTH_ACCOUNTS_PATH, { userId: input.userId }), "GET");
1184
- }
1185
- /** Unlink a linked account from a user. */
1186
- async unlinkAuthAccount(input) {
1187
- await this.adminFetch(AUTH_UNLINK_ACCOUNT_PATH, "POST", input);
1188
- }
1189
- /** List a user's registered passkeys (requires the passkey plugin). */
1190
- async listAuthPasskeys(input) {
1191
- return await this.adminFetch(withQuery(AUTH_PASSKEYS_PATH, { userId: input.userId }), "GET");
1192
- }
1193
- /** Delete a passkey by id (requires the passkey plugin). */
1194
- async deleteAuthPasskey(input) {
1195
- await this.adminFetch(AUTH_DELETE_PASSKEY_PATH, "POST", input);
1196
- }
1197
- /** Disable two-factor auth for a user (requires the two-factor plugin). */
1198
- async disableAuthTwoFactor(input) {
1199
- await this.adminFetch(AUTH_DISABLE_2FA_PATH, "POST", input);
1200
- }
1201
- /** List organizations, paged (requires the organization plugin). */
1202
- async listAuthOrganizations(options = {}) {
1203
- return await this.adminFetch(withQuery(AUTH_ORGS_PATH, { limit: options.limit, offset: options.offset }), "GET");
1204
- }
1205
- /** List the members of an organization (requires the organization plugin). */
1206
- async listAuthOrgMembers(input) {
1207
- const path = withQuery(AUTH_ORG_MEMBERS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1208
- return await this.adminFetch(path, "GET");
1209
- }
1210
- /** List an organization's pending invitations (requires the organization plugin). */
1211
- async listAuthOrgInvitations(input) {
1212
- const path = withQuery(AUTH_ORG_INVITATIONS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1213
- return await this.adminFetch(path, "GET");
1214
- }
1215
- /** Remove a member from an organization. */
1216
- async removeAuthOrgMember(input) {
1217
- await this.adminFetch(AUTH_REMOVE_MEMBER_PATH, "POST", input);
1218
- }
1219
- /** Cancel a pending organization invitation. */
1220
- async cancelAuthOrgInvitation(input) {
1221
- await this.adminFetch(AUTH_CANCEL_INVITATION_PATH, "POST", input);
1222
- }
1223
- /** List auth sessions, paged and optionally filtered to one user. */
1224
- async listAuthSessions(options = {}) {
1225
- if (this.closed) {
1226
- throw new Error("LunoraClient is closed");
1227
- }
1228
- const params = new URLSearchParams();
1229
- if (options.userId !== void 0 && options.userId !== "") {
1230
- params.set("userId", options.userId);
1231
- }
1232
- if (options.limit !== void 0) {
1233
- params.set("limit", String(options.limit));
1234
- }
1235
- if (options.offset !== void 0) {
1236
- params.set("offset", String(options.offset));
1237
- }
1238
- const query = params.toString();
1239
- return await this.adminFetch(query === "" ? AUTH_SESSIONS_PATH : `${AUTH_SESSIONS_PATH}?${query}`, "GET");
1240
- }
1241
- // --- Subscriptions ------------------------------------------------------
1242
- subscribe(function_, args, callback, options = {}) {
1243
- if (this.closed) {
1244
- throw new Error("LunoraClient is closed");
1245
- }
1246
- const argsRecord = args ?? {};
1247
- const key = SubscriptionRegistry.key(function_.__lunoraRef, argsRecord, options.shardKey);
1248
- let state = this.subscriptions.get(key);
1249
- const subscriptionCallback = callback;
1250
- const errorCallback = options.onError;
1251
- if (!state) {
1252
- this.nextSubId += 1;
1253
- const id = `sub_${this.nextSubId.toString()}`;
1254
- const argsKey = stableStringify(argsRecord);
1255
- const cached = this.takeHydratedCache(function_.__lunoraRef, argsKey, options.shardKey);
1256
- state = {
1257
- acked: false,
1258
- args: argsRecord,
1259
- argsKey,
1260
- callbacks: /* @__PURE__ */ new Set(),
1261
- errorCallbacks: /* @__PURE__ */ new Set(),
1262
- fn: function_,
1263
- id,
1264
- lastValue: cached?.value,
1265
- serverCursor: cached?.serverCursor,
1266
- serverVersion: 0,
1267
- shardKey: options.shardKey,
1268
- ...cached?.serverEpoch === void 0 ? {} : { serverEpoch: cached.serverEpoch }
1269
- };
1270
- this.subscriptions.add(state);
1271
- }
1272
- state.callbacks.add(subscriptionCallback);
1273
- if (errorCallback) {
1274
- state.errorCallbacks.add(errorCallback);
1275
- }
1276
- if (state.lastValue !== void 0) {
1277
- try {
1278
- subscriptionCallback(state.lastValue);
1279
- } catch {
1280
- }
1281
- }
1282
- this.ensureSocket(options.shardKey);
1283
- this.sendSubscribeIfOpen(state);
1284
- const subscriptionState = state;
1285
- return () => {
1286
- subscriptionState.callbacks.delete(subscriptionCallback);
1287
- if (errorCallback) {
1288
- subscriptionState.errorCallbacks.delete(errorCallback);
1289
- }
1290
- if (subscriptionState.callbacks.size === 0) {
1291
- const conn = this.getConnection(subscriptionState.shardKey);
1292
- const ok = conn ? sendOn(conn, { id: subscriptionState.id, type: "unsubscribe" }) : false;
1293
- if (!ok && conn) {
1294
- conn.pendingUnsubscribes.push(subscriptionState.id);
1295
- }
1296
- this.subscriptions.remove(subscriptionState);
1297
- }
1298
- };
1299
- }
1300
- /**
1301
- * Open a streaming query. The function reference must be a
1302
- * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1303
- * the type constraint catches accidental use of a query/mutation/action
1304
- * reference at compile time. The returned iterable yields one element per
1305
- * chunk frame the server pushes, terminating when the server sends
1306
- * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1307
- * rejection on the next `next()`.
1308
- *
1309
- * Streams ride the same WS as subscriptions and share the unsubscribe
1310
- * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1311
- * which the DO recognises as an abort signal for the in-flight iterator.
1312
- *
1313
- * Stream-start frames buffered while the socket is (re)connecting are
1314
- * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1315
- * cap drops the oldest queued frame (and fails its consumer) so a stuck
1316
- * reconnect can't OOM the page.
1317
- */
1318
- stream(function_, args, options = {}) {
1319
- if (this.closed) {
1320
- throw new Error("LunoraClient is closed");
1321
- }
1322
- if (this.WebSocketImpl === void 0) {
1323
- throw new Error("LunoraClient: streams require a WebSocket implementation");
1324
- }
1325
- this.nextStreamId += 1;
1326
- const id = `stream_${this.nextStreamId.toString()}`;
1327
- const { shardKey } = options;
1328
- const argsRecord = args ?? {};
1329
- const { handle, iterable } = createStream({
1330
- maxBuffer: options.maxBuffer,
1331
- onCancel: () => {
1332
- const conn2 = this.getConnection(shardKey);
1333
- if (conn2) {
1334
- sendOn(conn2, { id, type: "unsubscribe" });
1335
- }
1336
- this.streams.delete(id);
1337
- }
1338
- });
1339
- this.streams.set(id, { handle, shardKey });
1340
- this.ensureSocket(shardKey);
1341
- const conn = this.getConnection(shardKey);
1342
- const message = {
1343
- id,
1344
- query: { args: argsRecord, functionPath: function_.__lunoraRef, shardKey },
1345
- type: "stream"
1346
- };
1347
- const sentImmediately = conn?.wsState === "open" && sendOn(conn, message);
1348
- if (!sentImmediately && conn) {
1349
- conn.pendingStreams = conn.pendingStreams ?? [];
1350
- while (conn.pendingStreams.length >= MAX_PENDING_STREAMS) {
1351
- const dropped = conn.pendingStreams.shift();
1352
- const droppedId = dropped?.id;
1353
- const droppedStream = droppedId ? this.streams.get(droppedId) : void 0;
1354
- if (droppedStream) {
1355
- droppedStream.handle.fail(
1356
- Object.assign(new Error("stream-start frame evicted while socket was unreachable"), { code: "STREAM_QUEUE_OVERFLOW" })
1357
- );
1358
- this.streams.delete(droppedId);
1359
- }
1360
- }
1361
- conn.pendingStreams.push(message);
1362
- }
1363
- return iterable;
1364
- }
1365
- close() {
1366
- this.closed = true;
1367
- for (const stream of this.streams.values()) {
1368
- stream.handle.fail(Object.assign(new Error("LunoraClient closed"), { code: "CLIENT_CLOSED" }));
1369
- }
1370
- this.streams.clear();
1371
- for (const conn of this.connections.values()) {
1372
- if (conn.reconnectTimer !== void 0) {
1373
- clearTimeout(conn.reconnectTimer);
1374
- conn.reconnectTimer = void 0;
1375
- }
1376
- if (conn.connectTimer !== void 0) {
1377
- clearTimeout(conn.connectTimer);
1378
- conn.connectTimer = void 0;
1379
- }
1380
- this.stopHeartbeat(conn);
1381
- if (conn.socket) {
1382
- try {
1383
- conn.socket.close();
1384
- } catch {
1385
- }
1386
- conn.socket = void 0;
1387
- }
1388
- conn.wsState = "closed";
1389
- }
1390
- this.offlineQueue.clear();
1391
- this.queuedIdentities.clear();
1392
- if (this.cacheFlushTimer !== void 0) {
1393
- clearTimeout(this.cacheFlushTimer);
1394
- this.cacheFlushTimer = void 0;
1395
- }
1396
- if (this.pendingCacheWrites.size > 0) {
1397
- this.flushQueryCacheWrites().catch(() => void 0);
1398
- }
1399
- this.authTokenListeners.clear();
1400
- this.statusListeners.clear();
1401
- this.tokenExpiredListeners.clear();
1402
- this.whisperHandlers.clear();
1403
- }
1404
- // --- Internals ----------------------------------------------------------
1405
- /**
1406
- * Restore offline mutations persisted in a prior session and open a socket
1407
- * for each shard they target so they flush once the WS reconnects. Failures
1408
- * are swallowed — a broken durable store must not stop the client booting.
1409
- */
1410
- async hydratePersistedQueue() {
1411
- try {
1412
- const shardKeys = await this.offlineQueue.hydrate();
1413
- for (const shardKey of shardKeys) {
1414
- this.ensureSocket(shardKey);
1415
- }
1416
- } catch {
1417
- }
1418
- }
1419
- /**
1420
- * Load every cached query into {@link hydratedQueryCache} so the next
1421
- * `subscribe()` for each key seeds its initial value off disk. A
1422
- * subscription created before this resolves simply misses the cache (it
1423
- * gets a live snapshot as before); the gate at seed time also drops any
1424
- * entry whose stamped identity no longer matches the current one.
1425
- */
1426
- async hydrateQueryCache() {
1427
- if (!this.queryCache) {
1428
- return;
1429
- }
1430
- try {
1431
- const entries = await this.queryCache.load();
1432
- for (const { key, ...entry } of entries) {
1433
- this.hydratedQueryCache.set(key, entry);
1434
- }
1435
- } catch {
1436
- }
1437
- }
1438
- /**
1439
- * Consume the hydrated read-cache entry for a key (if any), gated on
1440
- * identity. The entry is removed whether or not it matches — the cache only
1441
- * ever seeds a subscription's first value. A mismatch (the cache was written
1442
- * under a different identity) yields `undefined` so a signed-out cache never
1443
- * leaks into a new session.
1444
- */
1445
- takeHydratedCache(functionPath, argsKey, shardKey) {
1446
- const key = queryCacheKey(functionPath, argsKey, shardKey);
1447
- const entry = this.hydratedQueryCache.get(key);
1448
- if (entry === void 0) {
1449
- return void 0;
1450
- }
1451
- this.hydratedQueryCache.delete(key);
1452
- return entry.identity === this.identityFingerprint() ? entry : void 0;
1453
- }
1454
- /**
1455
- * Queue a coalesced read-cache write for a subscription's current value.
1456
- * Latest-wins per key; flushed on a short debounce so a delta burst writes
1457
- * once. No-op when the read cache is disabled or the value is undefined
1458
- * (nothing to render offline).
1459
- */
1460
- persistQueryValue(state) {
1461
- if (!this.queryCache || state.lastValue === void 0) {
1462
- return;
1463
- }
1464
- const key = queryCacheKey(state.fn.__lunoraRef, state.argsKey, state.shardKey);
1465
- this.pendingCacheWrites.set(key, {
1466
- identity: this.identityFingerprint(),
1467
- serverCursor: state.serverCursor,
1468
- ts: Date.now(),
1469
- value: state.lastValue,
1470
- ...state.serverEpoch === void 0 ? {} : { serverEpoch: state.serverEpoch }
1471
- });
1472
- this.cacheFlushTimer ??= setTimeout(() => {
1473
- this.flushQueryCacheWrites().catch(() => void 0);
1474
- }, QUERY_CACHE_DEBOUNCE_MS);
1475
- }
1476
- /** Drain {@link pendingCacheWrites} to the durable store. */
1477
- async flushQueryCacheWrites() {
1478
- this.cacheFlushTimer = void 0;
1479
- const { queryCache } = this;
1480
- if (!queryCache) {
1481
- this.pendingCacheWrites.clear();
1482
- return;
1483
- }
1484
- const batch = [...this.pendingCacheWrites.entries()];
1485
- this.pendingCacheWrites.clear();
1486
- await Promise.allSettled(batch.map(([key, entry]) => queryCache.put(key, entry)));
1487
- }
1488
- /** Derive the aggregate status from the per-shard socket states. */
1489
- computeStatus() {
1490
- const conns = [...this.connections.values()];
1491
- if (conns.length === 0) {
1492
- return "idle";
1493
- }
1494
- if (conns.some((conn) => conn.wsState === "open")) {
1495
- return "connected";
1496
- }
1497
- if (conns.some((conn) => conn.wsState === "connecting")) {
1498
- return "connecting";
1499
- }
1500
- return "offline";
1501
- }
1502
- /** Recompute the aggregate status and notify listeners if it changed. */
1503
- emitConnectionStatus() {
1504
- const next = this.computeStatus();
1505
- if (next === this.lastStatus) {
1506
- return;
1507
- }
1508
- this.lastStatus = next;
1509
- for (const listener of this.statusListeners) {
1510
- try {
1511
- listener(next);
1512
- } catch {
1513
- }
1514
- }
1515
- }
1516
- /**
1517
- * Apply an optimistic update to every subscription that matches the
1518
- * mutation's function ref, shard key, and args, returning the rollback
1519
- * callbacks to invoke if the mutation later fails. Scoping to the same
1520
- * (fn, shardKey, args) keeps one user's mutation from clobbering another
1521
- * subscriber's value on the same function (e.g. two users on different rooms).
1522
- */
1523
- applyOptimisticUpdates(functionRef, argsRecord, mutationShardKey, optimistic) {
1524
- const optimisticRollbacks = [];
1525
- if (!optimistic) {
1526
- return optimisticRollbacks;
1527
- }
1528
- const mutationArgsKey = stableStringify(argsRecord);
1529
- for (const state of this.subscriptions.all()) {
1530
- if (state.fn.__lunoraRef !== functionRef || state.shardKey !== mutationShardKey || state.argsKey !== mutationArgsKey) {
1531
- continue;
1532
- }
1533
- const rollback = applyOptimisticToState(state, optimistic);
1534
- if (rollback) {
1535
- optimisticRollbacks.push(rollback);
1536
- }
1537
- }
1538
- return optimisticRollbacks;
1539
- }
1540
- /**
1541
- * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
1542
- * to the live subscription registry, appending each `setQuery` write's
1543
- * rollback to `optimisticRollbacks` (the same LIFO list the legacy path uses,
1544
- * unwound on settle/error). A throwing callback unwinds its own partial
1545
- * writes — LIFO over just the rollbacks it produced — and is swallowed, so a
1546
- * buggy optimistic update can never fail the mutation or leave a partial
1547
- * patch live, mirroring the legacy transform's throw handling.
1548
- */
1549
- applyOptimisticUpdate(optimisticUpdate, args, shardKey, optimisticRollbacks) {
1550
- const { rollbacks, store } = createLocalStore(this.subscriptions, shardKey, writeOptimisticToState, stableStringify);
1551
- try {
1552
- optimisticUpdate(store, args);
1553
- } catch {
1554
- for (let index = rollbacks.length - 1; index >= 0; index -= 1) {
1555
- rollbacks[index]?.();
1556
- }
1557
- return;
1558
- }
1559
- optimisticRollbacks.push(...rollbacks);
1560
- }
1561
- getConnection(shardKey) {
1562
- return this.connections.get(connectionKey(shardKey));
1563
- }
1564
- getOrCreateConnection(shardKey) {
1565
- const key = connectionKey(shardKey);
1566
- let conn = this.connections.get(key);
1567
- if (!conn) {
1568
- conn = {
1569
- connectTimer: void 0,
1570
- heartbeatTimer: void 0,
1571
- pendingUnsubscribes: [],
1572
- reconnect: createReconnect(this.reconnectOptions),
1573
- reconnectTimer: void 0,
1574
- shardKey,
1575
- socket: void 0,
1576
- wasEverConnected: false,
1577
- wsState: "idle"
1578
- };
1579
- this.connections.set(key, conn);
1580
- }
1581
- return conn;
1582
- }
1583
- wsUrlFor(shardKey) {
1584
- const params = [];
1585
- if (shardKey !== void 0) {
1586
- params.push(`shard=${encodeURIComponent(shardKey)}`);
1587
- }
1588
- if (this.wsToken !== void 0) {
1589
- params.push(`token=${encodeURIComponent(this.wsToken)}`);
1590
- }
1591
- if (params.length === 0) {
1592
- return this.wsUrl;
1593
- }
1594
- const separator = this.wsUrl.includes("?") ? "&" : "?";
1595
- return `${this.wsUrl}${separator}${params.join("&")}`;
1596
- }
1597
- /**
1598
- * Build the outbound RPC headers: JSON content type, optional bearer auth,
1599
- * the optional mutation-replay idempotency key, and the D1 read-your-writes
1600
- * bookmark when the caller opted into `attachBookmark`. The mutation id
1601
- * rides both the direct send and any offline-queue replay of the same write,
1602
- * so a mutation the server already committed returns its cached result
1603
- * instead of running twice.
1604
- */
1605
- rpcRequestHeaders(flags) {
1606
- const headers = { "content-type": "application/json" };
1607
- if (this.authToken) {
1608
- headers["authorization"] = `Bearer ${this.authToken}`;
1609
- }
1610
- if (flags.mutationId) {
1611
- headers["x-lunora-mutation-id"] = flags.mutationId;
1612
- }
1613
- if (flags.attachBookmark) {
1614
- const bookmark = this.bookmark.get();
1615
- if (bookmark) {
1616
- headers["x-d1-bookmark"] = bookmark;
1617
- }
1618
- }
1619
- return headers;
1620
- }
1621
- async rpc(functionPath, args, shardKey, flags = {}) {
1622
- if (!this.fetchImpl) {
1623
- throw new Error("LunoraClient: no `fetch` implementation available");
1624
- }
1625
- const headers = this.rpcRequestHeaders(flags);
1626
- const response = await this.fetchImpl(joinUrl(this.url, RPC_PATH), {
1627
- body: JSON.stringify({ args, functionPath, shardKey }),
1628
- headers,
1629
- method: "POST"
1630
- });
1631
- if (flags.captureBookmark) {
1632
- const value = response.headers.get("x-d1-bookmark");
1633
- if (value) {
1634
- this.bookmark.set(value);
1635
- }
1636
- }
1637
- let body;
1638
- try {
1639
- body = await response.json();
1640
- } catch {
1641
- const statusText = response.statusText ? ` ${response.statusText}` : "";
1642
- throw new Error(`LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
1643
- }
1644
- if ("error" in body) {
1645
- const error = new Error(body.error.message);
1646
- error.code = body.error.code;
1647
- throw error;
1648
- }
1649
- if (!response.ok) {
1650
- const statusText = response.statusText ? ` ${response.statusText}` : "";
1651
- throw new Error(`LunoraClient: request failed (status ${response.status.toString()}${statusText})`);
1652
- }
1653
- return body.result;
1654
- }
1655
- /**
1656
- * Authenticated request to a non-RPC admin endpoint (the scheduler list /
1657
- * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
1658
- * worker's `{ error: { code, message } }` envelope as a coded `Error` —
1659
- * mirroring {@link rpc} so callers see the same failure shape.
1660
- */
1661
- async adminFetch(path, method, payload, contentType) {
1662
- if (!this.fetchImpl) {
1663
- throw new Error("LunoraClient: no `fetch` implementation available");
1664
- }
1665
- const headers = {};
1666
- if (this.authToken) {
1667
- headers["authorization"] = `Bearer ${this.authToken}`;
1668
- }
1669
- const isBinary = payload instanceof ArrayBuffer || payload instanceof Blob;
1670
- let requestBody;
1671
- if (payload === void 0) {
1672
- requestBody = void 0;
1673
- } else if (isBinary) {
1674
- requestBody = payload;
1675
- if (contentType !== void 0) {
1676
- headers["content-type"] = contentType;
1677
- }
1678
- } else {
1679
- requestBody = JSON.stringify(payload);
1680
- headers["content-type"] = "application/json";
1681
- }
1682
- const response = await this.fetchImpl(joinUrl(this.url, path), {
1683
- body: requestBody,
1684
- headers,
1685
- method
1686
- });
1687
- let body;
1688
- try {
1689
- body = await response.json();
1690
- } catch {
1691
- const statusText = response.statusText ? ` ${response.statusText}` : "";
1692
- throw new Error(`LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
1693
- }
1694
- if (typeof body === "object" && body !== null && "error" in body) {
1695
- const envelope = body.error;
1696
- const error = new Error(envelope.message ?? "admin request failed");
1697
- error.code = envelope.code;
1698
- throw error;
1699
- }
1700
- if (!response.ok) {
1701
- const statusText = response.statusText ? ` ${response.statusText}` : "";
1702
- throw new Error(`LunoraClient: admin request failed (status ${response.status.toString()}${statusText})`);
1703
- }
1704
- return body;
1705
- }
1706
- /**
1707
- * Resolve the effective connection context for a shard: the most-recently
1708
- * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
1709
- * back to the imperative {@link setConnectionContext} override, then the
1710
- * client-wide default. Returns `undefined` when none apply.
1711
- */
1712
- effectiveConnectionContext(key) {
1713
- const holders = this.connectionContextHolders.get(key);
1714
- if (holders && holders.length > 0) {
1715
- return holders[holders.length - 1]?.context;
1716
- }
1717
- return this.connectionContexts.get(key) ?? this.defaultConnectionContext;
1718
- }
1719
- /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
1720
- refreshConnectionContext(key) {
1721
- const conn = this.connections.get(key);
1722
- if (conn?.wsState === "open") {
1723
- this.sendConnectEnvelope(conn);
1724
- }
1725
- }
1726
- /**
1727
- * Send the one-shot `connect` envelope on an open shard socket. Always sent
1728
- * once per socket open, so the server's `onConnect` hooks fire symmetrically
1729
- * with `onDisconnect` (which the DO dispatches unconditionally at close for
1730
- * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
1731
- * hooks are registered, so the single frame costs nothing in the common case.
1732
- *
1733
- * The shard's registered context (or the client-wide default) rides along
1734
- * when one is set — the DO records it on the attachment for replay to
1735
- * `onDisconnect`. A socket with no registered context still announces itself;
1736
- * the envelope simply omits `context`, which is optional on the wire.
1737
- * Register a context — e.g. `setConnectionContext({})` — to attach app state
1738
- * to the lifecycle dispatch.
1739
- */
1740
- sendConnectEnvelope(conn) {
1741
- const context = this.effectiveConnectionContext(connectionKey(conn.shardKey));
1742
- sendOn(conn, {
1743
- id: "connect",
1744
- type: "connect",
1745
- ...context === void 0 ? {} : { context }
1746
- });
1747
- }
1748
- ensureSocket(shardKey) {
1749
- if (this.closed || this.WebSocketImpl === void 0) {
1750
- return;
1751
- }
1752
- const conn = this.getOrCreateConnection(shardKey);
1753
- if (conn.wsState === "open" || conn.wsState === "connecting") {
1754
- return;
1755
- }
1756
- conn.wsState = "connecting";
1757
- this.emitConnectionStatus();
1758
- const socket = new this.WebSocketImpl(this.wsUrlFor(shardKey));
1759
- conn.socket = socket;
1760
- if (this.connectTimeoutMs > 0) {
1761
- conn.connectTimer = setTimeout(() => {
1762
- conn.connectTimer = void 0;
1763
- if (conn.socket !== socket || conn.wsState !== "connecting") {
1764
- return;
1765
- }
1766
- try {
1767
- socket.close();
1768
- } catch {
1769
- }
1770
- this.handleDisconnect(conn);
1771
- }, this.connectTimeoutMs);
1772
- }
1773
- socket.addEventListener("open", () => {
1774
- if (conn.socket !== socket) {
1775
- return;
1776
- }
1777
- if (conn.connectTimer !== void 0) {
1778
- clearTimeout(conn.connectTimer);
1779
- conn.connectTimer = void 0;
1780
- }
1781
- conn.wsState = "open";
1782
- conn.wasEverConnected = true;
1783
- conn.reconnect.reset();
1784
- this.emitConnectionStatus();
1785
- this.sendConnectEnvelope(conn);
1786
- this.markShardPendingAck(shardKey);
1787
- for (const state of this.subscriptions.all()) {
1788
- if (connectionKey(state.shardKey) === connectionKey(shardKey)) {
1789
- this.sendSubscribeIfOpen(state);
1790
- }
1791
- }
1792
- if (conn.pendingUnsubscribes.length > 0) {
1793
- const pending = conn.pendingUnsubscribes;
1794
- conn.pendingUnsubscribes = [];
1795
- for (const id of pending) {
1796
- sendOn(conn, { id, type: "unsubscribe" });
1797
- }
1798
- }
1799
- if (conn.pendingStreams && conn.pendingStreams.length > 0) {
1800
- const pending = conn.pendingStreams;
1801
- conn.pendingStreams = [];
1802
- for (const message of pending) {
1803
- sendOn(conn, message);
1804
- }
1805
- }
1806
- const byTopic = this.whisperHandlers.get(connectionKey(shardKey));
1807
- if (byTopic) {
1808
- for (const topic of byTopic.keys()) {
1809
- sendOn(conn, { topic, type: "whisper_subscribe" });
1810
- }
1811
- }
1812
- this.flushOfflineQueue(shardKey).catch(() => void 0);
1813
- this.startHeartbeat(conn);
1814
- });
1815
- socket.addEventListener("message", (event) => {
1816
- this.handleServerMessage(event.data, shardKey);
1817
- });
1818
- socket.addEventListener("close", (event) => {
1819
- if (conn.socket !== socket) {
1820
- return;
1821
- }
1822
- if (event?.code === 4001) {
1823
- this.notifyTokenExpired();
1824
- }
1825
- this.handleDisconnect(conn);
1826
- });
1827
- socket.addEventListener("error", () => {
1828
- if (conn.socket !== socket) {
1829
- return;
1830
- }
1831
- if (conn.wsState === "connecting" || conn.wsState === "open") {
1832
- this.handleDisconnect(conn);
1833
- }
1834
- });
1835
- }
1836
- handleDisconnect(conn) {
1837
- if (this.closed) {
1838
- return;
1839
- }
1840
- if (conn.wsState === "idle" || conn.wsState === "closed") {
1841
- return;
1842
- }
1843
- this.stopHeartbeat(conn);
1844
- if (conn.connectTimer !== void 0) {
1845
- clearTimeout(conn.connectTimer);
1846
- conn.connectTimer = void 0;
1847
- }
1848
- conn.socket = void 0;
1849
- conn.wsState = "idle";
1850
- this.emitConnectionStatus();
1851
- this.markShardPendingAck(conn.shardKey);
1852
- if (this.WebSocketImpl === void 0) {
1853
- return;
1854
- }
1855
- const delay = conn.reconnect.next();
1856
- conn.reconnectTimer = setTimeout(() => {
1857
- conn.reconnectTimer = void 0;
1858
- this.ensureSocket(conn.shardKey);
1859
- }, delay);
1860
- }
1861
- /**
1862
- * Begin the keepalive heartbeat on an open connection. Each tick sends a
1863
- * {@link WS_KEEPALIVE_PING} text frame the server answers from its
1864
- * hibernation auto-response without waking the DO. A no-op when the
1865
- * heartbeat is disabled (an interval of zero or less); idempotent — any
1866
- * existing timer is cleared first so a reconnect can't leak intervals.
1867
- */
1868
- startHeartbeat(conn) {
1869
- this.stopHeartbeat(conn);
1870
- if (this.heartbeatIntervalMs <= 0) {
1871
- return;
1872
- }
1873
- conn.heartbeatTimer = setInterval(() => {
1874
- if (conn.wsState !== "open" || !conn.socket) {
1875
- return;
1876
- }
1877
- try {
1878
- conn.socket.send(WS_KEEPALIVE_PING);
1879
- } catch {
1880
- }
1881
- }, this.heartbeatIntervalMs);
1882
- }
1883
- /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
1884
- // eslint-disable-next-line class-methods-use-this -- cohesive connection helper; pairs with startHeartbeat
1885
- stopHeartbeat(conn) {
1886
- if (conn.heartbeatTimer !== void 0) {
1887
- clearInterval(conn.heartbeatTimer);
1888
- conn.heartbeatTimer = void 0;
1889
- }
1890
- }
1891
- /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
1892
- markShardPendingAck(shardKey) {
1893
- const key = connectionKey(shardKey);
1894
- for (const state of this.subscriptions.all()) {
1895
- if (connectionKey(state.shardKey) === key) {
1896
- state.acked = false;
1897
- }
1898
- }
1899
- }
1900
- sendSubscribeIfOpen(state) {
1901
- const conn = this.getConnection(state.shardKey);
1902
- if (conn?.wsState !== "open" || state.acked) {
1903
- return;
1904
- }
1905
- const table = state.fn.__lunoraTable ?? state.fn.__lunoraRef;
1906
- sendOn(conn, {
1907
- id: state.id,
1908
- // `sinceSeq` rides along when we hold a persisted cursor for this
1909
- // sub (a hydrated read or an earlier frame), so the server can
1910
- // resume instead of re-snapshotting. Omitted on a cold sub.
1911
- query: {
1912
- args: state.args,
1913
- functionPath: state.fn.__lunoraRef,
1914
- table,
1915
- ...state.serverCursor === void 0 ? {} : { sinceSeq: state.serverCursor },
1916
- ...state.serverEpoch === void 0 ? {} : { sinceEpoch: state.serverEpoch }
1917
- },
1918
- type: "subscribe"
1919
- });
1920
- }
1921
- handleServerMessage(raw, shardKey) {
1922
- const text = decodeServerFrame(raw);
1923
- if (text === void 0) {
1924
- return;
1925
- }
1926
- let message;
1927
- try {
1928
- message = JSON.parse(text);
1929
- } catch {
1930
- return;
1931
- }
1932
- switch (message.type) {
1933
- case "ack": {
1934
- const state = this.subscriptions.getById(message.id);
1935
- if (state) {
1936
- state.acked = true;
1937
- }
1938
- return;
1939
- }
1940
- case "chunk": {
1941
- const { data, id } = message;
1942
- const stream = this.streams.get(id);
1943
- stream?.handle.push(data);
1944
- return;
1945
- }
1946
- case "complete": {
1947
- this.handleCompleteMessage(message.id);
1948
- return;
1949
- }
1950
- case "data":
1951
- case "delta": {
1952
- this.handleDataMessage(message);
1953
- return;
1954
- }
1955
- case "error": {
1956
- this.handleErrorMessage(message);
1957
- break;
1958
- }
1959
- case "resume": {
1960
- this.handleResumeMessage(message);
1961
- break;
1962
- }
1963
- case "whisper": {
1964
- this.dispatchWhisper(message, shardKey);
1965
- break;
1966
- }
1967
- }
1968
- }
1969
- handleErrorMessage(message) {
1970
- const errorCode = message.error?.code;
1971
- if (errorCode === "TOKEN_EXPIRED") {
1972
- this.notifyTokenExpired();
1973
- return;
1974
- }
1975
- const { id } = message;
1976
- const stream = id === void 0 ? void 0 : this.streams.get(id);
1977
- if (stream && id !== void 0) {
1978
- stream.handle.fail(buildStreamError(message));
1979
- this.streams.delete(id);
1980
- return;
1981
- }
1982
- const state = id === void 0 ? void 0 : this.subscriptions.getById(id);
1983
- if (state) {
1984
- const error = buildSubscriptionError(message);
1985
- for (const errorCallback of state.errorCallbacks) {
1986
- try {
1987
- errorCallback(error);
1988
- } catch {
1989
- }
1990
- }
1991
- }
1992
- }
1993
- handleDataMessage(message) {
1994
- const { id } = message;
1995
- const state = id ? this.subscriptions.getById(id) : void 0;
1996
- if (!state) {
1997
- return;
1998
- }
1999
- const payload = this.resolveDataPayload(message, state);
2000
- state.lastValue = payload;
2001
- state.serverVersion += 1;
2002
- if (message.cursor !== void 0) {
2003
- state.serverCursor = message.cursor;
2004
- }
2005
- if (message.epoch !== void 0) {
2006
- state.serverEpoch = message.epoch;
2007
- }
2008
- this.persistQueryValue(state);
2009
- for (const callback of state.callbacks) {
2010
- try {
2011
- callback(payload);
2012
- } catch {
2013
- }
2014
- }
2015
- }
2016
- /**
2017
- * Handle a `resume` frame (Pillar 1b): the server proved nothing the
2018
- * subscription reads changed since our `sinceSeq`, so the cached value is
2019
- * still current. We keep `lastValue` as-is, mark the sub acked, and advance
2020
- * the cursor (re-persisting so the next reconnect resumes from the newer
2021
- * watermark). No callback fires — the value didn't change, and `subscribe()`
2022
- * already replayed the cached value to every consumer synchronously.
2023
- */
2024
- handleResumeMessage(message) {
2025
- const state = this.subscriptions.getById(message.id);
2026
- if (!state) {
2027
- return;
2028
- }
2029
- state.acked = true;
2030
- if (message.cursor !== void 0 && message.cursor !== state.serverCursor || message.epoch !== void 0 && message.epoch !== state.serverEpoch) {
2031
- if (message.cursor !== void 0) {
2032
- state.serverCursor = message.cursor;
2033
- }
2034
- if (message.epoch !== void 0) {
2035
- state.serverEpoch = message.epoch;
2036
- }
2037
- this.persistQueryValue(state);
2038
- }
2039
- }
2040
- /**
2041
- * Resolve the value to publish for a `data`/`delta` frame.
2042
- *
2043
- * A `data` frame is an authoritative snapshot (the server re-execution path)
2044
- * and always replaces the cached value wholesale. A `delta` frame carrying a
2045
- * structured `MutationDelta` (the `broadcastDelta` row-change path) is
2046
- * merged incrementally into the cached list — preserving order, no dup/loss —
2047
- * so each subscription (including every paginated page) updates by delta
2048
- * rather than a full re-send. We fall back to full replacement when the
2049
- * delta isn't a recognisable row change, when there's no cached value yet,
2050
- * or when it can't be applied cleanly against the current cached shape.
2051
- */
2052
- // eslint-disable-next-line class-methods-use-this -- instance method for symmetry with the other message handlers; reads no shared client state
2053
- resolveDataPayload(message, state) {
2054
- if ("data" in message && message.data !== void 0) {
2055
- return message.data;
2056
- }
2057
- const { delta } = message;
2058
- if (isMutationDelta(delta) && state.lastValue !== void 0) {
2059
- const merged = applyDelta(state.lastValue, delta);
2060
- if (merged !== void 0) {
2061
- return merged;
2062
- }
2063
- }
2064
- return delta;
2065
- }
2066
- /** Route an inbound whisper to the topic's handlers on the originating shard. */
2067
- dispatchWhisper(message, shardKey) {
2068
- const handlers = this.whisperHandlers.get(connectionKey(shardKey))?.get(message.topic);
2069
- if (!handlers) {
2070
- return;
2071
- }
2072
- for (const handler of handlers) {
2073
- try {
2074
- handler(message.data, message.from);
2075
- } catch {
2076
- }
2077
- }
2078
- }
2079
- /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
2080
- notifyTokenExpired() {
2081
- for (const listener of this.tokenExpiredListeners) {
2082
- try {
2083
- listener();
2084
- } catch {
2085
- }
2086
- }
2087
- }
2088
- handleCompleteMessage(id) {
2089
- const stream = this.streams.get(id);
2090
- if (stream) {
2091
- stream.handle.complete();
2092
- this.streams.delete(id);
2093
- return;
2094
- }
2095
- const state = this.subscriptions.getById(id);
2096
- if (state) {
2097
- this.subscriptions.remove(state);
2098
- }
2099
- }
2100
- unpersist(id) {
2101
- if (id) {
2102
- this.persistence?.remove(id).catch((error) => {
2103
- reportPersistenceError(this.onPersistenceError, "remove", error, id);
2104
- });
2105
- }
2106
- }
2107
- /**
2108
- * Stable, non-reversible fingerprint of the current auth identity used to
2109
- * stamp queued offline writes. `null` (signed out) is its own identity and
2110
- * never matches a bearer-token fingerprint. The raw token is never stored;
2111
- * a length-prefixed FNV-1a hash is enough to detect an identity *change*
2112
- * without keeping the credential around in the queue map.
2113
- */
2114
- // `null` is the distinct "signed out" identity (separate from `undefined`,
2115
- // which means "not stamped / hydrated"); the two must not be conflated.
2116
- identityFingerprint() {
2117
- const token = this.authToken;
2118
- if (token === null) {
2119
- return null;
2120
- }
2121
- let hash = 2166136261;
2122
- for (let index = 0; index < token.length; index += 1) {
2123
- hash ^= token.charCodeAt(index);
2124
- hash = Math.imul(hash, 16777619);
2125
- }
2126
- return `${token.length.toString(36)}:${(hash >>> 0).toString(36)}`;
2127
- }
2128
- /**
2129
- * Drain every in-memory offline write and reject it because the auth
2130
- * identity changed. Durable entries are also dropped from persistence so a
2131
- * later `hydrate` can't resurrect another user's writes. Stamps are cleared
2132
- * alongside. Persisted entries restored without a live awaiter still get
2133
- * unpersisted here.
2134
- */
2135
- rejectQueuedForIdentityChange() {
2136
- const drained = this.offlineQueue.drain();
2137
- for (const item of drained) {
2138
- this.queuedIdentities.delete(item.id ?? "");
2139
- this.unpersist(item.id);
2140
- const error = new Error("offline mutation discarded: auth identity changed before replay");
2141
- error.code = "OFFLINE_IDENTITY_CHANGED";
2142
- item.reject(error);
2143
- }
2144
- this.clearQueryCacheForIdentityChange();
2145
- }
2146
- /**
2147
- * Drop the durable read cache on an identity change so a cached value stamped
2148
- * under the previous identity can never hydrate into a new session. Clears
2149
- * the in-flight write batch and the not-yet-consumed hydrated entries too;
2150
- * the durable `clear()` is best-effort.
2151
- */
2152
- clearQueryCacheForIdentityChange() {
2153
- if (this.cacheFlushTimer !== void 0) {
2154
- clearTimeout(this.cacheFlushTimer);
2155
- this.cacheFlushTimer = void 0;
2156
- }
2157
- this.pendingCacheWrites.clear();
2158
- this.hydratedQueryCache.clear();
2159
- this.queryCache?.clear().catch(() => void 0);
2160
- }
2161
- async flushOfflineQueue(shardKey) {
2162
- const key = connectionKey(shardKey);
2163
- const drained = this.offlineQueue.drain((item) => connectionKey(item.shardKey) === key);
2164
- for (let index = 0; index < drained.length; index += 1) {
2165
- const item = drained[index];
2166
- if (!item) {
2167
- continue;
2168
- }
2169
- const currentIdentity = this.identityFingerprint();
2170
- const liveStamp = item.id === void 0 ? void 0 : this.queuedIdentities.get(item.id);
2171
- const stamped = liveStamp === void 0 ? item.identity : liveStamp;
2172
- if (stamped !== void 0 && stamped !== currentIdentity) {
2173
- this.queuedIdentities.delete(item.id ?? "");
2174
- this.unpersist(item.id);
2175
- const error = new Error("offline mutation skipped: auth identity changed before replay");
2176
- error.code = "OFFLINE_IDENTITY_CHANGED";
2177
- item.reject(error);
2178
- continue;
2179
- }
2180
- this.queuedIdentities.delete(item.id ?? "");
2181
- try {
2182
- const value = await this.rpc(item.functionPath, item.args, item.shardKey, { captureBookmark: true, mutationId: item.id });
2183
- this.unpersist(item.id);
2184
- item.resolve(value);
2185
- } catch (error) {
2186
- if (error.code !== void 0) {
2187
- this.unpersist(item.id);
2188
- item.reject(error);
2189
- continue;
2190
- }
2191
- this.offlineQueue.requeue(drained.slice(index));
2192
- return;
2193
- }
2194
- }
2195
- }
2196
- }
2197
-
2198
- export { LunoraClient };