@lunora/client 1.0.0-alpha.213 → 1.0.0-alpha.215
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 +22 -3
- package/dist/index.d.ts +22 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs +1 -0
- package/dist/packem_shared/{LunoraClient-Bt_wlTdK.mjs → LunoraClient-DerKcvqC.mjs} +1 -1
- package/dist/packem_shared/{createServerClient-DAON0zRx.mjs → createServerClient-B1NCqPDO.mjs} +1 -1
- package/dist/packem_shared/httpStream-BhSpxRWB.mjs +9 -0
- package/dist/packem_shared/{lunora-client.d-B-1VFscs.d.mts → lunora-client.d-DFwg2da7.d.mts} +2 -0
- package/dist/packem_shared/{lunora-client.d-_Qd50jQo.d.ts → lunora-client.d-DS1iidgx.d.ts} +2 -0
- package/dist/packem_shared/{preload.d-D82baNUQ.d.mts → preload.d-DHBLZn6m.d.mts} +1 -1
- package/dist/packem_shared/{preload.d-ubxA2STh.d.ts → preload.d-L3NDOXp4.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/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +0 -1
- package/dist/packem_shared/httpStream-h8Tx3scO.mjs +0 -9
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-DFwg2da7.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-DS1iidgx.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 OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-
|
|
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-DFwg2da7.mjs";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-DFwg2da7.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-DHBLZn6m.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';
|
|
@@ -565,8 +565,27 @@ interface HttpStreamOptions {
|
|
|
565
565
|
fetch?: typeof fetch;
|
|
566
566
|
/** Extra request headers (e.g. `authorization`). `accept: text/event-stream` is always sent. */
|
|
567
567
|
headers?: Record<string, string>;
|
|
568
|
+
/**
|
|
569
|
+
* Seed the first request's `Last-Event-ID` header, resuming a stream from a
|
|
570
|
+
* position a previous consumer persisted. Once frames arrive this is
|
|
571
|
+
* superseded by their `id:`, and a reconnecting stream always sends the
|
|
572
|
+
* latest id it saw.
|
|
573
|
+
*/
|
|
574
|
+
lastEventId?: string;
|
|
568
575
|
/** Caps the in-flight chunk buffer (see `createStream`); exceeding it fails the stream. */
|
|
569
576
|
maxBuffer?: number;
|
|
577
|
+
/** Called with each frame's `id:` as it is seen (the value that will be replayed on reconnect). */
|
|
578
|
+
onEventId?: (id: string) => void;
|
|
579
|
+
/** Called when the server advertises a `retry:` reconnect delay, in milliseconds. */
|
|
580
|
+
onRetry?: (ms: number) => void;
|
|
581
|
+
/**
|
|
582
|
+
* Reopen the request after a transport interruption — a bare EOF or a
|
|
583
|
+
* read/transport error — replaying the last seen id as `Last-Event-ID`.
|
|
584
|
+
* Defaults to `false`, which surfaces the interruption as
|
|
585
|
+
* `HTTP_STREAM_INTERRUPTED` exactly as before. A terminal `complete`/`error`
|
|
586
|
+
* frame, a non-2xx status, and a consumer cancel never reconnect.
|
|
587
|
+
*/
|
|
588
|
+
reconnect?: boolean;
|
|
570
589
|
/** External abort signal — aborting it cancels the fetch (→ the server handler's `signal`). */
|
|
571
590
|
signal?: AbortSignal;
|
|
572
591
|
}
|
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 OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-
|
|
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-DS1iidgx.js";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-DS1iidgx.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-L3NDOXp4.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';
|
|
@@ -565,8 +565,27 @@ interface HttpStreamOptions {
|
|
|
565
565
|
fetch?: typeof fetch;
|
|
566
566
|
/** Extra request headers (e.g. `authorization`). `accept: text/event-stream` is always sent. */
|
|
567
567
|
headers?: Record<string, string>;
|
|
568
|
+
/**
|
|
569
|
+
* Seed the first request's `Last-Event-ID` header, resuming a stream from a
|
|
570
|
+
* position a previous consumer persisted. Once frames arrive this is
|
|
571
|
+
* superseded by their `id:`, and a reconnecting stream always sends the
|
|
572
|
+
* latest id it saw.
|
|
573
|
+
*/
|
|
574
|
+
lastEventId?: string;
|
|
568
575
|
/** Caps the in-flight chunk buffer (see `createStream`); exceeding it fails the stream. */
|
|
569
576
|
maxBuffer?: number;
|
|
577
|
+
/** Called with each frame's `id:` as it is seen (the value that will be replayed on reconnect). */
|
|
578
|
+
onEventId?: (id: string) => void;
|
|
579
|
+
/** Called when the server advertises a `retry:` reconnect delay, in milliseconds. */
|
|
580
|
+
onRetry?: (ms: number) => void;
|
|
581
|
+
/**
|
|
582
|
+
* Reopen the request after a transport interruption — a bare EOF or a
|
|
583
|
+
* read/transport error — replaying the last seen id as `Last-Event-ID`.
|
|
584
|
+
* Defaults to `false`, which surfaces the interruption as
|
|
585
|
+
* `HTTP_STREAM_INTERRUPTED` exactly as before. A terminal `complete`/`error`
|
|
586
|
+
* frame, a non-2xx status, and a consumer cancel never reconnect.
|
|
587
|
+
*/
|
|
588
|
+
reconnect?: boolean;
|
|
570
589
|
/** External abort signal — aborting it cancels the fetch (→ the server handler's `signal`). */
|
|
571
590
|
signal?: AbortSignal;
|
|
572
591
|
}
|
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 n}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as i}from"./packem_shared/createAsyncStorageQueryCache-f5023fdB.mjs";import{default as f}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-CXD7vulJ.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as S,TransportError as h,getErrorCode as D,getRetryAfterMs as Q,isAuthReplayFailure as _,isConflictError as F,isForbiddenError as I,isRateLimitedError as M,isUnauthorizedError as g}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as O}from"./packem_shared/httpStream-
|
|
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 n}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as i}from"./packem_shared/createAsyncStorageQueryCache-f5023fdB.mjs";import{default as f}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-CXD7vulJ.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as S,TransportError as h,getErrorCode as D,getRetryAfterMs as Q,isAuthReplayFailure as _,isConflictError as F,isForbiddenError as I,isRateLimitedError as M,isUnauthorizedError as g}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as O}from"./packem_shared/httpStream-BhSpxRWB.mjs";import{c as b}from"./packem_shared/local-store-fqWV2n_Z.mjs";import{LunoraClient as U}from"./packem_shared/LunoraClient-DerKcvqC.mjs";import{createMutatorRunner as k}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as N}from"./packem_shared/offline-queue-D_fr-uQ3.mjs";import{createInMemoryPersistence as K,createIndexedDbPersistence as V}from"./packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs";import{preloadQuery as j,preloadedQueryResult as v}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as G,createIndexedDbQueryCache as H,queryCacheKey as J}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Y}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as $}from"./packem_shared/createSnapshotPrecondition-CLkxVeN1.mjs";import{DEFAULT_MAX_BUFFER as re,createStream as oe}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as ae}from"./packem_shared/SubscriptionRegistry-DKIXE7M7.mjs";export{S as CONFLICT_ERROR_CODE,re as DEFAULT_MAX_BUFFER,U as LunoraClient,N as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ae as SubscriptionRegistry,d as TabCoordinator,h as TransportError,R as applyDelta,n as createAsyncStoragePersistence,i as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,f as createInMemoryBookmarkStorage,K as createInMemoryPersistence,G as createInMemoryQueryCache,V as createIndexedDbPersistence,H as createIndexedDbQueryCache,b as createLocalStore,k as createMutatorRunner,Y as createReconnect,$ as createSnapshotPrecondition,oe as createStream,D as getErrorCode,Q as getRetryAfterMs,O as httpStream,_ as isAuthReplayFailure,F as isConflictError,I as isForbiddenError,C as isMutationDelta,M as isRateLimitedError,g as isUnauthorizedError,t as maxSeq,j as preloadQuery,v as preloadedQueryResult,J as queryCacheKey,a as reconcileOptimistic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";const m=1024,p=o=>{const i=o.maxBuffer??m,r=[],l=[];let n=!1,t,s=!1;const u=()=>{const e=l.shift();if(!e)return!1;if(t)return e.reject(t),!0;if(r.length>0){const f=r.shift();return e.resolve({done:!1,value:f}),!0}return n?(e.resolve({done:!0,value:void 0}),!0):(l.unshift(e),!1)},a={complete(){if(!(n||t))for(n=!0;u(););},fail(e){if(!(n||t)){for(t=e,r.length=0;u(););o.onFail?.()}},push(e){if(!(n||t||s)){if(r.length>=i){a.fail(new h("STREAM_BACKPRESSURE",`stream buffer overflow (max=${i.toString()}); the consumer cannot keep up with the producer`));return}r.push(e),u()}}},c=()=>{if(!s){s=!0,n=!0,r.length=0;try{o.onCancel()}catch{}for(;u(););}};return{handle:a,iterable:{cancel:c,[Symbol.asyncIterator](){return{next(){if(t)return Promise.reject(t);if(r.length>0){const e=r.shift();return Promise.resolve({done:!1,value:e})}return n?Promise.resolve({done:!0,value:void 0}):new Promise((e,f)=>{l.push({reject:f,resolve:e})})},return(){return c(),Promise.resolve({done:!0,value:void 0})}}}}}};export{m as DEFAULT_MAX_BUFFER,p as createStream};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{encodeWire as M,decodeWire as k,stableWireKey as oe}from"@lunora/wire";import{r as Pe,U as Fe,P as He}from"./delta-merge-Ls3DED4g.mjs";import Le from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as Y,a as Me,e as N,r as Ue,b as ce,c as Ne,d as de}from"./wire-errors-WYlbE1Nh.mjs";import{ClientQueryStore as xe}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as Be}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as L,getRetryAfterMs as De,AUTH_REPLAY_ERROR_CODES as Qe,isAuthReplayFailure as W}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Ke}from"./httpStream-h8Tx3scO.mjs";import{d as X,r as O,a as P,b as qe,c as We,e as je,f as $e}from"./local-store-fqWV2n_Z.mjs";import{O as Ge,n as he,i as Ve,r as ze}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as Je}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Ye,queryCacheKey as _}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as ue}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as A,SubscriptionRegistry as v,wrapSubscriber as j}from"./SubscriptionRegistry-DKIXE7M7.mjs";import Xe from"./createSnapshotPrecondition-CLkxVeN1.mjs";import{createStream as Ze}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";const $=500,ge=(r,e)=>{if(r.size<e)return;const t=r.keys().next().value;t!==void 0&&r.delete(t)},C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",et=r=>{let e="",t=0;const s=r.length-2;for(;t<s;t+=3){const n=r[t]<<16|r[t+1]<<8|r[t+2];e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)+C.charAt(n>>6&63)+C.charAt(n&63)}const i=r.length-t;if(i===1){const n=r[t]<<16;e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)}else if(i===2){const n=r[t]<<16|r[t+1]<<8;e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)+C.charAt(n>>6&63)}return e};new TextDecoder;const tt=new TextEncoder,st=r=>et(tt.encode(JSON.stringify(r))),rt="x-lunora-expect-subject",it=r=>st({subject:r}),le=Symbol.for("lunora:session-change"),nt="lunora:session-change",at="better-auth.message",ot="signout",Te=()=>{const r=globalThis;let e=r[le];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},r[le]=e),e},ct=()=>"document"in globalThis,dt=async()=>{const r=[];for(const e of Te().listeners)try{r.push(e())}catch{}await Promise.allSettled(r)},ht=(r,e)=>{if(r!==at||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===ot}catch{return!1}},ut=r=>{const e=[],t=()=>{dt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(nt):void 0}catch{s=void 0}if(s!==void 0){const n=s;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==r&&t()}),e.push(()=>{n.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const n=o=>{ht(o.key,o.newValue)&&t()};i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(const n of e)n()}},lt=r=>{const e=Te();return e.listeners.add(r),e.detach===void 0&&ct()&&(e.detach=ut(e.tab)),()=>{e.listeners.delete(r),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},ft="/_lunora/rpc",G="/_lunora/rpc-batch",pt="/_lunora/ws",mt="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",St="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",gt="/_lunora/admin/scheduled/cancel",fe="/_lunora/admin/scheduled/dead",Tt="/_lunora/admin/scheduled/dead/retry",vt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",kt="/_lunora/admin/workflows/instance",wt="/_lunora/admin/workflows/status",se="/_lunora/admin/storage",Et="/_lunora/admin/storage/url",At="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",It="/_lunora/admin/cron-jobs",Ot="/_lunora/admin/cron-jobs/run",Rt="/_lunora/admin/architecture",Pt="/_lunora/admin/openapi",Ft="/_lunora/admin/openrpc",Ht="/_lunora/admin/global/tables",Lt="/_lunora/admin/global/table",Mt="/_lunora/admin/global/facet",Ut="/_lunora/admin/vector/indexes",Nt="/_lunora/admin/vector/query",xt="/_lunora/admin/logs/archive",Bt="/_lunora/admin/kv/namespaces",Dt="/_lunora/admin/kv/keys",re="/_lunora/admin/kv/value",Qt="/_lunora/admin/auth/users",Kt="/_lunora/admin/auth/sessions",qt="/_lunora/admin/auth/users/create",Wt="/_lunora/admin/auth/users/role",jt="/_lunora/admin/auth/users/ban",$t="/_lunora/admin/auth/users/unban",Gt="/_lunora/admin/auth/users/password",Vt="/_lunora/admin/auth/users/remove",zt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Yt="/_lunora/admin/auth/sessions/revoke-all",Xt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",es="/_lunora/admin/auth/accounts",ts="/_lunora/admin/auth/accounts/unlink",ss="/_lunora/admin/auth/passkeys",rs="/_lunora/admin/auth/passkeys/delete",is="/_lunora/admin/auth/two-factor/disable",ns="/_lunora/admin/auth/organizations",as="/_lunora/admin/auth/organizations/members",os="/_lunora/admin/auth/organizations/invitations",cs="/_lunora/admin/auth/organizations/members/remove",ds="/_lunora/admin/auth/organizations/invitations/cancel",hs="/_lunora/admin/auth/config",us="/_lunora/admin/auth/sign-up-invitations",ls="/_lunora/admin/auth/sign-up-invitations/create",fs="/_lunora/admin/auth/sign-up-invitations/revoke",ps="/_lunora/admin/auth/organizations/create",ms="/_lunora/admin/auth/organizations/update",ys="/_lunora/admin/auth/organizations/remove",Ss="/_lunora/admin/auth/organizations/members/add",bs="/_lunora/admin/auth/organizations/members/invite",gs="/_lunora/admin/auth/organizations/members/role",Ts="/_lunora/admin/auth/organizations/teams",vs="/_lunora/admin/auth/organizations/teams/create",Cs="/_lunora/admin/auth/organizations/teams/update",ks="/_lunora/admin/auth/organizations/teams/remove",ws="/_lunora/admin/auth/organizations/teams/members",Es="/_lunora/admin/auth/organizations/teams/members/add",As="/_lunora/admin/auth/organizations/teams/members/remove",_s="/_lunora/admin/auth/organizations/roles",Is="/_lunora/admin/auth/organizations/roles/create",Os="/_lunora/admin/auth/organizations/roles/update",Rs="/_lunora/admin/auth/organizations/roles/remove",Ps="/api/auth",Fs="/get-session",Hs="lunora-ping",Ls=async r=>(r.assertOpen(),(await r.adminFetch(_t,"GET")).functions??[]),Ms=async r=>(r.assertOpen(),(await r.adminFetch(It,"GET")).jobs??[]),Us=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(Ot,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},Ns=async r=>(r.assertOpen(),await r.adminFetch(Pt,"GET")),xs=async r=>(r.assertOpen(),await r.adminFetch(Rt,"GET")),Bs=async r=>(r.assertOpen(),await r.adminFetch(Ft,"GET")),Ds=async r=>(r.assertOpen(),await r.adminFetch(Ht,"GET")),Qs=async(r,e)=>{r.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(M(e.filters))),k(await r.adminFetch(`${Lt}?${t.toString()}`,"GET"))},Ks=async(r,e)=>{r.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(M(e.filters))),k(await r.adminFetch(`${Mt}?${t.toString()}`,"GET"))},ie=r=>r===void 0||r===""?"":`&bucket=${encodeURIComponent(r)}`,pe=r=>r.startsWith("https://")?`wss://${r.slice(8)}`:r.startsWith("http://")?`ws://${r.slice(7)}`:r,w=(r,e)=>`${r.endsWith("/")?r.slice(0,-1):r}${e}`,S=(r,e)=>{const t=new URLSearchParams;for(const[i,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(i,String(n));const s=t.toString();return s===""?r:`${r}?${s}`},qs=async r=>(r.assertOpen(),(await r.adminFetch(Bt,"GET")).namespaces??[]),Ws=async(r,e)=>{r.assertOpen();const t=S(Dt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await r.adminFetch(t,"GET")},js=async(r,e)=>{r.assertOpen();const t=S(re,{key:e.key,namespace:e.namespace});return await r.adminFetch(t,"GET")},$s=async(r,e)=>{r.assertOpen(),await r.adminFetch(re,"PUT",e)},Gs=async(r,e)=>{r.assertOpen();const t=S(re,{key:e.key,namespace:e.namespace});await r.adminFetch(t,"DELETE")},Vs=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(mt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},zs=async(r,e={})=>{r.assertOpen();const t=await r.adminFetch(xt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},Js=async r=>{const e=[];let t;for(;;){const s=await r(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}},ne=r=>"args"in r?{...r,args:k(r.args)}:r,Ys=async r=>(r.assertOpen(),((await r.adminFetch(yt,"GET")).records??[]).map(t=>ne(t))),Xs=async r=>{r.assertOpen();const e=await r.adminFetch(St,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},Zs=async(r,e)=>(r.assertOpen(),{cancelled:(await r.adminFetch(gt,"POST",{id:e})).cancelled===!0}),er=async r=>(r.assertOpen(),(await Js(async t=>await r.adminFetch(t===void 0?fe:`${fe}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>ne(t))),tr=async(r,e)=>(r.assertOpen(),{retried:(await r.adminFetch(Tt,"POST",{id:e})).retried===!0}),sr=async(r,e)=>(r.assertOpen(),{removed:(await r.adminFetch(vt,"POST",{id:e})).removed===!0}),rr=async(r,e)=>{r.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 r.adminFetch(`${Ct}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},ir=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await r.adminFetch(`${kt}?${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??[]}},nr=async(r,e)=>(r.assertOpen(),{status:(await r.adminFetch(wt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),ar=async(r,e={})=>{r.assertOpen();const t=S(se,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await r.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},or=async(r,e,t)=>{r.assertOpen();const s=`${se}?key=${encodeURIComponent(e)}${ie(t?.bucket)}`,i=await r.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},cr=async r=>(r.assertOpen(),(await r.adminFetch(At,"GET")).buckets??[]),dr=async(r,e)=>{r.assertOpen();const t=`${se}?key=${encodeURIComponent(e.key)}${ie(e.bucket)}`,s=await r.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},hr=async(r,e,t)=>{r.assertOpen();const s=t?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Et}?key=${encodeURIComponent(e)}${i}${ie(t?.bucket)}`,o=await r.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},ur=async r=>(r.assertOpen(),(await r.adminFetch(Ut,"GET")).indexes??[]),lr=async(r,e)=>(r.assertOpen(),(await r.adminFetch(Nt,"POST",e)).matches??[]),E=(r,e)=>{try{return M(r)}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)}},me=r=>{try{return M(r),!0}catch{return!1}},ve=r=>r!==null&&typeof r=="object"&&("error"in r||"result"in r),fr=(r,e)=>{const t=Array.from({length:e});for(const s of r){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!ve(s.body)){t[s.id]={error:Y({}),ok:!1};continue}const i=s.body;t[s.id]="error"in i?{error:Y(i),ok:!1}:{ok:!0,value:k(i.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},V=(r,e)=>e!==null?{}:r===null?{expectSubject:null}:r?.startsWith("subj:")===!0?{expectSubject:r.slice(5)}:{},pr=3e4,mr=1e4,yr=5e3,Sr=3,br=250,gr=5e3,Tr=5e3,vr=64,Cr=3,kr=1e4,wr=8,z=r=>r==="connected"||r==="polling",l=r=>r??"",g=(r,e)=>{if(!r.socket||r.wsState!=="open")return!1;try{return r.socket.send(JSON.stringify(e)),!0}catch{return!1}},Er=r=>{if(!r.pendingStreams||r.pendingStreams.length===0)return;const e=r.pendingStreams;r.pendingStreams=[];for(const t of e)g(r,t)},Ar=new TextDecoder,_r=r=>{if(typeof r=="string")return r;if(r instanceof ArrayBuffer)return Ar.decode(r)};class I{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const H=r=>{r.heartbeatTimer!==void 0&&(clearInterval(r.heartbeatTimer),r.heartbeatTimer=void 0)},Ir=(r,e,t)=>{H(r),!(e<=0)&&(r.heartbeatTimer=setInterval(()=>{if(!r.socket)return;const{socket:s}=r;if(Date.now()-r.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Hs)}catch{}},e))},ye=(r,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=t;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const a=new i(e);r.socket=a;const c=()=>{H(r),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.socket===a&&(r.socket=void 0)},d=h=>{c(),s.onClose(h)};n>0&&(r.connectTimer=setTimeout(()=>{if(r.connectTimer=void 0,r.socket===a){try{a.close()}catch{}d()}},n)),a.addEventListener("open",()=>{if(r.socket===a){r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.lastFrameAt=Date.now();try{s.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}Ir(r,o,d)}}),a.addEventListener("message",h=>{if(r.socket===a){r.lastFrameAt=Date.now();try{s.onMessage(h)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),a.addEventListener("close",h=>{r.socket===a&&d(h)}),a.addEventListener("error",()=>{r.socket===a&&d()})},Or=r=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:n}=r,o=t>0&&e>0;let a=0,c,d=!1,h=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},p=f=>{if(c!==void 0){if(!f){u();return}d||(d=!0,i()),s()}},m=()=>{h||(h=!0,n().then(p).finally(()=>{h=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{a+=1,!(!o||c!==void 0||a<e)&&(c=setInterval(m,t),i(),m())},noteOpen:()=>{a=0,u()},stop:u}},Rr=1e4,Se=async r=>{const e=new AbortController;let t;const s=new Promise((i,n)=>{t=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Rr)});try{return await Promise.race([r(e.signal),s])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(t)}},Ce=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Pr=r=>{if(r instanceof L)return!0;const e=r?.code;return e===void 0||Ce.has(e)||Qe.has(e)},ke=6e4,Fr=1e3,Hr={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},F=(r,e,t)=>{const s=Me(t),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${r.toString()}${e?` ${e}`:""})`;return r<400||r>=500||r===408?new L(n,i):new y(Hr[r]??"BAD_REQUEST",n,{data:i})},Z=(r,e=Math.random)=>{const t=Math.min(Fr*2**Math.max(r-1,0),ke);return Math.round(t*(.5+e()*.5))},Lr=r=>r instanceof L||Ce.has(r?.code??""),Mr=(r,e,t)=>{const s=De(r);return s!==void 0&&s>0?Math.min(s,ke):Lr(r)?Z(e,t):void 0},Ur=983040,Nr=r=>typeof TextEncoder>"u"?r.length:new TextEncoder().encode(r).length,we=new WeakSet,Ee=r=>{const e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${r instanceof Error?r.message:String(r)}`,{cause:r});return we.add(e),e},x=r=>r instanceof Error&&we.has(r),xr=r=>{const e=new Map;for(const t of r)typeof t.id=="number"&&ve(t.body)&&e.set(t.id,t.body);return e},Br=r=>{if(r===void 0)return{kind:"unanswered"};if("error"in r)return{error:Y(r),kind:"errored"};try{return{commitCursor:r.commitCursor,kind:"committed",value:k(r.result)}}catch(e){return{commitCursor:r.commitCursor,error:Ee(e),kind:"undecodable"}}},J=(r,e)=>`${l(r)}\0${e}`,Dr=(r,e)=>{for(const t of e)t.op==="delete"?r.delete(t.key):t.value!==void 0&&r.set(t.key,t.value)};class Qr{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){ge(this.buffers,this.maxBuffers),this.buffers.set(J(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(J(e,t.pokeId));if(!s)return;const i=[];try{for(const a of t.rowsPatch)i.push(a.value===void 0?a:{...a,value:k(a.value)})}catch(a){s.undecodable.set(t.shapeId,a);return}const n=s.parts.get(t.shapeId)??[];for(const a of i)n.push(a);s.parts.set(t.shapeId,n),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=J(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const Kr=(r,e,t)=>{const s=e.parts.get(r.id)??[],i=e.resets.has(r.id),n=e.bases.get(r.id),o=e.epoch!==void 0&&r.serverEpoch!==void 0&&e.epoch!==r.serverEpoch,a=n!==void 0&&r.serverCursor!==void 0&&r.serverCursor!==n;if(!i&&(o||a))return r.rows.clear(),r.serverCursor=void 0,r.serverEpoch=void 0,"reseed";i&&r.rows.clear(),Dr(r.rows,s),t.checkpoint!==void 0&&(r.serverCursor=t.checkpoint),t.epoch!==void 0&&(r.serverEpoch=t.epoch);const c=e.lastMutationId.get(r.id);return c!==void 0&&(r.lastMutationId=c),"applied"},be=r=>{const e=[...r.rows.values()];for(const t of r.callbacks)try{t(e)}catch{}},qr=(r,e)=>{for(const[t,s]of e.undecodable){const i=r.get(t);i&&A(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},ee=(r,e)=>{r.lastMutationId=Math.max(r.lastMutationId??0,e)},te=(r,e=!1)=>{for(const t of r.checkpointCallbacks)t({checkpoint:r.serverCursor,mutationId:r.lastMutationId,...e&&{rowsFollow:!0}})},Ae=(r,e,t)=>{r.serverBase=e,t.cursor!==void 0&&(r.serverCursor=t.cursor),t.epoch!==void 0&&(r.serverEpoch=t.epoch)},B=(r,e)=>r!==void 0&&r!==e,Wr=(r,e)=>e==="connected"&&r!=="connected"||e==="polling"&&r!=="connected"&&r!=="polling",jr=r=>{for(const e of r.activeSubscriptions())r.ensureSocket(e.shardKey),r.queueResubscribe(e);for(const e of r.queuedShardKeys())r.ensureSocket(e);r.broadcastStatus(r.computeStatus(),r.identityFingerprint())},$r=r=>{r.closeConnections();const e=r.leader;e.status=void 0,e.wasEverConnected=!1},Gr=(r,e,t)=>{if(B(t,r.identityFingerprint()))return;const s=r.leader,i=Wr(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),r.emitConnectionStatus(),i&&r.flushOfflineQueues()},Vr=r=>{r.isLeader()&&r.broadcastStatus(r.computeStatus(),r.identityFingerprint())},zr=(r,e,t,s,i,n)=>{if(B(n,r.identityFingerprint()))return;const o=r.subscription(e);o&&(r.dropCacheSeed(e),Ae(o,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&X(o,s),O(o,t))},Jr=(r,e,t,s)=>{if(B(s,r.identityFingerprint()))return;const i=r.subscription(e);i&&A(i.errorCallbacks,t)},Yr=(r,e,t,s,i,n,o)=>{if(B(o,r.identityFingerprint()))return;const a=r.subscription(e);a&&(r.ackAndAdvanceCursor(a,t,s),i!==void 0&&n===r.clientIdentifier()&&ee(a,i),te(a))},Xr=(r,e,t)=>r!==null||e&&t===null,Zr=[He],ei=Promise.resolve();class _e{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;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new v;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 I;statusListeners=new I;tokenExpiredListeners=new I;identityChangeListeners=new I;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new I;pendingChangeListeners=new I;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Qr(_e.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(pe(e.url),pt),this.wsToken=e.wsToken;const t=e.authBasePath??Ps;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??Le(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??pr,this.connectTimeoutMs=e.connectTimeoutMs??mr,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??yr,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Sr,this.defaultConnectionContext=e.connectionContext,this.persistence=Je(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ye(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new xe,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=ei),this.offlineQueue=new Ge(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${he()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=lt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,i=this.identityFingerprint(),n=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 d=this.identityFingerprint();d!==i&&(!s&&e!==null&&n?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!s&&e===null&&i===null&&n&&!a?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(c,e),Xr(i,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),s&&this.authTokenListeners.emit(e),(d!==i||s||o)&&this.offlineQueue.size>0&&z(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 n=s?.shardKey??"",o=this.identityFingerprint();let a,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:u=>{a=u}})}catch(u){if(!x(u))throw u;d=u}if(a!==void 0&&a>(this.clientWatermarks.get(o??"")?.get(n)??0)){let u=this.clientWatermarks.get(o??"");u===void 0&&(ge(this.clientWatermarks,wr),u=new Map,this.clientWatermarks.set(o??"",u)),u.set(n,a)}if(d!==void 0)throw d;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(w(this.url,`${this.authBasePath}${Fs}`),{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.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},n=this.connectionContextHolders.get(s);n?n.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 n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e);const a=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(t),this.ensureSocket(s.shardKey),a){const c=this.getConnection(s.shardKey);c&&g(c,{topic:e,type:"whisper_subscribe"})}return()=>{const c=this.whisperHandlers.get(i),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const h=this.getConnection(s.shardKey);h&&g(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(s.shardKey)}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey);i&&g(i,{data:E(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(s.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const o=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}const i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.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 Xe(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,oe(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=_(e,t,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=v.key(e,t,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:i}=await this.runMutation(e,t,s);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})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),o=t.length;let a=0,c=0,d=0;for(let h=0;h<o;h+=i){const u=t.slice(h,h+i),p=d,{committed:m}=await this.runMutation(e,n(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(p)}`},shardKey:s.shardKey});d+=1,a+=u.length,m&&(c+=u.length),s.onProgress?.({done:a,total:o})}return{chunks:d,imported:c,queued:a-c}}async shardTraffic(e){return Vs(this.adminHost,e)}async listScheduledJobs(){return Ys(this.adminHost)}async schedulerStatus(){return Xs(this.adminHost)}async cancelScheduledJob(e){return Zs(this.adminHost,e)}async listDeadJobs(){return er(this.adminHost)}async retryDeadJob(e){return tr(this.adminHost,e)}async removeDeadJob(e){return sr(this.adminHost,e)}async listWorkflowInstances(e){return rr(this.adminHost,e)}async getWorkflowInstance(e){return ir(this.adminHost,e)}async setWorkflowInstanceStatus(e){return nr(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=w(pe(this.url),bt),s=ue(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,o=!1;const a=()=>{o||this.closed||(n=setTimeout(h,s.next()))},c=p=>{if(o||this.WebSocketImpl===void 0)return;const m=p===void 0?t:`${t}?token=${encodeURIComponent(p)}`;ye(i,m,this.managedSocketOptions,{onClose:()=>{a()},onMessage:f=>{let b;try{b=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(T=>ne(T))))}})},d=async p=>{let m;try{m=await p()}catch{a();return}c(m)},h=()=>{if(o||this.WebSocketImpl===void 0)return;const{wsToken:p}=this;if(typeof p=="function"){d(p).catch(()=>{});return}c(p)};h();const u=()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i),i.socket?.close(),i.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return Ls(this.adminHost)}async getCronJobs(){return Ms(this.adminHost)}async runCronJob(e){return Us(this.adminHost,e)}async fetchOpenApi(){return Ns(this.adminHost)}async fetchArchitecture(){return xs(this.adminHost)}async fetchOpenRpc(){return Bs(this.adminHost)}async listStorageObjects(e={}){return ar(this.adminHost,e)}async deleteStorageObject(e,t){return or(this.adminHost,e,t)}async listStorageBuckets(){return cr(this.adminHost)}async uploadStorageObject(e){return dr(this.adminHost,e)}async signedStorageUrl(e,t){return hr(this.adminHost,e,t)}async listGlobalTables(){return Ds(this.adminHost)}async readGlobalTablePage(e){return Qs(this.adminHost,e)}async facetGlobalColumn(e){return Ks(this.adminHost,e)}async listVectorIndexes(){return ur(this.adminHost)}async queryVectorIndex(e){return lr(this.adminHost,e)}async queryLogArchive(e={}){return zs(this.adminHost,e)}async listKvNamespaces(){return qs(this.adminHost)}async listKvKeys(e){return Ws(this.adminHost,e)}async getKvValue(e){return js(this.adminHost,e)}async putKvValue(e){return $s(this.adminHost,e)}async deleteKvKey(e){return Gs(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=S(Qt,{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(qt,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(Wt,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(jt,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch($t,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Gt,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Vt,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(zt,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(Jt,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Yt,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Xt,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(Zt,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(S(es,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(ts,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(S(ss,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(rs,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(is,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(S(ns,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=S(as,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=S(os,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=S(us,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(ls,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(fs,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(cs,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(ds,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(hs,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ps,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ms,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(ys,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(bs,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(gs,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=S(Ts,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Cs,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(ks,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=S(ws,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Es,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(As,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=S(_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(Is,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Os,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Rs,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=S(Kt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,i={}){this.assertOpen();const n=t??{},o=v.key(e.__lunoraRef,n,i.shardKey);let a=this.subscriptions.get(o);const c=j(s),d=j(i.onError),h=j(i.onCheckpoint);if(!a){this.nextSubId+=1;const p=`sub_${this.nextSubId.toString()}`,m=oe(n),f=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);a={acked:!1,args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:p,lastValue:f?.value,optimisticLayers:[],serverBase:f?.value,serverCursor:f?.serverCursor,shardKey:i.shardKey,wireArgs:E(n,`args for '${e.__lunoraRef}'`),...f?.serverEpoch===void 0?{}:{serverEpoch:f.serverEpoch}},this.subscriptions.add(a),f!==void 0&&this.cacheSeededQueries.set(o,f)}if(a.callbacks.add(c),d&&a.errorCallbacks.add(d),h&&a.checkpointCallbacks.add(h),a.lastValue!==void 0)try{c(a.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(c),d&&u.errorCallbacks.delete(d),h&&u.checkpointCallbacks.delete(h),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(v.keyOf(u)),this.subscriptions.remove(u),this.releaseIdleShard(u.shardKey))}}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()}`,n={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,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}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:n}=s,o=t??{},{handle:a,iterable:c}=Ze({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,n)}});this.ensureSocket(n);const d=this.getConnection(n),h={id:i,query:{args:E(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:h,shardKey:n};this.streams.set(i,u);const p=d?.wsState==="open"&&g(d,h);if(!p&&d===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(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=vr;){const f=d.pendingStreams.shift()?.id,b=f?this.streams.get(f):void 0;b&&(b.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(h)}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 Ke(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.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())},Tr))}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,n]of this.streams)l(n.shardKey)===t&&(n.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={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,n)=>{this.ackAndAdvanceCursor(s,i,n)},subscription:s=>this.subscriptions.get(s)};return new Be({channelName:e,onBecomeLeader:()=>{jr(t)},onStopBeingLeader:()=>{$r(t)},onConnectionStatus:(s,i)=>{Gr(t,s,i)},onSubscriptionData:(s,i,n,o,a)=>{zr(t,s,i,n,o,a)},onLeaderClaimAnswered:()=>{Vr(t)},onSubscriptionError:(s,i,n)=>{Jr(t,s,i,n)},onSubscriptionSettled:(s,i,n,o,a,c)=>{Yr(t,s,i,n,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(w(this.url,G),{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 n;try{n=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const o=N(n);if(!s.ok||o!==void 0&&!n.results)throw o!==void 0?Ue(o):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of n.results??[]){const c=a.body?.commitCursor;typeof a.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[a.id]?.shardKey,c)}return fr(n.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const i=t,n=s.mutationId??he(),o=this.takeReplayCredential(s.replayCredential),a=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:c,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,d,c);const h=this.offlineFlushes.get(l(s.shardKey));h!==void 0&&await h;const{hasSocket:u,idleClosed:p,polling:m,wasEverConnected:f,wsState:b}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:T}=this.offlineQueue,U=f||T,D=this.WebSocketImpl!==void 0&&U,Q=m||p,Ie=b==="connecting"&&U&&!Q,Oe=b!=="open"&&!u&&D&&!Q,Re=D&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),ae=async()=>this.enqueueOfflineMutation(e,i,s.shardKey,a,n,d,c,s.precondition,s.mutationId,o?.stamp);if(Oe||Ie||Re)return ae();let K;try{const R=await this.rpc(e.__lunoraRef,i,s.shardKey,{baselineSeq:a,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:q=>{K=q}});for(const q of c)q(K);return{committed:!0,value:R}}catch(R){if(Q&&D&&R instanceof TypeError&&me(i))return ae();throw this.settleFailedDirectWrite(R,K,c,d,o?.flags.authToken),R}}settleFailedDirectWrite(e,t,s,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),x(e)){for(const o of s)o(t);return}P(i)}async enqueueOfflineMutation(e,t,s,i,n,o,a,c,d,h){const u=h===void 0?this.identityFingerprint():h;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:d??`${this.clientId}:${String(m)}`,identity:u,mutationId:m,...o.length>0&&{onRejected:()=>{P(o)}},shardKey:s})}catch(f){throw P(o),f instanceof Error?f:new Error(String(f))}for(const f of a)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,f)=>{const b={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:u,precondition:c,onCommit:T=>{for(const U of a)U(T)},reject:T=>{this.queuedIdentities.delete(n),x(T)||P(o),f(T instanceof Error?T:new Error(String(T))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(b),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),b.id!==void 0&&this.queuedIdentities.set(b.id,u)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(_(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(Ve(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const n=t.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,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(_(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),O(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,O(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=_(e,t,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=_(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=_(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:t,...n===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(()=>{})},br))}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)))}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}async pollSubscriptions(e){const t=l(e),s=[];for(const a of this.subscriptions.all())l(a.shardKey)===t&&(me(a.args)?s.push(a):A(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=$e(),n=this.identityFingerprint();let o;try{o=await Se(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()!==n)return!0;for(const[a,c]of s.entries()){const d=o[a];if(d!==void 0){if(!d.ok){A(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:M(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Se(async t=>e(w(this.url,G),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,i){const n=[],o=[];if(!i)return{confirms:n,rollbacks:o};const a=v.key(e,t,s),c=this.subscriptions.get(a);if(c){const d=qe(c,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,t,s,i,n){const{confirms:o,rollbacks:a,store:c}=We(this.subscriptions,s);try{e(c,t)}catch{P(a);return}i.push(...a),n.push(...o)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!g(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:Or({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ue(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[rt]=it(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(s.authorization=`Bearer ${n}`),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={}){if(!this.fetchImpl)throw new L("LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,a=await this.fetchImpl(w(this.url,ft),{body:JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){const u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{throw F(a.status,a.statusText,a.headers.get("retry-after"))}const d=c;if(typeof d!="object"||d===null||Array.isArray(d))throw F(a.status,a.statusText,a.headers.get("retry-after"));const h=N(c);if(h!==void 0)throw ce(h,a.headers.get("retry-after"));if(!a.ok)throw F(a.status,a.statusText,a.headers.get("retry-after"));i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor);try{return k(c.result)}catch(u){throw Ee(u)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.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&&(n["content-type"]=i)):(a=JSON.stringify(s),n["content-type"]="application/json");const c=await this.fetchImpl(w(this.url,e),{body:a,headers:n,method:t});let d;try{d=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const h=N(d);if(h!==void 0){const u=new Error(h.message??"admin request failed");throw u.code=h.code,u}if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${u})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));g(e,{caps:Zr,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,i)}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,ye(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.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},gr),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const n of this.subscriptions.all())l(n.shardKey)===l(t)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:o,type:a}of n)g(e,{id:o,type:a});this.releaseIdleShard(t)}Er(e);const i=this.whisperHandlers.get(l(t));if(i)for(const n of i.keys())g(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),g(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",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,n]of this.streams)if(!(l(n.shardKey)!==l(e.shardKey)||t.has(i))){if(n.durable){const o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==i),o];continue}n.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){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Cr;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},kr))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return g(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&g(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=_r(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 n=this.getConnection(t);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{const n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,generation:o,id:a,seq:c}=i,d=this.streams.get(a);d&&typeof c=="number"&&(d.lastSeq=c,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(k(n));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);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}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(Ne(e)),this.forgetStream(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){const a=de(e),c=this.identityFingerprint(),d=v.keyOf(n);A(n.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,a,c);return}const o=s===void 0?void 0:this.shapeSubscriptions.get(s);o&&A(o.errorCallbacks,de(e))}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){qr(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&!s.undecodable.has(i)&&this.applyPokePart(n,s,e)}}}applyPokePart(e,t,s){const i=Kr(e,t,s);if(be(e),i==="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,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)return;let n;try{n=Pe(e,i.serverBase)}catch(o){A(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(n===Fe){this.resnapshotSubscription(i);return}if(this.dropCacheSeed(v.keyOf(i)),Ae(i,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(ee(i,e.lastMutationId),te(i,!0)),this.persistQueryValue(i),X(i,i.serverCursor),t!==void 0&&je(i,t),O(i,n),this.tabCoordinator?.isLeader()){const o=v.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,n,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&&ee(t,e.lastMutationId),te(t),this.tabCoordinator?.isLeader())){const s=v.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),X(e,e.serverCursor)&&O(e,e.serverBase))}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const i=k(e.data);for(const n of s)try{n(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,A(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ze(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let i=0;i<e.length;i+=1){const n=e.charCodeAt(i);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}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&&z(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject: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 n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}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 n=t??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,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.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,O(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,be(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const i=(async()=>{await(s??Promise.resolve());const{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&z(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 h of s){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",u)}const i=l(e),n=this.offlineQueue.drain(h=>l(h.shardKey)===i);if(n.length===0)return;const o=[],a=[];for(const h of n){const u=this.replayGateVerdict(h);u==="send"?o.push(h):u==="hold"&&a.push(h)}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 d=[];for(let h=0;h<c.length;h+=$){const u=c.slice(h,h+$),p=await this.replayBatched(u,e,t);if(d.push(...p.requeue),p.stop){d.push(...c.slice(h+$));break}}d.length>0&&this.offlineQueue.requeue(d),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,Z(i))})}noteReplayRetryDelay(e,t,s){const i=l(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,a=Mr(t,o)??(s===null&&W(t)?Z(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:a===void 0?n?.delayMs:Math.max(n?.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 n=this.replayRetryTimers.get(t);n!==void 0&&clearTimeout(n),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)||Pr(e)}noteReplayAuthRefusal(e,t){if(!W(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,...V(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const n=e[i];if(!n)continue;let o;try{const a=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:s,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...V(n.identity,s),mutationId:n.id,onCommitCursor:c=>{o=c}});this.settleReplaySuccess(n,a,o)}catch(a){if(x(a)){this.settleReplayUndecodable(n,a,o);continue}if(!this.shouldRequeueReplayFailure(a,s)){this.settleReplayTerminal(n,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&&Nr(i)>Ur)return await this.replayBatchedHalves(e,t,s);let n;try{n=await this.fetchImpl(w(this.url,G),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...V(e.find(d=>d.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let a;const c=n.headers.get("retry-after");try{a=await n.json()}catch{return this.settleWholeBatchError(e,F(n.status,n.statusText,c),t,s)}if(!a.results){const d=N(a),h=d===void 0?F(n.status,n.statusText,c):ce(d,c);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 L||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:e,stop:!0};for(const n of e)this.settleReplayTerminal(n,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),t,s);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};const o=await this.replayBatched(e.slice(i),t,s);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,t,s,i){const n=xr(t),o=[];let a=!1,c=!1;for(const[d,h]of e.entries()){const u=Br(n.get(d));switch(u.kind){case"committed":{a=!0,this.settleReplaySuccess(h,u.value,u.commitCursor);break}case"errored":{c||=W(u.error),this.shouldRequeueReplayFailure(u.error,i)?(this.noteReplayRetryDelay(s,u.error,i),o.push(h)):this.settleReplayTerminal(h,u.error);break}case"unanswered":{o.push(h);break}default:a=!0,this.settleReplayUndecodable(h,u.error,u.commitCursor)}}return a&&!c&&this.noteCredentialAccepted(i),o}}export{_e as LunoraClient};
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{encodeWire as M,decodeWire as k,stableWireKey as oe}from"@lunora/wire";import{r as Pe,U as Fe,P as He}from"./delta-merge-Ls3DED4g.mjs";import Le from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as Y,a as Me,e as N,r as Ue,b as ce,c as Ne,d as de}from"./wire-errors-WYlbE1Nh.mjs";import{ClientQueryStore as xe}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as Be}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as L,getRetryAfterMs as De,AUTH_REPLAY_ERROR_CODES as Qe,isAuthReplayFailure as W}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Ke}from"./httpStream-BhSpxRWB.mjs";import{d as X,r as O,a as P,b as qe,c as We,e as je,f as $e}from"./local-store-fqWV2n_Z.mjs";import{O as Ge,n as he,i as Ve,r as ze}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as Je}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Ye,queryCacheKey as _}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as ue}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as A,SubscriptionRegistry as v,wrapSubscriber as j}from"./SubscriptionRegistry-DKIXE7M7.mjs";import Xe from"./createSnapshotPrecondition-CLkxVeN1.mjs";import{createStream as Ze}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const $=500,ge=(r,e)=>{if(r.size<e)return;const t=r.keys().next().value;t!==void 0&&r.delete(t)},C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",et=r=>{let e="",t=0;const s=r.length-2;for(;t<s;t+=3){const n=r[t]<<16|r[t+1]<<8|r[t+2];e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)+C.charAt(n>>6&63)+C.charAt(n&63)}const i=r.length-t;if(i===1){const n=r[t]<<16;e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)}else if(i===2){const n=r[t]<<16|r[t+1]<<8;e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)+C.charAt(n>>6&63)}return e};new TextDecoder;const tt=new TextEncoder,st=r=>et(tt.encode(JSON.stringify(r))),rt="x-lunora-expect-subject",it=r=>st({subject:r}),le=Symbol.for("lunora:session-change"),nt="lunora:session-change",at="better-auth.message",ot="signout",Te=()=>{const r=globalThis;let e=r[le];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},r[le]=e),e},ct=()=>"document"in globalThis,dt=async()=>{const r=[];for(const e of Te().listeners)try{r.push(e())}catch{}await Promise.allSettled(r)},ht=(r,e)=>{if(r!==at||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===ot}catch{return!1}},ut=r=>{const e=[],t=()=>{dt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(nt):void 0}catch{s=void 0}if(s!==void 0){const n=s;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==r&&t()}),e.push(()=>{n.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const n=o=>{ht(o.key,o.newValue)&&t()};i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(const n of e)n()}},lt=r=>{const e=Te();return e.listeners.add(r),e.detach===void 0&&ct()&&(e.detach=ut(e.tab)),()=>{e.listeners.delete(r),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},ft="/_lunora/rpc",G="/_lunora/rpc-batch",pt="/_lunora/ws",mt="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",St="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",gt="/_lunora/admin/scheduled/cancel",fe="/_lunora/admin/scheduled/dead",Tt="/_lunora/admin/scheduled/dead/retry",vt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",kt="/_lunora/admin/workflows/instance",wt="/_lunora/admin/workflows/status",se="/_lunora/admin/storage",Et="/_lunora/admin/storage/url",At="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",It="/_lunora/admin/cron-jobs",Ot="/_lunora/admin/cron-jobs/run",Rt="/_lunora/admin/architecture",Pt="/_lunora/admin/openapi",Ft="/_lunora/admin/openrpc",Ht="/_lunora/admin/global/tables",Lt="/_lunora/admin/global/table",Mt="/_lunora/admin/global/facet",Ut="/_lunora/admin/vector/indexes",Nt="/_lunora/admin/vector/query",xt="/_lunora/admin/logs/archive",Bt="/_lunora/admin/kv/namespaces",Dt="/_lunora/admin/kv/keys",re="/_lunora/admin/kv/value",Qt="/_lunora/admin/auth/users",Kt="/_lunora/admin/auth/sessions",qt="/_lunora/admin/auth/users/create",Wt="/_lunora/admin/auth/users/role",jt="/_lunora/admin/auth/users/ban",$t="/_lunora/admin/auth/users/unban",Gt="/_lunora/admin/auth/users/password",Vt="/_lunora/admin/auth/users/remove",zt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Yt="/_lunora/admin/auth/sessions/revoke-all",Xt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",es="/_lunora/admin/auth/accounts",ts="/_lunora/admin/auth/accounts/unlink",ss="/_lunora/admin/auth/passkeys",rs="/_lunora/admin/auth/passkeys/delete",is="/_lunora/admin/auth/two-factor/disable",ns="/_lunora/admin/auth/organizations",as="/_lunora/admin/auth/organizations/members",os="/_lunora/admin/auth/organizations/invitations",cs="/_lunora/admin/auth/organizations/members/remove",ds="/_lunora/admin/auth/organizations/invitations/cancel",hs="/_lunora/admin/auth/config",us="/_lunora/admin/auth/sign-up-invitations",ls="/_lunora/admin/auth/sign-up-invitations/create",fs="/_lunora/admin/auth/sign-up-invitations/revoke",ps="/_lunora/admin/auth/organizations/create",ms="/_lunora/admin/auth/organizations/update",ys="/_lunora/admin/auth/organizations/remove",Ss="/_lunora/admin/auth/organizations/members/add",bs="/_lunora/admin/auth/organizations/members/invite",gs="/_lunora/admin/auth/organizations/members/role",Ts="/_lunora/admin/auth/organizations/teams",vs="/_lunora/admin/auth/organizations/teams/create",Cs="/_lunora/admin/auth/organizations/teams/update",ks="/_lunora/admin/auth/organizations/teams/remove",ws="/_lunora/admin/auth/organizations/teams/members",Es="/_lunora/admin/auth/organizations/teams/members/add",As="/_lunora/admin/auth/organizations/teams/members/remove",_s="/_lunora/admin/auth/organizations/roles",Is="/_lunora/admin/auth/organizations/roles/create",Os="/_lunora/admin/auth/organizations/roles/update",Rs="/_lunora/admin/auth/organizations/roles/remove",Ps="/api/auth",Fs="/get-session",Hs="lunora-ping",Ls=async r=>(r.assertOpen(),(await r.adminFetch(_t,"GET")).functions??[]),Ms=async r=>(r.assertOpen(),(await r.adminFetch(It,"GET")).jobs??[]),Us=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(Ot,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},Ns=async r=>(r.assertOpen(),await r.adminFetch(Pt,"GET")),xs=async r=>(r.assertOpen(),await r.adminFetch(Rt,"GET")),Bs=async r=>(r.assertOpen(),await r.adminFetch(Ft,"GET")),Ds=async r=>(r.assertOpen(),await r.adminFetch(Ht,"GET")),Qs=async(r,e)=>{r.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(M(e.filters))),k(await r.adminFetch(`${Lt}?${t.toString()}`,"GET"))},Ks=async(r,e)=>{r.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(M(e.filters))),k(await r.adminFetch(`${Mt}?${t.toString()}`,"GET"))},ie=r=>r===void 0||r===""?"":`&bucket=${encodeURIComponent(r)}`,pe=r=>r.startsWith("https://")?`wss://${r.slice(8)}`:r.startsWith("http://")?`ws://${r.slice(7)}`:r,w=(r,e)=>`${r.endsWith("/")?r.slice(0,-1):r}${e}`,S=(r,e)=>{const t=new URLSearchParams;for(const[i,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(i,String(n));const s=t.toString();return s===""?r:`${r}?${s}`},qs=async r=>(r.assertOpen(),(await r.adminFetch(Bt,"GET")).namespaces??[]),Ws=async(r,e)=>{r.assertOpen();const t=S(Dt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await r.adminFetch(t,"GET")},js=async(r,e)=>{r.assertOpen();const t=S(re,{key:e.key,namespace:e.namespace});return await r.adminFetch(t,"GET")},$s=async(r,e)=>{r.assertOpen(),await r.adminFetch(re,"PUT",e)},Gs=async(r,e)=>{r.assertOpen();const t=S(re,{key:e.key,namespace:e.namespace});await r.adminFetch(t,"DELETE")},Vs=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(mt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},zs=async(r,e={})=>{r.assertOpen();const t=await r.adminFetch(xt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},Js=async r=>{const e=[];let t;for(;;){const s=await r(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}},ne=r=>"args"in r?{...r,args:k(r.args)}:r,Ys=async r=>(r.assertOpen(),((await r.adminFetch(yt,"GET")).records??[]).map(t=>ne(t))),Xs=async r=>{r.assertOpen();const e=await r.adminFetch(St,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},Zs=async(r,e)=>(r.assertOpen(),{cancelled:(await r.adminFetch(gt,"POST",{id:e})).cancelled===!0}),er=async r=>(r.assertOpen(),(await Js(async t=>await r.adminFetch(t===void 0?fe:`${fe}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>ne(t))),tr=async(r,e)=>(r.assertOpen(),{retried:(await r.adminFetch(Tt,"POST",{id:e})).retried===!0}),sr=async(r,e)=>(r.assertOpen(),{removed:(await r.adminFetch(vt,"POST",{id:e})).removed===!0}),rr=async(r,e)=>{r.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 r.adminFetch(`${Ct}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},ir=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await r.adminFetch(`${kt}?${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??[]}},nr=async(r,e)=>(r.assertOpen(),{status:(await r.adminFetch(wt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),ar=async(r,e={})=>{r.assertOpen();const t=S(se,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await r.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},or=async(r,e,t)=>{r.assertOpen();const s=`${se}?key=${encodeURIComponent(e)}${ie(t?.bucket)}`,i=await r.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},cr=async r=>(r.assertOpen(),(await r.adminFetch(At,"GET")).buckets??[]),dr=async(r,e)=>{r.assertOpen();const t=`${se}?key=${encodeURIComponent(e.key)}${ie(e.bucket)}`,s=await r.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},hr=async(r,e,t)=>{r.assertOpen();const s=t?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Et}?key=${encodeURIComponent(e)}${i}${ie(t?.bucket)}`,o=await r.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},ur=async r=>(r.assertOpen(),(await r.adminFetch(Ut,"GET")).indexes??[]),lr=async(r,e)=>(r.assertOpen(),(await r.adminFetch(Nt,"POST",e)).matches??[]),E=(r,e)=>{try{return M(r)}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)}},me=r=>{try{return M(r),!0}catch{return!1}},ve=r=>r!==null&&typeof r=="object"&&("error"in r||"result"in r),fr=(r,e)=>{const t=Array.from({length:e});for(const s of r){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!ve(s.body)){t[s.id]={error:Y({}),ok:!1};continue}const i=s.body;t[s.id]="error"in i?{error:Y(i),ok:!1}:{ok:!0,value:k(i.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},V=(r,e)=>e!==null?{}:r===null?{expectSubject:null}:r?.startsWith("subj:")===!0?{expectSubject:r.slice(5)}:{},pr=3e4,mr=1e4,yr=5e3,Sr=3,br=250,gr=5e3,Tr=5e3,vr=64,Cr=3,kr=1e4,wr=8,z=r=>r==="connected"||r==="polling",l=r=>r??"",g=(r,e)=>{if(!r.socket||r.wsState!=="open")return!1;try{return r.socket.send(JSON.stringify(e)),!0}catch{return!1}},Er=r=>{if(!r.pendingStreams||r.pendingStreams.length===0)return;const e=r.pendingStreams;r.pendingStreams=[];for(const t of e)g(r,t)},Ar=new TextDecoder,_r=r=>{if(typeof r=="string")return r;if(r instanceof ArrayBuffer)return Ar.decode(r)};class I{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const H=r=>{r.heartbeatTimer!==void 0&&(clearInterval(r.heartbeatTimer),r.heartbeatTimer=void 0)},Ir=(r,e,t)=>{H(r),!(e<=0)&&(r.heartbeatTimer=setInterval(()=>{if(!r.socket)return;const{socket:s}=r;if(Date.now()-r.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Hs)}catch{}},e))},ye=(r,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=t;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const a=new i(e);r.socket=a;const c=()=>{H(r),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.socket===a&&(r.socket=void 0)},d=h=>{c(),s.onClose(h)};n>0&&(r.connectTimer=setTimeout(()=>{if(r.connectTimer=void 0,r.socket===a){try{a.close()}catch{}d()}},n)),a.addEventListener("open",()=>{if(r.socket===a){r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.lastFrameAt=Date.now();try{s.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}Ir(r,o,d)}}),a.addEventListener("message",h=>{if(r.socket===a){r.lastFrameAt=Date.now();try{s.onMessage(h)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),a.addEventListener("close",h=>{r.socket===a&&d(h)}),a.addEventListener("error",()=>{r.socket===a&&d()})},Or=r=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:n}=r,o=t>0&&e>0;let a=0,c,d=!1,h=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},p=f=>{if(c!==void 0){if(!f){u();return}d||(d=!0,i()),s()}},m=()=>{h||(h=!0,n().then(p).finally(()=>{h=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{a+=1,!(!o||c!==void 0||a<e)&&(c=setInterval(m,t),i(),m())},noteOpen:()=>{a=0,u()},stop:u}},Rr=1e4,Se=async r=>{const e=new AbortController;let t;const s=new Promise((i,n)=>{t=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Rr)});try{return await Promise.race([r(e.signal),s])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(t)}},Ce=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Pr=r=>{if(r instanceof L)return!0;const e=r?.code;return e===void 0||Ce.has(e)||Qe.has(e)},ke=6e4,Fr=1e3,Hr={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},F=(r,e,t)=>{const s=Me(t),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${r.toString()}${e?` ${e}`:""})`;return r<400||r>=500||r===408?new L(n,i):new y(Hr[r]??"BAD_REQUEST",n,{data:i})},Z=(r,e=Math.random)=>{const t=Math.min(Fr*2**Math.max(r-1,0),ke);return Math.round(t*(.5+e()*.5))},Lr=r=>r instanceof L||Ce.has(r?.code??""),Mr=(r,e,t)=>{const s=De(r);return s!==void 0&&s>0?Math.min(s,ke):Lr(r)?Z(e,t):void 0},Ur=983040,Nr=r=>typeof TextEncoder>"u"?r.length:new TextEncoder().encode(r).length,we=new WeakSet,Ee=r=>{const e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${r instanceof Error?r.message:String(r)}`,{cause:r});return we.add(e),e},x=r=>r instanceof Error&&we.has(r),xr=r=>{const e=new Map;for(const t of r)typeof t.id=="number"&&ve(t.body)&&e.set(t.id,t.body);return e},Br=r=>{if(r===void 0)return{kind:"unanswered"};if("error"in r)return{error:Y(r),kind:"errored"};try{return{commitCursor:r.commitCursor,kind:"committed",value:k(r.result)}}catch(e){return{commitCursor:r.commitCursor,error:Ee(e),kind:"undecodable"}}},J=(r,e)=>`${l(r)}\0${e}`,Dr=(r,e)=>{for(const t of e)t.op==="delete"?r.delete(t.key):t.value!==void 0&&r.set(t.key,t.value)};class Qr{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){ge(this.buffers,this.maxBuffers),this.buffers.set(J(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(J(e,t.pokeId));if(!s)return;const i=[];try{for(const a of t.rowsPatch)i.push(a.value===void 0?a:{...a,value:k(a.value)})}catch(a){s.undecodable.set(t.shapeId,a);return}const n=s.parts.get(t.shapeId)??[];for(const a of i)n.push(a);s.parts.set(t.shapeId,n),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=J(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const Kr=(r,e,t)=>{const s=e.parts.get(r.id)??[],i=e.resets.has(r.id),n=e.bases.get(r.id),o=e.epoch!==void 0&&r.serverEpoch!==void 0&&e.epoch!==r.serverEpoch,a=n!==void 0&&r.serverCursor!==void 0&&r.serverCursor!==n;if(!i&&(o||a))return r.rows.clear(),r.serverCursor=void 0,r.serverEpoch=void 0,"reseed";i&&r.rows.clear(),Dr(r.rows,s),t.checkpoint!==void 0&&(r.serverCursor=t.checkpoint),t.epoch!==void 0&&(r.serverEpoch=t.epoch);const c=e.lastMutationId.get(r.id);return c!==void 0&&(r.lastMutationId=c),"applied"},be=r=>{const e=[...r.rows.values()];for(const t of r.callbacks)try{t(e)}catch{}},qr=(r,e)=>{for(const[t,s]of e.undecodable){const i=r.get(t);i&&A(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},ee=(r,e)=>{r.lastMutationId=Math.max(r.lastMutationId??0,e)},te=(r,e=!1)=>{for(const t of r.checkpointCallbacks)t({checkpoint:r.serverCursor,mutationId:r.lastMutationId,...e&&{rowsFollow:!0}})},Ae=(r,e,t)=>{r.serverBase=e,t.cursor!==void 0&&(r.serverCursor=t.cursor),t.epoch!==void 0&&(r.serverEpoch=t.epoch)},B=(r,e)=>r!==void 0&&r!==e,Wr=(r,e)=>e==="connected"&&r!=="connected"||e==="polling"&&r!=="connected"&&r!=="polling",jr=r=>{for(const e of r.activeSubscriptions())r.ensureSocket(e.shardKey),r.queueResubscribe(e);for(const e of r.queuedShardKeys())r.ensureSocket(e);r.broadcastStatus(r.computeStatus(),r.identityFingerprint())},$r=r=>{r.closeConnections();const e=r.leader;e.status=void 0,e.wasEverConnected=!1},Gr=(r,e,t)=>{if(B(t,r.identityFingerprint()))return;const s=r.leader,i=Wr(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),r.emitConnectionStatus(),i&&r.flushOfflineQueues()},Vr=r=>{r.isLeader()&&r.broadcastStatus(r.computeStatus(),r.identityFingerprint())},zr=(r,e,t,s,i,n)=>{if(B(n,r.identityFingerprint()))return;const o=r.subscription(e);o&&(r.dropCacheSeed(e),Ae(o,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&X(o,s),O(o,t))},Jr=(r,e,t,s)=>{if(B(s,r.identityFingerprint()))return;const i=r.subscription(e);i&&A(i.errorCallbacks,t)},Yr=(r,e,t,s,i,n,o)=>{if(B(o,r.identityFingerprint()))return;const a=r.subscription(e);a&&(r.ackAndAdvanceCursor(a,t,s),i!==void 0&&n===r.clientIdentifier()&&ee(a,i),te(a))},Xr=(r,e,t)=>r!==null||e&&t===null,Zr=[He],ei=Promise.resolve();class _e{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;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new v;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 I;statusListeners=new I;tokenExpiredListeners=new I;identityChangeListeners=new I;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new I;pendingChangeListeners=new I;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Qr(_e.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(pe(e.url),pt),this.wsToken=e.wsToken;const t=e.authBasePath??Ps;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??Le(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??pr,this.connectTimeoutMs=e.connectTimeoutMs??mr,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??yr,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Sr,this.defaultConnectionContext=e.connectionContext,this.persistence=Je(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ye(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new xe,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=ei),this.offlineQueue=new Ge(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${he()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=lt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,i=this.identityFingerprint(),n=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 d=this.identityFingerprint();d!==i&&(!s&&e!==null&&n?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!s&&e===null&&i===null&&n&&!a?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(c,e),Xr(i,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),s&&this.authTokenListeners.emit(e),(d!==i||s||o)&&this.offlineQueue.size>0&&z(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 n=s?.shardKey??"",o=this.identityFingerprint();let a,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:u=>{a=u}})}catch(u){if(!x(u))throw u;d=u}if(a!==void 0&&a>(this.clientWatermarks.get(o??"")?.get(n)??0)){let u=this.clientWatermarks.get(o??"");u===void 0&&(ge(this.clientWatermarks,wr),u=new Map,this.clientWatermarks.set(o??"",u)),u.set(n,a)}if(d!==void 0)throw d;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(w(this.url,`${this.authBasePath}${Fs}`),{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.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},n=this.connectionContextHolders.get(s);n?n.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 n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e);const a=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(t),this.ensureSocket(s.shardKey),a){const c=this.getConnection(s.shardKey);c&&g(c,{topic:e,type:"whisper_subscribe"})}return()=>{const c=this.whisperHandlers.get(i),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const h=this.getConnection(s.shardKey);h&&g(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(s.shardKey)}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey);i&&g(i,{data:E(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(s.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const o=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}const i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.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 Xe(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,oe(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=_(e,t,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=v.key(e,t,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:i}=await this.runMutation(e,t,s);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})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),o=t.length;let a=0,c=0,d=0;for(let h=0;h<o;h+=i){const u=t.slice(h,h+i),p=d,{committed:m}=await this.runMutation(e,n(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(p)}`},shardKey:s.shardKey});d+=1,a+=u.length,m&&(c+=u.length),s.onProgress?.({done:a,total:o})}return{chunks:d,imported:c,queued:a-c}}async shardTraffic(e){return Vs(this.adminHost,e)}async listScheduledJobs(){return Ys(this.adminHost)}async schedulerStatus(){return Xs(this.adminHost)}async cancelScheduledJob(e){return Zs(this.adminHost,e)}async listDeadJobs(){return er(this.adminHost)}async retryDeadJob(e){return tr(this.adminHost,e)}async removeDeadJob(e){return sr(this.adminHost,e)}async listWorkflowInstances(e){return rr(this.adminHost,e)}async getWorkflowInstance(e){return ir(this.adminHost,e)}async setWorkflowInstanceStatus(e){return nr(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=w(pe(this.url),bt),s=ue(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,o=!1;const a=()=>{o||this.closed||(n=setTimeout(h,s.next()))},c=p=>{if(o||this.WebSocketImpl===void 0)return;const m=p===void 0?t:`${t}?token=${encodeURIComponent(p)}`;ye(i,m,this.managedSocketOptions,{onClose:()=>{a()},onMessage:f=>{let b;try{b=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(T=>ne(T))))}})},d=async p=>{let m;try{m=await p()}catch{a();return}c(m)},h=()=>{if(o||this.WebSocketImpl===void 0)return;const{wsToken:p}=this;if(typeof p=="function"){d(p).catch(()=>{});return}c(p)};h();const u=()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i),i.socket?.close(),i.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return Ls(this.adminHost)}async getCronJobs(){return Ms(this.adminHost)}async runCronJob(e){return Us(this.adminHost,e)}async fetchOpenApi(){return Ns(this.adminHost)}async fetchArchitecture(){return xs(this.adminHost)}async fetchOpenRpc(){return Bs(this.adminHost)}async listStorageObjects(e={}){return ar(this.adminHost,e)}async deleteStorageObject(e,t){return or(this.adminHost,e,t)}async listStorageBuckets(){return cr(this.adminHost)}async uploadStorageObject(e){return dr(this.adminHost,e)}async signedStorageUrl(e,t){return hr(this.adminHost,e,t)}async listGlobalTables(){return Ds(this.adminHost)}async readGlobalTablePage(e){return Qs(this.adminHost,e)}async facetGlobalColumn(e){return Ks(this.adminHost,e)}async listVectorIndexes(){return ur(this.adminHost)}async queryVectorIndex(e){return lr(this.adminHost,e)}async queryLogArchive(e={}){return zs(this.adminHost,e)}async listKvNamespaces(){return qs(this.adminHost)}async listKvKeys(e){return Ws(this.adminHost,e)}async getKvValue(e){return js(this.adminHost,e)}async putKvValue(e){return $s(this.adminHost,e)}async deleteKvKey(e){return Gs(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=S(Qt,{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(qt,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(Wt,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(jt,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch($t,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Gt,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Vt,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(zt,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(Jt,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Yt,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Xt,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(Zt,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(S(es,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(ts,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(S(ss,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(rs,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(is,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(S(ns,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=S(as,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=S(os,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=S(us,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(ls,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(fs,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(cs,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(ds,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(hs,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ps,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ms,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(ys,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(bs,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(gs,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=S(Ts,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Cs,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(ks,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=S(ws,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Es,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(As,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=S(_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(Is,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Os,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Rs,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=S(Kt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,i={}){this.assertOpen();const n=t??{},o=v.key(e.__lunoraRef,n,i.shardKey);let a=this.subscriptions.get(o);const c=j(s),d=j(i.onError),h=j(i.onCheckpoint);if(!a){this.nextSubId+=1;const p=`sub_${this.nextSubId.toString()}`,m=oe(n),f=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);a={acked:!1,args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:p,lastValue:f?.value,optimisticLayers:[],serverBase:f?.value,serverCursor:f?.serverCursor,shardKey:i.shardKey,wireArgs:E(n,`args for '${e.__lunoraRef}'`),...f?.serverEpoch===void 0?{}:{serverEpoch:f.serverEpoch}},this.subscriptions.add(a),f!==void 0&&this.cacheSeededQueries.set(o,f)}if(a.callbacks.add(c),d&&a.errorCallbacks.add(d),h&&a.checkpointCallbacks.add(h),a.lastValue!==void 0)try{c(a.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(c),d&&u.errorCallbacks.delete(d),h&&u.checkpointCallbacks.delete(h),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(v.keyOf(u)),this.subscriptions.remove(u),this.releaseIdleShard(u.shardKey))}}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()}`,n={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,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}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:n}=s,o=t??{},{handle:a,iterable:c}=Ze({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,n)}});this.ensureSocket(n);const d=this.getConnection(n),h={id:i,query:{args:E(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:h,shardKey:n};this.streams.set(i,u);const p=d?.wsState==="open"&&g(d,h);if(!p&&d===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(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=vr;){const f=d.pendingStreams.shift()?.id,b=f?this.streams.get(f):void 0;b&&(b.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(h)}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 Ke(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.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())},Tr))}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,n]of this.streams)l(n.shardKey)===t&&(n.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={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,n)=>{this.ackAndAdvanceCursor(s,i,n)},subscription:s=>this.subscriptions.get(s)};return new Be({channelName:e,onBecomeLeader:()=>{jr(t)},onStopBeingLeader:()=>{$r(t)},onConnectionStatus:(s,i)=>{Gr(t,s,i)},onSubscriptionData:(s,i,n,o,a)=>{zr(t,s,i,n,o,a)},onLeaderClaimAnswered:()=>{Vr(t)},onSubscriptionError:(s,i,n)=>{Jr(t,s,i,n)},onSubscriptionSettled:(s,i,n,o,a,c)=>{Yr(t,s,i,n,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(w(this.url,G),{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 n;try{n=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const o=N(n);if(!s.ok||o!==void 0&&!n.results)throw o!==void 0?Ue(o):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of n.results??[]){const c=a.body?.commitCursor;typeof a.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[a.id]?.shardKey,c)}return fr(n.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const i=t,n=s.mutationId??he(),o=this.takeReplayCredential(s.replayCredential),a=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:c,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,d,c);const h=this.offlineFlushes.get(l(s.shardKey));h!==void 0&&await h;const{hasSocket:u,idleClosed:p,polling:m,wasEverConnected:f,wsState:b}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:T}=this.offlineQueue,U=f||T,D=this.WebSocketImpl!==void 0&&U,Q=m||p,Ie=b==="connecting"&&U&&!Q,Oe=b!=="open"&&!u&&D&&!Q,Re=D&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),ae=async()=>this.enqueueOfflineMutation(e,i,s.shardKey,a,n,d,c,s.precondition,s.mutationId,o?.stamp);if(Oe||Ie||Re)return ae();let K;try{const R=await this.rpc(e.__lunoraRef,i,s.shardKey,{baselineSeq:a,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:q=>{K=q}});for(const q of c)q(K);return{committed:!0,value:R}}catch(R){if(Q&&D&&R instanceof TypeError&&me(i))return ae();throw this.settleFailedDirectWrite(R,K,c,d,o?.flags.authToken),R}}settleFailedDirectWrite(e,t,s,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),x(e)){for(const o of s)o(t);return}P(i)}async enqueueOfflineMutation(e,t,s,i,n,o,a,c,d,h){const u=h===void 0?this.identityFingerprint():h;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:d??`${this.clientId}:${String(m)}`,identity:u,mutationId:m,...o.length>0&&{onRejected:()=>{P(o)}},shardKey:s})}catch(f){throw P(o),f instanceof Error?f:new Error(String(f))}for(const f of a)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,f)=>{const b={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:u,precondition:c,onCommit:T=>{for(const U of a)U(T)},reject:T=>{this.queuedIdentities.delete(n),x(T)||P(o),f(T instanceof Error?T:new Error(String(T))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(b),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),b.id!==void 0&&this.queuedIdentities.set(b.id,u)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(_(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(Ve(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const n=t.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,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(_(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),O(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,O(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=_(e,t,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=_(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=_(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:t,...n===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(()=>{})},br))}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)))}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}async pollSubscriptions(e){const t=l(e),s=[];for(const a of this.subscriptions.all())l(a.shardKey)===t&&(me(a.args)?s.push(a):A(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=$e(),n=this.identityFingerprint();let o;try{o=await Se(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()!==n)return!0;for(const[a,c]of s.entries()){const d=o[a];if(d!==void 0){if(!d.ok){A(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:M(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Se(async t=>e(w(this.url,G),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,i){const n=[],o=[];if(!i)return{confirms:n,rollbacks:o};const a=v.key(e,t,s),c=this.subscriptions.get(a);if(c){const d=qe(c,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,t,s,i,n){const{confirms:o,rollbacks:a,store:c}=We(this.subscriptions,s);try{e(c,t)}catch{P(a);return}i.push(...a),n.push(...o)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!g(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:Or({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ue(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[rt]=it(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(s.authorization=`Bearer ${n}`),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={}){if(!this.fetchImpl)throw new L("LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,a=await this.fetchImpl(w(this.url,ft),{body:JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){const u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{throw F(a.status,a.statusText,a.headers.get("retry-after"))}const d=c;if(typeof d!="object"||d===null||Array.isArray(d))throw F(a.status,a.statusText,a.headers.get("retry-after"));const h=N(c);if(h!==void 0)throw ce(h,a.headers.get("retry-after"));if(!a.ok)throw F(a.status,a.statusText,a.headers.get("retry-after"));i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor);try{return k(c.result)}catch(u){throw Ee(u)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.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&&(n["content-type"]=i)):(a=JSON.stringify(s),n["content-type"]="application/json");const c=await this.fetchImpl(w(this.url,e),{body:a,headers:n,method:t});let d;try{d=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const h=N(d);if(h!==void 0){const u=new Error(h.message??"admin request failed");throw u.code=h.code,u}if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${u})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));g(e,{caps:Zr,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,i)}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,ye(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.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},gr),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const n of this.subscriptions.all())l(n.shardKey)===l(t)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:o,type:a}of n)g(e,{id:o,type:a});this.releaseIdleShard(t)}Er(e);const i=this.whisperHandlers.get(l(t));if(i)for(const n of i.keys())g(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),g(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",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,n]of this.streams)if(!(l(n.shardKey)!==l(e.shardKey)||t.has(i))){if(n.durable){const o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==i),o];continue}n.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){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Cr;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},kr))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return g(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&g(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=_r(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 n=this.getConnection(t);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{const n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,generation:o,id:a,seq:c}=i,d=this.streams.get(a);d&&typeof c=="number"&&(d.lastSeq=c,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(k(n));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);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}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(Ne(e)),this.forgetStream(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){const a=de(e),c=this.identityFingerprint(),d=v.keyOf(n);A(n.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,a,c);return}const o=s===void 0?void 0:this.shapeSubscriptions.get(s);o&&A(o.errorCallbacks,de(e))}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){qr(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&!s.undecodable.has(i)&&this.applyPokePart(n,s,e)}}}applyPokePart(e,t,s){const i=Kr(e,t,s);if(be(e),i==="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,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)return;let n;try{n=Pe(e,i.serverBase)}catch(o){A(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(n===Fe){this.resnapshotSubscription(i);return}if(this.dropCacheSeed(v.keyOf(i)),Ae(i,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(ee(i,e.lastMutationId),te(i,!0)),this.persistQueryValue(i),X(i,i.serverCursor),t!==void 0&&je(i,t),O(i,n),this.tabCoordinator?.isLeader()){const o=v.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,n,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&&ee(t,e.lastMutationId),te(t),this.tabCoordinator?.isLeader())){const s=v.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),X(e,e.serverCursor)&&O(e,e.serverBase))}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const i=k(e.data);for(const n of s)try{n(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,A(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ze(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let i=0;i<e.length;i+=1){const n=e.charCodeAt(i);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}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&&z(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject: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 n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}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 n=t??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,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.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,O(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,be(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const i=(async()=>{await(s??Promise.resolve());const{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&z(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 h of s){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",u)}const i=l(e),n=this.offlineQueue.drain(h=>l(h.shardKey)===i);if(n.length===0)return;const o=[],a=[];for(const h of n){const u=this.replayGateVerdict(h);u==="send"?o.push(h):u==="hold"&&a.push(h)}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 d=[];for(let h=0;h<c.length;h+=$){const u=c.slice(h,h+$),p=await this.replayBatched(u,e,t);if(d.push(...p.requeue),p.stop){d.push(...c.slice(h+$));break}}d.length>0&&this.offlineQueue.requeue(d),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,Z(i))})}noteReplayRetryDelay(e,t,s){const i=l(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,a=Mr(t,o)??(s===null&&W(t)?Z(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:a===void 0?n?.delayMs:Math.max(n?.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 n=this.replayRetryTimers.get(t);n!==void 0&&clearTimeout(n),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)||Pr(e)}noteReplayAuthRefusal(e,t){if(!W(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,...V(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const n=e[i];if(!n)continue;let o;try{const a=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:s,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...V(n.identity,s),mutationId:n.id,onCommitCursor:c=>{o=c}});this.settleReplaySuccess(n,a,o)}catch(a){if(x(a)){this.settleReplayUndecodable(n,a,o);continue}if(!this.shouldRequeueReplayFailure(a,s)){this.settleReplayTerminal(n,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&&Nr(i)>Ur)return await this.replayBatchedHalves(e,t,s);let n;try{n=await this.fetchImpl(w(this.url,G),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...V(e.find(d=>d.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let a;const c=n.headers.get("retry-after");try{a=await n.json()}catch{return this.settleWholeBatchError(e,F(n.status,n.statusText,c),t,s)}if(!a.results){const d=N(a),h=d===void 0?F(n.status,n.statusText,c):ce(d,c);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 L||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:e,stop:!0};for(const n of e)this.settleReplayTerminal(n,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),t,s);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};const o=await this.replayBatched(e.slice(i),t,s);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,t,s,i){const n=xr(t),o=[];let a=!1,c=!1;for(const[d,h]of e.entries()){const u=Br(n.get(d));switch(u.kind){case"committed":{a=!0,this.settleReplaySuccess(h,u.value,u.commitCursor);break}case"errored":{c||=W(u.error),this.shouldRequeueReplayFailure(u.error,i)?(this.noteReplayRetryDelay(s,u.error,i),o.push(h)):this.settleReplayTerminal(h,u.error);break}case"unanswered":{o.push(h);break}default:a=!0,this.settleReplayUndecodable(h,u.error,u.commitCursor)}}return a&&!c&&this.noteCredentialAccepted(i),o}}export{_e as LunoraClient};
|
package/dist/packem_shared/{createServerClient-DAON0zRx.mjs → createServerClient-B1NCqPDO.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraClient as r}from"./LunoraClient-
|
|
1
|
+
import{LunoraClient as r}from"./LunoraClient-DerKcvqC.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};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{decodeWire as N}from"@lunora/wire";import{createReconnect as P}from"./createReconnect-CjTmjJDH.mjs";import{createStream as O}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const S=/^ /u,L=/^\d+$/u,C=2147483647,I=10,w=e=>typeof e=="object"&&e!==null?JSON.stringify(e):String(e),H=e=>{let n="",t,s;const d=[];for(const r of e.split(`
|
|
2
|
+
`))if(r.startsWith("event:"))n=r.slice(6).replace(S,"");else if(r.startsWith("data:"))d.push(r.slice(5).replace(S,""));else if(r.startsWith("id:")){const a=r.slice(3).replace(S,"");a.includes("\0")||(t=a)}else if(r.startsWith("retry:")){const a=r.slice(6).replace(S,"");L.test(a)&&Number.isSafeInteger(Number(a))&&(s=Math.min(Number(a),C))}return{data:d.join(`
|
|
3
|
+
`),event:n,id:t,retry:s}},x=(e,n,t)=>{const s=n.params??{},d=e.path.split("/").map(o=>{if(!o.startsWith(":"))return o;const f=o.slice(1),c=s[f];if(c===void 0)throw new m("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${f}" for route ${e.path}`);return encodeURIComponent(w(c))}).join("/"),r=new URLSearchParams;for(const[o,f]of Object.entries(n.searchParams??{}))f!==void 0&&r.set(o,w(f));const a=r.toString();return`${t.endsWith("/")?t.slice(0,-1):t}${d}${a===""?"":`?${a}`}`},k=(e,n)=>{if(e.event==="complete")return n.complete(),!0;if(e.event==="error"){let t={};try{t=JSON.parse(e.data)}catch{}const s=typeof t.message=="string"?t.message:"stream error",d=typeof t.code=="string"?t.code:"HTTP_STREAM_ERROR";return n.fail(new m(d,s)),!0}if((e.event===""||e.event==="message")&&e.data!=="")try{n.push(N(JSON.parse(e.data)))}catch{return n.fail(new m("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},F=async(e,n,t)=>{const s=e.getReader(),d=new TextDecoder;let r="",a=!1;const p=c=>{let l=a?`\r${c}`:c;a=l.endsWith("\r"),a&&(l=l.slice(0,-1)),r+=l.replaceAll(`\r
|
|
4
|
+
`,`
|
|
5
|
+
`)},o=()=>{let c=r.indexOf(`
|
|
6
|
+
|
|
7
|
+
`);for(;c!==-1;){const l=H(r.slice(0,c));if(r=r.slice(c+2),t.onFrame?.(),l.id!==void 0&&t.onId?.(l.id),l.retry!==void 0&&t.onRetry?.(l.retry),k(l,n))return!0;c=r.indexOf(`
|
|
8
|
+
|
|
9
|
+
`)}return!1},f=()=>s.cancel().then(()=>{},()=>{});try{for(;;){const{done:c,value:l}=await s.read();if(c)break;if(p(d.decode(l,{stream:!0})),o())return await f(),!0}return p(d.decode()),o()}catch(c){throw await f(),c}},$=async(e,n)=>{n.aborted||await new Promise(t=>{let s;const d=()=>{clearTimeout(s),t()};s=setTimeout(()=>{n.removeEventListener("abort",d),t()},e),n.addEventListener("abort",d,{once:!0})})},B=(e,n)=>{const t=Object.entries(e??{}).filter(([s])=>n===void 0||s.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(t),...n===void 0?{}:{"last-event-id":n}}},_=e=>e instanceof Error&&"code"in e?e:new m("HTTP_STREAM_TRANSPORT",e instanceof Error?e.message:String(e),{cause:e}),J=(e,n,t={})=>{const s=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new m("INTERNAL","httpStream: no `fetch` implementation available");const d=x(e,n??{},t.baseUrl??""),r=new AbortController;let a;t.signal&&(t.signal.aborted?r.abort():(a=()=>{r.abort()},t.signal.addEventListener("abort",a,{once:!0})));const p=()=>{a&&t.signal?.removeEventListener("abort",a)},{handle:o,iterable:f}=O({maxBuffer:t.maxBuffer,onCancel:()=>{r.abort()},onFail:()=>{r.abort()}}),c=t.reconnect??!1,l=P();let{lastEventId:v}=t,y,T=0;const g=()=>{l.reset(),T=0},E={},R=i=>{try{i()}catch(h){throw E.value={error:h},h}},A={onFrame:g,onId:i=>{R(()=>t.onEventId?.(i)),v=i},onRetry:i=>{R(()=>t.onRetry?.(i)),y=i}},M=async()=>{const i=B(t.headers,v),h=new m("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame");try{const u=await s(d,{headers:i,method:e.method,signal:r.signal});if(!u.ok){await u.body?.cancel().catch(()=>{}),o.fail(new m("HTTP_STREAM_STATUS",`httpStream: request failed (status ${u.status.toString()})`,{status:u.status}));return}if(!u.body){o.fail(new m("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}return{completed:await F(u.body,o,A),error:h}}catch(u){if(r.signal.aborted){o.complete();return}if(E.value){const{error:b}=E.value;o.fail(b instanceof Error?b:new m("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:_(u)}}};return(async()=>{try{for(;;){if(r.signal.aborted){o.complete();return}const i=await M();if(!i)return;if(i.completed||!c||T>=I){i.completed||o.fail(i.error);return}T+=1,await $(y??l.next(),r.signal)}}finally{p()}})().catch(i=>{if(r.signal.aborted){o.complete();return}o.fail(_(i))}),f};export{J as httpStream};
|
package/dist/packem_shared/{lunora-client.d-B-1VFscs.d.mts → lunora-client.d-DFwg2da7.d.mts}
RENAMED
|
@@ -1519,6 +1519,8 @@ interface StreamIterable<T> extends AsyncIterable<T> {
|
|
|
1519
1519
|
declare const createStream: <T>(options: {
|
|
1520
1520
|
maxBuffer?: number;
|
|
1521
1521
|
onCancel: () => void;
|
|
1522
|
+
/** Invoked once the stream is failed, so a producer can stop feeding it. */
|
|
1523
|
+
onFail?: () => void;
|
|
1522
1524
|
}) => {
|
|
1523
1525
|
handle: StreamHandle<T>;
|
|
1524
1526
|
iterable: StreamIterable<T>;
|
|
@@ -1519,6 +1519,8 @@ interface StreamIterable<T> extends AsyncIterable<T> {
|
|
|
1519
1519
|
declare const createStream: <T>(options: {
|
|
1520
1520
|
maxBuffer?: number;
|
|
1521
1521
|
onCancel: () => void;
|
|
1522
|
+
/** Invoked once the stream is failed, so a producer can stop feeding it. */
|
|
1523
|
+
onFail?: () => void;
|
|
1522
1524
|
}) => {
|
|
1523
1525
|
handle: StreamHandle<T>;
|
|
1524
1526
|
iterable: StreamIterable<T>;
|
|
@@ -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-DFwg2da7.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-DS1iidgx.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-DFwg2da7.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-DFwg2da7.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-DS1iidgx.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-DS1iidgx.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-DFwg2da7.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-DHBLZn6m.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-DS1iidgx.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-L3NDOXp4.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-B1NCqPDO.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 h}from"@lunora/errors";const m=1024,p=f=>{const i=f.maxBuffer??m,r=[],o=[];let n=!1,t,l=!1;const u=()=>{const e=o.shift();if(!e)return!1;if(t)return e.reject(t),!0;if(r.length>0){const s=r.shift();return e.resolve({done:!1,value:s}),!0}return n?(e.resolve({done:!0,value:void 0}),!0):(o.unshift(e),!1)},a={complete(){if(!(n||t))for(n=!0;u(););},fail(e){if(!(n||t))for(t=e,r.length=0;u(););},push(e){if(!(n||t||l)){if(r.length>=i){a.fail(new h("STREAM_BACKPRESSURE",`stream buffer overflow (max=${i.toString()}); the consumer cannot keep up with the producer`));return}r.push(e),u()}}},c=()=>{if(!l){l=!0,n=!0,r.length=0;try{f.onCancel()}catch{}for(;u(););}};return{handle:a,iterable:{cancel:c,[Symbol.asyncIterator](){return{next(){if(t)return Promise.reject(t);if(r.length>0){const e=r.shift();return Promise.resolve({done:!1,value:e})}return n?Promise.resolve({done:!0,value:void 0}):new Promise((e,s)=>{o.push({reject:s,resolve:e})})},return(){return c(),Promise.resolve({done:!0,value:void 0})}}}}}};export{m as DEFAULT_MAX_BUFFER,p as createStream};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{decodeWire as p}from"@lunora/wire";import{createStream as u}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";const m=/^ /u,h=t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),S=t=>{let s="";const e=[];for(const o of t.split(`
|
|
2
|
-
`))o.startsWith("event:")?s=o.slice(6).replace(m,""):o.startsWith("data:")&&e.push(o.slice(5).replace(m,""));return{data:e.join(`
|
|
3
|
-
`),event:s}},T=(t,s,e)=>{const o=s.params??{},c=t.path.split("/").map(a=>{if(!a.startsWith(":"))return a;const n=a.slice(1),r=o[n];if(r===void 0)throw new f("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${n}" for route ${t.path}`);return encodeURIComponent(h(r))}).join("/"),i=new URLSearchParams;for(const[a,n]of Object.entries(s.searchParams??{}))n!==void 0&&i.set(a,h(n));const l=i.toString();return`${e.endsWith("/")?e.slice(0,-1):e}${c}${l===""?"":`?${l}`}`},E=(t,s)=>{if(t.event==="complete")return s.complete(),!0;if(t.event==="error"){let e={};try{e=JSON.parse(t.data)}catch{}const o=typeof e.message=="string"?e.message:"stream error",c=typeof e.code=="string"?e.code:"HTTP_STREAM_ERROR";return s.fail(new f(c,o)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{s.push(p(JSON.parse(t.data)))}catch{return s.fail(new f("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},b=async(t,s)=>{const e=t.getReader(),o=new TextDecoder;let c="",i=!1;const l=a=>{let n=i?`\r${a}`:a;i=n.endsWith("\r"),i&&(n=n.slice(0,-1)),c+=n.replaceAll(`\r
|
|
4
|
-
`,`
|
|
5
|
-
`)},d=()=>{let a=c.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);for(;a!==-1;){const n=S(c.slice(0,a));if(c=c.slice(a+2),E(n,s))return!0;a=c.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}return!1};for(;;){const{done:a,value:n}=await e.read();if(a)break;if(l(o.decode(n,{stream:!0})),d()){await e.cancel().catch(()=>{});return}}l(o.decode()),d()||s.fail(new f("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},_=(t,s,e={})=>{const o=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!o)throw new f("INTERNAL","httpStream: no `fetch` implementation available");const c=T(t,s??{},e.baseUrl??""),i=new AbortController;let l;e.signal&&(e.signal.aborted?i.abort():(l=()=>{i.abort()},e.signal.addEventListener("abort",l,{once:!0})));const d=()=>{l&&e.signal?.removeEventListener("abort",l)},{handle:a,iterable:n}=u({maxBuffer:e.maxBuffer,onCancel:()=>{i.abort()}});return(async()=>{try{const r=await o(c,{headers:{accept:"text/event-stream",...e.headers},method:t.method,signal:i.signal});if(!r.ok){await r.body?.cancel().catch(()=>{}),a.fail(new f("HTTP_STREAM_STATUS",`httpStream: request failed (status ${r.status.toString()})`,{status:r.status}));return}if(!r.body){a.fail(new f("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await b(r.body,a)}finally{d()}})().catch(r=>{if(i.signal.aborted){a.complete();return}if(r instanceof Error&&"code"in r){a.fail(r);return}a.fail(new f("HTTP_STREAM_TRANSPORT",r instanceof Error?r.message:String(r),{cause:r}))}),n};export{_ as httpStream};
|