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

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.
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
2
- import { U as User } from "../packem_shared/types.d-MI8BwMXt.mjs";
1
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
2
+ import { U as User } from "../packem_shared/types.d-w4VrTsKH.mjs";
3
3
  import '@lunora/runtime';
4
4
  interface IdentityStore {
5
5
  /** Read the current resolved user, or `null` when signed out / not yet resolved. */
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
2
- import { U as User } from "../packem_shared/types.d-MI8BwMXt.js";
1
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
2
+ import { U as User } from "../packem_shared/types.d-w4VrTsKH.js";
3
3
  import '@lunora/runtime';
4
4
  interface IdentityStore {
5
5
  /** Read the current resolved user, or `null` when signed out / not yet resolved. */
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-MI8BwMXt.mjs";
2
- export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-MI8BwMXt.mjs";
3
- import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-B-hIlqf_.mjs";
4
- export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-B-hIlqf_.mjs";
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-C6emVQoK.mjs";
1
+ import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-w4VrTsKH.mjs";
2
+ export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-w4VrTsKH.mjs";
3
+ import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-DbRRvSya.mjs";
4
+ export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-DbRRvSya.mjs";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BmSiP8F_.mjs";
6
6
  export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
7
7
  declare const anyApi: Record<string, Record<string, unknown>>;
8
8
  /**
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-MI8BwMXt.js";
2
- export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-MI8BwMXt.js";
3
- import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Rv8-L9mJ.js";
4
- export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-Rv8-L9mJ.js";
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-CBi9DddN.js";
1
+ import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-w4VrTsKH.js";
2
+ export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-w4VrTsKH.js";
3
+ import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Kd72FRSr.js";
4
+ export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-Kd72FRSr.js";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-D55TcvEq.js";
6
6
  export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
7
7
  declare const anyApi: Record<string, Record<string, unknown>>;
8
8
  /**
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{anyApi as o}from"./packem_shared/anyApi-BD4dgvDY.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as n,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs";import{createAsyncStoragePersistence as m}from"./packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{createClientQuery as s}from"./packem_shared/createClientQuery-CrdRoicO.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CMFYQCL-.mjs";import{applyDelta as y,isMutationDelta as R}from"./packem_shared/applyDelta-DXqQORbM.mjs";import{CONFLICT_ERROR_CODE as C,getErrorCode as S,getRetryAfterMs as A,isConflictError as D,isForbiddenError as M,isRateLimitedError as _,isUnauthorizedError as h}from"./packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs";import{httpStream as Q}from"./packem_shared/httpStream-Cz4_QyjV.mjs";import{c as L}from"./packem_shared/local-store-DFMSEM2j.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-CrIthWcp.mjs";import{createMutationRunner as O}from"./packem_shared/createMutationRunner-lQXH8Amk.mjs";import{createMutatorRunner as U}from"./packem_shared/createMutatorRunner-BVzo0FBZ.mjs";import{h as B}from"./packem_shared/offline-queue-CKMw-5rF.mjs";import{createInMemoryPersistence as N,createIndexedDbPersistence as v}from"./packem_shared/createInMemoryPersistence-CQYXy8UP.mjs";import{preloadQuery as z,preloadedQueryResult as K}from"./packem_shared/preloadQuery-DjwSjFwt.mjs";import{createInMemoryQueryCache as W,createIndexedDbQueryCache as X,queryCacheKey as j}from"./packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as H}from"./packem_shared/createReconnect-CFT7YRSR.mjs";import{default as Y}from"./packem_shared/createSnapshotPrecondition-CKvCNKyD.mjs";import{DEFAULT_MAX_BUFFER as $,createStream as ee}from"./packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as oe}from"./packem_shared/SubscriptionRegistry-C72rCp44.mjs";import{ClientServiceWorker as ae}from"./packem_shared/ClientServiceWorker-CRQ5yl7-.mjs";import{createReply as pe,sendToSw as ce}from"./packem_shared/createReply-DF0jRsv-.mjs";export{C as CONFLICT_ERROR_CODE,ae as ClientServiceWorker,$ as DEFAULT_MAX_BUFFER,b as LunoraClient,B as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,oe as SubscriptionRegistry,d as TabCoordinator,o as anyApi,y as applyDelta,m as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,N as createInMemoryPersistence,W as createInMemoryQueryCache,v as createIndexedDbPersistence,X as createIndexedDbQueryCache,L as createLocalStore,O as createMutationRunner,U as createMutatorRunner,H as createReconnect,pe as createReply,Y as createSnapshotPrecondition,ee as createStream,S as getErrorCode,A as getRetryAfterMs,Q as httpStream,D as isConflictError,M as isForbiddenError,R as isMutationDelta,_ as isRateLimitedError,h as isUnauthorizedError,n as maxSeq,z as preloadQuery,K as preloadedQueryResult,j as queryCacheKey,p as reconcileOptimistic,ce as sendToSw};
1
+ import{anyApi as o}from"./packem_shared/anyApi-BD4dgvDY.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as n,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs";import{createAsyncStoragePersistence as m}from"./packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{createClientQuery as s}from"./packem_shared/createClientQuery-CrdRoicO.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CMFYQCL-.mjs";import{applyDelta as y,isMutationDelta as R}from"./packem_shared/applyDelta-DXqQORbM.mjs";import{CONFLICT_ERROR_CODE as C,getErrorCode as S,getRetryAfterMs as A,isConflictError as D,isForbiddenError as M,isRateLimitedError as _,isUnauthorizedError as h}from"./packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs";import{httpStream as Q}from"./packem_shared/httpStream-Cz4_QyjV.mjs";import{c as L}from"./packem_shared/local-store-DFMSEM2j.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-CbRvTqjM.mjs";import{createMutationRunner as O}from"./packem_shared/createMutationRunner-lQXH8Amk.mjs";import{createMutatorRunner as U}from"./packem_shared/createMutatorRunner-BVzo0FBZ.mjs";import{h as B}from"./packem_shared/offline-queue-CKMw-5rF.mjs";import{createInMemoryPersistence as N,createIndexedDbPersistence as v}from"./packem_shared/createInMemoryPersistence-CQYXy8UP.mjs";import{preloadQuery as z,preloadedQueryResult as K}from"./packem_shared/preloadQuery-DjwSjFwt.mjs";import{createInMemoryQueryCache as W,createIndexedDbQueryCache as X,queryCacheKey as j}from"./packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as H}from"./packem_shared/createReconnect-CFT7YRSR.mjs";import{default as Y}from"./packem_shared/createSnapshotPrecondition-CKvCNKyD.mjs";import{DEFAULT_MAX_BUFFER as $,createStream as ee}from"./packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as oe}from"./packem_shared/SubscriptionRegistry-C72rCp44.mjs";import{ClientServiceWorker as ae}from"./packem_shared/ClientServiceWorker-CRQ5yl7-.mjs";import{createReply as pe,sendToSw as ce}from"./packem_shared/createReply-DF0jRsv-.mjs";export{C as CONFLICT_ERROR_CODE,ae as ClientServiceWorker,$ as DEFAULT_MAX_BUFFER,b as LunoraClient,B as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,oe as SubscriptionRegistry,d as TabCoordinator,o as anyApi,y as applyDelta,m as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,N as createInMemoryPersistence,W as createInMemoryQueryCache,v as createIndexedDbPersistence,X as createIndexedDbQueryCache,L as createLocalStore,O as createMutationRunner,U as createMutatorRunner,H as createReconnect,pe as createReply,Y as createSnapshotPrecondition,ee as createStream,S as getErrorCode,A as getRetryAfterMs,Q as httpStream,D as isConflictError,M as isForbiddenError,R as isMutationDelta,_ as isRateLimitedError,h as isUnauthorizedError,n as maxSeq,z as preloadQuery,K as preloadedQueryResult,j as queryCacheKey,p as reconcileOptimistic,ce as sendToSw};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{s as b,a as B}from"./wire-codec-D_fiax9d.mjs";import{t as I}from"./wire-key-j8BZ65HQ.mjs";import D from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as j}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as H}from"./TabCoordinator-CMFYQCL-.mjs";import{isMutationDelta as V,applyDelta as J}from"./applyDelta-DXqQORbM.mjs";import{httpStream as X}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Y,c as Z}from"./local-store-DFMSEM2j.mjs";import{h as tt,u as $,d as et,s as st}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as rt}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as it,queryCacheKey as R}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as nt}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-C72rCp44.mjs";const x=500,at=(h,t)=>{if(h.size<t)return;const e=h.keys().next().value;e!==void 0&&h.delete(e)};class C{listeners=new Set;add(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(...t){const[e]=t;for(const s of this.listeners)try{s(e)}catch{}}clear(){this.listeners.clear()}}const ot="/_lunora/rpc",Q="/_lunora/rpc-batch",ct="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,O=h=>{for(let t=h.length-1;t>=0;t-=1)h[t]?.()},ht=(h,t)=>{for(const e of t)e.op==="delete"?h.delete(e.key):e.value!==void 0&&h.set(e.key,e.value)},ut="lunora-ping",dt=3e4,lt=1e4,pt=250,mt=64,ft="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",gt="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",St="/_lunora/admin/scheduled/cancel",vt="/_lunora/admin/scheduled/dead",kt="/_lunora/admin/scheduled/dead/retry",wt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",Tt="/_lunora/admin/workflows/instance",It="/_lunora/admin/workflows/status",L="/_lunora/admin/storage",Ot="/_lunora/admin/storage/url",Et="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",Ft="/_lunora/admin/cron-jobs",Pt="/_lunora/admin/cron-jobs/run",At="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",xt="/_lunora/admin/global/tables",Mt="/_lunora/admin/global/table",Lt="/_lunora/admin/global/facet",Kt="/_lunora/admin/vector/indexes",$t="/_lunora/admin/vector/query",qt="/_lunora/admin/logs/archive",Qt="/_lunora/admin/kv/namespaces",Ut="/_lunora/admin/kv/keys",K="/_lunora/admin/kv/value",Nt="/_lunora/admin/auth/users",Bt="/_lunora/admin/auth/sessions",Wt="/_lunora/admin/auth/users/create",zt="/_lunora/admin/auth/users/role",Gt="/_lunora/admin/auth/users/ban",Dt="/_lunora/admin/auth/users/unban",jt="/_lunora/admin/auth/users/password",Ht="/_lunora/admin/auth/users/remove",Vt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Xt="/_lunora/admin/auth/sessions/revoke-all",Yt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",te="/_lunora/admin/auth/accounts",ee="/_lunora/admin/auth/accounts/unlink",se="/_lunora/admin/auth/passkeys",re="/_lunora/admin/auth/passkeys/delete",ie="/_lunora/admin/auth/two-factor/disable",ne="/_lunora/admin/auth/organizations",ae="/_lunora/admin/auth/organizations/members",oe="/_lunora/admin/auth/organizations/invitations",ce="/_lunora/admin/auth/organizations/members/remove",he="/_lunora/admin/auth/organizations/invitations/cancel",ue="/_lunora/admin/auth/config",de="/_lunora/admin/auth/organizations/create",le="/_lunora/admin/auth/organizations/update",pe="/_lunora/admin/auth/organizations/remove",me="/_lunora/admin/auth/organizations/members/add",fe="/_lunora/admin/auth/organizations/members/invite",ye="/_lunora/admin/auth/organizations/members/role",ge="/_lunora/admin/auth/organizations/teams",be="/_lunora/admin/auth/organizations/teams/create",Se="/_lunora/admin/auth/organizations/teams/update",ve="/_lunora/admin/auth/organizations/teams/remove",ke="/_lunora/admin/auth/organizations/teams/members",we="/_lunora/admin/auth/organizations/teams/members/add",Ce="/_lunora/admin/auth/organizations/teams/members/remove",Te="/_lunora/admin/auth/organizations/roles",Ie="/_lunora/admin/auth/organizations/roles/create",Oe="/_lunora/admin/auth/organizations/roles/update",Ee="/_lunora/admin/auth/organizations/roles/remove",_e="/api/auth",Fe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[r,i]of Object.entries(t))i!==void 0&&i!==""&&e.set(r,String(i));const s=e.toString();return s===""?h:`${h}?${s}`},m=h=>h??"",W=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,r=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??t}},Pe=h=>{const{code:t,messageText:e}=W(h,"stream error");return t===void 0?new Error(e):new p(t,e)},N=h=>{const{code:t,messageText:e}=W(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Ae=new TextDecoder,Re=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Ae.decode(h)},g=(h,t)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(t)),!0}catch{return!1}},T=h=>{const t=new Error(h.message??"request failed");return t.code=h.code,h.data!==void 0&&(t.data=b(h.data)),h.hint!==void 0&&(t.hint=h.hint),h.docsUrl!==void 0&&(t.docsUrl=h.docsUrl),t},k=(h,t)=>{try{return B(h)}catch(e){const s=e instanceof Error?e.message:String(e);throw new TypeError(`LunoraClient: cannot encode ${t} — ${s}`,e instanceof Error?{cause:e}:void 0)}},xe=(h,t)=>{const e=Array.from({length:t});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=t)continue;const r=s.body;e[s.id]=r&&"error"in r&&r.error?{error:T(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Me=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Le=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(t,e){return{defaultValue:e,key:t}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(t){this.url=t.url,this.wsUrl=t.wsUrl??v(U(t.url),ct),this.wsToken=t.wsToken;const e=t.authBasePath??_e;this.authBasePath=e.endsWith("/")?e.slice(0,-1):e,this.fetchImpl=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=t.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=t.bookmarkStorage??D(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??dt,this.connectTimeoutMs=t.connectTimeoutMs??lt,this.defaultConnectionContext=t.connectionContext,this.persistence=rt(t.persistence,t.outbox===void 0),this.persistenceVersion=t.persistenceVersion,this.queryCache=it(t.queryCache),this.onPersistenceError=t.offlineQueue?.onPersistenceError,this.clientQueryStore=new j,t.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,t.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Le),this.offlineQueue=new tt(t.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${$()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(t,e){const s=this.authToken!==t,r=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const i=this.identityFingerprint();if(i!==r&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(r,i),this.tabCoordinator)){const n=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),n&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(t)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(t){return this.clientWatermarks.get(t??"")??0}async callMutator(t,e,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"";let n;const a=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:o=>{n=o}});return n!==void 0&&n>(this.clientWatermarks.get(i)??0)&&this.clientWatermarks.set(i,n),{applied:n===void 0||n===r,result:a}}onAuthTokenChange(t){return this.authTokenListeners.add(t)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const t={};this.authToken&&(t.authorization=`Bearer ${this.authToken}`);try{const e=await this.fetchImpl(v(this.url,`${this.authBasePath}${Fe}`),{credentials:"include",headers:t,method:"GET"});return e.ok?(await e.json())?.user??null:null}catch{return null}}setWsToken(t){if(this.wsToken!==t){this.wsToken=t;for(const e of this.connections.values())if(e.socket)try{e.socket.close()}catch{}}}setConnectionContext(t,e={}){const s=m(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=m(e.shardKey),r={context:t},i=this.connectionContextHolders.get(s);i?i.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let n=!1;return()=>{if(n)return;n=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const r=m(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(t);const a=n===void 0;if(n||(n=new Set,i.set(t,n)),n.add(e),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:t,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&g(u,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{data:k(e??null,`whisper data for topic '${t}'`),topic:t,type:"whisper"})}onTokenExpired(t){return this.tokenExpiredListeners.add(t)}connectionStatus(){return this.computeStatus()}onConnectionStatus(t){const e=this.statusListeners.add(t);return t(this.computeStatus()),e}pendingCount(){return this.offlineQueue.size}debug(){const t=[],e=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(const r of e){const i=this.connections.get(r);t.push({confirmedMutationWatermark:this.clientWatermarks.get(r)??0,hasSocket:i?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const s=this.subscriptions.all().map(r=>({acked:r.acked,functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())s.push({acked:r.serverCursor!==void 0,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((r,i)=>(r.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:s.toSorted((r,i)=>r.functionPath.localeCompare(i.functionPath))}}onPendingChange(t){const e=this.pendingChangeListeners.add(t);return t(this.offlineQueue.size),e}onMutationSettled(t){return this.mutationSettledListeners.add(t)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(t){return this.clientQueryStore.get(t)}setClientQuery(t,e){this.clientQueryStore.set(t,e)}subscribeClientQuery(t,e){return this.clientQueryStore.subscribe(t,e)}resetClientQuery(t){this.clientQueryStore.reset(t)}snapshotPrecondition(t,e,s){const r=this.peekActiveQueryValue(t.__lunoraRef,e,s),i=r===void 0?void 0:I(r);return()=>{const n=this.peekActiveQueryValue(t.__lunoraRef,e,s);return i===void 0&&n===void 0?!0:i===void 0||n===void 0?!1:I(n)===i}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const r=I(e),i=R(t,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQueryValue(t,e,s){const r=w.key(t,e,s);return this.subscriptions.get(r)?.lastValue}async query(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey,{attachBookmark:!0})}async batch(t){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args??{},`args for batch call '${i.fn.__lunoraRef}'`),functionPath:i.fn.__lunoraRef,id:n,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||r.error&&!r.results)throw r.error?T(r.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(t[i.id]?.shardKey,n)}return xe(r.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const r=e,i=s.mutationId??$(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,n);const{hasSocket:o,wasEverConnected:c,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:d}=this.offlineQueue,l=c||d,y=this.WebSocketImpl!==void 0&&l;if(u!=="open"&&!o&&y||u==="connecting"&&l)return this.enqueueOfflineMutation(t,r,s.shardKey,i,a,n,s.precondition);try{let S;const G=await this.rpc(t.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:_=>{S=_}});for(const _ of n)_(S);return G}catch(S){throw O(a),S}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=e.length;let a=0,o=0;for(let c=0;c<n;c+=r){const u=e.slice(c,c+r),d=o;await this.mutation(t,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(d)}`},shardKey:s.shardKey}),o+=1,a+=u.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(ft,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(yt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(gt,"GET");return{backlog:t.backlog??0,inFlight:t.inFlight??0,pools:t.pools??[]}}async cancelScheduledJob(t){return this.assertOpen(),{cancelled:(await this.adminFetch(St,"POST",{id:t})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(vt,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(kt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(wt,"POST",{id:t})).removed===!0}}async listWorkflowInstances(t){this.assertOpen();const e=new URLSearchParams({name:t.name});t.status!==void 0&&e.set("status",t.status),t.page!==void 0&&e.set("page",String(t.page)),t.perPage!==void 0&&e.set("perPage",String(t.perPage));const s=await this.adminFetch(`${Ct}?${e.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??t.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(t){this.assertOpen();const e=new URLSearchParams({id:t.id,name:t.name}),s=await this.adminFetch(`${Tt}?${e.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??t.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(t){return this.assertOpen(),{status:(await this.adminFetch(It,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=v(U(this.url),bt),s=q(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||(i=setTimeout(u,s.next()))},o=d=>{if(n||this.WebSocketImpl===void 0)return;const l=d===void 0?e:`${e}?token=${encodeURIComponent(d)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const S=JSON.parse(typeof y.data=="string"?y.data:"");S.type==="jobs"&&Array.isArray(S.records)&&t(S.records)}catch{}},onOpen:()=>{s.reset()}})},c=async d=>{let l;try{l=await d()}catch{a();return}o(l)},u=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:d}=this;if(typeof d=="function"){c(d).catch(()=>{});return}o(d)};return u(),()=>{n=!0,i!==void 0&&clearTimeout(i),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(Pt,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(At,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(L,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),s=await this.adminFetch(e,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(t,e){this.assertOpen();const s=`${L}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Et,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${L}?key=${encodeURIComponent(t.key)}${M(t.bucket)}`,s=await this.adminFetch(e,"PUT",t.body,t.contentType);return{etag:s.etag,key:s.key??t.key}}async signedStorageUrl(t,e){this.assertOpen();const s=e?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Ot}?key=${encodeURIComponent(t)}${r}${M(e?.bucket)}`,n=await this.adminFetch(i,"GET");if(typeof n.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return n.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(xt,"GET")}async readGlobalTablePage(t){this.assertOpen();const e=new URLSearchParams({table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.offset!==void 0&&e.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Mt}?${e.toString()}`,"GET")}async facetGlobalColumn(t){this.assertOpen();const e=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Lt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Kt,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch($t,"POST",t)).matches??[]}async queryLogArchive(t={}){this.assertOpen();const e=await this.adminFetch(qt,"POST",t);return{nextCursor:e.nextCursor,rows:e.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Qt,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Ut,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await this.adminFetch(e,"GET")}async getKvValue(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch(K,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Nt,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminFetch(e,"GET")}async createAuthUser(t){return await this.adminFetch(Wt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(zt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Gt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(jt,"POST",t)}async removeAuthUser(t){await this.adminFetch(Ht,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Vt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Jt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Xt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Yt,"GET")}async updateAuthUser(t){return await this.adminFetch(Zt,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(te,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(ee,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(se,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){await this.adminFetch(re,"POST",t)}async disableAuthTwoFactor(t){await this.adminFetch(ie,"POST",t)}async listAuthOrganizations(t={}){return await this.adminFetch(f(ne,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(ae,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(ce,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(he,"POST",t)}async getAuthConfig(){return await this.adminFetch(ue,"GET")}async createAuthOrganization(t){return await this.adminFetch(de,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(pe,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(me,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ye,"POST",t)}async listAuthOrgTeams(t){const e=f(ge,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(be,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(Se,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(ve,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(ke,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(we,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Ce,"POST",t)}async listAuthOrgRoles(t){const e=f(Te,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Ie,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(Ee,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Bt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,r={}){this.assertOpen();const i=e??{},n=w.key(t.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const d=`sub_${this.nextSubId.toString()}`,l=I(i),y=this.takeHydratedCache(t.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:d,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:r.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),c&&u.errorCallbacks.delete(c),r.onCheckpoint&&u.checkpointCallbacks.delete(r.onCheckpoint),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.subscriptions.remove(u))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:t.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:t.args===void 0?void 0:k(t.args,`shape args for '${t.name}'`)};return this.shapeSubscriptions.set(r,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(i.shardKey,r,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=e??{},{handle:a,iterable:o}=nt({maxBuffer:s.maxBuffer,onCancel:()=>{const d=this.getConnection(i);d&&g(d,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(i);const c=this.getConnection(i),u={id:r,query:{args:k(n,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:i},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:u,shardKey:i}),!(c?.wsState==="open"&&g(c,u))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=mt;){const d=c.pendingStreams.shift()?.id,l=d?this.streams.get(d):void 0;l&&(l.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(d))}c.pendingStreams.push(u)}return o}httpStream(t,e,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return X(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const t of this.streams.values())t.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const t of this.connections.values())this.teardownConnection(t);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}teardownConnection(t){if(t.reconnectTimer!==void 0&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),this.stopHeartbeat(t),t.socket){try{t.socket.close()}catch{}t.socket=void 0}t.wsState="closed"}createTabCoordinator(){const t=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new H({channelName:t,onBecomeLeader:()=>{for(const e of this.subscriptions.all())this.ensureSocket(e.shardKey),this.sendSubscribeIfOpen(e);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[e,s]of this.connections)this.teardownConnection(s),this.connections.delete(e);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(e,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),F(a,r)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const r=this.subscriptions.get(e);r&&E(r.errorCallbacks,s)},onSubscriptionSettled:(e,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(t,e,s,r,i,n,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:e,clientId:this.clientId,functionPath:t.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(u){throw O(i),u instanceof Error?u:new Error(String(u))}for(const u of n)u(void 0);return}return new Promise((c,u)=>{const d={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of n)y(l)},reject:l=>{this.queuedIdentities.delete(r),O(i),u(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(d),this.queuedOfflineShardKeys.add(s),d.id!==void 0&&this.queuedIdentities.set(d.id,o)})}async hydratePersistedQueue(){try{const t=await this.offlineQueue.hydrate();for(const e of t)this.queuedOfflineShardKeys.add(e),this.ensureSocket(e)}catch{}}hydrateAsOutboxLeader(){const t=()=>{this.hydratePersistedQueue().catch(()=>{})},e=globalThis.navigator?.locks;if(!e){t();return}e.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||t(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(t)}async hydrateQueryCache(){if(this.queryCache)try{const t=await this.queryCache.load();for(const{key:e,...s}of t){if(et(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const r=R(t,e,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=R(t.fn.__lunoraRef,t.argsKey,t.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:t.serverCursor,ts:Date.now(),value:e,...t.serverEpoch===void 0?{}:{serverEpoch:t.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},pt)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:t}=this;if(!t){this.pendingCacheWrites.clear();return}const e=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(e.map(([s,r])=>t.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const t=[...this.connections.values()];return t.length===0?"idle":t.some(e=>e.wsState==="open")?"connected":t.some(e=>e.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const t=this.computeStatus();t!==this.lastStatus&&(this.lastStatus=t,this.statusListeners.emit(t),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(t,this.identityFingerprint()))}emitItemSettled(t,e,s){this.mutationSettledListeners.emit({args:t.args,code:s===void 0?void 0:s.code,error:s,functionPath:t.functionPath,hadAwaiter:t.liveAwaiter??!1,id:t.id??"",shardKey:t.shardKey,status:e})}applyOptimisticUpdates(t,e,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Y(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(t,e,s,r,i){const{confirms:n,rollbacks:a,store:o}=Z(this.subscriptions,s);try{t(o,e)}catch{O(a);return}r.push(...a),i.push(...n)}getConnection(t){return this.connections.get(m(t))}sendOrQueueUnsubscribe(t,e,s){const r=this.getConnection(t);r&&!g(r,{id:e,type:s})&&r.pendingUnsubscribes.push({id:e,type:s})}connectionGateState(t){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const e=this.getConnection(t);return{hasSocket:e?.socket!==void 0,wasEverConnected:e?.wasEverConnected??!1,wsState:e?.wsState??"idle"}}getOrCreateConnection(t){const e=m(t);let s=this.connections.get(e);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:q(this.reconnectOptions),reconnectTimer:void 0,shardKey:t,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(e,s)),s}wsUrlFor(t,e){const s=[];if(t!==void 0&&s.push(`shard=${encodeURIComponent(t)}`),e!==void 0&&s.push(`token=${encodeURIComponent(e)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(t,e){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(e));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),t.mutationId&&(s["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(s["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(s["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(t,e,s,r={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(v(this.url,ot),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const o=n.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await n.json()}catch{const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${n.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!n.ok){const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(t,e,s,r){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const n=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:n?(a=s,r!==void 0&&(i["content-type"]=r)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(v(this.url,t),{body:a,headers:i,method:e});let c;try{c=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if(typeof c=="object"&&c!==null&&"error"in c){const u=c.error,d=new Error(u.message??"admin request failed");throw d.code=u.code,d}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}return c}effectiveConnectionContext(t){const e=this.connectionContextHolders.get(t);return e&&e.length>0?e[e.length-1]?.context:this.connectionContexts.get(t)??this.defaultConnectionContext}refreshConnectionContext(t){const e=this.connections.get(t);e?.wsState==="open"&&this.sendConnectEnvelope(e)}sendConnectEnvelope(t){const e=this.effectiveConnectionContext(m(t.shardKey));g(t,{clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())m(e.shardKey)===m(t)&&this.sendShapeSubscribeIfOpen(e)}ensureSocket(t){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const e=this.getOrCreateConnection(t);if(!(e.wsState==="open"||e.wsState==="connecting")){if(e.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(e,t,this.wsToken).catch(()=>{});return}this.openSocket(e,t,this.wsToken)}}async openSocketWithProvidedToken(t,e,s){let r;try{r=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,r)}openManagedSocket(t,e,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new p("INTERNAL","no WebSocket implementation available");const n=new i(e);t.socket=n;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===n&&(t.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{t.socket===n&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(t,o))}),n.addEventListener("message",c=>{t.socket===n&&(t.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{t.socket===n&&o(c)}),n.addEventListener("error",()=>{t.socket===n&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:r=>{this.handleServerMessage(r.data,e)},onOpen:()=>{t.wsState="open",t.wasEverConnected=!0,t.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(t),this.markShardPendingAck(e);for(const i of this.subscriptions.all())m(i.shardKey)===m(e)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const i=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:n,type:a}of i)g(t,{id:n,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const i=t.pendingStreams;t.pendingStreams=[];for(const n of i)g(t,n)}const r=this.whisperHandlers.get(m(e));if(r)for(const i of r.keys())g(t,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(e).catch(()=>{})}})}handleDisconnect(t){if(this.closed||t.wsState==="idle"||t.wsState==="closed")return;this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket=void 0,t.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(t.shardKey);const e=new Set((t.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(m(i.shardKey)!==m(t.shardKey)||e.has(r))){if(i.durable){const n={...i.message,sinceChunk:i.lastSeq};i.message=n,t.pendingStreams=[...(t.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=t.reconnect.next();t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,this.ensureSocket(t.shardKey)},s)}startHeartbeat(t,e){this.stopHeartbeat(t),!(this.heartbeatIntervalMs<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;const{socket:s}=t;if(Date.now()-t.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}e();return}try{s.send(ut)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(t){t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)}markShardPendingAck(t){const e=m(t);for(const s of this.subscriptions.all())m(s.shardKey)===e&&(s.acked=!1)}sendSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);if(e?.wsState!=="open"||t.acked)return;const s=t.fn.__lunoraTable??t.fn.__lunoraRef;g(e,{id:t.id,query:{args:B(t.args),functionPath:t.fn.__lunoraRef,table:s,...t.serverCursor===void 0?{}:{sinceSeq:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);e?.wsState==="open"&&g(e,{id:t.id,shape:{name:t.name,...t.wireArgs===void 0?{}:{args:t.wireArgs}},type:"shape_subscribe",...t.serverCursor===void 0?{}:{sinceCheckpoint:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}})}handleServerMessage(t,e){const s=Re(t);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,id:n,seq:a}=r,o=this.streams.get(n);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,e);break}}}handleErrorMessage(t){if(t.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:e}=t,s=e===void 0?void 0:this.streams.get(e);if(s&&e!==void 0){s.handle.fail(Pe(t)),this.streams.delete(e);return}const r=e===void 0?void 0:this.subscriptions.getById(e);if(r){E(r.errorCallbacks,N(t));return}const i=e===void 0?void 0:this.shapeSubscriptions.get(e);i&&E(i.errorCallbacks,N(t))}handlePokeStart(t){at(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(t.pokeId,{baseCheckpoint:t.baseCheckpoint,epoch:t.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(t){const e=this.pokeBuffers.get(t.pokeId);if(!e)return;const s=e.parts.get(t.shapeId)??[];for(const r of t.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.value)});e.parts.set(t.shapeId,s),t.lastMutationId!==void 0&&e.lastMutationId.set(t.shapeId,t.lastMutationId)}handlePokeEnd(t){const e=this.pokeBuffers.get(t.pokeId);if(e){this.pokeBuffers.delete(t.pokeId);for(const[s,r]of e.parts){const i=this.shapeSubscriptions.get(s);if(!i)continue;const n=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,a=e.baseCheckpoint!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==e.baseCheckpoint;if(n||a){i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,this.emitShapeRows(i),this.sendShapeSubscribeIfOpen(i);continue}ht(i.rows,r),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const o=e.lastMutationId.get(s);o!==void 0&&(i.lastMutationId=o),this.emitShapeRows(i),i.onCheckpoint?.({checkpoint:i.serverCursor,mutationId:i.lastMutationId})}}}emitShapeRows(t){const e=[...t.rows.values()];for(const s of t.callbacks)try{s(e)}catch{}}handleDataMessage(t){const{id:e}=t,s=e?this.subscriptions.getById(e):void 0;if(!s)return;const r=this.resolveDataPayload(t,s);if(s.serverBase=r,t.cursor!==void 0&&(s.serverCursor=t.cursor),t.epoch!==void 0&&(s.serverEpoch=t.epoch),t.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,t.lastMutationId);for(const i of s.checkpointCallbacks)i({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),F(s,s.serverCursor),P(s,A(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(t){const e=this.subscriptions.getById(t.id);e&&this.ackAndAdvanceCursor(e,t.cursor,t.epoch)}handleSettledMessage(t){const e=this.subscriptions.getById(t.id);if(e){this.ackAndAdvanceCursor(e,t.cursor,t.epoch),t.lastMutationId!==void 0&&(e.lastMutationId=t.lastMutationId);for(const s of e.checkpointCallbacks)s({checkpoint:e.serverCursor,mutationId:e.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=w.key(e.fn.__lunoraRef,e.args,e.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,e.serverCursor,e.serverEpoch,e.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(t,e,s){t.acked=!0,(e!==void 0&&e!==t.serverCursor||s!==void 0&&s!==t.serverEpoch)&&(e!==void 0&&(t.serverCursor=e),s!==void 0&&(t.serverEpoch=s),this.persistQueryValue(t),F(t,t.serverCursor)&&P(t,A(t.serverBase,t.optimisticLayers)))}resolveDataPayload(t,e){if("data"in t&&t.data!==void 0)return b(t.data);const s=b(t.delta);if(V(s)&&e.serverBase!==void 0){const r=J(e.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(m(e))?.get(t.topic);if(!s)return;const r=b(t.data);for(const i of s)try{i(r,t.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(t){const e=this.streams.get(t);if(e){e.handle.complete(),this.streams.delete(t);return}const s=this.subscriptions.getById(t);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(t){t&&this.persistence?.remove(t).catch(e=>{st(this.onPersistenceError,"remove",e,t)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const t=this.authToken;return t===null?null:this.hashToken(t)}hashToken(t){let e=2166136261,s=5381;for(let r=0;r<t.length;r+=1){const i=t.charCodeAt(r);e^=i,e=Math.imul(e,16777619),s=Math.imul(s,33)+i}return`${t.length.toString(36)}:${(e>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(t){if(t===null||t.startsWith("subj:"))return!1;const e=this.authToken;return e===null?!1:this.hashToken(e)===t}rejectQueuedForIdentityChange(){const t=this.offlineQueue.drain();for(const e of t){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",e.reject(s),this.emitItemSettled(e,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(t,e){for(const[s,r]of this.queuedIdentities)r===t&&this.queuedIdentities.set(s,e)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const t of this.queuedOfflineShardKeys)this.flushOfflineQueue(t).catch(()=>{})}async flushOfflineQueue(t){const e=this.offlineQueue.drainConflict();for(const c of e){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",u)}const s=m(t),r=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(r.length===0)return;const i=this.identityFingerprint(),n=[];for(const c of r)this.passesReplayIdentityGate(c,i)&&n.push(c);if(n.length===0)return;const a=this.encodableOrSettleTerminal(n);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=x){const u=a.slice(c,c+x),d=await this.replayBatched(u);if(o.push(...d.requeue),d.stop){o.push(...a.slice(c+x));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(t){const e=[];for(const s of t)try{k(s.args,`args for '${s.functionPath}'`),e.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),r=s===void 0?t.identity:s;if(r!==void 0&&r!==e&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",t.reject(i),this.emitItemSettled(t,"rejected",i),!1}return this.queuedIdentities.delete(t.id??""),!0}settleReplaySuccess(t,e,s){this.unpersist(t.id),this.recordShardCursor(t.shardKey,s),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}cursorKeyFor(t){return t??this.defaultShardKey??""}learnDefaultShardKey(t,e){const s=t.headers.get("x-lunora-shard-key");if(s===null||e!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(t,e){if(typeof e!="number")return;const s=this.cursorKeyFor(t);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,e))}settleReplayTerminal(t,e){this.unpersist(t.id),t.reject(e),this.emitItemSettled(t,"rejected",e)}async replaySequential(t){for(let e=0;e<t.length;e+=1){const s=t[e];if(s)try{let r;const i=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:n=>{r=n}});this.settleReplaySuccess(s,i,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);continue}this.offlineQueue.requeue(t.slice(e));return}}}async replayBatched(t){if(!this.fetchImpl)return{requeue:t,stop:!0};let e;try{e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args,`args for '${i.functionPath}'`),functionPath:i.functionPath,id:n,clientId:i.clientId??this.clientId,mutationId:i.id,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:t,stop:!0}}const s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{return{requeue:t,stop:!0}}if(!r.results){if(r.error){const i=T(r.error);for(const n of t)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,r.results),stop:!1}}settleReplayBatchSlots(t,e){const s=new Map;for(const i of e)typeof i.id=="number"&&i.body!==void 0&&s.set(i.id,i.body);const r=[];for(const[i,n]of t.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Me.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,T(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};
@@ -1 +1 @@
1
- import{LunoraClient as r}from"./LunoraClient-CrIthWcp.mjs";const o=t=>{const e=new r({fetch:t.fetch,url:t.url});return t.token!==void 0&&e.setAuthToken(t.token),e};export{o as createServerClient};
1
+ import{LunoraClient as r}from"./LunoraClient-CbRvTqjM.mjs";const o=t=>{const e=new r({fetch:t.fetch,url:t.url});return t.token!==void 0&&e.setAuthToken(t.token),e};export{o as createServerClient};
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-MI8BwMXt.js";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-w4VrTsKH.mjs";
2
2
  import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
3
  /**
4
4
  * Reactive key-value store for local-only client state.
@@ -499,6 +499,24 @@ declare class LunoraClient {
499
499
  private readonly outbox;
500
500
  /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
501
501
  private readonly clientId;
502
+ /**
503
+ * Highest CDC cursor this client has seen a write commit at, per shard key
504
+ * (`""` for the default shard) — the read-your-writes bookmark sent as
505
+ * `x-lunora-min-seq`.
506
+ *
507
+ * In memory only, and deliberately: it exists to keep THIS session's reads
508
+ * behind THIS session's writes. Persisting it across reloads would pin a
509
+ * fresh page to a cursor it has no reason to require and force needless
510
+ * fallbacks to the owner.
511
+ */
512
+ private readonly shardCursors;
513
+ /**
514
+ * The server's own name for the default shard (`defaultShardKey`), learned
515
+ * from the first response to a call that named no shard. `undefined` until
516
+ * then, which is why `cursorKeyFor` falls back to a placeholder entry that
517
+ * `learnDefaultShardKey` folds in once the name arrives.
518
+ */
519
+ private defaultShardKey;
502
520
  /**
503
521
  * `true` when the constructor's hydration microtask has finished loading the
504
522
  * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
@@ -1690,6 +1708,7 @@ declare class LunoraClient {
1690
1708
  * reconnect can't OOM the page.
1691
1709
  */
1692
1710
  stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
1711
+ durable?: boolean;
1693
1712
  maxBuffer?: number;
1694
1713
  shardKey?: string;
1695
1714
  }): StreamIterable<ReturnOf<F>>;
@@ -2129,6 +2148,37 @@ declare class LunoraClient {
2129
2148
  private passesReplayIdentityGate;
2130
2149
  /** Settle a write that replayed successfully: confirm its optimistic layer against the echoed commit cursor BEFORE resolving, so the gapless drop is in place when the awaiter (and any confirming frame) observes the settle. */
2131
2150
  private settleReplaySuccess;
2151
+ /**
2152
+ * The entry a shard's cursor lives under.
2153
+ *
2154
+ * Only the server knows that an omitted `shardKey` and an explicit one
2155
+ * spelling out its configured default name are the same shard — the default
2156
+ * is server-side configuration the client never sees. Keying on what was
2157
+ * SENT would split one shard's cursor across two entries, so a write under
2158
+ * one spelling would stop constraining a read under the other. Resolving
2159
+ * `undefined` through the learned name is what keeps both spellings on one
2160
+ * entry.
2161
+ */
2162
+ private cursorKeyFor;
2163
+ /**
2164
+ * Learn the server's own name for the default shard from a response to a
2165
+ * call that named no shard.
2166
+ *
2167
+ * Any cursor recorded before the name was known sits under the placeholder
2168
+ * entry, so it is folded in rather than stranded — otherwise the requirement
2169
+ * from a client's first write would be lost exactly once, which is the kind
2170
+ * of gap that only shows up as a stale read under load.
2171
+ */
2172
+ private learnDefaultShardKey;
2173
+ /**
2174
+ * Record the cursor a write committed at as this shard's read-your-writes
2175
+ * requirement.
2176
+ *
2177
+ * Monotonic: responses can land out of order, and moving the requirement
2178
+ * BACKWARDS would let a later read be answered from a replica copy that
2179
+ * predates a write this client already saw.
2180
+ */
2181
+ private recordShardCursor;
2132
2182
  /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
2133
2183
  private settleReplayTerminal;
2134
2184
  /**
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-MI8BwMXt.mjs";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-w4VrTsKH.js";
2
2
  import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
3
  /**
4
4
  * Reactive key-value store for local-only client state.
@@ -499,6 +499,24 @@ declare class LunoraClient {
499
499
  private readonly outbox;
500
500
  /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
501
501
  private readonly clientId;
502
+ /**
503
+ * Highest CDC cursor this client has seen a write commit at, per shard key
504
+ * (`""` for the default shard) — the read-your-writes bookmark sent as
505
+ * `x-lunora-min-seq`.
506
+ *
507
+ * In memory only, and deliberately: it exists to keep THIS session's reads
508
+ * behind THIS session's writes. Persisting it across reloads would pin a
509
+ * fresh page to a cursor it has no reason to require and force needless
510
+ * fallbacks to the owner.
511
+ */
512
+ private readonly shardCursors;
513
+ /**
514
+ * The server's own name for the default shard (`defaultShardKey`), learned
515
+ * from the first response to a call that named no shard. `undefined` until
516
+ * then, which is why `cursorKeyFor` falls back to a placeholder entry that
517
+ * `learnDefaultShardKey` folds in once the name arrives.
518
+ */
519
+ private defaultShardKey;
502
520
  /**
503
521
  * `true` when the constructor's hydration microtask has finished loading the
504
522
  * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
@@ -1690,6 +1708,7 @@ declare class LunoraClient {
1690
1708
  * reconnect can't OOM the page.
1691
1709
  */
1692
1710
  stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F>, options?: {
1711
+ durable?: boolean;
1693
1712
  maxBuffer?: number;
1694
1713
  shardKey?: string;
1695
1714
  }): StreamIterable<ReturnOf<F>>;
@@ -2129,6 +2148,37 @@ declare class LunoraClient {
2129
2148
  private passesReplayIdentityGate;
2130
2149
  /** Settle a write that replayed successfully: confirm its optimistic layer against the echoed commit cursor BEFORE resolving, so the gapless drop is in place when the awaiter (and any confirming frame) observes the settle. */
2131
2150
  private settleReplaySuccess;
2151
+ /**
2152
+ * The entry a shard's cursor lives under.
2153
+ *
2154
+ * Only the server knows that an omitted `shardKey` and an explicit one
2155
+ * spelling out its configured default name are the same shard — the default
2156
+ * is server-side configuration the client never sees. Keying on what was
2157
+ * SENT would split one shard's cursor across two entries, so a write under
2158
+ * one spelling would stop constraining a read under the other. Resolving
2159
+ * `undefined` through the learned name is what keeps both spellings on one
2160
+ * entry.
2161
+ */
2162
+ private cursorKeyFor;
2163
+ /**
2164
+ * Learn the server's own name for the default shard from a response to a
2165
+ * call that named no shard.
2166
+ *
2167
+ * Any cursor recorded before the name was known sits under the placeholder
2168
+ * entry, so it is folded in rather than stranded — otherwise the requirement
2169
+ * from a client's first write would be lost exactly once, which is the kind
2170
+ * of gap that only shows up as a stale read under load.
2171
+ */
2172
+ private learnDefaultShardKey;
2173
+ /**
2174
+ * Record the cursor a write committed at as this shard's read-your-writes
2175
+ * requirement.
2176
+ *
2177
+ * Monotonic: responses can land out of order, and moving the requirement
2178
+ * BACKWARDS would let a later read be answered from a replica copy that
2179
+ * predates a write this client already saw.
2180
+ */
2181
+ private recordShardCursor;
2132
2182
  /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
2133
2183
  private settleReplayTerminal;
2134
2184
  /**
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "./lunora-client.d-B-hIlqf_.mjs";
2
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-MI8BwMXt.mjs";
1
+ import { L as LunoraClient } from "./lunora-client.d-DbRRvSya.mjs";
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-w4VrTsKH.mjs";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
5
5
  * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
@@ -1,5 +1,5 @@
1
- import { L as LunoraClient } from "./lunora-client.d-Rv8-L9mJ.js";
2
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-MI8BwMXt.js";
1
+ import { L as LunoraClient } from "./lunora-client.d-Kd72FRSr.js";
2
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-w4VrTsKH.js";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
5
5
  * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
@@ -551,6 +551,17 @@ interface ClientStreamMessage {
551
551
  functionPath: string;
552
552
  shardKey?: string;
553
553
  };
554
+ /**
555
+ * Resume watermark: the highest chunk `seq` this client already received.
556
+ * Only meaningful for a stream the server declared `durable` — the run
557
+ * replays everything after it and then continues live, which is what turns
558
+ * a reconnect into a resume instead of a lost generation. Omitted on a
559
+ * first attach.
560
+ *
561
+ * Named `sinceChunk`, not `sinceSeq`, because a subscribe envelope already
562
+ * carries a `query.sinceSeq` meaning the CDC cursor.
563
+ */
564
+ sinceChunk?: number;
554
565
  type: "stream";
555
566
  }
556
567
  /**
@@ -652,6 +663,13 @@ interface ServerCompleteMessage {
652
663
  interface ServerChunkMessage {
653
664
  data: unknown;
654
665
  id: string;
666
+ /**
667
+ * Monotonic position of this chunk within a **durable** run, starting at 1.
668
+ * The client stores the last one it saw and replays it as
669
+ * {@link ClientStreamMessage.sinceChunk} when the socket comes back. Absent
670
+ * on an ephemeral stream, which has nothing to resume from.
671
+ */
672
+ seq?: number;
655
673
  type: "chunk";
656
674
  }
657
675
  /**
@@ -551,6 +551,17 @@ interface ClientStreamMessage {
551
551
  functionPath: string;
552
552
  shardKey?: string;
553
553
  };
554
+ /**
555
+ * Resume watermark: the highest chunk `seq` this client already received.
556
+ * Only meaningful for a stream the server declared `durable` — the run
557
+ * replays everything after it and then continues live, which is what turns
558
+ * a reconnect into a resume instead of a lost generation. Omitted on a
559
+ * first attach.
560
+ *
561
+ * Named `sinceChunk`, not `sinceSeq`, because a subscribe envelope already
562
+ * carries a `query.sinceSeq` meaning the CDC cursor.
563
+ */
564
+ sinceChunk?: number;
554
565
  type: "stream";
555
566
  }
556
567
  /**
@@ -652,6 +663,13 @@ interface ServerCompleteMessage {
652
663
  interface ServerChunkMessage {
653
664
  data: unknown;
654
665
  id: string;
666
+ /**
667
+ * Monotonic position of this chunk within a **durable** run, starting at 1.
668
+ * The client stores the last one it saw and replays it as
669
+ * {@link ClientStreamMessage.sinceChunk} when the socket comes back. Absent
670
+ * on an ephemeral stream, which has nothing to resume from.
671
+ */
672
+ seq?: number;
655
673
  type: "chunk";
656
674
  }
657
675
  /**
@@ -1,6 +1,6 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-MI8BwMXt.mjs";
2
- import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
3
- export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-w4VrTsKH.mjs";
2
+ import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
3
+ export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1,6 +1,6 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-MI8BwMXt.js";
2
- import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
3
- export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-w4VrTsKH.js";
2
+ import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
3
+ export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-MI8BwMXt.mjs";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-w4VrTsKH.mjs";
2
2
  /**
3
3
  * The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
4
4
  * route; the envelope shape below is that route's documented contract.
package/dist/service.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-MI8BwMXt.js";
1
+ import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-w4VrTsKH.js";
2
2
  /**
3
3
  * The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
4
4
  * route; the envelope shape below is that route's documented contract.
@@ -1,7 +1,7 @@
1
- import { P as Preloaded } from "../packem_shared/types.d-MI8BwMXt.mjs";
2
- export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-MI8BwMXt.mjs";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-C6emVQoK.mjs";
4
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
1
+ import { P as Preloaded } from "../packem_shared/types.d-w4VrTsKH.mjs";
2
+ export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-w4VrTsKH.mjs";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-BmSiP8F_.mjs";
4
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-DbRRvSya.mjs";
5
5
  import '@lunora/runtime';
6
6
  /**
7
7
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1,7 +1,7 @@
1
- import { P as Preloaded } from "../packem_shared/types.d-MI8BwMXt.js";
2
- export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-MI8BwMXt.js";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-CBi9DddN.js";
4
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
1
+ import { P as Preloaded } from "../packem_shared/types.d-w4VrTsKH.js";
2
+ export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-w4VrTsKH.js";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-D55TcvEq.js";
4
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-Kd72FRSr.js";
5
5
  import '@lunora/runtime';
6
6
  /**
7
7
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1 +1 @@
1
- import{getServerSession as o}from"../packem_shared/getServerSession-CGjgRBAE.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-BKDKj3mJ.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-DjwSjFwt.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
1
+ import{getServerSession as o}from"../packem_shared/getServerSession-CGjgRBAE.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-BU2gC5p6.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-DjwSjFwt.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/client",
3
- "version": "1.0.0-alpha.45",
3
+ "version": "1.0.0-alpha.47",
4
4
  "description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -70,7 +70,7 @@
70
70
  "access": "public"
71
71
  },
72
72
  "dependencies": {
73
- "@lunora/errors": "1.0.0-alpha.18",
73
+ "@lunora/errors": "1.0.0-alpha.21",
74
74
  "@visulima/storage-client": "1.0.0"
75
75
  },
76
76
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{s as b,a as B}from"./wire-codec-D_fiax9d.mjs";import{t as I}from"./wire-key-j8BZ65HQ.mjs";import D from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as j}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as H}from"./TabCoordinator-CMFYQCL-.mjs";import{isMutationDelta as V,applyDelta as J}from"./applyDelta-DXqQORbM.mjs";import{httpStream as X}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Y,c as Z}from"./local-store-DFMSEM2j.mjs";import{h as tt,u as K,d as et,s as st}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as it}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as nt,queryCacheKey as R}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as rt}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-C72rCp44.mjs";const L=500,at=(h,t)=>{if(h.size<t)return;const e=h.keys().next().value;e!==void 0&&h.delete(e)};class C{listeners=new Set;add(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(...t){const[e]=t;for(const s of this.listeners)try{s(e)}catch{}}clear(){this.listeners.clear()}}const ot="/_lunora/rpc",Q="/_lunora/rpc-batch",ct="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,O=h=>{for(let t=h.length-1;t>=0;t-=1)h[t]?.()},ht=(h,t)=>{for(const e of t)e.op==="delete"?h.delete(e.key):e.value!==void 0&&h.set(e.key,e.value)},dt="lunora-ping",ut=3e4,lt=1e4,pt=250,mt=64,ft="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",gt="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",St="/_lunora/admin/scheduled/dead",kt="/_lunora/admin/scheduled/dead/retry",wt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",Tt="/_lunora/admin/workflows/instance",It="/_lunora/admin/workflows/status",x="/_lunora/admin/storage",Ot="/_lunora/admin/storage/url",Et="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",Ft="/_lunora/admin/cron-jobs",Pt="/_lunora/admin/cron-jobs/run",At="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Lt="/_lunora/admin/global/tables",Mt="/_lunora/admin/global/table",xt="/_lunora/admin/global/facet",$t="/_lunora/admin/vector/indexes",Kt="/_lunora/admin/vector/query",qt="/_lunora/admin/logs/archive",Qt="/_lunora/admin/kv/namespaces",Ut="/_lunora/admin/kv/keys",$="/_lunora/admin/kv/value",Nt="/_lunora/admin/auth/users",Bt="/_lunora/admin/auth/sessions",Wt="/_lunora/admin/auth/users/create",zt="/_lunora/admin/auth/users/role",Gt="/_lunora/admin/auth/users/ban",Dt="/_lunora/admin/auth/users/unban",jt="/_lunora/admin/auth/users/password",Ht="/_lunora/admin/auth/users/remove",Vt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Xt="/_lunora/admin/auth/sessions/revoke-all",Yt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",te="/_lunora/admin/auth/accounts",ee="/_lunora/admin/auth/accounts/unlink",se="/_lunora/admin/auth/passkeys",ie="/_lunora/admin/auth/passkeys/delete",ne="/_lunora/admin/auth/two-factor/disable",re="/_lunora/admin/auth/organizations",ae="/_lunora/admin/auth/organizations/members",oe="/_lunora/admin/auth/organizations/invitations",ce="/_lunora/admin/auth/organizations/members/remove",he="/_lunora/admin/auth/organizations/invitations/cancel",de="/_lunora/admin/auth/config",ue="/_lunora/admin/auth/organizations/create",le="/_lunora/admin/auth/organizations/update",pe="/_lunora/admin/auth/organizations/remove",me="/_lunora/admin/auth/organizations/members/add",fe="/_lunora/admin/auth/organizations/members/invite",ye="/_lunora/admin/auth/organizations/members/role",ge="/_lunora/admin/auth/organizations/teams",be="/_lunora/admin/auth/organizations/teams/create",ve="/_lunora/admin/auth/organizations/teams/update",Se="/_lunora/admin/auth/organizations/teams/remove",ke="/_lunora/admin/auth/organizations/teams/members",we="/_lunora/admin/auth/organizations/teams/members/add",Ce="/_lunora/admin/auth/organizations/teams/members/remove",Te="/_lunora/admin/auth/organizations/roles",Ie="/_lunora/admin/auth/organizations/roles/create",Oe="/_lunora/admin/auth/organizations/roles/update",Ee="/_lunora/admin/auth/organizations/roles/remove",_e="/api/auth",Fe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,S=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[i,n]of Object.entries(t))n!==void 0&&n!==""&&e.set(i,String(n));const s=e.toString();return s===""?h:`${h}?${s}`},m=h=>h??"",W=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,i=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??i??t}},Pe=h=>{const{code:t,messageText:e}=W(h,"stream error");return t===void 0?new Error(e):new p(t,e)},N=h=>{const{code:t,messageText:e}=W(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Ae=new TextDecoder,Re=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Ae.decode(h)},g=(h,t)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(t)),!0}catch{return!1}},T=h=>{const t=new Error(h.message??"request failed");return t.code=h.code,h.data!==void 0&&(t.data=b(h.data)),h.hint!==void 0&&(t.hint=h.hint),h.docsUrl!==void 0&&(t.docsUrl=h.docsUrl),t},k=(h,t)=>{try{return B(h)}catch(e){const s=e instanceof Error?e.message:String(e);throw new TypeError(`LunoraClient: cannot encode ${t} — ${s}`,e instanceof Error?{cause:e}:void 0)}},Le=(h,t)=>{const e=Array.from({length:t});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=t)continue;const i=s.body;e[s.id]=i&&"error"in i&&i.error?{error:T(i.error),ok:!1}:{ok:!0,value:b(i?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Me=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),xe=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(t,e){return{defaultValue:e,key:t}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(t){this.url=t.url,this.wsUrl=t.wsUrl??S(U(t.url),ct),this.wsToken=t.wsToken;const e=t.authBasePath??_e;this.authBasePath=e.endsWith("/")?e.slice(0,-1):e,this.fetchImpl=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=t.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=t.bookmarkStorage??D(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??ut,this.connectTimeoutMs=t.connectTimeoutMs??lt,this.defaultConnectionContext=t.connectionContext,this.persistence=it(t.persistence,t.outbox===void 0),this.persistenceVersion=t.persistenceVersion,this.queryCache=nt(t.queryCache),this.onPersistenceError=t.offlineQueue?.onPersistenceError,this.clientQueryStore=new j,t.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,t.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=xe),this.offlineQueue=new tt(t.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${K()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(t,e){const s=this.authToken!==t,i=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const n=this.identityFingerprint();if(n!==i&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(i,n),this.tabCoordinator)){const r=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),r&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(t)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(t){return this.clientWatermarks.get(t??"")??0}async callMutator(t,e,s){const i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const n=s?.shardKey??"";let r;const a=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o=>{r=o}});return r!==void 0&&r>(this.clientWatermarks.get(n)??0)&&this.clientWatermarks.set(n,r),{applied:r===void 0||r===i,result:a}}onAuthTokenChange(t){return this.authTokenListeners.add(t)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const t={};this.authToken&&(t.authorization=`Bearer ${this.authToken}`);try{const e=await this.fetchImpl(S(this.url,`${this.authBasePath}${Fe}`),{credentials:"include",headers:t,method:"GET"});return e.ok?(await e.json())?.user??null:null}catch{return null}}setWsToken(t){if(this.wsToken!==t){this.wsToken=t;for(const e of this.connections.values())if(e.socket)try{e.socket.close()}catch{}}}setConnectionContext(t,e={}){const s=m(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=m(e.shardKey),i={context:t},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let r=!1;return()=>{if(r)return;r=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(i);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const i=m(s.shardKey);let n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let r=n.get(t);const a=r===void 0;if(r||(r=new Set,n.set(t,r)),r.add(e),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:t,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(i),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(i);const d=this.getConnection(s.shardKey);d&&g(d,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey);i&&g(i,{data:k(e??null,`whisper data for topic '${t}'`),topic:t,type:"whisper"})}onTokenExpired(t){return this.tokenExpiredListeners.add(t)}connectionStatus(){return this.computeStatus()}onConnectionStatus(t){const e=this.statusListeners.add(t);return t(this.computeStatus()),e}pendingCount(){return this.offlineQueue.size}debug(){const t=[],e=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(const i of e){const n=this.connections.get(i);t.push({confirmedMutationWatermark:this.clientWatermarks.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}const s=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(const i of this.shapeSubscriptions.values())s.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:s.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(t){const e=this.pendingChangeListeners.add(t);return t(this.offlineQueue.size),e}onMutationSettled(t){return this.mutationSettledListeners.add(t)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(t){return this.clientQueryStore.get(t)}setClientQuery(t,e){this.clientQueryStore.set(t,e)}subscribeClientQuery(t,e){return this.clientQueryStore.subscribe(t,e)}resetClientQuery(t){this.clientQueryStore.reset(t)}snapshotPrecondition(t,e,s){const i=this.peekActiveQueryValue(t.__lunoraRef,e,s),n=i===void 0?void 0:I(i);return()=>{const r=this.peekActiveQueryValue(t.__lunoraRef,e,s);return n===void 0&&r===void 0?!0:n===void 0||r===void 0?!1:I(r)===n}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const i=I(e),n=R(t,i,s),r=this.hydratedQueryCache.get(n);if(r!==void 0)return r.identity===this.identityFingerprint()?r.value:void 0}peekActiveQueryValue(t,e,s){const i=w.key(t,e,s);return this.subscriptions.get(i)?.lastValue}async query(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey,{attachBookmark:!0})}async batch(t){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(S(this.url,Q),{body:JSON.stringify({calls:t.map((n,r)=>({args:k(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:r,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await e.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||i.error&&!i.results)throw i.error?T(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);return Le(i.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const i=e,n=s.mutationId??K(),{confirms:r,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,r);const{hasSocket:o,wasEverConnected:c,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:u}=this.offlineQueue,l=c||u,y=this.WebSocketImpl!==void 0&&l;if(d!=="open"&&!o&&y||d==="connecting"&&l)return this.enqueueOfflineMutation(t,i,s.shardKey,n,a,r,s.precondition);try{let v;const G=await this.rpc(t.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:_=>{v=_}});for(const _ of r)_(v);return G}catch(v){throw O(a),v}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(c=>({rows:c})),r=e.length;let a=0,o=0;for(let c=0;c<r;c+=i){const d=e.slice(c,c+i),u=o;await this.mutation(t,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:r})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(ft,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(yt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(gt,"GET");return{backlog:t.backlog??0,inFlight:t.inFlight??0,pools:t.pools??[]}}async cancelScheduledJob(t){return this.assertOpen(),{cancelled:(await this.adminFetch(vt,"POST",{id:t})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(St,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(kt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(wt,"POST",{id:t})).removed===!0}}async listWorkflowInstances(t){this.assertOpen();const e=new URLSearchParams({name:t.name});t.status!==void 0&&e.set("status",t.status),t.page!==void 0&&e.set("page",String(t.page)),t.perPage!==void 0&&e.set("perPage",String(t.perPage));const s=await this.adminFetch(`${Ct}?${e.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??t.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(t){this.assertOpen();const e=new URLSearchParams({id:t.id,name:t.name}),s=await this.adminFetch(`${Tt}?${e.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??t.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(t){return this.assertOpen(),{status:(await this.adminFetch(It,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=S(U(this.url),bt),s=q(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,r=!1;const a=()=>{r||(n=setTimeout(d,s.next()))},o=u=>{if(r||this.WebSocketImpl===void 0)return;const l=u===void 0?e:`${e}?token=${encodeURIComponent(u)}`;this.openManagedSocket(i,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const v=JSON.parse(typeof y.data=="string"?y.data:"");v.type==="jobs"&&Array.isArray(v.records)&&t(v.records)}catch{}},onOpen:()=>{s.reset()}})},c=async u=>{let l;try{l=await u()}catch{a();return}o(l)},d=()=>{if(r||this.WebSocketImpl===void 0)return;const{wsToken:u}=this;if(typeof u=="function"){c(u).catch(()=>{});return}o(u)};return d(),()=>{r=!0,n!==void 0&&clearTimeout(n),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(Pt,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(At,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(x,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),s=await this.adminFetch(e,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(t,e){this.assertOpen();const s=`${x}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted??!0,key:i.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Et,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${x}?key=${encodeURIComponent(t.key)}${M(t.bucket)}`,s=await this.adminFetch(e,"PUT",t.body,t.contentType);return{etag:s.etag,key:s.key??t.key}}async signedStorageUrl(t,e){this.assertOpen();const s=e?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Ot}?key=${encodeURIComponent(t)}${i}${M(e?.bucket)}`,r=await this.adminFetch(n,"GET");if(typeof r.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return r.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Lt,"GET")}async readGlobalTablePage(t){this.assertOpen();const e=new URLSearchParams({table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.offset!==void 0&&e.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Mt}?${e.toString()}`,"GET")}async facetGlobalColumn(t){this.assertOpen();const e=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${xt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($t,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch(Kt,"POST",t)).matches??[]}async queryLogArchive(t={}){this.assertOpen();const e=await this.adminFetch(qt,"POST",t);return{nextCursor:e.nextCursor,rows:e.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Qt,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Ut,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await this.adminFetch(e,"GET")}async getKvValue(t){this.assertOpen();const e=f($,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch($,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f($,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Nt,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminFetch(e,"GET")}async createAuthUser(t){return await this.adminFetch(Wt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(zt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Gt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(jt,"POST",t)}async removeAuthUser(t){await this.adminFetch(Ht,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Vt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Jt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Xt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Yt,"GET")}async updateAuthUser(t){return await this.adminFetch(Zt,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(te,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(ee,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(se,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){await this.adminFetch(ie,"POST",t)}async disableAuthTwoFactor(t){await this.adminFetch(ne,"POST",t)}async listAuthOrganizations(t={}){return await this.adminFetch(f(re,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(ae,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(ce,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(he,"POST",t)}async getAuthConfig(){return await this.adminFetch(de,"GET")}async createAuthOrganization(t){return await this.adminFetch(ue,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(pe,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(me,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ye,"POST",t)}async listAuthOrgTeams(t){const e=f(ge,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(be,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(ve,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(Se,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(ke,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(we,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Ce,"POST",t)}async listAuthOrgRoles(t){const e=f(Te,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Ie,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(Ee,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Bt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,i={}){this.assertOpen();const n=e??{},r=w.key(t.__lunoraRef,n,i.shardKey);let a=this.subscriptions.get(r);const o=s,c=i.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=I(n),y=this.takeHydratedCache(t.__lunoraRef,l,i.shardKey);a={acked:!1,args:n,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:u,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:i.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),i.onCheckpoint&&a.checkpointCallbacks.add(i.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(a);const d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),i.onCheckpoint&&d.checkpointCallbacks.delete(i.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const i=`shape_${this.nextShapeId.toString()}`,n={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:t.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:t.args===void 0?void 0:k(t.args,`shape args for '${t.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,r=e??{},{handle:a,iterable:o}=rt({maxBuffer:s.maxBuffer,onCancel:()=>{const u=this.getConnection(n);u&&g(u,{id:i,type:"unsubscribe"}),this.streams.delete(i)}});this.streams.set(i,{handle:a,shardKey:n}),this.ensureSocket(n);const c=this.getConnection(n),d={id:i,query:{args:k(r,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:n},type:"stream"};if(!(c?.wsState==="open"&&g(c,d))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=mt;){const u=c.pendingStreams.shift()?.id,l=u?this.streams.get(u):void 0;l&&(l.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(u))}c.pendingStreams.push(d)}return o}httpStream(t,e,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return X(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const t of this.streams.values())t.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const t of this.connections.values())this.teardownConnection(t);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}teardownConnection(t){if(t.reconnectTimer!==void 0&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),this.stopHeartbeat(t),t.socket){try{t.socket.close()}catch{}t.socket=void 0}t.wsState="closed"}createTabCoordinator(){const t=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new H({channelName:t,onBecomeLeader:()=>{for(const e of this.subscriptions.all())this.ensureSocket(e.shardKey),this.sendSubscribeIfOpen(e);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[e,s]of this.connections)this.teardownConnection(s),this.connections.delete(e);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(e,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const i=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,i,n,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,i!==void 0&&(a.serverCursor=i,n!==void 0&&(a.serverEpoch=n),F(a,i)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const i=this.subscriptions.get(e);i&&E(i.errorCallbacks,s)},onSubscriptionSettled:(e,s,i,n,r,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,i),n!==void 0&&r===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,n));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(t,e,s,i,n,r,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:e,clientId:this.clientId,functionPath:t.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw O(n),d instanceof Error?d:new Error(String(d))}for(const d of r)d(void 0);return}return new Promise((c,d)=>{const u={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of r)y(l)},reject:l=>{this.queuedIdentities.delete(i),O(n),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const t=await this.offlineQueue.hydrate();for(const e of t)this.queuedOfflineShardKeys.add(e),this.ensureSocket(e)}catch{}}hydrateAsOutboxLeader(){const t=()=>{this.hydratePersistedQueue().catch(()=>{})},e=globalThis.navigator?.locks;if(!e){t();return}e.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||t(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(t)}async hydrateQueryCache(){if(this.queryCache)try{const t=await this.queryCache.load();for(const{key:e,...s}of t){if(et(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const i=R(t,e,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.hydratedQueryCache.delete(i),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=R(t.fn.__lunoraRef,t.argsKey,t.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:t.serverCursor,ts:Date.now(),value:e,...t.serverEpoch===void 0?{}:{serverEpoch:t.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},pt)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:t}=this;if(!t){this.pendingCacheWrites.clear();return}const e=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(e.map(([s,i])=>t.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const t=[...this.connections.values()];return t.length===0?"idle":t.some(e=>e.wsState==="open")?"connected":t.some(e=>e.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const t=this.computeStatus();t!==this.lastStatus&&(this.lastStatus=t,this.statusListeners.emit(t),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(t,this.identityFingerprint()))}emitItemSettled(t,e,s){this.mutationSettledListeners.emit({args:t.args,code:s===void 0?void 0:s.code,error:s,functionPath:t.functionPath,hadAwaiter:t.liveAwaiter??!1,id:t.id??"",shardKey:t.shardKey,status:e})}applyOptimisticUpdates(t,e,s,i){const n=[],r=[];if(!i)return{confirms:n,rollbacks:r};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Y(o,i);c&&(n.push(c.confirm),r.push(c.rollback))}return{confirms:n,rollbacks:r}}applyOptimisticUpdate(t,e,s,i,n){const{confirms:r,rollbacks:a,store:o}=Z(this.subscriptions,s);try{t(o,e)}catch{O(a);return}i.push(...a),n.push(...r)}getConnection(t){return this.connections.get(m(t))}sendOrQueueUnsubscribe(t,e,s){const i=this.getConnection(t);i&&!g(i,{id:e,type:s})&&i.pendingUnsubscribes.push({id:e,type:s})}connectionGateState(t){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const e=this.getConnection(t);return{hasSocket:e?.socket!==void 0,wasEverConnected:e?.wasEverConnected??!1,wsState:e?.wsState??"idle"}}getOrCreateConnection(t){const e=m(t);let s=this.connections.get(e);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:q(this.reconnectOptions),reconnectTimer:void 0,shardKey:t,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(e,s)),s}wsUrlFor(t,e){const s=[];if(t!==void 0&&s.push(`shard=${encodeURIComponent(t)}`),e!==void 0&&s.push(`token=${encodeURIComponent(e)}`),s.length===0)return this.wsUrl;const i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(t){const e={"content-type":"application/json"};if(this.authToken&&(e.authorization=`Bearer ${this.authToken}`),t.mutationId&&(e["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(e["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(e["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const s=this.bookmark.get();s&&(e["x-d1-bookmark"]=s)}return e}async rpc(t,e,s,i={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(i),r=await this.fetchImpl(S(this.url,ot),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){const o=r.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await r.json()}catch{const o=r.statusText?` ${r.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${r.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${r.status.toString()}${o})`)}return i.onMutationAck?.(a.lastMutationId),i.onCommitCursor?.(a.commitCursor),b(a.result)}async adminFetch(t,e,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const r=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:r?(a=s,i!==void 0&&(n["content-type"]=i)):(a=JSON.stringify(s),n["content-type"]="application/json");const o=await this.fetchImpl(S(this.url,t),{body:a,headers:n,method:e});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}effectiveConnectionContext(t){const e=this.connectionContextHolders.get(t);return e&&e.length>0?e[e.length-1]?.context:this.connectionContexts.get(t)??this.defaultConnectionContext}refreshConnectionContext(t){const e=this.connections.get(t);e?.wsState==="open"&&this.sendConnectEnvelope(e)}sendConnectEnvelope(t){const e=this.effectiveConnectionContext(m(t.shardKey));g(t,{clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())m(e.shardKey)===m(t)&&this.sendShapeSubscribeIfOpen(e)}ensureSocket(t){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const e=this.getOrCreateConnection(t);if(!(e.wsState==="open"||e.wsState==="connecting")){if(e.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(e,t,this.wsToken).catch(()=>{});return}this.openSocket(e,t,this.wsToken)}}async openSocketWithProvidedToken(t,e,s){let i;try{i=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,i)}openManagedSocket(t,e,s,i){const{WebSocketImpl:n}=this;if(n===void 0)throw new p("INTERNAL","no WebSocket implementation available");const r=new n(e);t.socket=r;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===r&&(t.socket=void 0)},o=c=>{a(),i.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===r){try{r.close()}catch{}o()}},s)),r.addEventListener("open",()=>{t.socket===r&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),i.onOpen(),this.startHeartbeat(t,o))}),r.addEventListener("message",c=>{t.socket===r&&(t.lastFrameAt=Date.now(),i.onMessage(c))}),r.addEventListener("close",c=>{t.socket===r&&o(c)}),r.addEventListener("error",()=>{t.socket===r&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:i=>{this.handleServerMessage(i.data,e)},onOpen:()=>{t.wsState="open",t.wasEverConnected=!0,t.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(t),this.markShardPendingAck(e);for(const n of this.subscriptions.all())m(n.shardKey)===m(e)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const n=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:r,type:a}of n)g(t,{id:r,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const n=t.pendingStreams;t.pendingStreams=[];for(const r of n)g(t,r)}const i=this.whisperHandlers.get(m(e));if(i)for(const n of i.keys())g(t,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(e).catch(()=>{})}})}handleDisconnect(t){if(this.closed||t.wsState==="idle"||t.wsState==="closed")return;this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket=void 0,t.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(t.shardKey);const e=new Set((t.pendingStreams??[]).map(i=>i.id));for(const[i,n]of this.streams)m(n.shardKey)===m(t.shardKey)&&!e.has(i)&&(n.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i));if(this.WebSocketImpl===void 0)return;const s=t.reconnect.next();t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,this.ensureSocket(t.shardKey)},s)}startHeartbeat(t,e){this.stopHeartbeat(t),!(this.heartbeatIntervalMs<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;const{socket:s}=t;if(Date.now()-t.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}e();return}try{s.send(dt)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(t){t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)}markShardPendingAck(t){const e=m(t);for(const s of this.subscriptions.all())m(s.shardKey)===e&&(s.acked=!1)}sendSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);if(e?.wsState!=="open"||t.acked)return;const s=t.fn.__lunoraTable??t.fn.__lunoraRef;g(e,{id:t.id,query:{args:B(t.args),functionPath:t.fn.__lunoraRef,table:s,...t.serverCursor===void 0?{}:{sinceSeq:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);e?.wsState==="open"&&g(e,{id:t.id,shape:{name:t.name,...t.wireArgs===void 0?{}:{args:t.wireArgs}},type:"shape_subscribe",...t.serverCursor===void 0?{}:{sinceCheckpoint:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}})}handleServerMessage(t,e){const s=Re(t);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type){case"ack":{const n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,id:r}=i;this.streams.get(r)?.handle.push(b(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i);break}case"pokePart":{this.handlePokePart(i);break}case"pokeStart":{this.handlePokeStart(i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,e);break}}}handleErrorMessage(t){if(t.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:e}=t,s=e===void 0?void 0:this.streams.get(e);if(s&&e!==void 0){s.handle.fail(Pe(t)),this.streams.delete(e);return}const i=e===void 0?void 0:this.subscriptions.getById(e);if(i){E(i.errorCallbacks,N(t));return}const n=e===void 0?void 0:this.shapeSubscriptions.get(e);n&&E(n.errorCallbacks,N(t))}handlePokeStart(t){at(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(t.pokeId,{baseCheckpoint:t.baseCheckpoint,epoch:t.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(t){const e=this.pokeBuffers.get(t.pokeId);if(!e)return;const s=e.parts.get(t.shapeId)??[];for(const i of t.rowsPatch)s.push(i.value===void 0?i:{...i,value:b(i.value)});e.parts.set(t.shapeId,s),t.lastMutationId!==void 0&&e.lastMutationId.set(t.shapeId,t.lastMutationId)}handlePokeEnd(t){const e=this.pokeBuffers.get(t.pokeId);if(e){this.pokeBuffers.delete(t.pokeId);for(const[s,i]of e.parts){const n=this.shapeSubscriptions.get(s);if(!n)continue;const r=e.epoch!==void 0&&n.serverEpoch!==void 0&&e.epoch!==n.serverEpoch,a=e.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==e.baseCheckpoint;if(r||a){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}ht(n.rows,i),t.checkpoint!==void 0&&(n.serverCursor=t.checkpoint),t.epoch!==void 0&&(n.serverEpoch=t.epoch);const o=e.lastMutationId.get(s);o!==void 0&&(n.lastMutationId=o),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}emitShapeRows(t){const e=[...t.rows.values()];for(const s of t.callbacks)try{s(e)}catch{}}handleDataMessage(t){const{id:e}=t,s=e?this.subscriptions.getById(e):void 0;if(!s)return;const i=this.resolveDataPayload(t,s);if(s.serverBase=i,t.cursor!==void 0&&(s.serverCursor=t.cursor),t.epoch!==void 0&&(s.serverEpoch=t.epoch),t.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,t.lastMutationId);for(const n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),F(s,s.serverCursor),P(s,A(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(t){const e=this.subscriptions.getById(t.id);e&&this.ackAndAdvanceCursor(e,t.cursor,t.epoch)}handleSettledMessage(t){const e=this.subscriptions.getById(t.id);if(e){this.ackAndAdvanceCursor(e,t.cursor,t.epoch),t.lastMutationId!==void 0&&(e.lastMutationId=t.lastMutationId);for(const s of e.checkpointCallbacks)s({checkpoint:e.serverCursor,mutationId:e.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=w.key(e.fn.__lunoraRef,e.args,e.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,e.serverCursor,e.serverEpoch,e.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(t,e,s){t.acked=!0,(e!==void 0&&e!==t.serverCursor||s!==void 0&&s!==t.serverEpoch)&&(e!==void 0&&(t.serverCursor=e),s!==void 0&&(t.serverEpoch=s),this.persistQueryValue(t),F(t,t.serverCursor)&&P(t,A(t.serverBase,t.optimisticLayers)))}resolveDataPayload(t,e){if("data"in t&&t.data!==void 0)return b(t.data);const s=b(t.delta);if(V(s)&&e.serverBase!==void 0){const i=J(e.serverBase,s);if(i!==void 0)return i}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(m(e))?.get(t.topic);if(!s)return;const i=b(t.data);for(const n of s)try{n(i,t.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(t){const e=this.streams.get(t);if(e){e.handle.complete(),this.streams.delete(t);return}const s=this.subscriptions.getById(t);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(t){t&&this.persistence?.remove(t).catch(e=>{st(this.onPersistenceError,"remove",e,t)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const t=this.authToken;return t===null?null:this.hashToken(t)}hashToken(t){let e=2166136261,s=5381;for(let i=0;i<t.length;i+=1){const n=t.charCodeAt(i);e^=n,e=Math.imul(e,16777619),s=Math.imul(s,33)+n}return`${t.length.toString(36)}:${(e>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(t){if(t===null||t.startsWith("subj:"))return!1;const e=this.authToken;return e===null?!1:this.hashToken(e)===t}rejectQueuedForIdentityChange(){const t=this.offlineQueue.drain();for(const e of t){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",e.reject(s),this.emitItemSettled(e,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(t,e){for(const[s,i]of this.queuedIdentities)i===t&&this.queuedIdentities.set(s,e)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const t of this.queuedOfflineShardKeys)this.flushOfflineQueue(t).catch(()=>{})}async flushOfflineQueue(t){const e=this.offlineQueue.drainConflict();for(const c of e){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=m(t),i=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(i.length===0)return;const n=this.identityFingerprint(),r=[];for(const c of i)this.passesReplayIdentityGate(c,n)&&r.push(c);if(r.length===0)return;const a=this.encodableOrSettleTerminal(r);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=L){const d=a.slice(c,c+L),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+L));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(t){const e=[];for(const s of t)try{k(s.args,`args for '${s.functionPath}'`),e.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),i=s===void 0?t.identity:s;if(i!==void 0&&i!==e&&!this.isSameCredentialUnderTokenHash(i)){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",t.reject(n),this.emitItemSettled(t,"rejected",n),!1}return this.queuedIdentities.delete(t.id??""),!0}settleReplaySuccess(t,e,s){this.unpersist(t.id),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}settleReplayTerminal(t,e){this.unpersist(t.id),t.reject(e),this.emitItemSettled(t,"rejected",e)}async replaySequential(t){for(let e=0;e<t.length;e+=1){const s=t[e];if(s)try{let i;const n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:r=>{i=r}});this.settleReplaySuccess(s,n,i)}catch(i){if(i.code!==void 0){this.settleReplayTerminal(s,i);continue}this.offlineQueue.requeue(t.slice(e));return}}}async replayBatched(t){if(!this.fetchImpl)return{requeue:t,stop:!0};let e;try{e=await this.fetchImpl(S(this.url,Q),{body:JSON.stringify({calls:t.map((n,r)=>({args:k(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:r,clientId:n.clientId??this.clientId,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:t,stop:!0}}const s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await e.json()}catch{return{requeue:t,stop:!0}}if(!i.results){if(i.error){const n=T(i.error);for(const r of t)this.settleReplayTerminal(r,n);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,i.results),stop:!1}}settleReplayBatchSlots(t,e){const s=new Map;for(const n of e)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);const i=[];for(const[n,r]of t.entries()){const a=s.get(n);a===void 0?i.push(r):"error"in a?Me.has(a.error.code)?i.push(r):this.settleReplayTerminal(r,T(a.error)):this.settleReplaySuccess(r,b(a.result),a.commitCursor)}return i}}export{z as LunoraClient};