@lunora/client 1.0.0-alpha.8 → 1.0.0-alpha.80

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