@lunora/client 1.0.0-alpha.241 → 1.0.0-alpha.242
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 +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/LunoraClient-CwCISTif.mjs +1 -0
- package/dist/packem_shared/{createServerClient-dd_Fdt5Z.mjs → createServerClient-CmZmYeQK.mjs} +1 -1
- package/dist/packem_shared/{lunora-client.d-zxkfXzoj.d.ts → lunora-client.d-Pvj-sj8S.d.ts} +85 -50
- package/dist/packem_shared/{lunora-client.d-XR8Gbgd_.d.mts → lunora-client.d-mAuddnZ9.d.mts} +85 -50
- package/dist/packem_shared/{preload.d-sSG_NtRh.d.mts → preload.d-C3a5W5-O.d.mts} +1 -1
- package/dist/packem_shared/{preload.d-L9KZ08dO.d.ts → preload.d-DxVQwugq.d.ts} +1 -1
- package/dist/query/index.d.mts +2 -2
- package/dist/query/index.d.ts +2 -2
- 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/LunoraClient-uzfWJwNk.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-mAuddnZ9.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-Pvj-sj8S.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 { R as ReconnectOptions, 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, 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 OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type a as Unsubscribe, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-
|
|
1
|
+
import { R as ReconnectOptions, 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, L as LunoraClient } from "./packem_shared/lunora-client.d-mAuddnZ9.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 OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type a as Unsubscribe, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-mAuddnZ9.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-C3a5W5-O.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';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { R as ReconnectOptions, 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, 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 OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type a as Unsubscribe, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-
|
|
1
|
+
import { R as ReconnectOptions, 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, L as LunoraClient } from "./packem_shared/lunora-client.d-Pvj-sj8S.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 OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type a as Unsubscribe, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-Pvj-sj8S.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-DxVQwugq.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';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as i}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-COqH5_SV.mjs";import{default as s}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-DBuR7Dwv.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as A,TransportError as b,getErrorCode as h,getRetryAfterMs as D,isAuthReplayFailure as L,isConflictError as Q,isForbiddenError as T,isRateLimitedError as _,isUnauthorizedError as F}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as M}from"./packem_shared/httpStream-B9iENFKq.mjs";import{c as O}from"./packem_shared/live-stream-Dil9byXF.mjs";import{liveTopicSubscription as U,subscribeLiveTopic as v}from"./packem_shared/liveTopicSubscription-gOmRbuhH.mjs";import{c as k}from"./packem_shared/local-store-fqWV2n_Z.mjs";import{LunoraClient as N}from"./packem_shared/LunoraClient-
|
|
1
|
+
import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as i}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-COqH5_SV.mjs";import{default as s}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-DBuR7Dwv.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as A,TransportError as b,getErrorCode as h,getRetryAfterMs as D,isAuthReplayFailure as L,isConflictError as Q,isForbiddenError as T,isRateLimitedError as _,isUnauthorizedError as F}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as M}from"./packem_shared/httpStream-B9iENFKq.mjs";import{c as O}from"./packem_shared/live-stream-Dil9byXF.mjs";import{liveTopicSubscription as U,subscribeLiveTopic as v}from"./packem_shared/liveTopicSubscription-gOmRbuhH.mjs";import{c as k}from"./packem_shared/local-store-fqWV2n_Z.mjs";import{LunoraClient as N}from"./packem_shared/LunoraClient-CwCISTif.mjs";import{createMutatorRunner as K}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as X}from"./packem_shared/offline-queue-Dt_um8sR.mjs";import{createInMemoryPersistence as w,createIndexedDbPersistence as G}from"./packem_shared/createInMemoryPersistence-BfgXApi_.mjs";import{preloadQuery as J,preloadedQueryResult as W}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as Z,createIndexedDbQueryCache as $,queryCacheKey as ee}from"./packem_shared/createInMemoryQueryCache-B5wX-gTy.mjs";import{createReconnect as oe}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as ae}from"./packem_shared/createSnapshotPrecondition-CLkxVeN1.mjs";import{DEFAULT_MAX_BUFFER as ie,createStream as pe}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as me}from"./packem_shared/SubscriptionRegistry-DKIXE7M7.mjs";export{A as CONFLICT_ERROR_CODE,ie as DEFAULT_MAX_BUFFER,N as LunoraClient,X as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,me as SubscriptionRegistry,d as TabCoordinator,b as TransportError,R as applyDelta,O as connectLiveStream,i as createAsyncStoragePersistence,n as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,s as createInMemoryBookmarkStorage,w as createInMemoryPersistence,Z as createInMemoryQueryCache,G as createIndexedDbPersistence,$ as createIndexedDbQueryCache,k as createLocalStore,K as createMutatorRunner,oe as createReconnect,ae as createSnapshotPrecondition,pe as createStream,h as getErrorCode,D as getRetryAfterMs,M as httpStream,L as isAuthReplayFailure,Q as isConflictError,T as isForbiddenError,C as isMutationDelta,_ as isRateLimitedError,F as isUnauthorizedError,U as liveTopicSubscription,t as maxSeq,J as preloadQuery,W as preloadedQueryResult,ee as queryCacheKey,a as reconcileOptimistic,v as subscribeLiveTopic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{encodeWire as x,decodeWire as C,stableWireKey as ce}from"@lunora/wire";import{r as xe,U as Be,P as Qe}from"./delta-merge-Ls3DED4g.mjs";import{w as g,b as ne,j as E,d as de,p as he,s as ue}from"./client-urls-BHLUjjcG.mjs";import qe from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as X,a as Ke,e as B,r as le,b as fe,c as Ge,d as pe,u as je}from"./wire-errors-u1qRPmDJ.mjs";import{ClientQueryStore as $e}from"./createClientQuery-B8Nfj-7o.mjs";import{D as Ve,a as ze,b as Je,c as Ye,d as Xe,S as me,M as Ze,I as et,Q as tt,R as st,e as it,f as nt,g as rt}from"./client-tuning-C10B2KCO.mjs";import{TabCoordinator as ot}from"./TabCoordinator-DBuR7Dwv.mjs";import{TransportError as U,getRetryAfterMs as at,AUTH_REPLAY_ERROR_CODES as ct,isAuthReplayFailure as Q}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as dt}from"./httpStream-B9iENFKq.mjs";import{d as Z,r as M,a as F,b as ht,c as ut,e as lt,f as ft}from"./local-store-fqWV2n_Z.mjs";import{O as pt,n as ye,i as mt}from"./offline-queue-Dt_um8sR.mjs";import{resolvePersistenceAdapter as yt}from"./createInMemoryPersistence-BfgXApi_.mjs";import{w as D,a as Se,b as St}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as bt,queryCacheKey as L}from"./createInMemoryQueryCache-B5wX-gTy.mjs";import{createReconnect as be}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as O,SubscriptionRegistry as _,wrapSubscriber as j}from"./SubscriptionRegistry-DKIXE7M7.mjs";import vt from"./createSnapshotPrecondition-CLkxVeN1.mjs";import{createStream as gt}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const $=500,_e=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)},I="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Tt=n=>{let e="",t=0;const s=n.length-2;for(;t<s;t+=3){const r=n[t]<<16|n[t+1]<<8|n[t+2];e+=I.charAt(r>>18&63)+I.charAt(r>>12&63)+I.charAt(r>>6&63)+I.charAt(r&63)}const i=n.length-t;if(i===1){const r=n[t]<<16;e+=I.charAt(r>>18&63)+I.charAt(r>>12&63)}else if(i===2){const r=n[t]<<16|n[t+1]<<8;e+=I.charAt(r>>18&63)+I.charAt(r>>12&63)+I.charAt(r>>6&63)}return e};new TextDecoder;const kt=new TextEncoder,Ct=n=>Tt(kt.encode(JSON.stringify(n))),wt="x-lunora-expect-subject",Et=n=>Ct({subject:n}),ve=Symbol.for("lunora:session-change"),At="lunora:session-change",_t="better-auth.message",It="signout",Ie=()=>{const n=globalThis;let e=n[ve];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[ve]=e),e},Ot=()=>"document"in globalThis,Rt=async()=>{const n=[];for(const e of Ie().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},Pt=(n,e)=>{if(n!==_t||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===It}catch{return!1}},Ft=n=>{const e=[],t=()=>{Rt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(At):void 0}catch{s=void 0}if(s!==void 0){const r=s;r.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==n&&t()}),e.push(()=>{r.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const r=a=>{Pt(a.key,a.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},Lt=n=>{const e=Ie();return e.listeners.add(n),e.detach===void 0&&Ot()&&(e.detach=Ft(e.tab)),()=>{e.listeners.delete(n),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},Mt="/_lunora/rpc",V="/_lunora/rpc-batch",z="/_lunora/ws",Ht="/_lunora/admin/shard-traffic",Ut="/_lunora/admin/scheduled",Nt="/_lunora/admin/scheduled/status",Wt="/_lunora/admin/scheduled/ws",Dt="/_lunora/admin/scheduled/cancel",ge="/_lunora/admin/scheduled/dead",xt="/_lunora/admin/scheduled/dead/retry",Bt="/_lunora/admin/scheduled/dead/cancel",Qt="/_lunora/admin/workflows/instances",qt="/_lunora/admin/workflows/instance",Kt="/_lunora/admin/workflows/status",re="/_lunora/admin/storage",Gt="/_lunora/admin/storage/url",jt="/_lunora/admin/storage/buckets",$t="/_lunora/admin/functions",Vt="/_lunora/admin/cron-jobs",zt="/_lunora/admin/cron-jobs/run",Jt="/_lunora/admin/architecture",Yt="/_lunora/admin/openapi",Xt="/_lunora/admin/openrpc",Zt="/_lunora/admin/global/tables",es="/_lunora/admin/global/table",ts="/_lunora/admin/global/facet",ss="/_lunora/admin/vector/indexes",is="/_lunora/admin/vector/query",ns="/_lunora/admin/logs/archive",rs="/_lunora/admin/kv/namespaces",os="/_lunora/admin/kv/keys",oe="/_lunora/admin/kv/value",as="/_lunora/admin/auth/users",cs="/_lunora/admin/auth/sessions",ds="/_lunora/admin/auth/users/create",hs="/_lunora/admin/auth/users/role",us="/_lunora/admin/auth/users/ban",ls="/_lunora/admin/auth/users/unban",fs="/_lunora/admin/auth/users/password",ps="/_lunora/admin/auth/users/remove",ms="/_lunora/admin/auth/users/impersonate",ys="/_lunora/admin/auth/sessions/revoke",Ss="/_lunora/admin/auth/sessions/revoke-all",bs="/_lunora/admin/auth/capabilities",vs="/_lunora/admin/auth/users/update",gs="/_lunora/admin/auth/accounts",Ts="/_lunora/admin/auth/accounts/unlink",ks="/_lunora/admin/auth/passkeys",Cs="/_lunora/admin/auth/passkeys/delete",ws="/_lunora/admin/auth/two-factor/disable",Es="/_lunora/admin/auth/organizations",As="/_lunora/admin/auth/organizations/members",_s="/_lunora/admin/auth/organizations/invitations",Is="/_lunora/admin/auth/organizations/members/remove",Os="/_lunora/admin/auth/organizations/invitations/cancel",Rs="/_lunora/admin/auth/config",Ps="/_lunora/admin/auth/sign-up-invitations",Fs="/_lunora/admin/auth/sign-up-invitations/create",Ls="/_lunora/admin/auth/sign-up-invitations/revoke",Ms="/_lunora/admin/auth/organizations/create",Hs="/_lunora/admin/auth/organizations/update",Us="/_lunora/admin/auth/organizations/remove",Ns="/_lunora/admin/auth/organizations/members/add",Ws="/_lunora/admin/auth/organizations/members/invite",Ds="/_lunora/admin/auth/organizations/members/role",xs="/_lunora/admin/auth/organizations/teams",Bs="/_lunora/admin/auth/organizations/teams/create",Qs="/_lunora/admin/auth/organizations/teams/update",qs="/_lunora/admin/auth/organizations/teams/remove",Ks="/_lunora/admin/auth/organizations/teams/members",Gs="/_lunora/admin/auth/organizations/teams/members/add",js="/_lunora/admin/auth/organizations/teams/members/remove",$s="/_lunora/admin/auth/organizations/roles",Vs="/_lunora/admin/auth/organizations/roles/create",zs="/_lunora/admin/auth/organizations/roles/update",Js="/_lunora/admin/auth/organizations/roles/remove",Ys="/api/auth",Xs="/get-session",Zs="lunora-ping",ei=async n=>(n.assertOpen(),(await n.adminFetch($t,"GET")).functions??[]),ti=async n=>(n.assertOpen(),(await n.adminFetch(Vt,"GET")).jobs??[]),si=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(zt,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},ii=async n=>(n.assertOpen(),await n.adminFetch(Yt,"GET")),ni=async n=>(n.assertOpen(),await n.adminFetch(Jt,"GET")),ri=async n=>(n.assertOpen(),await n.adminFetch(Xt,"GET")),oi=async n=>(n.assertOpen(),await n.adminFetch(Zt,"GET")),ai=async(n,e)=>{n.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(x(e.filters))),C(await n.adminFetch(`${es}?${t.toString()}`,"GET"))},ci=async(n,e)=>{n.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(x(e.filters))),C(await n.adminFetch(`${ts}?${t.toString()}`,"GET"))},di=async n=>(n.assertOpen(),(await n.adminFetch(rs,"GET")).namespaces??[]),hi=async(n,e)=>{n.assertOpen();const t=g(os,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await n.adminFetch(t,"GET")},ui=async(n,e)=>{n.assertOpen();const t=g(oe,{key:e.key,namespace:e.namespace});return await n.adminFetch(t,"GET")},li=async(n,e)=>{n.assertOpen(),await n.adminFetch(oe,"PUT",e)},fi=async(n,e)=>{n.assertOpen();const t=g(oe,{key:e.key,namespace:e.namespace});await n.adminFetch(t,"DELETE")},pi=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(Ht,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},mi=async(n,e={})=>{n.assertOpen();const t=await n.adminFetch(ns,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},yi=async n=>{const e=[];let t;for(;;){const s=await n(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}},ae=n=>"args"in n?{...n,args:C(n.args)}:n,Si=async n=>(n.assertOpen(),((await n.adminFetch(Ut,"GET")).records??[]).map(t=>ae(t))),bi=async n=>{n.assertOpen();const e=await n.adminFetch(Nt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},vi=async(n,e)=>(n.assertOpen(),{cancelled:(await n.adminFetch(Dt,"POST",{id:e})).cancelled===!0}),gi=async n=>(n.assertOpen(),(await yi(async t=>await n.adminFetch(t===void 0?ge:`${ge}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>ae(t))),Ti=async(n,e)=>(n.assertOpen(),{retried:(await n.adminFetch(xt,"POST",{id:e})).retried===!0}),ki=async(n,e)=>(n.assertOpen(),{removed:(await n.adminFetch(Bt,"POST",{id:e})).removed===!0}),Ci=async(n,e)=>{n.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 n.adminFetch(`${Qt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},wi=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await n.adminFetch(`${qt}?${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??[]}},Ei=async(n,e)=>(n.assertOpen(),{status:(await n.adminFetch(Kt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),Ai=async(n,e={})=>{n.assertOpen();const t=g(re,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await n.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},_i=async(n,e,t)=>{n.assertOpen();const s=`${re}?key=${encodeURIComponent(e)}${ne(t?.bucket)}`,i=await n.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},Ii=async n=>(n.assertOpen(),(await n.adminFetch(jt,"GET")).buckets??[]),Oi=async(n,e)=>{n.assertOpen();const t=`${re}?key=${encodeURIComponent(e.key)}${ne(e.bucket)}`,s=await n.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},Ri=async(n,e,t)=>{n.assertOpen();const s=t?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,r=`${Gt}?key=${encodeURIComponent(e)}${i}${ne(t?.bucket)}`,a=await n.adminFetch(r,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url},Pi=async n=>(n.assertOpen(),(await n.adminFetch(ss,"GET")).indexes??[]),Fi=async(n,e)=>(n.assertOpen(),(await n.adminFetch(is,"POST",e)).matches??[]),A=(n,e)=>{try{return x(n)}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)}},ee=n=>{try{return x(n),!0}catch{return!1}},Oe=n=>n!==null&&typeof n=="object"&&("error"in n||"result"in n),Li=(n,e)=>{const t=Array.from({length:e});for(const s of n){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!Oe(s.body)){t[s.id]={error:X({}),ok:!1};continue}const i=s.body;t[s.id]="error"in i?{error:X(i),ok:!1}:{ok:!0,value:C(i.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},J=(n,e)=>e!==null?{}:n===null?{expectSubject:null}:n?.startsWith("subj:")===!0?{expectSubject:n.slice(5)}:{},q=n=>n==="connected"||n==="polling",l=n=>n??"",k=(n,e)=>{if(!n.socket||n.wsState!=="open")return!1;try{return n.socket.send(JSON.stringify(e)),!0}catch{return!1}},Mi=n=>{if(!n.pendingStreams||n.pendingStreams.length===0)return;const e=n.pendingStreams;n.pendingStreams=[];for(const t of e)k(n,t)},Hi=new TextDecoder,Ui=n=>{if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return Hi.decode(n)};class R{listeners=new Set;get size(){return this.listeners.size}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 H=n=>{n.heartbeatTimer!==void 0&&(clearInterval(n.heartbeatTimer),n.heartbeatTimer=void 0)},Ni=(n,e,t)=>{H(n),!(e<=0)&&(n.heartbeatTimer=setInterval(()=>{if(!n.socket)return;const{socket:s}=n;if(Date.now()-n.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Zs)}catch{}},e))},Te=(n,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:a}=t;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");const o=new i(e);n.socket=o;const c=()=>{H(n),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.socket===o&&(n.socket=void 0)},h=d=>{c(),s.onClose(d)};r>0&&(n.connectTimer=setTimeout(()=>{if(n.connectTimer=void 0,n.socket===o){try{o.close()}catch{}h()}},r)),o.addEventListener("open",()=>{if(n.socket===o){n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.lastFrameAt=Date.now();try{s.onOpen?.()}catch(d){console.error("[lunora] connection open handler threw",d)}n.socket===o&&Ni(n,a,h)}}),o.addEventListener("message",d=>{if(n.socket===o){n.lastFrameAt=Date.now();try{s.onMessage(d)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),o.addEventListener("close",d=>{n.socket===o&&h(d)}),o.addEventListener("error",()=>{n.socket===o&&h()})},Wi=n=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=n,a=t>0&&e>0;let o=0,c,h=!1,d=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,h=!1,i())},f=y=>{if(c!==void 0){if(!y){u();return}h||(h=!0,i()),s()}},p=()=>{d||(d=!0,r().then(f).finally(()=>{d=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&h,noteFailedOpen:()=>{o+=1,!(!a||c!==void 0||o<e)&&(c=setInterval(p,t),i(),p())},noteOpen:()=>{o=0,u()},stop:u}},Di=1e4,ke=async n=>D(Di,void 0,n,()=>new TypeError("LunoraClient: poll timed out")),Re=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ce=n=>{if(n instanceof U)return!0;const e=n?.code;return e===void 0||Re.has(e)||ct.has(e)},xi=1e3,Pe=6e4,Bi={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},W=(n,e,t)=>{const s=Ke(t),i=s===void 0?void 0:{retryAfterMs:s},r=`LunoraClient: response carried no error envelope (status ${n.toString()}${e?` ${e}`:""})`;return n<400||n>=500||n===408?new U(r,i):new b(Bi[n]??"BAD_REQUEST",r,{data:i})},te=(n,e=Math.random)=>{const t=Math.min(xi*2**Math.max(n-1,0),Pe);return Math.round(t*(.5+e()*.5))},Qi=n=>{const e=n?.code;return n instanceof U||e===void 0||Re.has(e)},qi=(n,e,t)=>{const s=at(n);return s!==void 0&&s>0?Math.min(s,Pe):Qi(n)?te(e,t):void 0},Ki=983040,Gi=n=>typeof TextEncoder>"u"?n.length:new TextEncoder().encode(n).length,Fe=new WeakSet,Le=n=>{const e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${n instanceof Error?n.message:String(n)}`,{cause:n});return Fe.add(e),e},K=n=>n instanceof Error&&Fe.has(n),ji=n=>{const e=new Map;for(const t of n)typeof t.id=="number"&&Oe(t.body)&&e.set(t.id,t.body);return e},$i=n=>{if(n===void 0)return{kind:"unanswered"};if("error"in n)return{error:X(n),kind:"errored"};try{return{commitCursor:n.commitCursor,kind:"committed",value:C(n.result)}}catch(e){return{commitCursor:n.commitCursor,error:Le(e),kind:"undecodable"}}},Y=(n,e)=>`${l(n)}\0${e}`,Vi=(n,e)=>{for(const t of e)t.op==="delete"?n.delete(t.key):t.value!==void 0&&n.set(t.key,t.value)};class zi{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){_e(this.buffers,this.maxBuffers),this.buffers.set(Y(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(Y(e,t.pokeId));if(!s)return;const i=[];try{for(const o of t.rowsPatch)i.push(o.value===void 0?o:{...o,value:C(o.value)})}catch(o){s.undecodable.set(t.shapeId,o);return}const r=s.parts.get(t.shapeId)??[];for(const o of i)r.push(o);s.parts.set(t.shapeId,r),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const a=t.baseCheckpoint??s.baseCheckpoint;a!==void 0&&s.bases.set(t.shapeId,a),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=Y(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const Ji=(n,e,t)=>{const s=e.parts.get(n.id)??[],i=e.resets.has(n.id),r=e.bases.get(n.id),a=e.epoch!==void 0&&n.serverEpoch!==void 0&&e.epoch!==n.serverEpoch,o=r!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r;if(!i&&(a||o))return n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,n.answered=!1,"reseed";i&&n.rows.clear(),Vi(n.rows,s),n.answered=!0,t.checkpoint!==void 0&&(n.serverCursor=t.checkpoint),t.epoch!==void 0&&(n.serverEpoch=t.epoch);const c=e.lastMutationId.get(n.id);return c!==void 0&&(n.lastMutationId=c),"applied"},we=n=>{const e=[...n.rows.values()];for(const t of n.callbacks)try{t(e)}catch{}},Yi=(n,e)=>{for(const[t,s]of e.undecodable){const i=n.get(t);i&&O(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},se=(n,e)=>{n.lastMutationId=Math.max(n.lastMutationId??0,e)},ie=(n,e=!1)=>{for(const t of n.checkpointCallbacks)t({checkpoint:n.serverCursor,mutationId:n.lastMutationId,...e&&{rowsFollow:!0}})},Me=(n,e,t)=>{n.serverBase=e,t.cursor!==void 0&&(n.serverCursor=t.cursor),t.epoch!==void 0&&(n.serverEpoch=t.epoch)},Xi=(n,e)=>e.cursor!==void 0&&n.serverCursor!==void 0&&n.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===n.serverEpoch&&e.cursor<n.serverCursor,G=(n,e)=>n!==void 0&&n!==e,Zi=(n,e)=>e==="connected"&&n!=="connected"||e==="polling"&&n!=="connected"&&n!=="polling",en=n=>{for(const e of n.activeSubscriptions())e.valueReceived=!1,n.ensureSocket(e.shardKey),n.queueResubscribe(e);for(const e of n.activeShapes())e.answered=!1,n.ensureSocket(e.shardKey);for(const e of n.queuedShardKeys())n.ensureSocket(e);n.broadcastStatus(n.computeStatus(),n.identityFingerprint()),n.emitConnectionStatus()},tn=n=>{n.closeConnections();const e=n.leader;e.status=void 0,e.wasEverConnected=!1;for(const t of n.activeSubscriptions())t.acked=!1,t.valueReceived=!1;for(const t of n.activeShapes())t.answered=!1;n.emitConnectionStatus()},sn=(n,e,t)=>{if(G(t,n.identityFingerprint()))return;const s=n.leader,i=Zi(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),n.emitConnectionStatus(),i&&n.flushOfflineQueues()},nn=n=>{n.isLeader()&&n.broadcastStatus(n.computeStatus(),n.identityFingerprint())},rn=(n,e,t,s,i,r)=>{if(G(r,n.identityFingerprint()))return;const a=n.subscription(e);if(!a)return;n.dropCacheSeed(e);const o=!a.valueReceived;a.valueReceived=!0,Me(a,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&Z(a,s),M(a,t),o&&n.emitConnectionStatus()},on=(n,e,t,s)=>{if(G(s,n.identityFingerprint()))return;const i=n.subscription(e);if(i){const r=!i.valueReceived;i.valueReceived=!0,O(i.errorCallbacks,t),r&&n.emitConnectionStatus()}},an=(n,e,t,s,i,r,a)=>{if(G(a,n.identityFingerprint()))return;const o=n.subscription(e);o&&(n.ackAndAdvanceCursor(o,t,s),i!==void 0&&r===n.clientIdentifier()&&se(o,i),ie(o))},cn=(n,e,t)=>n!==null||e&&t===null,dn=n=>n.sensitive===!0,hn=(n,e)=>{if(!dn(n))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${n.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},un=[Qe],ln=100,He=1e4,fn=1e4,pn=(n,e)=>{let t;const s=new Promise((r,a)=>{t=setTimeout(()=>{a(new Error("ws ticket mint timed out"))},e)}),i=(async()=>n())();return Promise.race([i,s]).finally(()=>{clearTimeout(t)})},Ee=async n=>typeof n=="function"?await n():n,mn=async(n,e,t,s)=>{const i=new AbortController,r=setTimeout(()=>{i.abort()},He);try{const a=await n(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return await a.text(),a.status}finally{clearTimeout(r)}},Ae=(n,e)=>new b("OFFLINE_NOT_QUEUED",`'${n}' is online-only and the connection is not live, so it was not queued`,{cause:e}),yn=(n,e)=>n instanceof TypeError&&ee(e),Sn=(n,e,t,s)=>e||n===!0&&t&&!s,bn=Promise.resolve();class Ue{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new _;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;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 R;statusListeners=new R;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new R;identityChangeListeners=new R;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new R;pendingChangeListeners=new R;syncStatusListeners=new R;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new zi(Ue.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??E(de(e.url),z),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??Ys;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??qe(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Ve,this.connectTimeoutMs=e.connectTimeoutMs??ze,this.rpcTimeoutMs=e.rpcTimeoutMs??Je,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Ye,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Xe,this.defaultConnectionContext=e.connectionContext,this.persistence=yt(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=bt(e.queryCache),this.clientQueryStore=new $e,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=bn),this.offlineQueue=new pt(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onReplayingChange:()=>{this.emitSyncStatus()},onSizeChange:s=>{this.pendingChangeListeners.emit(s),this.emitSyncStatus()},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${ye()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=Lt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,i=this.identityFingerprint(),r=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),o=this.isKnownNobody(),c=this.authToken;this.authToken=e,this.applySubject(e,t);const h=this.identityFingerprint();h!==i&&(!s&&e!==null&&r?(this.restampQueuedIdentity(i,h),this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):!s&&e===null&&i===null&&r&&!o?(this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(c,e),cn(i,o,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(h!==i||s||a)&&this.offlineQueue.size>0&&q(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 i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const r=s?.shardKey??"",a=this.identityFingerprint();let o,c,h;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:u=>{o=u}})}catch(u){if(!K(u))throw u;h=u}if(o!==void 0&&o>(this.clientWatermarks.get(a??"")?.get(r)??0)){let u=this.clientWatermarks.get(a??"");u===void 0&&(_e(this.clientWatermarks,rt),u=new Map,this.clientWatermarks.set(a??"",u)),u.set(r,o)}if(h!==void 0)throw h;return{applied:o===void 0||o===i,result:c}}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 i=await this.fetchImpl(E(this.url,`${this.authBasePath}${Xs}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(t,null,s),null;const a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,a,s),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}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),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),i={context:e},r=this.connectionContextHolders.get(s);r?r.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;const o=this.connectionContextHolders.get(s);if(!o)return;const c=o.indexOf(i);c!==-1&&o.splice(c,1),o.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const i=l(s.shardKey);let r=this.whisperHandlers.get(i);r||(r=new Map,this.whisperHandlers.set(i,r));let a=r.get(e);const o=a===void 0;if(a||(a=new Set,r.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),o){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,i,e)}return()=>{const c=this.whisperHandlers.get(i),h=c?.get(e);if(!h?.delete(t)||h.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const d=this.getConnection(s.shardKey);d&&k(d,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:i,stream:r,topic:a}=e;if(a.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const o=`ws-live-${String(this.nextLiveSocketId)}`,c=l(i),h=`/live/${r}/control`;let u=this.whisperSubscribe(a,()=>{},{shardKey:i});const f=()=>{const S=u;u=void 0,S?.()};let p=this.liveSocketGrants.get(c);p===void 0&&(p=new Map,this.liveSocketGrants.set(c,p)),p.set(o,{onError:t,onEvent:s,release:f,stream:r,topic:a});const y=this.getConnection(i)?.connectionId;y!==void 0&&this.grantWhenJoined(i,o,y);let m=!1;return()=>{if(m)return;m=!0;const S=this.liveSocketGrants.get(c),w=S?.delete(o)===!0;S?.size===0&&this.liveSocketGrants.delete(c);const v=this.getConnection(i)?.connectionId;w&&v!==void 0&&this.postLiveControl(h,i,{action:"unsubscribe",connectionId:v,stream:r,subscriptionId:o,topic:a}),f()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,A(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const i=`room:${e.name}`,r=this.whisperSubscribe(i,f=>{t.onMessage(f)},s);let a=!1;const o=[],c=()=>{o.length=0},h=()=>{for(;o.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(i,o[0],s))return;o.shift()}},d=l(s.shardKey),u=this.roomFlushes.get(d)??new Set;return u.add(h),this.roomFlushes.set(d,u),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,u.delete(h),u.size===0&&this.roomFlushes.delete(d),this.roomIdentityResets.delete(c),r()},send:f=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=A(f,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return h(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,y,s)?!0:o.length>=ln?!1:(o.push(y),!0)}}}connectWebSocket(e,t,s={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:()=>{},send:()=>{}};const i=o=>{try{o?.()}catch(c){console.error("[lunora] socket route handler threw",c)}};let r;const a=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:()=>{clearTimeout(r),i(t.onClose)},onMessage:o=>{let c;try{c=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}c.type==="message"&&(a.resetBackoff(),i(()=>{t.onMessage(C(c.data))}))},onOpen:()=>{clearTimeout(r);const o=a.socket();r=setTimeout(()=>{a.socket()===o&&a.resetBackoff()},me),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(r),a.close()},send:o=>{const c=JSON.stringify(A(o,`socket message for '${e}'`)),h=a.socket();if(h!==void 0)try{h.send(c)}catch{}}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}syncStatus(){const e=this.computeStatus(),t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader();let s=0;for(const r of this.subscriptions.all())(t||this.connectionGateState(r.shardKey).polling?r.valueReceived:r.acked)||(s+=1);for(const r of this.shapeSubscriptions.values())r.answered||(s+=1);const i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:s,pendingWrites:i,synced:q(e)&&s===0&&i===0}}onSyncStatus(e){const t=this.syncStatusListeners.add(e),s=this.syncStatus();return this.lastSyncStatus=s,e(s),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 r of s){const a=this.connections.get(r);e.push({confirmedMutationWatermark:t?.get(r)??0,hasSocket:a?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}const i=this.subscriptions.all().map(r=>({acked:r.acked,functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())i.push({acked:r.answered,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((r,a)=>(r.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((r,a)=>r.functionPath.localeCompare(a.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 vt(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Se(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ce(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=L(e,t,s),r=this.hydratedQueryCache.get(i);if(r!==void 0)return this.cachedQueryMatchesIdentity(r)?r.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=_.key(e,t,s),r=this.subscriptions.get(i);return{present:r!==void 0,value:r?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,signal:s.signal})}async batch(e){return D(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw St(s.signal);const{value:i}=await Se(this.runMutation(e,t,s),s.signal);return i}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,signal:s.signal,unbounded:!0})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),r=s.toArgs??(d=>({rows:d})),a=t.length;let o=0,c=0,h=0;for(let d=0;d<a;d+=i){const u=t.slice(d,d+i),f=h,{committed:p}=await this.runMutation(e,r(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(f)}`},shardKey:s.shardKey});h+=1,o+=u.length,p&&(c+=u.length),s.onProgress?.({done:o,total:a})}return{chunks:h,imported:c,queued:o-c}}async shardTraffic(e){return pi(this.adminHost,e)}async listScheduledJobs(){return Si(this.adminHost)}async schedulerStatus(){return bi(this.adminHost)}async cancelScheduledJob(e){return vi(this.adminHost,e)}async listDeadJobs(){return gi(this.adminHost)}async retryDeadJob(e){return Ti(this.adminHost,e)}async removeDeadJob(e){return ki(this.adminHost,e)}async listWorkflowInstances(e){return Ci(this.adminHost,e)}async getWorkflowInstance(e){return wi(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ei(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=this.openSupplementarySocket(E(de(this.url),Wt),{onMessage:s=>{let i;try{i=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(t.resetBackoff(),e(i.records.map(r=>ae(r))))}});return t.close}async listFunctions(){return ei(this.adminHost)}async getCronJobs(){return ti(this.adminHost)}async runCronJob(e){return si(this.adminHost,e)}async fetchOpenApi(){return ii(this.adminHost)}async fetchArchitecture(){return ni(this.adminHost)}async fetchOpenRpc(){return ri(this.adminHost)}async listStorageObjects(e={}){return Ai(this.adminHost,e)}async deleteStorageObject(e,t){return _i(this.adminHost,e,t)}async listStorageBuckets(){return Ii(this.adminHost)}async uploadStorageObject(e){return Oi(this.adminHost,e)}async signedStorageUrl(e,t){return Ri(this.adminHost,e,t)}async listGlobalTables(){return oi(this.adminHost)}async readGlobalTablePage(e){return ai(this.adminHost,e)}async facetGlobalColumn(e){return ci(this.adminHost,e)}async listVectorIndexes(){return Pi(this.adminHost)}async queryVectorIndex(e){return Fi(this.adminHost,e)}async queryLogArchive(e={}){return mi(this.adminHost,e)}async listKvNamespaces(){return di(this.adminHost)}async listKvKeys(e){return hi(this.adminHost,e)}async getKvValue(e){return ui(this.adminHost,e)}async putKvValue(e){return li(this.adminHost,e)}async deleteKvKey(e){return fi(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=g(as,{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 this.assertOpen(),await this.adminFetch(ds,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(hs,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(us,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(ls,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(fs,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(ps,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(ms,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(ys,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(bs,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(g(gs,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(Ts,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(g(ks,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(Cs,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(ws,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(g(Es,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=g(As,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=g(_s,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=g(Ps,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Fs,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Ls,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(Is,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Os,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(Rs,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Ms,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Hs,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Us,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ns,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ws,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Ds,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=g(xs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Bs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Qs,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(qs,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=g(Ks,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Gs,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(js,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=g($s,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Vs,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(zs,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Js,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=g(cs,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const r=t??{},a=_.key(e.__lunoraRef,r,i.shardKey);let o=this.subscriptions.get(a);const c=j(s),h=j(i.onError),d=j(i.onCheckpoint);if(!o){this.nextSubId+=1;const y=`sub_${this.nextSubId.toString()}`,m=ce(r),S=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);o={acked:!1,args:r,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:S?.value,optimisticLayers:[],serverBase:S?.value,serverCursor:S?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:A(r,`args for '${e.__lunoraRef}'`),...S?.serverEpoch===void 0?{}:{serverEpoch:S.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),S!==void 0&&this.cacheSeededQueries.set(a,S)}if(o.callbacks.add(c),h&&o.errorCallbacks.add(h),d&&o.checkpointCallbacks.add(d),o.lastValue!==void 0)try{c(o.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const u=o;let f=!1;const p=()=>{if(!f&&(f=!0,i.signal?.removeEventListener("abort",p),u.callbacks.delete(c),h&&u.errorCallbacks.delete(h),d&&u.checkpointCallbacks.delete(d),u.callbacks.size===0)){this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(_.keyOf(u)),this.subscriptions.remove(u);const y=this.getConnection(u.shardKey);y&&this.settleSubscribeWatchdog(y,u.id),this.releaseIdleShard(u.shardKey),this.emitSyncStatus()}};return i.signal?.addEventListener("abort",p,{once:!0}),i.signal?.aborted&&p(),p}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({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 i=`shape_${this.nextShapeId.toString()}`,r={answered:!1,args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:A(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,r),this.emitSyncStatus(),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(r),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(r.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(r.shardKey),this.emitSyncStatus()}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:r}=s,a=t??{},{handle:o,iterable:c}=gt({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const h=this.getConnection(r),d={id:i,query:{args:A(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:r},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:o,lastSeq:0,message:d,shardKey:r};this.streams.set(i,u);const f=h?.wsState==="open"&&k(h,d);if(!f&&h===void 0)return this.forgetStream(i),o.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Ze;){const y=h.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(y))}h.pendingStreams.push(d)}return c}httpStream(e,t,s={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return dt(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new b("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(),this.supplementaryBounces.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.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.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 b("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 b("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}shardInUse(e){const t=s=>l(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=l(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},et))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[i,r]of this.streams)l(r.shardKey)===t&&(r.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,H(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeShapes:()=>[...this.shapeSubscriptions.values()],activeSubscriptions:()=>this.subscriptions.all(),broadcastStatus:(s,i)=>this.tabCoordinator?.broadcastConnectionStatus(s,i),closeConnections:()=>{for(const[s,i]of this.connections)this.teardownConnection(i),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,i,r)=>{this.ackAndAdvanceCursor(s,i,r)},subscription:s=>this.subscriptions.get(s)};return new ot({channelName:e,onBecomeLeader:()=>{en(t)},onStopBeingLeader:()=>{tn(t)},onConnectionStatus:(s,i)=>{sn(t,s,i)},onSubscriptionData:(s,i,r,a,o)=>{rn(t,s,i,r,a,o)},onLeaderClaimAnswered:()=>{nn(t)},onSubscriptionError:(s,i,r)=>{on(t,s,i,r)},onSubscriptionSettled:(s,i,r,a,o,c)=>{an(t,s,i,r,a,o,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(E(this.url,V),{body:JSON.stringify({calls:e.map((o,c)=>({args:A(o.args??{},`args for batch call '${o.fn.__lunoraRef}'`),functionPath:o.fn.__lunoraRef,id:c,shardKey:o.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let r;try{r=await s.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const a=B(r);if(!s.ok||a!==void 0&&!r.results)throw a!==void 0?le(a):new b("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const o of r.results??[]){const c=o.body?.commitCursor;typeof o.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[o.id]?.shardKey,c)}return Li(r.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const i=hn(e,s),r=t,a=i.mutationId??ye();this.mutationIssueCounter+=1;const o=this.mutationIssueCounter,c=this.takeReplayCredential(i.replayCredential),h=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);const{confirms:d,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,r,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,u,d);const f=i.onlineOnly?void 0:this.offlineFlushes.get(l(i.shardKey));f!==void 0&&await f;const{httpFirst:p,midReconnect:y,shouldQueueOffline:m,socketDown:S}=this.writeQueueGate(i.shardKey),w=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),v=async(T=!1)=>this.enqueueOfflineMutation(e,r,i.shardKey,h,a,u,d,T?void 0:i.precondition,i.mutationId,c?.stamp,T,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,u),S||y||w)return v();let N;try{const T=await this.rpc(e.__lunoraRef,r,i.shardKey,{baselineSeq:h,captureBookmark:!0,...c?.flags,mutationId:a,onCommitCursor:P=>{N=P}});for(const P of d)P(N);return{committed:!0,value:T}}catch(T){const P=yn(T,r),Ne=p&&m&&P,We=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(T instanceof TypeError||T instanceof U)&&ee(r)){const De=v(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),De}throw this.settleFailedDirectWrite(T,N,d,u,c?.flags.authToken),Sn(i.onlineOnly,Ne,P,We)?Ae(e.__lunoraRef,T):T}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw F(s),Ae(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){const{hasSocket:t,idleClosed:s,polling:i,wasEverConnected:r,wsState:a}=this.connectionGateState(e),{queueBeforeFirstConnect:o}=this.offlineQueue,c=r||o,h=this.WebSocketImpl!==void 0&&c,d=i||s;return{httpFirst:d,midReconnect:a==="connecting"&&c&&!d,shouldQueueOffline:h,socketDown:a!=="open"&&!t&&h&&!d,socketOpen:a==="open"}}settleFailedDirectWrite(e,t,s,i,r){if(this.noteIdentityMismatch(e),r!==void 0&&this.noteReplayAuthRefusal(e,r),K(e)){for(const a of s)a(t);return}F(i)}async enqueueOfflineMutation(e,t,s,i,r,a,o,c,h,d,u,f){const p=d===void 0?this.identityFingerprint():d;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(m)}`,identity:p,mutationId:m,...a.length>0&&{onRejected:()=>{F(a)}},shardKey:s})}catch(S){throw F(a),S instanceof Error?S:new Error(String(S))}for(const S of o)S(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,S)=>{const w={ambiguousSend:u,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,issueSeq:f,clientId:this.clientId,identity:p,precondition:c,onCommit:v=>{for(const N of o)N(v)},reject:v=>{this.queuedIdentities.delete(r),K(v)||F(a),S(v instanceof Error?v:new Error(String(v))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(w),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),w.id!==void 0&&this.queuedIdentities.set(w.id,p)})}}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(L(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(mt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const r=t.get(s);if(r&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(r,i);continue}this.hydratedQueryCache.set(s,i)}}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(L(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),M(e,t.value))}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,M(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=L(e,t,s),r=this.hydratedQueryCache.get(i);if(!(r===void 0||!this.cachedQueryMatchesIdentity(r)))return this.hydratedQueryCache.delete(i),r}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=L(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=L(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,r=i===void 0?this.identityFingerprint():i;r===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:r,serverCursor:e.serverCursor,ts:Date.now(),value:t,...r===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(()=>{})},tt))}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,i])=>e.put(s,i)))}installPageHideFlush(){const e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;const t=()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},s=()=>{e.document?.visibilityState==="hidden"&&t()};e.addEventListener("pagehide",t),e.document?.addEventListener("visibilitychange",s),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",t),e.document?.removeEventListener("visibilitychange",s)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"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 i of this.subscriptions.all())l(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}composedBaselineFor(e,t){return e===void 0?this.baselineCursorFor(t):e??void 0}async pollSubscriptions(e){const t=l(e),s=[];for(const o of this.subscriptions.all())l(o.shardKey)===t&&(ee(o.args)?s.push(o):(this.markQueryRejected(o,!0),O(o.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(s.length===0)return this.probeOrigin();const i=ft(),r=this.identityFingerprint();let a;try{a=await ke(async o=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),o))}catch(o){return!(o instanceof TypeError)}if(this.identityFingerprint()!==r)return!0;for(const[o,c]of s.entries()){const h=a[o];if(h!==void 0){if(!h.ok){this.markQueryRejected(c,!0),O(c.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:x(h.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await ke(async t=>e(E(this.url,V),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;const e=this.syncStatus(),t=this.lastSyncStatus;t?.connection===e.connection&&t.pendingSubscriptions===e.pendingSubscriptions&&t.pendingWrites===e.pendingWrites&&t.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){const e=this.computeStatus();this.emitSyncStatus(),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,i){const r=[],a=[];if(!i)return{confirms:r,rollbacks:a};const o=_.key(e,t,s),c=this.subscriptions.get(o);if(c){const h=ht(c,i);h&&(r.push(h.confirm),a.push(h.rollback))}return{confirms:r,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,r){e&&this.applyOptimisticUpdate(e,t,s,i,r)}applyOptimisticUpdate(e,t,s,i,r){const{confirms:a,rollbacks:o,store:c}=ut(this.subscriptions,s);try{e(c,t)}catch{F(o);return}i.push(...o),r.push(...a)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!k(i,{id:t,type:s})&&i.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(l(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,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:Wi({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:be(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}openSupplementarySocket(e,t){if(this.WebSocketImpl===void 0||this.closed)return{close:()=>{},resetBackoff:()=>{},socket:()=>{}};const s=be(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let r,a=!1;const o=()=>{a||this.closed||(r=setTimeout(f,s.next()))},c=m=>{a||this.WebSocketImpl===void 0||Te(i,this.wsUrlFor(t.shardKey,m,e),this.managedSocketOptions,{onClose:()=>{o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen}})};let h=0,d;const u=async m=>{const S=this.wsCredentialGeneration;h+=1;const w=h;let v;d=S;try{v=await pn(m,fn)}catch{w===h&&(d=void 0,o());return}if(w===h){if(d=void 0,S!==this.wsCredentialGeneration){f();return}c(v)}},f=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:m}=this;if(typeof m=="function"){u(m).catch(()=>{});return}c(m)};f();const p=()=>{a=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i);const{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}};this.adminSocketTeardowns.add(p);const y=()=>{const{socket:m}=i;if(m===void 0){d!==void 0&&d!==this.wsCredentialGeneration&&(h+=1,d=void 0,f());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i);try{m.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(y),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(y)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=he(this.wsUrl),s=t.pathname.endsWith(z)?t.pathname.slice(0,-z.length):t.pathname;return t.pathname=E(s,e),ue(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=he(s);if(e===void 0&&t===void 0&&!i.searchParams.has("token"))return s;const r=new Set([...e===void 0?[]:["shard"],"token"]),a=[...i.searchParams].filter(([o])=>!r.has(o)).map(([o,c])=>`${encodeURIComponent(o)}=${encodeURIComponent(c)}`);return e!==void 0&&a.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&a.push(`token=${encodeURIComponent(t)}`),i.search=a.join("&"),ue(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[wt]=Et(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const r=e.authToken===void 0?this.authToken:e.authToken;if(r&&(s.authorization=`Bearer ${r}`),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 a=this.bookmark.get();a&&(s["x-d1-bookmark"]=a)}return s}async rpc(e,t,s,i={}){const{fetchImpl:r}=this;if(!r)throw new U("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:A(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:h,response:d}=await D(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const y=await r(E(this.url,Mt),{body:c,headers:a,method:"POST",signal:p});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){const p=d.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(h===void 0)throw W(d.status,d.statusText,d.headers.get("retry-after"));const u=h;if(typeof u!="object"||u===null||Array.isArray(u))throw W(d.status,d.statusText,d.headers.get("retry-after"));const f=B(h);if(f!==void 0)throw fe(f,d.headers.get("retry-after"));if(!d.ok)throw W(d.status,d.statusText,d.headers.get("retry-after"));i.onMutationAck?.(h.lastMutationId),i.onCommitCursor?.(h.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(d,s),this.recordShardCursor(s,h.commitCursor);try{return C(h.result)}catch(p){throw Le(p)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");const r={};this.authToken&&(r.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let o;s===void 0?o=void 0:a?(o=s,i!==void 0&&(r["content-type"]=i)):(o=JSON.stringify(s),r["content-type"]="application/json");const c=await this.fetchImpl(E(this.url,e),{body:o,headers:r,method:t});let h;try{h=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const d=B(h);if(d!==void 0)throw le({...d,message:d.message??"admin request failed"});if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${c.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));k(e,{caps:un,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}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);t.wsState==="open"||t.wsState==="connecting"||(t.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(t,e).catch(()=>{this.handleDisconnect(t)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,t){const{wsToken:s,wsTicket:i}=this;if(typeof s=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,t);return}this.openSocket(e,t,{session:s,ticket:i})}async openSocketWithProvidedCredentials(e,t){const s=this.wsCredentialGeneration,i=Symbol("ws-token-attempt");let r;e.providerAttempt=i;try{r=await D(this.connectTimeoutMs,void 0,async()=>({session:await Ee(this.wsToken),ticket:await Ee(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(s!==this.wsCredentialGeneration){await this.startShardSocket(e,t);return}this.openSocket(e,t,r)}}openSocket(e,t,s){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),s.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=s.session,e.retired=!1;const i=this.wsCredentialGeneration;Te(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:r=>{r?.code===4003&&e.polling.noteFailedOpen(),r?.code===4001?this.notifyTokenExpired():r?.code===4003&&r.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},onMessage:r=>{e.retired!==!0&&this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},me),this.sendConnectEnvelope(e),this.markShardPendingAck(t,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(const o of this.subscriptions.all())l(o.shardKey)===l(t)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:c,type:h}of o)k(e,{id:c,type:h});this.releaseIdleShard(t)}Mi(e);const r=l(t),a=this.whisperHandlers.get(r);if(this.dropWhisperJoinWaiters(r),this.whisperJoins.set(r,new Map),a)for(const o of a.keys())this.sendWhisperJoin(e,r,o);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})}})}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),k(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),H(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(l(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,r]of this.streams)if(!(l(r.shardKey)!==l(e.shardKey)||t.has(i))){if(r.durable){const a={...r.message,...r.generation===void 0?{}:{generation:r.generation},sinceChunk:r.lastSeq};r.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(o=>o.id!==i),a];continue}r.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e,t=!1){const s=l(e);for(const i of this.subscriptions.all())l(i.shardKey)===s&&(i.acked=!1,t&&(i.valueReceived=!1));for(const i of this.shapeSubscriptions.values())l(i.shardKey)===s&&(i.answered=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<st;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribeSlots.add(t.id)}}settleSubscribeWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t)),e.unackedWatchdogs.delete(t),e.resubscribeSlots.delete(t)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(const t of e.unackedWatchdogs.values())clearTimeout(t);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,t=!1){const s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;const i=e.serverCursor!==void 0&&e.serverBase!==void 0,r=k(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return r&&!t&&this.armUnackedWatchdog(s,e),r}armUnackedWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t.id)),e.unackedWatchdogs.set(t.id,setTimeout(()=>{!t.acked&&this.subscriptions.getById(t.id)===t&&this.sendSubscribeIfOpen(t,!0),this.settleSubscribeWatchdog(e,t.id)},it))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&k(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=Ui(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}if(i.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof i.id=="string"){const r=this.getConnection(t);if(r){const{id:a}=i;this.settleSubscribeWatchdog(r,a)}}switch(i.type){case"ack":{const r=this.subscriptions.getById(i.id);r&&this.ackAndAdvanceCursor(r,void 0,void 0);return}case"chunk":{const{data:r,generation:a,id:o,seq:c}=i,h=this.streams.get(o);h&&typeof c=="number"&&(h.lastSeq=c,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(C(r));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,t),this.adoptSocketConnectionId(i,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(i,t);break}case"pokeEnd":{this.handlePokeEnd(i,t);break}case"pokePart":{this.pokeAssembler.part(t,i);break}case"pokeStart":{this.pokeAssembler.start(t,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(l(t),i.topic);break}}}handleErrorMessage(e){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(Ge(e)),this.forgetStream(s);return}const r=s===void 0?void 0:this.subscriptions.getById(s);if(r){const o=pe(e),c=this.identityFingerprint(),h=_.keyOf(r);this.markQueryRejected(r),O(r.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,o,c);return}const a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&(a.answered||(a.answered=!0,this.emitSyncStatus()),O(a.errorCallbacks,pe(e)))}markQueryRejected(e,t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){const s=t?"valueReceived":"acked";e[s]||(e[s]=!0,this.emitSyncStatus())}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){Yi(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const r=this.shapeSubscriptions.get(i);r&&!s.undecodable.has(i)&&this.applyPokePart(r,s,e)}}}applyPokePart(e,t,s){const i=e.answered,r=Ji(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),we(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&Xi(i,e))return;let r;try{r=xe(e,i.serverBase)}catch(o){O(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${o instanceof Error?o.message:String(o)}`});return}if(r===Be){this.resnapshotSubscription(i);return}this.dropCacheSeed(_.keyOf(i));const a=t!==void 0&&!i.valueReceived;if(Me(i,r,{cursor:e.cursor,epoch:e.epoch}),a&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(se(i,e.lastMutationId),ie(i,!0)),this.persistQueryValue(i),Z(i,i.serverCursor),t!==void 0&<(i,t),M(i,r),this.tabCoordinator?.isLeader()){const o=_.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,r,i.serverCursor,i.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&&se(t,e.lastMutationId),ie(t),this.tabCoordinator?.isLeader())){const s=_.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){const i=!e.acked;e.acked=!0,i&&this.emitSyncStatus(),(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),Z(e,e.serverCursor)&&M(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(!(s===void 0||typeof e.connectionId!="string")){s.connectionId=e.connectionId,s.whisperAck=e.whisperAck===!0;for(const i of this.liveSocketGrants.get(l(t))?.keys()??[])this.grantWhenJoined(t,i,e.connectionId)}}grantWhenJoined(e,t,s){const i=l(e),r=this.liveSocketGrants.get(i)?.get(t);if(r===void 0)return;const{stream:a,topic:o}=r,c=()=>{this.liveSocketGrants.get(i)?.get(t)===void 0||this.getConnection(e)?.connectionId!==s||this.postLiveControl(`/live/${a}/control`,e,{action:"subscribe",connectionId:s,stream:a,subscriptionId:t,topic:o},d=>{this.refuseLiveGrant(e,t,d,s)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,o,c):c()}sendWhisperJoin(e,t,s){const i=this.whisperJoinState(t,s);i.pending+=1,i.joined=!1,k(e,{topic:s,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,t){const s=this.whisperJoins.get(e)?.get(t);if(s!==void 0&&(s.pending=Math.max(0,s.pending-1),!(s.pending>0))){s.joined=!0;for(const i of s.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,t)}}releaseWhisperJoin(e,t){if(this.whisperHandlers.get(e)?.has(t)===!0)return;const s=this.whisperJoins.get(e),i=s?.get(t);if(!(s===void 0||i===void 0||i.pending>0)){for(const r of i.waiters.splice(0))clearTimeout(r.timer);s.delete(t),s.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,t,s){const i=this.whisperJoinState(e,t);if(i.joined){s();return}const r={run:s,timer:void 0};r.timer=setTimeout(()=>{i.waiters=i.waiters.filter(a=>a!==r),s()},He),i.waiters.push(r)}dropWhisperJoinWaiters(e){for(const t of this.whisperJoins.get(e)?.values()??[])for(const s of t.waiters.splice(0))clearTimeout(s.timer)}whisperJoinState(e,t){let s=this.whisperJoins.get(e);s===void 0&&(s=new Map,this.whisperJoins.set(e,s));let i=s.get(t);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},s.set(t,i)),i}refuseLiveGrant(e,t,s,i){const r=l(e),a=this.liveSocketGrants.get(r),o=a?.get(t);a===void 0||o===void 0||this.getConnection(e)?.connectionId!==i||(a.delete(t),a.size===0&&this.liveSocketGrants.delete(r),o.release(),o.onError?.({status:s,topic:o.topic}))}postLiveControl(e,t,s,i){const{fetchImpl:r}=this;if(!r)return;const a=JSON.stringify(t===void 0?s:{...s,shardKey:t}),o=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>mn(r,E(this.url,e),a,o)).then(c=>{c>=400&&c<500&&c!==404&&c!==401&&i?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(l(t));if(!s)return;const i=C(e.data);for(const r of s.values())if(!(r.stream!==e.stream||r.topic!==e.topic))try{r.onEvent(i)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const i=C(e.data);for(const r of s)try{r(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,this.emitSyncStatus(),O(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(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 i=0;i<e.length;i+=1){const r=e.charCodeAt(i);t^=r,t=Math.imul(t,16777619),s=Math.imul(s,33)+r}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&&q(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)}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey),r=i!==void 0&&k(i,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),r}roomSendsAdmitted(e){const t=this.getConnection(e);return t?.wsState==="open"&&t.retired!==!0&&t.identityConfirmed===!0&&t.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(const t of this.roomFlushes.get(l(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0,t.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==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}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const i of t){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);const r=new Error("offline mutation discarded: auth identity changed before replay");r.code="OFFLINE_IDENTITY_CHANGED",i.reject(r),this.emitItemSettled(i,"rejected",r)}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,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);const r=t??"",a=this.clientWatermarks.get(r);if(a===void 0)this.clientWatermarks.set(r,i);else for(const[o,c]of i)a.set(o,c)}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.resetRoomSends(),this.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,e.valueReceived=!1,M(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,we(e);this.emitSyncStatus(),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()}resetRoomSends(){for(const e of this.roomIdentityResets)e()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)});for(const e of this.supplementaryBounces)e()}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 i=(async()=>{await(s??Promise.resolve());const{authToken:r}=this;try{await this.drainOfflineQueue(e,r)}catch{}!this.closed&&this.authToken!==r&&this.offlineQueue.size>0&&q(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,i),await i,this.offlineFlushes.get(t)===i&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}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 i=l(e),r=this.offlineQueue.drain(d=>l(d.shardKey)===i);if(r.length===0)return;const a=[],o=[];for(const d of r){const u=this.replayGateVerdict(d);u==="send"?a.push(d):u==="hold"&&o.push(d)}if(this.offlineQueue.requeue(o),o.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(a);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const h=[];for(let d=0;d<c.length;d+=$){const u=c.slice(d,d+$),f=await this.replayBatched(u,e,t);if(h.push(...f.requeue),f.stop||f.requeue.length>0){h.push(...c.slice(d+$));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(e),s=this.replayRetryState.get(t),i=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:i,delayMs:Math.max(s?.delayMs??0,te(i))})}noteReplayRetryDelay(e,t,s){const i=l(e),r=this.replayRetryState.get(i),a=(r?.attempts??0)+1,o=qi(t,a)??(s===null&&Q(t)?te(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:o===void 0?r?.delayMs:Math.max(r?.delayMs??0,o)})}scheduleRateLimitedRetry(e){const t=l(e),s=this.replayRetryState.get(t),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const r=this.replayRetryTimers.get(t);r!==void 0&&clearTimeout(r),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{A(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}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 i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"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 i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),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)||Ce(e)}noteReplayAuthRefusal(e,t){if(!Q(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 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,...J(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)}spendsLastReplayAttempt(e,t){if(e.id===void 0)return!1;const s=t?.code;if(e.ambiguousSend!==!0||Q(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||!Ce(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=nt}keepUnexhaustedAmbiguousWrites(e,t){return e.filter(s=>s.ambiguousSend===!0&&this.spendsLastReplayAttempt(s,t)?(this.settleReplayTerminal(s,t),!1):!0)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const r=e[i];if(!r)continue;let a;try{const o=await this.rpc(r.functionPath,r.args,r.shardKey,{authToken:s,baselineSeq:r.baselineSeq,captureBookmark:!0,clientId:r.clientId??this.clientId,...J(r.identity,s),mutationId:r.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(r,o,a)}catch(o){if(K(o)){this.settleReplayUndecodable(r,o,a);continue}if(!this.shouldRequeueReplayFailure(o,s)||this.spendsLastReplayAttempt(r,o)){this.settleReplayTerminal(r,o);continue}this.noteReplayRetryDelay(t,o,s),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const i=JSON.stringify({calls:e.map((d,u)=>({args:A(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:u,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Gi(i)>Ki)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:r}=this;let a,o;try{({payload:o,response:a}=await D(this.rpcTimeoutMs,void 0,async d=>{const u=await r(E(this.url,V),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...J(e.find(f=>f.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(u.status===413&&e.length>1)return{payload:void 0,response:u};try{return{payload:await u.json(),response:u}}catch{return{payload:void 0,response:u}}}))}catch(d){return this.noteReplayRetryDelay(t,d,s),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}const c=a.headers.get("x-d1-bookmark");if(c&&this.bookmark.set(c),a.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);const h=a.headers.get("retry-after");if(!o)return this.settleWholeBatchError(e,W(a.status,a.statusText,h),t,s);if(!Array.isArray(o.results)){const d=B(o),u=d===void 0?W(a.status,a.statusText,h):fe(d,h);return this.settleWholeBatchError(e,u,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof U||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,t),stop:!0};for(const r of e)this.settleReplayTerminal(r,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),r=await this.replayBatched(e.slice(0,i),t,s);if(r.stop||r.requeue.length>0)return{requeue:[...r.requeue,...e.slice(i)],stop:!0};const a=await this.replayBatched(e.slice(i),t,s);return{requeue:[...r.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,t,s,i){const r=ji(t),a=[];let o=!1,c=!1;for(const[h,d]of e.entries()){const u=$i(r.get(h));switch(u.kind){case"committed":{o=!0,this.settleReplaySuccess(d,u.value,u.commitCursor);break}case"errored":{c||=Q(u.error),this.shouldRequeueReplayFailure(u.error,i)&&!this.spendsLastReplayAttempt(d,u.error)?(this.noteReplayRetryDelay(s,u.error,i),a.push(d)):this.settleReplayTerminal(d,u.error);break}case"unanswered":{const f=je();if(this.spendsLastReplayAttempt(d,f)){this.settleReplayTerminal(d,f);break}this.noteReplayRetryDelay(s,f,i),a.push(d);break}default:o=!0,this.settleReplayUndecodable(d,u.error,u.commitCursor)}}return o&&!c&&this.noteCredentialAccepted(i),a}}export{Ue as LunoraClient};
|
package/dist/packem_shared/{createServerClient-dd_Fdt5Z.mjs → createServerClient-CmZmYeQK.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraClient as r}from"./LunoraClient-
|
|
1
|
+
import{LunoraClient as r}from"./LunoraClient-CwCISTif.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};
|
|
@@ -368,12 +368,11 @@ interface QueryCacheAdapter {
|
|
|
368
368
|
remove: (key: string) => Promise<void>;
|
|
369
369
|
}
|
|
370
370
|
/**
|
|
371
|
-
* Resolves
|
|
372
|
-
*
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
* connect attempt, and the client retries with its normal reconnect backoff.
|
|
371
|
+
* Resolves a WebSocket credential (`wsToken` or `wsTicket`) fresh at every
|
|
372
|
+
* (re)connect, so a short-lived credential is re-minted rather than held.
|
|
373
|
+
* May return the value synchronously or as a Promise; returning `undefined`
|
|
374
|
+
* connects without one. A thrown error / rejected Promise fails that connect
|
|
375
|
+
* attempt, and the client retries with its normal reconnect backoff.
|
|
377
376
|
*/
|
|
378
377
|
type WsTokenProvider = () => Promise<string | undefined> | string | undefined;
|
|
379
378
|
interface LunoraClientOptions {
|
|
@@ -554,19 +553,24 @@ interface LunoraClientOptions {
|
|
|
554
553
|
url: string;
|
|
555
554
|
WebSocket?: typeof WebSocket;
|
|
556
555
|
/**
|
|
557
|
-
*
|
|
558
|
-
*
|
|
559
|
-
* `
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
* server logs and history, so prefer a short-lived rotating token in
|
|
563
|
-
* production over a static secret.
|
|
556
|
+
* The short-lived ticket appended to the WebSocket URL as `?token=…`. Only
|
|
557
|
+
* an ephemeral admin sub-token belongs here, minted by
|
|
558
|
+
* `POST /_lunora/admin/ws-token`; the server authorizes `__lunora_admin__:*`
|
|
559
|
+
* subscriptions from it. A ticket lapses after its TTL, so a static master
|
|
560
|
+
* token must never be used here: the server refuses it in the URL.
|
|
564
561
|
*
|
|
565
|
-
* Pass a {@link WsTokenProvider}
|
|
566
|
-
*
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
562
|
+
* Pass a {@link WsTokenProvider} to re-mint on every (re)connect, including
|
|
563
|
+
* the one that follows a lapsed ticket.
|
|
564
|
+
*/
|
|
565
|
+
wsTicket?: string | WsTokenProvider;
|
|
566
|
+
/**
|
|
567
|
+
* The session credential. It is sent in the `connect` frame of every shard
|
|
568
|
+
* socket and never in the WebSocket URL, because a URL is logged by every
|
|
569
|
+
* proxy and edge on the way (protocol §6). The server matches it against
|
|
570
|
+
* `LUNORA_WS_BEARER`; a socket that does not present a match is closed.
|
|
571
|
+
*
|
|
572
|
+
* Pass a {@link WsTokenProvider} to resolve it fresh at every (re)connect, so
|
|
573
|
+
* a rotated session is picked up on the next connect.
|
|
570
574
|
*/
|
|
571
575
|
wsToken?: string | WsTokenProvider;
|
|
572
576
|
wsUrl?: string;
|
|
@@ -663,6 +667,12 @@ interface ClientConnectMessage {
|
|
|
663
667
|
clientId?: string;
|
|
664
668
|
context?: Record<string, unknown>;
|
|
665
669
|
id: string;
|
|
670
|
+
/**
|
|
671
|
+
* The session credential (protocol §6). A gated server checks it against
|
|
672
|
+
* `LUNORA_WS_BEARER`. Set from the client's `wsToken` and never placed in the
|
|
673
|
+
* socket URL.
|
|
674
|
+
*/
|
|
675
|
+
token?: string;
|
|
666
676
|
type: "connect";
|
|
667
677
|
}
|
|
668
678
|
/**
|
|
@@ -1877,9 +1887,14 @@ declare class LunoraClient {
|
|
|
1877
1887
|
private readonly adminHost;
|
|
1878
1888
|
/** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
|
|
1879
1889
|
private readonly clientQueryStore;
|
|
1890
|
+
/** The session credential, sent in the `connect` frame and never in the URL (protocol §6). */
|
|
1880
1891
|
private wsToken;
|
|
1881
|
-
/**
|
|
1882
|
-
private
|
|
1892
|
+
/** The short-lived ticket appended to the upgrade URL as `?token=` (protocol §6). */
|
|
1893
|
+
private wsTicket;
|
|
1894
|
+
/** Bumped on every `setWsToken` / `setWsTicket` change: a provider request started under an older value is superseded. */
|
|
1895
|
+
private wsCredentialGeneration;
|
|
1896
|
+
/** The credential generation the server last refused with 4003, so that refusal notifies once. */
|
|
1897
|
+
private refusedCredentialGeneration;
|
|
1883
1898
|
/** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
|
|
1884
1899
|
private readonly authBasePath;
|
|
1885
1900
|
private readonly fetchImpl;
|
|
@@ -2294,8 +2309,8 @@ declare class LunoraClient {
|
|
|
2294
2309
|
* {@link replayIdentityVerdict} — so a refresh can't replay them and an
|
|
2295
2310
|
* account switch can't replay the previous user's writes as the new one.
|
|
2296
2311
|
*
|
|
2297
|
-
* Does NOT update the WebSocket auth —
|
|
2298
|
-
*
|
|
2312
|
+
* Does NOT update the WebSocket auth — a socket keeps the session credential
|
|
2313
|
+
* it connected with for its life. To refresh live WS auth, call
|
|
2299
2314
|
* {@link setWsToken} explicitly, which closes existing shard sockets to
|
|
2300
2315
|
* force a reconnect with the new credential.
|
|
2301
2316
|
*/
|
|
@@ -2491,15 +2506,23 @@ declare class LunoraClient {
|
|
|
2491
2506
|
*/
|
|
2492
2507
|
getCurrentUser(): Promise<User | null>;
|
|
2493
2508
|
/**
|
|
2494
|
-
* Replace the
|
|
2495
|
-
* every open shard socket so the reconnect
|
|
2496
|
-
*
|
|
2497
|
-
* in
|
|
2498
|
-
* {@link WsTokenProvider} resolved fresh at every (re)connect
|
|
2499
|
-
* for
|
|
2500
|
-
* Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
|
|
2509
|
+
* Replace the session credential sent in the `connect` frame, and close
|
|
2510
|
+
* every open shard socket so the reconnect presents the new value. The
|
|
2511
|
+
* credential never rides the WebSocket URL. Call this when the user's session
|
|
2512
|
+
* changes (sign-in, sign-out, switching workspaces). Accepts a static string
|
|
2513
|
+
* or a {@link WsTokenProvider} resolved fresh at every (re)connect. Bearer
|
|
2514
|
+
* tokens for HTTP RPC are independent — see {@link setAuthToken}.
|
|
2501
2515
|
*/
|
|
2502
2516
|
setWsToken(token: string | undefined | WsTokenProvider): void;
|
|
2517
|
+
/**
|
|
2518
|
+
* Replace the short-lived ticket appended to WS upgrade URLs as `?token=…`,
|
|
2519
|
+
* and close every open shard socket so the reconnect picks up the new value.
|
|
2520
|
+
* Only an ephemeral admin sub-token belongs here (minted by
|
|
2521
|
+
* `POST /_lunora/admin/ws-token`): a URL is logged by every proxy on the way,
|
|
2522
|
+
* so a session credential never goes here — see {@link setWsToken}. Accepts a
|
|
2523
|
+
* static string or a {@link WsTokenProvider} resolved fresh at every (re)connect.
|
|
2524
|
+
*/
|
|
2525
|
+
setWsTicket(ticket: string | undefined | WsTokenProvider): void;
|
|
2503
2526
|
/**
|
|
2504
2527
|
* Register (or clear, with `undefined`) the app context sent in the `connect`
|
|
2505
2528
|
* envelope for a shard's socket, overriding the client-wide
|
|
@@ -2671,12 +2694,15 @@ declare class LunoraClient {
|
|
|
2671
2694
|
* chat.close();
|
|
2672
2695
|
* ```
|
|
2673
2696
|
*
|
|
2674
|
-
* The socket carries the browser's session cookie,
|
|
2675
|
-
*
|
|
2676
|
-
* the server refuses a socket with no verified session. The `wsToken`
|
|
2677
|
-
*
|
|
2678
|
-
*
|
|
2679
|
-
*
|
|
2697
|
+
* The socket carries the browser's session cookie, or an `Authorization` header
|
|
2698
|
+
* where the client can set one, and either establishes a user. A route declared `auth: true` on
|
|
2699
|
+
* the server refuses a socket with no verified session. The `wsToken` is
|
|
2700
|
+
* sent only on shard sockets, in their first `connect` frame; a route socket
|
|
2701
|
+
* has no `connect` frame, so `wsToken` does not authenticate it. The `wsTicket`
|
|
2702
|
+
* (`?token=`, see {@link setWsTicket}) is an ephemeral admin credential
|
|
2703
|
+
* appended to the URL, and it does not sign a user in to a route, so a
|
|
2704
|
+
* private route needs a verified session from the cookie or an `Authorization`
|
|
2705
|
+
* header. Reconnects with the
|
|
2680
2706
|
* client's configured backoff. `onMessage` receives what the route's server
|
|
2681
2707
|
* handler sent (via its `socket.send`/`socket.broadcast`), never the sender's
|
|
2682
2708
|
* own raw frame — the handler is authoritative. Returns a handle with `send`
|
|
@@ -2696,8 +2722,9 @@ declare class LunoraClient {
|
|
|
2696
2722
|
/**
|
|
2697
2723
|
* Subscribe to token-expiry events: invoked whenever the server drops a
|
|
2698
2724
|
* shard socket because the connection's credential lapsed (close code
|
|
2699
|
-
* `4001`)
|
|
2700
|
-
*
|
|
2725
|
+
* `4001`) or the server refused the session credential (close code `4003`,
|
|
2726
|
+
* notified once per credential). The client already reconnects automatically
|
|
2727
|
+
* (re-resolving identity from the cookie/token in effect); use this to refresh a
|
|
2701
2728
|
* short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
|
|
2702
2729
|
* with a freshly minted one. Returns an unsubscribe function.
|
|
2703
2730
|
*
|
|
@@ -3136,10 +3163,10 @@ declare class LunoraClient {
|
|
|
3136
3163
|
* Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
|
|
3137
3164
|
* WebSocket. `onJobs` fires with the full list on connect and on every
|
|
3138
3165
|
* change (schedule / cancel / alarm-fire). Reconnects with the client's
|
|
3139
|
-
* configured backoff. Requires `
|
|
3140
|
-
* (the browser can't send an `Authorization` header on a WS) —
|
|
3141
|
-
*
|
|
3142
|
-
*
|
|
3166
|
+
* configured backoff. Requires `wsTicket` to be set to an admin credential
|
|
3167
|
+
* (the browser can't send an `Authorization` header on a WS) — a
|
|
3168
|
+
* {@link WsTokenProvider} minting the ephemeral sub-token, so the master
|
|
3169
|
+
* credential stays out of the URL. Returns an
|
|
3143
3170
|
* unsubscribe function that closes the socket and stops reconnecting.
|
|
3144
3171
|
*/
|
|
3145
3172
|
subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
|
|
@@ -4193,8 +4220,8 @@ declare class LunoraClient {
|
|
|
4193
4220
|
* admin socket and {@link connectWebSocket}'s `defineWebSocket` route — and
|
|
4194
4221
|
* they must share it rather than each hand-roll it: the connect-timeout +
|
|
4195
4222
|
* heartbeat/watchdog/identity-guard live in `openManagedSocket`, the backoff
|
|
4196
|
-
* policy in `createReconnect`, and reading `
|
|
4197
|
-
* lets a post-connect `
|
|
4223
|
+
* policy in `createReconnect`, and reading `wsTicket` at connect time is what
|
|
4224
|
+
* lets a post-connect `setWsTicket()` rotation be picked up on the next
|
|
4198
4225
|
* reconnect attempt instead of looping with a stale token. Registered on
|
|
4199
4226
|
* {@link adminSocketTeardowns} so `close()` stops it too.
|
|
4200
4227
|
*
|
|
@@ -4263,16 +4290,24 @@ declare class LunoraClient {
|
|
|
4263
4290
|
*/
|
|
4264
4291
|
private resendShapeSubscriptions;
|
|
4265
4292
|
private ensureSocket;
|
|
4293
|
+
/** Supersede any in-flight credential mint, drop held sends, and bounce the shard sockets onto the new credentials. */
|
|
4294
|
+
private applyWsCredentialChange;
|
|
4295
|
+
/**
|
|
4296
|
+
* Open the shard socket now when both credentials are static, or after
|
|
4297
|
+
* resolving whichever is a {@link WsTokenProvider}. An async function runs
|
|
4298
|
+
* synchronously up to its first `await`, so the static path stays synchronous.
|
|
4299
|
+
*/
|
|
4300
|
+
private startShardSocket;
|
|
4266
4301
|
/**
|
|
4267
|
-
* Resolve
|
|
4268
|
-
* minted
|
|
4269
|
-
* async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
|
|
4302
|
+
* Resolve each {@link WsTokenProvider} and open the shard socket with the
|
|
4303
|
+
* minted credentials. The connection is already in the `connecting` state, so the
|
|
4304
|
+
* async gap is race-guarded: a client `close()`, a `setWsToken` / `setWsTicket` bounce, or a
|
|
4270
4305
|
* competing connect that landed first all abandon this attempt. A provider
|
|
4271
4306
|
* failure fails the attempt through {@link handleDisconnect}, which arms the
|
|
4272
4307
|
* normal reconnect backoff — a broken mint endpoint degrades to retries, not
|
|
4273
4308
|
* a silent tokenless socket the admin gate would reject.
|
|
4274
4309
|
*/
|
|
4275
|
-
private
|
|
4310
|
+
private openSocketWithProvidedCredentials;
|
|
4276
4311
|
/** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
|
|
4277
4312
|
private openSocket;
|
|
4278
4313
|
/**
|
|
@@ -4654,9 +4689,9 @@ declare class LunoraClient {
|
|
|
4654
4689
|
* since changed hands, and is still delivering that user's rows: the
|
|
4655
4690
|
* session it belongs to is retired, which replaces the socket.
|
|
4656
4691
|
*
|
|
4657
|
-
* Ignored for a socket that authenticated with a token rather
|
|
4658
|
-
* cookie (see `ShardConnection.identityQuestion`) — its answer is about
|
|
4659
|
-
*
|
|
4692
|
+
* Ignored for a socket that authenticated with a ticket or an auth token rather
|
|
4693
|
+
* than the cookie (see `ShardConnection.identityQuestion`) — its answer is about
|
|
4694
|
+
* that credential, not about the cookie session this client's identity tracks.
|
|
4660
4695
|
*/
|
|
4661
4696
|
private handleIdentityFrame;
|
|
4662
4697
|
/**
|
package/dist/packem_shared/{lunora-client.d-XR8Gbgd_.d.mts → lunora-client.d-mAuddnZ9.d.mts}
RENAMED
|
@@ -368,12 +368,11 @@ interface QueryCacheAdapter {
|
|
|
368
368
|
remove: (key: string) => Promise<void>;
|
|
369
369
|
}
|
|
370
370
|
/**
|
|
371
|
-
* Resolves
|
|
372
|
-
*
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
* connect attempt, and the client retries with its normal reconnect backoff.
|
|
371
|
+
* Resolves a WebSocket credential (`wsToken` or `wsTicket`) fresh at every
|
|
372
|
+
* (re)connect, so a short-lived credential is re-minted rather than held.
|
|
373
|
+
* May return the value synchronously or as a Promise; returning `undefined`
|
|
374
|
+
* connects without one. A thrown error / rejected Promise fails that connect
|
|
375
|
+
* attempt, and the client retries with its normal reconnect backoff.
|
|
377
376
|
*/
|
|
378
377
|
type WsTokenProvider = () => Promise<string | undefined> | string | undefined;
|
|
379
378
|
interface LunoraClientOptions {
|
|
@@ -554,19 +553,24 @@ interface LunoraClientOptions {
|
|
|
554
553
|
url: string;
|
|
555
554
|
WebSocket?: typeof WebSocket;
|
|
556
555
|
/**
|
|
557
|
-
*
|
|
558
|
-
*
|
|
559
|
-
* `
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
* server logs and history, so prefer a short-lived rotating token in
|
|
563
|
-
* production over a static secret.
|
|
556
|
+
* The short-lived ticket appended to the WebSocket URL as `?token=…`. Only
|
|
557
|
+
* an ephemeral admin sub-token belongs here, minted by
|
|
558
|
+
* `POST /_lunora/admin/ws-token`; the server authorizes `__lunora_admin__:*`
|
|
559
|
+
* subscriptions from it. A ticket lapses after its TTL, so a static master
|
|
560
|
+
* token must never be used here: the server refuses it in the URL.
|
|
564
561
|
*
|
|
565
|
-
* Pass a {@link WsTokenProvider}
|
|
566
|
-
*
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
562
|
+
* Pass a {@link WsTokenProvider} to re-mint on every (re)connect, including
|
|
563
|
+
* the one that follows a lapsed ticket.
|
|
564
|
+
*/
|
|
565
|
+
wsTicket?: string | WsTokenProvider;
|
|
566
|
+
/**
|
|
567
|
+
* The session credential. It is sent in the `connect` frame of every shard
|
|
568
|
+
* socket and never in the WebSocket URL, because a URL is logged by every
|
|
569
|
+
* proxy and edge on the way (protocol §6). The server matches it against
|
|
570
|
+
* `LUNORA_WS_BEARER`; a socket that does not present a match is closed.
|
|
571
|
+
*
|
|
572
|
+
* Pass a {@link WsTokenProvider} to resolve it fresh at every (re)connect, so
|
|
573
|
+
* a rotated session is picked up on the next connect.
|
|
570
574
|
*/
|
|
571
575
|
wsToken?: string | WsTokenProvider;
|
|
572
576
|
wsUrl?: string;
|
|
@@ -663,6 +667,12 @@ interface ClientConnectMessage {
|
|
|
663
667
|
clientId?: string;
|
|
664
668
|
context?: Record<string, unknown>;
|
|
665
669
|
id: string;
|
|
670
|
+
/**
|
|
671
|
+
* The session credential (protocol §6). A gated server checks it against
|
|
672
|
+
* `LUNORA_WS_BEARER`. Set from the client's `wsToken` and never placed in the
|
|
673
|
+
* socket URL.
|
|
674
|
+
*/
|
|
675
|
+
token?: string;
|
|
666
676
|
type: "connect";
|
|
667
677
|
}
|
|
668
678
|
/**
|
|
@@ -1877,9 +1887,14 @@ declare class LunoraClient {
|
|
|
1877
1887
|
private readonly adminHost;
|
|
1878
1888
|
/** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
|
|
1879
1889
|
private readonly clientQueryStore;
|
|
1890
|
+
/** The session credential, sent in the `connect` frame and never in the URL (protocol §6). */
|
|
1880
1891
|
private wsToken;
|
|
1881
|
-
/**
|
|
1882
|
-
private
|
|
1892
|
+
/** The short-lived ticket appended to the upgrade URL as `?token=` (protocol §6). */
|
|
1893
|
+
private wsTicket;
|
|
1894
|
+
/** Bumped on every `setWsToken` / `setWsTicket` change: a provider request started under an older value is superseded. */
|
|
1895
|
+
private wsCredentialGeneration;
|
|
1896
|
+
/** The credential generation the server last refused with 4003, so that refusal notifies once. */
|
|
1897
|
+
private refusedCredentialGeneration;
|
|
1883
1898
|
/** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
|
|
1884
1899
|
private readonly authBasePath;
|
|
1885
1900
|
private readonly fetchImpl;
|
|
@@ -2294,8 +2309,8 @@ declare class LunoraClient {
|
|
|
2294
2309
|
* {@link replayIdentityVerdict} — so a refresh can't replay them and an
|
|
2295
2310
|
* account switch can't replay the previous user's writes as the new one.
|
|
2296
2311
|
*
|
|
2297
|
-
* Does NOT update the WebSocket auth —
|
|
2298
|
-
*
|
|
2312
|
+
* Does NOT update the WebSocket auth — a socket keeps the session credential
|
|
2313
|
+
* it connected with for its life. To refresh live WS auth, call
|
|
2299
2314
|
* {@link setWsToken} explicitly, which closes existing shard sockets to
|
|
2300
2315
|
* force a reconnect with the new credential.
|
|
2301
2316
|
*/
|
|
@@ -2491,15 +2506,23 @@ declare class LunoraClient {
|
|
|
2491
2506
|
*/
|
|
2492
2507
|
getCurrentUser(): Promise<User | null>;
|
|
2493
2508
|
/**
|
|
2494
|
-
* Replace the
|
|
2495
|
-
* every open shard socket so the reconnect
|
|
2496
|
-
*
|
|
2497
|
-
* in
|
|
2498
|
-
* {@link WsTokenProvider} resolved fresh at every (re)connect
|
|
2499
|
-
* for
|
|
2500
|
-
* Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
|
|
2509
|
+
* Replace the session credential sent in the `connect` frame, and close
|
|
2510
|
+
* every open shard socket so the reconnect presents the new value. The
|
|
2511
|
+
* credential never rides the WebSocket URL. Call this when the user's session
|
|
2512
|
+
* changes (sign-in, sign-out, switching workspaces). Accepts a static string
|
|
2513
|
+
* or a {@link WsTokenProvider} resolved fresh at every (re)connect. Bearer
|
|
2514
|
+
* tokens for HTTP RPC are independent — see {@link setAuthToken}.
|
|
2501
2515
|
*/
|
|
2502
2516
|
setWsToken(token: string | undefined | WsTokenProvider): void;
|
|
2517
|
+
/**
|
|
2518
|
+
* Replace the short-lived ticket appended to WS upgrade URLs as `?token=…`,
|
|
2519
|
+
* and close every open shard socket so the reconnect picks up the new value.
|
|
2520
|
+
* Only an ephemeral admin sub-token belongs here (minted by
|
|
2521
|
+
* `POST /_lunora/admin/ws-token`): a URL is logged by every proxy on the way,
|
|
2522
|
+
* so a session credential never goes here — see {@link setWsToken}. Accepts a
|
|
2523
|
+
* static string or a {@link WsTokenProvider} resolved fresh at every (re)connect.
|
|
2524
|
+
*/
|
|
2525
|
+
setWsTicket(ticket: string | undefined | WsTokenProvider): void;
|
|
2503
2526
|
/**
|
|
2504
2527
|
* Register (or clear, with `undefined`) the app context sent in the `connect`
|
|
2505
2528
|
* envelope for a shard's socket, overriding the client-wide
|
|
@@ -2671,12 +2694,15 @@ declare class LunoraClient {
|
|
|
2671
2694
|
* chat.close();
|
|
2672
2695
|
* ```
|
|
2673
2696
|
*
|
|
2674
|
-
* The socket carries the browser's session cookie,
|
|
2675
|
-
*
|
|
2676
|
-
* the server refuses a socket with no verified session. The `wsToken`
|
|
2677
|
-
*
|
|
2678
|
-
*
|
|
2679
|
-
*
|
|
2697
|
+
* The socket carries the browser's session cookie, or an `Authorization` header
|
|
2698
|
+
* where the client can set one, and either establishes a user. A route declared `auth: true` on
|
|
2699
|
+
* the server refuses a socket with no verified session. The `wsToken` is
|
|
2700
|
+
* sent only on shard sockets, in their first `connect` frame; a route socket
|
|
2701
|
+
* has no `connect` frame, so `wsToken` does not authenticate it. The `wsTicket`
|
|
2702
|
+
* (`?token=`, see {@link setWsTicket}) is an ephemeral admin credential
|
|
2703
|
+
* appended to the URL, and it does not sign a user in to a route, so a
|
|
2704
|
+
* private route needs a verified session from the cookie or an `Authorization`
|
|
2705
|
+
* header. Reconnects with the
|
|
2680
2706
|
* client's configured backoff. `onMessage` receives what the route's server
|
|
2681
2707
|
* handler sent (via its `socket.send`/`socket.broadcast`), never the sender's
|
|
2682
2708
|
* own raw frame — the handler is authoritative. Returns a handle with `send`
|
|
@@ -2696,8 +2722,9 @@ declare class LunoraClient {
|
|
|
2696
2722
|
/**
|
|
2697
2723
|
* Subscribe to token-expiry events: invoked whenever the server drops a
|
|
2698
2724
|
* shard socket because the connection's credential lapsed (close code
|
|
2699
|
-
* `4001`)
|
|
2700
|
-
*
|
|
2725
|
+
* `4001`) or the server refused the session credential (close code `4003`,
|
|
2726
|
+
* notified once per credential). The client already reconnects automatically
|
|
2727
|
+
* (re-resolving identity from the cookie/token in effect); use this to refresh a
|
|
2701
2728
|
* short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
|
|
2702
2729
|
* with a freshly minted one. Returns an unsubscribe function.
|
|
2703
2730
|
*
|
|
@@ -3136,10 +3163,10 @@ declare class LunoraClient {
|
|
|
3136
3163
|
* Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
|
|
3137
3164
|
* WebSocket. `onJobs` fires with the full list on connect and on every
|
|
3138
3165
|
* change (schedule / cancel / alarm-fire). Reconnects with the client's
|
|
3139
|
-
* configured backoff. Requires `
|
|
3140
|
-
* (the browser can't send an `Authorization` header on a WS) —
|
|
3141
|
-
*
|
|
3142
|
-
*
|
|
3166
|
+
* configured backoff. Requires `wsTicket` to be set to an admin credential
|
|
3167
|
+
* (the browser can't send an `Authorization` header on a WS) — a
|
|
3168
|
+
* {@link WsTokenProvider} minting the ephemeral sub-token, so the master
|
|
3169
|
+
* credential stays out of the URL. Returns an
|
|
3143
3170
|
* unsubscribe function that closes the socket and stops reconnecting.
|
|
3144
3171
|
*/
|
|
3145
3172
|
subscribeScheduledJobs(onJobs: (jobs: ScheduleRecord[]) => void): Unsubscribe;
|
|
@@ -4193,8 +4220,8 @@ declare class LunoraClient {
|
|
|
4193
4220
|
* admin socket and {@link connectWebSocket}'s `defineWebSocket` route — and
|
|
4194
4221
|
* they must share it rather than each hand-roll it: the connect-timeout +
|
|
4195
4222
|
* heartbeat/watchdog/identity-guard live in `openManagedSocket`, the backoff
|
|
4196
|
-
* policy in `createReconnect`, and reading `
|
|
4197
|
-
* lets a post-connect `
|
|
4223
|
+
* policy in `createReconnect`, and reading `wsTicket` at connect time is what
|
|
4224
|
+
* lets a post-connect `setWsTicket()` rotation be picked up on the next
|
|
4198
4225
|
* reconnect attempt instead of looping with a stale token. Registered on
|
|
4199
4226
|
* {@link adminSocketTeardowns} so `close()` stops it too.
|
|
4200
4227
|
*
|
|
@@ -4263,16 +4290,24 @@ declare class LunoraClient {
|
|
|
4263
4290
|
*/
|
|
4264
4291
|
private resendShapeSubscriptions;
|
|
4265
4292
|
private ensureSocket;
|
|
4293
|
+
/** Supersede any in-flight credential mint, drop held sends, and bounce the shard sockets onto the new credentials. */
|
|
4294
|
+
private applyWsCredentialChange;
|
|
4295
|
+
/**
|
|
4296
|
+
* Open the shard socket now when both credentials are static, or after
|
|
4297
|
+
* resolving whichever is a {@link WsTokenProvider}. An async function runs
|
|
4298
|
+
* synchronously up to its first `await`, so the static path stays synchronous.
|
|
4299
|
+
*/
|
|
4300
|
+
private startShardSocket;
|
|
4266
4301
|
/**
|
|
4267
|
-
* Resolve
|
|
4268
|
-
* minted
|
|
4269
|
-
* async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
|
|
4302
|
+
* Resolve each {@link WsTokenProvider} and open the shard socket with the
|
|
4303
|
+
* minted credentials. The connection is already in the `connecting` state, so the
|
|
4304
|
+
* async gap is race-guarded: a client `close()`, a `setWsToken` / `setWsTicket` bounce, or a
|
|
4270
4305
|
* competing connect that landed first all abandon this attempt. A provider
|
|
4271
4306
|
* failure fails the attempt through {@link handleDisconnect}, which arms the
|
|
4272
4307
|
* normal reconnect backoff — a broken mint endpoint degrades to retries, not
|
|
4273
4308
|
* a silent tokenless socket the admin gate would reject.
|
|
4274
4309
|
*/
|
|
4275
|
-
private
|
|
4310
|
+
private openSocketWithProvidedCredentials;
|
|
4276
4311
|
/** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
|
|
4277
4312
|
private openSocket;
|
|
4278
4313
|
/**
|
|
@@ -4654,9 +4689,9 @@ declare class LunoraClient {
|
|
|
4654
4689
|
* since changed hands, and is still delivering that user's rows: the
|
|
4655
4690
|
* session it belongs to is retired, which replaces the socket.
|
|
4656
4691
|
*
|
|
4657
|
-
* Ignored for a socket that authenticated with a token rather
|
|
4658
|
-
* cookie (see `ShardConnection.identityQuestion`) — its answer is about
|
|
4659
|
-
*
|
|
4692
|
+
* Ignored for a socket that authenticated with a ticket or an auth token rather
|
|
4693
|
+
* than the cookie (see `ShardConnection.identityQuestion`) — its answer is about
|
|
4694
|
+
* that credential, not about the cookie session this client's identity tracks.
|
|
4660
4695
|
*/
|
|
4661
4696
|
private handleIdentityFrame;
|
|
4662
4697
|
/**
|
|
@@ -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-mAuddnZ9.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
|
|
@@ -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-Pvj-sj8S.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
|
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-mAuddnZ9.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-mAuddnZ9.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-Pvj-sj8S.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-Pvj-sj8S.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/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-mAuddnZ9.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-C3a5W5-O.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-Pvj-sj8S.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-DxVQwugq.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-CyFK_cv6.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-CyFK_cv6.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-CmZmYeQK.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{LunoraError as y}from"@lunora/errors";import{encodeWire as x,decodeWire as w,stableWireKey as ce}from"@lunora/wire";import{r as We,U as xe,P as Be}from"./delta-merge-Ls3DED4g.mjs";import{w as v,b as ne,j as C,d as de,p as ue,s as he}from"./client-urls-BHLUjjcG.mjs";import Qe from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as X,a as qe,e as B,r as le,b as fe,c as Ke,d as pe,u as Ge}from"./wire-errors-u1qRPmDJ.mjs";import{ClientQueryStore as je}from"./createClientQuery-B8Nfj-7o.mjs";import{D as $e,a as Ve,b as ze,c as Je,d as Ye,S as me,M as Xe,I as Ze,Q as et,R as tt,e as st,f as it,g as nt}from"./client-tuning-C10B2KCO.mjs";import{TabCoordinator as rt}from"./TabCoordinator-DBuR7Dwv.mjs";import{TransportError as U,getRetryAfterMs as ot,AUTH_REPLAY_ERROR_CODES as at,isAuthReplayFailure as Q}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as ct}from"./httpStream-B9iENFKq.mjs";import{d as Z,r as M,a as F,b as dt,c as ut,e as ht,f as lt}from"./local-store-fqWV2n_Z.mjs";import{O as ft,n as ye,i as pt}from"./offline-queue-Dt_um8sR.mjs";import{resolvePersistenceAdapter as mt}from"./createInMemoryPersistence-BfgXApi_.mjs";import{w as W,a as Se,b as yt}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as St,queryCacheKey as L}from"./createInMemoryQueryCache-B5wX-gTy.mjs";import{createReconnect as be}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as I,SubscriptionRegistry as A,wrapSubscriber as j}from"./SubscriptionRegistry-DKIXE7M7.mjs";import bt from"./createSnapshotPrecondition-CLkxVeN1.mjs";import{createStream as vt}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const $=500,Ae=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)},_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",gt=n=>{let e="",t=0;const s=n.length-2;for(;t<s;t+=3){const r=n[t]<<16|n[t+1]<<8|n[t+2];e+=_.charAt(r>>18&63)+_.charAt(r>>12&63)+_.charAt(r>>6&63)+_.charAt(r&63)}const i=n.length-t;if(i===1){const r=n[t]<<16;e+=_.charAt(r>>18&63)+_.charAt(r>>12&63)}else if(i===2){const r=n[t]<<16|n[t+1]<<8;e+=_.charAt(r>>18&63)+_.charAt(r>>12&63)+_.charAt(r>>6&63)}return e};new TextDecoder;const Tt=new TextEncoder,kt=n=>gt(Tt.encode(JSON.stringify(n))),wt="x-lunora-expect-subject",Ct=n=>kt({subject:n}),ve=Symbol.for("lunora:session-change"),Et="lunora:session-change",At="better-auth.message",_t="signout",_e=()=>{const n=globalThis;let e=n[ve];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[ve]=e),e},It=()=>"document"in globalThis,Ot=async()=>{const n=[];for(const e of _e().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},Rt=(n,e)=>{if(n!==At||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===_t}catch{return!1}},Pt=n=>{const e=[],t=()=>{Ot().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(Et):void 0}catch{s=void 0}if(s!==void 0){const r=s;r.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==n&&t()}),e.push(()=>{r.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const r=o=>{Rt(o.key,o.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},Ft=n=>{const e=_e();return e.listeners.add(n),e.detach===void 0&&It()&&(e.detach=Pt(e.tab)),()=>{e.listeners.delete(n),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},Lt="/_lunora/rpc",V="/_lunora/rpc-batch",z="/_lunora/ws",Mt="/_lunora/admin/shard-traffic",Ht="/_lunora/admin/scheduled",Ut="/_lunora/admin/scheduled/status",Nt="/_lunora/admin/scheduled/ws",Dt="/_lunora/admin/scheduled/cancel",ge="/_lunora/admin/scheduled/dead",Wt="/_lunora/admin/scheduled/dead/retry",xt="/_lunora/admin/scheduled/dead/cancel",Bt="/_lunora/admin/workflows/instances",Qt="/_lunora/admin/workflows/instance",qt="/_lunora/admin/workflows/status",re="/_lunora/admin/storage",Kt="/_lunora/admin/storage/url",Gt="/_lunora/admin/storage/buckets",jt="/_lunora/admin/functions",$t="/_lunora/admin/cron-jobs",Vt="/_lunora/admin/cron-jobs/run",zt="/_lunora/admin/architecture",Jt="/_lunora/admin/openapi",Yt="/_lunora/admin/openrpc",Xt="/_lunora/admin/global/tables",Zt="/_lunora/admin/global/table",es="/_lunora/admin/global/facet",ts="/_lunora/admin/vector/indexes",ss="/_lunora/admin/vector/query",is="/_lunora/admin/logs/archive",ns="/_lunora/admin/kv/namespaces",rs="/_lunora/admin/kv/keys",oe="/_lunora/admin/kv/value",os="/_lunora/admin/auth/users",as="/_lunora/admin/auth/sessions",cs="/_lunora/admin/auth/users/create",ds="/_lunora/admin/auth/users/role",us="/_lunora/admin/auth/users/ban",hs="/_lunora/admin/auth/users/unban",ls="/_lunora/admin/auth/users/password",fs="/_lunora/admin/auth/users/remove",ps="/_lunora/admin/auth/users/impersonate",ms="/_lunora/admin/auth/sessions/revoke",ys="/_lunora/admin/auth/sessions/revoke-all",Ss="/_lunora/admin/auth/capabilities",bs="/_lunora/admin/auth/users/update",vs="/_lunora/admin/auth/accounts",gs="/_lunora/admin/auth/accounts/unlink",Ts="/_lunora/admin/auth/passkeys",ks="/_lunora/admin/auth/passkeys/delete",ws="/_lunora/admin/auth/two-factor/disable",Cs="/_lunora/admin/auth/organizations",Es="/_lunora/admin/auth/organizations/members",As="/_lunora/admin/auth/organizations/invitations",_s="/_lunora/admin/auth/organizations/members/remove",Is="/_lunora/admin/auth/organizations/invitations/cancel",Os="/_lunora/admin/auth/config",Rs="/_lunora/admin/auth/sign-up-invitations",Ps="/_lunora/admin/auth/sign-up-invitations/create",Fs="/_lunora/admin/auth/sign-up-invitations/revoke",Ls="/_lunora/admin/auth/organizations/create",Ms="/_lunora/admin/auth/organizations/update",Hs="/_lunora/admin/auth/organizations/remove",Us="/_lunora/admin/auth/organizations/members/add",Ns="/_lunora/admin/auth/organizations/members/invite",Ds="/_lunora/admin/auth/organizations/members/role",Ws="/_lunora/admin/auth/organizations/teams",xs="/_lunora/admin/auth/organizations/teams/create",Bs="/_lunora/admin/auth/organizations/teams/update",Qs="/_lunora/admin/auth/organizations/teams/remove",qs="/_lunora/admin/auth/organizations/teams/members",Ks="/_lunora/admin/auth/organizations/teams/members/add",Gs="/_lunora/admin/auth/organizations/teams/members/remove",js="/_lunora/admin/auth/organizations/roles",$s="/_lunora/admin/auth/organizations/roles/create",Vs="/_lunora/admin/auth/organizations/roles/update",zs="/_lunora/admin/auth/organizations/roles/remove",Js="/api/auth",Ys="/get-session",Xs="lunora-ping",Zs=async n=>(n.assertOpen(),(await n.adminFetch(jt,"GET")).functions??[]),ei=async n=>(n.assertOpen(),(await n.adminFetch($t,"GET")).jobs??[]),ti=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(Vt,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},si=async n=>(n.assertOpen(),await n.adminFetch(Jt,"GET")),ii=async n=>(n.assertOpen(),await n.adminFetch(zt,"GET")),ni=async n=>(n.assertOpen(),await n.adminFetch(Yt,"GET")),ri=async n=>(n.assertOpen(),await n.adminFetch(Xt,"GET")),oi=async(n,e)=>{n.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(x(e.filters))),w(await n.adminFetch(`${Zt}?${t.toString()}`,"GET"))},ai=async(n,e)=>{n.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(x(e.filters))),w(await n.adminFetch(`${es}?${t.toString()}`,"GET"))},ci=async n=>(n.assertOpen(),(await n.adminFetch(ns,"GET")).namespaces??[]),di=async(n,e)=>{n.assertOpen();const t=v(rs,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await n.adminFetch(t,"GET")},ui=async(n,e)=>{n.assertOpen();const t=v(oe,{key:e.key,namespace:e.namespace});return await n.adminFetch(t,"GET")},hi=async(n,e)=>{n.assertOpen(),await n.adminFetch(oe,"PUT",e)},li=async(n,e)=>{n.assertOpen();const t=v(oe,{key:e.key,namespace:e.namespace});await n.adminFetch(t,"DELETE")},fi=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(Mt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},pi=async(n,e={})=>{n.assertOpen();const t=await n.adminFetch(is,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},mi=async n=>{const e=[];let t;for(;;){const s=await n(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}},ae=n=>"args"in n?{...n,args:w(n.args)}:n,yi=async n=>(n.assertOpen(),((await n.adminFetch(Ht,"GET")).records??[]).map(t=>ae(t))),Si=async n=>{n.assertOpen();const e=await n.adminFetch(Ut,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},bi=async(n,e)=>(n.assertOpen(),{cancelled:(await n.adminFetch(Dt,"POST",{id:e})).cancelled===!0}),vi=async n=>(n.assertOpen(),(await mi(async t=>await n.adminFetch(t===void 0?ge:`${ge}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>ae(t))),gi=async(n,e)=>(n.assertOpen(),{retried:(await n.adminFetch(Wt,"POST",{id:e})).retried===!0}),Ti=async(n,e)=>(n.assertOpen(),{removed:(await n.adminFetch(xt,"POST",{id:e})).removed===!0}),ki=async(n,e)=>{n.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 n.adminFetch(`${Bt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},wi=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await n.adminFetch(`${Qt}?${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??[]}},Ci=async(n,e)=>(n.assertOpen(),{status:(await n.adminFetch(qt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),Ei=async(n,e={})=>{n.assertOpen();const t=v(re,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await n.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},Ai=async(n,e,t)=>{n.assertOpen();const s=`${re}?key=${encodeURIComponent(e)}${ne(t?.bucket)}`,i=await n.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},_i=async n=>(n.assertOpen(),(await n.adminFetch(Gt,"GET")).buckets??[]),Ii=async(n,e)=>{n.assertOpen();const t=`${re}?key=${encodeURIComponent(e.key)}${ne(e.bucket)}`,s=await n.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},Oi=async(n,e,t)=>{n.assertOpen();const s=t?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,r=`${Kt}?key=${encodeURIComponent(e)}${i}${ne(t?.bucket)}`,o=await n.adminFetch(r,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},Ri=async n=>(n.assertOpen(),(await n.adminFetch(ts,"GET")).indexes??[]),Pi=async(n,e)=>(n.assertOpen(),(await n.adminFetch(ss,"POST",e)).matches??[]),E=(n,e)=>{try{return x(n)}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)}},ee=n=>{try{return x(n),!0}catch{return!1}},Ie=n=>n!==null&&typeof n=="object"&&("error"in n||"result"in n),Fi=(n,e)=>{const t=Array.from({length:e});for(const s of n){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!Ie(s.body)){t[s.id]={error:X({}),ok:!1};continue}const i=s.body;t[s.id]="error"in i?{error:X(i),ok:!1}:{ok:!0,value:w(i.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},J=(n,e)=>e!==null?{}:n===null?{expectSubject:null}:n?.startsWith("subj:")===!0?{expectSubject:n.slice(5)}:{},q=n=>n==="connected"||n==="polling",l=n=>n??"",k=(n,e)=>{if(!n.socket||n.wsState!=="open")return!1;try{return n.socket.send(JSON.stringify(e)),!0}catch{return!1}},Li=n=>{if(!n.pendingStreams||n.pendingStreams.length===0)return;const e=n.pendingStreams;n.pendingStreams=[];for(const t of e)k(n,t)},Mi=new TextDecoder,Hi=n=>{if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return Mi.decode(n)};class R{listeners=new Set;get size(){return this.listeners.size}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 H=n=>{n.heartbeatTimer!==void 0&&(clearInterval(n.heartbeatTimer),n.heartbeatTimer=void 0)},Ui=(n,e,t)=>{H(n),!(e<=0)&&(n.heartbeatTimer=setInterval(()=>{if(!n.socket)return;const{socket:s}=n;if(Date.now()-n.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Xs)}catch{}},e))},Te=(n,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:o}=t;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const a=new i(e);n.socket=a;const c=()=>{H(n),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.socket===a&&(n.socket=void 0)},u=d=>{c(),s.onClose(d)};r>0&&(n.connectTimer=setTimeout(()=>{if(n.connectTimer=void 0,n.socket===a){try{a.close()}catch{}u()}},r)),a.addEventListener("open",()=>{if(n.socket===a){n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.lastFrameAt=Date.now();try{s.onOpen?.()}catch(d){console.error("[lunora] connection open handler threw",d)}n.socket===a&&Ui(n,o,u)}}),a.addEventListener("message",d=>{if(n.socket===a){n.lastFrameAt=Date.now();try{s.onMessage(d)}catch(h){console.error("[lunora] server frame handler threw",h)}}}),a.addEventListener("close",d=>{n.socket===a&&u(d)}),a.addEventListener("error",()=>{n.socket===a&&u()})},Ni=n=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=n,o=t>0&&e>0;let a=0,c,u=!1,d=!1;const h=()=>{c!==void 0&&(clearInterval(c),c=void 0,u=!1,i())},p=m=>{if(c!==void 0){if(!m){h();return}u||(u=!0,i()),s()}},f=()=>{d||(d=!0,r().then(p).finally(()=>{d=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&u,noteFailedOpen:()=>{a+=1,!(!o||c!==void 0||a<e)&&(c=setInterval(f,t),i(),f())},noteOpen:()=>{a=0,h()},stop:h}},Di=1e4,ke=async n=>W(Di,void 0,n,()=>new TypeError("LunoraClient: poll timed out")),Oe=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),we=n=>{if(n instanceof U)return!0;const e=n?.code;return e===void 0||Oe.has(e)||at.has(e)},Wi=1e3,Re=6e4,xi={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},D=(n,e,t)=>{const s=qe(t),i=s===void 0?void 0:{retryAfterMs:s},r=`LunoraClient: response carried no error envelope (status ${n.toString()}${e?` ${e}`:""})`;return n<400||n>=500||n===408?new U(r,i):new y(xi[n]??"BAD_REQUEST",r,{data:i})},te=(n,e=Math.random)=>{const t=Math.min(Wi*2**Math.max(n-1,0),Re);return Math.round(t*(.5+e()*.5))},Bi=n=>{const e=n?.code;return n instanceof U||e===void 0||Oe.has(e)},Qi=(n,e,t)=>{const s=ot(n);return s!==void 0&&s>0?Math.min(s,Re):Bi(n)?te(e,t):void 0},qi=983040,Ki=n=>typeof TextEncoder>"u"?n.length:new TextEncoder().encode(n).length,Pe=new WeakSet,Fe=n=>{const e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${n instanceof Error?n.message:String(n)}`,{cause:n});return Pe.add(e),e},K=n=>n instanceof Error&&Pe.has(n),Gi=n=>{const e=new Map;for(const t of n)typeof t.id=="number"&&Ie(t.body)&&e.set(t.id,t.body);return e},ji=n=>{if(n===void 0)return{kind:"unanswered"};if("error"in n)return{error:X(n),kind:"errored"};try{return{commitCursor:n.commitCursor,kind:"committed",value:w(n.result)}}catch(e){return{commitCursor:n.commitCursor,error:Fe(e),kind:"undecodable"}}},Y=(n,e)=>`${l(n)}\0${e}`,$i=(n,e)=>{for(const t of e)t.op==="delete"?n.delete(t.key):t.value!==void 0&&n.set(t.key,t.value)};class Vi{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Ae(this.buffers,this.maxBuffers),this.buffers.set(Y(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(Y(e,t.pokeId));if(!s)return;const i=[];try{for(const a of t.rowsPatch)i.push(a.value===void 0?a:{...a,value:w(a.value)})}catch(a){s.undecodable.set(t.shapeId,a);return}const r=s.parts.get(t.shapeId)??[];for(const a of i)r.push(a);s.parts.set(t.shapeId,r),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const o=t.baseCheckpoint??s.baseCheckpoint;o!==void 0&&s.bases.set(t.shapeId,o),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=Y(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const zi=(n,e,t)=>{const s=e.parts.get(n.id)??[],i=e.resets.has(n.id),r=e.bases.get(n.id),o=e.epoch!==void 0&&n.serverEpoch!==void 0&&e.epoch!==n.serverEpoch,a=r!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r;if(!i&&(o||a))return n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,n.answered=!1,"reseed";i&&n.rows.clear(),$i(n.rows,s),n.answered=!0,t.checkpoint!==void 0&&(n.serverCursor=t.checkpoint),t.epoch!==void 0&&(n.serverEpoch=t.epoch);const c=e.lastMutationId.get(n.id);return c!==void 0&&(n.lastMutationId=c),"applied"},Ce=n=>{const e=[...n.rows.values()];for(const t of n.callbacks)try{t(e)}catch{}},Ji=(n,e)=>{for(const[t,s]of e.undecodable){const i=n.get(t);i&&I(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},se=(n,e)=>{n.lastMutationId=Math.max(n.lastMutationId??0,e)},ie=(n,e=!1)=>{for(const t of n.checkpointCallbacks)t({checkpoint:n.serverCursor,mutationId:n.lastMutationId,...e&&{rowsFollow:!0}})},Le=(n,e,t)=>{n.serverBase=e,t.cursor!==void 0&&(n.serverCursor=t.cursor),t.epoch!==void 0&&(n.serverEpoch=t.epoch)},Yi=(n,e)=>e.cursor!==void 0&&n.serverCursor!==void 0&&n.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===n.serverEpoch&&e.cursor<n.serverCursor,G=(n,e)=>n!==void 0&&n!==e,Xi=(n,e)=>e==="connected"&&n!=="connected"||e==="polling"&&n!=="connected"&&n!=="polling",Zi=n=>{for(const e of n.activeSubscriptions())e.valueReceived=!1,n.ensureSocket(e.shardKey),n.queueResubscribe(e);for(const e of n.activeShapes())e.answered=!1,n.ensureSocket(e.shardKey);for(const e of n.queuedShardKeys())n.ensureSocket(e);n.broadcastStatus(n.computeStatus(),n.identityFingerprint()),n.emitConnectionStatus()},en=n=>{n.closeConnections();const e=n.leader;e.status=void 0,e.wasEverConnected=!1;for(const t of n.activeSubscriptions())t.acked=!1,t.valueReceived=!1;for(const t of n.activeShapes())t.answered=!1;n.emitConnectionStatus()},tn=(n,e,t)=>{if(G(t,n.identityFingerprint()))return;const s=n.leader,i=Xi(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),n.emitConnectionStatus(),i&&n.flushOfflineQueues()},sn=n=>{n.isLeader()&&n.broadcastStatus(n.computeStatus(),n.identityFingerprint())},nn=(n,e,t,s,i,r)=>{if(G(r,n.identityFingerprint()))return;const o=n.subscription(e);if(!o)return;n.dropCacheSeed(e);const a=!o.valueReceived;o.valueReceived=!0,Le(o,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&Z(o,s),M(o,t),a&&n.emitConnectionStatus()},rn=(n,e,t,s)=>{if(G(s,n.identityFingerprint()))return;const i=n.subscription(e);if(i){const r=!i.valueReceived;i.valueReceived=!0,I(i.errorCallbacks,t),r&&n.emitConnectionStatus()}},on=(n,e,t,s,i,r,o)=>{if(G(o,n.identityFingerprint()))return;const a=n.subscription(e);a&&(n.ackAndAdvanceCursor(a,t,s),i!==void 0&&r===n.clientIdentifier()&&se(a,i),ie(a))},an=(n,e,t)=>n!==null||e&&t===null,cn=n=>n.sensitive===!0,dn=(n,e)=>{if(!cn(n))return e;if(e.onlineOnly===!1)throw new y("BAD_REQUEST",`'${n.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},un=[Be],hn=100,Me=1e4,ln=async(n,e,t,s)=>{const i=new AbortController,r=setTimeout(()=>{i.abort()},Me);try{const o=await n(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return await o.text(),o.status}finally{clearTimeout(r)}},Ee=(n,e)=>new y("OFFLINE_NOT_QUEUED",`'${n}' is online-only and the connection is not live, so it was not queued`,{cause:e}),fn=(n,e)=>n instanceof TypeError&&ee(e),pn=(n,e,t,s)=>e||n===!0&&t&&!s,mn=Promise.resolve();class He{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;wsTokenGeneration=0;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new A;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;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 R;statusListeners=new R;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new R;identityChangeListeners=new R;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new R;pendingChangeListeners=new R;syncStatusListeners=new R;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Vi(He.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??C(de(e.url),z),this.wsToken=e.wsToken;const t=e.authBasePath??Js;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??Qe(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??$e,this.connectTimeoutMs=e.connectTimeoutMs??Ve,this.rpcTimeoutMs=e.rpcTimeoutMs??ze,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Je,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Ye,this.defaultConnectionContext=e.connectionContext,this.persistence=mt(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=St(e.queryCache),this.clientQueryStore=new je,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=mn),this.offlineQueue=new ft(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onReplayingChange:()=>{this.emitSyncStatus()},onSizeChange:s=>{this.pendingChangeListeners.emit(s),this.emitSyncStatus()},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${ye()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=Ft(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,i=this.identityFingerprint(),r=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),a=this.isKnownNobody(),c=this.authToken;this.authToken=e,this.applySubject(e,t);const u=this.identityFingerprint();u!==i&&(!s&&e!==null&&r?(this.restampQueuedIdentity(i,u),this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):!s&&e===null&&i===null&&r&&!a?(this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(c,e),an(i,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),s&&this.authTokenListeners.emit(e),(u!==i||s||o)&&this.offlineQueue.size>0&&q(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 i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const r=s?.shardKey??"",o=this.identityFingerprint();let a,c,u;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:h=>{a=h}})}catch(h){if(!K(h))throw h;u=h}if(a!==void 0&&a>(this.clientWatermarks.get(o??"")?.get(r)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(Ae(this.clientWatermarks,nt),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(r,a)}if(u!==void 0)throw u;return{applied:a===void 0||a===i,result:c}}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 i=await this.fetchImpl(C(this.url,`${this.authBasePath}${Ys}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(t,null,s),null;const o=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,o,s),o}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.wsTokenGeneration+=1,this.resetRoomSends(),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),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),i={context:e},r=this.connectionContextHolders.get(s);r?r.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let o=!1;return()=>{if(o)return;o=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const i=l(s.shardKey);let r=this.whisperHandlers.get(i);r||(r=new Map,this.whisperHandlers.set(i,r));let o=r.get(e);const a=o===void 0;if(o||(o=new Set,r.set(e,o)),o.add(t),this.ensureSocket(s.shardKey),a){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,i,e)}return()=>{const c=this.whisperHandlers.get(i),u=c?.get(e);if(!u?.delete(t)||u.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const d=this.getConnection(s.shardKey);d&&k(d,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:i,stream:r,topic:o}=e;if(o.length===0)throw new y("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const a=`ws-live-${String(this.nextLiveSocketId)}`,c=l(i),u=`/live/${r}/control`;let h=this.whisperSubscribe(o,()=>{},{shardKey:i});const p=()=>{const S=h;h=void 0,S?.()};let f=this.liveSocketGrants.get(c);f===void 0&&(f=new Map,this.liveSocketGrants.set(c,f)),f.set(a,{onError:t,onEvent:s,release:p,stream:r,topic:o});const m=this.getConnection(i)?.connectionId;m!==void 0&&this.grantWhenJoined(i,a,m);let b=!1;return()=>{if(b)return;b=!0;const S=this.liveSocketGrants.get(c),O=S?.delete(a)===!0;S?.size===0&&this.liveSocketGrants.delete(c);const g=this.getConnection(i)?.connectionId;O&&g!==void 0&&this.postLiveControl(u,i,{action:"unsubscribe",connectionId:g,stream:r,subscriptionId:a,topic:o}),p()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,E(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const i=`room:${e.name}`,r=this.whisperSubscribe(i,p=>{t.onMessage(p)},s);let o=!1;const a=[],c=()=>{a.length=0},u=()=>{for(;a.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(i,a[0],s))return;a.shift()}},d=l(s.shardKey),h=this.roomFlushes.get(d)??new Set;return h.add(u),this.roomFlushes.set(d,h),this.roomIdentityResets.add(c),{close:()=>{o=!0,a.length=0,h.delete(u),h.size===0&&this.roomFlushes.delete(d),this.roomIdentityResets.delete(c),r()},send:p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;const f=E(p,`room message for '${i}'`),m=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return u(),a.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,m,s)?!0:a.length>=hn?!1:(a.push(m),!0)}}}connectWebSocket(e,t,s={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:()=>{},send:()=>{}};const i=a=>{try{a?.()}catch(c){console.error("[lunora] socket route handler threw",c)}};let r;const o=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:()=>{clearTimeout(r),i(t.onClose)},onMessage:a=>{let c;try{c=JSON.parse(typeof a.data=="string"?a.data:"")}catch{return}c.type==="message"&&(o.resetBackoff(),i(()=>{t.onMessage(w(c.data))}))},onOpen:()=>{clearTimeout(r);const a=o.socket();r=setTimeout(()=>{o.socket()===a&&o.resetBackoff()},me),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(r),o.close()},send:a=>{const c=JSON.stringify(E(a,`socket message for '${e}'`)),u=o.socket();if(u!==void 0)try{u.send(c)}catch{}}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}syncStatus(){const e=this.computeStatus(),t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader();let s=0;for(const r of this.subscriptions.all())(t||this.connectionGateState(r.shardKey).polling?r.valueReceived:r.acked)||(s+=1);for(const r of this.shapeSubscriptions.values())r.answered||(s+=1);const i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:s,pendingWrites:i,synced:q(e)&&s===0&&i===0}}onSyncStatus(e){const t=this.syncStatusListeners.add(e),s=this.syncStatus();return this.lastSyncStatus=s,e(s),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 r of s){const o=this.connections.get(r);e.push({confirmedMutationWatermark:t?.get(r)??0,hasSocket:o?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}const i=this.subscriptions.all().map(r=>({acked:r.acked,functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())i.push({acked:r.answered,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((r,o)=>(r.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((r,o)=>r.functionPath.localeCompare(o.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 bt(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Se(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ce(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=L(e,t,s),r=this.hydratedQueryCache.get(i);if(r!==void 0)return this.cachedQueryMatchesIdentity(r)?r.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=A.key(e,t,s),r=this.subscriptions.get(i);return{present:r!==void 0,value:r?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,signal:s.signal})}async batch(e){return W(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw yt(s.signal);const{value:i}=await Se(this.runMutation(e,t,s),s.signal);return i}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,signal:s.signal,unbounded:!0})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),r=s.toArgs??(d=>({rows:d})),o=t.length;let a=0,c=0,u=0;for(let d=0;d<o;d+=i){const h=t.slice(d,d+i),p=u,{committed:f}=await this.runMutation(e,r(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(p)}`},shardKey:s.shardKey});u+=1,a+=h.length,f&&(c+=h.length),s.onProgress?.({done:a,total:o})}return{chunks:u,imported:c,queued:a-c}}async shardTraffic(e){return fi(this.adminHost,e)}async listScheduledJobs(){return yi(this.adminHost)}async schedulerStatus(){return Si(this.adminHost)}async cancelScheduledJob(e){return bi(this.adminHost,e)}async listDeadJobs(){return vi(this.adminHost)}async retryDeadJob(e){return gi(this.adminHost,e)}async removeDeadJob(e){return Ti(this.adminHost,e)}async listWorkflowInstances(e){return ki(this.adminHost,e)}async getWorkflowInstance(e){return wi(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ci(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=this.openSupplementarySocket(C(de(this.url),Nt),{onMessage:s=>{let i;try{i=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(t.resetBackoff(),e(i.records.map(r=>ae(r))))}});return t.close}async listFunctions(){return Zs(this.adminHost)}async getCronJobs(){return ei(this.adminHost)}async runCronJob(e){return ti(this.adminHost,e)}async fetchOpenApi(){return si(this.adminHost)}async fetchArchitecture(){return ii(this.adminHost)}async fetchOpenRpc(){return ni(this.adminHost)}async listStorageObjects(e={}){return Ei(this.adminHost,e)}async deleteStorageObject(e,t){return Ai(this.adminHost,e,t)}async listStorageBuckets(){return _i(this.adminHost)}async uploadStorageObject(e){return Ii(this.adminHost,e)}async signedStorageUrl(e,t){return Oi(this.adminHost,e,t)}async listGlobalTables(){return ri(this.adminHost)}async readGlobalTablePage(e){return oi(this.adminHost,e)}async facetGlobalColumn(e){return ai(this.adminHost,e)}async listVectorIndexes(){return Ri(this.adminHost)}async queryVectorIndex(e){return Pi(this.adminHost,e)}async queryLogArchive(e={}){return pi(this.adminHost,e)}async listKvNamespaces(){return ci(this.adminHost)}async listKvKeys(e){return di(this.adminHost,e)}async getKvValue(e){return ui(this.adminHost,e)}async putKvValue(e){return hi(this.adminHost,e)}async deleteKvKey(e){return li(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=v(os,{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 this.assertOpen(),await this.adminFetch(cs,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(ds,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(us,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(hs,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(ls,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(fs,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(ps,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(ms,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(ys,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Ss,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(bs,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(v(vs,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(gs,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(v(Ts,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(ks,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(ws,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(v(Cs,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=v(Es,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=v(As,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=v(Rs,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Ps,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Fs,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(_s,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Is,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(Os,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Ls,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Ms,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Hs,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Us,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ns,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Ds,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=v(Ws,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(xs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Bs,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(Qs,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=v(qs,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Ks,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Gs,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=v(js,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch($s,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Vs,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(zs,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=v(as,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const r=t??{},o=A.key(e.__lunoraRef,r,i.shardKey);let a=this.subscriptions.get(o);const c=j(s),u=j(i.onError),d=j(i.onCheckpoint);if(!a){this.nextSubId+=1;const m=`sub_${this.nextSubId.toString()}`,b=ce(r),S=this.takeHydratedCache(e.__lunoraRef,b,i.shardKey);a={acked:!1,args:r,argsKey:b,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:m,lastValue:S?.value,optimisticLayers:[],serverBase:S?.value,serverCursor:S?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:E(r,`args for '${e.__lunoraRef}'`),...S?.serverEpoch===void 0?{}:{serverEpoch:S.serverEpoch}},this.subscriptions.add(a),this.emitSyncStatus(),S!==void 0&&this.cacheSeededQueries.set(o,S)}if(a.callbacks.add(c),u&&a.errorCallbacks.add(u),d&&a.checkpointCallbacks.add(d),a.lastValue!==void 0)try{c(a.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(a);const h=a;let p=!1;const f=()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),h.callbacks.delete(c),u&&h.errorCallbacks.delete(u),d&&h.checkpointCallbacks.delete(d),h.callbacks.size===0)){this.sendOrQueueUnsubscribe(h.shardKey,h.id,"unsubscribe"),this.returnCacheSeed(A.keyOf(h)),this.subscriptions.remove(h);const m=this.getConnection(h.shardKey);m&&this.settleSubscribeWatchdog(m,h.id),this.releaseIdleShard(h.shardKey),this.emitSyncStatus()}};return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:o}=s;return o!==void 0&&queueMicrotask(()=>{o({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 i=`shape_${this.nextShapeId.toString()}`,r={answered:!1,args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,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(i,r),this.emitSyncStatus(),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(r),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(r.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(r.shardKey),this.emitSyncStatus()}}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 i=`stream_${this.nextStreamId.toString()}`,{shardKey:r}=s,o=t??{},{handle:a,iterable:c}=vt({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const u=this.getConnection(r),d={id:i,query:{args:E(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:r},type:"stream"},h={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:d,shardKey:r};this.streams.set(i,h);const p=u?.wsState==="open"&&k(u,d);if(!p&&u===void 0)return this.forgetStream(i),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")),c;if(!p){for(u.pendingStreams=u.pendingStreams??[];u.pendingStreams.length>=Xe;){const m=u.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.forgetStream(m))}u.pendingStreams.push(d)}return c}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 i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return ct(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=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(),this.supplementaryBounces.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.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.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}shardInUse(e){const t=s=>l(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=l(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},Ze))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[i,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(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,H(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeShapes:()=>[...this.shapeSubscriptions.values()],activeSubscriptions:()=>this.subscriptions.all(),broadcastStatus:(s,i)=>this.tabCoordinator?.broadcastConnectionStatus(s,i),closeConnections:()=>{for(const[s,i]of this.connections)this.teardownConnection(i),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,i,r)=>{this.ackAndAdvanceCursor(s,i,r)},subscription:s=>this.subscriptions.get(s)};return new rt({channelName:e,onBecomeLeader:()=>{Zi(t)},onStopBeingLeader:()=>{en(t)},onConnectionStatus:(s,i)=>{tn(t,s,i)},onSubscriptionData:(s,i,r,o,a)=>{nn(t,s,i,r,o,a)},onLeaderClaimAnswered:()=>{sn(t)},onSubscriptionError:(s,i,r)=>{rn(t,s,i,r)},onSubscriptionSettled:(s,i,r,o,a,c)=>{on(t,s,i,r,o,a,c)}})}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,V),{body:JSON.stringify({calls:e.map((a,c)=>({args:E(a.args??{},`args for batch call '${a.fn.__lunoraRef}'`),functionPath:a.fn.__lunoraRef,id:c,shardKey:a.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let r;try{r=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const o=B(r);if(!s.ok||o!==void 0&&!r.results)throw o!==void 0?le(o):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of r.results??[]){const c=a.body?.commitCursor;typeof a.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[a.id]?.shardKey,c)}return Fi(r.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const i=dn(e,s),r=t,o=i.mutationId??ye();this.mutationIssueCounter+=1;const a=this.mutationIssueCounter,c=this.takeReplayCredential(i.replayCredential),u=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);const{confirms:d,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,r,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,h,d);const p=i.onlineOnly?void 0:this.offlineFlushes.get(l(i.shardKey));p!==void 0&&await p;const{httpFirst:f,midReconnect:m,shouldQueueOffline:b,socketDown:S}=this.writeQueueGate(i.shardKey),O=!i.onlineOnly&&b&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),g=async(T=!1)=>this.enqueueOfflineMutation(e,r,i.shardKey,u,o,h,d,T?void 0:i.precondition,i.mutationId,c?.stamp,T,a);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,h),S||m||O)return g();let N;try{const T=await this.rpc(e.__lunoraRef,r,i.shardKey,{baselineSeq:u,captureBookmark:!0,...c?.flags,mutationId:o,onCommitCursor:P=>{N=P}});for(const P of d)P(N);return{committed:!0,value:T}}catch(T){const P=fn(T,r),Ue=f&&b&&P,Ne=this.ownSocketOpen(i.shardKey);if(b&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(T instanceof TypeError||T instanceof U)&&ee(r)){const De=g(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),De}throw this.settleFailedDirectWrite(T,N,d,h,c?.flags.authToken),pn(i.onlineOnly,Ue,P,Ne)?Ee(e.__lunoraRef,T):T}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw F(s),Ee(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){const{hasSocket:t,idleClosed:s,polling:i,wasEverConnected:r,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:a}=this.offlineQueue,c=r||a,u=this.WebSocketImpl!==void 0&&c,d=i||s;return{httpFirst:d,midReconnect:o==="connecting"&&c&&!d,shouldQueueOffline:u,socketDown:o!=="open"&&!t&&u&&!d,socketOpen:o==="open"}}settleFailedDirectWrite(e,t,s,i,r){if(this.noteIdentityMismatch(e),r!==void 0&&this.noteReplayAuthRefusal(e,r),K(e)){for(const o of s)o(t);return}F(i)}async enqueueOfflineMutation(e,t,s,i,r,o,a,c,u,d,h,p){const f=d===void 0?this.identityFingerprint():d;if(this.outbox){this.outboxMutationCounter+=1;const b=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:u??`${this.clientId}:${String(b)}`,identity:f,mutationId:b,...o.length>0&&{onRejected:()=>{F(o)}},shardKey:s})}catch(S){throw F(o),S instanceof Error?S:new Error(String(S))}for(const S of a)S(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((b,S)=>{const O={ambiguousSend:h,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,issueSeq:p,clientId:this.clientId,identity:f,precondition:c,onCommit:g=>{for(const N of a)N(g)},reject:g=>{this.queuedIdentities.delete(r),K(g)||F(o),S(g instanceof Error?g:new Error(String(g))),this.releaseIdleShard(s)},resolve:b,shardKey:s};this.offlineQueue.enqueue(O),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),O.id!==void 0&&this.queuedIdentities.set(O.id,f)})}}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(L(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(pt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const r=t.get(s);if(r&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(r,i);continue}this.hydratedQueryCache.set(s,i)}}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(L(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),M(e,t.value))}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,M(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=L(e,t,s),r=this.hydratedQueryCache.get(i);if(!(r===void 0||!this.cachedQueryMatchesIdentity(r)))return this.hydratedQueryCache.delete(i),r}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=L(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=L(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,r=i===void 0?this.identityFingerprint():i;r===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:r,serverCursor:e.serverCursor,ts:Date.now(),value:t,...r===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(()=>{})},et))}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,i])=>e.put(s,i)))}installPageHideFlush(){const e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;const t=()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},s=()=>{e.document?.visibilityState==="hidden"&&t()};e.addEventListener("pagehide",t),e.document?.addEventListener("visibilitychange",s),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",t),e.document?.removeEventListener("visibilitychange",s)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"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 i of this.subscriptions.all())l(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}composedBaselineFor(e,t){return e===void 0?this.baselineCursorFor(t):e??void 0}async pollSubscriptions(e){const t=l(e),s=[];for(const a of this.subscriptions.all())l(a.shardKey)===t&&(ee(a.args)?s.push(a):(this.markQueryRejected(a,!0),I(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 i=lt(),r=this.identityFingerprint();let o;try{o=await ke(async a=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),a))}catch(a){return!(a instanceof TypeError)}if(this.identityFingerprint()!==r)return!0;for(const[a,c]of s.entries()){const u=o[a];if(u!==void 0){if(!u.ok){this.markQueryRejected(c,!0),I(c.errorCallbacks,{code:u.error.code,message:u.error.message});continue}this.handleDataMessage({data:x(u.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await ke(async t=>e(C(this.url,V),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;const e=this.syncStatus(),t=this.lastSyncStatus;t?.connection===e.connection&&t.pendingSubscriptions===e.pendingSubscriptions&&t.pendingWrites===e.pendingWrites&&t.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){const e=this.computeStatus();this.emitSyncStatus(),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,i){const r=[],o=[];if(!i)return{confirms:r,rollbacks:o};const a=A.key(e,t,s),c=this.subscriptions.get(a);if(c){const u=dt(c,i);u&&(r.push(u.confirm),o.push(u.rollback))}return{confirms:r,rollbacks:o}}applyOptionalOptimisticUpdate(e,t,s,i,r){e&&this.applyOptimisticUpdate(e,t,s,i,r)}applyOptimisticUpdate(e,t,s,i,r){const{confirms:o,rollbacks:a,store:c}=ut(this.subscriptions,s);try{e(c,t)}catch{F(a);return}i.push(...a),r.push(...o)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!k(i,{id:t,type:s})&&i.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(l(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,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:Ni({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:be(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}openSupplementarySocket(e,t){if(this.WebSocketImpl===void 0||this.closed)return{close:()=>{},resetBackoff:()=>{},socket:()=>{}};const s=be(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let r,o=!1;const a=()=>{o||this.closed||(r=setTimeout(d,s.next()))},c=f=>{o||this.WebSocketImpl===void 0||Te(i,this.wsUrlFor(t.shardKey,f,e),this.managedSocketOptions,{onClose:()=>{a(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen}})},u=async f=>{const m=this.wsTokenGeneration;let b;try{b=await f()}catch{a();return}if(m!==this.wsTokenGeneration){d();return}c(b)},d=()=>{if(o||this.WebSocketImpl===void 0)return;const{wsToken:f}=this;if(typeof f=="function"){u(f).catch(()=>{});return}c(f)};d();const h=()=>{o=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i);const{socket:f}=i;i.socket=void 0;try{f?.close()}catch{}};this.adminSocketTeardowns.add(h);const p=()=>{const{socket:f}=i;if(f!==void 0){i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i);try{f.close()}catch{}t.onClose?.(),a()}};return this.supplementaryBounces.add(p),{close:()=>{h(),this.adminSocketTeardowns.delete(h),this.supplementaryBounces.delete(p)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=ue(this.wsUrl),s=t.pathname.endsWith(z)?t.pathname.slice(0,-z.length):t.pathname;return t.pathname=C(s,e),he(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){if(e===void 0&&t===void 0)return s;const i=ue(s),r=new Set([...e===void 0?[]:["shard"],...t===void 0?[]:["token"]]),o=[...i.searchParams].filter(([a])=>!r.has(a)).map(([a,c])=>`${encodeURIComponent(a)}=${encodeURIComponent(c)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&o.push(`token=${encodeURIComponent(t)}`),i.search=o.join("&"),he(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[wt]=Ct(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const r=e.authToken===void 0?this.authToken:e.authToken;if(r&&(s.authorization=`Bearer ${r}`),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 o=this.bookmark.get();o&&(s["x-d1-bookmark"]=o)}return s}async rpc(e,t,s,i={}){const{fetchImpl:r}=this;if(!r)throw new U("LunoraClient: no `fetch` implementation available");const o=this.rpcRequestHeaders(i,s),a=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:u,response:d}=await W(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{const m=await r(C(this.url,Lt),{body:c,headers:o,method:"POST",signal:f});try{return{body:await m.json(),response:m}}catch{return{body:void 0,response:m}}});if(i.captureBookmark){const f=d.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(u===void 0)throw D(d.status,d.statusText,d.headers.get("retry-after"));const h=u;if(typeof h!="object"||h===null||Array.isArray(h))throw D(d.status,d.statusText,d.headers.get("retry-after"));const p=B(u);if(p!==void 0)throw fe(p,d.headers.get("retry-after"));if(!d.ok)throw D(d.status,d.statusText,d.headers.get("retry-after"));i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(a),this.learnDefaultShardKey(d,s),this.recordShardCursor(s,u.commitCursor);try{return w(u.result)}catch(f){throw Fe(f)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={};this.authToken&&(r.authorization=`Bearer ${this.authToken}`);const o=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:o?(a=s,i!==void 0&&(r["content-type"]=i)):(a=JSON.stringify(s),r["content-type"]="application/json");const c=await this.fetchImpl(C(this.url,e),{body:a,headers:r,method:t});let u;try{u=await c.json()}catch{const h=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${h})`)}const d=B(u);if(d!==void 0)throw le({...d,message:d.message??"admin request failed"});if(!c.ok){const h=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${h})`)}return u}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));k(e,{caps:un,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){const i=this.wsTokenGeneration,r=Symbol("ws-token-attempt");let o;e.providerAttempt=r;try{o=await W(this.connectTimeoutMs,void 0,async()=>s(),()=>new Error("LunoraClient: wsToken provider timed out"))}catch{e.providerAttempt===r&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===r&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(i!==this.wsTokenGeneration){typeof this.wsToken=="function"?await this.openSocketWithProvidedToken(e,t,this.wsToken):this.openSocket(e,t,this.wsToken);return}this.openSocket(e,t,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,Te(e,this.wsUrlFor(t,s),this.managedSocketOptions,{onClose:i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:i=>{e.retired!==!0&&this.handleServerMessage(i.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},me),this.markShardPendingAck(t,!0),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.clearResubscribeQueue(e);for(const o of this.subscriptions.all())l(o.shardKey)===l(t)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:a,type:c}of o)k(e,{id:a,type:c});this.releaseIdleShard(t)}Li(e);const i=l(t),r=this.whisperHandlers.get(i);if(this.dropWhisperJoinWaiters(i),this.whisperJoins.set(i,new Map),r)for(const o of r.keys())this.sendWhisperJoin(e,i,o);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})}}))}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),k(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),H(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(l(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,r]of this.streams)if(!(l(r.shardKey)!==l(e.shardKey)||t.has(i))){if(r.durable){const o={...r.message,...r.generation===void 0?{}:{generation:r.generation},sinceChunk:r.lastSeq};r.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==i),o];continue}r.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e,t=!1){const s=l(e);for(const i of this.subscriptions.all())l(i.shardKey)===s&&(i.acked=!1,t&&(i.valueReceived=!1));for(const i of this.shapeSubscriptions.values())l(i.shardKey)===s&&(i.answered=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<tt;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribeSlots.add(t.id)}}settleSubscribeWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t)),e.unackedWatchdogs.delete(t),e.resubscribeSlots.delete(t)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(const t of e.unackedWatchdogs.values())clearTimeout(t);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,t=!1){const s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;const i=e.serverCursor!==void 0&&e.serverBase!==void 0,r=k(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return r&&!t&&this.armUnackedWatchdog(s,e),r}armUnackedWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t.id)),e.unackedWatchdogs.set(t.id,setTimeout(()=>{!t.acked&&this.subscriptions.getById(t.id)===t&&this.sendSubscribeIfOpen(t,!0),this.settleSubscribeWatchdog(e,t.id)},st))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&k(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=Hi(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}if(i.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof i.id=="string"){const r=this.getConnection(t);if(r){const{id:o}=i;this.settleSubscribeWatchdog(r,o)}}switch(i.type){case"ack":{const r=this.subscriptions.getById(i.id);r&&this.ackAndAdvanceCursor(r,void 0,void 0);return}case"chunk":{const{data:r,generation:o,id:a,seq:c}=i,u=this.streams.get(a);u&&typeof c=="number"&&(u.lastSeq=c,typeof o=="number"&&(u.generation=o),u.durable=!0),u?.handle.push(w(r));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,t),this.adoptSocketConnectionId(i,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(i,t);break}case"pokeEnd":{this.handlePokeEnd(i,t);break}case"pokePart":{this.pokeAssembler.part(t,i);break}case"pokeStart":{this.pokeAssembler.start(t,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(l(t),i.topic);break}}}handleErrorMessage(e){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(Ke(e)),this.forgetStream(s);return}const r=s===void 0?void 0:this.subscriptions.getById(s);if(r){const a=pe(e),c=this.identityFingerprint(),u=A.keyOf(r);this.markQueryRejected(r),I(r.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}const o=s===void 0?void 0:this.shapeSubscriptions.get(s);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),I(o.errorCallbacks,pe(e)))}markQueryRejected(e,t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){const s=t?"valueReceived":"acked";e[s]||(e[s]=!0,this.emitSyncStatus())}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){Ji(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const r=this.shapeSubscriptions.get(i);r&&!s.undecodable.has(i)&&this.applyPokePart(r,s,e)}}}applyPokePart(e,t,s){const i=e.answered,r=zi(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),Ce(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&Yi(i,e))return;let r;try{r=We(e,i.serverBase)}catch(a){I(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${a instanceof Error?a.message:String(a)}`});return}if(r===xe){this.resnapshotSubscription(i);return}this.dropCacheSeed(A.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(Le(i,r,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(se(i,e.lastMutationId),ie(i,!0)),this.persistQueryValue(i),Z(i,i.serverCursor),t!==void 0&&ht(i,t),M(i,r),this.tabCoordinator?.isLeader()){const a=A.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(a,r,i.serverCursor,i.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&&se(t,e.lastMutationId),ie(t),this.tabCoordinator?.isLeader())){const s=A.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){const i=!e.acked;e.acked=!0,i&&this.emitSyncStatus(),(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),Z(e,e.serverCursor)&&M(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(!(s===void 0||typeof e.connectionId!="string")){s.connectionId=e.connectionId,s.whisperAck=e.whisperAck===!0;for(const i of this.liveSocketGrants.get(l(t))?.keys()??[])this.grantWhenJoined(t,i,e.connectionId)}}grantWhenJoined(e,t,s){const i=l(e),r=this.liveSocketGrants.get(i)?.get(t);if(r===void 0)return;const{stream:o,topic:a}=r,c=()=>{this.liveSocketGrants.get(i)?.get(t)===void 0||this.getConnection(e)?.connectionId!==s||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:s,stream:o,subscriptionId:t,topic:a},d=>{this.refuseLiveGrant(e,t,d,s)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,a,c):c()}sendWhisperJoin(e,t,s){const i=this.whisperJoinState(t,s);i.pending+=1,i.joined=!1,k(e,{topic:s,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,t){const s=this.whisperJoins.get(e)?.get(t);if(s!==void 0&&(s.pending=Math.max(0,s.pending-1),!(s.pending>0))){s.joined=!0;for(const i of s.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,t)}}releaseWhisperJoin(e,t){if(this.whisperHandlers.get(e)?.has(t)===!0)return;const s=this.whisperJoins.get(e),i=s?.get(t);if(!(s===void 0||i===void 0||i.pending>0)){for(const r of i.waiters.splice(0))clearTimeout(r.timer);s.delete(t),s.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,t,s){const i=this.whisperJoinState(e,t);if(i.joined){s();return}const r={run:s,timer:void 0};r.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==r),s()},Me),i.waiters.push(r)}dropWhisperJoinWaiters(e){for(const t of this.whisperJoins.get(e)?.values()??[])for(const s of t.waiters.splice(0))clearTimeout(s.timer)}whisperJoinState(e,t){let s=this.whisperJoins.get(e);s===void 0&&(s=new Map,this.whisperJoins.set(e,s));let i=s.get(t);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},s.set(t,i)),i}refuseLiveGrant(e,t,s,i){const r=l(e),o=this.liveSocketGrants.get(r),a=o?.get(t);o===void 0||a===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(t),o.size===0&&this.liveSocketGrants.delete(r),a.release(),a.onError?.({status:s,topic:a.topic}))}postLiveControl(e,t,s,i){const{fetchImpl:r}=this;if(!r)return;const o=JSON.stringify(t===void 0?s:{...s,shardKey:t}),a=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>ln(r,C(this.url,e),o,a)).then(c=>{c>=400&&c<500&&c!==404&&c!==401&&i?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(l(t));if(!s)return;const i=w(e.data);for(const r of s.values())if(!(r.stream!==e.stream||r.topic!==e.topic))try{r.onEvent(i)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const i=w(e.data);for(const r of s)try{r(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,this.emitSyncStatus(),I(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(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 i=0;i<e.length;i+=1){const r=e.charCodeAt(i);t^=r,t=Math.imul(t,16777619),s=Math.imul(s,33)+r}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&&q(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)}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey),r=i!==void 0&&k(i,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),r}roomSendsAdmitted(e){const t=this.getConnection(e);return t?.wsState==="open"&&t.retired!==!0&&t.identityConfirmed===!0&&t.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(const t of this.roomFlushes.get(l(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==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}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const i of t){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);const r=new Error("offline mutation discarded: auth identity changed before replay");r.code="OFFLINE_IDENTITY_CHANGED",i.reject(r),this.emitItemSettled(i,"rejected",r)}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,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);const r=t??"",o=this.clientWatermarks.get(r);if(o===void 0)this.clientWatermarks.set(r,i);else for(const[a,c]of i)o.set(a,c)}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.resetRoomSends(),this.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,e.valueReceived=!1,M(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Ce(e);this.emitSyncStatus(),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()}resetRoomSends(){for(const e of this.roomIdentityResets)e()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}for(const e of this.supplementaryBounces)e()}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 i=(async()=>{await(s??Promise.resolve());const{authToken:r}=this;try{await this.drainOfflineQueue(e,r)}catch{}!this.closed&&this.authToken!==r&&this.offlineQueue.size>0&&q(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,i),await i,this.offlineFlushes.get(t)===i&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const d of s){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");const h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",h)}const i=l(e),r=this.offlineQueue.drain(d=>l(d.shardKey)===i);if(r.length===0)return;const o=[],a=[];for(const d of r){const h=this.replayGateVerdict(d);h==="send"?o.push(d):h==="hold"&&a.push(d)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(o);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const u=[];for(let d=0;d<c.length;d+=$){const h=c.slice(d,d+$),p=await this.replayBatched(h,e,t);if(u.push(...p.requeue),p.stop||p.requeue.length>0){u.push(...c.slice(d+$));break}}u.length>0&&this.offlineQueue.requeue(u),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(e),s=this.replayRetryState.get(t),i=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:i,delayMs:Math.max(s?.delayMs??0,te(i))})}noteReplayRetryDelay(e,t,s){const i=l(e),r=this.replayRetryState.get(i),o=(r?.attempts??0)+1,a=Qi(t,o)??(s===null&&Q(t)?te(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:a===void 0?r?.delayMs:Math.max(r?.delayMs??0,a)})}scheduleRateLimitedRetry(e){const t=l(e),s=this.replayRetryState.get(t),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const r=this.replayRetryTimers.get(t);r!==void 0&&clearTimeout(r),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{E(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}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 i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"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 i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),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)||we(e)}noteReplayAuthRefusal(e,t){if(!Q(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 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,...J(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)}spendsLastReplayAttempt(e,t){if(e.id===void 0)return!1;const s=t?.code;if(e.ambiguousSend!==!0||Q(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||!we(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=it}keepUnexhaustedAmbiguousWrites(e,t){return e.filter(s=>s.ambiguousSend===!0&&this.spendsLastReplayAttempt(s,t)?(this.settleReplayTerminal(s,t),!1):!0)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const r=e[i];if(!r)continue;let o;try{const a=await this.rpc(r.functionPath,r.args,r.shardKey,{authToken:s,baselineSeq:r.baselineSeq,captureBookmark:!0,clientId:r.clientId??this.clientId,...J(r.identity,s),mutationId:r.id,onCommitCursor:c=>{o=c}});this.settleReplaySuccess(r,a,o)}catch(a){if(K(a)){this.settleReplayUndecodable(r,a,o);continue}if(!this.shouldRequeueReplayFailure(a,s)||this.spendsLastReplayAttempt(r,a)){this.settleReplayTerminal(r,a);continue}this.noteReplayRetryDelay(t,a,s),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const i=JSON.stringify({calls:e.map((d,h)=>({args:E(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Ki(i)>qi)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:r}=this;let o,a;try{({payload:a,response:o}=await W(this.rpcTimeoutMs,void 0,async d=>{const h=await r(C(this.url,V),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...J(e.find(p=>p.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(h.status===413&&e.length>1)return{payload:void 0,response:h};try{return{payload:await h.json(),response:h}}catch{return{payload:void 0,response:h}}}))}catch(d){return this.noteReplayRetryDelay(t,d,s),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}const c=o.headers.get("x-d1-bookmark");if(c&&this.bookmark.set(c),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);const u=o.headers.get("retry-after");if(!a)return this.settleWholeBatchError(e,D(o.status,o.statusText,u),t,s);if(!Array.isArray(a.results)){const d=B(a),h=d===void 0?D(o.status,o.statusText,u):fe(d,u);return this.settleWholeBatchError(e,h,t,s)}return{requeue:this.settleReplayBatchSlots(e,a.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof U||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,t),stop:!0};for(const r of e)this.settleReplayTerminal(r,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),r=await this.replayBatched(e.slice(0,i),t,s);if(r.stop||r.requeue.length>0)return{requeue:[...r.requeue,...e.slice(i)],stop:!0};const o=await this.replayBatched(e.slice(i),t,s);return{requeue:[...r.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,t,s,i){const r=Gi(t),o=[];let a=!1,c=!1;for(const[u,d]of e.entries()){const h=ji(r.get(u));switch(h.kind){case"committed":{a=!0,this.settleReplaySuccess(d,h.value,h.commitCursor);break}case"errored":{c||=Q(h.error),this.shouldRequeueReplayFailure(h.error,i)&&!this.spendsLastReplayAttempt(d,h.error)?(this.noteReplayRetryDelay(s,h.error,i),o.push(d)):this.settleReplayTerminal(d,h.error);break}case"unanswered":{const p=Ge();if(this.spendsLastReplayAttempt(d,p)){this.settleReplayTerminal(d,p);break}this.noteReplayRetryDelay(s,p,i),o.push(d);break}default:a=!0,this.settleReplayUndecodable(d,h.error,h.commitCursor)}}return a&&!c&&this.noteCredentialAccepted(i),o}}export{He as LunoraClient};
|