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

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