@lunora/client 1.0.0-alpha.47 → 1.0.0-alpha.48

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 (33) hide show
  1. package/dist/auth/index.d.mts +2 -2
  2. package/dist/auth/index.d.ts +2 -2
  3. package/dist/index.d.mts +15 -42
  4. package/dist/index.d.ts +15 -42
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/LunoraClient-BluyW2SA.mjs +1 -0
  7. package/dist/packem_shared/{SubscriptionRegistry-C72rCp44.mjs → SubscriptionRegistry-HXgW6BXq.mjs} +1 -1
  8. package/dist/packem_shared/applyDelta-Dw5isoZR.mjs +1 -0
  9. package/dist/packem_shared/createLocalStore-7WO7dnOs.mjs +1 -0
  10. package/dist/packem_shared/{createServerClient-BU2gC5p6.mjs → createServerClient-DoNhxkkm.mjs} +1 -1
  11. package/dist/packem_shared/{createSnapshotPrecondition-CKvCNKyD.mjs → createSnapshotPrecondition-A10yhOpq.mjs} +1 -1
  12. package/dist/packem_shared/delta-merge-DoT5IpTP.mjs +1 -0
  13. package/dist/packem_shared/{local-store-DFMSEM2j.mjs → local-store-CGsgaEph.mjs} +1 -1
  14. package/dist/packem_shared/{lunora-client.d-Kd72FRSr.d.ts → lunora-client.d-Dv40CCsu.d.ts} +1 -1
  15. package/dist/packem_shared/{lunora-client.d-DbRRvSya.d.mts → lunora-client.d-nHupuaoI.d.mts} +1 -1
  16. package/dist/packem_shared/{preload.d-D55TcvEq.d.ts → preload.d-DtFFNok3.d.ts} +2 -2
  17. package/dist/packem_shared/{preload.d-BmSiP8F_.d.mts → preload.d-y5DTDa0X.d.mts} +2 -2
  18. package/dist/packem_shared/{types.d-w4VrTsKH.d.mts → types.d-CsuRAQvb.d.mts} +7 -0
  19. package/dist/packem_shared/{types.d-w4VrTsKH.d.ts → types.d-CsuRAQvb.d.ts} +7 -0
  20. package/dist/packem_shared/{wire-codec-D_fiax9d.mjs → wire-codec-aTWt2XiW.mjs} +1 -1
  21. package/dist/packem_shared/{wire-key-j8BZ65HQ.mjs → wire-key-Cb-kXfSh.mjs} +1 -1
  22. package/dist/query/index.d.mts +3 -3
  23. package/dist/query/index.d.ts +3 -3
  24. package/dist/service.d.mts +1 -1
  25. package/dist/service.d.ts +1 -1
  26. package/dist/service.mjs +1 -1
  27. package/dist/ssr/index.d.mts +4 -4
  28. package/dist/ssr/index.d.ts +4 -4
  29. package/dist/ssr/index.mjs +1 -1
  30. package/package.json +1 -1
  31. package/dist/packem_shared/LunoraClient-CbRvTqjM.mjs +0 -1
  32. package/dist/packem_shared/applyDelta-DXqQORbM.mjs +0 -1
  33. package/dist/packem_shared/createLocalStore-CwuKPK9x.mjs +0 -1
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
2
- import { U as User } from "../packem_shared/types.d-w4VrTsKH.mjs";
1
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
2
+ import { U as User } from "../packem_shared/types.d-CsuRAQvb.mjs";
3
3
  import '@lunora/runtime';
4
4
  interface IdentityStore {
5
5
  /** Read the current resolved user, or `null` when signed out / not yet resolved. */
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
2
- import { U as User } from "../packem_shared/types.d-w4VrTsKH.js";
1
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
2
+ import { U as User } from "../packem_shared/types.d-CsuRAQvb.js";
3
3
  import '@lunora/runtime';
4
4
  interface IdentityStore {
5
5
  /** Read the current resolved user, or `null` when signed out / not yet resolved. */
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-w4VrTsKH.mjs";
2
- export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-w4VrTsKH.mjs";
3
- import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-DbRRvSya.mjs";
4
- export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-DbRRvSya.mjs";
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BmSiP8F_.mjs";
1
+ import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-CsuRAQvb.mjs";
2
+ export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-CsuRAQvb.mjs";
3
+ import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-nHupuaoI.mjs";
4
+ export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-nHupuaoI.mjs";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-y5DTDa0X.mjs";
6
6
  export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
7
7
  declare const anyApi: Record<string, Record<string, unknown>>;
8
8
  /**
@@ -337,27 +337,6 @@ declare class TabCoordinator {
337
337
  */
338
338
  private claimAndPromote;
339
339
  }
340
- /**
341
- * Client-side incremental merging of structured mutation deltas.
342
- *
343
- * Lunora's live-query fan-out has two server paths:
344
- *
345
- * 1. Server re-execution (subscriptions carrying a `functionPath`) pushes a
346
- * full `data` snapshot whenever a write touches a table the query reads. These
347
- * already carry the authoritative result and are applied wholesale.
348
- * 2. Legacy delta fan-out (`broadcastDelta`) pushes a structured `MutationDelta`
349
- * as a `delta` frame to subscribers matched by table + args. The delta describes
350
- * a single row change (`insert` / `update` / `delete`) keyed by row id, so the
351
- * client can splice it into the cached list result without a full re-send.
352
- *
353
- * Historically the client treated the `delta` field as an opaque blob and
354
- * replaced the whole cached value with it on every message — which only made
355
- * sense for the rare delta payloads that already carried the full result. This
356
- * module lets the client recognise a structured delta and merge it into the
357
- * existing array (preserving order, no dup/loss), falling back to full
358
- * replacement when the payload isn't a recognisable row delta or can't be
359
- * applied cleanly against the current cached shape.
360
- */
361
340
  /**
362
341
  * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
363
342
  * `MutationDelta` in `@lunora/do` structurally so the client carries no
@@ -380,25 +359,19 @@ interface MutationDelta {
380
359
  */
381
360
  declare const isMutationDelta: (value: unknown) => value is MutationDelta;
382
361
  /**
383
- * Apply a structured `MutationDelta` to a cached array result, returning a new
384
- * array (never mutating the input). Returns `undefined` when the delta can't be
362
+ * Apply a structured `MutationDelta` to a cached list result, returning a new
363
+ * value (never mutating the input). Returns `undefined` when the delta can't be
385
364
  * applied cleanly — the caller should then fall back to the existing
386
365
  * full-replacement behaviour (or trust the next snapshot to reconcile).
387
366
  *
388
- * Mergeable shape: a plain array of id-bearing row objects, e.g. the result of
389
- * `db.query().collect()`.
390
- *
391
- * Insert / update / delete are matched by row `_id`:
392
- * - `insert`: appended (or placed by `_creationTime` order) if absent; treated
393
- * as an update if a row with the same id already exists (idempotent — guards
394
- * against a delta replayed after a snapshot already included it).
395
- * - `update`: replaces the matching row in place, preserving its position.
396
- * - `delete`: removes the matching row.
397
- *
398
- * Returns `undefined` when `current` isn't an array of id-keyable objects, or
399
- * when an `insert`/`update` delta carries no `row` to splice in.
400
- */
401
- declare const applyDelta: (current: unknown, delta: MutationDelta) => undefined | unknown[];
367
+ * Mergeable shapes: an array of id-bearing row objects, or a `.paginate()`
368
+ * result wrapping one in `page` (see `rowListOf`). A paginated value keeps its
369
+ * other fields and comes back as a new object with a new `page` — the server
370
+ * only sends row deltas for that shape when everything outside the page is
371
+ * unchanged, so the merged value matches the snapshot it chose not to send.
372
+ * @returns the merged value, or `undefined` when the delta cannot be applied
373
+ */
374
+ declare const applyDelta: (current: unknown, delta: MutationDelta) => Record<string, unknown> | undefined | unknown[];
402
375
  /**
403
376
  * Options accepted by {@link httpStream}.
404
377
  * @experimental Part of the HTTP-SSE stream surface.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-w4VrTsKH.js";
2
- export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-w4VrTsKH.js";
3
- import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Kd72FRSr.js";
4
- export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-Kd72FRSr.js";
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-D55TcvEq.js";
1
+ import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-CsuRAQvb.js";
2
+ export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-CsuRAQvb.js";
3
+ import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Dv40CCsu.js";
4
+ export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-Dv40CCsu.js";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-DtFFNok3.js";
6
6
  export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
7
7
  declare const anyApi: Record<string, Record<string, unknown>>;
8
8
  /**
@@ -337,27 +337,6 @@ declare class TabCoordinator {
337
337
  */
338
338
  private claimAndPromote;
339
339
  }
340
- /**
341
- * Client-side incremental merging of structured mutation deltas.
342
- *
343
- * Lunora's live-query fan-out has two server paths:
344
- *
345
- * 1. Server re-execution (subscriptions carrying a `functionPath`) pushes a
346
- * full `data` snapshot whenever a write touches a table the query reads. These
347
- * already carry the authoritative result and are applied wholesale.
348
- * 2. Legacy delta fan-out (`broadcastDelta`) pushes a structured `MutationDelta`
349
- * as a `delta` frame to subscribers matched by table + args. The delta describes
350
- * a single row change (`insert` / `update` / `delete`) keyed by row id, so the
351
- * client can splice it into the cached list result without a full re-send.
352
- *
353
- * Historically the client treated the `delta` field as an opaque blob and
354
- * replaced the whole cached value with it on every message — which only made
355
- * sense for the rare delta payloads that already carried the full result. This
356
- * module lets the client recognise a structured delta and merge it into the
357
- * existing array (preserving order, no dup/loss), falling back to full
358
- * replacement when the payload isn't a recognisable row delta or can't be
359
- * applied cleanly against the current cached shape.
360
- */
361
340
  /**
362
341
  * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
363
342
  * `MutationDelta` in `@lunora/do` structurally so the client carries no
@@ -380,25 +359,19 @@ interface MutationDelta {
380
359
  */
381
360
  declare const isMutationDelta: (value: unknown) => value is MutationDelta;
382
361
  /**
383
- * Apply a structured `MutationDelta` to a cached array result, returning a new
384
- * array (never mutating the input). Returns `undefined` when the delta can't be
362
+ * Apply a structured `MutationDelta` to a cached list result, returning a new
363
+ * value (never mutating the input). Returns `undefined` when the delta can't be
385
364
  * applied cleanly — the caller should then fall back to the existing
386
365
  * full-replacement behaviour (or trust the next snapshot to reconcile).
387
366
  *
388
- * Mergeable shape: a plain array of id-bearing row objects, e.g. the result of
389
- * `db.query().collect()`.
390
- *
391
- * Insert / update / delete are matched by row `_id`:
392
- * - `insert`: appended (or placed by `_creationTime` order) if absent; treated
393
- * as an update if a row with the same id already exists (idempotent — guards
394
- * against a delta replayed after a snapshot already included it).
395
- * - `update`: replaces the matching row in place, preserving its position.
396
- * - `delete`: removes the matching row.
397
- *
398
- * Returns `undefined` when `current` isn't an array of id-keyable objects, or
399
- * when an `insert`/`update` delta carries no `row` to splice in.
400
- */
401
- declare const applyDelta: (current: unknown, delta: MutationDelta) => undefined | unknown[];
367
+ * Mergeable shapes: an array of id-bearing row objects, or a `.paginate()`
368
+ * result wrapping one in `page` (see `rowListOf`). A paginated value keeps its
369
+ * other fields and comes back as a new object with a new `page` — the server
370
+ * only sends row deltas for that shape when everything outside the page is
371
+ * unchanged, so the merged value matches the snapshot it chose not to send.
372
+ * @returns the merged value, or `undefined` when the delta cannot be applied
373
+ */
374
+ declare const applyDelta: (current: unknown, delta: MutationDelta) => Record<string, unknown> | undefined | unknown[];
402
375
  /**
403
376
  * Options accepted by {@link httpStream}.
404
377
  * @experimental Part of the HTTP-SSE stream surface.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{anyApi as o}from"./packem_shared/anyApi-BD4dgvDY.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as n,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs";import{createAsyncStoragePersistence as m}from"./packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{createClientQuery as s}from"./packem_shared/createClientQuery-CrdRoicO.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CMFYQCL-.mjs";import{applyDelta as y,isMutationDelta as R}from"./packem_shared/applyDelta-DXqQORbM.mjs";import{CONFLICT_ERROR_CODE as C,getErrorCode as S,getRetryAfterMs as A,isConflictError as D,isForbiddenError as M,isRateLimitedError as _,isUnauthorizedError as h}from"./packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs";import{httpStream as Q}from"./packem_shared/httpStream-Cz4_QyjV.mjs";import{c as L}from"./packem_shared/local-store-DFMSEM2j.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-CbRvTqjM.mjs";import{createMutationRunner as O}from"./packem_shared/createMutationRunner-lQXH8Amk.mjs";import{createMutatorRunner as U}from"./packem_shared/createMutatorRunner-BVzo0FBZ.mjs";import{h as B}from"./packem_shared/offline-queue-CKMw-5rF.mjs";import{createInMemoryPersistence as N,createIndexedDbPersistence as v}from"./packem_shared/createInMemoryPersistence-CQYXy8UP.mjs";import{preloadQuery as z,preloadedQueryResult as K}from"./packem_shared/preloadQuery-DjwSjFwt.mjs";import{createInMemoryQueryCache as W,createIndexedDbQueryCache as X,queryCacheKey as j}from"./packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as H}from"./packem_shared/createReconnect-CFT7YRSR.mjs";import{default as Y}from"./packem_shared/createSnapshotPrecondition-CKvCNKyD.mjs";import{DEFAULT_MAX_BUFFER as $,createStream as ee}from"./packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as oe}from"./packem_shared/SubscriptionRegistry-C72rCp44.mjs";import{ClientServiceWorker as ae}from"./packem_shared/ClientServiceWorker-CRQ5yl7-.mjs";import{createReply as pe,sendToSw as ce}from"./packem_shared/createReply-DF0jRsv-.mjs";export{C as CONFLICT_ERROR_CODE,ae as ClientServiceWorker,$ as DEFAULT_MAX_BUFFER,b as LunoraClient,B as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,oe as SubscriptionRegistry,d as TabCoordinator,o as anyApi,y as applyDelta,m as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,N as createInMemoryPersistence,W as createInMemoryQueryCache,v as createIndexedDbPersistence,X as createIndexedDbQueryCache,L as createLocalStore,O as createMutationRunner,U as createMutatorRunner,H as createReconnect,pe as createReply,Y as createSnapshotPrecondition,ee as createStream,S as getErrorCode,A as getRetryAfterMs,Q as httpStream,D as isConflictError,M as isForbiddenError,R as isMutationDelta,_ as isRateLimitedError,h as isUnauthorizedError,n as maxSeq,z as preloadQuery,K as preloadedQueryResult,j as queryCacheKey,p as reconcileOptimistic,ce as sendToSw};
1
+ import{anyApi as o}from"./packem_shared/anyApi-BD4dgvDY.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as n,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs";import{createAsyncStoragePersistence as m}from"./packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{createClientQuery as s}from"./packem_shared/createClientQuery-CrdRoicO.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CMFYQCL-.mjs";import{y as l,w as R}from"./packem_shared/delta-merge-DoT5IpTP.mjs";import{CONFLICT_ERROR_CODE as C,getErrorCode as S,getRetryAfterMs as A,isConflictError as D,isForbiddenError as M,isRateLimitedError as _,isUnauthorizedError as h}from"./packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs";import{httpStream as Q}from"./packem_shared/httpStream-Cz4_QyjV.mjs";import{c as L}from"./packem_shared/local-store-CGsgaEph.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-BluyW2SA.mjs";import{createMutationRunner as O}from"./packem_shared/createMutationRunner-lQXH8Amk.mjs";import{createMutatorRunner as U}from"./packem_shared/createMutatorRunner-BVzo0FBZ.mjs";import{h as B}from"./packem_shared/offline-queue-CKMw-5rF.mjs";import{createInMemoryPersistence as w,createIndexedDbPersistence as N}from"./packem_shared/createInMemoryPersistence-CQYXy8UP.mjs";import{preloadQuery as z,preloadedQueryResult as K}from"./packem_shared/preloadQuery-DjwSjFwt.mjs";import{createInMemoryQueryCache as W,createIndexedDbQueryCache as X,queryCacheKey as j}from"./packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as H}from"./packem_shared/createReconnect-CFT7YRSR.mjs";import{default as Y}from"./packem_shared/createSnapshotPrecondition-A10yhOpq.mjs";import{DEFAULT_MAX_BUFFER as $,createStream as ee}from"./packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as oe}from"./packem_shared/SubscriptionRegistry-HXgW6BXq.mjs";import{ClientServiceWorker as ae}from"./packem_shared/ClientServiceWorker-CRQ5yl7-.mjs";import{createReply as pe,sendToSw as ce}from"./packem_shared/createReply-DF0jRsv-.mjs";export{C as CONFLICT_ERROR_CODE,ae as ClientServiceWorker,$ as DEFAULT_MAX_BUFFER,b as LunoraClient,B as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,oe as SubscriptionRegistry,d as TabCoordinator,o as anyApi,l as applyDelta,m as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,w as createInMemoryPersistence,W as createInMemoryQueryCache,N as createIndexedDbPersistence,X as createIndexedDbQueryCache,L as createLocalStore,O as createMutationRunner,U as createMutatorRunner,H as createReconnect,pe as createReply,Y as createSnapshotPrecondition,ee as createStream,S as getErrorCode,A as getRetryAfterMs,Q as httpStream,D as isConflictError,M as isForbiddenError,R as isMutationDelta,_ as isRateLimitedError,h as isUnauthorizedError,n as maxSeq,z as preloadQuery,K as preloadedQueryResult,j as queryCacheKey,p as reconcileOptimistic,ce as sendToSw};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{w as D,y as j,a as H}from"./delta-merge-DoT5IpTP.mjs";import{s as b,a as B}from"./wire-codec-aTWt2XiW.mjs";import{t as I}from"./wire-key-Cb-kXfSh.mjs";import V from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as J}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as X}from"./TabCoordinator-CMFYQCL-.mjs";import{httpStream as Y}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Z,c as tt}from"./local-store-CGsgaEph.mjs";import{h as et,u as $,d as st,s as rt}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as it}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as nt,queryCacheKey as x}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as at}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-HXgW6BXq.mjs";const R=500,ot=(h,t)=>{if(h.size<t)return;const e=h.keys().next().value;e!==void 0&&h.delete(e)};class C{listeners=new Set;add(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(...t){const[e]=t;for(const s of this.listeners)try{s(e)}catch{}}clear(){this.listeners.clear()}}const ct="/_lunora/rpc",Q="/_lunora/rpc-batch",ht="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,O=h=>{for(let t=h.length-1;t>=0;t-=1)h[t]?.()},ut=(h,t)=>{for(const e of t)e.op==="delete"?h.delete(e.key):e.value!==void 0&&h.set(e.key,e.value)},dt="lunora-ping",lt=3e4,pt=1e4,mt=250,ft=64,yt="/_lunora/admin/shard-traffic",gt="/_lunora/admin/scheduled",bt="/_lunora/admin/scheduled/status",St="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",kt="/_lunora/admin/scheduled/dead",wt="/_lunora/admin/scheduled/dead/retry",Ct="/_lunora/admin/scheduled/dead/cancel",Tt="/_lunora/admin/workflows/instances",It="/_lunora/admin/workflows/instance",Ot="/_lunora/admin/workflows/status",L="/_lunora/admin/storage",Et="/_lunora/admin/storage/url",_t="/_lunora/admin/storage/buckets",Ft="/_lunora/admin/functions",Pt="/_lunora/admin/cron-jobs",At="/_lunora/admin/cron-jobs/run",xt="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Mt="/_lunora/admin/global/tables",Lt="/_lunora/admin/global/table",Kt="/_lunora/admin/global/facet",$t="/_lunora/admin/vector/indexes",qt="/_lunora/admin/vector/query",Qt="/_lunora/admin/logs/archive",Ut="/_lunora/admin/kv/namespaces",Nt="/_lunora/admin/kv/keys",K="/_lunora/admin/kv/value",Bt="/_lunora/admin/auth/users",Wt="/_lunora/admin/auth/sessions",zt="/_lunora/admin/auth/users/create",Gt="/_lunora/admin/auth/users/role",Dt="/_lunora/admin/auth/users/ban",jt="/_lunora/admin/auth/users/unban",Ht="/_lunora/admin/auth/users/password",Vt="/_lunora/admin/auth/users/remove",Jt="/_lunora/admin/auth/users/impersonate",Xt="/_lunora/admin/auth/sessions/revoke",Yt="/_lunora/admin/auth/sessions/revoke-all",Zt="/_lunora/admin/auth/capabilities",te="/_lunora/admin/auth/users/update",ee="/_lunora/admin/auth/accounts",se="/_lunora/admin/auth/accounts/unlink",re="/_lunora/admin/auth/passkeys",ie="/_lunora/admin/auth/passkeys/delete",ne="/_lunora/admin/auth/two-factor/disable",ae="/_lunora/admin/auth/organizations",oe="/_lunora/admin/auth/organizations/members",ce="/_lunora/admin/auth/organizations/invitations",he="/_lunora/admin/auth/organizations/members/remove",ue="/_lunora/admin/auth/organizations/invitations/cancel",de="/_lunora/admin/auth/config",le="/_lunora/admin/auth/organizations/create",pe="/_lunora/admin/auth/organizations/update",me="/_lunora/admin/auth/organizations/remove",fe="/_lunora/admin/auth/organizations/members/add",ye="/_lunora/admin/auth/organizations/members/invite",ge="/_lunora/admin/auth/organizations/members/role",be="/_lunora/admin/auth/organizations/teams",Se="/_lunora/admin/auth/organizations/teams/create",ve="/_lunora/admin/auth/organizations/teams/update",ke="/_lunora/admin/auth/organizations/teams/remove",we="/_lunora/admin/auth/organizations/teams/members",Ce="/_lunora/admin/auth/organizations/teams/members/add",Te="/_lunora/admin/auth/organizations/teams/members/remove",Ie="/_lunora/admin/auth/organizations/roles",Oe="/_lunora/admin/auth/organizations/roles/create",Ee="/_lunora/admin/auth/organizations/roles/update",_e="/_lunora/admin/auth/organizations/roles/remove",Fe="/api/auth",Pe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[r,i]of Object.entries(t))i!==void 0&&i!==""&&e.set(r,String(i));const s=e.toString();return s===""?h:`${h}?${s}`},Ae=[H],m=h=>h??"",W=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,r=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??t}},xe=h=>{const{code:t,messageText:e}=W(h,"stream error");return t===void 0?new Error(e):new p(t,e)},N=h=>{const{code:t,messageText:e}=W(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Re=new TextDecoder,Me=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Re.decode(h)},g=(h,t)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(t)),!0}catch{return!1}},T=h=>{const t=new Error(h.message??"request failed");return t.code=h.code,h.data!==void 0&&(t.data=b(h.data)),h.hint!==void 0&&(t.hint=h.hint),h.docsUrl!==void 0&&(t.docsUrl=h.docsUrl),t},k=(h,t)=>{try{return B(h)}catch(e){const s=e instanceof Error?e.message:String(e);throw new TypeError(`LunoraClient: cannot encode ${t} — ${s}`,e instanceof Error?{cause:e}:void 0)}},Le=(h,t)=>{const e=Array.from({length:t});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=t)continue;const r=s.body;e[s.id]=r&&"error"in r&&r.error?{error:T(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Ke=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),$e=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(t,e){return{defaultValue:e,key:t}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(t){this.url=t.url,this.wsUrl=t.wsUrl??v(U(t.url),ht),this.wsToken=t.wsToken;const e=t.authBasePath??Fe;this.authBasePath=e.endsWith("/")?e.slice(0,-1):e,this.fetchImpl=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=t.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=t.bookmarkStorage??V(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??lt,this.connectTimeoutMs=t.connectTimeoutMs??pt,this.defaultConnectionContext=t.connectionContext,this.persistence=it(t.persistence,t.outbox===void 0),this.persistenceVersion=t.persistenceVersion,this.queryCache=nt(t.queryCache),this.onPersistenceError=t.offlineQueue?.onPersistenceError,this.clientQueryStore=new J,t.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,t.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=$e),this.offlineQueue=new et(t.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${$()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(t,e){const s=this.authToken!==t,r=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const i=this.identityFingerprint();if(i!==r&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(r,i),this.tabCoordinator)){const n=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),n&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(t)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(t){return this.clientWatermarks.get(t??"")??0}async callMutator(t,e,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"";let n;const a=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:o=>{n=o}});return n!==void 0&&n>(this.clientWatermarks.get(i)??0)&&this.clientWatermarks.set(i,n),{applied:n===void 0||n===r,result:a}}onAuthTokenChange(t){return this.authTokenListeners.add(t)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const t={};this.authToken&&(t.authorization=`Bearer ${this.authToken}`);try{const e=await this.fetchImpl(v(this.url,`${this.authBasePath}${Pe}`),{credentials:"include",headers:t,method:"GET"});return e.ok?(await e.json())?.user??null:null}catch{return null}}setWsToken(t){if(this.wsToken!==t){this.wsToken=t;for(const e of this.connections.values())if(e.socket)try{e.socket.close()}catch{}}}setConnectionContext(t,e={}){const s=m(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=m(e.shardKey),r={context:t},i=this.connectionContextHolders.get(s);i?i.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let n=!1;return()=>{if(n)return;n=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const r=m(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(t);const a=n===void 0;if(n||(n=new Set,i.set(t,n)),n.add(e),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:t,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&g(u,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{data:k(e??null,`whisper data for topic '${t}'`),topic:t,type:"whisper"})}onTokenExpired(t){return this.tokenExpiredListeners.add(t)}connectionStatus(){return this.computeStatus()}onConnectionStatus(t){const e=this.statusListeners.add(t);return t(this.computeStatus()),e}pendingCount(){return this.offlineQueue.size}debug(){const t=[],e=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(const r of e){const i=this.connections.get(r);t.push({confirmedMutationWatermark:this.clientWatermarks.get(r)??0,hasSocket:i?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const s=this.subscriptions.all().map(r=>({acked:r.acked,functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())s.push({acked:r.serverCursor!==void 0,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((r,i)=>(r.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:s.toSorted((r,i)=>r.functionPath.localeCompare(i.functionPath))}}onPendingChange(t){const e=this.pendingChangeListeners.add(t);return t(this.offlineQueue.size),e}onMutationSettled(t){return this.mutationSettledListeners.add(t)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(t){return this.clientQueryStore.get(t)}setClientQuery(t,e){this.clientQueryStore.set(t,e)}subscribeClientQuery(t,e){return this.clientQueryStore.subscribe(t,e)}resetClientQuery(t){this.clientQueryStore.reset(t)}snapshotPrecondition(t,e,s){const r=this.peekActiveQueryValue(t.__lunoraRef,e,s),i=r===void 0?void 0:I(r);return()=>{const n=this.peekActiveQueryValue(t.__lunoraRef,e,s);return i===void 0&&n===void 0?!0:i===void 0||n===void 0?!1:I(n)===i}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const r=I(e),i=x(t,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQueryValue(t,e,s){const r=w.key(t,e,s);return this.subscriptions.get(r)?.lastValue}async query(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey,{attachBookmark:!0})}async batch(t){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args??{},`args for batch call '${i.fn.__lunoraRef}'`),functionPath:i.fn.__lunoraRef,id:n,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||r.error&&!r.results)throw r.error?T(r.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(t[i.id]?.shardKey,n)}return Le(r.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const r=e,i=s.mutationId??$(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,n);const{hasSocket:o,wasEverConnected:c,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:d}=this.offlineQueue,l=c||d,y=this.WebSocketImpl!==void 0&&l;if(u!=="open"&&!o&&y||u==="connecting"&&l)return this.enqueueOfflineMutation(t,r,s.shardKey,i,a,n,s.precondition);try{let S;const G=await this.rpc(t.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:_=>{S=_}});for(const _ of n)_(S);return G}catch(S){throw O(a),S}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=e.length;let a=0,o=0;for(let c=0;c<n;c+=r){const u=e.slice(c,c+r),d=o;await this.mutation(t,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(d)}`},shardKey:s.shardKey}),o+=1,a+=u.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(yt,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(gt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(bt,"GET");return{backlog:t.backlog??0,inFlight:t.inFlight??0,pools:t.pools??[]}}async cancelScheduledJob(t){return this.assertOpen(),{cancelled:(await this.adminFetch(vt,"POST",{id:t})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(kt,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(wt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(Ct,"POST",{id:t})).removed===!0}}async listWorkflowInstances(t){this.assertOpen();const e=new URLSearchParams({name:t.name});t.status!==void 0&&e.set("status",t.status),t.page!==void 0&&e.set("page",String(t.page)),t.perPage!==void 0&&e.set("perPage",String(t.perPage));const s=await this.adminFetch(`${Tt}?${e.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??t.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(t){this.assertOpen();const e=new URLSearchParams({id:t.id,name:t.name}),s=await this.adminFetch(`${It}?${e.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??t.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(t){return this.assertOpen(),{status:(await this.adminFetch(Ot,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=v(U(this.url),St),s=q(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||(i=setTimeout(u,s.next()))},o=d=>{if(n||this.WebSocketImpl===void 0)return;const l=d===void 0?e:`${e}?token=${encodeURIComponent(d)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const S=JSON.parse(typeof y.data=="string"?y.data:"");S.type==="jobs"&&Array.isArray(S.records)&&t(S.records)}catch{}},onOpen:()=>{s.reset()}})},c=async d=>{let l;try{l=await d()}catch{a();return}o(l)},u=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:d}=this;if(typeof d=="function"){c(d).catch(()=>{});return}o(d)};return u(),()=>{n=!0,i!==void 0&&clearTimeout(i),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Pt,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(At,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(xt,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(L,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),s=await this.adminFetch(e,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(t,e){this.assertOpen();const s=`${L}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${L}?key=${encodeURIComponent(t.key)}${M(t.bucket)}`,s=await this.adminFetch(e,"PUT",t.body,t.contentType);return{etag:s.etag,key:s.key??t.key}}async signedStorageUrl(t,e){this.assertOpen();const s=e?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Et}?key=${encodeURIComponent(t)}${r}${M(e?.bucket)}`,n=await this.adminFetch(i,"GET");if(typeof n.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return n.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Mt,"GET")}async readGlobalTablePage(t){this.assertOpen();const e=new URLSearchParams({table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.offset!==void 0&&e.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Lt}?${e.toString()}`,"GET")}async facetGlobalColumn(t){this.assertOpen();const e=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Kt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($t,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch(qt,"POST",t)).matches??[]}async queryLogArchive(t={}){this.assertOpen();const e=await this.adminFetch(Qt,"POST",t);return{nextCursor:e.nextCursor,rows:e.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Ut,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Nt,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await this.adminFetch(e,"GET")}async getKvValue(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch(K,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Bt,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminFetch(e,"GET")}async createAuthUser(t){return await this.adminFetch(zt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(Gt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(jt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(Ht,"POST",t)}async removeAuthUser(t){await this.adminFetch(Vt,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Jt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Xt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Yt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Zt,"GET")}async updateAuthUser(t){return await this.adminFetch(te,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(ee,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(se,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(re,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){await this.adminFetch(ie,"POST",t)}async disableAuthTwoFactor(t){await this.adminFetch(ne,"POST",t)}async listAuthOrganizations(t={}){return await this.adminFetch(f(ae,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(ce,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(he,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(ue,"POST",t)}async getAuthConfig(){return await this.adminFetch(de,"GET")}async createAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(pe,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(me,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(ye,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ge,"POST",t)}async listAuthOrgTeams(t){const e=f(be,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(Se,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(ve,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(ke,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(we,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(Ce,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Te,"POST",t)}async listAuthOrgRoles(t){const e=f(Ie,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Ee,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(_e,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Wt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,r={}){this.assertOpen();const i=e??{},n=w.key(t.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const d=`sub_${this.nextSubId.toString()}`,l=I(i),y=this.takeHydratedCache(t.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:d,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:r.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),c&&u.errorCallbacks.delete(c),r.onCheckpoint&&u.checkpointCallbacks.delete(r.onCheckpoint),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.subscriptions.remove(u))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:t.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:t.args===void 0?void 0:k(t.args,`shape args for '${t.name}'`)};return this.shapeSubscriptions.set(r,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(i.shardKey,r,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=e??{},{handle:a,iterable:o}=at({maxBuffer:s.maxBuffer,onCancel:()=>{const d=this.getConnection(i);d&&g(d,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(i);const c=this.getConnection(i),u={id:r,query:{args:k(n,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:i},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:u,shardKey:i}),!(c?.wsState==="open"&&g(c,u))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=ft;){const d=c.pendingStreams.shift()?.id,l=d?this.streams.get(d):void 0;l&&(l.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(d))}c.pendingStreams.push(u)}return o}httpStream(t,e,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Y(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const t of this.streams.values())t.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const t of this.connections.values())this.teardownConnection(t);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}teardownConnection(t){if(t.reconnectTimer!==void 0&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),this.stopHeartbeat(t),t.socket){try{t.socket.close()}catch{}t.socket=void 0}t.wsState="closed"}createTabCoordinator(){const t=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new X({channelName:t,onBecomeLeader:()=>{for(const e of this.subscriptions.all())this.ensureSocket(e.shardKey),this.sendSubscribeIfOpen(e);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[e,s]of this.connections)this.teardownConnection(s),this.connections.delete(e);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(e,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),F(a,r)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const r=this.subscriptions.get(e);r&&E(r.errorCallbacks,s)},onSubscriptionSettled:(e,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(t,e,s,r,i,n,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:e,clientId:this.clientId,functionPath:t.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(u){throw O(i),u instanceof Error?u:new Error(String(u))}for(const u of n)u(void 0);return}return new Promise((c,u)=>{const d={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of n)y(l)},reject:l=>{this.queuedIdentities.delete(r),O(i),u(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(d),this.queuedOfflineShardKeys.add(s),d.id!==void 0&&this.queuedIdentities.set(d.id,o)})}async hydratePersistedQueue(){try{const t=await this.offlineQueue.hydrate();for(const e of t)this.queuedOfflineShardKeys.add(e),this.ensureSocket(e)}catch{}}hydrateAsOutboxLeader(){const t=()=>{this.hydratePersistedQueue().catch(()=>{})},e=globalThis.navigator?.locks;if(!e){t();return}e.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||t(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(t)}async hydrateQueryCache(){if(this.queryCache)try{const t=await this.queryCache.load();for(const{key:e,...s}of t){if(st(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const r=x(t,e,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=x(t.fn.__lunoraRef,t.argsKey,t.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:t.serverCursor,ts:Date.now(),value:e,...t.serverEpoch===void 0?{}:{serverEpoch:t.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},mt)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:t}=this;if(!t){this.pendingCacheWrites.clear();return}const e=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(e.map(([s,r])=>t.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const t=[...this.connections.values()];return t.length===0?"idle":t.some(e=>e.wsState==="open")?"connected":t.some(e=>e.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const t=this.computeStatus();t!==this.lastStatus&&(this.lastStatus=t,this.statusListeners.emit(t),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(t,this.identityFingerprint()))}emitItemSettled(t,e,s){this.mutationSettledListeners.emit({args:t.args,code:s===void 0?void 0:s.code,error:s,functionPath:t.functionPath,hadAwaiter:t.liveAwaiter??!1,id:t.id??"",shardKey:t.shardKey,status:e})}applyOptimisticUpdates(t,e,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Z(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(t,e,s,r,i){const{confirms:n,rollbacks:a,store:o}=tt(this.subscriptions,s);try{t(o,e)}catch{O(a);return}r.push(...a),i.push(...n)}getConnection(t){return this.connections.get(m(t))}sendOrQueueUnsubscribe(t,e,s){const r=this.getConnection(t);r&&!g(r,{id:e,type:s})&&r.pendingUnsubscribes.push({id:e,type:s})}connectionGateState(t){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const e=this.getConnection(t);return{hasSocket:e?.socket!==void 0,wasEverConnected:e?.wasEverConnected??!1,wsState:e?.wsState??"idle"}}getOrCreateConnection(t){const e=m(t);let s=this.connections.get(e);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:q(this.reconnectOptions),reconnectTimer:void 0,shardKey:t,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(e,s)),s}wsUrlFor(t,e){const s=[];if(t!==void 0&&s.push(`shard=${encodeURIComponent(t)}`),e!==void 0&&s.push(`token=${encodeURIComponent(e)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(t,e){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(e));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),t.mutationId&&(s["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(s["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(s["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(t,e,s,r={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(v(this.url,ct),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const o=n.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await n.json()}catch{const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${n.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!n.ok){const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(t,e,s,r){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const n=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:n?(a=s,r!==void 0&&(i["content-type"]=r)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(v(this.url,t),{body:a,headers:i,method:e});let c;try{c=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if(typeof c=="object"&&c!==null&&"error"in c){const u=c.error,d=new Error(u.message??"admin request failed");throw d.code=u.code,d}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}return c}effectiveConnectionContext(t){const e=this.connectionContextHolders.get(t);return e&&e.length>0?e[e.length-1]?.context:this.connectionContexts.get(t)??this.defaultConnectionContext}refreshConnectionContext(t){const e=this.connections.get(t);e?.wsState==="open"&&this.sendConnectEnvelope(e)}sendConnectEnvelope(t){const e=this.effectiveConnectionContext(m(t.shardKey));g(t,{caps:Ae,clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())m(e.shardKey)===m(t)&&this.sendShapeSubscribeIfOpen(e)}ensureSocket(t){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const e=this.getOrCreateConnection(t);if(!(e.wsState==="open"||e.wsState==="connecting")){if(e.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(e,t,this.wsToken).catch(()=>{});return}this.openSocket(e,t,this.wsToken)}}async openSocketWithProvidedToken(t,e,s){let r;try{r=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,r)}openManagedSocket(t,e,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new p("INTERNAL","no WebSocket implementation available");const n=new i(e);t.socket=n;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===n&&(t.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{t.socket===n&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(t,o))}),n.addEventListener("message",c=>{t.socket===n&&(t.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{t.socket===n&&o(c)}),n.addEventListener("error",()=>{t.socket===n&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:r=>{this.handleServerMessage(r.data,e)},onOpen:()=>{t.wsState="open",t.wasEverConnected=!0,t.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(t),this.markShardPendingAck(e);for(const i of this.subscriptions.all())m(i.shardKey)===m(e)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const i=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:n,type:a}of i)g(t,{id:n,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const i=t.pendingStreams;t.pendingStreams=[];for(const n of i)g(t,n)}const r=this.whisperHandlers.get(m(e));if(r)for(const i of r.keys())g(t,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(e).catch(()=>{})}})}handleDisconnect(t){if(this.closed||t.wsState==="idle"||t.wsState==="closed")return;this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket=void 0,t.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(t.shardKey);const e=new Set((t.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(m(i.shardKey)!==m(t.shardKey)||e.has(r))){if(i.durable){const n={...i.message,sinceChunk:i.lastSeq};i.message=n,t.pendingStreams=[...(t.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=t.reconnect.next();t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,this.ensureSocket(t.shardKey)},s)}startHeartbeat(t,e){this.stopHeartbeat(t),!(this.heartbeatIntervalMs<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;const{socket:s}=t;if(Date.now()-t.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}e();return}try{s.send(dt)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(t){t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)}markShardPendingAck(t){const e=m(t);for(const s of this.subscriptions.all())m(s.shardKey)===e&&(s.acked=!1)}sendSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);if(e?.wsState!=="open"||t.acked)return;const s=t.fn.__lunoraTable??t.fn.__lunoraRef;g(e,{id:t.id,query:{args:B(t.args),functionPath:t.fn.__lunoraRef,table:s,...t.serverCursor===void 0?{}:{sinceSeq:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);e?.wsState==="open"&&g(e,{id:t.id,shape:{name:t.name,...t.wireArgs===void 0?{}:{args:t.wireArgs}},type:"shape_subscribe",...t.serverCursor===void 0?{}:{sinceCheckpoint:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}})}handleServerMessage(t,e){const s=Me(t);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,id:n,seq:a}=r,o=this.streams.get(n);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,e);break}}}handleErrorMessage(t){if(t.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:e}=t,s=e===void 0?void 0:this.streams.get(e);if(s&&e!==void 0){s.handle.fail(xe(t)),this.streams.delete(e);return}const r=e===void 0?void 0:this.subscriptions.getById(e);if(r){E(r.errorCallbacks,N(t));return}const i=e===void 0?void 0:this.shapeSubscriptions.get(e);i&&E(i.errorCallbacks,N(t))}handlePokeStart(t){ot(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(t.pokeId,{baseCheckpoint:t.baseCheckpoint,epoch:t.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(t){const e=this.pokeBuffers.get(t.pokeId);if(!e)return;const s=e.parts.get(t.shapeId)??[];for(const r of t.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.value)});e.parts.set(t.shapeId,s),t.lastMutationId!==void 0&&e.lastMutationId.set(t.shapeId,t.lastMutationId)}handlePokeEnd(t){const e=this.pokeBuffers.get(t.pokeId);if(e){this.pokeBuffers.delete(t.pokeId);for(const[s,r]of e.parts){const i=this.shapeSubscriptions.get(s);if(!i)continue;const n=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,a=e.baseCheckpoint!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==e.baseCheckpoint;if(n||a){i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,this.emitShapeRows(i),this.sendShapeSubscribeIfOpen(i);continue}ut(i.rows,r),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const o=e.lastMutationId.get(s);o!==void 0&&(i.lastMutationId=o),this.emitShapeRows(i),i.onCheckpoint?.({checkpoint:i.serverCursor,mutationId:i.lastMutationId})}}}emitShapeRows(t){const e=[...t.rows.values()];for(const s of t.callbacks)try{s(e)}catch{}}handleDataMessage(t){const{id:e}=t,s=e?this.subscriptions.getById(e):void 0;if(!s)return;const r=this.resolveDataPayload(t,s);if(s.serverBase=r,t.cursor!==void 0&&(s.serverCursor=t.cursor),t.epoch!==void 0&&(s.serverEpoch=t.epoch),t.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,t.lastMutationId);for(const i of s.checkpointCallbacks)i({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),F(s,s.serverCursor),P(s,A(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(t){const e=this.subscriptions.getById(t.id);e&&this.ackAndAdvanceCursor(e,t.cursor,t.epoch)}handleSettledMessage(t){const e=this.subscriptions.getById(t.id);if(e){this.ackAndAdvanceCursor(e,t.cursor,t.epoch),t.lastMutationId!==void 0&&(e.lastMutationId=t.lastMutationId);for(const s of e.checkpointCallbacks)s({checkpoint:e.serverCursor,mutationId:e.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=w.key(e.fn.__lunoraRef,e.args,e.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,e.serverCursor,e.serverEpoch,e.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(t,e,s){t.acked=!0,(e!==void 0&&e!==t.serverCursor||s!==void 0&&s!==t.serverEpoch)&&(e!==void 0&&(t.serverCursor=e),s!==void 0&&(t.serverEpoch=s),this.persistQueryValue(t),F(t,t.serverCursor)&&P(t,A(t.serverBase,t.optimisticLayers)))}resolveDataPayload(t,e){if("data"in t&&t.data!==void 0)return b(t.data);const s=b(t.delta);if(D(s)&&e.serverBase!==void 0){const r=j(e.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(m(e))?.get(t.topic);if(!s)return;const r=b(t.data);for(const i of s)try{i(r,t.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(t){const e=this.streams.get(t);if(e){e.handle.complete(),this.streams.delete(t);return}const s=this.subscriptions.getById(t);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(t){t&&this.persistence?.remove(t).catch(e=>{rt(this.onPersistenceError,"remove",e,t)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const t=this.authToken;return t===null?null:this.hashToken(t)}hashToken(t){let e=2166136261,s=5381;for(let r=0;r<t.length;r+=1){const i=t.charCodeAt(r);e^=i,e=Math.imul(e,16777619),s=Math.imul(s,33)+i}return`${t.length.toString(36)}:${(e>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(t){if(t===null||t.startsWith("subj:"))return!1;const e=this.authToken;return e===null?!1:this.hashToken(e)===t}rejectQueuedForIdentityChange(){const t=this.offlineQueue.drain();for(const e of t){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",e.reject(s),this.emitItemSettled(e,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(t,e){for(const[s,r]of this.queuedIdentities)r===t&&this.queuedIdentities.set(s,e)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const t of this.queuedOfflineShardKeys)this.flushOfflineQueue(t).catch(()=>{})}async flushOfflineQueue(t){const e=this.offlineQueue.drainConflict();for(const c of e){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",u)}const s=m(t),r=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(r.length===0)return;const i=this.identityFingerprint(),n=[];for(const c of r)this.passesReplayIdentityGate(c,i)&&n.push(c);if(n.length===0)return;const a=this.encodableOrSettleTerminal(n);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=R){const u=a.slice(c,c+R),d=await this.replayBatched(u);if(o.push(...d.requeue),d.stop){o.push(...a.slice(c+R));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(t){const e=[];for(const s of t)try{k(s.args,`args for '${s.functionPath}'`),e.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),r=s===void 0?t.identity:s;if(r!==void 0&&r!==e&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",t.reject(i),this.emitItemSettled(t,"rejected",i),!1}return this.queuedIdentities.delete(t.id??""),!0}settleReplaySuccess(t,e,s){this.unpersist(t.id),this.recordShardCursor(t.shardKey,s),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}cursorKeyFor(t){return t??this.defaultShardKey??""}learnDefaultShardKey(t,e){const s=t.headers.get("x-lunora-shard-key");if(s===null||e!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(t,e){if(typeof e!="number")return;const s=this.cursorKeyFor(t);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,e))}settleReplayTerminal(t,e){this.unpersist(t.id),t.reject(e),this.emitItemSettled(t,"rejected",e)}async replaySequential(t){for(let e=0;e<t.length;e+=1){const s=t[e];if(s)try{let r;const i=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:n=>{r=n}});this.settleReplaySuccess(s,i,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);continue}this.offlineQueue.requeue(t.slice(e));return}}}async replayBatched(t){if(!this.fetchImpl)return{requeue:t,stop:!0};let e;try{e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args,`args for '${i.functionPath}'`),functionPath:i.functionPath,id:n,clientId:i.clientId??this.clientId,mutationId:i.id,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:t,stop:!0}}const s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{return{requeue:t,stop:!0}}if(!r.results){if(r.error){const i=T(r.error);for(const n of t)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,r.results),stop:!1}}settleReplayBatchSlots(t,e){const s=new Map;for(const i of e)typeof i.id=="number"&&i.body!==void 0&&s.set(i.id,i.body);const r=[];for(const[i,n]of t.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Ke.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,T(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};
@@ -1 +1 @@
1
- import{t as a}from"./wire-key-j8BZ65HQ.mjs";class y{static key(e,t,s){return`${e}::${a(t)}::${s??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(y.key(e.fn.__lunoraRef,e.args,e.shardKey),e),this.byId.set(e.id,e)}remove(e){const t=y.key(e.fn.__lunoraRef,e.args,e.shardKey);this.byKey.get(t)===e&&this.byKey.delete(t),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}}export{y as SubscriptionRegistry};
1
+ import{t as a}from"./wire-key-Cb-kXfSh.mjs";class y{static key(e,t,s){return`${e}::${a(t)}::${s??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(y.key(e.fn.__lunoraRef,e.args,e.shardKey),e),this.byId.set(e.id,e)}remove(e){const t=y.key(e.fn.__lunoraRef,e.args,e.shardKey);this.byKey.get(t)===e&&this.byKey.delete(t),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}}export{y as SubscriptionRegistry};
@@ -0,0 +1 @@
1
+ import{y as e,w as l}from"./delta-merge-DoT5IpTP.mjs";export{e as applyDelta,l as isMutationDelta};
@@ -0,0 +1 @@
1
+ import{c as t}from"./local-store-CGsgaEph.mjs";import"./SubscriptionRegistry-HXgW6BXq.mjs";export{t as createLocalStore};
@@ -1 +1 @@
1
- import{LunoraClient as r}from"./LunoraClient-CbRvTqjM.mjs";const o=t=>{const e=new r({fetch:t.fetch,url:t.url});return t.token!==void 0&&e.setAuthToken(t.token),e};export{o as createServerClient};
1
+ import{LunoraClient as r}from"./LunoraClient-BluyW2SA.mjs";const o=t=>{const e=new r({fetch:t.fetch,url:t.url});return t.token!==void 0&&e.setAuthToken(t.token),e};export{o as createServerClient};
@@ -1 +1 @@
1
- import{t as n}from"./wire-key-j8BZ65HQ.mjs";const d=(r,t,i,u)=>{const a=r.peekActiveQueryValue(t.__lunoraRef,i,u),e=a===void 0?void 0:n(a);return()=>{const o=r.peekActiveQueryValue(t.__lunoraRef,i,u);return e===void 0&&o===void 0?!0:e===void 0||o===void 0?!1:n(o)===e}};export{d as default};
1
+ import{t as n}from"./wire-key-Cb-kXfSh.mjs";const d=(r,t,i,u)=>{const a=r.peekActiveQueryValue(t.__lunoraRef,i,u),e=a===void 0?void 0:n(a);return()=>{const o=r.peekActiveQueryValue(t.__lunoraRef,i,u);return e===void 0&&o===void 0?!0:e===void 0||o===void 0?!1:n(o)===e}};export{d as default};
@@ -0,0 +1 @@
1
+ import{A as a}from"./wire-codec-aTWt2XiW.mjs";const u="_id",c="_creationTime",p="page",h="pageDelta",d=r=>{if(Array.isArray(r))return r;if(a(r)&&Array.isArray(r[p]))return r[p]},g=r=>{let t;for(const e of r){const o=e[c];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},A=(r,t)=>{const e=t[c];if(typeof e!="number")return r.length;const o=g(r);for(const[s,f]of r.entries()){const n=f[c];if(typeof n=="number"&&(o?n<e:n>e))return s}return r.length},b=r=>{if(typeof r!="object"||r===null)return;const t=r[u];return typeof t=="string"?t:void 0},k=r=>{if(typeof r!="object"||r===null)return!1;const t=r;return typeof t.key=="string"&&typeof t.table=="string"&&(t.op==="insert"||t.op==="update"||t.op==="delete")},m=(r,t)=>{const e=[];for(const i of r){if(b(i)===void 0)return;e.push(i)}const{key:o,op:s,row:f}=t;if(s==="delete"){const i=e.filter(y=>y[u]!==o);return i.length===e.length?[...e]:i}if(f===void 0)return;const n=[...e],l=e.findIndex(i=>i[u]===o);return l===-1?n.splice(A(e,f),0,f):n[l]=f,n},$=(r,t)=>{const e=d(r);if(e===void 0)return;const o=m(e,t);return o===void 0||Array.isArray(r)?o:{...r,[p]:o}};export{h as a,k as w,$ as y};
@@ -1 +1 @@
1
- import{SubscriptionRegistry as f}from"./SubscriptionRegistry-C72rCp44.mjs";const m=(t,s)=>{let e=t;for(const o of s)try{e=o.transform(e)}catch{}return e},u=(t,s)=>{if(s!==t.lastValue){t.lastValue=s;for(const e of t.callbacks)try{e(s)}catch{}}},p=(t,s)=>{let e;try{e=s(t.lastValue)}catch{return}const o={id:Symbol("optimistic"),transform:s};t.optimisticLayers.push(o),u(t,e);const i=()=>{const r=t.optimisticLayers.findIndex(c=>c.id===o.id);return r===-1?!1:(t.optimisticLayers.splice(r,1),!0)},a=()=>{u(t,m(t.serverBase,t.optimisticLayers))};return{confirm:r=>{if(r===void 0){i();return}o.commitCursor=r,t.serverCursor!==void 0&&t.serverCursor>=r&&i()&&a()},rollback:()=>{i()&&a()}}},d=(t,s)=>{if(s===void 0||t.optimisticLayers.length===0)return!1;const e=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(o=>o.commitCursor===void 0||o.commitCursor>s),t.optimisticLayers.length!==e},L=(t,s)=>{const e=[],o=[],i=(a,r)=>t.get(f.key(a,r,s));return{confirms:e,rollbacks:o,store:{getAllQueries:a=>{const r=[];for(const c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(s??"")&&r.push({args:c.args,value:c.lastValue});return r},getQuery:(a,r)=>i(a.__lunoraRef,r??{})?.lastValue,setQuery:(a,r,c)=>{const l=i(a.__lunoraRef,r??{});if(!l)return;const n=p(l,()=>c);n&&(e.push(n.confirm),o.push(n.rollback))}}}};export{p as a,L as c,d,m as f,u as n};
1
+ import{SubscriptionRegistry as f}from"./SubscriptionRegistry-HXgW6BXq.mjs";const m=(t,s)=>{let e=t;for(const o of s)try{e=o.transform(e)}catch{}return e},u=(t,s)=>{if(s!==t.lastValue){t.lastValue=s;for(const e of t.callbacks)try{e(s)}catch{}}},p=(t,s)=>{let e;try{e=s(t.lastValue)}catch{return}const o={id:Symbol("optimistic"),transform:s};t.optimisticLayers.push(o),u(t,e);const i=()=>{const r=t.optimisticLayers.findIndex(c=>c.id===o.id);return r===-1?!1:(t.optimisticLayers.splice(r,1),!0)},a=()=>{u(t,m(t.serverBase,t.optimisticLayers))};return{confirm:r=>{if(r===void 0){i();return}o.commitCursor=r,t.serverCursor!==void 0&&t.serverCursor>=r&&i()&&a()},rollback:()=>{i()&&a()}}},d=(t,s)=>{if(s===void 0||t.optimisticLayers.length===0)return!1;const e=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(o=>o.commitCursor===void 0||o.commitCursor>s),t.optimisticLayers.length!==e},L=(t,s)=>{const e=[],o=[],i=(a,r)=>t.get(f.key(a,r,s));return{confirms:e,rollbacks:o,store:{getAllQueries:a=>{const r=[];for(const c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(s??"")&&r.push({args:c.args,value:c.lastValue});return r},getQuery:(a,r)=>i(a.__lunoraRef,r??{})?.lastValue,setQuery:(a,r,c)=>{const l=i(a.__lunoraRef,r??{});if(!l)return;const n=p(l,()=>c);n&&(e.push(n.confirm),o.push(n.rollback))}}}};export{p as a,L as c,d,m as f,u as n};
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-w4VrTsKH.js";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-CsuRAQvb.js";
2
2
  import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
3
  /**
4
4
  * Reactive key-value store for local-only client state.
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-w4VrTsKH.mjs";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-CsuRAQvb.mjs";
2
2
  import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
3
  /**
4
4
  * Reactive key-value store for local-only client state.
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "./lunora-client.d-Kd72FRSr.js";
2
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-w4VrTsKH.js";
1
+ import { L as LunoraClient } from "./lunora-client.d-Dv40CCsu.js";
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-CsuRAQvb.js";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
5
5
  * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "./lunora-client.d-DbRRvSya.mjs";
2
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-w4VrTsKH.mjs";
1
+ import { L as LunoraClient } from "./lunora-client.d-nHupuaoI.mjs";
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-CsuRAQvb.mjs";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
5
5
  * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
@@ -488,6 +488,13 @@ interface ClientUnsubscribeMessage {
488
488
  * `onDisconnect` when the socket drops.
489
489
  */
490
490
  interface ClientConnectMessage {
491
+ /**
492
+ * Wire behaviours this client can handle that an older one cannot, so the
493
+ * server can use them without breaking clients that can't. Currently just
494
+ * `"pageDelta"`; see `shared/page-result.ts` for what it promises and why it
495
+ * must be announced rather than assumed. Omitting it is always safe.
496
+ */
497
+ caps?: ReadonlyArray<string>;
491
498
  /**
492
499
  * Stable per-client id (persisted alongside the outbox). Lets the server
493
500
  * scope this connection's `__client_watermark` so custom-mutator pokes can
@@ -488,6 +488,13 @@ interface ClientUnsubscribeMessage {
488
488
  * `onDisconnect` when the socket drops.
489
489
  */
490
490
  interface ClientConnectMessage {
491
+ /**
492
+ * Wire behaviours this client can handle that an older one cannot, so the
493
+ * server can use them without breaking clients that can't. Currently just
494
+ * `"pageDelta"`; see `shared/page-result.ts` for what it promises and why it
495
+ * must be announced rather than assumed. Omitting it is always safe.
496
+ */
497
+ caps?: ReadonlyArray<string>;
491
498
  /**
492
499
  * Stable per-client id (persisted alongside the outbox). Lets the server
493
500
  * scope this connection's `__client_watermark` so custom-mutator pokes can
@@ -1 +1 @@
1
- const b=r=>{let n="";for(let u=0;u<r.length;u+=32768)n+=String.fromCharCode(...r.subarray(u,u+32768));return btoa(n)},g=r=>{const n=atob(r),u=new Uint8Array(n.length);for(let c=0;c<n.length;c+=1)u[c]=n.codePointAt(c)??0;return u},o="$lunora.wire$";const p="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},d={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},m=r=>{if(r===null||typeof r!="object")return!1;const n=Object.getPrototypeOf(r);return n===null||n===Object.prototype},s=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===void 0)return[o,"undefined"];if(r===null)return null;const u=typeof r;if(u==="bigint")return[o,"bigint",r.toString()];if(u==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(u!=="object")return r;if(r instanceof Date)return[o,"date",s(r.getTime(),n+1)];if(r instanceof Error){const e=r,a={};for(const l of Object.keys(e))e[l]!==void 0&&(a[l]=s(e[l],n+1));const i=[o,"error",e.name,e.message,a];return e.cause!==void 0&&i.push(s(e.cause,n+1)),i}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,a])=>[s(e,n+1),s(a,n+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>s(e,n+1))];if(r instanceof ArrayBuffer)return[o,"bytes",b(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,a=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return a==="Uint8Array"?[o,"bytes",b(i)]:[o,"bytes",b(i),a]}if(Array.isArray(r)){const e=r.map(a=>s(a,n+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!m(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=r,t={};for(const e of Object.keys(c)){const a=c[e];if(a===void 0)continue;const i=s(a,n+1);e===p?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}return t},f=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>f(t,n+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>1024||!/^-?\d+$/.test(t))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(t)}case"date":return new Date(f(r[2],n+1));case"map":return new Map(r[2].map(([t,e])=>[f(t,n+1),f(e,n+1)]));case"set":return new Set(r[2].map(t=>f(t,n+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],a=(Object.hasOwn(d,t)?d[t]:void 0)??Error,i=new a(e);i.name!==t&&Object.defineProperty(i,"name",{configurable:!0,value:t,writable:!0});const l=f(r[4],n+1);for(const y of Object.keys(l))y===p?Object.defineProperty(i,y,{configurable:!0,enumerable:!0,value:l[y],writable:!0}):i[y]=l[y];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(r[5],n+1),writable:!0}),i}case"bytes":{const t=g(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const a=Object.hasOwn(w,e)?w[e]:void 0;return a?new a(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>f(t,n+1))}return r.map(t=>f(t,n+1))}const u=r,c={};for(const t of Object.keys(u)){const e=f(u[t],n+1);t===p?Object.defineProperty(c,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):c[t]=e}return c};export{s as a,f as s};
1
+ const b=r=>{let n="";for(let u=0;u<r.length;u+=32768)n+=String.fromCharCode(...r.subarray(u,u+32768));return btoa(n)},g=r=>{const n=atob(r),u=new Uint8Array(n.length);for(let c=0;c<n.length;c+=1)u[c]=n.codePointAt(c)??0;return u},o="$lunora.wire$";const p="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},d={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},m=r=>{if(r===null||typeof r!="object")return!1;const n=Object.getPrototypeOf(r);return n===null||n===Object.prototype},s=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===void 0)return[o,"undefined"];if(r===null)return null;const u=typeof r;if(u==="bigint")return[o,"bigint",r.toString()];if(u==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(u!=="object")return r;if(r instanceof Date)return[o,"date",s(r.getTime(),n+1)];if(r instanceof Error){const e=r,a={};for(const l of Object.keys(e))e[l]!==void 0&&(a[l]=s(e[l],n+1));const i=[o,"error",e.name,e.message,a];return e.cause!==void 0&&i.push(s(e.cause,n+1)),i}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,a])=>[s(e,n+1),s(a,n+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>s(e,n+1))];if(r instanceof ArrayBuffer)return[o,"bytes",b(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,a=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return a==="Uint8Array"?[o,"bytes",b(i)]:[o,"bytes",b(i),a]}if(Array.isArray(r)){const e=r.map(a=>s(a,n+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!m(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=r,t={};for(const e of Object.keys(c)){const a=c[e];if(a===void 0)continue;const i=s(a,n+1);e===p?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}return t},f=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>f(t,n+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>1024||!/^-?\d+$/.test(t))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(t)}case"date":return new Date(f(r[2],n+1));case"map":return new Map(r[2].map(([t,e])=>[f(t,n+1),f(e,n+1)]));case"set":return new Set(r[2].map(t=>f(t,n+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],a=(Object.hasOwn(d,t)?d[t]:void 0)??Error,i=new a(e);i.name!==t&&Object.defineProperty(i,"name",{configurable:!0,value:t,writable:!0});const l=f(r[4],n+1);for(const y of Object.keys(l))y===p?Object.defineProperty(i,y,{configurable:!0,enumerable:!0,value:l[y],writable:!0}):i[y]=l[y];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(r[5],n+1),writable:!0}),i}case"bytes":{const t=g(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const a=Object.hasOwn(w,e)?w[e]:void 0;return a?new a(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>f(t,n+1))}return r.map(t=>f(t,n+1))}const u=r,c={};for(const t of Object.keys(u)){const e=f(u[t],n+1);t===p?Object.defineProperty(c,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):c[t]=e}return c};export{m as A,s as a,f as s};
@@ -1 +1 @@
1
- import{a as c}from"./wire-codec-D_fiax9d.mjs";const y=(e,t)=>e<t?-1:e>t?1:0,n=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>n(r)).join(",")}]`;const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const r=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=e,s=Object.keys(o).toSorted(y),i=[];for(const r of s){const a=o[r];a!==void 0&&i.push(`${JSON.stringify(r)}:${n(a)}`)}return`{${i.join(",")}}`},l=e=>n(c(e));export{l as t};
1
+ import{a as c}from"./wire-codec-aTWt2XiW.mjs";const y=(e,t)=>e<t?-1:e>t?1:0,n=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>n(r)).join(",")}]`;const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const r=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=e,s=Object.keys(o).toSorted(y),i=[];for(const r of s){const a=o[r];a!==void 0&&i.push(`${JSON.stringify(r)}:${n(a)}`)}return`{${i.join(",")}}`},l=e=>n(c(e));export{l as t};
@@ -1,6 +1,6 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-w4VrTsKH.mjs";
2
- import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
3
- export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.mjs";
2
+ import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
3
+ export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1,6 +1,6 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-w4VrTsKH.js";
2
- import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
3
- export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.js";
2
+ import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
3
+ export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-w4VrTsKH.mjs";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-CsuRAQvb.mjs";
2
2
  /**
3
3
  * The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
4
4
  * route; the envelope shape below is that route's documented contract.
package/dist/service.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-w4VrTsKH.js";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-CsuRAQvb.js";
2
2
  /**
3
3
  * The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
4
4
  * route; the envelope shape below is that route's documented contract.
package/dist/service.mjs CHANGED
@@ -1 +1 @@
1
- import{LunoraError as u}from"@lunora/errors";import{a as f,s as w}from"./packem_shared/wire-codec-D_fiax9d.mjs";const p="/_lunora/rpc",$="https://lunora.internal",g=e=>{const t=new Error(e.message??"request failed");return t.code=e.code,e.data!==void 0&&(t.data=w(e.data)),e.hint!==void 0&&(t.hint=e.hint),e.docsUrl!==void 0&&(t.docsUrl=e.docsUrl),t},h=async(e,t,a,o,d)=>{const s=a.__lunoraRef;let l;try{l=JSON.stringify({args:f(o??{}),functionPath:s,...d?.shardKey===void 0?{}:{shardKey:d.shardKey}})}catch(n){const y=n instanceof Error?n.message:String(n);throw new TypeError(`@lunora/client/service: cannot encode args for '${s}' — ${y}`,n instanceof Error?{cause:n}:void 0)}const r=await e.fetch(new Request(`${$}${p}`,{body:l,headers:{"content-type":"application/json"},method:"POST"}));let i;try{i=await r.json()}catch{throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" got a non-JSON response (status ${r.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:r.status})}if(i===null||typeof i!="object")throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" returned a JSON body that is not an object (status ${r.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:r.status});const c=i;if("error"in c)throw g(c.error);if(!r.ok)throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" failed with status ${r.status.toString()} and no error envelope.`,{status:r.status});return w(c.result)},m=e=>({action:async(t,a,o)=>await h(e,"action",t,a,o),mutation:async(t,a,o)=>await h(e,"mutation",t,a,o),query:async(t,a,o)=>await h(e,"query",t,a,o)});export{p as RPC_PATH,m as createServiceClient};
1
+ import{LunoraError as u}from"@lunora/errors";import{a as f,s as w}from"./packem_shared/wire-codec-aTWt2XiW.mjs";const p="/_lunora/rpc",$="https://lunora.internal",g=e=>{const t=new Error(e.message??"request failed");return t.code=e.code,e.data!==void 0&&(t.data=w(e.data)),e.hint!==void 0&&(t.hint=e.hint),e.docsUrl!==void 0&&(t.docsUrl=e.docsUrl),t},h=async(e,t,a,o,d)=>{const s=a.__lunoraRef;let l;try{l=JSON.stringify({args:f(o??{}),functionPath:s,...d?.shardKey===void 0?{}:{shardKey:d.shardKey}})}catch(n){const y=n instanceof Error?n.message:String(n);throw new TypeError(`@lunora/client/service: cannot encode args for '${s}' — ${y}`,n instanceof Error?{cause:n}:void 0)}const r=await e.fetch(new Request(`${$}${p}`,{body:l,headers:{"content-type":"application/json"},method:"POST"}));let i;try{i=await r.json()}catch{throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" got a non-JSON response (status ${r.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:r.status})}if(i===null||typeof i!="object")throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" returned a JSON body that is not an object (status ${r.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:r.status});const c=i;if("error"in c)throw g(c.error);if(!r.ok)throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" failed with status ${r.status.toString()} and no error envelope.`,{status:r.status});return w(c.result)},m=e=>({action:async(t,a,o)=>await h(e,"action",t,a,o),mutation:async(t,a,o)=>await h(e,"mutation",t,a,o),query:async(t,a,o)=>await h(e,"query",t,a,o)});export{p as RPC_PATH,m as createServiceClient};
@@ -1,7 +1,7 @@
1
- import { P as Preloaded } from "../packem_shared/types.d-w4VrTsKH.mjs";
2
- export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-w4VrTsKH.mjs";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-BmSiP8F_.mjs";
4
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
1
+ import { P as Preloaded } from "../packem_shared/types.d-CsuRAQvb.mjs";
2
+ export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-CsuRAQvb.mjs";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-y5DTDa0X.mjs";
4
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
5
5
  import '@lunora/runtime';
6
6
  /**
7
7
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1,7 +1,7 @@
1
- import { P as Preloaded } from "../packem_shared/types.d-w4VrTsKH.js";
2
- export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-w4VrTsKH.js";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-D55TcvEq.js";
4
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
1
+ import { P as Preloaded } from "../packem_shared/types.d-CsuRAQvb.js";
2
+ export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-CsuRAQvb.js";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-DtFFNok3.js";
4
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
5
5
  import '@lunora/runtime';
6
6
  /**
7
7
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1 +1 @@
1
- import{getServerSession as o}from"../packem_shared/getServerSession-CGjgRBAE.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-BU2gC5p6.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-DjwSjFwt.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
1
+ import{getServerSession as o}from"../packem_shared/getServerSession-CGjgRBAE.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-DoNhxkkm.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-DjwSjFwt.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/client",
3
- "version": "1.0.0-alpha.47",
3
+ "version": "1.0.0-alpha.48",
4
4
  "description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{s as b,a as B}from"./wire-codec-D_fiax9d.mjs";import{t as I}from"./wire-key-j8BZ65HQ.mjs";import D from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as j}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as H}from"./TabCoordinator-CMFYQCL-.mjs";import{isMutationDelta as V,applyDelta as J}from"./applyDelta-DXqQORbM.mjs";import{httpStream as X}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Y,c as Z}from"./local-store-DFMSEM2j.mjs";import{h as tt,u as $,d as et,s as st}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as rt}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as it,queryCacheKey as R}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as nt}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-C72rCp44.mjs";const x=500,at=(h,t)=>{if(h.size<t)return;const e=h.keys().next().value;e!==void 0&&h.delete(e)};class C{listeners=new Set;add(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(...t){const[e]=t;for(const s of this.listeners)try{s(e)}catch{}}clear(){this.listeners.clear()}}const ot="/_lunora/rpc",Q="/_lunora/rpc-batch",ct="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,O=h=>{for(let t=h.length-1;t>=0;t-=1)h[t]?.()},ht=(h,t)=>{for(const e of t)e.op==="delete"?h.delete(e.key):e.value!==void 0&&h.set(e.key,e.value)},ut="lunora-ping",dt=3e4,lt=1e4,pt=250,mt=64,ft="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",gt="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",St="/_lunora/admin/scheduled/cancel",vt="/_lunora/admin/scheduled/dead",kt="/_lunora/admin/scheduled/dead/retry",wt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",Tt="/_lunora/admin/workflows/instance",It="/_lunora/admin/workflows/status",L="/_lunora/admin/storage",Ot="/_lunora/admin/storage/url",Et="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",Ft="/_lunora/admin/cron-jobs",Pt="/_lunora/admin/cron-jobs/run",At="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",xt="/_lunora/admin/global/tables",Mt="/_lunora/admin/global/table",Lt="/_lunora/admin/global/facet",Kt="/_lunora/admin/vector/indexes",$t="/_lunora/admin/vector/query",qt="/_lunora/admin/logs/archive",Qt="/_lunora/admin/kv/namespaces",Ut="/_lunora/admin/kv/keys",K="/_lunora/admin/kv/value",Nt="/_lunora/admin/auth/users",Bt="/_lunora/admin/auth/sessions",Wt="/_lunora/admin/auth/users/create",zt="/_lunora/admin/auth/users/role",Gt="/_lunora/admin/auth/users/ban",Dt="/_lunora/admin/auth/users/unban",jt="/_lunora/admin/auth/users/password",Ht="/_lunora/admin/auth/users/remove",Vt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Xt="/_lunora/admin/auth/sessions/revoke-all",Yt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",te="/_lunora/admin/auth/accounts",ee="/_lunora/admin/auth/accounts/unlink",se="/_lunora/admin/auth/passkeys",re="/_lunora/admin/auth/passkeys/delete",ie="/_lunora/admin/auth/two-factor/disable",ne="/_lunora/admin/auth/organizations",ae="/_lunora/admin/auth/organizations/members",oe="/_lunora/admin/auth/organizations/invitations",ce="/_lunora/admin/auth/organizations/members/remove",he="/_lunora/admin/auth/organizations/invitations/cancel",ue="/_lunora/admin/auth/config",de="/_lunora/admin/auth/organizations/create",le="/_lunora/admin/auth/organizations/update",pe="/_lunora/admin/auth/organizations/remove",me="/_lunora/admin/auth/organizations/members/add",fe="/_lunora/admin/auth/organizations/members/invite",ye="/_lunora/admin/auth/organizations/members/role",ge="/_lunora/admin/auth/organizations/teams",be="/_lunora/admin/auth/organizations/teams/create",Se="/_lunora/admin/auth/organizations/teams/update",ve="/_lunora/admin/auth/organizations/teams/remove",ke="/_lunora/admin/auth/organizations/teams/members",we="/_lunora/admin/auth/organizations/teams/members/add",Ce="/_lunora/admin/auth/organizations/teams/members/remove",Te="/_lunora/admin/auth/organizations/roles",Ie="/_lunora/admin/auth/organizations/roles/create",Oe="/_lunora/admin/auth/organizations/roles/update",Ee="/_lunora/admin/auth/organizations/roles/remove",_e="/api/auth",Fe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[r,i]of Object.entries(t))i!==void 0&&i!==""&&e.set(r,String(i));const s=e.toString();return s===""?h:`${h}?${s}`},m=h=>h??"",W=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,r=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??t}},Pe=h=>{const{code:t,messageText:e}=W(h,"stream error");return t===void 0?new Error(e):new p(t,e)},N=h=>{const{code:t,messageText:e}=W(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Ae=new TextDecoder,Re=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Ae.decode(h)},g=(h,t)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(t)),!0}catch{return!1}},T=h=>{const t=new Error(h.message??"request failed");return t.code=h.code,h.data!==void 0&&(t.data=b(h.data)),h.hint!==void 0&&(t.hint=h.hint),h.docsUrl!==void 0&&(t.docsUrl=h.docsUrl),t},k=(h,t)=>{try{return B(h)}catch(e){const s=e instanceof Error?e.message:String(e);throw new TypeError(`LunoraClient: cannot encode ${t} — ${s}`,e instanceof Error?{cause:e}:void 0)}},xe=(h,t)=>{const e=Array.from({length:t});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=t)continue;const r=s.body;e[s.id]=r&&"error"in r&&r.error?{error:T(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Me=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Le=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(t,e){return{defaultValue:e,key:t}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(t){this.url=t.url,this.wsUrl=t.wsUrl??v(U(t.url),ct),this.wsToken=t.wsToken;const e=t.authBasePath??_e;this.authBasePath=e.endsWith("/")?e.slice(0,-1):e,this.fetchImpl=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=t.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=t.bookmarkStorage??D(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??dt,this.connectTimeoutMs=t.connectTimeoutMs??lt,this.defaultConnectionContext=t.connectionContext,this.persistence=rt(t.persistence,t.outbox===void 0),this.persistenceVersion=t.persistenceVersion,this.queryCache=it(t.queryCache),this.onPersistenceError=t.offlineQueue?.onPersistenceError,this.clientQueryStore=new j,t.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,t.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Le),this.offlineQueue=new tt(t.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${$()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(t,e){const s=this.authToken!==t,r=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const i=this.identityFingerprint();if(i!==r&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(r,i),this.tabCoordinator)){const n=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),n&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(t)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(t){return this.clientWatermarks.get(t??"")??0}async callMutator(t,e,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"";let n;const a=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:o=>{n=o}});return n!==void 0&&n>(this.clientWatermarks.get(i)??0)&&this.clientWatermarks.set(i,n),{applied:n===void 0||n===r,result:a}}onAuthTokenChange(t){return this.authTokenListeners.add(t)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const t={};this.authToken&&(t.authorization=`Bearer ${this.authToken}`);try{const e=await this.fetchImpl(v(this.url,`${this.authBasePath}${Fe}`),{credentials:"include",headers:t,method:"GET"});return e.ok?(await e.json())?.user??null:null}catch{return null}}setWsToken(t){if(this.wsToken!==t){this.wsToken=t;for(const e of this.connections.values())if(e.socket)try{e.socket.close()}catch{}}}setConnectionContext(t,e={}){const s=m(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=m(e.shardKey),r={context:t},i=this.connectionContextHolders.get(s);i?i.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let n=!1;return()=>{if(n)return;n=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const r=m(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(t);const a=n===void 0;if(n||(n=new Set,i.set(t,n)),n.add(e),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:t,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&g(u,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{data:k(e??null,`whisper data for topic '${t}'`),topic:t,type:"whisper"})}onTokenExpired(t){return this.tokenExpiredListeners.add(t)}connectionStatus(){return this.computeStatus()}onConnectionStatus(t){const e=this.statusListeners.add(t);return t(this.computeStatus()),e}pendingCount(){return this.offlineQueue.size}debug(){const t=[],e=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(const r of e){const i=this.connections.get(r);t.push({confirmedMutationWatermark:this.clientWatermarks.get(r)??0,hasSocket:i?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const s=this.subscriptions.all().map(r=>({acked:r.acked,functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())s.push({acked:r.serverCursor!==void 0,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((r,i)=>(r.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:s.toSorted((r,i)=>r.functionPath.localeCompare(i.functionPath))}}onPendingChange(t){const e=this.pendingChangeListeners.add(t);return t(this.offlineQueue.size),e}onMutationSettled(t){return this.mutationSettledListeners.add(t)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(t){return this.clientQueryStore.get(t)}setClientQuery(t,e){this.clientQueryStore.set(t,e)}subscribeClientQuery(t,e){return this.clientQueryStore.subscribe(t,e)}resetClientQuery(t){this.clientQueryStore.reset(t)}snapshotPrecondition(t,e,s){const r=this.peekActiveQueryValue(t.__lunoraRef,e,s),i=r===void 0?void 0:I(r);return()=>{const n=this.peekActiveQueryValue(t.__lunoraRef,e,s);return i===void 0&&n===void 0?!0:i===void 0||n===void 0?!1:I(n)===i}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const r=I(e),i=R(t,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQueryValue(t,e,s){const r=w.key(t,e,s);return this.subscriptions.get(r)?.lastValue}async query(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey,{attachBookmark:!0})}async batch(t){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args??{},`args for batch call '${i.fn.__lunoraRef}'`),functionPath:i.fn.__lunoraRef,id:n,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||r.error&&!r.results)throw r.error?T(r.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(t[i.id]?.shardKey,n)}return xe(r.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const r=e,i=s.mutationId??$(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,n);const{hasSocket:o,wasEverConnected:c,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:d}=this.offlineQueue,l=c||d,y=this.WebSocketImpl!==void 0&&l;if(u!=="open"&&!o&&y||u==="connecting"&&l)return this.enqueueOfflineMutation(t,r,s.shardKey,i,a,n,s.precondition);try{let S;const G=await this.rpc(t.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:_=>{S=_}});for(const _ of n)_(S);return G}catch(S){throw O(a),S}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=e.length;let a=0,o=0;for(let c=0;c<n;c+=r){const u=e.slice(c,c+r),d=o;await this.mutation(t,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(d)}`},shardKey:s.shardKey}),o+=1,a+=u.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(ft,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(yt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(gt,"GET");return{backlog:t.backlog??0,inFlight:t.inFlight??0,pools:t.pools??[]}}async cancelScheduledJob(t){return this.assertOpen(),{cancelled:(await this.adminFetch(St,"POST",{id:t})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(vt,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(kt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(wt,"POST",{id:t})).removed===!0}}async listWorkflowInstances(t){this.assertOpen();const e=new URLSearchParams({name:t.name});t.status!==void 0&&e.set("status",t.status),t.page!==void 0&&e.set("page",String(t.page)),t.perPage!==void 0&&e.set("perPage",String(t.perPage));const s=await this.adminFetch(`${Ct}?${e.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??t.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(t){this.assertOpen();const e=new URLSearchParams({id:t.id,name:t.name}),s=await this.adminFetch(`${Tt}?${e.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??t.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(t){return this.assertOpen(),{status:(await this.adminFetch(It,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=v(U(this.url),bt),s=q(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||(i=setTimeout(u,s.next()))},o=d=>{if(n||this.WebSocketImpl===void 0)return;const l=d===void 0?e:`${e}?token=${encodeURIComponent(d)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const S=JSON.parse(typeof y.data=="string"?y.data:"");S.type==="jobs"&&Array.isArray(S.records)&&t(S.records)}catch{}},onOpen:()=>{s.reset()}})},c=async d=>{let l;try{l=await d()}catch{a();return}o(l)},u=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:d}=this;if(typeof d=="function"){c(d).catch(()=>{});return}o(d)};return u(),()=>{n=!0,i!==void 0&&clearTimeout(i),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(Pt,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(At,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(L,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),s=await this.adminFetch(e,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(t,e){this.assertOpen();const s=`${L}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Et,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${L}?key=${encodeURIComponent(t.key)}${M(t.bucket)}`,s=await this.adminFetch(e,"PUT",t.body,t.contentType);return{etag:s.etag,key:s.key??t.key}}async signedStorageUrl(t,e){this.assertOpen();const s=e?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Ot}?key=${encodeURIComponent(t)}${r}${M(e?.bucket)}`,n=await this.adminFetch(i,"GET");if(typeof n.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return n.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(xt,"GET")}async readGlobalTablePage(t){this.assertOpen();const e=new URLSearchParams({table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.offset!==void 0&&e.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Mt}?${e.toString()}`,"GET")}async facetGlobalColumn(t){this.assertOpen();const e=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Lt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Kt,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch($t,"POST",t)).matches??[]}async queryLogArchive(t={}){this.assertOpen();const e=await this.adminFetch(qt,"POST",t);return{nextCursor:e.nextCursor,rows:e.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Qt,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Ut,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await this.adminFetch(e,"GET")}async getKvValue(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch(K,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Nt,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminFetch(e,"GET")}async createAuthUser(t){return await this.adminFetch(Wt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(zt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Gt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(jt,"POST",t)}async removeAuthUser(t){await this.adminFetch(Ht,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Vt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Jt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Xt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Yt,"GET")}async updateAuthUser(t){return await this.adminFetch(Zt,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(te,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(ee,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(se,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){await this.adminFetch(re,"POST",t)}async disableAuthTwoFactor(t){await this.adminFetch(ie,"POST",t)}async listAuthOrganizations(t={}){return await this.adminFetch(f(ne,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(ae,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(ce,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(he,"POST",t)}async getAuthConfig(){return await this.adminFetch(ue,"GET")}async createAuthOrganization(t){return await this.adminFetch(de,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(pe,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(me,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ye,"POST",t)}async listAuthOrgTeams(t){const e=f(ge,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(be,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(Se,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(ve,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(ke,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(we,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Ce,"POST",t)}async listAuthOrgRoles(t){const e=f(Te,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Ie,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(Ee,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Bt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,r={}){this.assertOpen();const i=e??{},n=w.key(t.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const d=`sub_${this.nextSubId.toString()}`,l=I(i),y=this.takeHydratedCache(t.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:d,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:r.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),c&&u.errorCallbacks.delete(c),r.onCheckpoint&&u.checkpointCallbacks.delete(r.onCheckpoint),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.subscriptions.remove(u))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:t.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:t.args===void 0?void 0:k(t.args,`shape args for '${t.name}'`)};return this.shapeSubscriptions.set(r,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(i.shardKey,r,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=e??{},{handle:a,iterable:o}=nt({maxBuffer:s.maxBuffer,onCancel:()=>{const d=this.getConnection(i);d&&g(d,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(i);const c=this.getConnection(i),u={id:r,query:{args:k(n,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:i},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:u,shardKey:i}),!(c?.wsState==="open"&&g(c,u))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=mt;){const d=c.pendingStreams.shift()?.id,l=d?this.streams.get(d):void 0;l&&(l.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(d))}c.pendingStreams.push(u)}return o}httpStream(t,e,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return X(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const t of this.streams.values())t.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const t of this.connections.values())this.teardownConnection(t);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}teardownConnection(t){if(t.reconnectTimer!==void 0&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),this.stopHeartbeat(t),t.socket){try{t.socket.close()}catch{}t.socket=void 0}t.wsState="closed"}createTabCoordinator(){const t=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new H({channelName:t,onBecomeLeader:()=>{for(const e of this.subscriptions.all())this.ensureSocket(e.shardKey),this.sendSubscribeIfOpen(e);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[e,s]of this.connections)this.teardownConnection(s),this.connections.delete(e);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(e,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),F(a,r)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const r=this.subscriptions.get(e);r&&E(r.errorCallbacks,s)},onSubscriptionSettled:(e,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(t,e,s,r,i,n,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:e,clientId:this.clientId,functionPath:t.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(u){throw O(i),u instanceof Error?u:new Error(String(u))}for(const u of n)u(void 0);return}return new Promise((c,u)=>{const d={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of n)y(l)},reject:l=>{this.queuedIdentities.delete(r),O(i),u(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(d),this.queuedOfflineShardKeys.add(s),d.id!==void 0&&this.queuedIdentities.set(d.id,o)})}async hydratePersistedQueue(){try{const t=await this.offlineQueue.hydrate();for(const e of t)this.queuedOfflineShardKeys.add(e),this.ensureSocket(e)}catch{}}hydrateAsOutboxLeader(){const t=()=>{this.hydratePersistedQueue().catch(()=>{})},e=globalThis.navigator?.locks;if(!e){t();return}e.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||t(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(t)}async hydrateQueryCache(){if(this.queryCache)try{const t=await this.queryCache.load();for(const{key:e,...s}of t){if(et(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const r=R(t,e,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=R(t.fn.__lunoraRef,t.argsKey,t.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:t.serverCursor,ts:Date.now(),value:e,...t.serverEpoch===void 0?{}:{serverEpoch:t.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},pt)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:t}=this;if(!t){this.pendingCacheWrites.clear();return}const e=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(e.map(([s,r])=>t.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const t=[...this.connections.values()];return t.length===0?"idle":t.some(e=>e.wsState==="open")?"connected":t.some(e=>e.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const t=this.computeStatus();t!==this.lastStatus&&(this.lastStatus=t,this.statusListeners.emit(t),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(t,this.identityFingerprint()))}emitItemSettled(t,e,s){this.mutationSettledListeners.emit({args:t.args,code:s===void 0?void 0:s.code,error:s,functionPath:t.functionPath,hadAwaiter:t.liveAwaiter??!1,id:t.id??"",shardKey:t.shardKey,status:e})}applyOptimisticUpdates(t,e,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Y(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(t,e,s,r,i){const{confirms:n,rollbacks:a,store:o}=Z(this.subscriptions,s);try{t(o,e)}catch{O(a);return}r.push(...a),i.push(...n)}getConnection(t){return this.connections.get(m(t))}sendOrQueueUnsubscribe(t,e,s){const r=this.getConnection(t);r&&!g(r,{id:e,type:s})&&r.pendingUnsubscribes.push({id:e,type:s})}connectionGateState(t){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const e=this.getConnection(t);return{hasSocket:e?.socket!==void 0,wasEverConnected:e?.wasEverConnected??!1,wsState:e?.wsState??"idle"}}getOrCreateConnection(t){const e=m(t);let s=this.connections.get(e);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:q(this.reconnectOptions),reconnectTimer:void 0,shardKey:t,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(e,s)),s}wsUrlFor(t,e){const s=[];if(t!==void 0&&s.push(`shard=${encodeURIComponent(t)}`),e!==void 0&&s.push(`token=${encodeURIComponent(e)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(t,e){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(e));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),t.mutationId&&(s["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(s["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(s["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(t,e,s,r={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(v(this.url,ot),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const o=n.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await n.json()}catch{const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${n.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!n.ok){const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(t,e,s,r){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const n=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:n?(a=s,r!==void 0&&(i["content-type"]=r)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(v(this.url,t),{body:a,headers:i,method:e});let c;try{c=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if(typeof c=="object"&&c!==null&&"error"in c){const u=c.error,d=new Error(u.message??"admin request failed");throw d.code=u.code,d}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}return c}effectiveConnectionContext(t){const e=this.connectionContextHolders.get(t);return e&&e.length>0?e[e.length-1]?.context:this.connectionContexts.get(t)??this.defaultConnectionContext}refreshConnectionContext(t){const e=this.connections.get(t);e?.wsState==="open"&&this.sendConnectEnvelope(e)}sendConnectEnvelope(t){const e=this.effectiveConnectionContext(m(t.shardKey));g(t,{clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())m(e.shardKey)===m(t)&&this.sendShapeSubscribeIfOpen(e)}ensureSocket(t){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const e=this.getOrCreateConnection(t);if(!(e.wsState==="open"||e.wsState==="connecting")){if(e.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(e,t,this.wsToken).catch(()=>{});return}this.openSocket(e,t,this.wsToken)}}async openSocketWithProvidedToken(t,e,s){let r;try{r=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,r)}openManagedSocket(t,e,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new p("INTERNAL","no WebSocket implementation available");const n=new i(e);t.socket=n;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===n&&(t.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{t.socket===n&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(t,o))}),n.addEventListener("message",c=>{t.socket===n&&(t.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{t.socket===n&&o(c)}),n.addEventListener("error",()=>{t.socket===n&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:r=>{this.handleServerMessage(r.data,e)},onOpen:()=>{t.wsState="open",t.wasEverConnected=!0,t.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(t),this.markShardPendingAck(e);for(const i of this.subscriptions.all())m(i.shardKey)===m(e)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const i=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:n,type:a}of i)g(t,{id:n,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const i=t.pendingStreams;t.pendingStreams=[];for(const n of i)g(t,n)}const r=this.whisperHandlers.get(m(e));if(r)for(const i of r.keys())g(t,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(e).catch(()=>{})}})}handleDisconnect(t){if(this.closed||t.wsState==="idle"||t.wsState==="closed")return;this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket=void 0,t.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(t.shardKey);const e=new Set((t.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(m(i.shardKey)!==m(t.shardKey)||e.has(r))){if(i.durable){const n={...i.message,sinceChunk:i.lastSeq};i.message=n,t.pendingStreams=[...(t.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=t.reconnect.next();t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,this.ensureSocket(t.shardKey)},s)}startHeartbeat(t,e){this.stopHeartbeat(t),!(this.heartbeatIntervalMs<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;const{socket:s}=t;if(Date.now()-t.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}e();return}try{s.send(ut)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(t){t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)}markShardPendingAck(t){const e=m(t);for(const s of this.subscriptions.all())m(s.shardKey)===e&&(s.acked=!1)}sendSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);if(e?.wsState!=="open"||t.acked)return;const s=t.fn.__lunoraTable??t.fn.__lunoraRef;g(e,{id:t.id,query:{args:B(t.args),functionPath:t.fn.__lunoraRef,table:s,...t.serverCursor===void 0?{}:{sinceSeq:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);e?.wsState==="open"&&g(e,{id:t.id,shape:{name:t.name,...t.wireArgs===void 0?{}:{args:t.wireArgs}},type:"shape_subscribe",...t.serverCursor===void 0?{}:{sinceCheckpoint:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}})}handleServerMessage(t,e){const s=Re(t);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,id:n,seq:a}=r,o=this.streams.get(n);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,e);break}}}handleErrorMessage(t){if(t.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:e}=t,s=e===void 0?void 0:this.streams.get(e);if(s&&e!==void 0){s.handle.fail(Pe(t)),this.streams.delete(e);return}const r=e===void 0?void 0:this.subscriptions.getById(e);if(r){E(r.errorCallbacks,N(t));return}const i=e===void 0?void 0:this.shapeSubscriptions.get(e);i&&E(i.errorCallbacks,N(t))}handlePokeStart(t){at(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(t.pokeId,{baseCheckpoint:t.baseCheckpoint,epoch:t.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(t){const e=this.pokeBuffers.get(t.pokeId);if(!e)return;const s=e.parts.get(t.shapeId)??[];for(const r of t.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.value)});e.parts.set(t.shapeId,s),t.lastMutationId!==void 0&&e.lastMutationId.set(t.shapeId,t.lastMutationId)}handlePokeEnd(t){const e=this.pokeBuffers.get(t.pokeId);if(e){this.pokeBuffers.delete(t.pokeId);for(const[s,r]of e.parts){const i=this.shapeSubscriptions.get(s);if(!i)continue;const n=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,a=e.baseCheckpoint!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==e.baseCheckpoint;if(n||a){i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,this.emitShapeRows(i),this.sendShapeSubscribeIfOpen(i);continue}ht(i.rows,r),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const o=e.lastMutationId.get(s);o!==void 0&&(i.lastMutationId=o),this.emitShapeRows(i),i.onCheckpoint?.({checkpoint:i.serverCursor,mutationId:i.lastMutationId})}}}emitShapeRows(t){const e=[...t.rows.values()];for(const s of t.callbacks)try{s(e)}catch{}}handleDataMessage(t){const{id:e}=t,s=e?this.subscriptions.getById(e):void 0;if(!s)return;const r=this.resolveDataPayload(t,s);if(s.serverBase=r,t.cursor!==void 0&&(s.serverCursor=t.cursor),t.epoch!==void 0&&(s.serverEpoch=t.epoch),t.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,t.lastMutationId);for(const i of s.checkpointCallbacks)i({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),F(s,s.serverCursor),P(s,A(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(t){const e=this.subscriptions.getById(t.id);e&&this.ackAndAdvanceCursor(e,t.cursor,t.epoch)}handleSettledMessage(t){const e=this.subscriptions.getById(t.id);if(e){this.ackAndAdvanceCursor(e,t.cursor,t.epoch),t.lastMutationId!==void 0&&(e.lastMutationId=t.lastMutationId);for(const s of e.checkpointCallbacks)s({checkpoint:e.serverCursor,mutationId:e.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=w.key(e.fn.__lunoraRef,e.args,e.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,e.serverCursor,e.serverEpoch,e.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(t,e,s){t.acked=!0,(e!==void 0&&e!==t.serverCursor||s!==void 0&&s!==t.serverEpoch)&&(e!==void 0&&(t.serverCursor=e),s!==void 0&&(t.serverEpoch=s),this.persistQueryValue(t),F(t,t.serverCursor)&&P(t,A(t.serverBase,t.optimisticLayers)))}resolveDataPayload(t,e){if("data"in t&&t.data!==void 0)return b(t.data);const s=b(t.delta);if(V(s)&&e.serverBase!==void 0){const r=J(e.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(m(e))?.get(t.topic);if(!s)return;const r=b(t.data);for(const i of s)try{i(r,t.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(t){const e=this.streams.get(t);if(e){e.handle.complete(),this.streams.delete(t);return}const s=this.subscriptions.getById(t);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(t){t&&this.persistence?.remove(t).catch(e=>{st(this.onPersistenceError,"remove",e,t)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const t=this.authToken;return t===null?null:this.hashToken(t)}hashToken(t){let e=2166136261,s=5381;for(let r=0;r<t.length;r+=1){const i=t.charCodeAt(r);e^=i,e=Math.imul(e,16777619),s=Math.imul(s,33)+i}return`${t.length.toString(36)}:${(e>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(t){if(t===null||t.startsWith("subj:"))return!1;const e=this.authToken;return e===null?!1:this.hashToken(e)===t}rejectQueuedForIdentityChange(){const t=this.offlineQueue.drain();for(const e of t){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",e.reject(s),this.emitItemSettled(e,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(t,e){for(const[s,r]of this.queuedIdentities)r===t&&this.queuedIdentities.set(s,e)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const t of this.queuedOfflineShardKeys)this.flushOfflineQueue(t).catch(()=>{})}async flushOfflineQueue(t){const e=this.offlineQueue.drainConflict();for(const c of e){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",u)}const s=m(t),r=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(r.length===0)return;const i=this.identityFingerprint(),n=[];for(const c of r)this.passesReplayIdentityGate(c,i)&&n.push(c);if(n.length===0)return;const a=this.encodableOrSettleTerminal(n);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=x){const u=a.slice(c,c+x),d=await this.replayBatched(u);if(o.push(...d.requeue),d.stop){o.push(...a.slice(c+x));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(t){const e=[];for(const s of t)try{k(s.args,`args for '${s.functionPath}'`),e.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),r=s===void 0?t.identity:s;if(r!==void 0&&r!==e&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",t.reject(i),this.emitItemSettled(t,"rejected",i),!1}return this.queuedIdentities.delete(t.id??""),!0}settleReplaySuccess(t,e,s){this.unpersist(t.id),this.recordShardCursor(t.shardKey,s),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}cursorKeyFor(t){return t??this.defaultShardKey??""}learnDefaultShardKey(t,e){const s=t.headers.get("x-lunora-shard-key");if(s===null||e!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(t,e){if(typeof e!="number")return;const s=this.cursorKeyFor(t);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,e))}settleReplayTerminal(t,e){this.unpersist(t.id),t.reject(e),this.emitItemSettled(t,"rejected",e)}async replaySequential(t){for(let e=0;e<t.length;e+=1){const s=t[e];if(s)try{let r;const i=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:n=>{r=n}});this.settleReplaySuccess(s,i,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);continue}this.offlineQueue.requeue(t.slice(e));return}}}async replayBatched(t){if(!this.fetchImpl)return{requeue:t,stop:!0};let e;try{e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args,`args for '${i.functionPath}'`),functionPath:i.functionPath,id:n,clientId:i.clientId??this.clientId,mutationId:i.id,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:t,stop:!0}}const s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{return{requeue:t,stop:!0}}if(!r.results){if(r.error){const i=T(r.error);for(const n of t)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,r.results),stop:!1}}settleReplayBatchSlots(t,e){const s=new Map;for(const i of e)typeof i.id=="number"&&i.body!==void 0&&s.set(i.id,i.body);const r=[];for(const[i,n]of t.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Me.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,T(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};
@@ -1 +0,0 @@
1
- const u="_creationTime",p=t=>{if(typeof t!="object"||t===null)return;const e=t._id;return typeof e=="string"?e:void 0},a=t=>{let e;for(const r of t){const n=r[u];if(typeof n=="number"){if(e!==void 0){if(n<e)return!0;if(n>e)return!1}e=n}}return!1},d=(t,e)=>{const r=e[u];if(typeof r!="number")return t.length;const n=a(t);for(const[s,i]of t.entries()){const f=i[u];if(typeof f=="number"&&(n?f<r:f>r))return s}return t.length},y=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},g=(t,e)=>{if(!Array.isArray(t))return;const r=[];for(const o of t){if(p(o)===void 0)return;r.push(o)}const{key:n,op:s,row:i}=e;if(s==="delete"){const o=r.filter(c=>c._id!==n);return o.length===r.length?[...r]:o}if(i===void 0)return;const f=r.findIndex(o=>o._id===n);if(f===-1){const o=[...r];return o.splice(d(r,i),0,i),o}const l=[...r];return l[f]=i,l};export{g as applyDelta,y as isMutationDelta};
@@ -1 +0,0 @@
1
- import{c as t}from"./local-store-DFMSEM2j.mjs";import"./SubscriptionRegistry-C72rCp44.mjs";export{t as createLocalStore};