@lunora/client 1.0.0-alpha.253 → 1.0.0-alpha.254

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -94,7 +94,8 @@ client.close();
94
94
  ## Related
95
95
 
96
96
  - [`@lunora/react`](https://www.npmjs.com/package/@lunora/react) — React hooks built on this client.
97
- - `@lunora/client/query` — the shared live-query state machine every UI adapter builds on (subpath of this package).
97
+ - `@lunora/client/query` — the shared live-query state machine every UI adapter builds on, plus the TanStack Query key contract and `lunoraQueryOptions` factory (subpath of this package).
98
+ - `@lunora/client/auth` — the identity store and auth-gate contract, plus the framework-neutral core of the admin/organization list hooks (subpath of this package).
98
99
  - `@lunora/client/ssr` — server-side preloading over this client's HTTP transport (subpath of this package).
99
100
 
100
101
  ## Supported Node.js Versions
@@ -1,7 +1,108 @@
1
- import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-ChRS_d1s.mjs";
1
+ /**
2
+ * `@lunora/client/auth` — framework-agnostic identity store, and the auth-gate
3
+ * contract every UI adapter implements.
4
+ *
5
+ * The `LunoraClient` is framework-neutral and exposes auth through an async
6
+ * `getCurrentUser()` plus `onAuthTokenChange`. This module lifts the per-client
7
+ * identity caching and listener-fan-out into a shared store that every UI
8
+ * adapter (React, Vue, Solid, Svelte, Angular) consumes, so only one fetch runs
9
+ * at a time and all mounted hooks re-render together when identity resolves or
10
+ * the token changes.
11
+ *
12
+ * ## The auth-gate contract
13
+ *
14
+ * **Read this before adding or changing a gate in any adapter.** Five adapters
15
+ * expose the same three-state gate, and they must agree on what each state
16
+ * means; deriving a gate from `user !== null` (or from the token alone) is how
17
+ * they last disagreed. The single source of truth is {@link AuthStatus}, and the
18
+ * two predicates {@link isAuthenticatedStatus} / {@link isLoadingStatus} — an
19
+ * adapter maps its reactive primitive onto those and adds nothing of its own.
20
+ *
21
+ * | status | meaning | gate |
22
+ * | ------------------ | ---------------------------------------------------------------- | --------------- |
23
+ * | `unauthenticated` | the server answered that there is no session | signed out |
24
+ * | `loading` | the first identity resolve is in flight | loading |
25
+ * | `authenticated` | the server returned a user | authenticated |
26
+ * | `unreachable` | a credential is held but the identity endpoint could not be reached | authenticated |
27
+ *
28
+ * No row says "no bearer token". A **cookie session carries no token here** —
29
+ * it is better-auth's default, what `@lunora/auth-ui` is built on, and what
30
+ * `examples/auth-playground` ships (`createAuthClient` plus
31
+ * `new LunoraClient({ url })`, never `setAuthToken`). Answering
32
+ * `unauthenticated` off a null token alone declared every user of every such
33
+ * app signed out without asking the server, which also left
34
+ * `LunoraClient`'s identity fingerprint `null` for all of them — and a
35
+ * fingerprint that is `null` for everyone is what turns the offline-queue,
36
+ * read-cache and socket identity gates into `null === null`. The first resolve
37
+ * therefore ALWAYS asks; only after an answer does a cleared token
38
+ * short-circuit.
39
+ *
40
+ * `unreachable` counts as authenticated because the **credential** is what
41
+ * authorises requests; a failed identity round-trip is a fact about the network,
42
+ * not about the session. Treating it as signed out turns every offline reload
43
+ * into a sign-out, and treating it as loading spins a fallback for the whole
44
+ * offline period — both of which shipped.
45
+ *
46
+ * The consequence a UI has to respect: `user` may be `null` while the gate says
47
+ * authenticated. Branch on `status`, never on `user === null`, to tell "signed
48
+ * out" from "signed in, identity not resolved yet".
49
+ */
50
+ import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-ChRS_d1s.mjs";
51
+ import { AuthPage, AuthSession, AuthUser } from '@lunora/runtime';
2
52
  import '@lunora/errors';
3
53
  import "../packem_shared/function-reference.d-Br_hsKje.mjs";
4
- import '@lunora/runtime';
54
+ /** Default page size for the first read; a "load more" grows the requested window by the page size. */
55
+ declare const ADMIN_AUTH_DEFAULT_PAGE_SIZE = 50;
56
+ /** One paged admin-auth collection: the key that identifies its inputs, and how to read a `{ limit }` window from the top. */
57
+ interface AdminAuthList<T> {
58
+ /** Read the first `limit` rows. `AuthPage` is offset/limit-based, so a larger window re-reads from the top rather than appending. */
59
+ readonly fetchPage: (limit: number) => Promise<AuthPage<T>>;
60
+ /** Every input that should invalidate the cache — not `fetchPage`, which is a fresh closure per call. */
61
+ readonly key: ReadonlyArray<unknown>;
62
+ }
63
+ /** Search / filter / sort inputs for {@link authUsersList}. */
64
+ interface AuthUsersListFilter {
65
+ filterField?: string;
66
+ filterValue?: string;
67
+ search?: string;
68
+ searchField?: string;
69
+ sortBy?: string;
70
+ sortDirection?: "asc" | "desc";
71
+ }
72
+ /** Users, via the admin-gated `GET /_lunora/admin/auth/users` (`client.listAuthUsers`). */
73
+ declare const authUsersList: (client: LunoraClient, filter?: AuthUsersListFilter) => AdminAuthList<AuthUser>;
74
+ /** Organizations (better-auth `organization` plugin), via `client.listAuthOrganizations`. */
75
+ declare const authOrganizationsList: (client: LunoraClient) => AdminAuthList<Record<string, unknown>>;
76
+ /** Sign-up invitations (`inviteOnly` plugin), via `client.listAuthSignUpInvitations`. Rows are unfiltered and newest-first. */
77
+ declare const authSignUpInvitationsList: (client: LunoraClient) => AdminAuthList<Record<string, unknown>>;
78
+ /** Auth sessions, optionally scoped to one user, via `client.listAuthSessions`. */
79
+ declare const authSessionsList: (client: LunoraClient, options?: {
80
+ userId?: string;
81
+ }) => AdminAuthList<AuthSession>;
82
+ /**
83
+ * The cache key for one window of an admin list: `[namespace, identity, ...list.key, limit]`.
84
+ *
85
+ * The acting identity (slot 1) partitions the cache, or a credential swap on the
86
+ * same client (admin A → admin B) would serve A's cached rows to B until the
87
+ * refetch lands. It is `client.currentIdentity()` — a `subj:` label or a
88
+ * non-reversible token hash — never the bearer token: query keys are not
89
+ * private (persisters write them to `localStorage`, devtools render them,
90
+ * telemetry logs them), and a same-user token refresh keeps the same key.
91
+ *
92
+ * An adapter that keeps the previous window visible while a larger one loads
93
+ * must only do so when slot 1 is unchanged, so one identity's rows never stand
94
+ * in for another's.
95
+ */
96
+ declare const adminAuthListQueryKey: (identity: string | null, list: AdminAuthList<unknown>, limit: number) => ReadonlyArray<unknown>;
97
+ /**
98
+ * Subscribe to every change of `client.currentIdentity()`. Both signals are
99
+ * needed: a bearer swap fires `onAuthTokenChange`, while a cookie session's
100
+ * user switch or sign-out fires only `onIdentityChange` (no token changes
101
+ * hands) — subscribing to one leaves the other's previous rows on screen.
102
+ */
103
+ declare const subscribeAdminAuthIdentity: (client: LunoraClient, onChange: () => void) => (() => void);
104
+ /** `true` when the server reports rows beyond the loaded window; `false` before the first page resolves, so "load more" past the end is a no-op. */
105
+ declare const adminAuthListHasMore: (page: AuthPage<unknown> | undefined) => boolean;
5
106
  /**
6
107
  * Every {@link AuthStatus}, as a value — the contract table in this module's
7
108
  * header, and the `@lunora/client` docs table that restates it for consumers,
@@ -48,4 +149,4 @@ interface IdentityStore {
48
149
  * returns the same store, keeping the single-fetch / fan-out invariant.
49
150
  */
50
151
  declare const getIdentityStore: (client: LunoraClient) => IdentityStore;
51
- export { AUTH_STATUSES, type AuthStatus, type IdentityStore, getIdentityStore, isAuthenticatedStatus, isLoadingStatus };
152
+ export { ADMIN_AUTH_DEFAULT_PAGE_SIZE, AUTH_STATUSES, type AdminAuthList, type AuthStatus, type AuthUsersListFilter, type IdentityStore, adminAuthListHasMore, adminAuthListQueryKey, authOrganizationsList, authSessionsList, authSignUpInvitationsList, authUsersList, getIdentityStore, isAuthenticatedStatus, isLoadingStatus, subscribeAdminAuthIdentity };
@@ -1,7 +1,108 @@
1
- import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-DNnOIB-r.js";
1
+ /**
2
+ * `@lunora/client/auth` — framework-agnostic identity store, and the auth-gate
3
+ * contract every UI adapter implements.
4
+ *
5
+ * The `LunoraClient` is framework-neutral and exposes auth through an async
6
+ * `getCurrentUser()` plus `onAuthTokenChange`. This module lifts the per-client
7
+ * identity caching and listener-fan-out into a shared store that every UI
8
+ * adapter (React, Vue, Solid, Svelte, Angular) consumes, so only one fetch runs
9
+ * at a time and all mounted hooks re-render together when identity resolves or
10
+ * the token changes.
11
+ *
12
+ * ## The auth-gate contract
13
+ *
14
+ * **Read this before adding or changing a gate in any adapter.** Five adapters
15
+ * expose the same three-state gate, and they must agree on what each state
16
+ * means; deriving a gate from `user !== null` (or from the token alone) is how
17
+ * they last disagreed. The single source of truth is {@link AuthStatus}, and the
18
+ * two predicates {@link isAuthenticatedStatus} / {@link isLoadingStatus} — an
19
+ * adapter maps its reactive primitive onto those and adds nothing of its own.
20
+ *
21
+ * | status | meaning | gate |
22
+ * | ------------------ | ---------------------------------------------------------------- | --------------- |
23
+ * | `unauthenticated` | the server answered that there is no session | signed out |
24
+ * | `loading` | the first identity resolve is in flight | loading |
25
+ * | `authenticated` | the server returned a user | authenticated |
26
+ * | `unreachable` | a credential is held but the identity endpoint could not be reached | authenticated |
27
+ *
28
+ * No row says "no bearer token". A **cookie session carries no token here** —
29
+ * it is better-auth's default, what `@lunora/auth-ui` is built on, and what
30
+ * `examples/auth-playground` ships (`createAuthClient` plus
31
+ * `new LunoraClient({ url })`, never `setAuthToken`). Answering
32
+ * `unauthenticated` off a null token alone declared every user of every such
33
+ * app signed out without asking the server, which also left
34
+ * `LunoraClient`'s identity fingerprint `null` for all of them — and a
35
+ * fingerprint that is `null` for everyone is what turns the offline-queue,
36
+ * read-cache and socket identity gates into `null === null`. The first resolve
37
+ * therefore ALWAYS asks; only after an answer does a cleared token
38
+ * short-circuit.
39
+ *
40
+ * `unreachable` counts as authenticated because the **credential** is what
41
+ * authorises requests; a failed identity round-trip is a fact about the network,
42
+ * not about the session. Treating it as signed out turns every offline reload
43
+ * into a sign-out, and treating it as loading spins a fallback for the whole
44
+ * offline period — both of which shipped.
45
+ *
46
+ * The consequence a UI has to respect: `user` may be `null` while the gate says
47
+ * authenticated. Branch on `status`, never on `user === null`, to tell "signed
48
+ * out" from "signed in, identity not resolved yet".
49
+ */
50
+ import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-DNnOIB-r.js";
51
+ import { AuthPage, AuthSession, AuthUser } from '@lunora/runtime';
2
52
  import '@lunora/errors';
3
53
  import "../packem_shared/function-reference.d-Br_hsKje.js";
4
- import '@lunora/runtime';
54
+ /** Default page size for the first read; a "load more" grows the requested window by the page size. */
55
+ declare const ADMIN_AUTH_DEFAULT_PAGE_SIZE = 50;
56
+ /** One paged admin-auth collection: the key that identifies its inputs, and how to read a `{ limit }` window from the top. */
57
+ interface AdminAuthList<T> {
58
+ /** Read the first `limit` rows. `AuthPage` is offset/limit-based, so a larger window re-reads from the top rather than appending. */
59
+ readonly fetchPage: (limit: number) => Promise<AuthPage<T>>;
60
+ /** Every input that should invalidate the cache — not `fetchPage`, which is a fresh closure per call. */
61
+ readonly key: ReadonlyArray<unknown>;
62
+ }
63
+ /** Search / filter / sort inputs for {@link authUsersList}. */
64
+ interface AuthUsersListFilter {
65
+ filterField?: string;
66
+ filterValue?: string;
67
+ search?: string;
68
+ searchField?: string;
69
+ sortBy?: string;
70
+ sortDirection?: "asc" | "desc";
71
+ }
72
+ /** Users, via the admin-gated `GET /_lunora/admin/auth/users` (`client.listAuthUsers`). */
73
+ declare const authUsersList: (client: LunoraClient, filter?: AuthUsersListFilter) => AdminAuthList<AuthUser>;
74
+ /** Organizations (better-auth `organization` plugin), via `client.listAuthOrganizations`. */
75
+ declare const authOrganizationsList: (client: LunoraClient) => AdminAuthList<Record<string, unknown>>;
76
+ /** Sign-up invitations (`inviteOnly` plugin), via `client.listAuthSignUpInvitations`. Rows are unfiltered and newest-first. */
77
+ declare const authSignUpInvitationsList: (client: LunoraClient) => AdminAuthList<Record<string, unknown>>;
78
+ /** Auth sessions, optionally scoped to one user, via `client.listAuthSessions`. */
79
+ declare const authSessionsList: (client: LunoraClient, options?: {
80
+ userId?: string;
81
+ }) => AdminAuthList<AuthSession>;
82
+ /**
83
+ * The cache key for one window of an admin list: `[namespace, identity, ...list.key, limit]`.
84
+ *
85
+ * The acting identity (slot 1) partitions the cache, or a credential swap on the
86
+ * same client (admin A → admin B) would serve A's cached rows to B until the
87
+ * refetch lands. It is `client.currentIdentity()` — a `subj:` label or a
88
+ * non-reversible token hash — never the bearer token: query keys are not
89
+ * private (persisters write them to `localStorage`, devtools render them,
90
+ * telemetry logs them), and a same-user token refresh keeps the same key.
91
+ *
92
+ * An adapter that keeps the previous window visible while a larger one loads
93
+ * must only do so when slot 1 is unchanged, so one identity's rows never stand
94
+ * in for another's.
95
+ */
96
+ declare const adminAuthListQueryKey: (identity: string | null, list: AdminAuthList<unknown>, limit: number) => ReadonlyArray<unknown>;
97
+ /**
98
+ * Subscribe to every change of `client.currentIdentity()`. Both signals are
99
+ * needed: a bearer swap fires `onAuthTokenChange`, while a cookie session's
100
+ * user switch or sign-out fires only `onIdentityChange` (no token changes
101
+ * hands) — subscribing to one leaves the other's previous rows on screen.
102
+ */
103
+ declare const subscribeAdminAuthIdentity: (client: LunoraClient, onChange: () => void) => (() => void);
104
+ /** `true` when the server reports rows beyond the loaded window; `false` before the first page resolves, so "load more" past the end is a no-op. */
105
+ declare const adminAuthListHasMore: (page: AuthPage<unknown> | undefined) => boolean;
5
106
  /**
6
107
  * Every {@link AuthStatus}, as a value — the contract table in this module's
7
108
  * header, and the `@lunora/client` docs table that restates it for consumers,
@@ -48,4 +149,4 @@ interface IdentityStore {
48
149
  * returns the same store, keeping the single-fetch / fan-out invariant.
49
150
  */
50
151
  declare const getIdentityStore: (client: LunoraClient) => IdentityStore;
51
- export { AUTH_STATUSES, type AuthStatus, type IdentityStore, getIdentityStore, isAuthenticatedStatus, isLoadingStatus };
152
+ export { ADMIN_AUTH_DEFAULT_PAGE_SIZE, AUTH_STATUSES, type AdminAuthList, type AuthStatus, type AuthUsersListFilter, type IdentityStore, adminAuthListHasMore, adminAuthListQueryKey, authOrganizationsList, authSessionsList, authSignUpInvitationsList, authUsersList, getIdentityStore, isAuthenticatedStatus, isLoadingStatus, subscribeAdminAuthIdentity };
@@ -1 +1 @@
1
- const b=["authenticated","loading","unauthenticated","unreachable"],y=t=>t==="authenticated"||t==="unreachable",A=t=>t==="loading",f=new WeakMap,S=t=>{const n=new Set;let u=null,s="loading",c=!1,h=!1,a;const g=()=>{for(const e of n)e()};let i=0;const r=(e,o)=>{(s!==e||u!==o)&&(s=e,u=o,g())},l=(e=!1)=>{i+=1;const o=i;if(!e&&t.getAuthToken()===null&&h){r("unauthenticated",null);return}r(u===null?"loading":"authenticated",u),t.getCurrentUser().then(d=>{o===i&&(h=!0,r(d===null?"unauthenticated":"authenticated",d),d!==null&&a===`subj:${d.id}`&&(a=void 0))}).catch(()=>{a=void 0,o===i&&r("unreachable",u)})};return t.expectIdentityResolution(),t.onAuthTokenChange(()=>{l()}),t.onIdentityChange(()=>{if(!c||t.getAuthToken()!==null)return;const e=t.currentIdentity();e===null?r("unauthenticated",null):e!==a&&(a=e,l(!0))}),t.onConnectionStatus(e=>{e==="connected"&&s==="unreachable"&&l(!0)}),{getStatus:()=>s,getUser:()=>u,subscribe:e=>(n.add(e),c||(c=!0,l()),()=>{n.delete(e)})}},T=t=>{let n=f.get(t);return n||(n=S(t),f.set(t,n)),n};export{b as AUTH_STATUSES,T as getIdentityStore,y as isAuthenticatedStatus,A as isLoadingStatus};
1
+ import{ADMIN_AUTH_DEFAULT_PAGE_SIZE as U,adminAuthListHasMore as k,adminAuthListQueryKey as p,authOrganizationsList as _,authSessionsList as m,authSignUpInvitationsList as v,authUsersList as E,subscribeAdminAuthIdentity as w}from"../packem_shared/ADMIN_AUTH_DEFAULT_PAGE_SIZE-V9c3bHU1.mjs";const S=["authenticated","loading","unauthenticated","unreachable"],y=t=>t==="authenticated"||t==="unreachable",b=t=>t==="loading",f=new WeakMap,A=t=>{const n=new Set;let u=null,r="loading",c=!1,h=!1,a;const g=()=>{for(const e of n)e()};let o=0;const s=(e,i)=>{(r!==e||u!==i)&&(r=e,u=i,g())},d=(e=!1)=>{o+=1;const i=o;if(!e&&t.getAuthToken()===null&&h){s("unauthenticated",null);return}s(u===null?"loading":"authenticated",u),t.getCurrentUser().then(l=>{i===o&&(h=!0,s(l===null?"unauthenticated":"authenticated",l),l!==null&&a===`subj:${l.id}`&&(a=void 0))}).catch(()=>{a=void 0,i===o&&s("unreachable",u)})};return t.expectIdentityResolution(),t.onAuthTokenChange(()=>{d()}),t.onIdentityChange(()=>{if(!c||t.getAuthToken()!==null)return;const e=t.currentIdentity();e===null?s("unauthenticated",null):e!==a&&(a=e,d(!0))}),t.onConnectionStatus(e=>{e==="connected"&&r==="unreachable"&&d(!0)}),{getStatus:()=>r,getUser:()=>u,subscribe:e=>(n.add(e),c||(c=!0,d()),()=>{n.delete(e)})}},I=t=>{let n=f.get(t);return n||(n=A(t),f.set(t,n)),n};export{U as ADMIN_AUTH_DEFAULT_PAGE_SIZE,S as AUTH_STATUSES,k as adminAuthListHasMore,p as adminAuthListQueryKey,_ as authOrganizationsList,m as authSessionsList,v as authSignUpInvitationsList,E as authUsersList,I as getIdentityStore,y as isAuthenticatedStatus,b as isLoadingStatus,w as subscribeAdminAuthIdentity};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as i}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-COqH5_SV.mjs";import{default as s}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as E}from"./packem_shared/TabCoordinator-DBuR7Dwv.mjs";import{a as d,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as A,TransportError as b,getErrorCode as h,getRetryAfterMs as D,isAuthReplayFailure as L,isConflictError as Q,isForbiddenError as T,isRateLimitedError as _,isUnauthorizedError as F}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as M}from"./packem_shared/httpStream-B9iENFKq.mjs";import{c as O}from"./packem_shared/live-stream-DBKgZlnb.mjs";import{liveTopicSubscription as U,subscribeLiveTopic as v}from"./packem_shared/liveTopicSubscription-DQtKMFKw.mjs";import{c as k}from"./packem_shared/local-store-C3bw2MPY.mjs";import{LunoraClient as N}from"./packem_shared/LunoraClient-C-auNTDs.mjs";import{createMutatorRunner as K}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as X}from"./packem_shared/offline-queue-BEqCPDmw.mjs";import{createInMemoryPersistence as w,createIndexedDbPersistence as G}from"./packem_shared/createInMemoryPersistence-BfgXApi_.mjs";import{preloadQuery as J,preloadedQueryResult as W}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as Z,createIndexedDbQueryCache as $,queryCacheKey as ee}from"./packem_shared/createInMemoryQueryCache-B5wX-gTy.mjs";import{createReconnect as oe}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{c as ae}from"./packem_shared/snapshot-precondition-BEtcSbWr.mjs";import{DEFAULT_MAX_BUFFER as ie,createStream as pe}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as me}from"./packem_shared/SubscriptionRegistry-BKgQtuh9.mjs";export{A as CONFLICT_ERROR_CODE,ie as DEFAULT_MAX_BUFFER,N as LunoraClient,X as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,me as SubscriptionRegistry,E as TabCoordinator,b as TransportError,d as applyDelta,O as connectLiveStream,i as createAsyncStoragePersistence,n as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,s as createInMemoryBookmarkStorage,w as createInMemoryPersistence,Z as createInMemoryQueryCache,G as createIndexedDbPersistence,$ as createIndexedDbQueryCache,k as createLocalStore,K as createMutatorRunner,oe as createReconnect,ae as createSnapshotPrecondition,pe as createStream,h as getErrorCode,D as getRetryAfterMs,M as httpStream,L as isAuthReplayFailure,Q as isConflictError,T as isForbiddenError,C as isMutationDelta,_ as isRateLimitedError,F as isUnauthorizedError,U as liveTopicSubscription,t as maxSeq,J as preloadQuery,W as preloadedQueryResult,ee as queryCacheKey,a as reconcileOptimistic,v as subscribeLiveTopic};
1
+ import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as i}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-D8NJXPJa.mjs";import{default as s}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as E}from"./packem_shared/TabCoordinator-DBuR7Dwv.mjs";import{a as d,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as A,TransportError as b,getErrorCode as h,getRetryAfterMs as D,isAuthReplayFailure as L,isConflictError as Q,isForbiddenError as T,isRateLimitedError as _,isUnauthorizedError as F}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as M}from"./packem_shared/httpStream-B9iENFKq.mjs";import{c as O}from"./packem_shared/live-stream-DBKgZlnb.mjs";import{liveTopicSubscription as U,subscribeLiveTopic as v}from"./packem_shared/liveTopicSubscription-DQtKMFKw.mjs";import{c as k}from"./packem_shared/local-store-C3bw2MPY.mjs";import{LunoraClient as N}from"./packem_shared/LunoraClient-WCMV2kam.mjs";import{createMutatorRunner as K}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as X}from"./packem_shared/offline-queue-BEqCPDmw.mjs";import{createInMemoryPersistence as w,createIndexedDbPersistence as G}from"./packem_shared/createInMemoryPersistence-C-IzNVbg.mjs";import{preloadQuery as J,preloadedQueryResult as W}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as Z,createIndexedDbQueryCache as $,queryCacheKey as ee}from"./packem_shared/createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as oe}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{c as ae}from"./packem_shared/snapshot-precondition-BEtcSbWr.mjs";import{DEFAULT_MAX_BUFFER as ie,createStream as pe}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as me}from"./packem_shared/SubscriptionRegistry-BKgQtuh9.mjs";export{A as CONFLICT_ERROR_CODE,ie as DEFAULT_MAX_BUFFER,N as LunoraClient,X as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,me as SubscriptionRegistry,E as TabCoordinator,b as TransportError,d as applyDelta,O as connectLiveStream,i as createAsyncStoragePersistence,n as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,s as createInMemoryBookmarkStorage,w as createInMemoryPersistence,Z as createInMemoryQueryCache,G as createIndexedDbPersistence,$ as createIndexedDbQueryCache,k as createLocalStore,K as createMutatorRunner,oe as createReconnect,ae as createSnapshotPrecondition,pe as createStream,h as getErrorCode,D as getRetryAfterMs,M as httpStream,L as isAuthReplayFailure,Q as isConflictError,T as isForbiddenError,C as isMutationDelta,_ as isRateLimitedError,F as isUnauthorizedError,U as liveTopicSubscription,t as maxSeq,J as preloadQuery,W as preloadedQueryResult,ee as queryCacheKey,a as reconcileOptimistic,v as subscribeLiveTopic};
@@ -0,0 +1 @@
1
+ const h="lunora-admin-auth-list",c=50,A=(t,s={})=>{const{filterField:n,filterValue:i,search:e,searchField:o,sortBy:r,sortDirection:a}=s;return{fetchPage:u=>t.listAuthUsers({filterField:n,filterValue:i,limit:u,search:e,searchField:o,sortBy:r,sortDirection:a}),key:["users",{filterField:n,filterValue:i,search:e,searchField:o,sortBy:r,sortDirection:a}]}},l=t=>({fetchPage:s=>t.listAuthOrganizations({limit:s}),key:["organizations"]}),d=t=>({fetchPage:s=>t.listAuthSignUpInvitations({limit:s}),key:["sign-up-invitations"]}),y=(t,s={})=>{const{userId:n}=s;return{fetchPage:i=>t.listAuthSessions({limit:i,userId:n}),key:["sessions",{userId:n}]}},f=(t,s,n)=>[h,t??"anon",...s.key,n],g=(t,s)=>{const n=t.onAuthTokenChange(s),i=t.onIdentityChange(s);return()=>{n(),i()}},I=t=>t!==void 0&&t.rows.length<t.total;export{c as ADMIN_AUTH_DEFAULT_PAGE_SIZE,I as adminAuthListHasMore,f as adminAuthListQueryKey,l as authOrganizationsList,y as authSessionsList,d as authSignUpInvitationsList,A as authUsersList,g as subscribeAdminAuthIdentity};
@@ -1 +1 @@
1
- import{LunoraError as b}from"@lunora/errors";import{encodeWire as K,decodeWire as C,stableWireKey as ue}from"@lunora/wire";import{r as qe,U as Ge,P as je}from"./delta-merge-Ls3DED4g.mjs";import{w as g,b as oe,j as _,d as le,p as fe,s as pe}from"./client-urls-BHLUjjcG.mjs";import $e from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{w as A,u as ae,s as Pe,a as Ve,i as q,e as G,r as me,b as ye,c as ze,d as Se,f as Je}from"./wire-errors-BgFi7ONA.mjs";import{ClientQueryStore as Ye}from"./createClientQuery-B8Nfj-7o.mjs";import{D as Xe,a as Ze,b as et,c as tt,d as st,S as be,M as it,I as rt,Q as nt,R as ot,e as ve,f as at,g as ct}from"./client-tuning-C10B2KCO.mjs";import{TabCoordinator as dt}from"./TabCoordinator-DBuR7Dwv.mjs";import{TransportError as W,getRetryAfterMs as ht,AUTH_REPLAY_ERROR_CODES as ut,isAuthReplayFailure as j}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as lt}from"./httpStream-B9iENFKq.mjs";import{d as te,r as U,a as M,b as ft,c as pt,e as mt,f as yt}from"./local-store-C3bw2MPY.mjs";import{O as St,n as ge,i as bt}from"./offline-queue-BEqCPDmw.mjs";import{resolvePersistenceAdapter as vt}from"./createInMemoryPersistence-BfgXApi_.mjs";import{w as Q,a as we,b as gt}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as wt,queryCacheKey as H}from"./createInMemoryQueryCache-B5wX-gTy.mjs";import{createReconnect as Te}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as F,setSubscriptionAck as R,SubscriptionRegistry as T,wrapSubscriber as V,releaseSubscribeFrame as z}from"./SubscriptionRegistry-BKgQtuh9.mjs";import{c as Tt,s as ke,r as kt}from"./snapshot-precondition-BEtcSbWr.mjs";import{createStream as Ct}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const J=500,Le=(r,e)=>{if(r.size<e)return;const t=r.keys().next().value;t!==void 0&&r.delete(t)},I="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",At=r=>{let e="",t=0;const s=r.length-2;for(;t<s;t+=3){const n=r[t]<<16|r[t+1]<<8|r[t+2];e+=I.charAt(n>>18&63)+I.charAt(n>>12&63)+I.charAt(n>>6&63)+I.charAt(n&63)}const i=r.length-t;if(i===1){const n=r[t]<<16;e+=I.charAt(n>>18&63)+I.charAt(n>>12&63)}else if(i===2){const n=r[t]<<16|r[t+1]<<8;e+=I.charAt(n>>18&63)+I.charAt(n>>12&63)+I.charAt(n>>6&63)}return e};new TextDecoder;const Et=new TextEncoder,_t=r=>At(Et.encode(JSON.stringify(r))),Ot="x-lunora-expect-subject",It=r=>_t({subject:r}),Ce=Symbol.for("lunora:session-change"),Rt="lunora:session-change",Ft="better-auth.message",Pt="signout",Me=()=>{const r=globalThis;let e=r[Ce];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},r[Ce]=e),e},Lt=()=>"document"in globalThis,Mt=async()=>{const r=[];for(const e of Me().listeners)try{r.push(e())}catch{}await Promise.allSettled(r)},Ht=(r,e)=>{if(r!==Ft||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===Pt}catch{return!1}},Ut=r=>{const e=[],t=()=>{Mt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(Rt):void 0}catch{s=void 0}if(s!==void 0){const n=s;n.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==r&&t()}),e.push(()=>{n.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const n=a=>{Ht(a.key,a.newValue)&&t()};i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(const n of e)n()}},Nt=r=>{const e=Me();return e.listeners.add(r),e.detach===void 0&&Lt()&&(e.detach=Ut(e.tab)),()=>{e.listeners.delete(r),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},Wt="/_lunora/rpc",Y="/_lunora/rpc-batch",X="/_lunora/ws",Dt="/_lunora/admin/shard-traffic",Bt="/_lunora/admin/scheduled",xt="/_lunora/admin/scheduled/status",Qt="/_lunora/admin/scheduled/ws",Kt="/_lunora/admin/scheduled/cancel",Ae="/_lunora/admin/scheduled/dead",qt="/_lunora/admin/scheduled/dead/retry",Gt="/_lunora/admin/scheduled/dead/cancel",jt="/_lunora/admin/workflows/instances",$t="/_lunora/admin/workflows/instance",Vt="/_lunora/admin/workflows/status",ce="/_lunora/admin/storage",zt="/_lunora/admin/storage/url",Jt="/_lunora/admin/storage/buckets",Yt="/_lunora/admin/functions",Xt="/_lunora/admin/cron-jobs",Zt="/_lunora/admin/cron-jobs/run",es="/_lunora/admin/architecture",ts="/_lunora/admin/openapi",ss="/_lunora/admin/openrpc",is="/_lunora/admin/global/tables",rs="/_lunora/admin/global/table",ns="/_lunora/admin/global/facet",os="/_lunora/admin/vector/indexes",as="/_lunora/admin/vector/query",cs="/_lunora/admin/logs/archive",ds="/_lunora/admin/kv/namespaces",hs="/_lunora/admin/kv/keys",de="/_lunora/admin/kv/value",us="/_lunora/admin/auth/users",ls="/_lunora/admin/auth/sessions",fs="/_lunora/admin/auth/users/create",ps="/_lunora/admin/auth/users/role",ms="/_lunora/admin/auth/users/ban",ys="/_lunora/admin/auth/users/unban",Ss="/_lunora/admin/auth/users/password",bs="/_lunora/admin/auth/users/remove",vs="/_lunora/admin/auth/users/impersonate",gs="/_lunora/admin/auth/sessions/revoke",ws="/_lunora/admin/auth/sessions/revoke-all",Ts="/_lunora/admin/auth/capabilities",ks="/_lunora/admin/auth/users/update",Cs="/_lunora/admin/auth/accounts",As="/_lunora/admin/auth/accounts/unlink",Es="/_lunora/admin/auth/passkeys",_s="/_lunora/admin/auth/passkeys/delete",Os="/_lunora/admin/auth/two-factor/disable",Is="/_lunora/admin/auth/organizations",Rs="/_lunora/admin/auth/organizations/members",Fs="/_lunora/admin/auth/organizations/invitations",Ps="/_lunora/admin/auth/organizations/members/remove",Ls="/_lunora/admin/auth/organizations/invitations/cancel",Ms="/_lunora/admin/auth/config",Hs="/_lunora/admin/auth/sign-up-invitations",Us="/_lunora/admin/auth/sign-up-invitations/create",Ns="/_lunora/admin/auth/sign-up-invitations/revoke",Ws="/_lunora/admin/auth/organizations/create",Ds="/_lunora/admin/auth/organizations/update",Bs="/_lunora/admin/auth/organizations/remove",xs="/_lunora/admin/auth/organizations/members/add",Qs="/_lunora/admin/auth/organizations/members/invite",Ks="/_lunora/admin/auth/organizations/members/role",qs="/_lunora/admin/auth/organizations/teams",Gs="/_lunora/admin/auth/organizations/teams/create",js="/_lunora/admin/auth/organizations/teams/update",$s="/_lunora/admin/auth/organizations/teams/remove",Vs="/_lunora/admin/auth/organizations/teams/members",zs="/_lunora/admin/auth/organizations/teams/members/add",Js="/_lunora/admin/auth/organizations/teams/members/remove",Ys="/_lunora/admin/auth/organizations/roles",Xs="/_lunora/admin/auth/organizations/roles/create",Zs="/_lunora/admin/auth/organizations/roles/update",ei="/_lunora/admin/auth/organizations/roles/remove",ti="/api/auth",si="/get-session",ii="lunora-ping",ri=async r=>(r.assertOpen(),(await r.adminFetch(Yt,"GET")).functions??[]),ni=async r=>(r.assertOpen(),(await r.adminFetch(Xt,"GET")).jobs??[]),oi=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(Zt,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},ai=async r=>(r.assertOpen(),await r.adminFetch(ts,"GET")),ci=async r=>(r.assertOpen(),await r.adminFetch(es,"GET")),di=async r=>(r.assertOpen(),await r.adminFetch(ss,"GET")),hi=async r=>(r.assertOpen(),await r.adminFetch(is,"GET")),ui=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(K(e.filters))),C(await r.adminFetch(`${rs}?${t.toString()}`,"GET"))},li=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(K(e.filters))),C(await r.adminFetch(`${ns}?${t.toString()}`,"GET"))},fi=async r=>(r.assertOpen(),(await r.adminFetch(ds,"GET")).namespaces??[]),pi=async(r,e)=>{r.assertOpen();const t=g(hs,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await r.adminFetch(t,"GET")},mi=async(r,e)=>{r.assertOpen();const t=g(de,{key:e.key,namespace:e.namespace});return await r.adminFetch(t,"GET")},yi=async(r,e)=>{r.assertOpen(),await r.adminFetch(de,"PUT",e)},Si=async(r,e)=>{r.assertOpen();const t=g(de,{key:e.key,namespace:e.namespace});await r.adminFetch(t,"DELETE")},bi=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(Dt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},vi=async(r,e={})=>{r.assertOpen();const t=await r.adminFetch(cs,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},gi=async r=>{const e=[];let t;for(;;){const s=await r(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},he=r=>"args"in r?{...r,args:C(r.args)}:r,wi=async r=>(r.assertOpen(),((await r.adminFetch(Bt,"GET")).records??[]).map(t=>he(t))),Ti=async r=>{r.assertOpen();const e=await r.adminFetch(xt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},ki=async(r,e)=>(r.assertOpen(),{cancelled:(await r.adminFetch(Kt,"POST",{id:e})).cancelled===!0}),Ci=async r=>(r.assertOpen(),(await gi(async t=>await r.adminFetch(t===void 0?Ae:`${Ae}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>he(t))),Ai=async(r,e)=>(r.assertOpen(),{retried:(await r.adminFetch(qt,"POST",{id:e})).retried===!0}),Ei=async(r,e)=>(r.assertOpen(),{removed:(await r.adminFetch(Gt,"POST",{id:e})).removed===!0}),_i=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await r.adminFetch(`${jt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},Oi=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await r.adminFetch(`${$t}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}},Ii=async(r,e)=>(r.assertOpen(),{status:(await r.adminFetch(Vt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),Ri=async(r,e={})=>{r.assertOpen();const t=g(ce,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await r.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},Fi=async(r,e,t)=>{r.assertOpen();const s=`${ce}?key=${encodeURIComponent(e)}${oe(t?.bucket)}`,i=await r.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},Pi=async r=>(r.assertOpen(),(await r.adminFetch(Jt,"GET")).buckets??[]),Li=async(r,e)=>{r.assertOpen();const t=`${ce}?key=${encodeURIComponent(e.key)}${oe(e.bucket)}`,s=await r.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},Mi=async(r,e,t)=>{r.assertOpen();const s=t?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${zt}?key=${encodeURIComponent(e)}${i}${oe(t?.bucket)}`,a=await r.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url},Hi=async r=>(r.assertOpen(),(await r.adminFetch(os,"GET")).indexes??[]),Ui=async(r,e)=>(r.assertOpen(),(await r.adminFetch(as,"POST",e)).matches??[]),O=(r,e)=>{try{return K(r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},se=r=>{try{return K(r),!0}catch{return!1}},He=r=>r!==null&&typeof r=="object"&&("error"in r||"result"in r),Ni=(r,e,t)=>{const s=Array.from({length:e}),i=n=>({error:A(Pe(n),t),ok:!1});for(const n of r){if(typeof n.id!="number"||n.id<0||n.id>=e)continue;if(!He(n.body)){s[n.id]=i({});continue}const a=n.body;if("error"in a){s[n.id]=i(a);continue}try{s[n.id]={ok:!0,value:C(a.result)}}catch(o){s[n.id]={error:A(ae(o),t),ok:!1}}}return s.map(n=>n??{error:A(new Error("batch call returned no result"),t),ok:!1})},Z=(r,e)=>e!==null?{}:r===null?{expectSubject:null}:r?.startsWith("subj:")===!0?{expectSubject:r.slice(5)}:{},B=r=>r==="connected"||r==="polling",f=r=>r??"",k=(r,e)=>{if(!r.socket||r.wsState!=="open")return!1;try{return r.socket.send(JSON.stringify(e)),!0}catch{return!1}},Wi=r=>{if(!r.pendingStreams||r.pendingStreams.length===0)return;const e=r.pendingStreams;r.pendingStreams=[];for(const t of e)k(r,t)},Di=new TextDecoder,Bi=r=>{if(typeof r=="string")return r;if(r instanceof ArrayBuffer)return Di.decode(r)};class P{listeners=new Set;get size(){return this.listeners.size}add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const N=r=>{r.heartbeatTimer!==void 0&&(clearInterval(r.heartbeatTimer),r.heartbeatTimer=void 0)},xi=(r,e,t)=>{N(r),!(e<=0)&&(r.heartbeatTimer=setInterval(()=>{if(!r.socket)return;const{socket:s}=r;if(Date.now()-r.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(ii)}catch{}},e))},Ee=(r,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:a}=t;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");const o=new i(e);r.socket=o;const c=()=>{N(r),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.socket===o&&(r.socket=void 0)},d=h=>{c(),s.onClose(h)};n>0&&(r.connectTimer=setTimeout(()=>{if(r.connectTimer=void 0,r.socket===o){try{o.close()}catch{}d()}},n)),o.addEventListener("open",()=>{if(r.socket===o){r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.lastFrameAt=Date.now();try{s.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}r.socket===o&&xi(r,a,d)}}),o.addEventListener("message",h=>{if(r.socket===o){r.lastFrameAt=Date.now();try{s.onMessage(h)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),o.addEventListener("close",h=>{r.socket===o&&d(h)}),o.addEventListener("error",()=>{r.socket===o&&d()})},Qi=r=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:n}=r,a=t>0&&e>0;let o=0,c,d=!1,h=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},l=y=>{if(c!==void 0){if(!y){u();return}d||(d=!0,i()),s()}},p=()=>{h||(h=!0,n().then(l).finally(()=>{h=!1}).catch(()=>{}))};return{hasFailedOpen:()=>o>0,isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{o+=1,!(!a||c!==void 0||o<e)&&(c=setInterval(p,t),i(),p())},noteOpen:()=>{o=0,u()},stop:u}},Ki=1e4,_e=async r=>Q(Ki,void 0,r,()=>new TypeError("LunoraClient: poll timed out")),Ue=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Oe=r=>{if(r instanceof W)return!0;const e=r?.code;return e===void 0||Ue.has(e)||ut.has(e)},qi=1e3,Ne=6e4,Gi={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},x=(r,e,t)=>{const s=Ve(t.get("retry-after")),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${r.toString()}${e?` ${e}`:""})`,a=r<400||r>=500||r===408?new W(n,i):new b(Gi[r]??"BAD_REQUEST",n,{data:i});return A(a,t)},ie=(r,e=Math.random)=>{const t=Math.min(qi*2**Math.max(r-1,0),Ne);return Math.round(t*(.5+e()*.5))},ji=r=>{const e=r?.code;return r instanceof W||e===void 0||Ue.has(e)},$i=(r,e,t)=>{const s=ht(r);return s!==void 0&&s>0?Math.min(s,Ne):ji(r)?ie(e,t):void 0},Vi=983040,zi=r=>typeof TextEncoder>"u"?r.length:new TextEncoder().encode(r).length,Ji=r=>{const e=new Map;for(const t of r)typeof t.id=="number"&&He(t.body)&&e.set(t.id,t.body);return e},Yi=(r,e)=>{if(r===void 0)return{kind:"unanswered"};if("error"in r)return{error:A(Pe(r),e),kind:"errored"};try{return{commitCursor:r.commitCursor,kind:"committed",value:C(r.result)}}catch(t){return{commitCursor:r.commitCursor,error:A(ae(t),e),kind:"undecodable"}}},ee=(r,e)=>`${f(r)}\0${e}`,Xi=(r,e)=>{for(const t of e)t.op==="delete"?r.delete(t.key):t.value!==void 0&&r.set(t.key,t.value)};class Zi{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Le(this.buffers,this.maxBuffers),this.buffers.set(ee(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(ee(e,t.pokeId));if(!s)return;const i=[];try{for(const o of t.rowsPatch)i.push(o.value===void 0?o:{...o,value:C(o.value)})}catch(o){s.undecodable.set(t.shapeId,o);return}const n=s.parts.get(t.shapeId)??[];for(const o of i)n.push(o);s.parts.set(t.shapeId,n),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const a=t.baseCheckpoint??s.baseCheckpoint;a!==void 0&&s.bases.set(t.shapeId,a),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=ee(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const er=(r,e,t)=>{const s=e.parts.get(r.id)??[],i=e.resets.has(r.id),n=e.bases.get(r.id),a=e.epoch!==void 0&&r.serverEpoch!==void 0&&e.epoch!==r.serverEpoch,o=n!==void 0&&r.serverCursor!==void 0&&r.serverCursor!==n;if(!i&&(a||o))return r.rows.clear(),r.serverCursor=void 0,r.serverEpoch=void 0,r.answered=!1,"reseed";i&&r.rows.clear(),Xi(r.rows,s),r.answered=!0,t.checkpoint!==void 0&&(r.serverCursor=t.checkpoint),t.epoch!==void 0&&(r.serverEpoch=t.epoch);const c=e.lastMutationId.get(r.id);return c!==void 0&&(r.lastMutationId=c),"applied"},Ie=r=>{const e=[...r.rows.values()];for(const t of r.callbacks)try{t(e)}catch{}},tr=(r,e)=>{for(const[t,s]of e.undecodable){const i=r.get(t);i&&F(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},re=(r,e)=>{r.lastMutationId=Math.max(r.lastMutationId??0,e)},ne=(r,e=!1)=>{for(const t of r.checkpointCallbacks)t({checkpoint:r.serverCursor,mutationId:r.lastMutationId,...e&&{rowsFollow:!0}})},We=(r,e,t)=>{r.serverBase=e,t.cursor!==void 0&&(r.serverCursor=t.cursor),t.epoch!==void 0&&(r.serverEpoch=t.epoch)},sr=(r,e)=>e.cursor!==void 0&&r.serverCursor!==void 0&&r.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===r.serverEpoch&&e.cursor<r.serverCursor,ir=r=>r.type==="delta"&&r.more===!0,$=(r,e)=>r!==void 0&&r!==e,rr=(r,e)=>e==="connected"&&r!=="connected"||e==="polling"&&r!=="connected"&&r!=="polling",nr=r=>{for(const e of r.activeSubscriptions())e.valueReceived=!1,r.ensureSocket(e.shardKey),r.queueResubscribe(e);for(const e of r.activeShapes())e.answered=!1,r.ensureSocket(e.shardKey);for(const e of r.queuedShardKeys())r.ensureSocket(e);r.broadcastStatus(r.computeStatus(),r.identityFingerprint()),r.emitConnectionStatus()},or=r=>{r.closeConnections();const e=r.leader;e.status=void 0,e.wasEverConnected=!1;for(const t of r.activeSubscriptions())R(t,"idle"),t.valueReceived=!1;for(const t of r.activeShapes())t.answered=!1;r.emitConnectionStatus()},ar=(r,e,t)=>{if($(t,r.identityFingerprint()))return;const s=r.leader,i=rr(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),r.emitConnectionStatus(),i&&(r.awaitLeaderAnswers(),r.flushOfflineQueues())},cr=r=>{r.isLeader()&&r.broadcastStatus(r.computeStatus(),r.identityFingerprint())},dr=(r,e,t,s,i,n)=>{if($(n,r.identityFingerprint()))return;const a=r.subscription(e);if(!a)return;r.dropCacheSeed(e);const o=!a.valueReceived;a.valueReceived=!0,We(a,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&te(a,s),U(a,t),o&&r.emitConnectionStatus(),r.settleAwaitedAnswer(a,!0)},hr=(r,e,t,s)=>{if($(s,r.identityFingerprint()))return;const i=r.subscription(e);if(i){const n=!i.valueReceived;i.valueReceived=!0,F(i.errorCallbacks,t),n&&r.emitConnectionStatus(),r.settleAwaitedAnswer(i,!1)}},ur=(r,e,t,s,i,n,a)=>{if($(a,r.identityFingerprint()))return;const o=r.subscription(e);o&&(r.ackAndAdvanceCursor(o,t,s),i!==void 0&&n===r.clientIdentifier()&&re(o,i),ne(o))},lr=(r,e,t)=>r!==null||e&&t===null,fr=r=>r.sensitive===!0,pr=(r,e)=>{if(!fr(r))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${r.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},mr=[je],yr=100,De=1e4,Sr=1e4,br=(r,e)=>{let t;const s=new Promise((n,a)=>{t=setTimeout(()=>{a(new Error("ws ticket mint timed out"))},e)}),i=(async()=>r())();return Promise.race([i,s]).finally(()=>{clearTimeout(t)})},Re=async r=>typeof r=="function"?await r():r,vr=async(r,e,t,s)=>{const i=new AbortController,n=setTimeout(()=>{i.abort()},De);try{const a=await r(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return await a.text(),a.status}finally{clearTimeout(n)}},Fe=(r,e)=>new b("OFFLINE_NOT_QUEUED",`'${r}' is online-only and the connection is not live, so it was not queued`,{cause:e}),gr=(r,e)=>r instanceof TypeError&&se(e),wr=(r,e,t,s)=>e||r===!0&&t&&!s,Tr=Promise.resolve();class Be{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new T;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new P;statusListeners=new P;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new P;identityChangeListeners=new P;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new P;pendingChangeListeners=new P;syncStatusListeners=new P;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Zi(Be.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??_(le(e.url),X),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??ti;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??$e(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Xe,this.connectTimeoutMs=e.connectTimeoutMs??Ze,this.rpcTimeoutMs=e.rpcTimeoutMs??et,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??tt,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??st,this.defaultConnectionContext=e.connectionContext,this.persistence=vt(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=wt(e.queryCache),this.clientQueryStore=new Ye,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Tr),this.offlineQueue=new St(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onReplayingChange:()=>{this.emitSyncStatus()},onSizeChange:s=>{this.pendingChangeListeners.emit(s),this.emitSyncStatus()},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${ge()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=Nt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),o=this.isKnownNobody(),c=this.authToken;this.authToken=e,s&&(this.tokenFingerprint=void 0),this.applySubject(e,t);const d=this.identityFingerprint(),h=!s&&e!==null&&n,u=!s&&e===null&&i===null&&n&&!o,l=d!==i;let p=!1;l&&(h?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):u?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):p=this.retirePreviousIdentity(i,o,c,e)),p||this.applyUpgradeBearer(this.reconcileUpgradeBearer(c,e,l)),l&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==i||s||a)&&this.offlineQueue.size>0&&B(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){const t=this.identityVerdict(e);if(t!=="match")return{verdict:t};const s=Object.freeze({});return this.replayCredentials.set(s,{authToken:this.authToken,stamp:e}),{credential:s,verdict:t}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const n=s?.shardKey??"",a=this.identityFingerprint();let o,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:u=>{o=u}})}catch(u){if(!q(u))throw u;d=u}if(o!==void 0&&o>(this.clientWatermarks.get(a??"")?.get(n)??0)){let u=this.clientWatermarks.get(a??"");u===void 0&&(Le(this.clientWatermarks,ct),u=new Map,this.clientWatermarks.set(a??"",u)),u.set(n,o)}if(d!==void 0)throw d;return{applied:o===void 0||o===i,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const i=await this.fetchImpl(_(this.url,`${this.authBasePath}${si}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(t,null,s),null;const a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,a,s),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=f(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=f(t.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;const o=this.connectionContextHolders.get(s);if(!o)return;const c=o.indexOf(i);c!==-1&&o.splice(c,1),o.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const i=f(s.shardKey);let n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e);const o=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),o){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,i,e)}return()=>{const c=this.whisperHandlers.get(i),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const h=this.getConnection(s.shardKey);h&&k(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:i,stream:n,topic:a}=e;if(a.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const o=`ws-live-${String(this.nextLiveSocketId)}`,c=f(i),d=`/live/${n}/control`;let u=this.whisperSubscribe(a,()=>{},{shardKey:i});const l=()=>{const S=u;u=void 0,S?.()};let p=this.liveSocketGrants.get(c);p===void 0&&(p=new Map,this.liveSocketGrants.set(c,p)),p.set(o,{onError:t,onEvent:s,release:l,stream:n,topic:a});const y=this.getConnection(i)?.connectionId;y!==void 0&&this.grantWhenJoined(i,o,y);let m=!1;return()=>{if(m)return;m=!0;const S=this.liveSocketGrants.get(c),E=S?.delete(o)===!0;S?.size===0&&this.liveSocketGrants.delete(c);const v=this.getConnection(i)?.connectionId;E&&v!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:v,stream:n,subscriptionId:o,topic:a}),l()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,O(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const i=`room:${e.name}`,n=this.whisperSubscribe(i,l=>{t.onMessage(l)},s);let a=!1;const o=[],c=()=>{o.length=0},d=()=>{for(;o.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(i,o[0],s))return;o.shift()}},h=f(s.shardKey),u=this.roomFlushes.get(h)??new Set;return u.add(d),this.roomFlushes.set(h,u),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,u.delete(d),u.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(c),n()},send:l=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=O(l,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,y,s)?!0:o.length>=yr?!1:(o.push(y),!0)}}}connectWebSocket(e,t,s={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:()=>{},send:()=>{}};const i=o=>{try{o?.()}catch(c){console.error("[lunora] socket route handler threw",c)}};let n;const a=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:()=>{clearTimeout(n),i(t.onClose)},onMessage:o=>{let c;try{c=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}c.type==="message"&&(a.resetBackoff(),i(()=>{t.onMessage(C(c.data))}))},onOpen:()=>{clearTimeout(n);const o=a.socket();n=setTimeout(()=>{a.socket()===o&&a.resetBackoff()},be),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(n),a.close()},send:o=>{const c=JSON.stringify(O(o,`socket message for '${e}'`)),d=a.socket();if(d!==void 0)try{d.send(c)}catch{}}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}syncStatus(){const e=this.computeStatus(),t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader();let s=0;for(const n of this.subscriptions.all())(t||this.connectionGateState(n.shardKey).polling?n.valueReceived:n.ack==="acked")||(s+=1);for(const n of this.shapeSubscriptions.values())n.answered||(s+=1);const i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:s,pendingWrites:i,synced:B(e)&&s===0&&i===0}}onSyncStatus(e){const t=this.syncStatusListeners.add(e),s=this.syncStatus();return this.lastSyncStatus=s,e(s),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const a=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}const i=this.subscriptions.all().map(n=>({acked:n.ack==="acked",functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())i.push({acked:n.answered,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){const t=this.getConnection(e.shardKey);return t===void 0||t.wsState==="open"?!0:t.polling.isPolling()||!t.polling.hasFailedOpen()}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Tt(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:we(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ue(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=H(e,t,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=T.key(e,t,s),n=this.subscriptions.get(i);return{answered:n!==void 0&&(n.lastValue!==void 0||n.ack==="acked"||n.valueReceived),present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,signal:s.signal})}async batch(e){return Q(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw gt(s.signal);const{value:i}=await we(this.runMutation(e,t,s),s.signal);return i}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0,signal:s.signal,unbounded:!0})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),a=t.length;let o=0,c=0,d=0;for(let h=0;h<a;h+=i){const u=t.slice(h,h+i),l=d,{committed:p}=await this.runMutation(e,n(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey});d+=1,o+=u.length,p&&(c+=u.length),s.onProgress?.({done:o,total:a})}return{chunks:d,imported:c,queued:o-c}}async shardTraffic(e){return bi(this.adminHost,e)}async listScheduledJobs(){return wi(this.adminHost)}async schedulerStatus(){return Ti(this.adminHost)}async cancelScheduledJob(e){return ki(this.adminHost,e)}async listDeadJobs(){return Ci(this.adminHost)}async retryDeadJob(e){return Ai(this.adminHost,e)}async removeDeadJob(e){return Ei(this.adminHost,e)}async listWorkflowInstances(e){return _i(this.adminHost,e)}async getWorkflowInstance(e){return Oi(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ii(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=this.openSupplementarySocket(_(le(this.url),Qt),{onMessage:s=>{let i;try{i=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(t.resetBackoff(),e(i.records.map(n=>he(n))))}});return t.close}async listFunctions(){return ri(this.adminHost)}async getCronJobs(){return ni(this.adminHost)}async runCronJob(e){return oi(this.adminHost,e)}async fetchOpenApi(){return ai(this.adminHost)}async fetchArchitecture(){return ci(this.adminHost)}async fetchOpenRpc(){return di(this.adminHost)}async listStorageObjects(e={}){return Ri(this.adminHost,e)}async deleteStorageObject(e,t){return Fi(this.adminHost,e,t)}async listStorageBuckets(){return Pi(this.adminHost)}async uploadStorageObject(e){return Li(this.adminHost,e)}async signedStorageUrl(e,t){return Mi(this.adminHost,e,t)}async listGlobalTables(){return hi(this.adminHost)}async readGlobalTablePage(e){return ui(this.adminHost,e)}async facetGlobalColumn(e){return li(this.adminHost,e)}async listVectorIndexes(){return Hi(this.adminHost)}async queryVectorIndex(e){return Ui(this.adminHost,e)}async queryLogArchive(e={}){return vi(this.adminHost,e)}async listKvNamespaces(){return fi(this.adminHost)}async listKvKeys(e){return pi(this.adminHost,e)}async getKvValue(e){return mi(this.adminHost,e)}async putKvValue(e){return yi(this.adminHost,e)}async deleteKvKey(e){return Si(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=g(us,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(fs,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(ps,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(ms,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(ys,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(bs,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(gs,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(ws,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Ts,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(ks,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(g(Cs,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(As,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(g(Es,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(_s,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(Os,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(g(Is,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=g(Rs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=g(Fs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=g(Hs,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Us,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Ns,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(Ps,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Ls,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(Ms,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Ws,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Ds,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Bs,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(xs,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Qs,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Ks,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=g(qs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Gs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(js,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch($s,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=g(Vs,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(zs,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Js,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=g(Ys,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Xs,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Zs,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(ei,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=g(ls,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const n=t??{},a=T.key(e.__lunoraRef,n,i.shardKey);let o=this.subscriptions.get(a);const c=V(s),d=V(i.onError),h=V(i.onCheckpoint);if(!o){this.nextSubId+=1;const y=`sub_${this.nextSubId.toString()}`,m=ue(n),S=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);o={ack:"idle",args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:S?.value,optimisticLayers:[],serverBase:S?.value,serverCursor:S?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:O(n,`args for '${e.__lunoraRef}'`),...S?.serverEpoch===void 0?{}:{serverEpoch:S.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),this.isCrossTabFollower()&&B(this.computeStatus())&&this.awaitLeaderAnswer(o),S!==void 0&&this.cacheSeededQueries.set(a,S)}if(o.callbacks.add(c),d&&o.errorCallbacks.add(d),h&&o.checkpointCallbacks.add(h),o.lastValue!==void 0)try{c(o.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const u=o;let l=!1;const p=()=>{if(!l&&(l=!0,i.signal?.removeEventListener("abort",p),u.callbacks.delete(c),d&&u.errorCallbacks.delete(d),h&&u.checkpointCallbacks.delete(h),u.callbacks.size===0)){this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(T.keyOf(u)),this.subscriptions.remove(u);const y=this.getConnection(u.shardKey);y&&this.settleSubscribeWatchdog(y,u.id),this.releaseIdleShard(u.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(u,!0)}};return i.signal?.addEventListener("abort",p,{once:!0}),i.signal?.aborted&&p(),p}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const i=`shape_${this.nextShapeId.toString()}`,n={answered:!1,args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:O(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.emitSyncStatus(),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey),this.emitSyncStatus()}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=t??{},{handle:o,iterable:c}=Ct({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,n)}});this.ensureSocket(n);const d=this.getConnection(n),h={id:i,query:{args:O(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:o,lastSeq:0,message:h,shardKey:n};this.streams.set(i,u);const l=d?.wsState==="open"&&k(d,h);if(!l&&d===void 0)return this.forgetStream(i),o.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!l){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=it;){const y=d.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(y))}d.pendingStreams.push(h)}return c}httpStream(e,t,s={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return lt(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear();for(const e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}retirePreviousIdentity(e,t,s,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(s,i),lr(e,t,i)?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,t,s){return!this.authTokenOnUpgrade||t===null||e===t?"none":s?e===null?"cold":"none":e===null?"none":"warm"}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets()}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>f(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=f(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},rt))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=f(e.shardKey);for(const[i,n]of this.streams)f(n.shardKey)===t&&(n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,N(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeShapes:()=>[...this.shapeSubscriptions.values()],activeSubscriptions:()=>this.subscriptions.all(),awaitLeaderAnswers:()=>{this.awaitLeaderAnswers()},broadcastStatus:(s,i)=>this.tabCoordinator?.broadcastConnectionStatus(s,i),closeConnections:()=>{for(const[s,i]of this.connections)this.teardownConnection(i),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,i,n)=>{this.ackAndAdvanceCursor(s,i,n)},settleAwaitedAnswer:(s,i)=>{this.settleAwaitedAnswer(s,i)},subscription:s=>this.subscriptions.get(s)};return new dt({channelName:e,onBecomeLeader:()=>{nr(t)},onStopBeingLeader:()=>{or(t)},onConnectionStatus:(s,i)=>{ar(t,s,i)},onSubscriptionData:(s,i,n,a,o)=>{dr(t,s,i,n,a,o)},onLeaderClaimAnswered:()=>{cr(t)},onSubscriptionError:(s,i,n)=>{hr(t,s,i,n)},onSubscriptionSettled:(s,i,n,a,o,c)=>{ur(t,s,i,n,a,o,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(_(this.url,Y),{body:JSON.stringify({calls:e.map((o,c)=>({args:O(o.args??{},`args for batch call '${o.fn.__lunoraRef}'`),functionPath:o.fn.__lunoraRef,id:c,shardKey:o.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await s.json()}catch{throw A(new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`),s.headers)}const a=G(n);if(!s.ok||a!==void 0&&!n.results)throw a!==void 0?A(me(a),s.headers):A(new b("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`),s.headers);for(const o of n.results??[]){const c=o.body?.commitCursor;typeof o.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[o.id]?.shardKey,c)}return Ni(n.results??[],e.length,s.headers)}async runMutation(e,t,s){this.assertOpen();const i=pr(e,s),n=t,a=i.mutationId??ge();this.mutationIssueCounter+=1;const o=this.mutationIssueCounter,c=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);const{confirms:h,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,n,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,u,h);const l=i.onlineOnly?void 0:this.offlineFlushes.get(f(i.shardKey));l!==void 0&&await l;const{httpFirst:p,midReconnect:y,shouldQueueOffline:m,socketDown:S}=this.writeQueueGate(i.shardKey),E=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),v=async(w=!1)=>this.enqueueOfflineMutation(e,n,i.shardKey,d,a,u,h,w?void 0:i.precondition,i.mutationId,c?.stamp,w,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,u),S||y||E)return v();let D;try{const w=await this.rpc(e.__lunoraRef,n,i.shardKey,{baselineSeq:d,captureBookmark:!0,...c?.flags,mutationId:a,onCommitCursor:L=>{D=L}});for(const L of h)L(D);return{committed:!0,value:w}}catch(w){const L=gr(w,n),xe=p&&m&&L,Qe=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof W)&&se(n)){const Ke=v(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),Ke}throw this.settleFailedDirectWrite(w,D,h,u,c?.flags.authToken),wr(i.onlineOnly,xe,L,Qe)?Fe(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw M(s),Fe(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){const{hasSocket:t,idleClosed:s,polling:i,wasEverConnected:n,wsState:a}=this.connectionGateState(e),{queueBeforeFirstConnect:o}=this.offlineQueue,c=n||o,d=this.WebSocketImpl!==void 0&&c,h=i||s;return{httpFirst:h,midReconnect:a==="connecting"&&c&&!h,shouldQueueOffline:d,socketDown:a!=="open"&&!t&&d&&!h,socketOpen:a==="open"}}settleFailedDirectWrite(e,t,s,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),q(e)){for(const a of s)a(t);return}M(i)}async enqueueOfflineMutation(e,t,s,i,n,a,o,c,d,h,u,l){const p=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:p,mutationId:m,...a.length>0&&{onRejected:()=>{M(a)}},shardKey:s})}catch(S){throw M(a),S instanceof Error?S:new Error(String(S))}for(const S of o)S(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,S)=>{const E={ambiguousSend:u,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,issueSeq:l,clientId:this.clientId,identity:p,precondition:this.holdWhileUnanswered(c),onCommit:v=>{for(const D of o)D(v)},reject:v=>{this.queuedIdentities.delete(n),q(v)||M(a),S(v instanceof Error?v:new Error(String(v))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(E),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),E.id!==void 0&&this.queuedIdentities.set(E.id,p)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=f(e);return this.offlineQueue.hasPending(s=>f(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(H(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(bt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const n=t.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(H(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),U(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,U(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=H(e,t,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=H(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=H(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:t,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},nt))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,i])=>e.put(s,i)))}installPageHideFlush(){const e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;const t=()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},s=()=>{e.document?.visibilityState==="hidden"&&t()};e.addEventListener("pagehide",t),e.document?.addEventListener("visibilitychange",s),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",t),e.document?.removeEventListener("visibilitychange",s)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=f(e);let s;for(const i of this.subscriptions.all())f(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}composedBaselineFor(e,t){return e===void 0?this.baselineCursorFor(t):e??void 0}async pollSubscriptions(e){const t=f(e),s=[];for(const o of this.subscriptions.all())f(o.shardKey)===t&&(se(o.args)?s.push(o):(this.markQueryRejected(o,!0),F(o.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(s.length===0)return this.probeOrigin();const i=yt(),n=this.identityFingerprint();let a;try{a=await _e(async o=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),o))}catch(o){return!(o instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(const[o,c]of s.entries()){const d=a[o];if(d!==void 0){if(!d.ok){this.markQueryRejected(c,!0),F(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:K(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await _e(async t=>e(_(this.url,Y),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;const e=this.syncStatus(),t=this.lastSyncStatus;t?.connection===e.connection&&t.pendingSubscriptions===e.pendingSubscriptions&&t.pendingWrites===e.pendingWrites&&t.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){const e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,i){const n=[],a=[];if(!i)return{confirms:n,rollbacks:a};const o=T.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=ft(c,i);d&&(n.push(d.confirm),a.push(d.rollback))}return{confirms:n,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,n){e&&this.applyOptimisticUpdate(e,t,s,i,n)}applyOptimisticUpdate(e,t,s,i,n){const{confirms:a,rollbacks:o,store:c}=pt(this.subscriptions,s);try{e(c,t)}catch{M(o);return}i.push(...o),n.push(...a)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!k(i,{id:t,type:s})&&i.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(f(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=f(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Qi({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:Te(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}openSupplementarySocket(e,t){if(this.WebSocketImpl===void 0||this.closed)return{close:()=>{},resetBackoff:()=>{},socket:()=>{}};const s=Te(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,a=!1;const o=()=>{a||this.closed||(n=setTimeout(l,s.next()))},c=m=>{a||this.WebSocketImpl===void 0||Ee(i,this.wsUrlFor(t.shardKey,m,e),this.managedSocketOptions,{onClose:()=>{o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen}})};let d=0,h;const u=async m=>{const S=this.wsCredentialGeneration;d+=1;const E=d;let v;h=S;try{v=await br(m,Sr)}catch{E===d&&(h=void 0,o());return}if(E===d){if(h=void 0,S!==this.wsCredentialGeneration){l();return}c(v)}},l=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:m}=this;if(typeof m=="function"){u(m).catch(()=>{});return}c(m)};l();const p=()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),N(i);const{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}};this.adminSocketTeardowns.add(p);const y=()=>{const{socket:m}=i;if(m===void 0){h!==void 0&&h!==this.wsCredentialGeneration&&(d+=1,h=void 0,l());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),N(i);try{m.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(y),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(y)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=fe(this.wsUrl),s=t.pathname.endsWith(X)?t.pathname.slice(0,-X.length):t.pathname;return t.pathname=_(s,e),pe(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=fe(s);if(e===void 0&&t===void 0&&!i.searchParams.has("token"))return s;const n=new Set([...e===void 0?[]:["shard"],"token"]),a=[...i.searchParams].filter(([o])=>!n.has(o)).map(([o,c])=>`${encodeURIComponent(o)}=${encodeURIComponent(c)}`);return e!==void 0&&a.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&a.push(`token=${encodeURIComponent(t)}`),i.search=a.join("&"),pe(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[Ot]=It(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(s.authorization=`Bearer ${n}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const a=this.bookmark.get();a&&(s["x-d1-bookmark"]=a)}return s}async rpc(e,t,s,i={}){const{fetchImpl:n}=this;if(!n)throw new W("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:O(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:d,response:h}=await Q(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const y=await n(_(this.url,Wt),{body:c,headers:a,method:"POST",signal:p});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){const p=h.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(d===void 0)throw x(h.status,h.statusText,h.headers);const u=d;if(typeof u!="object"||u===null||Array.isArray(u))throw x(h.status,h.statusText,h.headers);const l=G(d);if(l!==void 0)throw ye(l,h.headers);if(!h.ok)throw x(h.status,h.statusText,h.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(h,s),this.recordShardCursor(s,d.commitCursor);try{return C(d.result)}catch(p){throw A(ae(p),h.headers)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let o;s===void 0?o=void 0:a?(o=s,i!==void 0&&(n["content-type"]=i)):(o=JSON.stringify(s),n["content-type"]="application/json");const c=await this.fetchImpl(_(this.url,e),{body:o,headers:n,method:t});let d;try{d=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const h=G(d);if(h!==void 0)throw me({...h,message:h.message??"admin request failed"});if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${u})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(f(e.shardKey));k(e,{caps:mr,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())f(t.shardKey)===f(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);t.wsState==="open"||t.wsState==="connecting"||(t.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(t,e).catch(()=>{this.handleDisconnect(t)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,t){const{wsToken:s,wsTicket:i}=this;if(typeof s=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,t);return}this.openSocket(e,t,{session:s,ticket:i})}async openSocketWithProvidedCredentials(e,t){const s=this.wsCredentialGeneration,i=Symbol("ws-token-attempt");let n;e.providerAttempt=i;try{n=await Q(this.connectTimeoutMs,void 0,async()=>({session:await Re(this.wsToken),ticket:await Re(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(s!==this.wsCredentialGeneration){await this.startShardSocket(e,t);return}this.openSocket(e,t,n)}}openSocket(e,t,s){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),s.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=s.session,e.retired=!1;const i=this.wsCredentialGeneration;Ee(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:n=>{n?.code===4003&&e.polling.noteFailedOpen(),n?.code===4001?this.notifyTokenExpired():n?.code===4003&&n.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},onMessage:n=>{e.retired!==!0&&this.handleServerMessage(n.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},be),this.sendConnectEnvelope(e),this.markShardPendingAck(t,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(const o of this.subscriptions.all())f(o.shardKey)===f(t)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:c,type:d}of o)k(e,{id:c,type:d});this.releaseIdleShard(t)}Wi(e);const n=f(t),a=this.whisperHandlers.get(n);if(this.dropWhisperJoinWaiters(n),this.whisperJoins.set(n,new Map),a)for(const o of a.keys())this.sendWhisperJoin(e,n,o);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})}})}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),k(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),N(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(f(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,n]of this.streams)if(!(f(n.shardKey)!==f(e.shardKey)||t.has(i))){if(n.durable){const a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(o=>o.id!==i),a];continue}n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e,t=!1){const s=f(e);for(const i of this.subscriptions.all())f(i.shardKey)===s&&(R(i,"idle"),i.pendingDeltaRun=void 0,t&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(const i of this.shapeSubscriptions.values())f(i.shardKey)===s&&(i.answered=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<ot;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribeSlots.add(t.id)}}settleSubscribeWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t)),e.unackedWatchdogs.delete(t),e.resubscribeSlots.delete(t)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(const t of e.unackedWatchdogs.values())clearTimeout(t);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,t=!1){const s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.ack==="acked"||!t&&e.ack==="inflight")return!1;const i=e.serverCursor!==void 0&&e.serverBase!==void 0,n=k(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return n&&R(e,"inflight"),n&&!t&&this.armUnackedWatchdog(s,e),n}armUnackedWatchdog(e,t,s=!1){clearTimeout(e.unackedWatchdogs.get(t.id)),e.unackedWatchdogs.set(t.id,setTimeout(()=>{if(s){e.unackedWatchdogs.delete(t.id),z(t),this.settleAwaitedAnswer(t,!1);return}const i=t.ack!=="acked"&&this.subscriptions.getById(t.id)===t&&this.sendSubscribeIfOpen(t,!0);this.settleSubscribeWatchdog(e,t.id),i?this.armUnackedWatchdog(e,t,!0):z(t)},ve))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&k(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Bi(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}if(i.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof i.id=="string"){const n=this.getConnection(t);if(n){const{id:a}=i;this.settleSubscribeWatchdog(n,a)}}switch(i.type){case"ack":{const n=this.subscriptions.getById(i.id);n&&this.ackAndAdvanceCursor(n,void 0,void 0);return}case"chunk":{const{data:n,generation:a,id:o,seq:c}=i,d=this.streams.get(o);d&&typeof c=="number"&&(d.lastSeq=c,typeof a=="number"&&(d.generation=a),d.durable=!0),d?.handle.push(C(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,t),this.adoptSocketConnectionId(i,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(i,t);break}case"pokeEnd":{this.handlePokeEnd(i,t);break}case"pokePart":{this.pokeAssembler.part(t,i);break}case"pokeStart":{this.pokeAssembler.start(t,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(f(t),i.topic);break}}}handleErrorMessage(e){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(ze(e)),this.forgetStream(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){z(n);const o=Se(e),c=this.identityFingerprint(),d=T.keyOf(n);this.markQueryRejected(n),F(n.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,o,c);return}const a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&(a.answered||(a.answered=!0,this.emitSyncStatus()),F(a.errorCallbacks,Se(e)))}markQueryRejected(e,t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(t?e.valueReceived:e.ack==="acked")&&(t?e.valueReceived=!0:R(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){tr(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&!s.undecodable.has(i)&&this.applyPokePart(n,s,e)}}}applyPokePart(e,t,s){const i=e.answered,n=er(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),Ie(e),n==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){R(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&sr(i,e))return;let n;const a=i.pendingDeltaRun;try{n=qe(e,a===void 0?i.serverBase:a.payload)}catch(c){i.pendingDeltaRun=void 0,F(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${c instanceof Error?c.message:String(c)}`}),this.settleAwaitedAnswer(i,!1);return}if(n===Ge){this.resnapshotSubscription(i);return}if(ir(e)){i.pendingDeltaRun={payload:n};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(T.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(We(i,n,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(re(i,e.lastMutationId),ne(i,!0)),this.persistQueryValue(i),te(i,i.serverCursor),t!==void 0&&mt(i,t),U(i,n),this.tabCoordinator?.isLeader()){const c=T.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&(t.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(t,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&t.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(T.keyOf(t),t.serverBase,t.serverCursor,t.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(t,!0))}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&re(t,e.lastMutationId),ne(t),this.tabCoordinator?.isLeader())){const s=T.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){const i=e.ack!=="acked";R(e,"acked"),i&&this.emitSyncStatus(),(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),te(e,e.serverCursor)&&U(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(!(s===void 0||typeof e.connectionId!="string")){s.connectionId=e.connectionId,s.whisperAck=e.whisperAck===!0;for(const i of this.liveSocketGrants.get(f(t))?.keys()??[])this.grantWhenJoined(t,i,e.connectionId)}}grantWhenJoined(e,t,s){const i=f(e),n=this.liveSocketGrants.get(i)?.get(t);if(n===void 0)return;const{stream:a,topic:o}=n,c=()=>{this.liveSocketGrants.get(i)?.get(t)===void 0||this.getConnection(e)?.connectionId!==s||this.postLiveControl(`/live/${a}/control`,e,{action:"subscribe",connectionId:s,stream:a,subscriptionId:t,topic:o},h=>{this.refuseLiveGrant(e,t,h,s)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,o,c):c()}sendWhisperJoin(e,t,s){const i=this.whisperJoinState(t,s);i.pending+=1,i.joined=!1,k(e,{topic:s,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,t){const s=this.whisperJoins.get(e)?.get(t);if(s!==void 0&&(s.pending=Math.max(0,s.pending-1),!(s.pending>0))){s.joined=!0;for(const i of s.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,t)}}releaseWhisperJoin(e,t){if(this.whisperHandlers.get(e)?.has(t)===!0)return;const s=this.whisperJoins.get(e),i=s?.get(t);if(!(s===void 0||i===void 0||i.pending>0)){for(const n of i.waiters.splice(0))clearTimeout(n.timer);s.delete(t),s.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,t,s){const i=this.whisperJoinState(e,t);if(i.joined){s();return}const n={run:s,timer:void 0};n.timer=setTimeout(()=>{i.waiters=i.waiters.filter(a=>a!==n),s()},De),i.waiters.push(n)}dropWhisperJoinWaiters(e){for(const t of this.whisperJoins.get(e)?.values()??[])for(const s of t.waiters.splice(0))clearTimeout(s.timer)}whisperJoinState(e,t){let s=this.whisperJoins.get(e);s===void 0&&(s=new Map,this.whisperJoins.set(e,s));let i=s.get(t);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},s.set(t,i)),i}refuseLiveGrant(e,t,s,i){const n=f(e),a=this.liveSocketGrants.get(n),o=a?.get(t);a===void 0||o===void 0||this.getConnection(e)?.connectionId!==i||(a.delete(t),a.size===0&&this.liveSocketGrants.delete(n),o.release(),o.onError?.({status:s,topic:o.topic}))}postLiveControl(e,t,s,i){const{fetchImpl:n}=this;if(!n)return;const a=JSON.stringify(t===void 0?s:{...s,shardKey:t}),o=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>vr(n,_(this.url,e),a,o)).then(c=>{c>=400&&c<500&&c!==404&&c!==401&&i?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(f(t));if(!s)return;const i=C(e.data);for(const n of s.values())if(!(n.stream!==e.stream||n.topic!==e.topic))try{n.onEvent(i)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(f(t))?.get(e.topic);if(!s)return;const i=C(e.data);for(const n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(R(s,"idle"),this.emitSyncStatus(),F(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let t=2166136261,s=5381;for(let i=0;i<e.length;i+=1){const n=e.charCodeAt(i);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&B(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey),n=i!==void 0&&k(i,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),n}roomSendsAdmitted(e){const t=this.getConnection(e);return t?.wsState==="open"&&t.retired!==!0&&t.identityConfirmed===!0&&t.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(const t of this.roomFlushes.get(f(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0,t.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const i of t){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);const n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);const n=t??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(const[o,c]of i)a.set(o,c)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(const e of this.roomIdentityResets)e()}reconnectCold(){for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,R(e,"idle"),e.valueReceived=!1,U(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Ie(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)});for(const e of this.supplementaryBounces)e()}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=f(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const i=(async()=>{await(s??Promise.resolve());const{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&B(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,i),await i,this.offlineFlushes.get(t)===i&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}snapshotAnswer(e){const t=ke(e),s=t&&this.subscriptions.get(T.key(t.functionPath,t.args,t.shardKey));if(s!==void 0)return this.awaitingAnswer.has(s)?"awaiting":this.answeredUnreadable.has(s)?"unreadable":void 0}holdWhileUnanswered(e){const t=ke(e);if(e===void 0||t===void 0)return e;const s=()=>this.snapshotAnswer(e)!==void 0||e();return kt(s,t),s}awaitLeaderAnswers(){for(const e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*ve))}settleAwaitedAnswer(e,t){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),t&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(t||this.answeredUnreadable.add(e),this.answerHeldShards.delete(f(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,t){const s=t.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return s===-1?t:(this.offlineQueue.requeue(t.slice(s)),this.answerHeldShards.add(e),t.slice(0,s))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const h of s){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",u)}const i=f(e),n=this.holdUndecidedWrites(i,this.offlineQueue.drain(h=>f(h.shardKey)===i));if(n.length===0)return;const a=[],o=[];for(const h of n){const u=this.replayGateVerdict(h);u==="send"?a.push(h):u==="hold"&&o.push(h)}if(this.offlineQueue.requeue(o),o.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(a);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let h=0;h<c.length;h+=J){const u=c.slice(h,h+J),l=await this.replayBatched(u,e,t);if(d.push(...l.requeue),l.stop||l.requeue.length>0){d.push(...c.slice(h+J));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=f(e),s=this.replayRetryState.get(t),i=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:i,delayMs:Math.max(s?.delayMs??0,ie(i))})}noteReplayRetryDelay(e,t,s){const i=f(e),n=this.replayRetryState.get(i),a=(n?.attempts??0)+1,o=$i(t,a)??(s===null&&j(t)?ie(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:o===void 0?n?.delayMs:Math.max(n?.delayMs??0,o)})}scheduleRateLimitedRetry(e){const t=f(e),s=this.replayRetryState.get(t),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const n=this.replayRetryTimers.get(t);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{O(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.identityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,t)||Oe(e)}noteReplayAuthRefusal(e,t){if(!j(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...Z(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}spendsLastReplayAttempt(e,t){if(e.id===void 0)return!1;const s=t?.code;if(e.ambiguousSend!==!0||j(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||!Oe(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=at}keepUnexhaustedAmbiguousWrites(e,t){return e.filter(s=>s.ambiguousSend===!0&&this.spendsLastReplayAttempt(s,t)?(this.settleReplayTerminal(s,t),!1):!0)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const n=e[i];if(!n)continue;let a;try{const o=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:s,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Z(n.identity,s),mutationId:n.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(n,o,a)}catch(o){if(q(o)){this.settleReplayUndecodable(n,o,a);continue}if(!this.shouldRequeueReplayFailure(o,s)||this.spendsLastReplayAttempt(n,o)){this.settleReplayTerminal(n,o);continue}this.noteReplayRetryDelay(t,o,s),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const i=JSON.stringify({calls:e.map((d,h)=>({args:O(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&zi(i)>Vi)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:n}=this;let a,o;try{({payload:o,response:a}=await Q(this.rpcTimeoutMs,void 0,async d=>{const h=await n(_(this.url,Y),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...Z(e.find(u=>u.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(h.status===413&&e.length>1)return{payload:void 0,response:h};try{return{payload:await h.json(),response:h}}catch{return{payload:void 0,response:h}}}))}catch(d){return this.noteReplayRetryDelay(t,d,s),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}const c=a.headers.get("x-d1-bookmark");if(c&&this.bookmark.set(c),a.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);if(!o)return this.settleWholeBatchError(e,x(a.status,a.statusText,a.headers),t,s);if(!Array.isArray(o.results)){const d=G(o),h=d===void 0?x(a.status,a.statusText,a.headers):ye(d,a.headers);return this.settleWholeBatchError(e,h,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s,a.headers),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof W||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,t),stop:!0};for(const n of e)this.settleReplayTerminal(n,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),t,s);if(n.stop||n.requeue.length>0)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};const a=await this.replayBatched(e.slice(i),t,s);return{requeue:[...n.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,t,s,i,n){const a=Ji(t),o=[];let c=!1,d=!1;for(const[h,u]of e.entries()){const l=Yi(a.get(h),n);switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(u,l.value,l.commitCursor);break}case"errored":{d||=j(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(u,l.error)?(this.noteReplayRetryDelay(s,l.error,i),o.push(u)):this.settleReplayTerminal(u,l.error);break}case"unanswered":{const p=A(Je(),n);if(this.spendsLastReplayAttempt(u,p)){this.settleReplayTerminal(u,p);break}this.noteReplayRetryDelay(s,p,i),o.push(u);break}default:c=!0,this.settleReplayUndecodable(u,l.error,l.commitCursor)}}return c&&!d&&this.noteCredentialAccepted(i),o}}export{Be as LunoraClient};
1
+ import{LunoraError as b}from"@lunora/errors";import{encodeWire as K,decodeWire as C,stableWireKey as ue}from"@lunora/wire";import{r as qe,U as Ge,P as je}from"./delta-merge-Ls3DED4g.mjs";import{w as g,b as oe,j as _,d as le,p as fe,s as pe}from"./client-urls-BHLUjjcG.mjs";import $e from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{w as A,u as ae,s as Pe,a as Ve,i as q,e as G,r as me,b as ye,c as ze,d as Se,f as Je}from"./wire-errors-BgFi7ONA.mjs";import{ClientQueryStore as Ye}from"./createClientQuery-B8Nfj-7o.mjs";import{D as Xe,a as Ze,b as et,c as tt,d as st,S as be,M as it,I as rt,Q as nt,R as ot,e as ve,f as at,g as ct}from"./client-tuning-C10B2KCO.mjs";import{TabCoordinator as dt}from"./TabCoordinator-DBuR7Dwv.mjs";import{TransportError as W,getRetryAfterMs as ht,AUTH_REPLAY_ERROR_CODES as ut,isAuthReplayFailure as j}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as lt}from"./httpStream-B9iENFKq.mjs";import{d as te,r as U,a as M,b as ft,c as pt,e as mt,f as yt}from"./local-store-C3bw2MPY.mjs";import{O as St,n as ge,i as bt}from"./offline-queue-BEqCPDmw.mjs";import{resolvePersistenceAdapter as vt}from"./createInMemoryPersistence-C-IzNVbg.mjs";import{w as Q,a as we,b as gt}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as wt,queryCacheKey as H}from"./createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as Te}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as F,setSubscriptionAck as R,SubscriptionRegistry as T,wrapSubscriber as V,releaseSubscribeFrame as z}from"./SubscriptionRegistry-BKgQtuh9.mjs";import{c as Tt,s as ke,r as kt}from"./snapshot-precondition-BEtcSbWr.mjs";import{createStream as Ct}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const J=500,Le=(r,e)=>{if(r.size<e)return;const t=r.keys().next().value;t!==void 0&&r.delete(t)},I="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",At=r=>{let e="",t=0;const s=r.length-2;for(;t<s;t+=3){const n=r[t]<<16|r[t+1]<<8|r[t+2];e+=I.charAt(n>>18&63)+I.charAt(n>>12&63)+I.charAt(n>>6&63)+I.charAt(n&63)}const i=r.length-t;if(i===1){const n=r[t]<<16;e+=I.charAt(n>>18&63)+I.charAt(n>>12&63)}else if(i===2){const n=r[t]<<16|r[t+1]<<8;e+=I.charAt(n>>18&63)+I.charAt(n>>12&63)+I.charAt(n>>6&63)}return e};new TextDecoder;const Et=new TextEncoder,_t=r=>At(Et.encode(JSON.stringify(r))),Ot="x-lunora-expect-subject",It=r=>_t({subject:r}),Ce=Symbol.for("lunora:session-change"),Rt="lunora:session-change",Ft="better-auth.message",Pt="signout",Me=()=>{const r=globalThis;let e=r[Ce];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},r[Ce]=e),e},Lt=()=>"document"in globalThis,Mt=async()=>{const r=[];for(const e of Me().listeners)try{r.push(e())}catch{}await Promise.allSettled(r)},Ht=(r,e)=>{if(r!==Ft||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===Pt}catch{return!1}},Ut=r=>{const e=[],t=()=>{Mt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(Rt):void 0}catch{s=void 0}if(s!==void 0){const n=s;n.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==r&&t()}),e.push(()=>{n.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const n=a=>{Ht(a.key,a.newValue)&&t()};i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(const n of e)n()}},Nt=r=>{const e=Me();return e.listeners.add(r),e.detach===void 0&&Lt()&&(e.detach=Ut(e.tab)),()=>{e.listeners.delete(r),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},Wt="/_lunora/rpc",Y="/_lunora/rpc-batch",X="/_lunora/ws",Dt="/_lunora/admin/shard-traffic",Bt="/_lunora/admin/scheduled",xt="/_lunora/admin/scheduled/status",Qt="/_lunora/admin/scheduled/ws",Kt="/_lunora/admin/scheduled/cancel",Ae="/_lunora/admin/scheduled/dead",qt="/_lunora/admin/scheduled/dead/retry",Gt="/_lunora/admin/scheduled/dead/cancel",jt="/_lunora/admin/workflows/instances",$t="/_lunora/admin/workflows/instance",Vt="/_lunora/admin/workflows/status",ce="/_lunora/admin/storage",zt="/_lunora/admin/storage/url",Jt="/_lunora/admin/storage/buckets",Yt="/_lunora/admin/functions",Xt="/_lunora/admin/cron-jobs",Zt="/_lunora/admin/cron-jobs/run",es="/_lunora/admin/architecture",ts="/_lunora/admin/openapi",ss="/_lunora/admin/openrpc",is="/_lunora/admin/global/tables",rs="/_lunora/admin/global/table",ns="/_lunora/admin/global/facet",os="/_lunora/admin/vector/indexes",as="/_lunora/admin/vector/query",cs="/_lunora/admin/logs/archive",ds="/_lunora/admin/kv/namespaces",hs="/_lunora/admin/kv/keys",de="/_lunora/admin/kv/value",us="/_lunora/admin/auth/users",ls="/_lunora/admin/auth/sessions",fs="/_lunora/admin/auth/users/create",ps="/_lunora/admin/auth/users/role",ms="/_lunora/admin/auth/users/ban",ys="/_lunora/admin/auth/users/unban",Ss="/_lunora/admin/auth/users/password",bs="/_lunora/admin/auth/users/remove",vs="/_lunora/admin/auth/users/impersonate",gs="/_lunora/admin/auth/sessions/revoke",ws="/_lunora/admin/auth/sessions/revoke-all",Ts="/_lunora/admin/auth/capabilities",ks="/_lunora/admin/auth/users/update",Cs="/_lunora/admin/auth/accounts",As="/_lunora/admin/auth/accounts/unlink",Es="/_lunora/admin/auth/passkeys",_s="/_lunora/admin/auth/passkeys/delete",Os="/_lunora/admin/auth/two-factor/disable",Is="/_lunora/admin/auth/organizations",Rs="/_lunora/admin/auth/organizations/members",Fs="/_lunora/admin/auth/organizations/invitations",Ps="/_lunora/admin/auth/organizations/members/remove",Ls="/_lunora/admin/auth/organizations/invitations/cancel",Ms="/_lunora/admin/auth/config",Hs="/_lunora/admin/auth/sign-up-invitations",Us="/_lunora/admin/auth/sign-up-invitations/create",Ns="/_lunora/admin/auth/sign-up-invitations/revoke",Ws="/_lunora/admin/auth/organizations/create",Ds="/_lunora/admin/auth/organizations/update",Bs="/_lunora/admin/auth/organizations/remove",xs="/_lunora/admin/auth/organizations/members/add",Qs="/_lunora/admin/auth/organizations/members/invite",Ks="/_lunora/admin/auth/organizations/members/role",qs="/_lunora/admin/auth/organizations/teams",Gs="/_lunora/admin/auth/organizations/teams/create",js="/_lunora/admin/auth/organizations/teams/update",$s="/_lunora/admin/auth/organizations/teams/remove",Vs="/_lunora/admin/auth/organizations/teams/members",zs="/_lunora/admin/auth/organizations/teams/members/add",Js="/_lunora/admin/auth/organizations/teams/members/remove",Ys="/_lunora/admin/auth/organizations/roles",Xs="/_lunora/admin/auth/organizations/roles/create",Zs="/_lunora/admin/auth/organizations/roles/update",ei="/_lunora/admin/auth/organizations/roles/remove",ti="/api/auth",si="/get-session",ii="lunora-ping",ri=async r=>(r.assertOpen(),(await r.adminFetch(Yt,"GET")).functions??[]),ni=async r=>(r.assertOpen(),(await r.adminFetch(Xt,"GET")).jobs??[]),oi=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(Zt,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},ai=async r=>(r.assertOpen(),await r.adminFetch(ts,"GET")),ci=async r=>(r.assertOpen(),await r.adminFetch(es,"GET")),di=async r=>(r.assertOpen(),await r.adminFetch(ss,"GET")),hi=async r=>(r.assertOpen(),await r.adminFetch(is,"GET")),ui=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(K(e.filters))),C(await r.adminFetch(`${rs}?${t.toString()}`,"GET"))},li=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(K(e.filters))),C(await r.adminFetch(`${ns}?${t.toString()}`,"GET"))},fi=async r=>(r.assertOpen(),(await r.adminFetch(ds,"GET")).namespaces??[]),pi=async(r,e)=>{r.assertOpen();const t=g(hs,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await r.adminFetch(t,"GET")},mi=async(r,e)=>{r.assertOpen();const t=g(de,{key:e.key,namespace:e.namespace});return await r.adminFetch(t,"GET")},yi=async(r,e)=>{r.assertOpen(),await r.adminFetch(de,"PUT",e)},Si=async(r,e)=>{r.assertOpen();const t=g(de,{key:e.key,namespace:e.namespace});await r.adminFetch(t,"DELETE")},bi=async(r,e)=>{r.assertOpen();const t=await r.adminFetch(Dt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},vi=async(r,e={})=>{r.assertOpen();const t=await r.adminFetch(cs,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},gi=async r=>{const e=[];let t;for(;;){const s=await r(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},he=r=>"args"in r?{...r,args:C(r.args)}:r,wi=async r=>(r.assertOpen(),((await r.adminFetch(Bt,"GET")).records??[]).map(t=>he(t))),Ti=async r=>{r.assertOpen();const e=await r.adminFetch(xt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},ki=async(r,e)=>(r.assertOpen(),{cancelled:(await r.adminFetch(Kt,"POST",{id:e})).cancelled===!0}),Ci=async r=>(r.assertOpen(),(await gi(async t=>await r.adminFetch(t===void 0?Ae:`${Ae}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>he(t))),Ai=async(r,e)=>(r.assertOpen(),{retried:(await r.adminFetch(qt,"POST",{id:e})).retried===!0}),Ei=async(r,e)=>(r.assertOpen(),{removed:(await r.adminFetch(Gt,"POST",{id:e})).removed===!0}),_i=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await r.adminFetch(`${jt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},Oi=async(r,e)=>{r.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await r.adminFetch(`${$t}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}},Ii=async(r,e)=>(r.assertOpen(),{status:(await r.adminFetch(Vt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),Ri=async(r,e={})=>{r.assertOpen();const t=g(ce,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await r.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},Fi=async(r,e,t)=>{r.assertOpen();const s=`${ce}?key=${encodeURIComponent(e)}${oe(t?.bucket)}`,i=await r.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},Pi=async r=>(r.assertOpen(),(await r.adminFetch(Jt,"GET")).buckets??[]),Li=async(r,e)=>{r.assertOpen();const t=`${ce}?key=${encodeURIComponent(e.key)}${oe(e.bucket)}`,s=await r.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},Mi=async(r,e,t)=>{r.assertOpen();const s=t?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${zt}?key=${encodeURIComponent(e)}${i}${oe(t?.bucket)}`,a=await r.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url},Hi=async r=>(r.assertOpen(),(await r.adminFetch(os,"GET")).indexes??[]),Ui=async(r,e)=>(r.assertOpen(),(await r.adminFetch(as,"POST",e)).matches??[]),O=(r,e)=>{try{return K(r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},se=r=>{try{return K(r),!0}catch{return!1}},He=r=>r!==null&&typeof r=="object"&&("error"in r||"result"in r),Ni=(r,e,t)=>{const s=Array.from({length:e}),i=n=>({error:A(Pe(n),t),ok:!1});for(const n of r){if(typeof n.id!="number"||n.id<0||n.id>=e)continue;if(!He(n.body)){s[n.id]=i({});continue}const a=n.body;if("error"in a){s[n.id]=i(a);continue}try{s[n.id]={ok:!0,value:C(a.result)}}catch(o){s[n.id]={error:A(ae(o),t),ok:!1}}}return s.map(n=>n??{error:A(new Error("batch call returned no result"),t),ok:!1})},Z=(r,e)=>e!==null?{}:r===null?{expectSubject:null}:r?.startsWith("subj:")===!0?{expectSubject:r.slice(5)}:{},B=r=>r==="connected"||r==="polling",f=r=>r??"",k=(r,e)=>{if(!r.socket||r.wsState!=="open")return!1;try{return r.socket.send(JSON.stringify(e)),!0}catch{return!1}},Wi=r=>{if(!r.pendingStreams||r.pendingStreams.length===0)return;const e=r.pendingStreams;r.pendingStreams=[];for(const t of e)k(r,t)},Di=new TextDecoder,Bi=r=>{if(typeof r=="string")return r;if(r instanceof ArrayBuffer)return Di.decode(r)};class P{listeners=new Set;get size(){return this.listeners.size}add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const N=r=>{r.heartbeatTimer!==void 0&&(clearInterval(r.heartbeatTimer),r.heartbeatTimer=void 0)},xi=(r,e,t)=>{N(r),!(e<=0)&&(r.heartbeatTimer=setInterval(()=>{if(!r.socket)return;const{socket:s}=r;if(Date.now()-r.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(ii)}catch{}},e))},Ee=(r,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:a}=t;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");const o=new i(e);r.socket=o;const c=()=>{N(r),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.socket===o&&(r.socket=void 0)},d=h=>{c(),s.onClose(h)};n>0&&(r.connectTimer=setTimeout(()=>{if(r.connectTimer=void 0,r.socket===o){try{o.close()}catch{}d()}},n)),o.addEventListener("open",()=>{if(r.socket===o){r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),r.lastFrameAt=Date.now();try{s.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}r.socket===o&&xi(r,a,d)}}),o.addEventListener("message",h=>{if(r.socket===o){r.lastFrameAt=Date.now();try{s.onMessage(h)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),o.addEventListener("close",h=>{r.socket===o&&d(h)}),o.addEventListener("error",()=>{r.socket===o&&d()})},Qi=r=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:n}=r,a=t>0&&e>0;let o=0,c,d=!1,h=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},l=y=>{if(c!==void 0){if(!y){u();return}d||(d=!0,i()),s()}},p=()=>{h||(h=!0,n().then(l).finally(()=>{h=!1}).catch(()=>{}))};return{hasFailedOpen:()=>o>0,isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{o+=1,!(!a||c!==void 0||o<e)&&(c=setInterval(p,t),i(),p())},noteOpen:()=>{o=0,u()},stop:u}},Ki=1e4,_e=async r=>Q(Ki,void 0,r,()=>new TypeError("LunoraClient: poll timed out")),Ue=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Oe=r=>{if(r instanceof W)return!0;const e=r?.code;return e===void 0||Ue.has(e)||ut.has(e)},qi=1e3,Ne=6e4,Gi={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},x=(r,e,t)=>{const s=Ve(t.get("retry-after")),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${r.toString()}${e?` ${e}`:""})`,a=r<400||r>=500||r===408?new W(n,i):new b(Gi[r]??"BAD_REQUEST",n,{data:i});return A(a,t)},ie=(r,e=Math.random)=>{const t=Math.min(qi*2**Math.max(r-1,0),Ne);return Math.round(t*(.5+e()*.5))},ji=r=>{const e=r?.code;return r instanceof W||e===void 0||Ue.has(e)},$i=(r,e,t)=>{const s=ht(r);return s!==void 0&&s>0?Math.min(s,Ne):ji(r)?ie(e,t):void 0},Vi=983040,zi=r=>typeof TextEncoder>"u"?r.length:new TextEncoder().encode(r).length,Ji=r=>{const e=new Map;for(const t of r)typeof t.id=="number"&&He(t.body)&&e.set(t.id,t.body);return e},Yi=(r,e)=>{if(r===void 0)return{kind:"unanswered"};if("error"in r)return{error:A(Pe(r),e),kind:"errored"};try{return{commitCursor:r.commitCursor,kind:"committed",value:C(r.result)}}catch(t){return{commitCursor:r.commitCursor,error:A(ae(t),e),kind:"undecodable"}}},ee=(r,e)=>`${f(r)}\0${e}`,Xi=(r,e)=>{for(const t of e)t.op==="delete"?r.delete(t.key):t.value!==void 0&&r.set(t.key,t.value)};class Zi{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Le(this.buffers,this.maxBuffers),this.buffers.set(ee(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(ee(e,t.pokeId));if(!s)return;const i=[];try{for(const o of t.rowsPatch)i.push(o.value===void 0?o:{...o,value:C(o.value)})}catch(o){s.undecodable.set(t.shapeId,o);return}const n=s.parts.get(t.shapeId)??[];for(const o of i)n.push(o);s.parts.set(t.shapeId,n),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const a=t.baseCheckpoint??s.baseCheckpoint;a!==void 0&&s.bases.set(t.shapeId,a),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=ee(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const er=(r,e,t)=>{const s=e.parts.get(r.id)??[],i=e.resets.has(r.id),n=e.bases.get(r.id),a=e.epoch!==void 0&&r.serverEpoch!==void 0&&e.epoch!==r.serverEpoch,o=n!==void 0&&r.serverCursor!==void 0&&r.serverCursor!==n;if(!i&&(a||o))return r.rows.clear(),r.serverCursor=void 0,r.serverEpoch=void 0,r.answered=!1,"reseed";i&&r.rows.clear(),Xi(r.rows,s),r.answered=!0,t.checkpoint!==void 0&&(r.serverCursor=t.checkpoint),t.epoch!==void 0&&(r.serverEpoch=t.epoch);const c=e.lastMutationId.get(r.id);return c!==void 0&&(r.lastMutationId=c),"applied"},Ie=r=>{const e=[...r.rows.values()];for(const t of r.callbacks)try{t(e)}catch{}},tr=(r,e)=>{for(const[t,s]of e.undecodable){const i=r.get(t);i&&F(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},re=(r,e)=>{r.lastMutationId=Math.max(r.lastMutationId??0,e)},ne=(r,e=!1)=>{for(const t of r.checkpointCallbacks)t({checkpoint:r.serverCursor,mutationId:r.lastMutationId,...e&&{rowsFollow:!0}})},We=(r,e,t)=>{r.serverBase=e,t.cursor!==void 0&&(r.serverCursor=t.cursor),t.epoch!==void 0&&(r.serverEpoch=t.epoch)},sr=(r,e)=>e.cursor!==void 0&&r.serverCursor!==void 0&&r.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===r.serverEpoch&&e.cursor<r.serverCursor,ir=r=>r.type==="delta"&&r.more===!0,$=(r,e)=>r!==void 0&&r!==e,rr=(r,e)=>e==="connected"&&r!=="connected"||e==="polling"&&r!=="connected"&&r!=="polling",nr=r=>{for(const e of r.activeSubscriptions())e.valueReceived=!1,r.ensureSocket(e.shardKey),r.queueResubscribe(e);for(const e of r.activeShapes())e.answered=!1,r.ensureSocket(e.shardKey);for(const e of r.queuedShardKeys())r.ensureSocket(e);r.broadcastStatus(r.computeStatus(),r.identityFingerprint()),r.emitConnectionStatus()},or=r=>{r.closeConnections();const e=r.leader;e.status=void 0,e.wasEverConnected=!1;for(const t of r.activeSubscriptions())R(t,"idle"),t.valueReceived=!1;for(const t of r.activeShapes())t.answered=!1;r.emitConnectionStatus()},ar=(r,e,t)=>{if($(t,r.identityFingerprint()))return;const s=r.leader,i=rr(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),r.emitConnectionStatus(),i&&(r.awaitLeaderAnswers(),r.flushOfflineQueues())},cr=r=>{r.isLeader()&&r.broadcastStatus(r.computeStatus(),r.identityFingerprint())},dr=(r,e,t,s,i,n)=>{if($(n,r.identityFingerprint()))return;const a=r.subscription(e);if(!a)return;r.dropCacheSeed(e);const o=!a.valueReceived;a.valueReceived=!0,We(a,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&te(a,s),U(a,t),o&&r.emitConnectionStatus(),r.settleAwaitedAnswer(a,!0)},hr=(r,e,t,s)=>{if($(s,r.identityFingerprint()))return;const i=r.subscription(e);if(i){const n=!i.valueReceived;i.valueReceived=!0,F(i.errorCallbacks,t),n&&r.emitConnectionStatus(),r.settleAwaitedAnswer(i,!1)}},ur=(r,e,t,s,i,n,a)=>{if($(a,r.identityFingerprint()))return;const o=r.subscription(e);o&&(r.ackAndAdvanceCursor(o,t,s),i!==void 0&&n===r.clientIdentifier()&&re(o,i),ne(o))},lr=(r,e,t)=>r!==null||e&&t===null,fr=r=>r.sensitive===!0,pr=(r,e)=>{if(!fr(r))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${r.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},mr=[je],yr=100,De=1e4,Sr=1e4,br=(r,e)=>{let t;const s=new Promise((n,a)=>{t=setTimeout(()=>{a(new Error("ws ticket mint timed out"))},e)}),i=(async()=>r())();return Promise.race([i,s]).finally(()=>{clearTimeout(t)})},Re=async r=>typeof r=="function"?await r():r,vr=async(r,e,t,s)=>{const i=new AbortController,n=setTimeout(()=>{i.abort()},De);try{const a=await r(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return await a.text(),a.status}finally{clearTimeout(n)}},Fe=(r,e)=>new b("OFFLINE_NOT_QUEUED",`'${r}' is online-only and the connection is not live, so it was not queued`,{cause:e}),gr=(r,e)=>r instanceof TypeError&&se(e),wr=(r,e,t,s)=>e||r===!0&&t&&!s,Tr=Promise.resolve();class Be{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new T;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new P;statusListeners=new P;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new P;identityChangeListeners=new P;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new P;pendingChangeListeners=new P;syncStatusListeners=new P;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Zi(Be.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??_(le(e.url),X),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??ti;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??$e(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Xe,this.connectTimeoutMs=e.connectTimeoutMs??Ze,this.rpcTimeoutMs=e.rpcTimeoutMs??et,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??tt,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??st,this.defaultConnectionContext=e.connectionContext,this.persistence=vt(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=wt(e.queryCache),this.clientQueryStore=new Ye,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Tr),this.offlineQueue=new St(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onReplayingChange:()=>{this.emitSyncStatus()},onSizeChange:s=>{this.pendingChangeListeners.emit(s),this.emitSyncStatus()},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${ge()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=Nt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),o=this.isKnownNobody(),c=this.authToken;this.authToken=e,s&&(this.tokenFingerprint=void 0),this.applySubject(e,t);const d=this.identityFingerprint(),h=!s&&e!==null&&n,u=!s&&e===null&&i===null&&n&&!o,l=d!==i;let p=!1;l&&(h?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):u?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):p=this.retirePreviousIdentity(i,o,c,e)),p||this.applyUpgradeBearer(this.reconcileUpgradeBearer(c,e,l)),l&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==i||s||a)&&this.offlineQueue.size>0&&B(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){const t=this.identityVerdict(e);if(t!=="match")return{verdict:t};const s=Object.freeze({});return this.replayCredentials.set(s,{authToken:this.authToken,stamp:e}),{credential:s,verdict:t}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const n=s?.shardKey??"",a=this.identityFingerprint();let o,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:u=>{o=u}})}catch(u){if(!q(u))throw u;d=u}if(o!==void 0&&o>(this.clientWatermarks.get(a??"")?.get(n)??0)){let u=this.clientWatermarks.get(a??"");u===void 0&&(Le(this.clientWatermarks,ct),u=new Map,this.clientWatermarks.set(a??"",u)),u.set(n,o)}if(d!==void 0)throw d;return{applied:o===void 0||o===i,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const i=await this.fetchImpl(_(this.url,`${this.authBasePath}${si}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(t,null,s),null;const a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,a,s),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=f(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=f(t.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;const o=this.connectionContextHolders.get(s);if(!o)return;const c=o.indexOf(i);c!==-1&&o.splice(c,1),o.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const i=f(s.shardKey);let n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e);const o=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),o){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,i,e)}return()=>{const c=this.whisperHandlers.get(i),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const h=this.getConnection(s.shardKey);h&&k(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:i,stream:n,topic:a}=e;if(a.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const o=`ws-live-${String(this.nextLiveSocketId)}`,c=f(i),d=`/live/${n}/control`;let u=this.whisperSubscribe(a,()=>{},{shardKey:i});const l=()=>{const S=u;u=void 0,S?.()};let p=this.liveSocketGrants.get(c);p===void 0&&(p=new Map,this.liveSocketGrants.set(c,p)),p.set(o,{onError:t,onEvent:s,release:l,stream:n,topic:a});const y=this.getConnection(i)?.connectionId;y!==void 0&&this.grantWhenJoined(i,o,y);let m=!1;return()=>{if(m)return;m=!0;const S=this.liveSocketGrants.get(c),E=S?.delete(o)===!0;S?.size===0&&this.liveSocketGrants.delete(c);const v=this.getConnection(i)?.connectionId;E&&v!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:v,stream:n,subscriptionId:o,topic:a}),l()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,O(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const i=`room:${e.name}`,n=this.whisperSubscribe(i,l=>{t.onMessage(l)},s);let a=!1;const o=[],c=()=>{o.length=0},d=()=>{for(;o.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(i,o[0],s))return;o.shift()}},h=f(s.shardKey),u=this.roomFlushes.get(h)??new Set;return u.add(d),this.roomFlushes.set(h,u),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,u.delete(d),u.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(c),n()},send:l=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=O(l,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,y,s)?!0:o.length>=yr?!1:(o.push(y),!0)}}}connectWebSocket(e,t,s={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:()=>{},send:()=>{}};const i=o=>{try{o?.()}catch(c){console.error("[lunora] socket route handler threw",c)}};let n;const a=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:()=>{clearTimeout(n),i(t.onClose)},onMessage:o=>{let c;try{c=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}c.type==="message"&&(a.resetBackoff(),i(()=>{t.onMessage(C(c.data))}))},onOpen:()=>{clearTimeout(n);const o=a.socket();n=setTimeout(()=>{a.socket()===o&&a.resetBackoff()},be),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(n),a.close()},send:o=>{const c=JSON.stringify(O(o,`socket message for '${e}'`)),d=a.socket();if(d!==void 0)try{d.send(c)}catch{}}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}syncStatus(){const e=this.computeStatus(),t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader();let s=0;for(const n of this.subscriptions.all())(t||this.connectionGateState(n.shardKey).polling?n.valueReceived:n.ack==="acked")||(s+=1);for(const n of this.shapeSubscriptions.values())n.answered||(s+=1);const i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:s,pendingWrites:i,synced:B(e)&&s===0&&i===0}}onSyncStatus(e){const t=this.syncStatusListeners.add(e),s=this.syncStatus();return this.lastSyncStatus=s,e(s),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const a=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}const i=this.subscriptions.all().map(n=>({acked:n.ack==="acked",functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())i.push({acked:n.answered,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){const t=this.getConnection(e.shardKey);return t===void 0||t.wsState==="open"?!0:t.polling.isPolling()||!t.polling.hasFailedOpen()}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Tt(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:we(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ue(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=H(e,t,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=T.key(e,t,s),n=this.subscriptions.get(i);return{answered:n!==void 0&&(n.lastValue!==void 0||n.ack==="acked"||n.valueReceived),present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,signal:s.signal})}async batch(e){return Q(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw gt(s.signal);const{value:i}=await we(this.runMutation(e,t,s),s.signal);return i}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0,signal:s.signal,unbounded:!0})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),a=t.length;let o=0,c=0,d=0;for(let h=0;h<a;h+=i){const u=t.slice(h,h+i),l=d,{committed:p}=await this.runMutation(e,n(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey});d+=1,o+=u.length,p&&(c+=u.length),s.onProgress?.({done:o,total:a})}return{chunks:d,imported:c,queued:o-c}}async shardTraffic(e){return bi(this.adminHost,e)}async listScheduledJobs(){return wi(this.adminHost)}async schedulerStatus(){return Ti(this.adminHost)}async cancelScheduledJob(e){return ki(this.adminHost,e)}async listDeadJobs(){return Ci(this.adminHost)}async retryDeadJob(e){return Ai(this.adminHost,e)}async removeDeadJob(e){return Ei(this.adminHost,e)}async listWorkflowInstances(e){return _i(this.adminHost,e)}async getWorkflowInstance(e){return Oi(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ii(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=this.openSupplementarySocket(_(le(this.url),Qt),{onMessage:s=>{let i;try{i=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(t.resetBackoff(),e(i.records.map(n=>he(n))))}});return t.close}async listFunctions(){return ri(this.adminHost)}async getCronJobs(){return ni(this.adminHost)}async runCronJob(e){return oi(this.adminHost,e)}async fetchOpenApi(){return ai(this.adminHost)}async fetchArchitecture(){return ci(this.adminHost)}async fetchOpenRpc(){return di(this.adminHost)}async listStorageObjects(e={}){return Ri(this.adminHost,e)}async deleteStorageObject(e,t){return Fi(this.adminHost,e,t)}async listStorageBuckets(){return Pi(this.adminHost)}async uploadStorageObject(e){return Li(this.adminHost,e)}async signedStorageUrl(e,t){return Mi(this.adminHost,e,t)}async listGlobalTables(){return hi(this.adminHost)}async readGlobalTablePage(e){return ui(this.adminHost,e)}async facetGlobalColumn(e){return li(this.adminHost,e)}async listVectorIndexes(){return Hi(this.adminHost)}async queryVectorIndex(e){return Ui(this.adminHost,e)}async queryLogArchive(e={}){return vi(this.adminHost,e)}async listKvNamespaces(){return fi(this.adminHost)}async listKvKeys(e){return pi(this.adminHost,e)}async getKvValue(e){return mi(this.adminHost,e)}async putKvValue(e){return yi(this.adminHost,e)}async deleteKvKey(e){return Si(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=g(us,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(fs,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(ps,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(ms,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(ys,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(bs,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(gs,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(ws,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Ts,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(ks,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(g(Cs,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(As,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(g(Es,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(_s,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(Os,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(g(Is,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=g(Rs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=g(Fs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=g(Hs,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Us,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Ns,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(Ps,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Ls,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(Ms,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Ws,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Ds,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Bs,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(xs,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Qs,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Ks,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=g(qs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Gs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(js,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch($s,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=g(Vs,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(zs,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Js,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=g(Ys,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Xs,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Zs,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(ei,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=g(ls,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const n=t??{},a=T.key(e.__lunoraRef,n,i.shardKey);let o=this.subscriptions.get(a);const c=V(s),d=V(i.onError),h=V(i.onCheckpoint);if(!o){this.nextSubId+=1;const y=`sub_${this.nextSubId.toString()}`,m=ue(n),S=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);o={ack:"idle",args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:S?.value,optimisticLayers:[],serverBase:S?.value,serverCursor:S?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:O(n,`args for '${e.__lunoraRef}'`),...S?.serverEpoch===void 0?{}:{serverEpoch:S.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),this.isCrossTabFollower()&&B(this.computeStatus())&&this.awaitLeaderAnswer(o),S!==void 0&&this.cacheSeededQueries.set(a,S)}if(o.callbacks.add(c),d&&o.errorCallbacks.add(d),h&&o.checkpointCallbacks.add(h),o.lastValue!==void 0)try{c(o.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const u=o;let l=!1;const p=()=>{if(!l&&(l=!0,i.signal?.removeEventListener("abort",p),u.callbacks.delete(c),d&&u.errorCallbacks.delete(d),h&&u.checkpointCallbacks.delete(h),u.callbacks.size===0)){this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(T.keyOf(u)),this.subscriptions.remove(u);const y=this.getConnection(u.shardKey);y&&this.settleSubscribeWatchdog(y,u.id),this.releaseIdleShard(u.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(u,!0)}};return i.signal?.addEventListener("abort",p,{once:!0}),i.signal?.aborted&&p(),p}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const i=`shape_${this.nextShapeId.toString()}`,n={answered:!1,args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:O(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.emitSyncStatus(),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey),this.emitSyncStatus()}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=t??{},{handle:o,iterable:c}=Ct({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,n)}});this.ensureSocket(n);const d=this.getConnection(n),h={id:i,query:{args:O(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:o,lastSeq:0,message:h,shardKey:n};this.streams.set(i,u);const l=d?.wsState==="open"&&k(d,h);if(!l&&d===void 0)return this.forgetStream(i),o.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!l){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=it;){const y=d.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(y))}d.pendingStreams.push(h)}return c}httpStream(e,t,s={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return lt(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear();for(const e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}retirePreviousIdentity(e,t,s,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(s,i),lr(e,t,i)?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,t,s){return!this.authTokenOnUpgrade||t===null||e===t?"none":s?e===null?"cold":"none":e===null?"none":"warm"}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets()}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>f(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=f(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},rt))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=f(e.shardKey);for(const[i,n]of this.streams)f(n.shardKey)===t&&(n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,N(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeShapes:()=>[...this.shapeSubscriptions.values()],activeSubscriptions:()=>this.subscriptions.all(),awaitLeaderAnswers:()=>{this.awaitLeaderAnswers()},broadcastStatus:(s,i)=>this.tabCoordinator?.broadcastConnectionStatus(s,i),closeConnections:()=>{for(const[s,i]of this.connections)this.teardownConnection(i),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,i,n)=>{this.ackAndAdvanceCursor(s,i,n)},settleAwaitedAnswer:(s,i)=>{this.settleAwaitedAnswer(s,i)},subscription:s=>this.subscriptions.get(s)};return new dt({channelName:e,onBecomeLeader:()=>{nr(t)},onStopBeingLeader:()=>{or(t)},onConnectionStatus:(s,i)=>{ar(t,s,i)},onSubscriptionData:(s,i,n,a,o)=>{dr(t,s,i,n,a,o)},onLeaderClaimAnswered:()=>{cr(t)},onSubscriptionError:(s,i,n)=>{hr(t,s,i,n)},onSubscriptionSettled:(s,i,n,a,o,c)=>{ur(t,s,i,n,a,o,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(_(this.url,Y),{body:JSON.stringify({calls:e.map((o,c)=>({args:O(o.args??{},`args for batch call '${o.fn.__lunoraRef}'`),functionPath:o.fn.__lunoraRef,id:c,shardKey:o.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await s.json()}catch{throw A(new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`),s.headers)}const a=G(n);if(!s.ok||a!==void 0&&!n.results)throw a!==void 0?A(me(a),s.headers):A(new b("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`),s.headers);for(const o of n.results??[]){const c=o.body?.commitCursor;typeof o.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[o.id]?.shardKey,c)}return Ni(n.results??[],e.length,s.headers)}async runMutation(e,t,s){this.assertOpen();const i=pr(e,s),n=t,a=i.mutationId??ge();this.mutationIssueCounter+=1;const o=this.mutationIssueCounter,c=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);const{confirms:h,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,n,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,u,h);const l=i.onlineOnly?void 0:this.offlineFlushes.get(f(i.shardKey));l!==void 0&&await l;const{httpFirst:p,midReconnect:y,shouldQueueOffline:m,socketDown:S}=this.writeQueueGate(i.shardKey),E=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),v=async(w=!1)=>this.enqueueOfflineMutation(e,n,i.shardKey,d,a,u,h,w?void 0:i.precondition,i.mutationId,c?.stamp,w,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,u),S||y||E)return v();let D;try{const w=await this.rpc(e.__lunoraRef,n,i.shardKey,{baselineSeq:d,captureBookmark:!0,...c?.flags,mutationId:a,onCommitCursor:L=>{D=L}});for(const L of h)L(D);return{committed:!0,value:w}}catch(w){const L=gr(w,n),xe=p&&m&&L,Qe=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof W)&&se(n)){const Ke=v(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),Ke}throw this.settleFailedDirectWrite(w,D,h,u,c?.flags.authToken),wr(i.onlineOnly,xe,L,Qe)?Fe(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw M(s),Fe(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){const{hasSocket:t,idleClosed:s,polling:i,wasEverConnected:n,wsState:a}=this.connectionGateState(e),{queueBeforeFirstConnect:o}=this.offlineQueue,c=n||o,d=this.WebSocketImpl!==void 0&&c,h=i||s;return{httpFirst:h,midReconnect:a==="connecting"&&c&&!h,shouldQueueOffline:d,socketDown:a!=="open"&&!t&&d&&!h,socketOpen:a==="open"}}settleFailedDirectWrite(e,t,s,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),q(e)){for(const a of s)a(t);return}M(i)}async enqueueOfflineMutation(e,t,s,i,n,a,o,c,d,h,u,l){const p=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:p,mutationId:m,...a.length>0&&{onRejected:()=>{M(a)}},shardKey:s})}catch(S){throw M(a),S instanceof Error?S:new Error(String(S))}for(const S of o)S(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,S)=>{const E={ambiguousSend:u,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,issueSeq:l,clientId:this.clientId,identity:p,precondition:this.holdWhileUnanswered(c),onCommit:v=>{for(const D of o)D(v)},reject:v=>{this.queuedIdentities.delete(n),q(v)||M(a),S(v instanceof Error?v:new Error(String(v))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(E),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),E.id!==void 0&&this.queuedIdentities.set(E.id,p)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=f(e);return this.offlineQueue.hasPending(s=>f(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(H(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(bt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const n=t.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(H(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),U(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,U(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=H(e,t,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=H(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=H(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:t,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},nt))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,i])=>e.put(s,i)))}installPageHideFlush(){const e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;const t=()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},s=()=>{e.document?.visibilityState==="hidden"&&t()};e.addEventListener("pagehide",t),e.document?.addEventListener("visibilitychange",s),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",t),e.document?.removeEventListener("visibilitychange",s)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=f(e);let s;for(const i of this.subscriptions.all())f(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}composedBaselineFor(e,t){return e===void 0?this.baselineCursorFor(t):e??void 0}async pollSubscriptions(e){const t=f(e),s=[];for(const o of this.subscriptions.all())f(o.shardKey)===t&&(se(o.args)?s.push(o):(this.markQueryRejected(o,!0),F(o.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(s.length===0)return this.probeOrigin();const i=yt(),n=this.identityFingerprint();let a;try{a=await _e(async o=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),o))}catch(o){return!(o instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(const[o,c]of s.entries()){const d=a[o];if(d!==void 0){if(!d.ok){this.markQueryRejected(c,!0),F(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:K(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await _e(async t=>e(_(this.url,Y),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;const e=this.syncStatus(),t=this.lastSyncStatus;t?.connection===e.connection&&t.pendingSubscriptions===e.pendingSubscriptions&&t.pendingWrites===e.pendingWrites&&t.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){const e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,i){const n=[],a=[];if(!i)return{confirms:n,rollbacks:a};const o=T.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=ft(c,i);d&&(n.push(d.confirm),a.push(d.rollback))}return{confirms:n,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,n){e&&this.applyOptimisticUpdate(e,t,s,i,n)}applyOptimisticUpdate(e,t,s,i,n){const{confirms:a,rollbacks:o,store:c}=pt(this.subscriptions,s);try{e(c,t)}catch{M(o);return}i.push(...o),n.push(...a)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!k(i,{id:t,type:s})&&i.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(f(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=f(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Qi({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:Te(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}openSupplementarySocket(e,t){if(this.WebSocketImpl===void 0||this.closed)return{close:()=>{},resetBackoff:()=>{},socket:()=>{}};const s=Te(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,a=!1;const o=()=>{a||this.closed||(n=setTimeout(l,s.next()))},c=m=>{a||this.WebSocketImpl===void 0||Ee(i,this.wsUrlFor(t.shardKey,m,e),this.managedSocketOptions,{onClose:()=>{o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen}})};let d=0,h;const u=async m=>{const S=this.wsCredentialGeneration;d+=1;const E=d;let v;h=S;try{v=await br(m,Sr)}catch{E===d&&(h=void 0,o());return}if(E===d){if(h=void 0,S!==this.wsCredentialGeneration){l();return}c(v)}},l=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:m}=this;if(typeof m=="function"){u(m).catch(()=>{});return}c(m)};l();const p=()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),N(i);const{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}};this.adminSocketTeardowns.add(p);const y=()=>{const{socket:m}=i;if(m===void 0){h!==void 0&&h!==this.wsCredentialGeneration&&(d+=1,h=void 0,l());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),N(i);try{m.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(y),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(y)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=fe(this.wsUrl),s=t.pathname.endsWith(X)?t.pathname.slice(0,-X.length):t.pathname;return t.pathname=_(s,e),pe(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=fe(s);if(e===void 0&&t===void 0&&!i.searchParams.has("token"))return s;const n=new Set([...e===void 0?[]:["shard"],"token"]),a=[...i.searchParams].filter(([o])=>!n.has(o)).map(([o,c])=>`${encodeURIComponent(o)}=${encodeURIComponent(c)}`);return e!==void 0&&a.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&a.push(`token=${encodeURIComponent(t)}`),i.search=a.join("&"),pe(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[Ot]=It(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(s.authorization=`Bearer ${n}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const a=this.bookmark.get();a&&(s["x-d1-bookmark"]=a)}return s}async rpc(e,t,s,i={}){const{fetchImpl:n}=this;if(!n)throw new W("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:O(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:d,response:h}=await Q(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const y=await n(_(this.url,Wt),{body:c,headers:a,method:"POST",signal:p});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){const p=h.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(d===void 0)throw x(h.status,h.statusText,h.headers);const u=d;if(typeof u!="object"||u===null||Array.isArray(u))throw x(h.status,h.statusText,h.headers);const l=G(d);if(l!==void 0)throw ye(l,h.headers);if(!h.ok)throw x(h.status,h.statusText,h.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(h,s),this.recordShardCursor(s,d.commitCursor);try{return C(d.result)}catch(p){throw A(ae(p),h.headers)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let o;s===void 0?o=void 0:a?(o=s,i!==void 0&&(n["content-type"]=i)):(o=JSON.stringify(s),n["content-type"]="application/json");const c=await this.fetchImpl(_(this.url,e),{body:o,headers:n,method:t});let d;try{d=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const h=G(d);if(h!==void 0)throw me({...h,message:h.message??"admin request failed"});if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${u})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(f(e.shardKey));k(e,{caps:mr,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())f(t.shardKey)===f(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);t.wsState==="open"||t.wsState==="connecting"||(t.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(t,e).catch(()=>{this.handleDisconnect(t)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,t){const{wsToken:s,wsTicket:i}=this;if(typeof s=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,t);return}this.openSocket(e,t,{session:s,ticket:i})}async openSocketWithProvidedCredentials(e,t){const s=this.wsCredentialGeneration,i=Symbol("ws-token-attempt");let n;e.providerAttempt=i;try{n=await Q(this.connectTimeoutMs,void 0,async()=>({session:await Re(this.wsToken),ticket:await Re(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(s!==this.wsCredentialGeneration){await this.startShardSocket(e,t);return}this.openSocket(e,t,n)}}openSocket(e,t,s){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),s.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=s.session,e.retired=!1;const i=this.wsCredentialGeneration;Ee(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:n=>{n?.code===4003&&e.polling.noteFailedOpen(),n?.code===4001?this.notifyTokenExpired():n?.code===4003&&n.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},onMessage:n=>{e.retired!==!0&&this.handleServerMessage(n.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},be),this.sendConnectEnvelope(e),this.markShardPendingAck(t,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(const o of this.subscriptions.all())f(o.shardKey)===f(t)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:c,type:d}of o)k(e,{id:c,type:d});this.releaseIdleShard(t)}Wi(e);const n=f(t),a=this.whisperHandlers.get(n);if(this.dropWhisperJoinWaiters(n),this.whisperJoins.set(n,new Map),a)for(const o of a.keys())this.sendWhisperJoin(e,n,o);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})}})}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),k(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),N(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(f(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,n]of this.streams)if(!(f(n.shardKey)!==f(e.shardKey)||t.has(i))){if(n.durable){const a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(o=>o.id!==i),a];continue}n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e,t=!1){const s=f(e);for(const i of this.subscriptions.all())f(i.shardKey)===s&&(R(i,"idle"),i.pendingDeltaRun=void 0,t&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(const i of this.shapeSubscriptions.values())f(i.shardKey)===s&&(i.answered=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<ot;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribeSlots.add(t.id)}}settleSubscribeWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t)),e.unackedWatchdogs.delete(t),e.resubscribeSlots.delete(t)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(const t of e.unackedWatchdogs.values())clearTimeout(t);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,t=!1){const s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.ack==="acked"||!t&&e.ack==="inflight")return!1;const i=e.serverCursor!==void 0&&e.serverBase!==void 0,n=k(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return n&&R(e,"inflight"),n&&!t&&this.armUnackedWatchdog(s,e),n}armUnackedWatchdog(e,t,s=!1){clearTimeout(e.unackedWatchdogs.get(t.id)),e.unackedWatchdogs.set(t.id,setTimeout(()=>{if(s){e.unackedWatchdogs.delete(t.id),z(t),this.settleAwaitedAnswer(t,!1);return}const i=t.ack!=="acked"&&this.subscriptions.getById(t.id)===t&&this.sendSubscribeIfOpen(t,!0);this.settleSubscribeWatchdog(e,t.id),i?this.armUnackedWatchdog(e,t,!0):z(t)},ve))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&k(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Bi(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}if(i.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof i.id=="string"){const n=this.getConnection(t);if(n){const{id:a}=i;this.settleSubscribeWatchdog(n,a)}}switch(i.type){case"ack":{const n=this.subscriptions.getById(i.id);n&&this.ackAndAdvanceCursor(n,void 0,void 0);return}case"chunk":{const{data:n,generation:a,id:o,seq:c}=i,d=this.streams.get(o);d&&typeof c=="number"&&(d.lastSeq=c,typeof a=="number"&&(d.generation=a),d.durable=!0),d?.handle.push(C(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,t),this.adoptSocketConnectionId(i,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(i,t);break}case"pokeEnd":{this.handlePokeEnd(i,t);break}case"pokePart":{this.pokeAssembler.part(t,i);break}case"pokeStart":{this.pokeAssembler.start(t,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(f(t),i.topic);break}}}handleErrorMessage(e){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(ze(e)),this.forgetStream(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){z(n);const o=Se(e),c=this.identityFingerprint(),d=T.keyOf(n);this.markQueryRejected(n),F(n.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,o,c);return}const a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&(a.answered||(a.answered=!0,this.emitSyncStatus()),F(a.errorCallbacks,Se(e)))}markQueryRejected(e,t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(t?e.valueReceived:e.ack==="acked")&&(t?e.valueReceived=!0:R(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){tr(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&!s.undecodable.has(i)&&this.applyPokePart(n,s,e)}}}applyPokePart(e,t,s){const i=e.answered,n=er(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),Ie(e),n==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){R(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&sr(i,e))return;let n;const a=i.pendingDeltaRun;try{n=qe(e,a===void 0?i.serverBase:a.payload)}catch(c){i.pendingDeltaRun=void 0,F(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${c instanceof Error?c.message:String(c)}`}),this.settleAwaitedAnswer(i,!1);return}if(n===Ge){this.resnapshotSubscription(i);return}if(ir(e)){i.pendingDeltaRun={payload:n};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(T.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(We(i,n,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(re(i,e.lastMutationId),ne(i,!0)),this.persistQueryValue(i),te(i,i.serverCursor),t!==void 0&&mt(i,t),U(i,n),this.tabCoordinator?.isLeader()){const c=T.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&(t.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(t,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&t.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(T.keyOf(t),t.serverBase,t.serverCursor,t.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(t,!0))}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&re(t,e.lastMutationId),ne(t),this.tabCoordinator?.isLeader())){const s=T.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){const i=e.ack!=="acked";R(e,"acked"),i&&this.emitSyncStatus(),(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),te(e,e.serverCursor)&&U(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(!(s===void 0||typeof e.connectionId!="string")){s.connectionId=e.connectionId,s.whisperAck=e.whisperAck===!0;for(const i of this.liveSocketGrants.get(f(t))?.keys()??[])this.grantWhenJoined(t,i,e.connectionId)}}grantWhenJoined(e,t,s){const i=f(e),n=this.liveSocketGrants.get(i)?.get(t);if(n===void 0)return;const{stream:a,topic:o}=n,c=()=>{this.liveSocketGrants.get(i)?.get(t)===void 0||this.getConnection(e)?.connectionId!==s||this.postLiveControl(`/live/${a}/control`,e,{action:"subscribe",connectionId:s,stream:a,subscriptionId:t,topic:o},h=>{this.refuseLiveGrant(e,t,h,s)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,o,c):c()}sendWhisperJoin(e,t,s){const i=this.whisperJoinState(t,s);i.pending+=1,i.joined=!1,k(e,{topic:s,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,t){const s=this.whisperJoins.get(e)?.get(t);if(s!==void 0&&(s.pending=Math.max(0,s.pending-1),!(s.pending>0))){s.joined=!0;for(const i of s.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,t)}}releaseWhisperJoin(e,t){if(this.whisperHandlers.get(e)?.has(t)===!0)return;const s=this.whisperJoins.get(e),i=s?.get(t);if(!(s===void 0||i===void 0||i.pending>0)){for(const n of i.waiters.splice(0))clearTimeout(n.timer);s.delete(t),s.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,t,s){const i=this.whisperJoinState(e,t);if(i.joined){s();return}const n={run:s,timer:void 0};n.timer=setTimeout(()=>{i.waiters=i.waiters.filter(a=>a!==n),s()},De),i.waiters.push(n)}dropWhisperJoinWaiters(e){for(const t of this.whisperJoins.get(e)?.values()??[])for(const s of t.waiters.splice(0))clearTimeout(s.timer)}whisperJoinState(e,t){let s=this.whisperJoins.get(e);s===void 0&&(s=new Map,this.whisperJoins.set(e,s));let i=s.get(t);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},s.set(t,i)),i}refuseLiveGrant(e,t,s,i){const n=f(e),a=this.liveSocketGrants.get(n),o=a?.get(t);a===void 0||o===void 0||this.getConnection(e)?.connectionId!==i||(a.delete(t),a.size===0&&this.liveSocketGrants.delete(n),o.release(),o.onError?.({status:s,topic:o.topic}))}postLiveControl(e,t,s,i){const{fetchImpl:n}=this;if(!n)return;const a=JSON.stringify(t===void 0?s:{...s,shardKey:t}),o=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>vr(n,_(this.url,e),a,o)).then(c=>{c>=400&&c<500&&c!==404&&c!==401&&i?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(f(t));if(!s)return;const i=C(e.data);for(const n of s.values())if(!(n.stream!==e.stream||n.topic!==e.topic))try{n.onEvent(i)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(f(t))?.get(e.topic);if(!s)return;const i=C(e.data);for(const n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(R(s,"idle"),this.emitSyncStatus(),F(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let t=2166136261,s=5381;for(let i=0;i<e.length;i+=1){const n=e.charCodeAt(i);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&B(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey),n=i!==void 0&&k(i,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),n}roomSendsAdmitted(e){const t=this.getConnection(e);return t?.wsState==="open"&&t.retired!==!0&&t.identityConfirmed===!0&&t.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(const t of this.roomFlushes.get(f(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0,t.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const i of t){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);const n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);const n=t??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(const[o,c]of i)a.set(o,c)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(const e of this.roomIdentityResets)e()}reconnectCold(){for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,R(e,"idle"),e.valueReceived=!1,U(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Ie(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)});for(const e of this.supplementaryBounces)e()}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=f(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const i=(async()=>{await(s??Promise.resolve());const{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&B(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,i),await i,this.offlineFlushes.get(t)===i&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}snapshotAnswer(e){const t=ke(e),s=t&&this.subscriptions.get(T.key(t.functionPath,t.args,t.shardKey));if(s!==void 0)return this.awaitingAnswer.has(s)?"awaiting":this.answeredUnreadable.has(s)?"unreadable":void 0}holdWhileUnanswered(e){const t=ke(e);if(e===void 0||t===void 0)return e;const s=()=>this.snapshotAnswer(e)!==void 0||e();return kt(s,t),s}awaitLeaderAnswers(){for(const e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*ve))}settleAwaitedAnswer(e,t){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),t&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(t||this.answeredUnreadable.add(e),this.answerHeldShards.delete(f(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,t){const s=t.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return s===-1?t:(this.offlineQueue.requeue(t.slice(s)),this.answerHeldShards.add(e),t.slice(0,s))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const h of s){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",u)}const i=f(e),n=this.holdUndecidedWrites(i,this.offlineQueue.drain(h=>f(h.shardKey)===i));if(n.length===0)return;const a=[],o=[];for(const h of n){const u=this.replayGateVerdict(h);u==="send"?a.push(h):u==="hold"&&o.push(h)}if(this.offlineQueue.requeue(o),o.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(a);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let h=0;h<c.length;h+=J){const u=c.slice(h,h+J),l=await this.replayBatched(u,e,t);if(d.push(...l.requeue),l.stop||l.requeue.length>0){d.push(...c.slice(h+J));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=f(e),s=this.replayRetryState.get(t),i=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:i,delayMs:Math.max(s?.delayMs??0,ie(i))})}noteReplayRetryDelay(e,t,s){const i=f(e),n=this.replayRetryState.get(i),a=(n?.attempts??0)+1,o=$i(t,a)??(s===null&&j(t)?ie(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:o===void 0?n?.delayMs:Math.max(n?.delayMs??0,o)})}scheduleRateLimitedRetry(e){const t=f(e),s=this.replayRetryState.get(t),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const n=this.replayRetryTimers.get(t);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{O(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.identityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,t)||Oe(e)}noteReplayAuthRefusal(e,t){if(!j(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...Z(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}spendsLastReplayAttempt(e,t){if(e.id===void 0)return!1;const s=t?.code;if(e.ambiguousSend!==!0||j(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||!Oe(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=at}keepUnexhaustedAmbiguousWrites(e,t){return e.filter(s=>s.ambiguousSend===!0&&this.spendsLastReplayAttempt(s,t)?(this.settleReplayTerminal(s,t),!1):!0)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const n=e[i];if(!n)continue;let a;try{const o=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:s,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Z(n.identity,s),mutationId:n.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(n,o,a)}catch(o){if(q(o)){this.settleReplayUndecodable(n,o,a);continue}if(!this.shouldRequeueReplayFailure(o,s)||this.spendsLastReplayAttempt(n,o)){this.settleReplayTerminal(n,o);continue}this.noteReplayRetryDelay(t,o,s),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const i=JSON.stringify({calls:e.map((d,h)=>({args:O(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&zi(i)>Vi)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:n}=this;let a,o;try{({payload:o,response:a}=await Q(this.rpcTimeoutMs,void 0,async d=>{const h=await n(_(this.url,Y),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...Z(e.find(u=>u.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(h.status===413&&e.length>1)return{payload:void 0,response:h};try{return{payload:await h.json(),response:h}}catch{return{payload:void 0,response:h}}}))}catch(d){return this.noteReplayRetryDelay(t,d,s),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}const c=a.headers.get("x-d1-bookmark");if(c&&this.bookmark.set(c),a.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);if(!o)return this.settleWholeBatchError(e,x(a.status,a.statusText,a.headers),t,s);if(!Array.isArray(o.results)){const d=G(o),h=d===void 0?x(a.status,a.statusText,a.headers):ye(d,a.headers);return this.settleWholeBatchError(e,h,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s,a.headers),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof W||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,t),stop:!0};for(const n of e)this.settleReplayTerminal(n,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),t,s);if(n.stop||n.requeue.length>0)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};const a=await this.replayBatched(e.slice(i),t,s);return{requeue:[...n.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,t,s,i,n){const a=Ji(t),o=[];let c=!1,d=!1;for(const[h,u]of e.entries()){const l=Yi(a.get(h),n);switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(u,l.value,l.commitCursor);break}case"errored":{d||=j(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(u,l.error)?(this.noteReplayRetryDelay(s,l.error,i),o.push(u)):this.settleReplayTerminal(u,l.error);break}case"unanswered":{const p=A(Je(),n);if(this.spendsLastReplayAttempt(u,p)){this.settleReplayTerminal(u,p);break}this.noteReplayRetryDelay(s,p,i),o.push(u);break}default:c=!0,this.settleReplayUndecodable(u,l.error,l.commitCursor)}}return c&&!d&&this.noteCredentialAccepted(i),o}}export{Be as LunoraClient};
@@ -1 +1 @@
1
- import{assertMaxEntries as y}from"./createInMemoryQueryCache-B5wX-gTy.mjs";import{s as u}from"./single-blob-store-DpqSxsgi.mjs";const w="lunora:query-cache",d=50,E=s=>{const n=y(s.maxEntries??d,"createAsyncStorageQueryCache"),r=u(s.storage,s.key??w),c=async()=>{const e=await r.read();return typeof e=="object"&&e!==null&&!Array.isArray(e)?new Map(Object.entries(e)):new Map},o=e=>r.write(Object.fromEntries(e)),i=e=>{if(e.size<=n)return;const a=[...e.values()].toSorted((t,l)=>t.ts-l.ts);for(const t of a){if(e.size<=n)break;e.delete(t.key)}};return{clear:r.clear,load:()=>r.serialize(async()=>[...(await c()).values()]),put:(e,a)=>r.serialize(async()=>{const t=await c();t.set(e,{...a,key:e}),i(t),await o(t)}),remove:e=>r.serialize(async()=>{const a=await c();a.delete(e)&&await o(a)})}};export{E as createAsyncStorageQueryCache};
1
+ import{assertMaxEntries as y}from"./createInMemoryQueryCache-DR6AorA2.mjs";import{s as u}from"./single-blob-store-DpqSxsgi.mjs";const w="lunora:query-cache",d=50,E=s=>{const n=y(s.maxEntries??d,"createAsyncStorageQueryCache"),r=u(s.storage,s.key??w),c=async()=>{const e=await r.read();return typeof e=="object"&&e!==null&&!Array.isArray(e)?new Map(Object.entries(e)):new Map},o=e=>r.write(Object.fromEntries(e)),i=e=>{if(e.size<=n)return;const a=[...e.values()].toSorted((t,l)=>t.ts-l.ts);for(const t of a){if(e.size<=n)break;e.delete(t.key)}};return{clear:r.clear,load:()=>r.serialize(async()=>[...(await c()).values()]),put:(e,a)=>r.serialize(async()=>{const t=await c();t.set(e,{...a,key:e}),i(t),await o(t)}),remove:e=>r.serialize(async()=>{const a=await c();a.delete(e)&&await o(a)})}};export{E as createAsyncStorageQueryCache};
@@ -1 +1 @@
1
- import{LunoraError as u}from"@lunora/errors";import{p as s,c as f,a as y}from"./idb-utility-BS7xvou1.mjs";const x=()=>{const r=new Map,t=e=>({...e,args:{...e.args}});return{append:e=>(r.set(e.id,t(e)),Promise.resolve()),clear:()=>(r.clear(),Promise.resolve()),load:()=>Promise.resolve([...r.values()].map(e=>t(e))),remove:e=>(r.delete(e),Promise.resolve()),replace:e=>(r.has(e.id)&&r.set(e.id,t(e)),Promise.resolve())}},m="lunora-outbox",p="offline-mutations",d="by_id",w=(r={})=>{const t=r.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!t)throw new u("INTERNAL","createIndexedDbPersistence: no IndexedDB available — pass `indexedDB` or use createInMemoryPersistence()");const e=r.databaseName??m,c=r.storeName??p,l=y(t,e,1,a=>{a.objectStoreNames.contains(c)||a.createObjectStore(c,{autoIncrement:!0}).createIndex(d,"id",{unique:!0})}),o=f(l,c);return{append:async a=>{await o("readwrite",n=>s(n.add(a)))},clear:async()=>{await o("readwrite",a=>s(a.clear()))},load:async()=>o("readonly",a=>s(a.getAll())),remove:async a=>{await o("readwrite",async n=>{const i=await s(n.index(d).getKey(a));i!==void 0&&await s(n.delete(i))})},replace:async a=>{await o("readwrite",async n=>{const i=await s(n.index(d).getKey(a.id));i!==void 0&&await s(n.put(a,i))})}}},b=(r,t=!0)=>{if(r!==!1){if(r)return r;if(!(!t||typeof indexedDB>"u"))return w()}};export{x as createInMemoryPersistence,w as createIndexedDbPersistence,b as resolvePersistenceAdapter};
1
+ import{LunoraError as u}from"@lunora/errors";import{c as f,p as s,a as y}from"./idb-utility-BS7xvou1.mjs";const x=()=>{const r=new Map,t=e=>({...e,args:{...e.args}});return{append:e=>(r.set(e.id,t(e)),Promise.resolve()),clear:()=>(r.clear(),Promise.resolve()),load:()=>Promise.resolve([...r.values()].map(e=>t(e))),remove:e=>(r.delete(e),Promise.resolve()),replace:e=>(r.has(e.id)&&r.set(e.id,t(e)),Promise.resolve())}},m="lunora-outbox",p="offline-mutations",d="by_id",w=(r={})=>{const t=r.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!t)throw new u("INTERNAL","createIndexedDbPersistence: no IndexedDB available — pass `indexedDB` or use createInMemoryPersistence()");const e=r.databaseName??m,c=r.storeName??p,l=y(t,e,1,a=>{a.objectStoreNames.contains(c)||a.createObjectStore(c,{autoIncrement:!0}).createIndex(d,"id",{unique:!0})}),o=f(l,c);return{append:async a=>{await o("readwrite",n=>s(n.add(a)))},clear:async()=>{await o("readwrite",a=>s(a.clear()))},load:async()=>o("readonly",a=>s(a.getAll())),remove:async a=>{await o("readwrite",async n=>{const i=await s(n.index(d).getKey(a));i!==void 0&&await s(n.delete(i))})},replace:async a=>{await o("readwrite",async n=>{const i=await s(n.index(d).getKey(a.id));i!==void 0&&await s(n.put(a,i))})}}},b=(r,t=!0)=>{if(r!==!1){if(r)return r;if(!(!t||typeof indexedDB>"u"))return w()}};export{x as createInMemoryPersistence,w as createIndexedDbPersistence,b as resolvePersistenceAdapter};
@@ -1 +1 @@
1
- import{LunoraError as v}from"@lunora/errors";import{p as u,c as h,a as I}from"./idb-utility-BS7xvou1.mjs";const T=(e,o,a)=>`${e}::${o}::${a??""}`,w=500,E=(e,o)=>{if(!Number.isInteger(e)||e<1)throw new v("INTERNAL",`${o}: maxEntries must be a positive integer, got ${String(e)}`);return e},B=(e={})=>{const o=E(e.maxEntries??w,"createInMemoryQueryCache"),a=new Map,s=r=>({...r,value:structuredClone(r.value)}),l=()=>{if(a.size<=o)return;const r=[...a.values()].toSorted((n,y)=>n.ts-y.ts);for(const n of r){if(a.size<=o)break;a.delete(n.key)}};return{clear:()=>(a.clear(),Promise.resolve()),load:()=>Promise.resolve([...a.values()].map(r=>s(r))),put:(r,n)=>(a.set(r,s({...n,key:r})),l(),Promise.resolve()),remove:r=>(a.delete(r),Promise.resolve())}},A="lunora-query-cache",b="query-cache",f="by_ts",p=1,N=(e={})=>{const o=e.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!o)throw new v("INTERNAL","createIndexedDbQueryCache: no IndexedDB available — pass `indexedDB` or use createInMemoryQueryCache()");const a=e.databaseName??A,s=e.storeName??b,l=E(e.maxEntries??w,"createIndexedDbQueryCache"),r=I(o,a,p,t=>{t.objectStoreNames.contains(s)||t.createObjectStore(s,{keyPath:"key"}).createIndex(f,"ts",{unique:!1})}),n=h(r,s),y=async t=>{let c=await u(t.count())-l;c<=0||await new Promise((D,x)=>{const d=t.index(f).openCursor();d.addEventListener("success",()=>{const m=d.result;if(!m||c<=0){D();return}m.delete(),c-=1,m.continue()}),d.addEventListener("error",()=>{x(d.error??new Error("IndexedDB eviction failed"))})})};return{clear:async()=>{await n("readwrite",t=>u(t.clear()))},load:async()=>n("readonly",t=>u(t.getAll())),put:async(t,i)=>{await n("readwrite",async c=>{await u(c.put({...i,key:t})),await y(c)})},remove:async t=>{await n("readwrite",i=>u(i.delete(t)))}}},L=e=>{if(e!==!1){if(e)return e;if(!(typeof indexedDB>"u"))return N()}};export{E as assertMaxEntries,B as createInMemoryQueryCache,N as createIndexedDbQueryCache,T as queryCacheKey,L as resolveQueryCacheAdapter};
1
+ import{LunoraError as v}from"@lunora/errors";import{c as h,p as u,a as I}from"./idb-utility-BS7xvou1.mjs";const T=(e,o,a)=>`${e}::${o}::${a??""}`,w=500,E=(e,o)=>{if(!Number.isInteger(e)||e<1)throw new v("INTERNAL",`${o}: maxEntries must be a positive integer, got ${String(e)}`);return e},B=(e={})=>{const o=E(e.maxEntries??w,"createInMemoryQueryCache"),a=new Map,s=r=>({...r,value:structuredClone(r.value)}),l=()=>{if(a.size<=o)return;const r=[...a.values()].toSorted((n,y)=>n.ts-y.ts);for(const n of r){if(a.size<=o)break;a.delete(n.key)}};return{clear:()=>(a.clear(),Promise.resolve()),load:()=>Promise.resolve([...a.values()].map(r=>s(r))),put:(r,n)=>(a.set(r,s({...n,key:r})),l(),Promise.resolve()),remove:r=>(a.delete(r),Promise.resolve())}},A="lunora-query-cache",b="query-cache",f="by_ts",p=1,N=(e={})=>{const o=e.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!o)throw new v("INTERNAL","createIndexedDbQueryCache: no IndexedDB available — pass `indexedDB` or use createInMemoryQueryCache()");const a=e.databaseName??A,s=e.storeName??b,l=E(e.maxEntries??w,"createIndexedDbQueryCache"),r=I(o,a,p,t=>{t.objectStoreNames.contains(s)||t.createObjectStore(s,{keyPath:"key"}).createIndex(f,"ts",{unique:!1})}),n=h(r,s),y=async t=>{let c=await u(t.count())-l;c<=0||await new Promise((D,x)=>{const d=t.index(f).openCursor();d.addEventListener("success",()=>{const m=d.result;if(!m||c<=0){D();return}m.delete(),c-=1,m.continue()}),d.addEventListener("error",()=>{x(d.error??new Error("IndexedDB eviction failed"))})})};return{clear:async()=>{await n("readwrite",t=>u(t.clear()))},load:async()=>n("readonly",t=>u(t.getAll())),put:async(t,i)=>{await n("readwrite",async c=>{await u(c.put({...i,key:t})),await y(c)})},remove:async t=>{await n("readwrite",i=>u(i.delete(t)))}}},L=e=>{if(e!==!1){if(e)return e;if(!(typeof indexedDB>"u"))return N()}};export{E as assertMaxEntries,B as createInMemoryQueryCache,N as createIndexedDbQueryCache,T as queryCacheKey,L as resolveQueryCacheAdapter};
@@ -1 +1 @@
1
- import{LunoraClient as r}from"./LunoraClient-C-auNTDs.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
1
+ import{LunoraClient as r}from"./LunoraClient-WCMV2kam.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
@@ -0,0 +1 @@
1
+ import{stableWireKey as a}from"@lunora/wire";const s=(e,r,y)=>["lunora",e,r,y??null],n=(e,r,y)=>s(e.__lunoraRef,a(r),y),t=(e,r,y,u={})=>{const o=y??{};return{queryFn:()=>e.query(r,o,{shardKey:u.shardKey}),queryKey:n(r,o,u.shardKey),staleTime:Number.POSITIVE_INFINITY}};export{n as lunoraQueryKey,s as lunoraQueryKeyFromArgsKey,t as lunoraQueryOptions};
@@ -1,4 +1,5 @@
1
- import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-ChRS_d1s.mjs";
1
+ import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
2
+ import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-ChRS_d1s.mjs";
2
3
  export type {
3
4
  /**
4
5
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -9,11 +10,62 @@ export type {
9
10
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
10
11
  * framework — each adapter supplies thin sinks that write into its own ref /
11
12
  * store / signal / cache.
13
+ *
14
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
15
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
16
+ * the same way.
12
17
  */
13
18
  b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-ChRS_d1s.mjs";
14
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
15
19
  import '@lunora/errors';
16
20
  import '@lunora/runtime';
21
+ /**
22
+ * The TanStack Query cache-key contract for Lunora queries. It lives here, not
23
+ * in an adapter, because every TanStack binding (React, Vue, Solid, Svelte,
24
+ * Angular Query) hashes keys the same way, and a value prefetched through one
25
+ * entry point must land under the exact key a hook reads back.
26
+ *
27
+ * Typed as `ReadonlyArray<unknown>` — TanStack v5's default `QueryKey` — so this
28
+ * module needs no TanStack dependency.
29
+ */
30
+ type LunoraQueryKey = ReadonlyArray<unknown>;
31
+ /**
32
+ * Project a Lunora `(fn, args, shardKey)` triple into the query key TanStack
33
+ * hashes for dedup. The `"lunora"` literal namespaces our entries so an app's
34
+ * own queries can't collide with ours.
35
+ *
36
+ * `args` sits in the key already encoded by `stableWireKey`, not as the raw
37
+ * object. TanStack hashes keys with `JSON.stringify`, which maps `NaN` to
38
+ * `null`, `-0` to `0` and a `Date` to its ISO string (so distinct args shared
39
+ * one cache entry and served each other's rows) and throws on a `bigint`. A
40
+ * string slot hashes the same under any hash function, so every QueryClient
41
+ * agrees on it without configuration.
42
+ */
43
+ declare const lunoraQueryKeyFromArgsKey: (ref: string, argsKey: string, shardKey: string | undefined) => LunoraQueryKey;
44
+ declare const lunoraQueryKey: (function_: FunctionReference, args: Record<string, unknown>, shardKey: string | undefined) => LunoraQueryKey;
45
+ /** Shape returned by `lunoraQueryOptions`, spread into a TanStack hook. */
46
+ interface LunoraQueryOptions<F extends FunctionReference> {
47
+ queryFn: () => Promise<ReturnOf<F>>;
48
+ queryKey: LunoraQueryKey;
49
+ staleTime: number;
50
+ }
51
+ /**
52
+ * Build a TanStack Query options object for a Lunora query, keyed identically
53
+ * to the adapters' first-class hooks (see `lunoraQueryKey`), so a value fetched
54
+ * through it shares cache identity with anything those hooks or a server-side
55
+ * `prefetchQuery` read or write for the same `(fn, args, shardKey)` triple.
56
+ *
57
+ * ```ts
58
+ * const { data } = useSuspenseQuery(lunoraQueryOptions(client, api.posts.list, {}));
59
+ * ```
60
+ *
61
+ * This is a one-shot fetch: it resolves once and `staleTime` is infinite, so
62
+ * TanStack never refetches on its own. It opens no WebSocket and has no
63
+ * framework or browser dependency, so it is safe on either side of an RSC
64
+ * boundary — the transport is the `LunoraClient` passed in.
65
+ */
66
+ declare const lunoraQueryOptions: <F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: {
67
+ shardKey?: string;
68
+ }) => LunoraQueryOptions<F>;
17
69
  /**
18
70
  * The sentinel a framework adapter resolves its reactive args to when it wants
19
71
  * to short-circuit a query — no network call, no socket.
@@ -82,6 +134,10 @@ export {
82
134
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
83
135
  * framework — each adapter supplies thin sinks that write into its own ref /
84
136
  * store / signal / cache.
137
+ *
138
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
139
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
140
+ * the same way.
85
141
  */
86
142
  type ArgsOf,
87
143
  /**
@@ -93,8 +149,12 @@ type ArgsOf,
93
149
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
94
150
  * framework — each adapter supplies thin sinks that write into its own ref /
95
151
  * store / signal / cache.
152
+ *
153
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
154
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
155
+ * the same way.
96
156
  */
97
- type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs,
157
+ type FunctionReference, type LunoraQueryKey, type LunoraQueryOptions, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs,
98
158
  /**
99
159
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
100
160
  * by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
@@ -104,6 +164,10 @@ type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSin
104
164
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
105
165
  * framework — each adapter supplies thin sinks that write into its own ref /
106
166
  * store / signal / cache.
167
+ *
168
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
169
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
170
+ * the same way.
107
171
  */
108
172
  type ReturnOf, SKIP,
109
173
  /**
@@ -115,6 +179,10 @@ type ReturnOf, SKIP,
115
179
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
116
180
  * framework — each adapter supplies thin sinks that write into its own ref /
117
181
  * store / signal / cache.
182
+ *
183
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
184
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
185
+ * the same way.
118
186
  */
119
187
  type SubscriptionError,
120
188
  /**
@@ -126,5 +194,9 @@ type SubscriptionError,
126
194
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
127
195
  * framework — each adapter supplies thin sinks that write into its own ref /
128
196
  * store / signal / cache.
197
+ *
198
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
199
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
200
+ * the same way.
129
201
  */
130
- type Unsubscribe, createQuerySubscription, toSubscriptionError };
202
+ type Unsubscribe, createQuerySubscription, lunoraQueryKey, lunoraQueryKeyFromArgsKey, lunoraQueryOptions, toSubscriptionError };
@@ -1,4 +1,5 @@
1
- import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-DNnOIB-r.js";
1
+ import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
2
+ import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-DNnOIB-r.js";
2
3
  export type {
3
4
  /**
4
5
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -9,11 +10,62 @@ export type {
9
10
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
10
11
  * framework — each adapter supplies thin sinks that write into its own ref /
11
12
  * store / signal / cache.
13
+ *
14
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
15
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
16
+ * the same way.
12
17
  */
13
18
  b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-DNnOIB-r.js";
14
- import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
15
19
  import '@lunora/errors';
16
20
  import '@lunora/runtime';
21
+ /**
22
+ * The TanStack Query cache-key contract for Lunora queries. It lives here, not
23
+ * in an adapter, because every TanStack binding (React, Vue, Solid, Svelte,
24
+ * Angular Query) hashes keys the same way, and a value prefetched through one
25
+ * entry point must land under the exact key a hook reads back.
26
+ *
27
+ * Typed as `ReadonlyArray<unknown>` — TanStack v5's default `QueryKey` — so this
28
+ * module needs no TanStack dependency.
29
+ */
30
+ type LunoraQueryKey = ReadonlyArray<unknown>;
31
+ /**
32
+ * Project a Lunora `(fn, args, shardKey)` triple into the query key TanStack
33
+ * hashes for dedup. The `"lunora"` literal namespaces our entries so an app's
34
+ * own queries can't collide with ours.
35
+ *
36
+ * `args` sits in the key already encoded by `stableWireKey`, not as the raw
37
+ * object. TanStack hashes keys with `JSON.stringify`, which maps `NaN` to
38
+ * `null`, `-0` to `0` and a `Date` to its ISO string (so distinct args shared
39
+ * one cache entry and served each other's rows) and throws on a `bigint`. A
40
+ * string slot hashes the same under any hash function, so every QueryClient
41
+ * agrees on it without configuration.
42
+ */
43
+ declare const lunoraQueryKeyFromArgsKey: (ref: string, argsKey: string, shardKey: string | undefined) => LunoraQueryKey;
44
+ declare const lunoraQueryKey: (function_: FunctionReference, args: Record<string, unknown>, shardKey: string | undefined) => LunoraQueryKey;
45
+ /** Shape returned by `lunoraQueryOptions`, spread into a TanStack hook. */
46
+ interface LunoraQueryOptions<F extends FunctionReference> {
47
+ queryFn: () => Promise<ReturnOf<F>>;
48
+ queryKey: LunoraQueryKey;
49
+ staleTime: number;
50
+ }
51
+ /**
52
+ * Build a TanStack Query options object for a Lunora query, keyed identically
53
+ * to the adapters' first-class hooks (see `lunoraQueryKey`), so a value fetched
54
+ * through it shares cache identity with anything those hooks or a server-side
55
+ * `prefetchQuery` read or write for the same `(fn, args, shardKey)` triple.
56
+ *
57
+ * ```ts
58
+ * const { data } = useSuspenseQuery(lunoraQueryOptions(client, api.posts.list, {}));
59
+ * ```
60
+ *
61
+ * This is a one-shot fetch: it resolves once and `staleTime` is infinite, so
62
+ * TanStack never refetches on its own. It opens no WebSocket and has no
63
+ * framework or browser dependency, so it is safe on either side of an RSC
64
+ * boundary — the transport is the `LunoraClient` passed in.
65
+ */
66
+ declare const lunoraQueryOptions: <F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: {
67
+ shardKey?: string;
68
+ }) => LunoraQueryOptions<F>;
17
69
  /**
18
70
  * The sentinel a framework adapter resolves its reactive args to when it wants
19
71
  * to short-circuit a query — no network call, no socket.
@@ -82,6 +134,10 @@ export {
82
134
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
83
135
  * framework — each adapter supplies thin sinks that write into its own ref /
84
136
  * store / signal / cache.
137
+ *
138
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
139
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
140
+ * the same way.
85
141
  */
86
142
  type ArgsOf,
87
143
  /**
@@ -93,8 +149,12 @@ type ArgsOf,
93
149
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
94
150
  * framework — each adapter supplies thin sinks that write into its own ref /
95
151
  * store / signal / cache.
152
+ *
153
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
154
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
155
+ * the same way.
96
156
  */
97
- type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs,
157
+ type FunctionReference, type LunoraQueryKey, type LunoraQueryOptions, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs,
98
158
  /**
99
159
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
100
160
  * by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
@@ -104,6 +164,10 @@ type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSin
104
164
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
105
165
  * framework — each adapter supplies thin sinks that write into its own ref /
106
166
  * store / signal / cache.
167
+ *
168
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
169
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
170
+ * the same way.
107
171
  */
108
172
  type ReturnOf, SKIP,
109
173
  /**
@@ -115,6 +179,10 @@ type ReturnOf, SKIP,
115
179
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
116
180
  * framework — each adapter supplies thin sinks that write into its own ref /
117
181
  * store / signal / cache.
182
+ *
183
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
184
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
185
+ * the same way.
118
186
  */
119
187
  type SubscriptionError,
120
188
  /**
@@ -126,5 +194,9 @@ type SubscriptionError,
126
194
  * cancellation-guarded teardown all in one place. Nothing here imports a UI
127
195
  * framework — each adapter supplies thin sinks that write into its own ref /
128
196
  * store / signal / cache.
197
+ *
198
+ * It also owns the TanStack Query key contract (`lunoraQueryKey`,
199
+ * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
200
+ * the same way.
129
201
  */
130
- type Unsubscribe, createQuerySubscription, toSubscriptionError };
202
+ type Unsubscribe, createQuerySubscription, lunoraQueryKey, lunoraQueryKeyFromArgsKey, lunoraQueryOptions, toSubscriptionError };
@@ -1 +1 @@
1
- import{SKIP as t,createQuerySubscription as e,toSubscriptionError as i}from"../packem_shared/SKIP-d7LeP-sY.mjs";export{t as SKIP,e as createQuerySubscription,i as toSubscriptionError};
1
+ import{lunoraQueryKey as e,lunoraQueryKeyFromArgsKey as u,lunoraQueryOptions as t}from"../packem_shared/lunoraQueryKey-CucWmxnx.mjs";import{SKIP as n,createQuerySubscription as i,toSubscriptionError as p}from"../packem_shared/SKIP-d7LeP-sY.mjs";export{n as SKIP,i as createQuerySubscription,e as lunoraQueryKey,u as lunoraQueryKeyFromArgsKey,t as lunoraQueryOptions,p as toSubscriptionError};
@@ -1 +1 @@
1
- import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CyFK_cv6.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-kd9cUs8g.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
1
+ import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CyFK_cv6.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-j03gPQ5w.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
package/dist/upload.d.mts CHANGED
@@ -1,3 +1,17 @@
1
+ /**
2
+ * `@lunora/client/upload` — framework-agnostic client upload core.
3
+ *
4
+ * The admin `uploadStorageObject` path on `LunoraClient` is a one-shot PUT gated
5
+ * by an `adminToken` — right for the Studio file browser, wrong for end users.
6
+ * This module gives end-user browsers progress, pause/resume, large-file
7
+ * resumable uploads and per-part retry by re-exporting `@visulima/storage-client`
8
+ * (Lunora does not hand-roll the uploader). Point {@link createUpload} at a route
9
+ * backed by `@lunora/storage/upload`'s RLS-gated handler.
10
+ *
11
+ * Framework users should prefer the hook re-exports (`@lunora/react` `useUpload`,
12
+ * `@lunora/vue`, `@lunora/solid`, `@lunora/svelte`); this vanilla core is for
13
+ * non-framework code and for the hooks to build on.
14
+ */
1
15
  import { UploadControl, HeadersResolver, UploadRestrictions, ChunkedRestAdapter, MultipartAdapter, TusAdapter } from '@visulima/storage-client';
2
16
  export { type ChunkedRestAdapter, type ChunkedRestAdapterOptions, type FingerprintFunction, type HeadersResolver, LocalStorageUrlStorage, MemoryUrlStorage, type MultipartAdapter, type MultipartAdapterOptions, type OnBeforeRequest, type RequestOptions, RestrictionError, type TusAdapter, type TusAdapterOptions, type UploadControl, UploadError, type UploadMethod, type UploadRestrictions, type UploadResult, type Uploader, type UrlStorage, createChunkedRestAdapter, createMultipartAdapter, createTusAdapter, putFile, validateFile, validateFiles } from '@visulima/storage-client';
3
17
  /** Resumable upload wire protocols {@link createUpload} can drive. */
package/dist/upload.d.ts CHANGED
@@ -1,3 +1,17 @@
1
+ /**
2
+ * `@lunora/client/upload` — framework-agnostic client upload core.
3
+ *
4
+ * The admin `uploadStorageObject` path on `LunoraClient` is a one-shot PUT gated
5
+ * by an `adminToken` — right for the Studio file browser, wrong for end users.
6
+ * This module gives end-user browsers progress, pause/resume, large-file
7
+ * resumable uploads and per-part retry by re-exporting `@visulima/storage-client`
8
+ * (Lunora does not hand-roll the uploader). Point {@link createUpload} at a route
9
+ * backed by `@lunora/storage/upload`'s RLS-gated handler.
10
+ *
11
+ * Framework users should prefer the hook re-exports (`@lunora/react` `useUpload`,
12
+ * `@lunora/vue`, `@lunora/solid`, `@lunora/svelte`); this vanilla core is for
13
+ * non-framework code and for the hooks to build on.
14
+ */
1
15
  import { UploadControl, HeadersResolver, UploadRestrictions, ChunkedRestAdapter, MultipartAdapter, TusAdapter } from '@visulima/storage-client';
2
16
  export { type ChunkedRestAdapter, type ChunkedRestAdapterOptions, type FingerprintFunction, type HeadersResolver, LocalStorageUrlStorage, MemoryUrlStorage, type MultipartAdapter, type MultipartAdapterOptions, type OnBeforeRequest, type RequestOptions, RestrictionError, type TusAdapter, type TusAdapterOptions, type UploadControl, UploadError, type UploadMethod, type UploadRestrictions, type UploadResult, type Uploader, type UrlStorage, createChunkedRestAdapter, createMultipartAdapter, createTusAdapter, putFile, validateFile, validateFiles } from '@visulima/storage-client';
3
17
  /** Resumable upload wire protocols {@link createUpload} can drive. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/client",
3
- "version": "1.0.0-alpha.253",
3
+ "version": "1.0.0-alpha.254",
4
4
  "description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
5
5
  "keywords": [
6
6
  "cloudflare",