@lunora/client 1.0.0-alpha.147 → 1.0.0-alpha.149
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.
- package/dist/auth/index.d.mts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/index.d.mts +10 -4
- package/dist/index.d.ts +10 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
- package/dist/packem_shared/LunoraClient-DEEbBpNA.mjs +1 -0
- package/dist/packem_shared/{createServerClient-DKz2XchD.mjs → createServerClient-BQ5rqRDi.mjs} +1 -1
- package/dist/packem_shared/{lunora-client.d-Cr3ZifMT.d.ts → lunora-client.d-BqcmL_p0.d.ts} +81 -12
- package/dist/packem_shared/{lunora-client.d-D6CMLEGY.d.mts → lunora-client.d-mHTdWjff.d.mts} +81 -12
- package/dist/packem_shared/{preload.d-CKqrejCH.d.ts → preload.d-f9FxbP31.d.ts} +1 -1
- package/dist/packem_shared/{preload.d-DVYt0iMr.d.mts → preload.d-wYfTr5NW.d.mts} +1 -1
- package/dist/packem_shared/replay-CXXDZ1_h.mjs +1 -0
- package/dist/query/index.d.mts +2 -2
- package/dist/query/index.d.ts +2 -2
- package/dist/service.mjs +1 -1
- package/dist/ssr/index.d.mts +2 -2
- package/dist/ssr/index.d.ts +2 -2
- package/dist/ssr/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/CONFLICT_ERROR_CODE-BOeeP_Wl.mjs +0 -1
- package/dist/packem_shared/LunoraClient-AzpMnC-G.mjs +0 -1
- package/dist/packem_shared/replay-DMEisOIL.mjs +0 -1
package/dist/auth/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-mHTdWjff.mjs";
|
|
2
2
|
import '@lunora/errors';
|
|
3
3
|
import "../packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
4
4
|
import '@lunora/runtime';
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-BqcmL_p0.js";
|
|
2
2
|
import '@lunora/errors';
|
|
3
3
|
import "../packem_shared/function-reference.d-Br_hsKje.js";
|
|
4
4
|
import '@lunora/runtime';
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, R as ReconnectOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-
|
|
2
|
-
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as
|
|
1
|
+
import { c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, R as ReconnectOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-mHTdWjff.mjs";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-mHTdWjff.mjs";
|
|
3
3
|
import { LunoraError, LunoraErrorCode } from '@lunora/errors';
|
|
4
4
|
export type { LunoraErrorCode } from '@lunora/errors';
|
|
5
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-wYfTr5NW.mjs";
|
|
6
6
|
import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
7
7
|
export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
8
8
|
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';
|
|
@@ -73,6 +73,12 @@ declare const getErrorCode: (error: unknown) => LunoraErrorCode | undefined;
|
|
|
73
73
|
* when absent/non-numeric. Pair with {@link isRateLimitedError}.
|
|
74
74
|
*/
|
|
75
75
|
declare const getRetryAfterMs: (error: unknown) => number | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Whether a durable replay's failure refused the credential rather than the
|
|
78
|
+
* write (see {@link AUTH_REPLAY_ERROR_CODES}) — a durable outbox holds such a
|
|
79
|
+
* write for the next attempt instead of dropping it.
|
|
80
|
+
*/
|
|
81
|
+
declare const isAuthReplayFailure: (error: unknown) => boolean;
|
|
76
82
|
declare const anyApi: Record<string, Record<string, unknown>>;
|
|
77
83
|
/**
|
|
78
84
|
* Optimistic-reconcile logic shared by every `@lunora/*` framework adapter's
|
|
@@ -1027,4 +1033,4 @@ declare const sendToSw: (sw: ServiceWorker | null, message: ClientToSwMessage, e
|
|
|
1027
1033
|
* Create a reply for a client message (call from inside the SW).
|
|
1028
1034
|
*/
|
|
1029
1035
|
declare const createReply: (original: ClientToSwMessage, payload?: unknown) => SwToClientMessage;
|
|
1030
|
-
export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, ClientServiceWorker, type ClientSwOptions, type ClientToSwMessage, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type ServiceWorkerStatus, type StreamIterable, type SubscriptionError, type SwToClientMessage, TabCoordinator, TransportError, anyApi, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };
|
|
1036
|
+
export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, ClientServiceWorker, type ClientSwOptions, type ClientToSwMessage, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type ServiceWorkerStatus, type StreamIterable, type SubscriptionError, type SwToClientMessage, TabCoordinator, TransportError, anyApi, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isAuthReplayFailure, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, R as ReconnectOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-
|
|
2
|
-
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as
|
|
1
|
+
import { c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, R as ReconnectOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-BqcmL_p0.js";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-BqcmL_p0.js";
|
|
3
3
|
import { LunoraError, LunoraErrorCode } from '@lunora/errors';
|
|
4
4
|
export type { LunoraErrorCode } from '@lunora/errors';
|
|
5
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-f9FxbP31.js";
|
|
6
6
|
import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.js";
|
|
7
7
|
export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.js";
|
|
8
8
|
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';
|
|
@@ -73,6 +73,12 @@ declare const getErrorCode: (error: unknown) => LunoraErrorCode | undefined;
|
|
|
73
73
|
* when absent/non-numeric. Pair with {@link isRateLimitedError}.
|
|
74
74
|
*/
|
|
75
75
|
declare const getRetryAfterMs: (error: unknown) => number | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Whether a durable replay's failure refused the credential rather than the
|
|
78
|
+
* write (see {@link AUTH_REPLAY_ERROR_CODES}) — a durable outbox holds such a
|
|
79
|
+
* write for the next attempt instead of dropping it.
|
|
80
|
+
*/
|
|
81
|
+
declare const isAuthReplayFailure: (error: unknown) => boolean;
|
|
76
82
|
declare const anyApi: Record<string, Record<string, unknown>>;
|
|
77
83
|
/**
|
|
78
84
|
* Optimistic-reconcile logic shared by every `@lunora/*` framework adapter's
|
|
@@ -1027,4 +1033,4 @@ declare const sendToSw: (sw: ServiceWorker | null, message: ClientToSwMessage, e
|
|
|
1027
1033
|
* Create a reply for a client message (call from inside the SW).
|
|
1028
1034
|
*/
|
|
1029
1035
|
declare const createReply: (original: ClientToSwMessage, payload?: unknown) => SwToClientMessage;
|
|
1030
|
-
export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, ClientServiceWorker, type ClientSwOptions, type ClientToSwMessage, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type ServiceWorkerStatus, type StreamIterable, type SubscriptionError, type SwToClientMessage, TabCoordinator, TransportError, anyApi, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };
|
|
1036
|
+
export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, ClientServiceWorker, type ClientSwOptions, type ClientToSwMessage, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type ServiceWorkerStatus, type StreamIterable, type SubscriptionError, type SwToClientMessage, TabCoordinator, TransportError, anyApi, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isAuthReplayFailure, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as
|
|
1
|
+
import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as p,reconcileOptimistic as c}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as i}from"./packem_shared/createAsyncStoragePersistence-CeUW9NTj.mjs";import{createAsyncStorageQueryCache as f}from"./packem_shared/createAsyncStorageQueryCache-Dpszf7UD.mjs";import{default as x}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as l}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as d}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as E}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as S,i as A}from"./packem_shared/delta-merge-D_5ChS-C.mjs";import{CONFLICT_ERROR_CODE as D,TransportError as Q,getErrorCode as _,getRetryAfterMs as F,isAuthReplayFailure as I,isConflictError as M,isForbiddenError as T,isRateLimitedError as g,isUnauthorizedError as L}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as b}from"./packem_shared/httpStream-v4etRV7m.mjs";import{c as U}from"./packem_shared/local-store-DDppw8Qr.mjs";import{LunoraClient as B}from"./packem_shared/LunoraClient-DEEbBpNA.mjs";import{createMutatorRunner as N}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as w}from"./packem_shared/offline-queue-D_fr-uQ3.mjs";import{createInMemoryPersistence as K,createIndexedDbPersistence as V}from"./packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs";import{preloadQuery as X,preloadedQueryResult as j}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as H,createIndexedDbQueryCache as J,queryCacheKey as Y}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as $}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as re}from"./packem_shared/createSnapshotPrecondition-5GQ_5fFu.mjs";import{DEFAULT_MAX_BUFFER as te,createStream as ae}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as ce}from"./packem_shared/SubscriptionRegistry-C3kLqped.mjs";import{ClientServiceWorker as ie}from"./packem_shared/ClientServiceWorker-DXnBXeWK.mjs";import{createReply as fe,sendToSw as se}from"./packem_shared/createReply-CwFABEJs.mjs";export{D as CONFLICT_ERROR_CODE,ie as ClientServiceWorker,te as DEFAULT_MAX_BUFFER,B as LunoraClient,w as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ce as SubscriptionRegistry,E as TabCoordinator,Q as TransportError,o as anyApi,S as applyDelta,i as createAsyncStoragePersistence,f as createAsyncStorageQueryCache,l as createCallRunner,d as createClientQuery,x as createInMemoryBookmarkStorage,K as createInMemoryPersistence,H as createInMemoryQueryCache,V as createIndexedDbPersistence,J as createIndexedDbQueryCache,U as createLocalStore,N as createMutatorRunner,$ as createReconnect,fe as createReply,re as createSnapshotPrecondition,ae as createStream,_ as getErrorCode,F as getRetryAfterMs,b as httpStream,I as isAuthReplayFailure,M as isConflictError,T as isForbiddenError,A as isMutationDelta,g as isRateLimitedError,L as isUnauthorizedError,p as maxSeq,X as preloadQuery,j as preloadedQueryResult,Y as queryCacheKey,c as reconcileOptimistic,se as sendToSw};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ERROR_CATALOG as e,LunoraError as n}from"@lunora/errors";const s=new Set(Object.keys(e));class R extends n{constructor(o,t){super("INTERNAL",o,{data:t})}}const E="CONFLICT",a=r=>r instanceof Error&&r.code===E,O=r=>r instanceof Error&&r.code==="FORBIDDEN",d=r=>r instanceof Error&&r.code==="UNAUTHORIZED",N=r=>r instanceof Error&&r.code==="TOO_MANY_REQUESTS",T=r=>{if(!(r instanceof Error))return;const{code:o}=r;return typeof o=="string"&&s.has(o)?o:void 0},f=r=>{const o=r?.data?.retryAfterMs;return typeof o=="number"&&Number.isFinite(o)?o:void 0},c=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),u=r=>c.has(r?.code??"");export{c as AUTH_REPLAY_ERROR_CODES,E as CONFLICT_ERROR_CODE,R as TransportError,T as getErrorCode,f as getRetryAfterMs,u as isAuthReplayFailure,a as isConflictError,O as isForbiddenError,N as isRateLimitedError,d as isUnauthorizedError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{t as Se,e as H,d as v}from"./wire-codec-BeIi1K-T.mjs";import{i as ge,a as ve,P as Te}from"./delta-merge-D_5ChS-C.mjs";import{s as Y}from"./wire-key-DCPYV4t8.mjs";import Ce from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as ke}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as we}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as X,isAuthReplayFailure as Ee}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Ae}from"./httpStream-v4etRV7m.mjs";import{d as B,n as A,f as _,a as _e,c as Ie,b as Oe,e as Re}from"./local-store-DDppw8Qr.mjs";import{O as Pe,n as Z,i as Fe,r as Me}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as Le}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as He,queryCacheKey as I}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as ee}from"./createReconnect-CjTmjJDH.mjs";import{i as U,e as L,u as F,a as te,d as Ue,r as xe,b as Ne,c as Be,M as Qe,f as De,g as qe}from"./replay-CXXDZ1_h.mjs";import Ke from"./createSnapshotPrecondition-5GQ_5fFu.mjs";import{createStream as We}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as C}from"./SubscriptionRegistry-C3kLqped.mjs";const Q=500,$e=async c=>{const e=[];let t;for(;;){const s=await c(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},se=(c,e)=>{if(c.size<e)return;const t=c.keys().next().value;t!==void 0&&c.delete(t)};new TextDecoder;const je=new TextEncoder,Ge=c=>Se(je.encode(JSON.stringify(c))),Ve="x-lunora-expect-subject",ze=c=>Ge({subject:c}),re=Symbol.for("lunora:session-change"),Je="lunora:session-change",Ye="better-auth.message",Xe="signout",ue=()=>{const c=globalThis;let e=c[re];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},c[re]=e),e},Ze=()=>"document"in globalThis,et=async()=>{const c=[];for(const e of ue().listeners)try{c.push(e())}catch{}await Promise.allSettled(c)},tt=(c,e)=>{if(c!==Ye||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===Xe}catch{return!1}},st=c=>{const e=[],t=()=>{et().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(Je):void 0}catch{s=void 0}if(s!==void 0){const i=s;i.addEventListener("message",n=>{n.data?.type==="lunora:session-change"&&n.data.tab!==c&&t()}),e.push(()=>{i.close()})}const r=globalThis;if(typeof r.addEventListener=="function"){const i=n=>{tt(n.key,n.newValue)&&t()};r.addEventListener("storage",i),e.push(()=>{r.removeEventListener?.("storage",i)})}return()=>{for(const i of e)i()}},rt=c=>{const e=ue();return e.listeners.add(c),e.detach===void 0&&Ze()&&(e.detach=st(e.tab)),()=>{e.listeners.delete(c),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}};class O{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const it=c=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:r,poll:i}=c,n=t>0&&e>0;let a=0,o,h=!1,d=!1;const u=()=>{o!==void 0&&(clearInterval(o),o=void 0,h=!1,r())},p=f=>{if(o!==void 0){if(!f){u();return}h||(h=!0,r()),s()}},m=()=>{d||(d=!0,i().then(p).finally(()=>{d=!1}).catch(()=>{}))};return{isPolling:()=>o!==void 0&&h,noteFailedOpen:()=>{a+=1,!(!n||o!==void 0||a<e)&&(o=setInterval(m,t),r(),m())},noteOpen:()=>{a=0,u()},stop:u}},nt="/_lunora/rpc",D="/_lunora/rpc-batch",at="/_lunora/ws",q=c=>c===void 0||c===""?"":`&bucket=${encodeURIComponent(c)}`,M=c=>{for(let e=c.length-1;e>=0;e-=1)c[e]?.()},ie=Symbol("lunora.unmergeableDelta"),ot=(c,e)=>{for(const t of e)t.op==="delete"?c.delete(t.key):t.value!==void 0&&c.set(t.key,t.value)},ct="lunora-ping",ht=3e4,dt=1e4,ut=5e3,lt=3,ft=250,pt=5e3,mt=64,yt=3,bt=1e4,St=8,gt="/_lunora/admin/shard-traffic",vt="/_lunora/admin/scheduled",Tt="/_lunora/admin/scheduled/status",Ct="/_lunora/admin/scheduled/ws",kt="/_lunora/admin/scheduled/cancel",ne="/_lunora/admin/scheduled/dead",wt="/_lunora/admin/scheduled/dead/retry",Et="/_lunora/admin/scheduled/dead/cancel",At="/_lunora/admin/workflows/instances",_t="/_lunora/admin/workflows/instance",It="/_lunora/admin/workflows/status",K="/_lunora/admin/storage",Ot="/_lunora/admin/storage/url",Rt="/_lunora/admin/storage/buckets",Pt="/_lunora/admin/functions",Ft="/_lunora/admin/cron-jobs",Mt="/_lunora/admin/cron-jobs/run",Lt="/_lunora/admin/openapi",Ht="/_lunora/admin/openrpc",Ut="/_lunora/admin/global/tables",xt="/_lunora/admin/global/table",Nt="/_lunora/admin/global/facet",Bt="/_lunora/admin/vector/indexes",Qt="/_lunora/admin/vector/query",Dt="/_lunora/admin/logs/archive",qt="/_lunora/admin/kv/namespaces",Kt="/_lunora/admin/kv/keys",W="/_lunora/admin/kv/value",Wt="/_lunora/admin/auth/users",$t="/_lunora/admin/auth/sessions",jt="/_lunora/admin/auth/users/create",Gt="/_lunora/admin/auth/users/role",Vt="/_lunora/admin/auth/users/ban",zt="/_lunora/admin/auth/users/unban",Jt="/_lunora/admin/auth/users/password",Yt="/_lunora/admin/auth/users/remove",Xt="/_lunora/admin/auth/users/impersonate",Zt="/_lunora/admin/auth/sessions/revoke",es="/_lunora/admin/auth/sessions/revoke-all",ts="/_lunora/admin/auth/capabilities",ss="/_lunora/admin/auth/users/update",rs="/_lunora/admin/auth/accounts",is="/_lunora/admin/auth/accounts/unlink",ns="/_lunora/admin/auth/passkeys",as="/_lunora/admin/auth/passkeys/delete",os="/_lunora/admin/auth/two-factor/disable",cs="/_lunora/admin/auth/organizations",hs="/_lunora/admin/auth/organizations/members",ds="/_lunora/admin/auth/organizations/invitations",us="/_lunora/admin/auth/organizations/members/remove",ls="/_lunora/admin/auth/organizations/invitations/cancel",fs="/_lunora/admin/auth/config",ps="/_lunora/admin/auth/sign-up-invitations",ms="/_lunora/admin/auth/sign-up-invitations/create",ys="/_lunora/admin/auth/sign-up-invitations/revoke",bs="/_lunora/admin/auth/organizations/create",Ss="/_lunora/admin/auth/organizations/update",gs="/_lunora/admin/auth/organizations/remove",vs="/_lunora/admin/auth/organizations/members/add",Ts="/_lunora/admin/auth/organizations/members/invite",Cs="/_lunora/admin/auth/organizations/members/role",ks="/_lunora/admin/auth/organizations/teams",ws="/_lunora/admin/auth/organizations/teams/create",Es="/_lunora/admin/auth/organizations/teams/update",As="/_lunora/admin/auth/organizations/teams/remove",_s="/_lunora/admin/auth/organizations/teams/members",Is="/_lunora/admin/auth/organizations/teams/members/add",Os="/_lunora/admin/auth/organizations/teams/members/remove",Rs="/_lunora/admin/auth/organizations/roles",Ps="/_lunora/admin/auth/organizations/roles/create",Fs="/_lunora/admin/auth/organizations/roles/update",Ms="/_lunora/admin/auth/organizations/roles/remove",Ls="/api/auth",Hs="/get-session",$=c=>c==="connected"||c==="polling",Us=(c,e,t)=>c!==null||e&&t===null,ae=c=>c.startsWith("https://")?`wss://${c.slice(8)}`:c.startsWith("http://")?`ws://${c.slice(7)}`:c,k=(c,e)=>`${c.endsWith("/")?c.slice(0,-1):c}${e}`,b=(c,e)=>{const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&i!==""&&t.set(r,String(i));const s=t.toString();return s===""?c:`${c}?${s}`},xs=[Te],l=c=>c??"",le=(c,e)=>{const t=c.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof c.message=="string"?c.message:void 0)??r??e}},Ns=c=>{const{code:e,messageText:t}=le(c,"stream error");return e===void 0?new Error(t):new y(e,t)},oe=c=>{const{code:e,messageText:t}=le(c,"subscription error");return{message:t,...e===void 0?{}:{code:e}}};function j(c){if(c!==void 0)return e=>{c(e)}}const w=(c,e)=>{for(const t of c)try{t(e)}catch{}},Bs=new TextDecoder,Qs=c=>{if(typeof c=="string")return c;if(c instanceof ArrayBuffer)return Bs.decode(c)},g=(c,e)=>{if(!c.socket||c.wsState!=="open")return!1;try{return c.socket.send(JSON.stringify(e)),!0}catch{return!1}},z=c=>{const e=new Error(c.message??"request failed");if(e.code=c.code,c.data!==void 0)try{e.data=v(c.data)}catch{}return c.hint!==void 0&&(e.hint=c.hint),c.docsUrl!==void 0&&(e.docsUrl=c.docsUrl),e},ce=(c,e)=>{const t=z(c),s=De(t,e);return s!==void 0&&(t.data=s),t},E=(c,e)=>{try{return H(c)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},Ds=1e4,he=async c=>{const e=new AbortController;let t;const s=new Promise((r,i)=>{t=setTimeout(()=>{e.abort(),i(new TypeError("LunoraClient: poll timed out"))},Ds)});try{return await Promise.race([c(e.signal),s])}catch(r){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):r}finally{clearTimeout(t)}},de=c=>{try{return H(c),!0}catch{return!1}},G=c=>"args"in c?{...c,args:v(c.args)}:c,fe=c=>{const e=L(c);return e===void 0?qe():z(e)},qs=(c,e)=>{const t=Array.from({length:e});for(const s of c){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r!==void 0&&"error"in r?{error:fe(r),ok:!1}:{ok:!0,value:v(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},V=(c,e)=>e!==null?{}:c===null?{expectSubject:null}:c?.startsWith("subj:")===!0?{expectSubject:c.slice(5)}:{},Ks=Promise.resolve();class pe{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new C;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new O;statusListeners=new O;tokenExpiredListeners=new O;identityChangeListeners=new O;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new O;pendingChangeListeners=new O;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??k(ae(e.url),at),this.wsToken=e.wsToken;const t=e.authBasePath??Ls;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Ce(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ht,this.connectTimeoutMs=e.connectTimeoutMs??dt,this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??ut,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??lt,this.defaultConnectionContext=e.connectionContext,this.persistence=Le(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=He(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new ke,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Ks),this.offlineQueue=new Pe(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Z()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=rt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint(),i=this.authSubject===void 0||this.subjectToken===this.authToken,n=this.subjectAwaitingReconfirm(),a=this.isKnownNobody();this.authToken=e,this.applySubject(e,t);const o=this.identityFingerprint();o!==r&&(!s&&e!==null&&i?(this.restampQueuedIdentity(r,o),this.restampWatermarks(r,o),this.restampConnectionIdentity(r,o),this.reseedFromHydratedCache()):!s&&e===null&&r===null&&i&&!a?(this.restampWatermarks(r,o),this.restampConnectionIdentity(r,o),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(r),Us(r,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(n),s&&this.authTokenListeners.emit(e),(o!==r||s||n)&&this.offlineQueue.size>0&&$(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){const t=this.identityVerdict(e);if(t!=="match")return{verdict:t};const s=Object.freeze({});return this.replayCredentials.set(s,{authToken:this.authToken,stamp:e}),{credential:s,verdict:t}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"",n=this.identityFingerprint();let a,o,h;try{o=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:u=>{a=u}})}catch(u){if(!U(u))throw u;h=u}if(a!==void 0&&a>(this.clientWatermarks.get(n??"")?.get(i)??0)){let u=this.clientWatermarks.get(n??"");u===void 0&&(se(this.clientWatermarks,St),u=new Map,this.clientWatermarks.set(n??"",u)),u.set(i,a)}if(h!==void 0)throw h;return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const r=await this.fetchImpl(k(this.url,`${this.authBasePath}${Hs}`),{credentials:"include",headers:e,method:"GET"});if(!r.ok)return this.identitySettled=!0,r.status===401&&this.adoptResolvedSubject(t,null,s),null;const n=(await r.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,n,s),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=l(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),r={context:e},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(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const r=l(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(e);const a=n===void 0;if(n||(n=new Set,i.set(e,n)),n.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),h=o?.get(e);if(!h?.delete(t)||h.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&g(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{data:E(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const i of s){const n=this.connections.get(i);e.push({confirmedMutationWatermark:t?.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}const r=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(const i of this.shapeSubscriptions.values())r.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:r.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Ke(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=Y(t),i=I(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=C.key(e,t,s),i=this.subscriptions.get(r);return{present:i!==void 0,value:i?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:r}=await this.runMutation(e,t,s);return r}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(d=>({rows:d})),n=t.length;let a=0,o=0,h=0;for(let d=0;d<n;d+=r){const u=t.slice(d,d+r),p=h,{committed:m}=await this.runMutation(e,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(p)}`},shardKey:s.shardKey});h+=1,a+=u.length,m&&(o+=u.length),s.onProgress?.({done:a,total:n})}return{chunks:h,imported:o,queued:a-o}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(gt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(vt,"GET")).records??[]).map(t=>G(t))}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(Tt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(kt,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await $e(async t=>await this.adminFetch(t===void 0?ne:`${ne}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>G(t))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(wt,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Et,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await this.adminFetch(`${At}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${_t}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(It,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=k(ae(this.url),Ct),s=ee(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||this.closed||(i=setTimeout(d,s.next()))},o=p=>{if(n||this.WebSocketImpl===void 0)return;const m=p===void 0?t:`${t}?token=${encodeURIComponent(p)}`;this.openManagedSocket(r,m,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:f=>{let S;try{S=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}S.type==="jobs"&&Array.isArray(S.records)&&(s.reset(),e(S.records.map(T=>G(T))))}})},h=async p=>{let m;try{m=await p()}catch{a();return}o(m)},d=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:p}=this;if(typeof p=="function"){h(p).catch(()=>{});return}o(p)};d();const u=()=>{n=!0,i!==void 0&&(clearTimeout(i),i=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Pt,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(Mt,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Lt,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Ht,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=b(K,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${K}?key=${encodeURIComponent(e)}${q(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Rt,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${K}?key=${encodeURIComponent(e.key)}${q(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Ot}?key=${encodeURIComponent(e)}${r}${q(t?.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(Ut,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(H(e.filters))),v(await this.adminFetch(`${xt}?${t.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(H(e.filters))),v(await this.adminFetch(`${Nt}?${t.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Bt,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Qt,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(Dt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(qt,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=b(Kt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=b(W,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(W,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=b(W,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=b(Wt,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch(jt,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Gt,"POST",e)}async banAuthUser(e){return await this.adminFetch(Vt,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(zt,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Jt,"POST",e)}async removeAuthUser(e){await this.adminFetch(Yt,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Xt,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Zt,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(es,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(ts,"GET")}async updateAuthUser(e){return await this.adminFetch(ss,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(b(rs,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(is,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(b(ns,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(as,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(os,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(b(cs,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=b(hs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=b(ds,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){const t=b(ps,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(ms,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(ys,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(us,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(ls,"POST",e)}async getAuthConfig(){return await this.adminFetch(fs,"GET")}async createAuthOrganization(e){return await this.adminFetch(bs,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Ss,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(gs,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(vs,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(Ts,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(Cs,"POST",e)}async listAuthOrgTeams(e){const t=b(ks,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(ws,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Es,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(As,"POST",e)}async listAuthOrgTeamMembers(e){const t=b(_s,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Is,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Os,"POST",e)}async listAuthOrgRoles(e){const t=b(Rs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Ps,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Fs,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Ms,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=b($t,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const i=t??{},n=C.key(e.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=j(s),h=j(r.onError),d=j(r.onCheckpoint);if(!a){this.nextSubId+=1;const p=`sub_${this.nextSubId.toString()}`,m=Y(i),f=this.takeHydratedCache(e.__lunoraRef,m,r.shardKey);a={acked:!1,args:i,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:p,lastValue:f?.value,optimisticLayers:[],serverBase:f?.value,serverCursor:f?.serverCursor,shardKey:r.shardKey,wireArgs:E(i,`args for '${e.__lunoraRef}'`),...f?.serverEpoch===void 0?{}:{serverEpoch:f.serverEpoch}},this.subscriptions.add(a),f!==void 0&&this.cacheSeededQueries.set(n,f)}if(a.callbacks.add(o),h&&a.errorCallbacks.add(h),d&&a.checkpointCallbacks.add(d),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),h&&u.errorCallbacks.delete(h),d&&u.checkpointCallbacks.delete(d),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(C.keyOf(u)),this.subscriptions.remove(u))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:n}=s;return n!==void 0&&queueMicrotask(()=>{n({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:E(e.args,`shape args for '${e.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(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=t??{},{handle:a,iterable:o}=We({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,i)}});this.ensureSocket(i);const h=this.getConnection(i),d={id:r,query:{args:E(n,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:i},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:d,shardKey:i,started:!1};this.streams.set(r,u);const p=h?.wsState==="open"&&g(h,d);if(u.started=p,!p&&h===void 0)return this.streams.delete(r),a.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),o;if(!p){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=mt;){const f=h.pendingStreams.shift()?.id,S=f?this.streams.get(f):void 0;S&&(S.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(f))}h.pendingStreams.push(d)}return o}httpStream(e,t,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Ae(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),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.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[s,r]of this.streams)l(r.shardKey)===t&&(r.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(s));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new we({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.queueResubscribe(t);for(const t of this.queuedOfflineShardKeys)this.ensureSocket(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected"||t==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,this.dropCacheSeed(t),r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),B(a,r)),A(a,_(s,a.optimisticLayers)))},onLeaderClaimAnswered:()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onSubscriptionError:(t,s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const i=this.subscriptions.get(t);i&&w(i.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const h of o.checkpointCallbacks)h({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(k(this.url,D),{body:JSON.stringify({calls:e.map((a,o)=>({args:E(a.args??{},`args for batch call '${a.fn.__lunoraRef}'`),functionPath:a.fn.__lunoraRef,id:o,shardKey:a.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),r=s.headers.get("x-d1-bookmark");r&&this.bookmark.set(r);let i;try{i=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const n=L(i);if(!s.ok||n!==void 0&&!i.results)throw n!==void 0?z(n):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of i.results??[]){const o=a.body?.commitCursor;typeof a.id=="number"&&typeof o=="number"&&this.recordShardCursor(e[a.id]?.shardKey,o)}return qs(i.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const r=t,i=s.mutationId??Z(),n=this.takeReplayCredential(s.replayCredential),a=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:o,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,h,o);const d=this.offlineFlushes.get(l(s.shardKey));d!==void 0&&await d;const{hasSocket:u,polling:p,wasEverConnected:m,wsState:f}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:S}=this.offlineQueue,T=m||S,R=this.WebSocketImpl!==void 0&&T,me=f==="connecting"&&T&&!p,ye=f!=="open"&&!u&&R&&!p,be=R&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),J=async()=>this.enqueueOfflineMutation(e,r,s.shardKey,a,i,h,o,s.precondition,s.mutationId,n?.stamp);if(ye||me||be)return J();let x;try{const P=await this.rpc(e.__lunoraRef,r,s.shardKey,{baselineSeq:a,captureBookmark:!0,...n?.flags,mutationId:i,onCommitCursor:N=>{x=N}});for(const N of o)N(x);return{committed:!0,value:P}}catch(P){if(p&&R&&P instanceof TypeError&&de(r))return J();throw this.settleFailedDirectWrite(P,x,o,h,n?.flags.authToken),P}}settleFailedDirectWrite(e,t,s,r,i){if(this.noteIdentityMismatch(e),i!==void 0&&this.noteReplayAuthRefusal(e,i),U(e)){for(const n of s)n(t);return}M(r)}async enqueueOfflineMutation(e,t,s,r,i,n,a,o,h,d){const u=d===void 0?this.identityFingerprint():d;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(m)}`,identity:u,mutationId:m,...n.length>0&&{onRejected:()=>{M(n)}},shardKey:s})}catch(f){throw M(n),f instanceof Error?f:new Error(String(f))}for(const f of a)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,f)=>{const S={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:r,id:i,clientId:this.clientId,identity:u,precondition:o,onCommit:T=>{for(const R of a)R(T)},reject:T=>{this.queuedIdentities.delete(i),U(T)||M(n),f(T instanceof Error?T:new Error(String(T)))},resolve:m,shardKey:s};this.offlineQueue.enqueue(S),this.queuedOfflineShardKeys.add(s),S.id!==void 0&&this.queuedIdentities.set(S.id,u)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(I(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...r}of e){if(Fe(this.persistenceVersion,r.version)){this.queryCache.remove(s).catch(()=>{});continue}const i=t.get(s);if(i&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(i,r);continue}this.hydratedQueryCache.set(s,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(I(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),A(e,_(t.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,A(s,_(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const r=I(e,t,s),i=this.hydratedQueryCache.get(r);if(!(i===void 0||!this.cachedQueryMatchesIdentity(i)))return this.hydratedQueryCache.delete(r),i}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=I(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=I(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity,i=r===void 0?this.identityFingerprint():r;i===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:i,serverCursor:e.serverCursor,ts:Date.now(),value:t,...i===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},ft))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=l(e);let s;for(const r of this.subscriptions.all())l(r.shardKey)!==t||r.serverCursor===void 0||(s=s===void 0?r.serverCursor:Math.max(s,r.serverCursor));return s}async pollSubscriptions(e){const t=l(e),s=[];for(const a of this.subscriptions.all())l(a.shardKey)===t&&(de(a.args)?s.push(a):w(a.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(s.length===0)return this.probeOrigin();const r=Re(),i=this.identityFingerprint();let n;try{n=await he(async a=>this.sendBatch(s.map(o=>({args:o.args,fn:o.fn,shardKey:o.shardKey})),a))}catch(a){return!(a instanceof TypeError)}if(this.identityFingerprint()!==i)return!0;for(const[a,o]of s.entries()){const h=n[a];if(h!==void 0){if(!h.ok){w(o.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:H(h.value),id:o.id,type:"data"},r)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await he(async t=>e(k(this.url,D),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=C.key(e,t,s),o=this.subscriptions.get(a);if(o){const h=_e(o,r);h&&(i.push(h.confirm),n.push(h.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(e,t,s,r,i){const{confirms:n,rollbacks:a,store:o}=Ie(this.subscriptions,s);try{e(o,t)}catch{M(a);return}r.push(...a),i.push(...n)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!g(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:s}}const t=this.getConnection(e);return{hasSocket:t?.socket!==void 0,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??!1,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=l(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:it({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ee(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[Ve]=ze(e.expectSubject));const r=this.shardCursors.get(this.cursorKeyFor(t));r!==void 0&&(s["x-lunora-min-seq"]=r.toString());const i=e.authToken===void 0?this.authToken:e.authToken;if(i&&(s.authorization=`Bearer ${i}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new X("LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(k(this.url,nt),{body:JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const d=n.headers.get("x-d1-bookmark");d&&this.bookmark.set(d)}let a;try{a=await n.json()}catch{throw F(n.status,n.statusText,n.headers.get("retry-after"))}const o=a;if(typeof o!="object"||o===null||Array.isArray(o))throw F(n.status,n.statusText,n.headers.get("retry-after"));const h=L(a);if(h!==void 0)throw ce(h,n.headers.get("retry-after"));if(!n.ok)throw F(n.status,n.statusText,n.headers.get("retry-after"));r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor);try{return v(a.result)}catch(d){throw te(d)}}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new y("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(k(this.url,e),{body:a,headers:i,method:t});let h;try{h=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}const d=L(h);if(d!==void 0){const u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}return h}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));g(e,{caps:xs,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openManagedSocket(e,t,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const n=new i(t);e.socket=n;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===n&&(e.socket=void 0)},o=h=>{a(),r.onClose(h)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{if(e.socket===n){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,o)}}),n.addEventListener("message",h=>{if(e.socket===n){e.lastFrameAt=Date.now();try{r.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),n.addEventListener("close",h=>{e.socket===n&&o(h)}),n.addEventListener("error",()=>{e.socket===n&&o()})}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),s===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{e.retired!==!0&&this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},pt),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const i of this.subscriptions.all())l(i.shardKey)===l(t)&&this.queueResubscribe(i);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const i=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:n,type:a}of i)g(e,{id:n,type:a})}this.flushPendingStreams(e);const r=this.whisperHandlers.get(l(t));if(r)for(const i of r.keys())g(e,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;const t=e.pendingStreams;e.pendingStreams=[];for(const s of t){const r=g(e,s)?this.streams.get(String(s.id)):void 0;r&&(r.started=!0)}}cancelStream(e,t){const s=this.getConnection(t),r=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),!g(s,{id:e,type:"unsubscribe"})&&r?.durable===!0&&r.started&&s.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(l(i.shardKey)!==l(e.shardKey)||t.has(r))){if(i.durable){const n={...i.message,...i.generation===void 0?{}:{generation:i.generation},sinceChunk:i.lastSeq};i.message=n,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(ct)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<yt;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},bt))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return g(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&g(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Qs(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}if(r.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof r.id=="string"){const i=this.getConnection(t);i&&this.releaseResubscribeSlot(i,r.id)}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,generation:n,id:a,seq:o}=r,h=this.streams.get(a);h&&typeof o=="number"&&(h.lastSeq=o,typeof n=="number"&&(h.generation=n),h.durable=!0),h?.handle.push(v(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"identity":{this.handleIdentityFrame(r,t);break}case"pokeEnd":{this.handlePokeEnd(r,t);break}case"pokePart":{this.handlePokePart(r,t);break}case"pokeStart":{this.handlePokeStart(r,t);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Ns(e)),this.streams.delete(s);return}const i=s===void 0?void 0:this.subscriptions.getById(s);if(i){const a=oe(e),o=this.identityFingerprint(),h=C.keyOf(i);w(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,a,o);return}const n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&w(n.errorCallbacks,oe(e))}pokeBufferKey(e,t){return`${l(e)}\0${t}`}handlePokeStart(e,t){se(this.pokeBuffers,pe.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(t,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,t){const s=this.pokeBuffers.get(this.pokeBufferKey(t,e.pokeId));if(!s)return;const r=[];try{for(const a of e.rowsPatch)r.push(a.value===void 0?a:{...a,value:v(a.value)})}catch(a){s.undecodable.set(e.shapeId,a);return}const i=s.parts.get(e.shapeId)??[];for(const a of r)i.push(a);s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);const n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,t){const s=this.pokeBufferKey(t,e.pokeId),r=this.pokeBuffers.get(s);if(r){this.pokeBuffers.delete(s);for(const[i,n]of r.undecodable){const a=this.shapeSubscriptions.get(i);a&&w(a.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${n instanceof Error?n.message:String(n)}`})}for(const i of r.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,t,s){const r=t.parts.get(e.id)??[],i=t.resets.has(e.id),n=t.bases.get(e.id),a=t.epoch!==void 0&&e.serverEpoch!==void 0&&t.epoch!==e.serverEpoch,o=n!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==n;if(!i&&(a||o)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}i&&e.rows.clear(),ot(e.rows,r),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);const h=t.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e,t){const{id:s}=e,r=s?this.subscriptions.getById(s):void 0;if(!r)return;let i;try{i=this.resolveDataPayload(e,r)}catch(n){w(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${n instanceof Error?n.message:String(n)}`});return}if(i===ie){this.resnapshotSubscription(r);return}if(r.serverBase=i,this.dropCacheSeed(C.keyOf(r)),e.cursor!==void 0&&(r.serverCursor=e.cursor),e.epoch!==void 0&&(r.serverEpoch=e.epoch),e.lastMutationId!==void 0){r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId);for(const n of r.checkpointCallbacks)n({checkpoint:r.serverCursor,mutationId:r.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(r),B(r,r.serverCursor),t!==void 0&&Oe(r,t),A(r,_(i,r.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=C.keyOf(r);this.tabCoordinator.broadcastSubscriptionData(n,i,r.serverCursor,r.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=Math.max(t.lastMutationId??0,e.lastMutationId));for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=C.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),B(e,e.serverCursor)&&A(e,_(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return v(e.data);const s=v(e.delta);return ge(s)?t.serverBase===void 0?s:ve(t.serverBase,s)??ie:s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const r=v(e.data);for(const i of s)try{i(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.streams.delete(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,w(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{Me(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const i=e.charCodeAt(r);t^=i,t=Math.imul(t,16777619),s=Math.imul(s,33)+i}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&$(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:r}=e;s===void 0||r!==null&&typeof r!="string"||this.adoptCookieSubject(r,s)||!this.closed&&this.authToken===null&&(r===null?null:`subj:${r}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const r of t){if(this.identityVerdict(this.stampOf(r))!=="mismatch"){s.push(r);continue}this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);const i=new Error("offline mutation discarded: auth identity changed before replay");i.code="OFFLINE_IDENTITY_CHANGED",r.reject(i),this.emitItemSettled(r,"rejected",i)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const i=t??"",n=this.clientWatermarks.get(i);if(n===void 0)this.clientWatermarks.set(i,r);else for(const[a,o]of r)n.set(a,o)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,A(e,_(void 0,e.optimisticLayers));for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const r=(async()=>{await(s??Promise.resolve());const{authToken:i}=this;try{await this.drainOfflineQueue(e,i)}catch{}!this.closed&&this.authToken!==i&&this.offlineQueue.size>0&&$(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,r),await r,this.offlineFlushes.get(t)===r&&this.offlineFlushes.delete(t)}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const d of s){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",u)}const r=l(e),i=this.offlineQueue.drain(d=>l(d.shardKey)===r);if(i.length===0)return;const n=[],a=[];for(const d of i){const u=this.replayGateVerdict(d);u==="send"?n.push(d):u==="hold"&&a.push(d)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),n.length===0){this.scheduleRateLimitedRetry(e);return}const o=this.encodableOrSettleTerminal(n);if(o.length===0){this.scheduleRateLimitedRetry(e);return}if(o.length===1){await this.replaySequential(o,e,t),this.scheduleRateLimitedRetry(e);return}const h=[];for(let d=0;d<o.length;d+=Q){const u=o.slice(d,d+Q),p=await this.replayBatched(u,e,t);if(h.push(...p.requeue),p.stop){h.push(...o.slice(d+Q));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(e),s=this.replayRetryState.get(t),r=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:r,delayMs:Math.max(s?.delayMs??0,Ue(r))})}noteReplayRetryDelay(e,t){const s=l(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1,n=xe(t,i);this.replayRetryState.set(s,{attempts:i,delayMs:n===void 0?r?.delayMs:Math.max(r?.delayMs??0,n)})}scheduleRateLimitedRetry(e){const t=l(e),s=this.replayRetryState.get(t),r=s?.delayMs;if(s===void 0||r===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const i=this.replayRetryTimers.get(t);i!==void 0&&clearTimeout(i),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},r))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{E(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.identityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const r=new Error("offline mutation skipped: auth identity changed before replay");return r.code="OFFLINE_IDENTITY_CHANGED",e.reject(r),this.emitItemSettled(e,"rejected",r),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==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(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,t)||Ne(e)}noteReplayAuthRefusal(e,t){if(!Ee(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...V(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;let n;try{const a=await this.rpc(i.functionPath,i.args,i.shardKey,{authToken:s,baselineSeq:i.baselineSeq,captureBookmark:!0,clientId:i.clientId??this.clientId,...V(i.identity,s),mutationId:i.id,onCommitCursor:o=>{n=o}});this.settleReplaySuccess(i,a,n)}catch(a){if(U(a)){this.settleReplayUndecodable(i,a,n);continue}if(!this.shouldRequeueReplayFailure(a,s)){this.settleReplayTerminal(i,a);continue}this.noteReplayRetryDelay(t,a),this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const r=JSON.stringify({calls:e.map((h,d)=>({args:E(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Be(r)>Qe)return await this.replayBatchedHalves(e,t,s);let i;try{i=await this.fetchImpl(k(this.url,D),{body:r,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...V(e.find(h=>h.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let a;const o=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,F(i.status,i.statusText,o),t,s)}if(!a.results){const h=L(a),d=h===void 0?F(i.status,i.statusText,o):ce(h,o);return this.settleWholeBatchError(e,d,t,s)}return{requeue:this.settleReplayBatchSlots(e,a.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,r){if(t instanceof X||t.code!==void 0&&this.shouldRequeueReplayFailure(t,r))return this.noteReplayRetryDelay(s,t),{requeue:e,stop:!0};for(const i of e)this.settleReplayTerminal(i,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const r=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,r),t,s);if(i.stop)return{requeue:[...i.requeue,...e.slice(r)],stop:!0};const n=await this.replayBatched(e.slice(r),t,s);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,t,s,r){const i=new Map;for(const a of t)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);const n=[];for(const[a,o]of e.entries()){const h=i.get(a);if(h===void 0)n.push(o);else if("error"in h){const d=fe(h);this.shouldRequeueReplayFailure(d,r)?(this.noteReplayRetryDelay(s,d),n.push(o)):this.settleReplayTerminal(o,d)}else this.settleReplayBatchResult(o,h)}return n}settleReplayBatchResult(e,t){let s;try{s=v(t.result)}catch(r){this.settleReplayUndecodable(e,te(r),t.commitCursor);return}this.settleReplaySuccess(e,s,t.commitCursor)}}export{pe as LunoraClient};
|
package/dist/packem_shared/{createServerClient-DKz2XchD.mjs → createServerClient-BQ5rqRDi.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraClient as r}from"./LunoraClient-
|
|
1
|
+
import{LunoraClient as r}from"./LunoraClient-DEEbBpNA.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
|
|
@@ -1668,17 +1668,44 @@ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unkn
|
|
|
1668
1668
|
*/
|
|
1669
1669
|
replayBaseline?: null | number;
|
|
1670
1670
|
/**
|
|
1671
|
-
* The
|
|
1672
|
-
*
|
|
1673
|
-
*
|
|
1674
|
-
*
|
|
1675
|
-
*
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
|
|
1679
|
-
|
|
1671
|
+
* The credential a durable replay was judged under — the one
|
|
1672
|
+
* {@link LunoraClient.replayIdentityVerdict} returns with a `"match"`. The
|
|
1673
|
+
* request is sent with exactly the bearer that verdict was judged against,
|
|
1674
|
+
* never the live one: a `setAuthToken` landing between the verdict and the
|
|
1675
|
+
* send would otherwise put a write judged as one user's on the next user's
|
|
1676
|
+
* bearer, and a bearer request carries no subject for the worker to refuse it
|
|
1677
|
+
* on. Under a cookie session the request also names the user the write was
|
|
1678
|
+
* queued by, and the worker refuses it with `IDENTITY_MISMATCH` when the
|
|
1679
|
+
* cookie now belongs to someone else — the check the client cannot make,
|
|
1680
|
+
* because it cannot see the cookie.
|
|
1681
|
+
*
|
|
1682
|
+
* Single use, and only valid on the client that issued it. A replay refused
|
|
1683
|
+
* for its credential (`UNAUTHENTICATED` / `TOKEN_EXPIRED`) fires {@link LunoraClient.onTokenExpired} once per credential, and only
|
|
1684
|
+
* while that credential is still the current one. Omit for normal calls,
|
|
1685
|
+
* which always send the live token.
|
|
1686
|
+
*/
|
|
1687
|
+
replayCredential?: ReplayCredential;
|
|
1680
1688
|
shardKey?: string;
|
|
1681
1689
|
}
|
|
1690
|
+
declare const replayCredentialBrand: unique symbol;
|
|
1691
|
+
/**
|
|
1692
|
+
* Opaque proof that a durable write was judged replayable, bound to the
|
|
1693
|
+
* credential it was judged under. Issued only by
|
|
1694
|
+
* {@link LunoraClient.replayIdentityVerdict}; pass it to
|
|
1695
|
+
* {@link MutationCallOptions.replayCredential}.
|
|
1696
|
+
*/
|
|
1697
|
+
interface ReplayCredential {
|
|
1698
|
+
readonly [replayCredentialBrand]: true;
|
|
1699
|
+
}
|
|
1700
|
+
/** {@link LunoraClient.replayIdentityVerdict}'s answer: a `"match"` carries the credential the replay must be sent with. */
|
|
1701
|
+
type ReplayIdentityVerdict = {
|
|
1702
|
+
credential: ReplayCredential;
|
|
1703
|
+
verdict: "match";
|
|
1704
|
+
} | {
|
|
1705
|
+
verdict: "mismatch";
|
|
1706
|
+
} | {
|
|
1707
|
+
verdict: "unknown";
|
|
1708
|
+
};
|
|
1682
1709
|
/** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
|
|
1683
1710
|
type ShapeCallback = (rows: Record<string, unknown>[]) => void;
|
|
1684
1711
|
/**
|
|
@@ -2008,8 +2035,12 @@ declare class LunoraClient {
|
|
|
2008
2035
|
private readonly tokenExpiredListeners;
|
|
2009
2036
|
/** Subscribers notified when the previous identity's session is retired (see `onIdentityChange`). */
|
|
2010
2037
|
private readonly identityChangeListeners;
|
|
2011
|
-
/**
|
|
2038
|
+
/** How many identities this client has retired (see `identityEpoch`). */
|
|
2039
|
+
private retiredIdentities;
|
|
2040
|
+
/** Token hash the last durable-replay auth refusal fired `onTokenExpired` for — see `noteReplayAuthRefusal`. */
|
|
2012
2041
|
private authRefusalNotifiedFor;
|
|
2042
|
+
/** What each outstanding {@link ReplayCredential} was judged against — see `replayIdentityVerdict`. */
|
|
2043
|
+
private readonly replayCredentials;
|
|
2013
2044
|
/** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
|
|
2014
2045
|
private readonly mutationSettledListeners;
|
|
2015
2046
|
/** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
|
|
@@ -2204,8 +2235,14 @@ declare class LunoraClient {
|
|
|
2204
2235
|
* `"mismatch"` is a different identity signed in, and is the one that must be
|
|
2205
2236
|
* terminal: replaying would attribute one user's write to another and pass
|
|
2206
2237
|
* THEIR row-level security.
|
|
2238
|
+
*
|
|
2239
|
+
* A `"match"` carries the {@link ReplayCredential} the replay must be sent
|
|
2240
|
+
* with ({@link MutationCallOptions.replayCredential}): the bearer held right
|
|
2241
|
+
* now, which is the one this verdict judged. The replay goes out with it even
|
|
2242
|
+
* if the token changes before the send, and the outbox's next attempt judges
|
|
2243
|
+
* again against whatever is current then.
|
|
2207
2244
|
*/
|
|
2208
|
-
replayIdentityVerdict(stamped: null | string | undefined):
|
|
2245
|
+
replayIdentityVerdict(stamped: null | string | undefined): ReplayIdentityVerdict;
|
|
2209
2246
|
/** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
|
|
2210
2247
|
clientIdentifier(): string;
|
|
2211
2248
|
/**
|
|
@@ -2266,6 +2303,17 @@ declare class LunoraClient {
|
|
|
2266
2303
|
* previous user's rows from it.
|
|
2267
2304
|
*/
|
|
2268
2305
|
onIdentityChange(listener: () => void): Unsubscribe;
|
|
2306
|
+
/**
|
|
2307
|
+
* How many identities this client has retired since it was constructed —
|
|
2308
|
+
* the number of times {@link onIdentityChange} has fired. Already moved when
|
|
2309
|
+
* those listeners run.
|
|
2310
|
+
*
|
|
2311
|
+
* A value rendered on the server (a `Preloaded` token) was read for whoever
|
|
2312
|
+
* was signed in when the page loaded, so it is only safe to show while this
|
|
2313
|
+
* is `0`: once a sign-out or user switch has retired that identity, a
|
|
2314
|
+
* component mounting later must not seed the previous user's rows.
|
|
2315
|
+
*/
|
|
2316
|
+
identityEpoch(): number;
|
|
2269
2317
|
/**
|
|
2270
2318
|
* Fetch the currently authenticated user from better-auth's `get-session`
|
|
2271
2319
|
* endpoint, returning the `user` record or `null` when signed out. Sends
|
|
@@ -4422,6 +4470,11 @@ declare class LunoraClient {
|
|
|
4422
4470
|
* the flush is the slow reconnect path.
|
|
4423
4471
|
*/
|
|
4424
4472
|
private encodableOrSettleTerminal;
|
|
4473
|
+
/**
|
|
4474
|
+
* The three-way comparison behind {@link replayIdentityVerdict} (documented
|
|
4475
|
+
* there), without a credential: the built-in queue sends with its own pinned token.
|
|
4476
|
+
*/
|
|
4477
|
+
private identityVerdict;
|
|
4425
4478
|
/**
|
|
4426
4479
|
* Identity gate for one queued write about to replay: a write stamped under
|
|
4427
4480
|
* one identity must never replay under another, and must never be DESTROYED
|
|
@@ -4495,6 +4548,22 @@ declare class LunoraClient {
|
|
|
4495
4548
|
* answer.
|
|
4496
4549
|
*/
|
|
4497
4550
|
private shouldRequeueReplayFailure;
|
|
4551
|
+
/**
|
|
4552
|
+
* Whether `error` refused a replay's CREDENTIAL (`authToken`, the bearer it
|
|
4553
|
+
* was sent with), and if so tell {@link onTokenExpired} — once per
|
|
4554
|
+
* credential, and only while it is still the current one. A refusal of a
|
|
4555
|
+
* token the app has already replaced says nothing about the current one:
|
|
4556
|
+
* the next pass re-sends under it, so asking for another refresh would be
|
|
4557
|
+
* spurious.
|
|
4558
|
+
*/
|
|
4559
|
+
private noteReplayAuthRefusal;
|
|
4560
|
+
/**
|
|
4561
|
+
* Redeem a {@link ReplayCredential} (single use) into the request flags it
|
|
4562
|
+
* pins (the judged bearer, and the subject a cookie replay names) and the
|
|
4563
|
+
* identity stamp it was judged for. Throws for a credential this client did
|
|
4564
|
+
* not issue or already redeemed.
|
|
4565
|
+
*/
|
|
4566
|
+
private takeReplayCredential;
|
|
4498
4567
|
/**
|
|
4499
4568
|
* Whether `failure` is the worker's `IDENTITY_MISMATCH` refusal, and if so,
|
|
4500
4569
|
* ask who is signed in now: the answer is what re-runs the replay gate
|
|
@@ -4589,4 +4658,4 @@ declare class LunoraClient {
|
|
|
4589
4658
|
*/
|
|
4590
4659
|
private settleReplayBatchResult;
|
|
4591
4660
|
}
|
|
4592
|
-
export {
|
|
4661
|
+
export { ServerMessage as $, ActionCallOptions as A, BookmarkStorage as B, ConnectionStatus as C, DEFAULT_MAX_BUFFER as D, OutboxMutation as E, FunctionArgumentDescriptor as F, GlobalFacetResult as G, HttpStreamRef as H, OutboxSink as I, PersistedMutation as J, ReplayCredential as K, LunoraClient as L, MutationCallOptions as M, ReplayIdentityVerdict as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReconnectOptions as R, SubscriptionError as S, RowOp as T, User as U, RpcEnvelope as V, RpcResponseBody as W, ScheduleRecord as X, ScheduleRetryPolicy as Y, SchedulerPoolStatus as Z, SchedulerStatus as _, Unsubscribe as a, ServerPokeEndMessage as a0, ServerPokePartMessage as a1, ServerPokeStartMessage as a2, ShardTrafficEntry as a3, ShardTrafficResult as a4, StorageListPage as a5, StorageObject as a6, StoredQuery as a7, StreamHandle as a8, SubscriptionCallback as a9, SubscriptionRegistry as aa, SubscriptionState as ab, SyncWatermark as ac, WorkflowInstanceAction as ad, WorkflowInstanceDetail as ae, WorkflowInstancePage as af, WorkflowInstanceStatus as ag, WorkflowInstanceSummary as ah, WorkflowStepDetail as ai, WsTokenProvider as aj, createClientQuery as ak, createLocalStore as al, createStream as am, SubscriptionErrorCallback as b, PersistenceAdapter as c, HttpStreamArgsOf as d, HttpStreamChunkOf as e, StreamIterable as f, BatchSlot as g, CachedQuery as h, ClientDebugShard as i, ClientDebugSnapshot as j, ClientDebugSubscription as k, ClientMessage as l, ClientQueryRef as m, ClientShapeSubscribeMessage as n, ClientShapeUnsubscribeMessage as o, FunctionDescriptor as p, GlobalFacetValue as q, GlobalFilterClause as r, GlobalTableInfo as s, GlobalTablePage as t, HttpStreamCallArgs as u, LunoraClientError as v, LunoraClientOptions as w, MutationSettledEvent as x, OptimisticLocalStore as y, OptimisticUpdate as z };
|
package/dist/packem_shared/{lunora-client.d-D6CMLEGY.d.mts → lunora-client.d-mHTdWjff.d.mts}
RENAMED
|
@@ -1668,17 +1668,44 @@ interface MutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unkn
|
|
|
1668
1668
|
*/
|
|
1669
1669
|
replayBaseline?: null | number;
|
|
1670
1670
|
/**
|
|
1671
|
-
* The
|
|
1672
|
-
*
|
|
1673
|
-
*
|
|
1674
|
-
*
|
|
1675
|
-
*
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
|
|
1679
|
-
|
|
1671
|
+
* The credential a durable replay was judged under — the one
|
|
1672
|
+
* {@link LunoraClient.replayIdentityVerdict} returns with a `"match"`. The
|
|
1673
|
+
* request is sent with exactly the bearer that verdict was judged against,
|
|
1674
|
+
* never the live one: a `setAuthToken` landing between the verdict and the
|
|
1675
|
+
* send would otherwise put a write judged as one user's on the next user's
|
|
1676
|
+
* bearer, and a bearer request carries no subject for the worker to refuse it
|
|
1677
|
+
* on. Under a cookie session the request also names the user the write was
|
|
1678
|
+
* queued by, and the worker refuses it with `IDENTITY_MISMATCH` when the
|
|
1679
|
+
* cookie now belongs to someone else — the check the client cannot make,
|
|
1680
|
+
* because it cannot see the cookie.
|
|
1681
|
+
*
|
|
1682
|
+
* Single use, and only valid on the client that issued it. A replay refused
|
|
1683
|
+
* for its credential (`UNAUTHENTICATED` / `TOKEN_EXPIRED`) fires {@link LunoraClient.onTokenExpired} once per credential, and only
|
|
1684
|
+
* while that credential is still the current one. Omit for normal calls,
|
|
1685
|
+
* which always send the live token.
|
|
1686
|
+
*/
|
|
1687
|
+
replayCredential?: ReplayCredential;
|
|
1680
1688
|
shardKey?: string;
|
|
1681
1689
|
}
|
|
1690
|
+
declare const replayCredentialBrand: unique symbol;
|
|
1691
|
+
/**
|
|
1692
|
+
* Opaque proof that a durable write was judged replayable, bound to the
|
|
1693
|
+
* credential it was judged under. Issued only by
|
|
1694
|
+
* {@link LunoraClient.replayIdentityVerdict}; pass it to
|
|
1695
|
+
* {@link MutationCallOptions.replayCredential}.
|
|
1696
|
+
*/
|
|
1697
|
+
interface ReplayCredential {
|
|
1698
|
+
readonly [replayCredentialBrand]: true;
|
|
1699
|
+
}
|
|
1700
|
+
/** {@link LunoraClient.replayIdentityVerdict}'s answer: a `"match"` carries the credential the replay must be sent with. */
|
|
1701
|
+
type ReplayIdentityVerdict = {
|
|
1702
|
+
credential: ReplayCredential;
|
|
1703
|
+
verdict: "match";
|
|
1704
|
+
} | {
|
|
1705
|
+
verdict: "mismatch";
|
|
1706
|
+
} | {
|
|
1707
|
+
verdict: "unknown";
|
|
1708
|
+
};
|
|
1682
1709
|
/** Callback a shape subscription invokes with its materialized rowset on every applied poke. */
|
|
1683
1710
|
type ShapeCallback = (rows: Record<string, unknown>[]) => void;
|
|
1684
1711
|
/**
|
|
@@ -2008,8 +2035,12 @@ declare class LunoraClient {
|
|
|
2008
2035
|
private readonly tokenExpiredListeners;
|
|
2009
2036
|
/** Subscribers notified when the previous identity's session is retired (see `onIdentityChange`). */
|
|
2010
2037
|
private readonly identityChangeListeners;
|
|
2011
|
-
/**
|
|
2038
|
+
/** How many identities this client has retired (see `identityEpoch`). */
|
|
2039
|
+
private retiredIdentities;
|
|
2040
|
+
/** Token hash the last durable-replay auth refusal fired `onTokenExpired` for — see `noteReplayAuthRefusal`. */
|
|
2012
2041
|
private authRefusalNotifiedFor;
|
|
2042
|
+
/** What each outstanding {@link ReplayCredential} was judged against — see `replayIdentityVerdict`. */
|
|
2043
|
+
private readonly replayCredentials;
|
|
2013
2044
|
/** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
|
|
2014
2045
|
private readonly mutationSettledListeners;
|
|
2015
2046
|
/** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
|
|
@@ -2204,8 +2235,14 @@ declare class LunoraClient {
|
|
|
2204
2235
|
* `"mismatch"` is a different identity signed in, and is the one that must be
|
|
2205
2236
|
* terminal: replaying would attribute one user's write to another and pass
|
|
2206
2237
|
* THEIR row-level security.
|
|
2238
|
+
*
|
|
2239
|
+
* A `"match"` carries the {@link ReplayCredential} the replay must be sent
|
|
2240
|
+
* with ({@link MutationCallOptions.replayCredential}): the bearer held right
|
|
2241
|
+
* now, which is the one this verdict judged. The replay goes out with it even
|
|
2242
|
+
* if the token changes before the send, and the outbox's next attempt judges
|
|
2243
|
+
* again against whatever is current then.
|
|
2207
2244
|
*/
|
|
2208
|
-
replayIdentityVerdict(stamped: null | string | undefined):
|
|
2245
|
+
replayIdentityVerdict(stamped: null | string | undefined): ReplayIdentityVerdict;
|
|
2209
2246
|
/** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
|
|
2210
2247
|
clientIdentifier(): string;
|
|
2211
2248
|
/**
|
|
@@ -2266,6 +2303,17 @@ declare class LunoraClient {
|
|
|
2266
2303
|
* previous user's rows from it.
|
|
2267
2304
|
*/
|
|
2268
2305
|
onIdentityChange(listener: () => void): Unsubscribe;
|
|
2306
|
+
/**
|
|
2307
|
+
* How many identities this client has retired since it was constructed —
|
|
2308
|
+
* the number of times {@link onIdentityChange} has fired. Already moved when
|
|
2309
|
+
* those listeners run.
|
|
2310
|
+
*
|
|
2311
|
+
* A value rendered on the server (a `Preloaded` token) was read for whoever
|
|
2312
|
+
* was signed in when the page loaded, so it is only safe to show while this
|
|
2313
|
+
* is `0`: once a sign-out or user switch has retired that identity, a
|
|
2314
|
+
* component mounting later must not seed the previous user's rows.
|
|
2315
|
+
*/
|
|
2316
|
+
identityEpoch(): number;
|
|
2269
2317
|
/**
|
|
2270
2318
|
* Fetch the currently authenticated user from better-auth's `get-session`
|
|
2271
2319
|
* endpoint, returning the `user` record or `null` when signed out. Sends
|
|
@@ -4422,6 +4470,11 @@ declare class LunoraClient {
|
|
|
4422
4470
|
* the flush is the slow reconnect path.
|
|
4423
4471
|
*/
|
|
4424
4472
|
private encodableOrSettleTerminal;
|
|
4473
|
+
/**
|
|
4474
|
+
* The three-way comparison behind {@link replayIdentityVerdict} (documented
|
|
4475
|
+
* there), without a credential: the built-in queue sends with its own pinned token.
|
|
4476
|
+
*/
|
|
4477
|
+
private identityVerdict;
|
|
4425
4478
|
/**
|
|
4426
4479
|
* Identity gate for one queued write about to replay: a write stamped under
|
|
4427
4480
|
* one identity must never replay under another, and must never be DESTROYED
|
|
@@ -4495,6 +4548,22 @@ declare class LunoraClient {
|
|
|
4495
4548
|
* answer.
|
|
4496
4549
|
*/
|
|
4497
4550
|
private shouldRequeueReplayFailure;
|
|
4551
|
+
/**
|
|
4552
|
+
* Whether `error` refused a replay's CREDENTIAL (`authToken`, the bearer it
|
|
4553
|
+
* was sent with), and if so tell {@link onTokenExpired} — once per
|
|
4554
|
+
* credential, and only while it is still the current one. A refusal of a
|
|
4555
|
+
* token the app has already replaced says nothing about the current one:
|
|
4556
|
+
* the next pass re-sends under it, so asking for another refresh would be
|
|
4557
|
+
* spurious.
|
|
4558
|
+
*/
|
|
4559
|
+
private noteReplayAuthRefusal;
|
|
4560
|
+
/**
|
|
4561
|
+
* Redeem a {@link ReplayCredential} (single use) into the request flags it
|
|
4562
|
+
* pins (the judged bearer, and the subject a cookie replay names) and the
|
|
4563
|
+
* identity stamp it was judged for. Throws for a credential this client did
|
|
4564
|
+
* not issue or already redeemed.
|
|
4565
|
+
*/
|
|
4566
|
+
private takeReplayCredential;
|
|
4498
4567
|
/**
|
|
4499
4568
|
* Whether `failure` is the worker's `IDENTITY_MISMATCH` refusal, and if so,
|
|
4500
4569
|
* ask who is signed in now: the answer is what re-runs the replay gate
|
|
@@ -4589,4 +4658,4 @@ declare class LunoraClient {
|
|
|
4589
4658
|
*/
|
|
4590
4659
|
private settleReplayBatchResult;
|
|
4591
4660
|
}
|
|
4592
|
-
export {
|
|
4661
|
+
export { ServerMessage as $, ActionCallOptions as A, BookmarkStorage as B, ConnectionStatus as C, DEFAULT_MAX_BUFFER as D, OutboxMutation as E, FunctionArgumentDescriptor as F, GlobalFacetResult as G, HttpStreamRef as H, OutboxSink as I, PersistedMutation as J, ReplayCredential as K, LunoraClient as L, MutationCallOptions as M, ReplayIdentityVerdict as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReconnectOptions as R, SubscriptionError as S, RowOp as T, User as U, RpcEnvelope as V, RpcResponseBody as W, ScheduleRecord as X, ScheduleRetryPolicy as Y, SchedulerPoolStatus as Z, SchedulerStatus as _, Unsubscribe as a, ServerPokeEndMessage as a0, ServerPokePartMessage as a1, ServerPokeStartMessage as a2, ShardTrafficEntry as a3, ShardTrafficResult as a4, StorageListPage as a5, StorageObject as a6, StoredQuery as a7, StreamHandle as a8, SubscriptionCallback as a9, SubscriptionRegistry as aa, SubscriptionState as ab, SyncWatermark as ac, WorkflowInstanceAction as ad, WorkflowInstanceDetail as ae, WorkflowInstancePage as af, WorkflowInstanceStatus as ag, WorkflowInstanceSummary as ah, WorkflowStepDetail as ai, WsTokenProvider as aj, createClientQuery as ak, createLocalStore as al, createStream as am, SubscriptionErrorCallback as b, PersistenceAdapter as c, HttpStreamArgsOf as d, HttpStreamChunkOf as e, StreamIterable as f, BatchSlot as g, CachedQuery as h, ClientDebugShard as i, ClientDebugSnapshot as j, ClientDebugSubscription as k, ClientMessage as l, ClientQueryRef as m, ClientShapeSubscribeMessage as n, ClientShapeUnsubscribeMessage as o, FunctionDescriptor as p, GlobalFacetValue as q, GlobalFilterClause as r, GlobalTableInfo as s, GlobalTablePage as t, HttpStreamCallArgs as u, LunoraClientError as v, LunoraClientOptions as w, MutationSettledEvent as x, OptimisticLocalStore as y, OptimisticUpdate as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-
|
|
1
|
+
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-BqcmL_p0.js";
|
|
2
2
|
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.js";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-
|
|
1
|
+
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-mHTdWjff.mjs";
|
|
2
2
|
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{TransportError as o,getRetryAfterMs as c,AUTH_REPLAY_ERROR_CODES as u}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";const d=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),T=e=>{if(e instanceof o)return!0;const t=e?.code;return t===void 0||d.has(t)||u.has(t)},E=6e4,R=1e3,l=e=>{if(e===null)return;const t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:void 0;const n=Date.parse(e);if(Number.isNaN(n))return;const r=n-Date.now();return r>0?r:void 0},_={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},M=(e,t,n)=>{const r=l(n),s=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${e.toString()}${t?` ${t}`:""})`;return e<400||e>=500||e===408?new o(a,s):new i(_[e]??"BAD_REQUEST",a,{data:s})},O=e=>{const t=e?.error;return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},p=()=>new o("LunoraClient: batch slot carried no error envelope"),v=(e,t)=>{const n=l(t);if(!(n===void 0||c(e)!==void 0))return e.data===void 0?{retryAfterMs:n}:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?{...e.data,retryAfterMs:n}:void 0},f=(e,t=Math.random)=>{const n=Math.min(R*2**Math.max(e-1,0),E);return Math.round(n*(.5+t()*.5))},D=e=>e instanceof o||d.has(e?.code??""),L=(e,t,n)=>{const r=c(e);return r!==void 0&&r>0?Math.min(r,E):D(e)?f(t,n):void 0},h=983040,m=e=>typeof TextEncoder>"u"?e.length:new TextEncoder().encode(e).length,A=new WeakSet,N=e=>{const t=new i("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${e instanceof Error?e.message:String(e)}`,{cause:e});return A.add(t),t},b=e=>e instanceof Error&&A.has(e);export{h as M,N as a,T as b,m as c,f as d,O as e,v as f,p as g,b as i,L as r,M as u};
|
package/dist/query/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-mHTdWjff.mjs";
|
|
2
2
|
export type {
|
|
3
3
|
/**
|
|
4
4
|
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
@@ -10,7 +10,7 @@ export type {
|
|
|
10
10
|
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
11
11
|
* store / signal / cache.
|
|
12
12
|
*/
|
|
13
|
-
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
13
|
+
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-mHTdWjff.mjs";
|
|
14
14
|
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
15
15
|
import '@lunora/errors';
|
|
16
16
|
import '@lunora/runtime';
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-BqcmL_p0.js";
|
|
2
2
|
export type {
|
|
3
3
|
/**
|
|
4
4
|
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
@@ -10,7 +10,7 @@ export type {
|
|
|
10
10
|
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
11
11
|
* store / signal / cache.
|
|
12
12
|
*/
|
|
13
|
-
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
13
|
+
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BqcmL_p0.js";
|
|
14
14
|
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
|
|
15
15
|
import '@lunora/errors';
|
|
16
16
|
import '@lunora/runtime';
|
package/dist/service.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{a as p,d}from"./packem_shared/wire-codec-BeIi1K-T.mjs";import{e as w}from"./packem_shared/replay-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{a as p,d}from"./packem_shared/wire-codec-BeIi1K-T.mjs";import{e as w}from"./packem_shared/replay-CXXDZ1_h.mjs";const v="/_lunora/rpc",N="https://lunora.internal",$=e=>{const t=new Error(e.message??"request failed");return t.code=e.code,e.data!==void 0&&(t.data=d(e.data)),e.hint!==void 0&&(t.hint=e.hint),e.docsUrl!==void 0&&(t.docsUrl=e.docsUrl),t},c=async(e,t,n,s,u)=>{const o=n.__lunoraRef,f=JSON.stringify({args:p("@lunora/client/service",o,s??{}),functionPath:o,...u?.shardKey===void 0?{}:{shardKey:u.shardKey}}),a=await e.fetch(new Request(`${N}${v}`,{body:f,headers:{"content-type":"application/json"},method:"POST"}));let r;try{r=await a.json()}catch{throw new i("INTERNAL",`@lunora/client/service: ${t} "${o}" got a non-JSON response (status ${a.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:a.status})}if(r===null||typeof r!="object")throw new i("INTERNAL",`@lunora/client/service: ${t} "${o}" returned a JSON body that is not an object (status ${a.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:a.status});const l=r,h=w(l);if(h!==void 0)throw $(h);if(!a.ok)throw new i("INTERNAL",`@lunora/client/service: ${t} "${o}" failed with status ${a.status.toString()} and no error envelope.`,{status:a.status});return d(l.result)},E=e=>({action:async(t,n,s)=>await c(e,"action",t,n,s),mutation:async(t,n,s)=>await c(e,"mutation",t,n,s),query:async(t,n,s)=>await c(e,"query",t,n,s)});export{v as RPC_PATH,E as createServiceClient};
|
package/dist/ssr/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-mHTdWjff.mjs";
|
|
2
2
|
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
3
3
|
export {
|
|
4
4
|
/**
|
|
@@ -20,7 +20,7 @@ p as preloadQuery,
|
|
|
20
20
|
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
21
21
|
* loader.
|
|
22
22
|
*/
|
|
23
|
-
a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
23
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-wYfTr5NW.mjs";
|
|
24
24
|
import '@lunora/errors';
|
|
25
25
|
import '@lunora/runtime';
|
|
26
26
|
/**
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-BqcmL_p0.js";
|
|
2
2
|
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
|
|
3
3
|
export {
|
|
4
4
|
/**
|
|
@@ -20,7 +20,7 @@ p as preloadQuery,
|
|
|
20
20
|
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
21
21
|
* loader.
|
|
22
22
|
*/
|
|
23
|
-
a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
23
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-f9FxbP31.js";
|
|
24
24
|
import '@lunora/errors';
|
|
25
25
|
import '@lunora/runtime';
|
|
26
26
|
/**
|
package/dist/ssr/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-Bffy70Wm.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-
|
|
1
|
+
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-Bffy70Wm.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-BQ5rqRDi.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.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 +0,0 @@
|
|
|
1
|
-
import{ERROR_CATALOG as n,LunoraError as e}from"@lunora/errors";const s=new Set(Object.keys(n));class E extends e{constructor(o,t){super("INTERNAL",o,{data:t})}}const c="CONFLICT",d=r=>r instanceof Error&&r.code===c,R=r=>r instanceof Error&&r.code==="FORBIDDEN",a=r=>r instanceof Error&&r.code==="UNAUTHORIZED",O=r=>r instanceof Error&&r.code==="TOO_MANY_REQUESTS",f=r=>{if(!(r instanceof Error))return;const{code:o}=r;return typeof o=="string"&&s.has(o)?o:void 0},u=r=>{const o=r?.data?.retryAfterMs;return typeof o=="number"&&Number.isFinite(o)?o:void 0};export{c as CONFLICT_ERROR_CODE,E as TransportError,f as getErrorCode,u as getRetryAfterMs,d as isConflictError,R as isForbiddenError,O as isRateLimitedError,a as isUnauthorizedError};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{t as be,e as L,d as v}from"./wire-codec-BeIi1K-T.mjs";import{i as Se,a as ge,P as ve}from"./delta-merge-D_5ChS-C.mjs";import{s as J}from"./wire-key-DCPYV4t8.mjs";import Te from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as Ce}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as ke}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as Y}from"./CONFLICT_ERROR_CODE-BOeeP_Wl.mjs";import{httpStream as we}from"./httpStream-v4etRV7m.mjs";import{d as N,n as A,f as _,a as Ee,c as Ae,b as _e,e as Ie}from"./local-store-DDppw8Qr.mjs";import{O as Oe,n as X,i as Re,r as Pe}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as Fe}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Me,queryCacheKey as I}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Z}from"./createReconnect-CjTmjJDH.mjs";import{i as H,e as M,u as P,a as ee,d as Le,r as He,b as Ue,c as xe,f as Ne,M as Be,g as Qe,h as De}from"./replay-DMEisOIL.mjs";import qe from"./createSnapshotPrecondition-5GQ_5fFu.mjs";import{createStream as Ke}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as T}from"./SubscriptionRegistry-C3kLqped.mjs";const B=500,We=async c=>{const e=[];let t;for(;;){const s=await c(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},te=(c,e)=>{if(c.size<e)return;const t=c.keys().next().value;t!==void 0&&c.delete(t)};new TextDecoder;const $e=new TextEncoder,je=c=>be($e.encode(JSON.stringify(c))),Ge="x-lunora-expect-subject",ze=c=>je({subject:c}),se=Symbol.for("lunora:session-change"),Ve="lunora:session-change",Je="better-auth.message",Ye="signout",de=()=>{const c=globalThis;let e=c[se];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},c[se]=e),e},Xe=()=>"document"in globalThis,Ze=async()=>{const c=[];for(const e of de().listeners)try{c.push(e())}catch{}await Promise.allSettled(c)},et=(c,e)=>{if(c!==Je||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===Ye}catch{return!1}},tt=c=>{const e=[],t=()=>{Ze().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(Ve):void 0}catch{s=void 0}if(s!==void 0){const i=s;i.addEventListener("message",n=>{n.data?.type==="lunora:session-change"&&n.data.tab!==c&&t()}),e.push(()=>{i.close()})}const r=globalThis;if(typeof r.addEventListener=="function"){const i=n=>{et(n.key,n.newValue)&&t()};r.addEventListener("storage",i),e.push(()=>{r.removeEventListener?.("storage",i)})}return()=>{for(const i of e)i()}},st=c=>{const e=de();return e.listeners.add(c),e.detach===void 0&&Xe()&&(e.detach=tt(e.tab)),()=>{e.listeners.delete(c),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}};class O{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const rt=c=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:r,poll:i}=c,n=t>0&&e>0;let a=0,o,h=!1,d=!1;const u=()=>{o!==void 0&&(clearInterval(o),o=void 0,h=!1,r())},f=m=>{if(o!==void 0){if(!m){u();return}h||(h=!0,r()),s()}},p=()=>{d||(d=!0,i().then(f).finally(()=>{d=!1}).catch(()=>{}))};return{isPolling:()=>o!==void 0&&h,noteFailedOpen:()=>{a+=1,!(!n||o!==void 0||a<e)&&(o=setInterval(p,t),r(),p())},noteOpen:()=>{a=0,u()},stop:u}},it="/_lunora/rpc",Q="/_lunora/rpc-batch",nt="/_lunora/ws",D=c=>c===void 0||c===""?"":`&bucket=${encodeURIComponent(c)}`,F=c=>{for(let e=c.length-1;e>=0;e-=1)c[e]?.()},re=Symbol("lunora.unmergeableDelta"),at=(c,e)=>{for(const t of e)t.op==="delete"?c.delete(t.key):t.value!==void 0&&c.set(t.key,t.value)},ot="lunora-ping",ct=3e4,ht=1e4,dt=5e3,ut=3,lt=250,ft=5e3,pt=64,mt=3,yt=1e4,bt=8,St="/_lunora/admin/shard-traffic",gt="/_lunora/admin/scheduled",vt="/_lunora/admin/scheduled/status",Tt="/_lunora/admin/scheduled/ws",Ct="/_lunora/admin/scheduled/cancel",ie="/_lunora/admin/scheduled/dead",kt="/_lunora/admin/scheduled/dead/retry",wt="/_lunora/admin/scheduled/dead/cancel",Et="/_lunora/admin/workflows/instances",At="/_lunora/admin/workflows/instance",_t="/_lunora/admin/workflows/status",q="/_lunora/admin/storage",It="/_lunora/admin/storage/url",Ot="/_lunora/admin/storage/buckets",Rt="/_lunora/admin/functions",Pt="/_lunora/admin/cron-jobs",Ft="/_lunora/admin/cron-jobs/run",Mt="/_lunora/admin/openapi",Lt="/_lunora/admin/openrpc",Ht="/_lunora/admin/global/tables",Ut="/_lunora/admin/global/table",xt="/_lunora/admin/global/facet",Nt="/_lunora/admin/vector/indexes",Bt="/_lunora/admin/vector/query",Qt="/_lunora/admin/logs/archive",Dt="/_lunora/admin/kv/namespaces",qt="/_lunora/admin/kv/keys",K="/_lunora/admin/kv/value",Kt="/_lunora/admin/auth/users",Wt="/_lunora/admin/auth/sessions",$t="/_lunora/admin/auth/users/create",jt="/_lunora/admin/auth/users/role",Gt="/_lunora/admin/auth/users/ban",zt="/_lunora/admin/auth/users/unban",Vt="/_lunora/admin/auth/users/password",Jt="/_lunora/admin/auth/users/remove",Yt="/_lunora/admin/auth/users/impersonate",Xt="/_lunora/admin/auth/sessions/revoke",Zt="/_lunora/admin/auth/sessions/revoke-all",es="/_lunora/admin/auth/capabilities",ts="/_lunora/admin/auth/users/update",ss="/_lunora/admin/auth/accounts",rs="/_lunora/admin/auth/accounts/unlink",is="/_lunora/admin/auth/passkeys",ns="/_lunora/admin/auth/passkeys/delete",as="/_lunora/admin/auth/two-factor/disable",os="/_lunora/admin/auth/organizations",cs="/_lunora/admin/auth/organizations/members",hs="/_lunora/admin/auth/organizations/invitations",ds="/_lunora/admin/auth/organizations/members/remove",us="/_lunora/admin/auth/organizations/invitations/cancel",ls="/_lunora/admin/auth/config",fs="/_lunora/admin/auth/sign-up-invitations",ps="/_lunora/admin/auth/sign-up-invitations/create",ms="/_lunora/admin/auth/sign-up-invitations/revoke",ys="/_lunora/admin/auth/organizations/create",bs="/_lunora/admin/auth/organizations/update",Ss="/_lunora/admin/auth/organizations/remove",gs="/_lunora/admin/auth/organizations/members/add",vs="/_lunora/admin/auth/organizations/members/invite",Ts="/_lunora/admin/auth/organizations/members/role",Cs="/_lunora/admin/auth/organizations/teams",ks="/_lunora/admin/auth/organizations/teams/create",ws="/_lunora/admin/auth/organizations/teams/update",Es="/_lunora/admin/auth/organizations/teams/remove",As="/_lunora/admin/auth/organizations/teams/members",_s="/_lunora/admin/auth/organizations/teams/members/add",Is="/_lunora/admin/auth/organizations/teams/members/remove",Os="/_lunora/admin/auth/organizations/roles",Rs="/_lunora/admin/auth/organizations/roles/create",Ps="/_lunora/admin/auth/organizations/roles/update",Fs="/_lunora/admin/auth/organizations/roles/remove",Ms="/api/auth",Ls="/get-session",W=c=>c==="connected"||c==="polling",Hs=(c,e,t)=>c!==null||e&&t===null,ne=c=>c.startsWith("https://")?`wss://${c.slice(8)}`:c.startsWith("http://")?`ws://${c.slice(7)}`:c,C=(c,e)=>`${c.endsWith("/")?c.slice(0,-1):c}${e}`,S=(c,e)=>{const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&i!==""&&t.set(r,String(i));const s=t.toString();return s===""?c:`${c}?${s}`},Us=[ve],l=c=>c??"",ue=(c,e)=>{const t=c.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof c.message=="string"?c.message:void 0)??r??e}},xs=c=>{const{code:e,messageText:t}=ue(c,"stream error");return e===void 0?new Error(t):new y(e,t)},ae=c=>{const{code:e,messageText:t}=ue(c,"subscription error");return{message:t,...e===void 0?{}:{code:e}}};function $(c){if(c!==void 0)return e=>{c(e)}}const k=(c,e)=>{for(const t of c)try{t(e)}catch{}},Ns=new TextDecoder,Bs=c=>{if(typeof c=="string")return c;if(c instanceof ArrayBuffer)return Ns.decode(c)},g=(c,e)=>{if(!c.socket||c.wsState!=="open")return!1;try{return c.socket.send(JSON.stringify(e)),!0}catch{return!1}},z=c=>{const e=new Error(c.message??"request failed");if(e.code=c.code,c.data!==void 0)try{e.data=v(c.data)}catch{}return c.hint!==void 0&&(e.hint=c.hint),c.docsUrl!==void 0&&(e.docsUrl=c.docsUrl),e},oe=(c,e)=>{const t=z(c),s=Qe(t,e);return s!==void 0&&(t.data=s),t},w=(c,e)=>{try{return L(c)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},Qs=1e4,ce=async c=>{const e=new AbortController;let t;const s=new Promise((r,i)=>{t=setTimeout(()=>{e.abort(),i(new TypeError("LunoraClient: poll timed out"))},Qs)});try{return await Promise.race([c(e.signal),s])}catch(r){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):r}finally{clearTimeout(t)}},he=c=>{try{return L(c),!0}catch{return!1}},j=c=>"args"in c?{...c,args:v(c.args)}:c,le=c=>{const e=M(c);return e===void 0?De():z(e)},Ds=(c,e)=>{const t=Array.from({length:e});for(const s of c){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r!==void 0&&"error"in r?{error:le(r),ok:!1}:{ok:!0,value:v(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},G=(c,e)=>e!==null?{}:c===null?{expectSubject:null}:c?.startsWith("subj:")===!0?{expectSubject:c.slice(5)}:{},qs=Promise.resolve();class fe{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new T;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new O;statusListeners=new O;tokenExpiredListeners=new O;identityChangeListeners=new O;authRefusalNotifiedFor;mutationSettledListeners=new O;pendingChangeListeners=new O;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??C(ne(e.url),nt),this.wsToken=e.wsToken;const t=e.authBasePath??Ms;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Te(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ct,this.connectTimeoutMs=e.connectTimeoutMs??ht,this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??dt,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??ut,this.defaultConnectionContext=e.connectionContext,this.persistence=Fe(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Me(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Ce,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=qs),this.offlineQueue=new Oe(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${X()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=st(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint(),i=this.authSubject===void 0||this.subjectToken===this.authToken,n=this.subjectAwaitingReconfirm(),a=this.isKnownNobody();this.authToken=e,this.applySubject(e,t);const o=this.identityFingerprint();o!==r&&(!s&&e!==null&&i?(this.restampQueuedIdentity(r,o),this.restampWatermarks(r,o),this.restampConnectionIdentity(r,o),this.reseedFromHydratedCache()):!s&&e===null&&r===null&&i&&!a?(this.restampWatermarks(r,o),this.restampConnectionIdentity(r,o),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(r),Hs(r,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(n),s&&this.authTokenListeners.emit(e),(o!==r||s||n)&&this.offlineQueue.size>0&&W(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"",n=this.identityFingerprint();let a,o,h;try{o=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:u=>{a=u}})}catch(u){if(!H(u))throw u;h=u}if(a!==void 0&&a>(this.clientWatermarks.get(n??"")?.get(i)??0)){let u=this.clientWatermarks.get(n??"");u===void 0&&(te(this.clientWatermarks,bt),u=new Map,this.clientWatermarks.set(n??"",u)),u.set(i,a)}if(h!==void 0)throw h;return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const r=await this.fetchImpl(C(this.url,`${this.authBasePath}${Ls}`),{credentials:"include",headers:e,method:"GET"});if(!r.ok)return this.identitySettled=!0,r.status===401&&this.adoptResolvedSubject(t,null,s),null;const n=(await r.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,n,s),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=l(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),r={context:e},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(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const r=l(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(e);const a=n===void 0;if(n||(n=new Set,i.set(e,n)),n.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),h=o?.get(e);if(!h?.delete(t)||h.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&g(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{data:w(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const i of s){const n=this.connections.get(i);e.push({confirmedMutationWatermark:t?.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}const r=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(const i of this.shapeSubscriptions.values())r.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:r.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return qe(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=J(t),i=I(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=T.key(e,t,s),i=this.subscriptions.get(r);return{present:i!==void 0,value:i?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:r}=await this.runMutation(e,t,s);return r}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(d=>({rows:d})),n=t.length;let a=0,o=0,h=0;for(let d=0;d<n;d+=r){const u=t.slice(d,d+r),f=h,{committed:p}=await this.runMutation(e,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(f)}`},shardKey:s.shardKey});h+=1,a+=u.length,p&&(o+=u.length),s.onProgress?.({done:a,total:n})}return{chunks:h,imported:o,queued:a-o}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(St,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(gt,"GET")).records??[]).map(t=>j(t))}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(vt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ct,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await We(async t=>await this.adminFetch(t===void 0?ie:`${ie}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>j(t))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(kt,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(wt,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await this.adminFetch(`${Et}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${At}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(_t,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=C(ne(this.url),Tt),s=Z(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||this.closed||(i=setTimeout(d,s.next()))},o=f=>{if(n||this.WebSocketImpl===void 0)return;const p=f===void 0?t:`${t}?token=${encodeURIComponent(f)}`;this.openManagedSocket(r,p,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(E=>j(E))))}})},h=async f=>{let p;try{p=await f()}catch{a();return}o(p)},d=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}o(f)};d();const u=()=>{n=!0,i!==void 0&&(clearTimeout(i),i=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Rt,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Pt,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(Ft,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Mt,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Lt,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=S(q,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${q}?key=${encodeURIComponent(e)}${D(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Ot,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${q}?key=${encodeURIComponent(e.key)}${D(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${It}?key=${encodeURIComponent(e)}${r}${D(t?.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(Ht,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(L(e.filters))),v(await this.adminFetch(`${Ut}?${t.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(L(e.filters))),v(await this.adminFetch(`${xt}?${t.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Nt,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Bt,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(Qt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Dt,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=S(qt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=S(K,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(K,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=S(K,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=S(Kt,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch($t,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(jt,"POST",e)}async banAuthUser(e){return await this.adminFetch(Gt,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(zt,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Vt,"POST",e)}async removeAuthUser(e){await this.adminFetch(Jt,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Yt,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Xt,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Zt,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(es,"GET")}async updateAuthUser(e){return await this.adminFetch(ts,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(S(ss,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(rs,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(S(is,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ns,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(as,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(S(os,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=S(cs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=S(hs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){const t=S(fs,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(ps,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(ms,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(ds,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(us,"POST",e)}async getAuthConfig(){return await this.adminFetch(ls,"GET")}async createAuthOrganization(e){return await this.adminFetch(ys,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(bs,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(Ss,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(gs,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(vs,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(Ts,"POST",e)}async listAuthOrgTeams(e){const t=S(Cs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(ks,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(ws,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Es,"POST",e)}async listAuthOrgTeamMembers(e){const t=S(As,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(_s,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Is,"POST",e)}async listAuthOrgRoles(e){const t=S(Os,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Rs,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Ps,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Fs,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=S(Wt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const i=t??{},n=T.key(e.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=$(s),h=$(r.onError),d=$(r.onCheckpoint);if(!a){this.nextSubId+=1;const f=`sub_${this.nextSubId.toString()}`,p=J(i),m=this.takeHydratedCache(e.__lunoraRef,p,r.shardKey);a={acked:!1,args:i,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:r.shardKey,wireArgs:w(i,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(a),m!==void 0&&this.cacheSeededQueries.set(n,m)}if(a.callbacks.add(o),h&&a.errorCallbacks.add(h),d&&a.checkpointCallbacks.add(d),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),h&&u.errorCallbacks.delete(h),d&&u.checkpointCallbacks.delete(d),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(T.keyOf(u)),this.subscriptions.remove(u))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:n}=s;return n!==void 0&&queueMicrotask(()=>{n({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:w(e.args,`shape args for '${e.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(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=t??{},{handle:a,iterable:o}=Ke({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,i)}});this.ensureSocket(i);const h=this.getConnection(i),d={id:r,query:{args:w(n,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:i},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:d,shardKey:i,started:!1};this.streams.set(r,u);const f=h?.wsState==="open"&&g(h,d);if(u.started=f,!f&&h===void 0)return this.streams.delete(r),a.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),o;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=pt;){const m=h.pendingStreams.shift()?.id,b=m?this.streams.get(m):void 0;b&&(b.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(m))}h.pendingStreams.push(d)}return o}httpStream(e,t,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return we(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),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.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[s,r]of this.streams)l(r.shardKey)===t&&(r.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(s));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new ke({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.queueResubscribe(t);for(const t of this.queuedOfflineShardKeys)this.ensureSocket(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected"||t==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,this.dropCacheSeed(t),r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),N(a,r)),A(a,_(s,a.optimisticLayers)))},onLeaderClaimAnswered:()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onSubscriptionError:(t,s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const i=this.subscriptions.get(t);i&&k(i.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const h of o.checkpointCallbacks)h({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(C(this.url,Q),{body:JSON.stringify({calls:e.map((a,o)=>({args:w(a.args??{},`args for batch call '${a.fn.__lunoraRef}'`),functionPath:a.fn.__lunoraRef,id:o,shardKey:a.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),r=s.headers.get("x-d1-bookmark");r&&this.bookmark.set(r);let i;try{i=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const n=M(i);if(!s.ok||n!==void 0&&!i.results)throw n!==void 0?z(n):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of i.results??[]){const o=a.body?.commitCursor;typeof a.id=="number"&&typeof o=="number"&&this.recordShardCursor(e[a.id]?.shardKey,o)}return Ds(i.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const r=t,i=s.mutationId??X(),n=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:a,rollbacks:o}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,o,a);const h=this.offlineFlushes.get(l(s.shardKey));h!==void 0&&await h;const{hasSocket:d,polling:u,wasEverConnected:f,wsState:p}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:m}=this.offlineQueue,b=f||m,E=this.WebSocketImpl!==void 0&&b,pe=p==="connecting"&&b&&!u,me=p!=="open"&&!d&&E&&!u,ye=E&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),V=async()=>this.enqueueOfflineMutation(e,r,s.shardKey,n,i,o,a,s.precondition,s.mutationId);if(me||pe||ye)return V();let U;try{const R=await this.rpc(e.__lunoraRef,r,s.shardKey,{baselineSeq:n,captureBookmark:!0,...G(s.replayIdentity,this.authToken),mutationId:i,onCommitCursor:x=>{U=x}});for(const x of a)x(U);return{committed:!0,value:R}}catch(R){if(u&&E&&R instanceof TypeError&&he(r))return V();throw this.settleFailedDirectWrite(R,U,a,o),R}}settleFailedDirectWrite(e,t,s,r){if(this.noteIdentityMismatch(e),H(e)){for(const i of s)i(t);return}F(r)}async enqueueOfflineMutation(e,t,s,r,i,n,a,o,h){const d=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const f=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(f)}`,identity:d,mutationId:f,...n.length>0&&{onRejected:()=>{F(n)}},shardKey:s})}catch(p){throw F(n),p instanceof Error?p:new Error(String(p))}for(const p of a)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((f,p)=>{const m={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:r,id:i,clientId:this.clientId,identity:d,precondition:o,onCommit:b=>{for(const E of a)E(b)},reject:b=>{this.queuedIdentities.delete(i),H(b)||F(n),p(b instanceof Error?b:new Error(String(b)))},resolve:f,shardKey:s};this.offlineQueue.enqueue(m),this.queuedOfflineShardKeys.add(s),m.id!==void 0&&this.queuedIdentities.set(m.id,d)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(I(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...r}of e){if(Re(this.persistenceVersion,r.version)){this.queryCache.remove(s).catch(()=>{});continue}const i=t.get(s);if(i&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(i,r);continue}this.hydratedQueryCache.set(s,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(I(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),A(e,_(t.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,A(s,_(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const r=I(e,t,s),i=this.hydratedQueryCache.get(r);if(!(i===void 0||!this.cachedQueryMatchesIdentity(i)))return this.hydratedQueryCache.delete(r),i}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=I(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=I(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity,i=r===void 0?this.identityFingerprint():r;i===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:i,serverCursor:e.serverCursor,ts:Date.now(),value:t,...i===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},lt))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=l(e);let s;for(const r of this.subscriptions.all())l(r.shardKey)!==t||r.serverCursor===void 0||(s=s===void 0?r.serverCursor:Math.max(s,r.serverCursor));return s}async pollSubscriptions(e){const t=l(e),s=[];for(const a of this.subscriptions.all())l(a.shardKey)===t&&(he(a.args)?s.push(a):k(a.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(s.length===0)return this.probeOrigin();const r=Ie(),i=this.identityFingerprint();let n;try{n=await ce(async a=>this.sendBatch(s.map(o=>({args:o.args,fn:o.fn,shardKey:o.shardKey})),a))}catch(a){return!(a instanceof TypeError)}if(this.identityFingerprint()!==i)return!0;for(const[a,o]of s.entries()){const h=n[a];if(h!==void 0){if(!h.ok){k(o.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:L(h.value),id:o.id,type:"data"},r)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await ce(async t=>e(C(this.url,Q),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=T.key(e,t,s),o=this.subscriptions.get(a);if(o){const h=Ee(o,r);h&&(i.push(h.confirm),n.push(h.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(e,t,s,r,i){const{confirms:n,rollbacks:a,store:o}=Ae(this.subscriptions,s);try{e(o,t)}catch{F(a);return}r.push(...a),i.push(...n)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!g(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:s}}const t=this.getConnection(e);return{hasSocket:t?.socket!==void 0,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??!1,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=l(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:rt({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:Z(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[Ge]=ze(e.expectSubject));const r=this.shardCursors.get(this.cursorKeyFor(t));r!==void 0&&(s["x-lunora-min-seq"]=r.toString());const i=e.authToken===void 0?this.authToken:e.authToken;if(i&&(s.authorization=`Bearer ${i}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new Y("LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(C(this.url,it),{body:JSON.stringify({args:w(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const d=n.headers.get("x-d1-bookmark");d&&this.bookmark.set(d)}let a;try{a=await n.json()}catch{throw P(n.status,n.statusText,n.headers.get("retry-after"))}const o=a;if(typeof o!="object"||o===null||Array.isArray(o))throw P(n.status,n.statusText,n.headers.get("retry-after"));const h=M(a);if(h!==void 0)throw oe(h,n.headers.get("retry-after"));if(!n.ok)throw P(n.status,n.statusText,n.headers.get("retry-after"));r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor);try{return v(a.result)}catch(d){throw ee(d)}}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new y("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(C(this.url,e),{body:a,headers:i,method:t});let h;try{h=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}const d=M(h);if(d!==void 0){const u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}return h}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));g(e,{caps:Us,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openManagedSocket(e,t,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const n=new i(t);e.socket=n;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===n&&(e.socket=void 0)},o=h=>{a(),r.onClose(h)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{if(e.socket===n){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,o)}}),n.addEventListener("message",h=>{if(e.socket===n){e.lastFrameAt=Date.now();try{r.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),n.addEventListener("close",h=>{e.socket===n&&o(h)}),n.addEventListener("error",()=>{e.socket===n&&o()})}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),s===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{e.retired!==!0&&this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},ft),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const i of this.subscriptions.all())l(i.shardKey)===l(t)&&this.queueResubscribe(i);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const i=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:n,type:a}of i)g(e,{id:n,type:a})}this.flushPendingStreams(e);const r=this.whisperHandlers.get(l(t));if(r)for(const i of r.keys())g(e,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;const t=e.pendingStreams;e.pendingStreams=[];for(const s of t){const r=g(e,s)?this.streams.get(String(s.id)):void 0;r&&(r.started=!0)}}cancelStream(e,t){const s=this.getConnection(t),r=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),!g(s,{id:e,type:"unsubscribe"})&&r?.durable===!0&&r.started&&s.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(l(i.shardKey)!==l(e.shardKey)||t.has(r))){if(i.durable){const n={...i.message,...i.generation===void 0?{}:{generation:i.generation},sinceChunk:i.lastSeq};i.message=n,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(ot)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<mt;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},yt))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return g(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&g(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Bs(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}if(r.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof r.id=="string"){const i=this.getConnection(t);i&&this.releaseResubscribeSlot(i,r.id)}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,generation:n,id:a,seq:o}=r,h=this.streams.get(a);h&&typeof o=="number"&&(h.lastSeq=o,typeof n=="number"&&(h.generation=n),h.durable=!0),h?.handle.push(v(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"identity":{this.handleIdentityFrame(r,t);break}case"pokeEnd":{this.handlePokeEnd(r,t);break}case"pokePart":{this.handlePokePart(r,t);break}case"pokeStart":{this.handlePokeStart(r,t);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(xs(e)),this.streams.delete(s);return}const i=s===void 0?void 0:this.subscriptions.getById(s);if(i){const a=ae(e),o=this.identityFingerprint(),h=T.keyOf(i);k(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,a,o);return}const n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&k(n.errorCallbacks,ae(e))}pokeBufferKey(e,t){return`${l(e)}\0${t}`}handlePokeStart(e,t){te(this.pokeBuffers,fe.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(t,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,t){const s=this.pokeBuffers.get(this.pokeBufferKey(t,e.pokeId));if(!s)return;const r=[];try{for(const a of e.rowsPatch)r.push(a.value===void 0?a:{...a,value:v(a.value)})}catch(a){s.undecodable.set(e.shapeId,a);return}const i=s.parts.get(e.shapeId)??[];for(const a of r)i.push(a);s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);const n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,t){const s=this.pokeBufferKey(t,e.pokeId),r=this.pokeBuffers.get(s);if(r){this.pokeBuffers.delete(s);for(const[i,n]of r.undecodable){const a=this.shapeSubscriptions.get(i);a&&k(a.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${n instanceof Error?n.message:String(n)}`})}for(const i of r.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,t,s){const r=t.parts.get(e.id)??[],i=t.resets.has(e.id),n=t.bases.get(e.id),a=t.epoch!==void 0&&e.serverEpoch!==void 0&&t.epoch!==e.serverEpoch,o=n!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==n;if(!i&&(a||o)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}i&&e.rows.clear(),at(e.rows,r),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);const h=t.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e,t){const{id:s}=e,r=s?this.subscriptions.getById(s):void 0;if(!r)return;let i;try{i=this.resolveDataPayload(e,r)}catch(n){k(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${n instanceof Error?n.message:String(n)}`});return}if(i===re){this.resnapshotSubscription(r);return}if(r.serverBase=i,this.dropCacheSeed(T.keyOf(r)),e.cursor!==void 0&&(r.serverCursor=e.cursor),e.epoch!==void 0&&(r.serverEpoch=e.epoch),e.lastMutationId!==void 0){r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId);for(const n of r.checkpointCallbacks)n({checkpoint:r.serverCursor,mutationId:r.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(r),N(r,r.serverCursor),t!==void 0&&_e(r,t),A(r,_(i,r.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=T.keyOf(r);this.tabCoordinator.broadcastSubscriptionData(n,i,r.serverCursor,r.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=Math.max(t.lastMutationId??0,e.lastMutationId));for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=T.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),N(e,e.serverCursor)&&A(e,_(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return v(e.data);const s=v(e.delta);return Se(s)?t.serverBase===void 0?s:ge(t.serverBase,s)??re:s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const r=v(e.data);for(const i of s)try{i(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.streams.delete(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,k(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{Pe(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const i=e.charCodeAt(r);t^=i,t=Math.imul(t,16777619),s=Math.imul(s,33)+i}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&W(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:r}=e;s===void 0||r!==null&&typeof r!="string"||this.adoptCookieSubject(r,s)||!this.closed&&this.authToken===null&&(r===null?null:`subj:${r}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const r of t){if(this.replayIdentityVerdict(this.stampOf(r))!=="mismatch"){s.push(r);continue}this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);const i=new Error("offline mutation discarded: auth identity changed before replay");i.code="OFFLINE_IDENTITY_CHANGED",r.reject(i),this.emitItemSettled(r,"rejected",i)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const i=t??"",n=this.clientWatermarks.get(i);if(n===void 0)this.clientWatermarks.set(i,r);else for(const[a,o]of r)n.set(a,o)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,A(e,_(void 0,e.optimisticLayers));for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const r=(async()=>{await(s??Promise.resolve());const{authToken:i}=this;try{await this.drainOfflineQueue(e,i)}catch{}!this.closed&&this.authToken!==i&&this.offlineQueue.size>0&&W(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,r),await r,this.offlineFlushes.get(t)===r&&this.offlineFlushes.delete(t)}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const d of s){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",u)}const r=l(e),i=this.offlineQueue.drain(d=>l(d.shardKey)===r);if(i.length===0)return;const n=[],a=[];for(const d of i){const u=this.replayGateVerdict(d);u==="send"?n.push(d):u==="hold"&&a.push(d)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),n.length===0){this.scheduleRateLimitedRetry(e);return}const o=this.encodableOrSettleTerminal(n);if(o.length===0){this.scheduleRateLimitedRetry(e);return}if(o.length===1){await this.replaySequential(o,e,t),this.scheduleRateLimitedRetry(e);return}const h=[];for(let d=0;d<o.length;d+=B){const u=o.slice(d,d+B),f=await this.replayBatched(u,e,t);if(h.push(...f.requeue),f.stop){h.push(...o.slice(d+B));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(e),s=this.replayRetryState.get(t),r=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:r,delayMs:Math.max(s?.delayMs??0,Le(r))})}noteReplayRetryDelay(e,t){const s=l(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1,n=He(t,i);this.replayRetryState.set(s,{attempts:i,delayMs:n===void 0?r?.delayMs:Math.max(r?.delayMs??0,n)})}scheduleRateLimitedRetry(e){const t=l(e),s=this.replayRetryState.get(t),r=s?.delayMs;if(s===void 0||r===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const i=this.replayRetryTimers.get(t);i!==void 0&&clearTimeout(i),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},r))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{w(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.replayIdentityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const r=new Error("offline mutation skipped: auth identity changed before replay");return r.code="OFFLINE_IDENTITY_CHANGED",e.reject(r),this.emitItemSettled(e,"rejected",r),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==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(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){if(this.noteIdentityMismatch(e))return!0;if(Ue(e)){const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}return xe(e)}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let r=0;r<e.length;r+=1){const i=e[r];if(!i)continue;let n;try{const a=await this.rpc(i.functionPath,i.args,i.shardKey,{authToken:s,baselineSeq:i.baselineSeq,captureBookmark:!0,clientId:i.clientId??this.clientId,...G(i.identity,s),mutationId:i.id,onCommitCursor:o=>{n=o}});this.settleReplaySuccess(i,a,n)}catch(a){if(H(a)){this.settleReplayUndecodable(i,a,n);continue}if(!this.shouldRequeueReplayFailure(a,s)){this.settleReplayTerminal(i,a);continue}this.noteReplayRetryDelay(t,a),this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const r=JSON.stringify({calls:e.map((h,d)=>({args:w(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Ne(r)>Be)return await this.replayBatchedHalves(e,t,s);let i;try{i=await this.fetchImpl(C(this.url,Q),{body:r,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...G(e.find(h=>h.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let a;const o=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,P(i.status,i.statusText,o),t,s)}if(!a.results){const h=M(a),d=h===void 0?P(i.status,i.statusText,o):oe(h,o);return this.settleWholeBatchError(e,d,t,s)}return{requeue:this.settleReplayBatchSlots(e,a.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,r){if(t instanceof Y||t.code!==void 0&&this.shouldRequeueReplayFailure(t,r))return this.noteReplayRetryDelay(s,t),{requeue:e,stop:!0};for(const i of e)this.settleReplayTerminal(i,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const r=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,r),t,s);if(i.stop)return{requeue:[...i.requeue,...e.slice(r)],stop:!0};const n=await this.replayBatched(e.slice(r),t,s);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,t,s,r){const i=new Map;for(const a of t)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);const n=[];for(const[a,o]of e.entries()){const h=i.get(a);if(h===void 0)n.push(o);else if("error"in h){const d=le(h);this.shouldRequeueReplayFailure(d,r)?(this.noteReplayRetryDelay(s,d),n.push(o)):this.settleReplayTerminal(o,d)}else this.settleReplayBatchResult(o,h)}return n}settleReplayBatchResult(e,t){let s;try{s=v(t.result)}catch(r){this.settleReplayUndecodable(e,ee(r),t.commitCursor);return}this.settleReplaySuccess(e,s,t.commitCursor)}}export{fe as LunoraClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{TransportError as o,getRetryAfterMs as c}from"./CONFLICT_ERROR_CODE-BOeeP_Wl.mjs";const d=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),E=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),y=e=>E.has(e?.code??""),O=e=>{if(e instanceof o)return!0;const t=e?.code;return t===void 0||d.has(t)||E.has(t)},l=6e4,u=1e3,A=e=>{if(e===null)return;const t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:void 0;const n=Date.parse(e);if(Number.isNaN(n))return;const r=n-Date.now();return r>0?r:void 0},_={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},M=(e,t,n)=>{const r=A(n),s=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${e.toString()}${t?` ${t}`:""})`;return e<400||e>=500||e===408?new o(a,s):new i(_[e]??"BAD_REQUEST",a,{data:s})},h=e=>{const t=e?.error;return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},p=()=>new o("LunoraClient: batch slot carried no error envelope"),N=(e,t)=>{const n=A(t);if(!(n===void 0||c(e)!==void 0))return e.data===void 0?{retryAfterMs:n}:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?{...e.data,retryAfterMs:n}:void 0},f=(e,t=Math.random)=>{const n=Math.min(u*2**Math.max(e-1,0),l);return Math.round(n*(.5+t()*.5))},T=e=>e instanceof o||d.has(e?.code??""),v=(e,t,n)=>{const r=c(e);return r!==void 0&&r>0?Math.min(r,l):T(e)?f(t,n):void 0},L=983040,m=e=>typeof TextEncoder>"u"?e.length:new TextEncoder().encode(e).length,R=new WeakSet,U=e=>{const t=new i("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${e instanceof Error?e.message:String(e)}`,{cause:e});return R.add(t),t},b=e=>e instanceof Error&&R.has(e);export{L as M,U as a,y as b,O as c,f as d,h as e,m as f,N as g,p as h,b as i,v as r,M as u};
|