@lunora/client 1.0.0-alpha.49 → 1.0.0-alpha.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/index.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/CONFLICT_ERROR_CODE-LjU7z0mB.mjs +1 -0
- package/dist/packem_shared/ClientServiceWorker-DXnBXeWK.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
- package/dist/packem_shared/LunoraClient-CWDiiVcr.mjs +1 -0
- package/dist/packem_shared/OfflineQueue-CoRNJFKm.mjs +1 -0
- package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
- package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
- package/dist/packem_shared/SubscriptionRegistry-D5Xu-a39.mjs +1 -0
- package/dist/packem_shared/TabCoordinator-DVKG2RlZ.mjs +1 -0
- package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
- package/dist/packem_shared/applyDelta-DGqMpi3N.mjs +1 -0
- package/dist/packem_shared/createAsyncStoragePersistence-yBu2KWAp.mjs +1 -0
- package/dist/packem_shared/{createClientQuery-CrdRoicO.mjs → createClientQuery-TKD_52cT.mjs} +1 -1
- package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
- package/dist/packem_shared/createInMemoryPersistence-BPdQiujT.mjs +1 -0
- package/dist/packem_shared/createInMemoryQueryCache-HMIq2XtS.mjs +1 -0
- package/dist/packem_shared/createLocalStore-C_UKH_Ok.mjs +1 -0
- package/dist/packem_shared/createMutationRunner-C0i1P5RS.mjs +1 -0
- package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
- package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
- package/dist/packem_shared/{createReply-DF0jRsv-.mjs → createReply-CwFABEJs.mjs} +1 -1
- package/dist/packem_shared/createServerClient-BxPCzuUt.mjs +1 -0
- package/dist/packem_shared/createSnapshotPrecondition-CP3e1HVS.mjs +1 -0
- package/dist/packem_shared/delta-merge-BoVuM-rE.mjs +1 -0
- package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
- package/dist/packem_shared/httpStream-x6q-x4yK.mjs +11 -0
- package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
- package/dist/packem_shared/local-store-BD0RFD7A.mjs +1 -0
- package/dist/packem_shared/offline-queue-BdQFXDz_.mjs +1 -0
- package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
- package/dist/packem_shared/wire-codec-D4iww4NV.mjs +1 -0
- package/dist/packem_shared/wire-key-BEmRM5ls.mjs +1 -0
- package/dist/pagination/index.mjs +1 -1
- package/dist/query/index.d.mts +69 -3
- package/dist/query/index.d.ts +69 -3
- package/dist/query/index.mjs +1 -1
- package/dist/service.mjs +1 -1
- package/dist/ssr/index.d.mts +21 -1
- package/dist/ssr/index.d.ts +21 -1
- package/dist/ssr/index.mjs +1 -1
- package/dist/upload.mjs +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs +0 -1
- package/dist/packem_shared/ClientServiceWorker-CRQ5yl7-.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs +0 -1
- package/dist/packem_shared/LunoraClient-M_ArXnWT.mjs +0 -1
- package/dist/packem_shared/OfflineQueue-D1yiY7sF.mjs +0 -1
- package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs +0 -1
- package/dist/packem_shared/SKIP-CArzT3Vl.mjs +0 -1
- package/dist/packem_shared/SubscriptionRegistry-HXgW6BXq.mjs +0 -1
- package/dist/packem_shared/TabCoordinator-CMFYQCL-.mjs +0 -1
- package/dist/packem_shared/anyApi-BD4dgvDY.mjs +0 -1
- package/dist/packem_shared/applyDelta-Dw5isoZR.mjs +0 -1
- package/dist/packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs +0 -1
- package/dist/packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs +0 -1
- package/dist/packem_shared/createInMemoryPersistence-CQYXy8UP.mjs +0 -1
- package/dist/packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs +0 -1
- package/dist/packem_shared/createLocalStore-7WO7dnOs.mjs +0 -1
- package/dist/packem_shared/createMutationRunner-lQXH8Amk.mjs +0 -1
- package/dist/packem_shared/createMutatorRunner-BVzo0FBZ.mjs +0 -1
- package/dist/packem_shared/createReconnect-CFT7YRSR.mjs +0 -1
- package/dist/packem_shared/createServerClient-BywwAr17.mjs +0 -1
- package/dist/packem_shared/createSnapshotPrecondition-A10yhOpq.mjs +0 -1
- package/dist/packem_shared/delta-merge-DoT5IpTP.mjs +0 -1
- package/dist/packem_shared/getServerSession-CGjgRBAE.mjs +0 -1
- package/dist/packem_shared/httpStream-Cz4_QyjV.mjs +0 -11
- package/dist/packem_shared/idb-utility-C-DR8nG1.mjs +0 -1
- package/dist/packem_shared/local-store-CGsgaEph.mjs +0 -1
- package/dist/packem_shared/offline-queue-CKMw-5rF.mjs +0 -1
- package/dist/packem_shared/preloadQuery-DjwSjFwt.mjs +0 -1
- package/dist/packem_shared/wire-codec-aTWt2XiW.mjs +0 -1
- package/dist/packem_shared/wire-key-Cb-kXfSh.mjs +0 -1
package/dist/auth/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const f=new WeakMap,a=r=>{const t=new Set;let s=null,u=!1;const c=()=>{for(const e of t)e()};let n=0;const o=e=>{s!==e&&(s=e,c())},l=()=>{n+=1;const e=n;if(r.getAuthToken()===null){o(null);return}r.getCurrentUser().then(i=>{e===n&&o(i)}).catch(()=>{e===n&&o(null)})};return r.onAuthTokenChange(l),{getUser:()=>s,subscribe:e=>(t.add(e),u||(u=!0,l()),()=>{t.delete(e)})}},d=r=>{let t=f.get(r);return t||(t=a(r),f.set(r,t)),t};export{d as getIdentityStore};
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{anyApi as o}from"./packem_shared/anyApi-
|
|
1
|
+
import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as n,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as i}from"./packem_shared/createAsyncStoragePersistence-yBu2KWAp.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createClientQuery as s}from"./packem_shared/createClientQuery-TKD_52cT.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-DVKG2RlZ.mjs";import{a as y,i as R}from"./packem_shared/delta-merge-BoVuM-rE.mjs";import{CONFLICT_ERROR_CODE as C,getErrorCode as S,getRetryAfterMs as A,isConflictError as D,isForbiddenError as M,isRateLimitedError as _,isUnauthorizedError as I}from"./packem_shared/CONFLICT_ERROR_CODE-LjU7z0mB.mjs";import{httpStream as h}from"./packem_shared/httpStream-x6q-x4yK.mjs";import{c as L}from"./packem_shared/local-store-BD0RFD7A.mjs";import{LunoraClient as T}from"./packem_shared/LunoraClient-CWDiiVcr.mjs";import{createMutationRunner as g}from"./packem_shared/createMutationRunner-C0i1P5RS.mjs";import{createMutatorRunner as U}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as B}from"./packem_shared/offline-queue-BdQFXDz_.mjs";import{createInMemoryPersistence as N,createIndexedDbPersistence as v}from"./packem_shared/createInMemoryPersistence-BPdQiujT.mjs";import{preloadQuery as z,preloadedQueryResult as K}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as W,createIndexedDbQueryCache as X,queryCacheKey as j}from"./packem_shared/createInMemoryQueryCache-HMIq2XtS.mjs";import{createReconnect as H}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as Y}from"./packem_shared/createSnapshotPrecondition-CP3e1HVS.mjs";import{DEFAULT_MAX_BUFFER as $,createStream as ee}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as oe}from"./packem_shared/SubscriptionRegistry-D5Xu-a39.mjs";import{ClientServiceWorker as ae}from"./packem_shared/ClientServiceWorker-DXnBXeWK.mjs";import{createReply as pe,sendToSw as ce}from"./packem_shared/createReply-CwFABEJs.mjs";export{C as CONFLICT_ERROR_CODE,ae as ClientServiceWorker,$ as DEFAULT_MAX_BUFFER,T as LunoraClient,B as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,oe as SubscriptionRegistry,d as TabCoordinator,o as anyApi,y as applyDelta,i as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,N as createInMemoryPersistence,W as createInMemoryQueryCache,v as createIndexedDbPersistence,X as createIndexedDbQueryCache,L as createLocalStore,g as createMutationRunner,U as createMutatorRunner,H as createReconnect,pe as createReply,Y as createSnapshotPrecondition,ee as createStream,S as getErrorCode,A as getRetryAfterMs,h as httpStream,D as isConflictError,M as isForbiddenError,R as isMutationDelta,_ as isRateLimitedError,I as isUnauthorizedError,n as maxSeq,z as preloadQuery,K as preloadedQueryResult,j as queryCacheKey,p as reconcileOptimistic,ce as sendToSw};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=["BAD_REQUEST","CONFLICT","COUNT_RLS_UNSUPPORTED","FORBIDDEN","INTERNAL_SERVER_ERROR","MASK_UNSUPPORTED","NOT_FOUND","NOT_IMPLEMENTED","RELATION_PREDICATE_UNSUPPORTED","TOO_MANY_REQUESTS","UNAUTHORIZED","UNPROCESSABLE"],r=new Set(t),R="CONFLICT",n=E=>E instanceof Error&&E.code===R,O=E=>E instanceof Error&&E.code==="FORBIDDEN",e=E=>E instanceof Error&&E.code==="UNAUTHORIZED",s=E=>E instanceof Error&&E.code==="TOO_MANY_REQUESTS",N=E=>{if(!(E instanceof Error))return;const{code:o}=E;return typeof o=="string"&&r.has(o)?o:void 0},c=E=>{const o=E?.data?.retryAfterMs;return typeof o=="number"&&Number.isFinite(o)?o:void 0};export{R as CONFLICT_ERROR_CODE,N as getErrorCode,c as getRetryAfterMs,n as isConflictError,O as isForbiddenError,s as isRateLimitedError,e as isUnauthorizedError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class r{swUrl;scope;#e=void 0;#r="unregistered";#i;#s=new Set;constructor(e){this.swUrl=e.swUrl,this.scope=e.scope??"/",this.#i=e.onStatusChange}get status(){return this.#r}get registration(){return this.#e}get active(){return this.#e?.active!==null&&this.#e?.active!==void 0}async register(){if(!("serviceWorker"in navigator))return this.#t("unsupported"),!1;this.#t("registering");try{this.#e=await navigator.serviceWorker.register(this.swUrl,{scope:this.scope}),this.#t("active"),navigator.serviceWorker.addEventListener("message",this.#a)}catch{return this.#t("error"),!1}return!0}async unregister(){if(!this.#e)return!1;navigator.serviceWorker.removeEventListener("message",this.#a);const e=await this.#e.unregister();return this.#e=void 0,this.#t("unregistered"),e}postMessage(e){const t=this.#e?.active;t&&t.postMessage(e)}onMessage(e){return this.#s.add(e),()=>{this.#s.delete(e)}}#t(e){this.#r=e,this.#i?.(e)}#a=e=>{for(const t of this.#s)try{t(e)}catch{}}}export{r as ClientServiceWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";const m=1024,p=f=>{const i=f.maxBuffer??m,r=[],o=[];let n=!1,t,l=!1;const u=()=>{const e=o.shift();if(!e)return!1;if(t)return e.reject(t),!0;if(r.length>0){const s=r.shift();return e.resolve({done:!1,value:s}),!0}return n?(e.resolve({done:!0,value:void 0}),!0):(o.unshift(e),!1)},a={complete(){if(!(n||t))for(n=!0;u(););},fail(e){if(!(n||t))for(t=e,r.length=0;u(););},push(e){if(!(n||t||l)){if(r.length>=i){a.fail(new h("STREAM_BACKPRESSURE",`stream buffer overflow (max=${i.toString()}); the consumer cannot keep up with the producer`));return}r.push(e),u()}}},c=()=>{if(!l){l=!0,n=!0,r.length=0;try{f.onCancel()}catch{}for(;u(););}};return{handle:a,iterable:{cancel:c,[Symbol.asyncIterator](){return{next(){if(t)return Promise.reject(t);if(r.length>0){const e=r.shift();return Promise.resolve({done:!1,value:e})}return n?Promise.resolve({done:!0,value:void 0}):new Promise((e,s)=>{o.push({reject:s,resolve:e})})},return(){return c(),Promise.resolve({done:!0,value:void 0})}}}}}};export{m as DEFAULT_MAX_BUFFER,p as createStream};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{i as z,a as V,P as j}from"./delta-merge-BoVuM-rE.mjs";import{d as b,e as D}from"./wire-codec-D4iww4NV.mjs";import{s as E}from"./wire-key-BEmRM5ls.mjs";import J from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as Y}from"./createClientQuery-TKD_52cT.mjs";import{TabCoordinator as X}from"./TabCoordinator-DVKG2RlZ.mjs";import{httpStream as Z}from"./httpStream-x6q-x4yK.mjs";import{d as P,n as R,f as H,a as ee,c as te}from"./local-store-BD0RFD7A.mjs";import{O as se,n as N,i as re,r as ne}from"./offline-queue-BdQFXDz_.mjs";import{resolvePersistenceAdapter as ie}from"./createInMemoryPersistence-BPdQiujT.mjs";import{resolveQueryCacheAdapter as ae,queryCacheKey as F}from"./createInMemoryQueryCache-HMIq2XtS.mjs";import{createReconnect as K}from"./createReconnect-CjTmjJDH.mjs";import{createStream as oe}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as g}from"./SubscriptionRegistry-D5Xu-a39.mjs";const L=500,ce=(h,e)=>{if(h.size<e)return;const t=h.keys().next().value;t!==void 0&&h.delete(t)};class C{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const he="/_lunora/rpc",B="/_lunora/rpc-batch",de="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,A=h=>{for(let e=h.length-1;e>=0;e-=1)h[e]?.()},ue=(h,e)=>{for(const t of e)t.op==="delete"?h.delete(t.key):t.value!==void 0&&h.set(t.key,t.value)},le="lunora-ping",fe=3e4,me=1e4,pe=250,ye=64,Se="/_lunora/admin/shard-traffic",be="/_lunora/admin/scheduled",Te="/_lunora/admin/scheduled/status",ke="/_lunora/admin/scheduled/ws",ve="/_lunora/admin/scheduled/cancel",ge="/_lunora/admin/scheduled/dead",Ce="/_lunora/admin/scheduled/dead/retry",_e="/_lunora/admin/scheduled/dead/cancel",we="/_lunora/admin/workflows/instances",Ee="/_lunora/admin/workflows/instance",Ae="/_lunora/admin/workflows/status",U="/_lunora/admin/storage",Ie="/_lunora/admin/storage/url",Oe="/_lunora/admin/storage/buckets",Pe="/_lunora/admin/functions",Re="/_lunora/admin/cron-jobs",He="/_lunora/admin/cron-jobs/run",Fe="/_lunora/admin/openapi",Le="/_lunora/admin/openrpc",Me="/_lunora/admin/global/tables",Ue="/_lunora/admin/global/table",xe="/_lunora/admin/global/facet",Ne="/_lunora/admin/vector/indexes",Ke="/_lunora/admin/vector/query",Be="/_lunora/admin/logs/archive",We="/_lunora/admin/kv/namespaces",qe="/_lunora/admin/kv/keys",x="/_lunora/admin/kv/value",De="/_lunora/admin/auth/users",$e="/_lunora/admin/auth/sessions",Qe="/_lunora/admin/auth/users/create",Ge="/_lunora/admin/auth/users/role",ze="/_lunora/admin/auth/users/ban",Ve="/_lunora/admin/auth/users/unban",je="/_lunora/admin/auth/users/password",Je="/_lunora/admin/auth/users/remove",Ye="/_lunora/admin/auth/users/impersonate",Xe="/_lunora/admin/auth/sessions/revoke",Ze="/_lunora/admin/auth/sessions/revoke-all",et="/_lunora/admin/auth/capabilities",tt="/_lunora/admin/auth/users/update",st="/_lunora/admin/auth/accounts",rt="/_lunora/admin/auth/accounts/unlink",nt="/_lunora/admin/auth/passkeys",it="/_lunora/admin/auth/passkeys/delete",at="/_lunora/admin/auth/two-factor/disable",ot="/_lunora/admin/auth/organizations",ct="/_lunora/admin/auth/organizations/members",ht="/_lunora/admin/auth/organizations/invitations",dt="/_lunora/admin/auth/organizations/members/remove",ut="/_lunora/admin/auth/organizations/invitations/cancel",lt="/_lunora/admin/auth/config",ft="/_lunora/admin/auth/organizations/create",mt="/_lunora/admin/auth/organizations/update",pt="/_lunora/admin/auth/organizations/remove",yt="/_lunora/admin/auth/organizations/members/add",St="/_lunora/admin/auth/organizations/members/invite",bt="/_lunora/admin/auth/organizations/members/role",Tt="/_lunora/admin/auth/organizations/teams",kt="/_lunora/admin/auth/organizations/teams/create",vt="/_lunora/admin/auth/organizations/teams/update",gt="/_lunora/admin/auth/organizations/teams/remove",Ct="/_lunora/admin/auth/organizations/teams/members",_t="/_lunora/admin/auth/organizations/teams/members/add",wt="/_lunora/admin/auth/organizations/teams/members/remove",Et="/_lunora/admin/auth/organizations/roles",At="/_lunora/admin/auth/organizations/roles/create",It="/_lunora/admin/auth/organizations/roles/update",Ot="/_lunora/admin/auth/organizations/roles/remove",Pt="/api/auth",Rt="/get-session",W=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,k=(h,e)=>`${h.endsWith("/")?h.slice(0,-1):h}${e}`,y=(h,e)=>{const t=new URLSearchParams;for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(r,String(n));const s=t.toString();return s===""?h:`${h}?${s}`},Ht=[j],m=h=>h??"",$=(h,e)=>{const t=h.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??e}},Ft=h=>{const{code:e,messageText:t}=$(h,"stream error");return e===void 0?new Error(t):new f(e,t)},q=h=>{const{code:e,messageText:t}=$(h,"subscription error");return{message:t,...e===void 0?{}:{code:e}}},I=(h,e)=>{for(const t of h)try{t(e)}catch{}},Lt=new TextDecoder,Mt=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Lt.decode(h)},S=(h,e)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(e)),!0}catch{return!1}},_=h=>{const e=new Error(h.message??"request failed");return e.code=h.code,h.data!==void 0&&(e.data=b(h.data)),h.hint!==void 0&&(e.hint=h.hint),h.docsUrl!==void 0&&(e.docsUrl=h.docsUrl),e},v=(h,e)=>{try{return D(h)}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)}},Ut=(h,e)=>{const t=Array.from({length:e});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r&&"error"in r&&r.error?{error:_(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},xt=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Nt=Promise.resolve();class Q{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new g;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??k(W(e.url),de),this.wsToken=e.wsToken;const t=e.authBasePath??Pt;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??J(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??fe,this.connectTimeoutMs=e.connectTimeoutMs??me,this.defaultConnectionContext=e.connectionContext,this.persistence=ie(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=ae(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Y,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=Nt),this.offlineQueue=new se(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${N()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint();this.authToken=e,t!==void 0&&(this.authSubject=t);const n=this.identityFingerprint();if(n!==r&&(s?this.rejectQueuedForIdentityChange():(this.restampQueuedIdentity(r,n),this.restampWatermarks(r,n)),this.tabCoordinator)){const i=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),i&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new f("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const n=s?.shardKey??"",i=this.identityFingerprint();let a;const o=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:d=>{a=d}});if(a!==void 0&&a>(this.clientWatermarks.get(i??"")?.get(n)??0)){let d=this.clientWatermarks.get(i??"");d===void 0&&(d=new Map,this.clientWatermarks.set(i??"",d)),d.set(n,a)}return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{const t=await this.fetchImpl(k(this.url,`${this.authBasePath}${Rt}`),{credentials:"include",headers:e,method:"GET"});return t.ok?(await t.json())?.user??null:null}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(const t of this.connections.values())if(t.socket)try{t.socket.close()}catch{}}}setConnectionContext(e,t={}){const s=m(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,t={}){const s=m(t.shardKey),r={context:e},n=this.connectionContextHolders.get(s);n?n.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let i=!1;return()=>{if(i)return;i=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,t,s={}){const r=m(s.shardKey);let n=this.whisperHandlers.get(r);n||(n=new Map,this.whisperHandlers.set(r,n));let i=n.get(e);const a=i===void 0;if(i||(i=new Set,n.set(e,i)),i.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&S(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(e);if(!c?.delete(t)||c.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&S(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,t,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&S(r,{data:v(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const i=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:i?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const r=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())r.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,i)=>(n.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:r.toSorted((n,i)=>n.functionPath.localeCompare(i.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){const r=this.peekActiveQueryValue(e.__lunoraRef,t,s),n=r===void 0?void 0:E(r);return()=>{const i=this.peekActiveQueryValue(e.__lunoraRef,t,s);return n===void 0&&i===void 0?!0:n===void 0||i===void 0?!1:E(i)===n}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=E(t),n=F(e,r,s),i=this.hydratedQueryCache.get(n);if(i!==void 0)return i.identity===this.identityFingerprint()?i.value:void 0}peekActiveQueryValue(e,t,s){const r=g.key(e,t,s);return this.subscriptions.get(r)?.lastValue}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const t=await this.fetchImpl(k(this.url,B),{body:JSON.stringify({calls:e.map((n,i)=>({args:v(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:i,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{throw new f("INTERNAL",`LunoraClient: batch response was not JSON (status ${t.status.toString()})`)}if(!t.ok||r.error&&!r.results)throw r.error?_(r.error):new f("INTERNAL",`LunoraClient: batch request failed (status ${t.status.toString()})`);for(const n of r.results??[]){const i=n.body?.commitCursor;typeof n.id=="number"&&typeof i=="number"&&this.recordShardCursor(e[n.id]?.shardKey,i)}return Ut(r.results??[],e.length)}async mutation(e,t,s={}){this.assertOpen();const r=t,n=s.mutationId??N(),{confirms:i,rollbacks:a}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,a,i);const{hasSocket:o,wasEverConnected:c,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:u}=this.offlineQueue,l=c||u,p=this.WebSocketImpl!==void 0&&l;if(d!=="open"&&!o&&p||d==="connecting"&&l)return this.enqueueOfflineMutation(e,r,s.shardKey,n,a,i,s.precondition);try{let w;const G=await this.rpc(e.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:O=>{w=O}});for(const O of i)O(w);return G}catch(w){throw A(a),w}}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey)}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(c=>({rows:c})),i=t.length;let a=0,o=0;for(let c=0;c<i;c+=r){const d=t.slice(c,c+r),u=o;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:i})}return{chunks:o,imported:a}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(Se,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(be,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(Te,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(ve,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(ge,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ce,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(_e,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await this.adminFetch(`${we}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Ee}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Ae,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=k(W(this.url),ke),s=K(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,i=!1;const a=()=>{i||(n=setTimeout(d,s.next()))},o=u=>{if(i||this.WebSocketImpl===void 0)return;const l=u===void 0?t:`${t}?token=${encodeURIComponent(u)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:p=>{try{const T=JSON.parse(typeof p.data=="string"?p.data:"");T.type==="jobs"&&Array.isArray(T.records)&&e(T.records)}catch{}},onOpen:()=>{s.reset()}})},c=async u=>{let l;try{l=await u()}catch{a();return}o(l)},d=()=>{if(i||this.WebSocketImpl===void 0)return;const{wsToken:u}=this;if(typeof u=="function"){c(u).catch(()=>{});return}o(u)};return d(),()=>{i=!0,n!==void 0&&clearTimeout(n),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Pe,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Re,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(He,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Fe,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Le,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=y(U,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${U}?key=${encodeURIComponent(e)}${M(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Oe,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${U}?key=${encodeURIComponent(e.key)}${M(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Ie}?key=${encodeURIComponent(e)}${r}${M(t?.bucket)}`,i=await this.adminFetch(n,"GET");if(typeof i.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return i.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Me,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${Ue}?${t.toString()}`,"GET")}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${xe}?${t.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Ne,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Ke,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(Be,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(We,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=y(qe,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=y(x,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(x,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=y(x,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=y(De,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch(Qe,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Ge,"POST",e)}async banAuthUser(e){return await this.adminFetch(ze,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Ve,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(je,"POST",e)}async removeAuthUser(e){await this.adminFetch(Je,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Ye,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Xe,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Ze,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(et,"GET")}async updateAuthUser(e){return await this.adminFetch(tt,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(y(st,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(rt,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(y(nt,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(it,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(at,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(y(ot,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=y(ct,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=y(ht,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async removeAuthOrgMember(e){await this.adminFetch(dt,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(ut,"POST",e)}async getAuthConfig(){return await this.adminFetch(lt,"GET")}async createAuthOrganization(e){return await this.adminFetch(ft,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(mt,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(pt,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(yt,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(St,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(bt,"POST",e)}async listAuthOrgTeams(e){const t=y(Tt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(kt,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(vt,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(gt,"POST",e)}async listAuthOrgTeamMembers(e){const t=y(Ct,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(_t,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(wt,"POST",e)}async listAuthOrgRoles(e){const t=y(Et,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(At,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(It,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Ot,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=y($e,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const n=t??{},i=g.key(e.__lunoraRef,n,r.shardKey);let a=this.subscriptions.get(i);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=E(n),p=this.takeHydratedCache(e.__lunoraRef,l,r.shardKey);a={acked:!1,args:n,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:u,lastValue:p?.value,optimisticLayers:[],serverBase:p?.value,serverCursor:p?.serverCursor,shardKey:r.shardKey,...p?.serverEpoch===void 0?{}:{serverEpoch:p.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),r.onCheckpoint&&d.checkpointCallbacks.delete(r.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(e,t,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:v(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(r,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(n.shardKey,r,"shape_unsubscribe")}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new f("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,i=t??{},{handle:a,iterable:o}=oe({maxBuffer:s.maxBuffer,onCancel:()=>{const l=this.getConnection(n);l&&S(l,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(n);const c=this.getConnection(n),d={id:r,query:{args:v(i,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:d,shardKey:n}),!(c?.wsState==="open"&&S(c,d))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=ye;){const p=c.pendingStreams.shift()?.id,T=p?this.streams.get(p):void 0;T&&(T.handle.fail(new f("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(p))}c.pendingStreams.push(d)}return o}httpStream(e,t,s={}){if(this.closed)throw new f("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Z(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new f("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new f("INTERNAL","LunoraClient is closed")}teardownConnection(e){if(e.reconnectTimer!==void 0&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new X({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.sendSubscribeIfOpen(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,n,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,n!==void 0&&(a.serverEpoch=n),P(a,r)),R(a,H(s,a.optimisticLayers)))},onSubscriptionError:(t,s)=>{const r=this.subscriptions.get(t);r&&I(r.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,n,i,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);if(o){this.ackAndAdvanceCursor(o,s,r),n!==void 0&&i===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,n));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(e,t,s,r,n,i,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw A(n),d instanceof Error?d:new Error(String(d))}for(const d of i)d(void 0);return}return new Promise((c,d)=>{const u={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const p of i)p(l)},reject:l=>{this.queuedIdentities.delete(r),A(n),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const 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();for(const{key:t,...s}of e){if(re(this.persistenceVersion,s.version)){this.queryCache.remove(t).catch(()=>{});continue}this.hydratedQueryCache.set(t,s)}}catch{}}takeHydratedCache(e,t,s){const r=F(e,t,s),n=this.hydratedQueryCache.get(r);if(n!==void 0)return this.hydratedQueryCache.delete(r),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=F(e.fn.__lunoraRef,e.argsKey,e.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},pe)}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(([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const n=[],i=[];if(!r)return{confirms:n,rollbacks:i};const a=g.key(e,t,s),o=this.subscriptions.get(a);if(o){const c=ee(o,r);c&&(n.push(c.confirm),i.push(c.rollback))}return{confirms:n,rollbacks:i}}applyOptimisticUpdate(e,t,s,r,n){const{confirms:i,rollbacks:a,store:o}=te(this.subscriptions,s);try{e(o,t)}catch{A(a);return}r.push(...a),n.push(...i)}getConnection(e){return this.connections.get(m(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!S(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const t=this.getConnection(e);return{hasSocket:t?.socket!==void 0,wasEverConnected:t?.wasEverConnected??!1,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=m(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:K(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(t));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),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.attachBookmark){const n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(r,s),i=await this.fetchImpl(k(this.url,he),{body:JSON.stringify({args:v(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(r.captureBookmark){const o=i.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await i.json()}catch{const o=i.statusText?` ${i.statusText}`:"";throw new f("INTERNAL",`LunoraClient: response was not JSON (status ${i.status.toString()}${o})`)}if("error"in a)throw _(a.error);if(!i.ok){const o=i.statusText?` ${i.statusText}`:"";throw new f("INTERNAL",`LunoraClient: request failed (status ${i.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(i,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const i=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:i?(a=s,r!==void 0&&(n["content-type"]=r)):(a=JSON.stringify(s),n["content-type"]="application/json");const o=await this.fetchImpl(k(this.url,e),{body:a,headers:n,method:t});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new f("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new f("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}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(m(e.shardKey));S(e,{caps:Ht,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())m(t.shardKey)===m(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openManagedSocket(e,t,s,r){const{WebSocketImpl:n}=this;if(n===void 0)throw new f("INTERNAL","no WebSocket implementation available");const i=new n(t);e.socket=i;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===i&&(e.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===i){try{i.close()}catch{}o()}},s)),i.addEventListener("open",()=>{e.socket===i&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(e,o))}),i.addEventListener("message",c=>{e.socket===i&&(e.lastFrameAt=Date.now(),r.onMessage(c))}),i.addEventListener("close",c=>{e.socket===i&&o(c)}),i.addEventListener("error",()=>{e.socket===i&&o()})}openSocket(e,t,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t);for(const n of this.subscriptions.all())m(n.shardKey)===m(t)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:i,type:a}of n)S(e,{id:i,type:a})}if(e.pendingStreams&&e.pendingStreams.length>0){const n=e.pendingStreams;e.pendingStreams=[];for(const i of n)S(e,i)}const r=this.whisperHandlers.get(m(t));if(r)for(const n of r.keys())S(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}})}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,n]of this.streams)if(!(m(n.shardKey)!==m(e.shardKey)||t.has(r))){if(n.durable){const i={...n.message,sinceChunk:n.lastSeq};n.message=i,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),i];continue}n.handle.fail(new f("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(le)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){const t=m(e);for(const s of this.subscriptions.all())m(s.shardKey)===t&&(s.acked=!1)}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return;const s=e.fn.__lunoraTable??e.fn.__lunoraRef;S(t,{id:e.id,query:{args:D(e.args),functionPath:e.fn.__lunoraRef,table:s,...e.serverCursor===void 0?{}:{sinceSeq:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&S(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=Mt(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const n=this.subscriptions.getById(r.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,id:i,seq:a}=r,o=this.streams.get(i);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(n));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Ft(e)),this.streams.delete(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){I(n.errorCallbacks,q(e));return}const i=s===void 0?void 0:this.shapeSubscriptions.get(s);i&&I(i.errorCallbacks,q(e))}handlePokeStart(e){ce(this.pokeBuffers,Q.MAX_POKE_BUFFERS),this.pokeBuffers.set(e.pokeId,{baseCheckpoint:e.baseCheckpoint,epoch:e.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(e){const t=this.pokeBuffers.get(e.pokeId);if(!t)return;const s=t.parts.get(e.shapeId)??[];for(const r of e.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.value)});t.parts.set(e.shapeId,s),e.lastMutationId!==void 0&&t.lastMutationId.set(e.shapeId,e.lastMutationId)}handlePokeEnd(e){const t=this.pokeBuffers.get(e.pokeId);if(t){this.pokeBuffers.delete(e.pokeId);for(const[s,r]of t.parts){const n=this.shapeSubscriptions.get(s);if(!n)continue;const i=t.epoch!==void 0&&n.serverEpoch!==void 0&&t.epoch!==n.serverEpoch,a=t.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==t.baseCheckpoint;if(i||a){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}ue(n.rows,r),e.checkpoint!==void 0&&(n.serverCursor=e.checkpoint),e.epoch!==void 0&&(n.serverEpoch=e.epoch);const o=t.lastMutationId.get(s);o!==void 0&&(n.lastMutationId=o),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e){const{id:t}=e,s=t?this.subscriptions.getById(t):void 0;if(!s)return;const r=this.resolveDataPayload(e,s);if(s.serverBase=r,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(const n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),P(s,s.serverCursor),R(s,H(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=g.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(n,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=e.lastMutationId);for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=g.key(t.fn.__lunoraRef,t.args,t.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),P(e,e.serverCursor)&&R(e,H(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return b(e.data);const s=b(e.delta);if(z(s)&&t.serverBase!==void 0){const r=V(t.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(m(t))?.get(e.topic);if(!s)return;const r=b(e.data);for(const n of s)try{n(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.streams.delete(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,I(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ne(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const n=e.charCodeAt(r);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)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}rejectQueuedForIdentityChange(){const e=this.offlineQueue.drain();for(const t of e){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",t.reject(s),this.emitItemSettled(t,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const n=t??"",i=this.clientWatermarks.get(n);if(i===void 0)this.clientWatermarks.set(n,r);else for(const[a,o]of r)i.set(a,o)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=this.offlineQueue.drainConflict();for(const c of t){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=m(e),r=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(r.length===0)return;const n=this.identityFingerprint(),i=[];for(const c of r)this.passesReplayIdentityGate(c,n)&&i.push(c);if(i.length===0)return;const a=this.encodableOrSettleTerminal(i);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=L){const d=a.slice(c,c+L),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+L));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{v(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}passesReplayIdentityGate(e,t){const s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),r=s===void 0?e.identity:s;if(r!==void 0&&r!==t&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",e.reject(n),this.emitItemSettled(e,"rejected",n),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e){for(let t=0;t<e.length;t+=1){const s=e[t];if(s)try{let r;const n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:i=>{r=i}});this.settleReplaySuccess(s,n,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);continue}this.offlineQueue.requeue(e.slice(t));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let t;try{t=await this.fetchImpl(k(this.url,B),{body:JSON.stringify({calls:e.map((n,i)=>({args:v(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:i,clientId:n.clientId??this.clientId,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}const s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{return{requeue:e,stop:!0}}if(!r.results){if(r.error){const n=_(r.error);for(const i of e)this.settleReplayTerminal(i,n);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,r.results),stop:!1}}settleReplayBatchSlots(e,t){const s=new Map;for(const n of t)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);const r=[];for(const[n,i]of e.entries()){const a=s.get(n);a===void 0?r.push(i):"error"in a?xt.has(a.error.code)?r.push(i):this.settleReplayTerminal(i,_(a.error)):this.settleReplaySuccess(i,b(a.result),a.commitCursor)}return r}}export{Q as LunoraClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{O as s,n,r as o}from"./offline-queue-BdQFXDz_.mjs";export{s as OfflineQueue,n as nextId,o as reportPersistenceError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const E=s=>{let e=-1;for(const r of s)r.seq>e&&(e=r.seq);return e},A=2,f=(s,e)=>{const r=e.filter(t=>t.role==="user"),a=E(e),o=new Set;return s.filter(t=>{for(const[n,c]of r.entries())if(!o.has(n)&&c.seq>t.maxDurableSeqAtSend&&c.content===t.content)return o.add(n),!1;return a-t.maxDurableSeqAtSend<2})};export{A as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,E as maxSeq,f as reconcileOptimistic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f="skip",E=e=>e instanceof Error?{message:e.message}:{message:String(e)},b=(e,s,n,t,a={})=>{if(n===f)return t.onReset?.(),()=>{};let o=!1;const c=r=>{o||t.onError?.(r)},i=t.onError?c:void 0;let u;try{u=e.subscribe(s,n,r=>{o||t.onData(r)},{onError:i,shardKey:a.shardKey})}catch(r){if(!t.onError)throw r;return c(E(r)),()=>{o=!0}}return()=>{o=!0,u()}};export{f as SKIP,b as createQuerySubscription,E as toSubscriptionError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as i}from"./wire-key-BEmRM5ls.mjs";class r{static key(e,y,d){return`${e}::${i(y)}::${d??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(r.key(e.fn.__lunoraRef,e.args,e.shardKey),e),this.byId.set(e.id,e)}remove(e){const y=r.key(e.fn.__lunoraRef,e.args,e.shardKey);this.byKey.get(y)===e&&this.byKey.delete(y),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}}export{r as SubscriptionRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let d=0;const s="lunora-bridge",o=1e3,h=3e3;class c{bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onSubscriptionError;onSubscriptionSettled;constructor(t={}){if(d+=1,this.tabId=`tab_${String(d)}_${crypto.randomUUID()}`,this.heartbeatInterval=t.heartbeatInterval??o,this.leaderTimeout=t.leaderTimeout??h,this.onBecomeLeader=t.onBecomeLeader,this.onStopBeingLeader=t.onStopBeingLeader,this.onConnectionStatus=t.onConnectionStatus,this.onSubscriptionData=t.onSubscriptionData,this.onSubscriptionError=t.onSubscriptionError,this.onSubscriptionSettled=t.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(t.channelName??s),this.bc.addEventListener("message",e=>{this.handleMessage(e.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(t,e,i,a,r){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:t,data:e,...i===void 0?{}:{cursor:i},...a===void 0?{}:{epoch:a},...r===void 0?{}:{identity:r}})}broadcastSubscriptionError(t,e){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:t,error:e})}broadcastSubscriptionSettled(t,e,i,a,r,n){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:t,...e===void 0?{}:{cursor:e},...i===void 0?{}:{epoch:i},...a===void 0?{}:{lastMutationId:a},...r===void 0?{}:{clientId:r},...n===void 0?{}:{identity:n}})}broadcastConnectionStatus(t,e){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:t,...e===void 0?{}:{identity:e}})}broadcast(t){this.bc?.postMessage(t)}handleMessage(t){switch(t.type){case"claim-leadership":{this.handleClaimLeadership(t);break}case"connection-status":{if(this.leader||t.tabId===this.tabId)break;this.onConnectionStatus?.(t.status,t.identity);break}case"heartbeat":{this.handleHeartbeat(t);break}case"subscription-data":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionData?.(t.key,t.data,t.cursor,t.epoch,t.identity);break}case"subscription-error":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionError?.(t.key,t.error);break}case"subscription-settled":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionSettled?.(t.key,t.cursor,t.epoch,t.lastMutationId,t.clientId,t.identity);break}case"yield-leadership":{this.knownLeader===t.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(t){if(t.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()});return}this.knownLeader===void 0&&t.tabId<this.tabId&&(this.knownLeader=t.tabId,this.lastHeartbeat=t.ts)}}handleHeartbeat(t){if(t.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(t);return}this.lastHeartbeat=t.ts,this.knownLeader=t.tabId}}resolveLeaderVsLeaderTieBreak(t){t.tabId<this.tabId?(this.leader=!1,this.knownLeader=t.tabId,this.lastHeartbeat=t.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!this.running||this.leader)return;if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}}export{c as TabCoordinator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=new Map,h=new Proxy({},{get(g,e){const n=a.get(e);if(n)return n;const t=new Map,c=new Proxy({},{get(f,r){const o=t.get(r);if(o)return o;const s={__lunoraRef:`${String(e)}:${String(r)}`};return t.set(r,s),s}});return a.set(e,c),c}});export{h as anyApi};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,i}from"./delta-merge-BoVuM-rE.mjs";export{e as applyDelta,i as isMutationDelta};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u="lunora:offline-mutations",y=o=>{const{storage:r}=o,a=o.key??u;let i=Promise.resolve();const n=t=>{const e=i.then(t,t);return i=e.then(()=>{},()=>{}),e},s=async()=>{const t=await r.getItem(a);if(t===null)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}},c=t=>r.setItem(a,JSON.stringify(t));return{append:t=>n(async()=>{const e=await s();e.push(t),await c(e)}),clear:()=>n(()=>r.removeItem(a)),load:()=>n(s),remove:t=>n(async()=>{const e=await s(),l=e.filter(m=>m.id!==t);l.length!==e.length&&await c(l)})}};export{y as createAsyncStoragePersistence};
|
package/dist/packem_shared/{createClientQuery-CrdRoicO.mjs → createClientQuery-TKD_52cT.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
class u{values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,t){if(t===void 0){this.reset(e);return}this.values.set(e.key,t),this.notify(e.key,t)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}subscribe(e,t){let s=this.subscribers.get(e.key);return s||(s=new Set,this.subscribers.set(e.key,s)),s.add(t),()=>{s.delete(t),s.size===0&&this.subscribers.delete(e.key)}}notify(e,t){const s=this.subscribers.get(e);if(s)for(const
|
|
1
|
+
class u{values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,t){if(t===void 0){this.reset(e);return}this.values.set(e.key,t),this.notify(e.key,t)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}subscribe(e,t){let s=this.subscribers.get(e.key);return s||(s=new Set,this.subscribers.set(e.key,s)),s.add(t),()=>{s.delete(t),s.size===0&&this.subscribers.delete(e.key)}}notify(e,t){const s=this.subscribers.get(e);if(s)for(const r of s)try{r(t)}catch{}}}const n=(i,e)=>({defaultValue:e,key:i});export{u as ClientQueryStore,n as createClientQuery};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=()=>{let e=null;return{get:()=>e,set:t=>{e=t}}};export{r as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{p as s,c as f,a as y}from"./idb-utility-C8WS390w.mjs";const x=()=>{const r=new Map,a=e=>({args:{...e.args},functionPath:e.functionPath,id:e.id,identity:e.identity,shardKey:e.shardKey});return{append:e=>(r.set(e.id,a(e)),Promise.resolve()),clear:()=>(r.clear(),Promise.resolve()),load:()=>Promise.resolve([...r.values()].map(e=>a(e))),remove:e=>(r.delete(e),Promise.resolve())}},m="lunora-outbox",D="offline-mutations",c="by_id",p=(r={})=>{const a=r.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!a)throw new u("INTERNAL","createIndexedDbPersistence: no IndexedDB available — pass `indexedDB` or use createInMemoryPersistence()");const e=r.databaseName??m,d=r.storeName??D,l=y(a,e,1,t=>{t.objectStoreNames.contains(d)||t.createObjectStore(d,{autoIncrement:!0}).createIndex(c,"id",{unique:!0})}),o=f(l,d);return{append:async t=>{await o("readwrite",n=>s(n.add(t)))},clear:async()=>{await o("readwrite",t=>s(t.clear()))},load:async()=>o("readonly",t=>s(t.getAll())),remove:async t=>{await o("readwrite",async n=>{const i=await s(n.index(c).getKey(t));i!==void 0&&await s(n.delete(i))})}}},P=(r,a=!0)=>{if(r!==!1){if(r)return r;if(!(!a||typeof indexedDB>"u"))return p()}};export{x as createInMemoryPersistence,p as createIndexedDbPersistence,P as resolvePersistenceAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{p as d,c as x,a as A}from"./idb-utility-C8WS390w.mjs";const B=(t,o,a)=>`${t}::${o}::${a??""}`,v=500,T=(t={})=>{const o=t.maxEntries??v,a=new Map,s=e=>({...e,value:structuredClone(e.value)}),l=()=>{if(a.size<=o)return;const e=[...a.values()].toSorted((n,y)=>n.ts-y.ts);for(const n of e){if(a.size<=o)break;a.delete(n.key)}};return{clear:()=>(a.clear(),Promise.resolve()),load:()=>Promise.resolve([...a.values()].map(e=>s(e))),put:(e,n)=>(a.set(e,s({...n,key:e})),l(),Promise.resolve()),remove:e=>(a.delete(e),Promise.resolve())}},h="lunora-query-cache",p="query-cache",f="by_ts",I=1,S=(t={})=>{const o=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!o)throw new D("INTERNAL","createIndexedDbQueryCache: no IndexedDB available — pass `indexedDB` or use createInMemoryQueryCache()");const a=t.databaseName??h,s=t.storeName??p,l=t.maxEntries??v,e=A(o,a,I,r=>{r.objectStoreNames.contains(s)||r.createObjectStore(s,{keyPath:"key"}).createIndex(f,"ts",{unique:!1})}),n=x(e,s),y=async r=>{let c=await d(r.count())-l;c<=0||await new Promise((E,w)=>{const u=r.index(f).openCursor();u.addEventListener("success",()=>{const m=u.result;if(!m||c<=0){E();return}m.delete(),c-=1,m.continue()}),u.addEventListener("error",()=>{w(u.error??new Error("IndexedDB eviction failed"))})})};return{clear:async()=>{await n("readwrite",r=>d(r.clear()))},load:async()=>n("readonly",r=>d(r.getAll())),put:async(r,i)=>{await n("readwrite",async c=>{await d(c.put({...i,key:r})),await y(c)})},remove:async r=>{await n("readwrite",i=>d(i.delete(r)))}}},C=t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return S()}};export{T as createInMemoryQueryCache,S as createIndexedDbQueryCache,B as queryCacheKey,C as resolveQueryCacheAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as t}from"./local-store-BD0RFD7A.mjs";import"./SubscriptionRegistry-D5Xu-a39.mjs";export{t as createLocalStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u=(o,a,r)=>{let e=0;return async(c,i)=>{e+=1,r.setPending(!0);try{const t=await o.mutation(a,c,i);return r.setResult(t),t}catch(t){const n=t instanceof Error?t:new Error(String(t));throw r.setError(n),n}finally{e-=1,r.setPending(e>0)}}};export{u as createMutationRunner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=(a,t)=>{let e=0,r=0;return{mutate:async c=>{r+=1;const n=r;e+=1,t.setPending(!0);try{await a(c).isPersisted.promise,n===r&&t.setError(void 0)}catch(o){const i=o instanceof Error?o:new Error(String(o));throw n===r&&t.setError(i),i}finally{e-=1,t.setPending(e>0)}},reset:()=>{t.setError(void 0)}}};export{d as createMutatorRunner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=(t={},r=Math.random)=>{const i=t.initialDelayMs??250,c=t.maxDelayMs??3e4,l=t.jitter??!0;let e=0;return{next(){const n=Math.min(c,i*2**e);if(e+=1,!l)return n;const a=n/2;return Math.floor(a+r()*(n-a))},reset(){e=0}}};export{s as createReconnect};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const v=(e,r,d=!1)=>new Promise((a,s)=>{if(!e){s(new Error("No active service worker"));return}const o=r.correlationId??crypto.randomUUID(),
|
|
1
|
+
const v=(e,r,d=!1)=>new Promise((a,s)=>{if(!e){s(new Error("No active service worker"));return}const o=r.correlationId??crypto.randomUUID(),n={...r,correlationId:o};if(d){let i;const t=c=>{c.data.correlationId===o&&(clearTimeout(i),navigator.serviceWorker.removeEventListener("message",t),a(c.data.payload))};i=setTimeout(()=>{navigator.serviceWorker.removeEventListener("message",t),s(new Error(`SW message ${o} timed out`))},3e4),navigator.serviceWorker.addEventListener("message",t),e.postMessage(n)}else e.postMessage(n),a(void 0)}),l=(e,r)=>({type:`${e.type}:reply`,payload:r,correlationId:e.correlationId});export{l as createReply,v as sendToSw};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraClient as r}from"./LunoraClient-CWDiiVcr.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{s as u}from"./wire-key-BEmRM5ls.mjs";const v=(r,t,n,i)=>{const s=r.peekActiveQueryValue(t.__lunoraRef,n,i),e=s===void 0?void 0:u(s);return()=>{const o=r.peekActiveQueryValue(t.__lunoraRef,n,i);return e===void 0&&o===void 0?!0:e===void 0||o===void 0?!1:u(o)===e}};export{v as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as g}from"./wire-codec-D4iww4NV.mjs";const c="_id",d="_creationTime",u="page",m="pageDelta",y=t=>{if(Array.isArray(t))return t;if(g(t)&&Array.isArray(t[u]))return t[u]},l=t=>{let e;for(const n of t){const o=n[d];if(typeof o=="number"){if(e!==void 0){if(o<e)return!0;if(o>e)return!1}e=o}}return!1},x=(t,e)=>{const n=e[d];if(typeof n!="number")return t.length;const o=l(t);for(const[f,s]of t.entries()){const r=s[d];if(typeof r=="number"&&(o?r<n:r>n))return f}return t.length},A=t=>{if(typeof t!="object"||t===null)return;const e=t[c];return typeof e=="string"?e:void 0},b=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},I=(t,e)=>{const n=[];for(const i of t){if(A(i)===void 0)return;n.push(i)}const{key:o,op:f,row:s}=e;if(f==="delete"){const i=n.filter(p=>p[c]!==o);return i.length===n.length?[...n]:i}if(s===void 0)return;const r=[...n],a=n.findIndex(i=>i[c]===o);return a===-1?r.splice(x(n,s),0,s):r[a]=s,r},E=(t,e)=>{const n=y(t);if(n===void 0)return;const o=I(n,e);return o===void 0||Array.isArray(t)?o:{...t,[u]:o}};export{m as P,E as a,b as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=e=>e instanceof Headers?e:e.headers,a=async(e,t)=>{const r=s(e);return await t.api.getSession({headers:r})??null};export{a as getServerSession};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{createStream as p}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";const m=/^ /u,h=t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),u=t=>{let r="";const e=[];for(const n of t.split(`
|
|
2
|
+
`))n.startsWith("event:")?r=n.slice(6).replace(m,""):n.startsWith("data:")&&e.push(n.slice(5).replace(m,""));return{data:e.join(`
|
|
3
|
+
`),event:r}},S=(t,r,e)=>{const n=r.params??{},o=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;const f=c.slice(1),a=n[f];if(a===void 0)throw new l("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${f}" for route ${t.path}`);return encodeURIComponent(h(a))}).join("/"),i=new URLSearchParams;for(const[c,f]of Object.entries(r.searchParams??{}))f!==void 0&&i.set(c,h(f));const s=i.toString();return`${e.endsWith("/")?e.slice(0,-1):e}${o}${s===""?"":`?${s}`}`},T=(t,r)=>{if(t.event==="complete")return r.complete(),!0;if(t.event==="error"){let e={};try{e=JSON.parse(t.data)}catch{}const n=typeof e.message=="string"?e.message:"stream error",o=typeof e.code=="string"?e.code:"HTTP_STREAM_ERROR";return r.fail(new l(o,n)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{r.push(JSON.parse(t.data))}catch{return r.fail(new l("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},E=async(t,r)=>{const e=t.getReader(),n=new TextDecoder;let o="";const i=()=>{let s=o.indexOf(`
|
|
4
|
+
|
|
5
|
+
`);for(;s!==-1;){const d=u(o.slice(0,s));if(o=o.slice(s+2),T(d,r))return!0;s=o.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}return!1};for(;;){const{done:s,value:d}=await e.read();if(s)break;if(o+=n.decode(d,{stream:!0}).replaceAll(`\r
|
|
8
|
+
`,`
|
|
9
|
+
`),i()){await e.cancel().catch(()=>{});return}}o+=n.decode().replaceAll(`\r
|
|
10
|
+
`,`
|
|
11
|
+
`),i()||r.fail(new l("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},w=(t,r,e={})=>{const n=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!n)throw new l("INTERNAL","httpStream: no `fetch` implementation available");const o=S(t,r??{},e.baseUrl??""),i=new AbortController;let s;e.signal&&(e.signal.aborted?i.abort():(s=()=>{i.abort()},e.signal.addEventListener("abort",s,{once:!0})));const d=()=>{s&&e.signal?.removeEventListener("abort",s)},{handle:c,iterable:f}=p({maxBuffer:e.maxBuffer,onCancel:()=>{i.abort()}});return(async()=>{try{const a=await n(o,{headers:{accept:"text/event-stream",...e.headers},method:t.method,signal:i.signal});if(!a.ok){await a.body?.cancel().catch(()=>{}),c.fail(new l("HTTP_STREAM_STATUS",`httpStream: request failed (status ${a.status.toString()})`,{status:a.status}));return}if(!a.body){c.fail(new l("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await E(a.body,c)}finally{d()}})().catch(a=>{if(i.signal.aborted){c.complete();return}if(a instanceof Error&&"code"in a){c.fail(a);return}c.fail(new l("HTTP_STREAM_TRANSPORT",a instanceof Error?a.message:String(a),{cause:a}))}),f};export{w as httpStream};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=e=>new Promise((n,a)=>{e.addEventListener("success",()=>{n(e.result)}),e.addEventListener("error",()=>{a(e.error??new Error("IndexedDB request failed"))})}),E=(e,n,a,o)=>{let s;return()=>s||(s=new Promise((r,d)=>{const t=e.open(n,a);t.addEventListener("upgradeneeded",()=>{o(t.result)}),t.addEventListener("success",()=>{r(t.result)}),t.addEventListener("error",()=>{d(t.error??new Error("IndexedDB open failed"))})}),s)},u=(e,n)=>async(a,o)=>{const r=(await e()).transaction(n,a),d=await o(r.objectStore(n));return await new Promise((t,i)=>{r.addEventListener("complete",()=>{t()}),r.addEventListener("error",()=>{i(r.error??new Error("IndexedDB transaction failed"))}),r.addEventListener("abort",()=>{i(r.error??new Error("IndexedDB transaction aborted"))})}),d};export{E as a,u as c,c as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SubscriptionRegistry as m}from"./SubscriptionRegistry-D5Xu-a39.mjs";const p=(r,o)=>{let e=r;for(const i of o)try{e=i.transform(e)}catch{}return e},u=(r,o)=>{if(o!==r.lastValue){r.lastValue=o;for(const e of r.callbacks)try{e(o)}catch{}}},y=(r,o)=>{let e;try{e=o(r.lastValue)}catch{return}const i={id:Symbol("optimistic"),transform:o};r.optimisticLayers.push(i),u(r,e);const c=()=>{const t=r.optimisticLayers.findIndex(s=>s.id===i.id);return t===-1?!1:(r.optimisticLayers.splice(t,1),!0)},a=()=>{u(r,p(r.serverBase,r.optimisticLayers))};return{confirm:t=>{if(t===void 0){c();return}i.commitCursor=t,r.serverCursor!==void 0&&r.serverCursor>=t&&c()&&a()},rollback:()=>{c()&&a()}}},h=(r,o)=>{if(o===void 0||r.optimisticLayers.length===0)return!1;const e=r.optimisticLayers.length;return r.optimisticLayers=r.optimisticLayers.filter(i=>i.commitCursor===void 0||i.commitCursor>o),r.optimisticLayers.length!==e},L=(r,o)=>{const e=[],i=[],c=(t,s)=>r.get(m.key(t,s,o));return{confirms:e,rollbacks:i,store:{getAllQueries:t=>{const s=[];for(const n of r.all())n.fn.__lunoraRef===t.__lunoraRef&&(n.shardKey??"")===(o??"")&&s.push({args:n.args,value:n.lastValue});return s},getQuery:(t,s)=>c(t.__lunoraRef,s??{})?.lastValue,setQuery:(t,s,n)=>{const f=c(t.__lunoraRef,s??{});if(!f)return;const l=y(f,()=>n);l&&(e.push(l.confirm),i.push(l.rollback))}}}};export{y as a,L as c,h as d,p as f,u as n};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let h=0;const d=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();h+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),t=>t.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${h.toString(36)}_${r}`},a=(r,t)=>r!==void 0&&t!==r,f=d,c=(r,t,e,s)=>{if(r){r({error:e,mutationId:s,operation:t});return}console.warn(`[lunora] offline-queue persistence ${t} failed`,e)};class u{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(t={},e={}){this.maxItems=t.maxItems??1e3,this.queueBeforeFirstConnect=t.queueBeforeFirstConnect??!1,this.onPersistenceError=t.onPersistenceError,this.persistence=e.persistence,this.onEvict=e.onEvict,this.onSizeChange=e.onSizeChange,this.version=e.version}get size(){return this.items.length}enqueue(t){const e=t;e.id??=f(),this.items.push(e),this.persistence?.append({args:e.args,clientId:e.clientId,functionPath:e.functionPath,id:e.id,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{c(this.onPersistenceError,"append",s,e.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let t;try{t=await this.persistence.load()}catch(i){throw c(this.onPersistenceError,"load",i),i}const e=[];for(const i of t)if(!(this.items.some(o=>o.id===i.id)||e.some(o=>o.id===i.id))){if(a(this.version,i.version)){this.persistence.remove(i.id).catch(o=>{c(this.onPersistenceError,"remove",o,i.id)});continue}e.push({args:i.args,clientId:i.clientId,functionPath:i.functionPath,id:i.id,identity:i.identity,reject:()=>{},resolve:()=>{},shardKey:i.shardKey})}this.items.unshift(...e),this.evictOverflow(),this.notifySize();const s=new Set(this.items),n=new Set;for(const i of e)s.has(i)&&n.add(i.shardKey);return[...n]}drain(t){if(!t){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const e=[],s=[];for(const n of this.items)(t(n)?e:s).push(n);return this.items.length=0,this.items.push(...s),this.notifySize(),e}requeue(t){t.length!==0&&(this.items.unshift(...t),this.notifySize())}drainConflict(){const t=[],e=[];for(const s of this.items)if(s.precondition!==void 0&&!s.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",s.reject(n),t.push(s)}else e.push(s);return t.length>0&&(this.items.length=0,this.items.push(...e),this.notifySize()),t}clear(){for(const t of this.items){const e=new Error("CLIENT_CLOSED");e.code="CLIENT_CLOSED",t.reject(e)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){const t=this.items.shift();if(t){t.id&&this.persistence?.remove(t.id).catch(s=>{c(this.onPersistenceError,"remove",s,t.id)});const e=new Error("offline queue overflow");e.code="OFFLINE_QUEUE_OVERFLOW",t.reject(e),this.onEvict?.(t,e)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{u as O,a as i,f as n,c as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=async(e,r,a,u={})=>{const l=await e.query(r,a,u);return{__lunoraPreloaded:!0,args:a??{},functionPath:r.__lunoraRef,shardKey:u.shardKey,value:l}},d=e=>e.value;export{t as preloadQuery,d as preloadedQueryResult};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const A=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},E=e=>{const t=atob(e),f=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)f[o]=t.codePointAt(o)??0;return f},i="$lunora.wire$";const d="__proto__",m={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},w={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},p=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const f=typeof e;if(f==="bigint")return[i,"bigint",e.toString()];if(f==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(f!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const a of Object.keys(r))r[a]!==void 0&&(n[a]=u(r[a],t+1));const c=[i,"error",r.name,r.message,n];return r.cause!==void 0&&c.push(u(r.cause,t+1)),c}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",A(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",A(c)]:[i,"bytes",A(c),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!p(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,s={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const c=u(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":return new Date(y(e[2],t+1));case"map":return new Map(e[2].map(([r,n])=>[y(r,t+1),y(n,t+1)]));case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],c=(Object.hasOwn(w,r)?w[r]:void 0)??Error,a=new c(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const g=y(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):a[b]=g[b];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}case"bytes":{const r=E(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const c=Object.hasOwn(m,n)?m[n]:void 0;return c?new c(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(s=>y(s,t+1))}const f=e,o={};for(const s of Object.keys(f)){const r=y(f[s],t+1);s===d?Object.defineProperty(o,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[s]=r}return o};export{y as d,u as e,p as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as c}from"./wire-codec-D4iww4NV.mjs";const y=(t,e)=>t<e?-1:t>e?1:0,n=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(r=>n(r)).join(",")}]`;const e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){const r=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=t,a=Object.keys(o).toSorted(y),i=[];for(const r of a){const s=o[r];s!==void 0&&i.push(`${JSON.stringify(r)}:${n(s)}`)}return`{${i.join(",")}}`},f=t=>n(c(t));export{f as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const l=2,
|
|
1
|
+
const l=2,m=.5,p=e=>[{lower:null,numItems:e,upper:null}],c=(e,r)=>{for(const[n,t]of e.entries()){if(t.upper===null)continue;const o=r[n];if(!o)continue;const i=o.page.length;if(i>2*t.numItems&&o.splitCursor){const u=o.splitCursor,s=[...e];return s.splice(n,1,{lower:t.lower,numItems:t.numItems,upper:u},{lower:u,numItems:t.numItems,upper:t.upper}),s}if(i<.5*t.numItems&&n+1<e.length){const u=e[n+1];if(!u)continue;const s=[...e];return s.splice(n,2,{lower:t.lower,numItems:t.numItems,upper:u.upper}),s}}},a=(e,r)=>{if(e||!r[0])return{nextCursor:void 0,status:"LoadingFirstPage"};const n=r.at(-1);return n?n.isDone||n.continueCursor===null?{nextCursor:void 0,status:"Exhausted"}:{nextCursor:n.continueCursor,status:"CanLoadMore"}:{nextCursor:void 0,status:"LoadingMore"}},I=(e,r,n)=>{if(r==null)return;const t=[...e],o=t.at(-1);return o&&(t[t.length-1]={lower:o.lower,numItems:o.numItems,upper:r}),t.push({lower:r,numItems:n,upper:null}),t};export{m as JOIN_FACTOR,l as SPLIT_FACTOR,I as applyLoadMore,a as derivePaginationStatus,p as initialPages,c as rebalance};
|
package/dist/query/index.d.mts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.mjs";
|
|
2
1
|
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-BOmxvSrG.mjs";
|
|
3
|
-
export type {
|
|
2
|
+
export type {
|
|
3
|
+
/**
|
|
4
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
5
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
6
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
7
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
8
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
9
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
10
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
11
|
+
* store / signal / cache.
|
|
12
|
+
*/
|
|
13
|
+
a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BOmxvSrG.mjs";
|
|
14
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.mjs";
|
|
4
15
|
import '@lunora/runtime';
|
|
5
16
|
/**
|
|
6
17
|
* The sentinel a framework adapter resolves its reactive args to when it wants
|
|
@@ -60,4 +71,59 @@ declare const toSubscriptionError: (error: unknown) => SubscriptionError;
|
|
|
60
71
|
* in-flight push reaches the sinks.
|
|
61
72
|
*/
|
|
62
73
|
declare const createQuerySubscription: <F extends FunctionReference, T = ReturnOf<F>>(client: LunoraClient, function_: F, args: ResolvedArgs<F>, sinks: QuerySubscriptionSinks<T>, options?: QuerySubscriptionOptions) => Unsubscribe;
|
|
63
|
-
export {
|
|
74
|
+
export {
|
|
75
|
+
/**
|
|
76
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
77
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
78
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
79
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
80
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
81
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
82
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
83
|
+
* store / signal / cache.
|
|
84
|
+
*/
|
|
85
|
+
type ArgsOf,
|
|
86
|
+
/**
|
|
87
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
88
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
89
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
90
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
91
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
92
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
93
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
94
|
+
* store / signal / cache.
|
|
95
|
+
*/
|
|
96
|
+
type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs,
|
|
97
|
+
/**
|
|
98
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
99
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
100
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
101
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
102
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
103
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
104
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
105
|
+
* store / signal / cache.
|
|
106
|
+
*/
|
|
107
|
+
type ReturnOf, SKIP,
|
|
108
|
+
/**
|
|
109
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
110
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
111
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
112
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
113
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
114
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
115
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
116
|
+
* store / signal / cache.
|
|
117
|
+
*/
|
|
118
|
+
type SubscriptionError,
|
|
119
|
+
/**
|
|
120
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
121
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
122
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
123
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
124
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
125
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
126
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
127
|
+
* store / signal / cache.
|
|
128
|
+
*/
|
|
129
|
+
type Unsubscribe, createQuerySubscription, toSubscriptionError };
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.js";
|
|
2
1
|
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-K16SL8Tj.js";
|
|
3
|
-
export type {
|
|
2
|
+
export type {
|
|
3
|
+
/**
|
|
4
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
5
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
6
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
7
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
8
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
9
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
10
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
11
|
+
* store / signal / cache.
|
|
12
|
+
*/
|
|
13
|
+
a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-K16SL8Tj.js";
|
|
14
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.js";
|
|
4
15
|
import '@lunora/runtime';
|
|
5
16
|
/**
|
|
6
17
|
* The sentinel a framework adapter resolves its reactive args to when it wants
|
|
@@ -60,4 +71,59 @@ declare const toSubscriptionError: (error: unknown) => SubscriptionError;
|
|
|
60
71
|
* in-flight push reaches the sinks.
|
|
61
72
|
*/
|
|
62
73
|
declare const createQuerySubscription: <F extends FunctionReference, T = ReturnOf<F>>(client: LunoraClient, function_: F, args: ResolvedArgs<F>, sinks: QuerySubscriptionSinks<T>, options?: QuerySubscriptionOptions) => Unsubscribe;
|
|
63
|
-
export {
|
|
74
|
+
export {
|
|
75
|
+
/**
|
|
76
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
77
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
78
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
79
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
80
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
81
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
82
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
83
|
+
* store / signal / cache.
|
|
84
|
+
*/
|
|
85
|
+
type ArgsOf,
|
|
86
|
+
/**
|
|
87
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
88
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
89
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
90
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
91
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
92
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
93
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
94
|
+
* store / signal / cache.
|
|
95
|
+
*/
|
|
96
|
+
type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs,
|
|
97
|
+
/**
|
|
98
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
99
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
100
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
101
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
102
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
103
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
104
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
105
|
+
* store / signal / cache.
|
|
106
|
+
*/
|
|
107
|
+
type ReturnOf, SKIP,
|
|
108
|
+
/**
|
|
109
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
110
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
111
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
112
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
113
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
114
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
115
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
116
|
+
* store / signal / cache.
|
|
117
|
+
*/
|
|
118
|
+
type SubscriptionError,
|
|
119
|
+
/**
|
|
120
|
+
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
121
|
+
* by every Lunora UI adapter (React, Vue, Svelte, Solid). It owns the seam
|
|
122
|
+
* between a `LunoraClient` subscription and a framework's reactivity primitive:
|
|
123
|
+
* the subscribe → snapshot → error/reset → cleanup lifecycle, with the
|
|
124
|
+
* skip-handling, value/error fan-out, attach-throw normalisation, and
|
|
125
|
+
* cancellation-guarded teardown all in one place. Nothing here imports a UI
|
|
126
|
+
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
127
|
+
* store / signal / cache.
|
|
128
|
+
*/
|
|
129
|
+
type Unsubscribe, createQuerySubscription, toSubscriptionError };
|
package/dist/query/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SKIP as t,createQuerySubscription as e,toSubscriptionError as i}from"../packem_shared/SKIP-
|
|
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};
|
package/dist/service.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{e as w,d as f}from"./packem_shared/wire-codec-D4iww4NV.mjs";const v="/_lunora/rpc",$="https://lunora.internal",N=e=>{const t=new Error(e.message??"request failed");return t.code=e.code,e.data!==void 0&&(t.data=f(e.data)),e.hint!==void 0&&(t.hint=e.hint),e.docsUrl!==void 0&&(t.docsUrl=e.docsUrl),t},h=async(e,t,r,a,l)=>{const s=r.__lunoraRef;let d;try{d=JSON.stringify({args:w(a??{}),functionPath:s,...l?.shardKey===void 0?{}:{shardKey:l.shardKey}})}catch(o){const p=o instanceof Error?o.message:String(o);throw new TypeError(`@lunora/client/service: cannot encode args for '${s}' — ${p}`,o instanceof Error?{cause:o}:void 0)}const n=await e.fetch(new Request(`${$}${v}`,{body:d,headers:{"content-type":"application/json"},method:"POST"}));let i;try{i=await n.json()}catch{throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" got a non-JSON response (status ${n.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:n.status})}if(i===null||typeof i!="object")throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" returned a JSON body that is not an object (status ${n.status.toString()}). Check the service binding points at the Lunora Worker that declares this function.`,{status:n.status});const c=i;if("error"in c)throw N(c.error);if(!n.ok)throw new u("INTERNAL",`@lunora/client/service: ${t} "${s}" failed with status ${n.status.toString()} and no error envelope.`,{status:n.status});return f(c.result)},E=e=>({action:async(t,r,a)=>await h(e,"action",t,r,a),mutation:async(t,r,a)=>await h(e,"mutation",t,r,a),query:async(t,r,a)=>await h(e,"query",t,r,a)});export{v as RPC_PATH,E as createServiceClient};
|
package/dist/ssr/index.d.mts
CHANGED
|
@@ -1,7 +1,27 @@
|
|
|
1
1
|
import { P as Preloaded } from "../packem_shared/types.d-CsuRAQvb.mjs";
|
|
2
2
|
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-CsuRAQvb.mjs";
|
|
3
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-BprjXhJi.mjs";
|
|
4
3
|
import { L as LunoraClient } from "../packem_shared/lunora-client.d-BOmxvSrG.mjs";
|
|
4
|
+
export {
|
|
5
|
+
/**
|
|
6
|
+
* `@lunora/client/ssr` — the framework-neutral server contract that every Lunora
|
|
7
|
+
* meta-framework adapter (React, Solid, Svelte, Vue) depends on. It owns the
|
|
8
|
+
* server-side seam: a request-scoped HTTP RPC client, session resolution from
|
|
9
|
+
* the inbound request, query preloading, and the dehydrate/serialize helpers
|
|
10
|
+
* for handing a preloaded snapshot to the client. Nothing here opens a
|
|
11
|
+
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
12
|
+
* loader.
|
|
13
|
+
*/
|
|
14
|
+
p as preloadQuery,
|
|
15
|
+
/**
|
|
16
|
+
* `@lunora/client/ssr` — the framework-neutral server contract that every Lunora
|
|
17
|
+
* meta-framework adapter (React, Solid, Svelte, Vue) depends on. It owns the
|
|
18
|
+
* server-side seam: a request-scoped HTTP RPC client, session resolution from
|
|
19
|
+
* the inbound request, query preloading, and the dehydrate/serialize helpers
|
|
20
|
+
* for handing a preloaded snapshot to the client. Nothing here opens a
|
|
21
|
+
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
22
|
+
* loader.
|
|
23
|
+
*/
|
|
24
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-BprjXhJi.mjs";
|
|
5
25
|
import '@lunora/runtime';
|
|
6
26
|
/**
|
|
7
27
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,7 +1,27 @@
|
|
|
1
1
|
import { P as Preloaded } from "../packem_shared/types.d-CsuRAQvb.js";
|
|
2
2
|
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-CsuRAQvb.js";
|
|
3
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-CM8-Mg2A.js";
|
|
4
3
|
import { L as LunoraClient } from "../packem_shared/lunora-client.d-K16SL8Tj.js";
|
|
4
|
+
export {
|
|
5
|
+
/**
|
|
6
|
+
* `@lunora/client/ssr` — the framework-neutral server contract that every Lunora
|
|
7
|
+
* meta-framework adapter (React, Solid, Svelte, Vue) depends on. It owns the
|
|
8
|
+
* server-side seam: a request-scoped HTTP RPC client, session resolution from
|
|
9
|
+
* the inbound request, query preloading, and the dehydrate/serialize helpers
|
|
10
|
+
* for handing a preloaded snapshot to the client. Nothing here opens a
|
|
11
|
+
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
12
|
+
* loader.
|
|
13
|
+
*/
|
|
14
|
+
p as preloadQuery,
|
|
15
|
+
/**
|
|
16
|
+
* `@lunora/client/ssr` — the framework-neutral server contract that every Lunora
|
|
17
|
+
* meta-framework adapter (React, Solid, Svelte, Vue) depends on. It owns the
|
|
18
|
+
* server-side seam: a request-scoped HTTP RPC client, session resolution from
|
|
19
|
+
* the inbound request, query preloading, and the dehydrate/serialize helpers
|
|
20
|
+
* for handing a preloaded snapshot to the client. Nothing here opens a
|
|
21
|
+
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
22
|
+
* loader.
|
|
23
|
+
*/
|
|
24
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-CM8-Mg2A.js";
|
|
5
25
|
import '@lunora/runtime';
|
|
6
26
|
/**
|
|
7
27
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getServerSession as o}from"../packem_shared/getServerSession-
|
|
1
|
+
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-BxPCzuUt.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.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createMultipartAdapter as
|
|
1
|
+
import{createMultipartAdapter as d,createChunkedRestAdapter as u,createTusAdapter as m}from"@visulima/storage-client";import{LocalStorageUrlStorage as S,MemoryUrlStorage as f,RestrictionError as g,UploadControl as x,UploadError as C,createChunkedRestAdapter as F,createMultipartAdapter as M,createTusAdapter as O,putFile as v,validateFile as y,validateFiles as E}from"@visulima/storage-client";const U=t=>{const r=t.protocol??"tus",{chunkSize:s,control:n,endpoint:e,headers:a,maxRetries:o,metadata:p,restrictions:i,retry:l}=t;if(r==="multipart")return d({endpoint:e,headers:a,maxRetries:o,metadata:p,restrictions:i,retry:l});const c={chunkSize:s,control:n,endpoint:e,headers:a,maxRetries:o,metadata:p,restrictions:i,retry:l};return r==="chunked-rest"?u(c):m(c)};export{S as LocalStorageUrlStorage,f as MemoryUrlStorage,g as RestrictionError,x as UploadControl,C as UploadError,F as createChunkedRestAdapter,M as createMultipartAdapter,O as createTusAdapter,U as createUpload,v as putFile,y as validateFile,E as validateFiles};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/client",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.50",
|
|
4
4
|
"description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
73
|
"@lunora/errors": "1.0.0-alpha.21",
|
|
74
|
-
"@visulima/storage-client": "1.0.
|
|
74
|
+
"@visulima/storage-client": "1.0.2"
|
|
75
75
|
},
|
|
76
76
|
"engines": {
|
|
77
77
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=["BAD_REQUEST","CONFLICT","COUNT_RLS_UNSUPPORTED","FORBIDDEN","INTERNAL_SERVER_ERROR","MASK_UNSUPPORTED","NOT_FOUND","NOT_IMPLEMENTED","RELATION_PREDICATE_UNSUPPORTED","TOO_MANY_REQUESTS","UNAUTHORIZED","UNPROCESSABLE"],o=new Set(e),t="CONFLICT",R=r=>r instanceof Error&&r.code===t,n=r=>r instanceof Error&&r.code==="FORBIDDEN",s=r=>r instanceof Error&&r.code==="UNAUTHORIZED",O=r=>r instanceof Error&&r.code==="TOO_MANY_REQUESTS",N=r=>{if(!(r instanceof Error))return;const{code:E}=r;return typeof E=="string"&&o.has(E)?E:void 0},i=r=>{const E=r?.data?.retryAfterMs;return typeof E=="number"&&Number.isFinite(E)?E:void 0};export{t as CONFLICT_ERROR_CODE,N as getErrorCode,i as getRetryAfterMs,R as isConflictError,n as isForbiddenError,O as isRateLimitedError,s as isUnauthorizedError};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
class r{swUrl;scope;#t=void 0;#r="unregistered";#i;#s=new Set;constructor(t){this.swUrl=t.swUrl,this.scope=t.scope??"/",this.#i=t.onStatusChange}get status(){return this.#r}get registration(){return this.#t}get active(){return this.#t?.active!==null&&this.#t?.active!==void 0}async register(){if(!("serviceWorker"in navigator))return this.#e("unsupported"),!1;this.#e("registering");try{this.#t=await navigator.serviceWorker.register(this.swUrl,{scope:this.scope}),this.#e("active"),navigator.serviceWorker.addEventListener("message",this.#n)}catch{return this.#e("error"),!1}return!0}async unregister(){if(!this.#t)return!1;navigator.serviceWorker.removeEventListener("message",this.#n);const t=await this.#t.unregister();return this.#t=void 0,this.#e("unregistered"),t}postMessage(t){const e=this.#t?.active;e&&e.postMessage(t)}onMessage(t){return this.#s.add(t),()=>{this.#s.delete(t)}}#e(t){this.#r=t,this.#i?.(t)}#n=t=>{for(const e of this.#s)try{e(t)}catch{}}}export{r as ClientServiceWorker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";const v=1024,d=f=>{const a=f.maxBuffer??v,r=[],u=[];let o=!1,t,s=!1;const n=()=>{const e=u.shift();if(!e)return!1;if(t)return e.reject(t),!0;if(r.length>0){const l=r.shift();return e.resolve({done:!1,value:l}),!0}return o?(e.resolve({done:!0,value:void 0}),!0):(u.unshift(e),!1)},i={complete(){if(!(o||t))for(o=!0;n(););},fail(e){if(!(o||t))for(t=e,r.length=0;n(););},push(e){if(!(o||t||s)){if(r.length>=a){i.fail(new h("STREAM_BACKPRESSURE",`stream buffer overflow (max=${a.toString()}); the consumer cannot keep up with the producer`));return}r.push(e),n()}}},c=()=>{if(!s){s=!0,o=!0,r.length=0;try{f.onCancel()}catch{}for(;n(););}};return{handle:i,iterable:{cancel:c,[Symbol.asyncIterator](){return{next(){if(t)return Promise.reject(t);if(r.length>0){const e=r.shift();return Promise.resolve({done:!1,value:e})}return o?Promise.resolve({done:!0,value:void 0}):new Promise((e,l)=>{u.push({reject:l,resolve:e})})},return(){return c(),Promise.resolve({done:!0,value:void 0})}}}}}};export{v as DEFAULT_MAX_BUFFER,d as createStream};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{w as D,y as j,a as H}from"./delta-merge-DoT5IpTP.mjs";import{s as b,a as N}from"./wire-codec-aTWt2XiW.mjs";import{t as I}from"./wire-key-Cb-kXfSh.mjs";import V from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as J}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as X}from"./TabCoordinator-CMFYQCL-.mjs";import{httpStream as Y}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Z,c as tt}from"./local-store-CGsgaEph.mjs";import{h as et,u as $,d as st,s as rt}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as it}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as nt,queryCacheKey as x}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as at}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-HXgW6BXq.mjs";const R=500,ot=(h,t)=>{if(h.size<t)return;const e=h.keys().next().value;e!==void 0&&h.delete(e)};class C{listeners=new Set;add(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(...t){const[e]=t;for(const s of this.listeners)try{s(e)}catch{}}clear(){this.listeners.clear()}}const ct="/_lunora/rpc",Q="/_lunora/rpc-batch",ht="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,O=h=>{for(let t=h.length-1;t>=0;t-=1)h[t]?.()},ut=(h,t)=>{for(const e of t)e.op==="delete"?h.delete(e.key):e.value!==void 0&&h.set(e.key,e.value)},dt="lunora-ping",lt=3e4,mt=1e4,pt=250,ft=64,yt="/_lunora/admin/shard-traffic",gt="/_lunora/admin/scheduled",bt="/_lunora/admin/scheduled/status",St="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",kt="/_lunora/admin/scheduled/dead",wt="/_lunora/admin/scheduled/dead/retry",Ct="/_lunora/admin/scheduled/dead/cancel",Tt="/_lunora/admin/workflows/instances",It="/_lunora/admin/workflows/instance",Ot="/_lunora/admin/workflows/status",L="/_lunora/admin/storage",Et="/_lunora/admin/storage/url",_t="/_lunora/admin/storage/buckets",Ft="/_lunora/admin/functions",Pt="/_lunora/admin/cron-jobs",At="/_lunora/admin/cron-jobs/run",xt="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Mt="/_lunora/admin/global/tables",Lt="/_lunora/admin/global/table",Kt="/_lunora/admin/global/facet",$t="/_lunora/admin/vector/indexes",qt="/_lunora/admin/vector/query",Qt="/_lunora/admin/logs/archive",Ut="/_lunora/admin/kv/namespaces",Wt="/_lunora/admin/kv/keys",K="/_lunora/admin/kv/value",Nt="/_lunora/admin/auth/users",Bt="/_lunora/admin/auth/sessions",zt="/_lunora/admin/auth/users/create",Gt="/_lunora/admin/auth/users/role",Dt="/_lunora/admin/auth/users/ban",jt="/_lunora/admin/auth/users/unban",Ht="/_lunora/admin/auth/users/password",Vt="/_lunora/admin/auth/users/remove",Jt="/_lunora/admin/auth/users/impersonate",Xt="/_lunora/admin/auth/sessions/revoke",Yt="/_lunora/admin/auth/sessions/revoke-all",Zt="/_lunora/admin/auth/capabilities",te="/_lunora/admin/auth/users/update",ee="/_lunora/admin/auth/accounts",se="/_lunora/admin/auth/accounts/unlink",re="/_lunora/admin/auth/passkeys",ie="/_lunora/admin/auth/passkeys/delete",ne="/_lunora/admin/auth/two-factor/disable",ae="/_lunora/admin/auth/organizations",oe="/_lunora/admin/auth/organizations/members",ce="/_lunora/admin/auth/organizations/invitations",he="/_lunora/admin/auth/organizations/members/remove",ue="/_lunora/admin/auth/organizations/invitations/cancel",de="/_lunora/admin/auth/config",le="/_lunora/admin/auth/organizations/create",me="/_lunora/admin/auth/organizations/update",pe="/_lunora/admin/auth/organizations/remove",fe="/_lunora/admin/auth/organizations/members/add",ye="/_lunora/admin/auth/organizations/members/invite",ge="/_lunora/admin/auth/organizations/members/role",be="/_lunora/admin/auth/organizations/teams",Se="/_lunora/admin/auth/organizations/teams/create",ve="/_lunora/admin/auth/organizations/teams/update",ke="/_lunora/admin/auth/organizations/teams/remove",we="/_lunora/admin/auth/organizations/teams/members",Ce="/_lunora/admin/auth/organizations/teams/members/add",Te="/_lunora/admin/auth/organizations/teams/members/remove",Ie="/_lunora/admin/auth/organizations/roles",Oe="/_lunora/admin/auth/organizations/roles/create",Ee="/_lunora/admin/auth/organizations/roles/update",_e="/_lunora/admin/auth/organizations/roles/remove",Fe="/api/auth",Pe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[r,i]of Object.entries(t))i!==void 0&&i!==""&&e.set(r,String(i));const s=e.toString();return s===""?h:`${h}?${s}`},Ae=[H],p=h=>h??"",B=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,r=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??t}},xe=h=>{const{code:t,messageText:e}=B(h,"stream error");return t===void 0?new Error(e):new m(t,e)},W=h=>{const{code:t,messageText:e}=B(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Re=new TextDecoder,Me=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Re.decode(h)},g=(h,t)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(t)),!0}catch{return!1}},T=h=>{const t=new Error(h.message??"request failed");return t.code=h.code,h.data!==void 0&&(t.data=b(h.data)),h.hint!==void 0&&(t.hint=h.hint),h.docsUrl!==void 0&&(t.docsUrl=h.docsUrl),t},k=(h,t)=>{try{return N(h)}catch(e){const s=e instanceof Error?e.message:String(e);throw new TypeError(`LunoraClient: cannot encode ${t} — ${s}`,e instanceof Error?{cause:e}:void 0)}},Le=(h,t)=>{const e=Array.from({length:t});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=t)continue;const r=s.body;e[s.id]=r&&"error"in r&&r.error?{error:T(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Ke=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),$e=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(t,e){return{defaultValue:e,key:t}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(t){this.url=t.url,this.wsUrl=t.wsUrl??v(U(t.url),ht),this.wsToken=t.wsToken;const e=t.authBasePath??Fe;this.authBasePath=e.endsWith("/")?e.slice(0,-1):e,this.fetchImpl=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=t.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=t.bookmarkStorage??V(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??lt,this.connectTimeoutMs=t.connectTimeoutMs??mt,this.defaultConnectionContext=t.connectionContext,this.persistence=it(t.persistence,t.outbox===void 0),this.persistenceVersion=t.persistenceVersion,this.queryCache=nt(t.queryCache),this.onPersistenceError=t.offlineQueue?.onPersistenceError,this.clientQueryStore=new J,t.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,t.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=$e),this.offlineQueue=new et(t.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${$()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(t,e){const s=this.authToken!==t,r=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const i=this.identityFingerprint();if(i!==r&&(s?this.rejectQueuedForIdentityChange():(this.restampQueuedIdentity(r,i),this.restampWatermarks(r,i)),this.tabCoordinator)){const n=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),n&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(t)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(t){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(t??"")??0}async callMutator(t,e,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new m("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"",n=this.identityFingerprint();let a;const o=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:c=>{a=c}});if(a!==void 0&&a>(this.clientWatermarks.get(n??"")?.get(i)??0)){let c=this.clientWatermarks.get(n??"");c===void 0&&(c=new Map,this.clientWatermarks.set(n??"",c)),c.set(i,a)}return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(t){return this.authTokenListeners.add(t)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const t={};this.authToken&&(t.authorization=`Bearer ${this.authToken}`);try{const e=await this.fetchImpl(v(this.url,`${this.authBasePath}${Pe}`),{credentials:"include",headers:t,method:"GET"});return e.ok?(await e.json())?.user??null:null}catch{return null}}setWsToken(t){if(this.wsToken!==t){this.wsToken=t;for(const e of this.connections.values())if(e.socket)try{e.socket.close()}catch{}}}setConnectionContext(t,e={}){const s=p(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=p(e.shardKey),r={context:t},i=this.connectionContextHolders.get(s);i?i.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let n=!1;return()=>{if(n)return;n=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const r=p(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(t);const a=n===void 0;if(n||(n=new Set,i.set(t,n)),n.add(e),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:t,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&g(u,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{data:k(e??null,`whisper data for topic '${t}'`),topic:t,type:"whisper"})}onTokenExpired(t){return this.tokenExpiredListeners.add(t)}connectionStatus(){return this.computeStatus()}onConnectionStatus(t){const e=this.statusListeners.add(t);return t(this.computeStatus()),e}pendingCount(){return this.offlineQueue.size}debug(){const t=[],e=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...e?.keys()??[]]);for(const i of s){const n=this.connections.get(i);t.push({confirmedMutationWatermark:e?.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}const r=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(const i of this.shapeSubscriptions.values())r.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:r.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(t){const e=this.pendingChangeListeners.add(t);return t(this.offlineQueue.size),e}onMutationSettled(t){return this.mutationSettledListeners.add(t)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(t){return this.clientQueryStore.get(t)}setClientQuery(t,e){this.clientQueryStore.set(t,e)}subscribeClientQuery(t,e){return this.clientQueryStore.subscribe(t,e)}resetClientQuery(t){this.clientQueryStore.reset(t)}snapshotPrecondition(t,e,s){const r=this.peekActiveQueryValue(t.__lunoraRef,e,s),i=r===void 0?void 0:I(r);return()=>{const n=this.peekActiveQueryValue(t.__lunoraRef,e,s);return i===void 0&&n===void 0?!0:i===void 0||n===void 0?!1:I(n)===i}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const r=I(e),i=x(t,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQueryValue(t,e,s){const r=w.key(t,e,s);return this.subscriptions.get(r)?.lastValue}async query(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey,{attachBookmark:!0})}async batch(t){if(this.assertOpen(),!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args??{},`args for batch call '${i.fn.__lunoraRef}'`),functionPath:i.fn.__lunoraRef,id:n,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{throw new m("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||r.error&&!r.results)throw r.error?T(r.error):new m("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(t[i.id]?.shardKey,n)}return Le(r.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const r=e,i=s.mutationId??$(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,n);const{hasSocket:o,wasEverConnected:c,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:d}=this.offlineQueue,l=c||d,y=this.WebSocketImpl!==void 0&&l;if(u!=="open"&&!o&&y||u==="connecting"&&l)return this.enqueueOfflineMutation(t,r,s.shardKey,i,a,n,s.precondition);try{let S;const G=await this.rpc(t.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:_=>{S=_}});for(const _ of n)_(S);return G}catch(S){throw O(a),S}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=e.length;let a=0,o=0;for(let c=0;c<n;c+=r){const u=e.slice(c,c+r),d=o;await this.mutation(t,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(d)}`},shardKey:s.shardKey}),o+=1,a+=u.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(yt,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(gt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(bt,"GET");return{backlog:t.backlog??0,inFlight:t.inFlight??0,pools:t.pools??[]}}async cancelScheduledJob(t){return this.assertOpen(),{cancelled:(await this.adminFetch(vt,"POST",{id:t})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(kt,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(wt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(Ct,"POST",{id:t})).removed===!0}}async listWorkflowInstances(t){this.assertOpen();const e=new URLSearchParams({name:t.name});t.status!==void 0&&e.set("status",t.status),t.page!==void 0&&e.set("page",String(t.page)),t.perPage!==void 0&&e.set("perPage",String(t.perPage));const s=await this.adminFetch(`${Tt}?${e.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??t.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(t){this.assertOpen();const e=new URLSearchParams({id:t.id,name:t.name}),s=await this.adminFetch(`${It}?${e.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??t.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(t){return this.assertOpen(),{status:(await this.adminFetch(Ot,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=v(U(this.url),St),s=q(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||(i=setTimeout(u,s.next()))},o=d=>{if(n||this.WebSocketImpl===void 0)return;const l=d===void 0?e:`${e}?token=${encodeURIComponent(d)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const S=JSON.parse(typeof y.data=="string"?y.data:"");S.type==="jobs"&&Array.isArray(S.records)&&t(S.records)}catch{}},onOpen:()=>{s.reset()}})},c=async d=>{let l;try{l=await d()}catch{a();return}o(l)},u=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:d}=this;if(typeof d=="function"){c(d).catch(()=>{});return}o(d)};return u(),()=>{n=!0,i!==void 0&&clearTimeout(i),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Pt,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(At,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(xt,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(L,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),s=await this.adminFetch(e,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(t,e){this.assertOpen();const s=`${L}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${L}?key=${encodeURIComponent(t.key)}${M(t.bucket)}`,s=await this.adminFetch(e,"PUT",t.body,t.contentType);return{etag:s.etag,key:s.key??t.key}}async signedStorageUrl(t,e){this.assertOpen();const s=e?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Et}?key=${encodeURIComponent(t)}${r}${M(e?.bucket)}`,n=await this.adminFetch(i,"GET");if(typeof n.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return n.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Mt,"GET")}async readGlobalTablePage(t){this.assertOpen();const e=new URLSearchParams({table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.offset!==void 0&&e.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Lt}?${e.toString()}`,"GET")}async facetGlobalColumn(t){this.assertOpen();const e=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Kt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($t,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch(qt,"POST",t)).matches??[]}async queryLogArchive(t={}){this.assertOpen();const e=await this.adminFetch(Qt,"POST",t);return{nextCursor:e.nextCursor,rows:e.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Ut,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Wt,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await this.adminFetch(e,"GET")}async getKvValue(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch(K,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Nt,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminFetch(e,"GET")}async createAuthUser(t){return await this.adminFetch(zt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(Gt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(jt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(Ht,"POST",t)}async removeAuthUser(t){await this.adminFetch(Vt,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Jt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Xt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Yt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Zt,"GET")}async updateAuthUser(t){return await this.adminFetch(te,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(ee,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(se,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(re,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){await this.adminFetch(ie,"POST",t)}async disableAuthTwoFactor(t){await this.adminFetch(ne,"POST",t)}async listAuthOrganizations(t={}){return await this.adminFetch(f(ae,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(ce,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(he,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(ue,"POST",t)}async getAuthConfig(){return await this.adminFetch(de,"GET")}async createAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(me,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(pe,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(ye,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ge,"POST",t)}async listAuthOrgTeams(t){const e=f(be,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(Se,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(ve,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(ke,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(we,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(Ce,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Te,"POST",t)}async listAuthOrgRoles(t){const e=f(Ie,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Ee,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(_e,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Bt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,r={}){this.assertOpen();const i=e??{},n=w.key(t.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const d=`sub_${this.nextSubId.toString()}`,l=I(i),y=this.takeHydratedCache(t.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:d,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:r.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),c&&u.errorCallbacks.delete(c),r.onCheckpoint&&u.checkpointCallbacks.delete(r.onCheckpoint),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.subscriptions.remove(u))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:t.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:t.args===void 0?void 0:k(t.args,`shape args for '${t.name}'`)};return this.shapeSubscriptions.set(r,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(i.shardKey,r,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new m("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=e??{},{handle:a,iterable:o}=at({maxBuffer:s.maxBuffer,onCancel:()=>{const d=this.getConnection(i);d&&g(d,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(i);const c=this.getConnection(i),u={id:r,query:{args:k(n,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:i},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:u,shardKey:i}),!(c?.wsState==="open"&&g(c,u))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=ft;){const d=c.pendingStreams.shift()?.id,l=d?this.streams.get(d):void 0;l&&(l.handle.fail(new m("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(d))}c.pendingStreams.push(u)}return o}httpStream(t,e,s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Y(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const t of this.streams.values())t.handle.fail(new m("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const t of this.connections.values())this.teardownConnection(t);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new m("INTERNAL","LunoraClient is closed")}teardownConnection(t){if(t.reconnectTimer!==void 0&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),this.stopHeartbeat(t),t.socket){try{t.socket.close()}catch{}t.socket=void 0}t.wsState="closed"}createTabCoordinator(){const t=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new X({channelName:t,onBecomeLeader:()=>{for(const e of this.subscriptions.all())this.ensureSocket(e.shardKey),this.sendSubscribeIfOpen(e);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[e,s]of this.connections)this.teardownConnection(s),this.connections.delete(e);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(e,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),F(a,r)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const r=this.subscriptions.get(e);r&&E(r.errorCallbacks,s)},onSubscriptionSettled:(e,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(t,e,s,r,i,n,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:e,clientId:this.clientId,functionPath:t.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(u){throw O(i),u instanceof Error?u:new Error(String(u))}for(const u of n)u(void 0);return}return new Promise((c,u)=>{const d={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of n)y(l)},reject:l=>{this.queuedIdentities.delete(r),O(i),u(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(d),this.queuedOfflineShardKeys.add(s),d.id!==void 0&&this.queuedIdentities.set(d.id,o)})}async hydratePersistedQueue(){try{const t=await this.offlineQueue.hydrate();for(const e of t)this.queuedOfflineShardKeys.add(e),this.ensureSocket(e)}catch{}}hydrateAsOutboxLeader(){const t=()=>{this.hydratePersistedQueue().catch(()=>{})},e=globalThis.navigator?.locks;if(!e){t();return}e.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||t(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(t)}async hydrateQueryCache(){if(this.queryCache)try{const t=await this.queryCache.load();for(const{key:e,...s}of t){if(st(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const r=x(t,e,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=x(t.fn.__lunoraRef,t.argsKey,t.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:t.serverCursor,ts:Date.now(),value:e,...t.serverEpoch===void 0?{}:{serverEpoch:t.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},pt)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:t}=this;if(!t){this.pendingCacheWrites.clear();return}const e=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(e.map(([s,r])=>t.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const t=[...this.connections.values()];return t.length===0?"idle":t.some(e=>e.wsState==="open")?"connected":t.some(e=>e.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const t=this.computeStatus();t!==this.lastStatus&&(this.lastStatus=t,this.statusListeners.emit(t),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(t,this.identityFingerprint()))}emitItemSettled(t,e,s){this.mutationSettledListeners.emit({args:t.args,code:s===void 0?void 0:s.code,error:s,functionPath:t.functionPath,hadAwaiter:t.liveAwaiter??!1,id:t.id??"",shardKey:t.shardKey,status:e})}applyOptimisticUpdates(t,e,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Z(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(t,e,s,r,i){const{confirms:n,rollbacks:a,store:o}=tt(this.subscriptions,s);try{t(o,e)}catch{O(a);return}r.push(...a),i.push(...n)}getConnection(t){return this.connections.get(p(t))}sendOrQueueUnsubscribe(t,e,s){const r=this.getConnection(t);r&&!g(r,{id:e,type:s})&&r.pendingUnsubscribes.push({id:e,type:s})}connectionGateState(t){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const e=this.getConnection(t);return{hasSocket:e?.socket!==void 0,wasEverConnected:e?.wasEverConnected??!1,wsState:e?.wsState??"idle"}}getOrCreateConnection(t){const e=p(t);let s=this.connections.get(e);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:q(this.reconnectOptions),reconnectTimer:void 0,shardKey:t,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(e,s)),s}wsUrlFor(t,e){const s=[];if(t!==void 0&&s.push(`shard=${encodeURIComponent(t)}`),e!==void 0&&s.push(`token=${encodeURIComponent(e)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(t,e){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(e));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),t.mutationId&&(s["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(s["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(s["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(t,e,s,r={}){if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(v(this.url,ct),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const o=n.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await n.json()}catch{const o=n.statusText?` ${n.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${n.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!n.ok){const o=n.statusText?` ${n.statusText}`:"";throw new m("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(t,e,s,r){if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const n=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:n?(a=s,r!==void 0&&(i["content-type"]=r)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(v(this.url,t),{body:a,headers:i,method:e});let c;try{c=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if(typeof c=="object"&&c!==null&&"error"in c){const u=c.error,d=new Error(u.message??"admin request failed");throw d.code=u.code,d}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}return c}effectiveConnectionContext(t){const e=this.connectionContextHolders.get(t);return e&&e.length>0?e[e.length-1]?.context:this.connectionContexts.get(t)??this.defaultConnectionContext}refreshConnectionContext(t){const e=this.connections.get(t);e?.wsState==="open"&&this.sendConnectEnvelope(e)}sendConnectEnvelope(t){const e=this.effectiveConnectionContext(p(t.shardKey));g(t,{caps:Ae,clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())p(e.shardKey)===p(t)&&this.sendShapeSubscribeIfOpen(e)}ensureSocket(t){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const e=this.getOrCreateConnection(t);if(!(e.wsState==="open"||e.wsState==="connecting")){if(e.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(e,t,this.wsToken).catch(()=>{});return}this.openSocket(e,t,this.wsToken)}}async openSocketWithProvidedToken(t,e,s){let r;try{r=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,r)}openManagedSocket(t,e,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new m("INTERNAL","no WebSocket implementation available");const n=new i(e);t.socket=n;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===n&&(t.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{t.socket===n&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(t,o))}),n.addEventListener("message",c=>{t.socket===n&&(t.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{t.socket===n&&o(c)}),n.addEventListener("error",()=>{t.socket===n&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:r=>{this.handleServerMessage(r.data,e)},onOpen:()=>{t.wsState="open",t.wasEverConnected=!0,t.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(t),this.markShardPendingAck(e);for(const i of this.subscriptions.all())p(i.shardKey)===p(e)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const i=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:n,type:a}of i)g(t,{id:n,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const i=t.pendingStreams;t.pendingStreams=[];for(const n of i)g(t,n)}const r=this.whisperHandlers.get(p(e));if(r)for(const i of r.keys())g(t,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(e).catch(()=>{})}})}handleDisconnect(t){if(this.closed||t.wsState==="idle"||t.wsState==="closed")return;this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket=void 0,t.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(t.shardKey);const e=new Set((t.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(p(i.shardKey)!==p(t.shardKey)||e.has(r))){if(i.durable){const n={...i.message,sinceChunk:i.lastSeq};i.message=n,t.pendingStreams=[...(t.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=t.reconnect.next();t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,this.ensureSocket(t.shardKey)},s)}startHeartbeat(t,e){this.stopHeartbeat(t),!(this.heartbeatIntervalMs<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;const{socket:s}=t;if(Date.now()-t.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}e();return}try{s.send(dt)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(t){t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)}markShardPendingAck(t){const e=p(t);for(const s of this.subscriptions.all())p(s.shardKey)===e&&(s.acked=!1)}sendSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);if(e?.wsState!=="open"||t.acked)return;const s=t.fn.__lunoraTable??t.fn.__lunoraRef;g(e,{id:t.id,query:{args:N(t.args),functionPath:t.fn.__lunoraRef,table:s,...t.serverCursor===void 0?{}:{sinceSeq:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);e?.wsState==="open"&&g(e,{id:t.id,shape:{name:t.name,...t.wireArgs===void 0?{}:{args:t.wireArgs}},type:"shape_subscribe",...t.serverCursor===void 0?{}:{sinceCheckpoint:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}})}handleServerMessage(t,e){const s=Me(t);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,id:n,seq:a}=r,o=this.streams.get(n);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,e);break}}}handleErrorMessage(t){if(t.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:e}=t,s=e===void 0?void 0:this.streams.get(e);if(s&&e!==void 0){s.handle.fail(xe(t)),this.streams.delete(e);return}const r=e===void 0?void 0:this.subscriptions.getById(e);if(r){E(r.errorCallbacks,W(t));return}const i=e===void 0?void 0:this.shapeSubscriptions.get(e);i&&E(i.errorCallbacks,W(t))}handlePokeStart(t){ot(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(t.pokeId,{baseCheckpoint:t.baseCheckpoint,epoch:t.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(t){const e=this.pokeBuffers.get(t.pokeId);if(!e)return;const s=e.parts.get(t.shapeId)??[];for(const r of t.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.value)});e.parts.set(t.shapeId,s),t.lastMutationId!==void 0&&e.lastMutationId.set(t.shapeId,t.lastMutationId)}handlePokeEnd(t){const e=this.pokeBuffers.get(t.pokeId);if(e){this.pokeBuffers.delete(t.pokeId);for(const[s,r]of e.parts){const i=this.shapeSubscriptions.get(s);if(!i)continue;const n=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,a=e.baseCheckpoint!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==e.baseCheckpoint;if(n||a){i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,this.emitShapeRows(i),this.sendShapeSubscribeIfOpen(i);continue}ut(i.rows,r),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const o=e.lastMutationId.get(s);o!==void 0&&(i.lastMutationId=o),this.emitShapeRows(i),i.onCheckpoint?.({checkpoint:i.serverCursor,mutationId:i.lastMutationId})}}}emitShapeRows(t){const e=[...t.rows.values()];for(const s of t.callbacks)try{s(e)}catch{}}handleDataMessage(t){const{id:e}=t,s=e?this.subscriptions.getById(e):void 0;if(!s)return;const r=this.resolveDataPayload(t,s);if(s.serverBase=r,t.cursor!==void 0&&(s.serverCursor=t.cursor),t.epoch!==void 0&&(s.serverEpoch=t.epoch),t.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,t.lastMutationId);for(const i of s.checkpointCallbacks)i({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),F(s,s.serverCursor),P(s,A(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(t){const e=this.subscriptions.getById(t.id);e&&this.ackAndAdvanceCursor(e,t.cursor,t.epoch)}handleSettledMessage(t){const e=this.subscriptions.getById(t.id);if(e){this.ackAndAdvanceCursor(e,t.cursor,t.epoch),t.lastMutationId!==void 0&&(e.lastMutationId=t.lastMutationId);for(const s of e.checkpointCallbacks)s({checkpoint:e.serverCursor,mutationId:e.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=w.key(e.fn.__lunoraRef,e.args,e.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,e.serverCursor,e.serverEpoch,e.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(t,e,s){t.acked=!0,(e!==void 0&&e!==t.serverCursor||s!==void 0&&s!==t.serverEpoch)&&(e!==void 0&&(t.serverCursor=e),s!==void 0&&(t.serverEpoch=s),this.persistQueryValue(t),F(t,t.serverCursor)&&P(t,A(t.serverBase,t.optimisticLayers)))}resolveDataPayload(t,e){if("data"in t&&t.data!==void 0)return b(t.data);const s=b(t.delta);if(D(s)&&e.serverBase!==void 0){const r=j(e.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(p(e))?.get(t.topic);if(!s)return;const r=b(t.data);for(const i of s)try{i(r,t.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(t){const e=this.streams.get(t);if(e){e.handle.complete(),this.streams.delete(t);return}const s=this.subscriptions.getById(t);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(t){t&&this.persistence?.remove(t).catch(e=>{rt(this.onPersistenceError,"remove",e,t)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const t=this.authToken;return t===null?null:this.hashToken(t)}hashToken(t){let e=2166136261,s=5381;for(let r=0;r<t.length;r+=1){const i=t.charCodeAt(r);e^=i,e=Math.imul(e,16777619),s=Math.imul(s,33)+i}return`${t.length.toString(36)}:${(e>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(t){if(t===null||t.startsWith("subj:"))return!1;const e=this.authToken;return e===null?!1:this.hashToken(e)===t}rejectQueuedForIdentityChange(){const t=this.offlineQueue.drain();for(const e of t){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",e.reject(s),this.emitItemSettled(e,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(t,e){for(const[s,r]of this.queuedIdentities)r===t&&this.queuedIdentities.set(s,e)}restampWatermarks(t,e){const s=t??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const i=e??"",n=this.clientWatermarks.get(i);if(n===void 0)this.clientWatermarks.set(i,r);else for(const[a,o]of r)n.set(a,o)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const t of this.queuedOfflineShardKeys)this.flushOfflineQueue(t).catch(()=>{})}async flushOfflineQueue(t){const e=this.offlineQueue.drainConflict();for(const c of e){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",u)}const s=p(t),r=this.offlineQueue.drain(c=>p(c.shardKey)===s);if(r.length===0)return;const i=this.identityFingerprint(),n=[];for(const c of r)this.passesReplayIdentityGate(c,i)&&n.push(c);if(n.length===0)return;const a=this.encodableOrSettleTerminal(n);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=R){const u=a.slice(c,c+R),d=await this.replayBatched(u);if(o.push(...d.requeue),d.stop){o.push(...a.slice(c+R));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(t){const e=[];for(const s of t)try{k(s.args,`args for '${s.functionPath}'`),e.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),r=s===void 0?t.identity:s;if(r!==void 0&&r!==e&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",t.reject(i),this.emitItemSettled(t,"rejected",i),!1}return this.queuedIdentities.delete(t.id??""),!0}settleReplaySuccess(t,e,s){this.unpersist(t.id),this.recordShardCursor(t.shardKey,s),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}cursorKeyFor(t){return t??this.defaultShardKey??""}learnDefaultShardKey(t,e){const s=t.headers.get("x-lunora-shard-key");if(s===null||e!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(t,e){if(typeof e!="number")return;const s=this.cursorKeyFor(t);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,e))}settleReplayTerminal(t,e){this.unpersist(t.id),t.reject(e),this.emitItemSettled(t,"rejected",e)}async replaySequential(t){for(let e=0;e<t.length;e+=1){const s=t[e];if(s)try{let r;const i=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:n=>{r=n}});this.settleReplaySuccess(s,i,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);continue}this.offlineQueue.requeue(t.slice(e));return}}}async replayBatched(t){if(!this.fetchImpl)return{requeue:t,stop:!0};let e;try{e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args,`args for '${i.functionPath}'`),functionPath:i.functionPath,id:n,clientId:i.clientId??this.clientId,mutationId:i.id,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:t,stop:!0}}const s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{return{requeue:t,stop:!0}}if(!r.results){if(r.error){const i=T(r.error);for(const n of t)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,r.results),stop:!1}}settleReplayBatchSlots(t,e){const s=new Map;for(const i of e)typeof i.id=="number"&&i.body!==void 0&&s.set(i.id,i.body);const r=[];for(const[i,n]of t.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Ke.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,T(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{h as s,u as o,s as t}from"./offline-queue-CKMw-5rF.mjs";export{s as OfflineQueue,o as nextId,t as reportPersistenceError};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const i=n=>{let e=-1;for(const r of n)r.seq>e&&(e=r.seq);return e},l=2,f=(n,e)=>{const r=e.filter(t=>t.role==="user"),c=i(e),o=new Set;return n.filter(t=>{for(const[s,a]of r.entries())if(!o.has(s)&&a.seq>t.maxDurableSeqAtSend&&a.content===t.content)return o.add(s),!1;return c-t.maxDurableSeqAtSend<2})};export{l as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,i as maxSeq,f as reconcileOptimistic};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const E="skip",b=e=>e instanceof Error?{message:e.message}:{message:String(e)},f=(e,n,s,o,c={})=>{if(s===E)return o.onReset?.(),()=>{};let t=!1;const a=r=>{t||o.onError?.(r)},u=o.onError?a:void 0;let i;try{i=e.subscribe(n,s,r=>{t||o.onData(r)},{onError:u,shardKey:c.shardKey})}catch(r){if(!o.onError)throw r;return a(b(r)),()=>{t=!0}}return()=>{t=!0,i()}};export{E as SKIP,f as createQuerySubscription,b as toSubscriptionError};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as a}from"./wire-key-Cb-kXfSh.mjs";class y{static key(e,t,s){return`${e}::${a(t)}::${s??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(y.key(e.fn.__lunoraRef,e.args,e.shardKey),e),this.byId.set(e.id,e)}remove(e){const t=y.key(e.fn.__lunoraRef,e.args,e.shardKey);this.byKey.get(t)===e&&this.byKey.delete(t),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}}export{y as SubscriptionRegistry};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let d=0;const n="lunora-bridge",o=1e3,h=3e3;class c{bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(d+=1,this.tabId=`tab_${String(d)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??o,this.leaderTimeout=e.leaderTimeout??h,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??n),this.bc.addEventListener("message",t=>{this.handleMessage(t.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,t,a,i,s){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:t,...a===void 0?{}:{cursor:a},...i===void 0?{}:{epoch:i},...s===void 0?{}:{identity:s}})}broadcastSubscriptionError(e,t){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:t})}broadcastSubscriptionSettled(e,t,a,i,s,r){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...t===void 0?{}:{cursor:t},...a===void 0?{}:{epoch:a},...i===void 0?{}:{lastMutationId:i},...s===void 0?{}:{clientId:s},...r===void 0?{}:{identity:r}})}broadcastConnectionStatus(e,t){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...t===void 0?{}:{identity:t}})}broadcast(e){this.bc?.postMessage(e)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()});return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}}export{c as TabCoordinator};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const a=new Map,u=new Proxy({},{get(c,t){const e=a.get(t);if(e)return e;const r=new Map,o=new Proxy({},{get(i,n){const s=r.get(n);if(s)return s;const g={__lunoraRef:`${String(t)}:${String(n)}`};return r.set(n,g),g}});return a.set(t,o),o}});export{u as anyApi};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{y as e,w as l}from"./delta-merge-DoT5IpTP.mjs";export{e as applyDelta,l as isMutationDelta};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const y="lunora:offline-mutations",m=c=>{const{storage:n}=c,a=c.key??y;let o=Promise.resolve();const r=t=>{const e=o.then(t,t);return o=e.then(()=>{},()=>{}),e},s=async()=>{const t=await n.getItem(a);if(t===null)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}},i=t=>n.setItem(a,JSON.stringify(t));return{append:t=>r(async()=>{const e=await s();e.push(t),await i(e)}),clear:()=>r(()=>n.removeItem(a)),load:()=>r(s),remove:t=>r(async()=>{const e=await s(),l=e.filter(u=>u.id!==t);l.length!==e.length&&await i(l)})}};export{m as createAsyncStoragePersistence};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const l=()=>{let e=null;return{get:()=>e,set:t=>{e=t}}};export{l as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{c as n,b as m,D as y}from"./idb-utility-C-DR8nG1.mjs";const D=()=>{const r=new Map,t=e=>({args:{...e.args},functionPath:e.functionPath,id:e.id,identity:e.identity,shardKey:e.shardKey});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())}},f="lunora-outbox",p="offline-mutations",c="by_id",x=(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??f,s=r.storeName??p,l=y(t,e,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(c,"id",{unique:!0})}),o=m(l,s);return{append:async a=>{await o("readwrite",i=>n(i.add(a)))},clear:async()=>{await o("readwrite",a=>n(a.clear()))},load:async()=>o("readonly",a=>n(a.getAll())),remove:async a=>{await o("readwrite",async i=>{const d=await n(i.index(c).getKey(a));d!==void 0&&await n(i.delete(d))})}}},P=(r,t=!0)=>{if(r!==!1){if(r)return r;if(!(!t||typeof indexedDB>"u"))return x()}};export{D as createInMemoryPersistence,x as createIndexedDbPersistence,P as resolvePersistenceAdapter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{c as i,b as x,D}from"./idb-utility-C-DR8nG1.mjs";const k=(a,o,t)=>`${a}::${o}::${t??""}`,v=500,P=(a={})=>{const o=a.maxEntries??v,t=new Map,c=e=>({...e,value:structuredClone(e.value)}),l=()=>{if(t.size<=o)return;const e=[...t.values()].toSorted((s,y)=>s.ts-y.ts);for(const s of e){if(t.size<=o)break;t.delete(s.key)}};return{clear:()=>(t.clear(),Promise.resolve()),load:()=>Promise.resolve([...t.values()].map(e=>c(e))),put:(e,s)=>(t.set(e,c({...s,key:e})),l(),Promise.resolve()),remove:e=>(t.delete(e),Promise.resolve())}},b="lunora-query-cache",h="query-cache",f="by_ts",C=1,I=(a={})=>{const o=a.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!o)throw new p("INTERNAL","createIndexedDbQueryCache: no IndexedDB available — pass `indexedDB` or use createInMemoryQueryCache()");const t=a.databaseName??b,c=a.storeName??h,l=a.maxEntries??v,e=D(o,t,C,r=>{r.objectStoreNames.contains(c)||r.createObjectStore(c,{keyPath:"key"}).createIndex(f,"ts",{unique:!1})}),s=x(e,c),y=async r=>{let n=await i(r.count())-l;n<=0||await new Promise((d,w)=>{const u=r.index(f).openCursor();u.addEventListener("success",()=>{const m=u.result;if(!m||n<=0){d();return}m.delete(),n-=1,m.continue()}),u.addEventListener("error",()=>{w(u.error??new Error("IndexedDB eviction failed"))})})};return{clear:async()=>{await s("readwrite",r=>i(r.clear()))},load:async()=>s("readonly",r=>i(r.getAll())),put:async(r,n)=>{await s("readwrite",async d=>{await i(d.put({...n,key:r})),await y(d)})},remove:async r=>{await s("readwrite",n=>i(n.delete(r)))}}},N=a=>{if(a!==!1){if(a)return a;if(!(typeof indexedDB>"u"))return I()}};export{P as createInMemoryQueryCache,I as createIndexedDbQueryCache,k as queryCacheKey,N as resolveQueryCacheAdapter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as t}from"./local-store-CGsgaEph.mjs";import"./SubscriptionRegistry-HXgW6BXq.mjs";export{t as createLocalStore};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const i=(o,s,r)=>{let t=0;return async(a,c)=>{t+=1,r.setPending(!0);try{const n=await o.mutation(s,a,c);return r.setResult(n),n}catch(n){const e=n instanceof Error?n:new Error(String(n));throw r.setError(e),e}finally{t-=1,r.setPending(t>0)}}};export{i as createMutationRunner};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const c=(i,t)=>{let e=0,r=0;return{mutate:async a=>{r+=1;const o=r;e+=1,t.setPending(!0);try{await i(a).isPersisted.promise,o===r&&t.setError(void 0)}catch(n){const s=n instanceof Error?n:new Error(String(n));throw o===r&&t.setError(s),s}finally{e-=1,t.setPending(e>0)}},reset:()=>{t.setError(void 0)}}};export{c as createMutatorRunner};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s=(e={},o=Math.random)=>{const a=e.initialDelayMs??250,c=e.maxDelayMs??3e4,i=e.jitter??!0;let t=0;return{next(){const n=Math.min(c,a*2**t);if(t+=1,!i)return n;const r=n/2;return Math.floor(r+o()*(n-r))},reset(){t=0}}};export{s as createReconnect};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraClient as r}from"./LunoraClient-M_ArXnWT.mjs";const o=t=>{const e=new r({fetch:t.fetch,url:t.url});return t.token!==void 0&&e.setAuthToken(t.token),e};export{o as createServerClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as n}from"./wire-key-Cb-kXfSh.mjs";const d=(r,t,i,u)=>{const a=r.peekActiveQueryValue(t.__lunoraRef,i,u),e=a===void 0?void 0:n(a);return()=>{const o=r.peekActiveQueryValue(t.__lunoraRef,i,u);return e===void 0&&o===void 0?!0:e===void 0||o===void 0?!1:n(o)===e}};export{d as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as a}from"./wire-codec-aTWt2XiW.mjs";const u="_id",c="_creationTime",p="page",h="pageDelta",d=r=>{if(Array.isArray(r))return r;if(a(r)&&Array.isArray(r[p]))return r[p]},g=r=>{let t;for(const e of r){const o=e[c];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},A=(r,t)=>{const e=t[c];if(typeof e!="number")return r.length;const o=g(r);for(const[s,f]of r.entries()){const n=f[c];if(typeof n=="number"&&(o?n<e:n>e))return s}return r.length},b=r=>{if(typeof r!="object"||r===null)return;const t=r[u];return typeof t=="string"?t:void 0},k=r=>{if(typeof r!="object"||r===null)return!1;const t=r;return typeof t.key=="string"&&typeof t.table=="string"&&(t.op==="insert"||t.op==="update"||t.op==="delete")},m=(r,t)=>{const e=[];for(const i of r){if(b(i)===void 0)return;e.push(i)}const{key:o,op:s,row:f}=t;if(s==="delete"){const i=e.filter(y=>y[u]!==o);return i.length===e.length?[...e]:i}if(f===void 0)return;const n=[...e],l=e.findIndex(i=>i[u]===o);return l===-1?n.splice(A(e,f),0,f):n[l]=f,n},$=(r,t)=>{const e=d(r);if(e===void 0)return;const o=m(e,t);return o===void 0||Array.isArray(r)?o:{...r,[p]:o}};export{h as a,k as w,$ as y};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const a=e=>e instanceof Headers?e:e.headers,r=async(e,s)=>{const n=a(e);return await s.api.getSession({headers:n})??null};export{r as getServerSession};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{createStream as h}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";const m=/^ /u,u=t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),p=t=>{let r="";const e=[];for(const a of t.split(`
|
|
2
|
-
`))a.startsWith("event:")?r=a.slice(6).replace(m,""):a.startsWith("data:")&&e.push(a.slice(5).replace(m,""));return{data:e.join(`
|
|
3
|
-
`),event:r}},S=(t,r,e)=>{const a=r.params??{},s=t.path.split("/").map(l=>{if(!l.startsWith(":"))return l;const i=l.slice(1),d=a[i];if(d===void 0)throw new f("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${i}" for route ${t.path}`);return encodeURIComponent(u(d))}).join("/"),c=new URLSearchParams;for(const[l,i]of Object.entries(r.searchParams??{}))i!==void 0&&c.set(l,u(i));const n=c.toString();return`${e.endsWith("/")?e.slice(0,-1):e}${s}${n===""?"":`?${n}`}`},T=(t,r)=>{if(t.event==="complete")return r.complete(),!0;if(t.event==="error"){let e={};try{e=JSON.parse(t.data)}catch{}const a=typeof e.message=="string"?e.message:"stream error",s=typeof e.code=="string"?e.code:"HTTP_STREAM_ERROR";return r.fail(new f(s,a)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{r.push(JSON.parse(t.data))}catch{return r.fail(new f("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},g=async(t,r)=>{const e=t.getReader(),a=new TextDecoder;let s="";const c=()=>{let n=s.indexOf(`
|
|
4
|
-
|
|
5
|
-
`);for(;n!==-1;){const l=p(s.slice(0,n));if(s=s.slice(n+2),T(l,r))return!0;n=s.indexOf(`
|
|
6
|
-
|
|
7
|
-
`)}return!1};for(;;){const{done:n,value:l}=await e.read();if(n)break;if(s+=a.decode(l,{stream:!0}).replaceAll(`\r
|
|
8
|
-
`,`
|
|
9
|
-
`),c()){await e.cancel().catch(()=>{});return}}s+=a.decode().replaceAll(`\r
|
|
10
|
-
`,`
|
|
11
|
-
`),c()||r.fail(new f("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},w=(t,r,e={})=>{const a=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!a)throw new f("INTERNAL","httpStream: no `fetch` implementation available");const s=S(t,r??{},e.baseUrl??""),c=new AbortController;let n;e.signal&&(e.signal.aborted?c.abort():(n=()=>{c.abort()},e.signal.addEventListener("abort",n,{once:!0})));const l=()=>{n&&e.signal?.removeEventListener("abort",n)},{handle:i,iterable:d}=h({maxBuffer:e.maxBuffer,onCancel:()=>{c.abort()}});return(async()=>{try{const o=await a(s,{headers:{accept:"text/event-stream",...e.headers},method:t.method,signal:c.signal});if(!o.ok){await o.body?.cancel().catch(()=>{}),i.fail(new f("HTTP_STREAM_STATUS",`httpStream: request failed (status ${o.status.toString()})`,{status:o.status}));return}if(!o.body){i.fail(new f("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await g(o.body,i)}finally{l()}})().catch(o=>{if(c.signal.aborted){i.complete();return}if(o instanceof Error&&"code"in o){i.fail(o);return}i.fail(new f("HTTP_STREAM_TRANSPORT",o instanceof Error?o.message:String(o),{cause:o}))}),d};export{w as httpStream};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const i=n=>new Promise((t,d)=>{n.addEventListener("success",()=>{t(n.result)}),n.addEventListener("error",()=>{d(n.error??new Error("IndexedDB request failed"))})}),c=(n,t,d,s)=>{let e;return()=>e||(e=new Promise((o,a)=>{const r=n.open(t,d);r.addEventListener("upgradeneeded",()=>{s(r.result)}),r.addEventListener("success",()=>{o(r.result)}),r.addEventListener("error",()=>{a(r.error??new Error("IndexedDB open failed"))})}),e)},E=(n,t)=>async(d,s)=>{const e=(await n()).transaction(t,d),o=await s(e.objectStore(t));return await new Promise((a,r)=>{e.addEventListener("complete",()=>{a()}),e.addEventListener("error",()=>{r(e.error??new Error("IndexedDB transaction failed"))}),e.addEventListener("abort",()=>{r(e.error??new Error("IndexedDB transaction aborted"))})}),o};export{c as D,E as b,i as c};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{SubscriptionRegistry as f}from"./SubscriptionRegistry-HXgW6BXq.mjs";const m=(t,s)=>{let e=t;for(const o of s)try{e=o.transform(e)}catch{}return e},u=(t,s)=>{if(s!==t.lastValue){t.lastValue=s;for(const e of t.callbacks)try{e(s)}catch{}}},p=(t,s)=>{let e;try{e=s(t.lastValue)}catch{return}const o={id:Symbol("optimistic"),transform:s};t.optimisticLayers.push(o),u(t,e);const i=()=>{const r=t.optimisticLayers.findIndex(c=>c.id===o.id);return r===-1?!1:(t.optimisticLayers.splice(r,1),!0)},a=()=>{u(t,m(t.serverBase,t.optimisticLayers))};return{confirm:r=>{if(r===void 0){i();return}o.commitCursor=r,t.serverCursor!==void 0&&t.serverCursor>=r&&i()&&a()},rollback:()=>{i()&&a()}}},d=(t,s)=>{if(s===void 0||t.optimisticLayers.length===0)return!1;const e=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(o=>o.commitCursor===void 0||o.commitCursor>s),t.optimisticLayers.length!==e},L=(t,s)=>{const e=[],o=[],i=(a,r)=>t.get(f.key(a,r,s));return{confirms:e,rollbacks:o,store:{getAllQueries:a=>{const r=[];for(const c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(s??"")&&r.push({args:c.args,value:c.lastValue});return r},getQuery:(a,r)=>i(a.__lunoraRef,r??{})?.lastValue,setQuery:(a,r,c)=>{const l=i(a.__lunoraRef,r??{});if(!l)return;const n=p(l,()=>c);n&&(e.push(n.confirm),o.push(n.rollback))}}}};export{p as a,L as c,d,m as f,u as n};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let c=0;const a=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();c+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${c.toString(36)}_${r}`},f=(r,e)=>r!==void 0&&e!==r,d=a,h=(r,e,t,s)=>{if(r){r({error:t,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,t)};class u{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},t={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=t.persistence,this.onEvict=t.onEvict,this.onSizeChange=t.onSizeChange,this.version=t.version}get size(){return this.items.length}enqueue(e){const t=e;t.id??=d(),this.items.push(t),this.persistence?.append({args:t.args,clientId:t.clientId,functionPath:t.functionPath,id:t.id,identity:t.identity,shardKey:t.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{h(this.onPersistenceError,"append",s,t.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(i){throw h(this.onPersistenceError,"load",i),i}const t=[];for(const i of e)if(!(this.items.some(o=>o.id===i.id)||t.some(o=>o.id===i.id))){if(f(this.version,i.version)){this.persistence.remove(i.id).catch(o=>{h(this.onPersistenceError,"remove",o,i.id)});continue}t.push({args:i.args,clientId:i.clientId,functionPath:i.functionPath,id:i.id,identity:i.identity,reject:()=>{},resolve:()=>{},shardKey:i.shardKey})}this.items.unshift(...t),this.evictOverflow(),this.notifySize();const s=new Set(this.items),n=new Set;for(const i of t)s.has(i)&&n.add(i.shardKey);return[...n]}drain(e){if(!e){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const t=[],s=[];for(const n of this.items)(e(n)?t:s).push(n);return this.items.length=0,this.items.push(...s),this.notifySize(),t}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){const e=[],t=[];for(const s of this.items)if(s.precondition!==void 0&&!s.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",s.reject(n),e.push(s)}else t.push(s);return e.length>0&&(this.items.length=0,this.items.push(...t),this.notifySize()),e}clear(){for(const e of this.items){const t=new Error("CLIENT_CLOSED");t.code="CLIENT_CLOSED",e.reject(t)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){const e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{h(this.onPersistenceError,"remove",s,e.id)});const t=new Error("offline queue overflow");t.code="OFFLINE_QUEUE_OVERFLOW",e.reject(t),this.onEvict?.(e,t)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{f as d,u as h,h as s,d as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const l=async(e,a,r,u={})=>{const o=await e.query(a,r,u);return{__lunoraPreloaded:!0,args:r??{},functionPath:a.__lunoraRef,shardKey:u.shardKey,value:o}},t=e=>e.value;export{l as preloadQuery,t as preloadedQueryResult};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const b=r=>{let n="";for(let u=0;u<r.length;u+=32768)n+=String.fromCharCode(...r.subarray(u,u+32768));return btoa(n)},g=r=>{const n=atob(r),u=new Uint8Array(n.length);for(let c=0;c<n.length;c+=1)u[c]=n.codePointAt(c)??0;return u},o="$lunora.wire$";const p="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},d={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},m=r=>{if(r===null||typeof r!="object")return!1;const n=Object.getPrototypeOf(r);return n===null||n===Object.prototype},s=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===void 0)return[o,"undefined"];if(r===null)return null;const u=typeof r;if(u==="bigint")return[o,"bigint",r.toString()];if(u==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(u!=="object")return r;if(r instanceof Date)return[o,"date",s(r.getTime(),n+1)];if(r instanceof Error){const e=r,a={};for(const l of Object.keys(e))e[l]!==void 0&&(a[l]=s(e[l],n+1));const i=[o,"error",e.name,e.message,a];return e.cause!==void 0&&i.push(s(e.cause,n+1)),i}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,a])=>[s(e,n+1),s(a,n+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>s(e,n+1))];if(r instanceof ArrayBuffer)return[o,"bytes",b(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,a=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return a==="Uint8Array"?[o,"bytes",b(i)]:[o,"bytes",b(i),a]}if(Array.isArray(r)){const e=r.map(a=>s(a,n+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!m(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=r,t={};for(const e of Object.keys(c)){const a=c[e];if(a===void 0)continue;const i=s(a,n+1);e===p?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}return t},f=(r,n=0)=>{if(n>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>f(t,n+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>1024||!/^-?\d+$/.test(t))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(t)}case"date":return new Date(f(r[2],n+1));case"map":return new Map(r[2].map(([t,e])=>[f(t,n+1),f(e,n+1)]));case"set":return new Set(r[2].map(t=>f(t,n+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],a=(Object.hasOwn(d,t)?d[t]:void 0)??Error,i=new a(e);i.name!==t&&Object.defineProperty(i,"name",{configurable:!0,value:t,writable:!0});const l=f(r[4],n+1);for(const y of Object.keys(l))y===p?Object.defineProperty(i,y,{configurable:!0,enumerable:!0,value:l[y],writable:!0}):i[y]=l[y];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(r[5],n+1),writable:!0}),i}case"bytes":{const t=g(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const a=Object.hasOwn(w,e)?w[e]:void 0;return a?new a(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>f(t,n+1))}return r.map(t=>f(t,n+1))}const u=r,c={};for(const t of Object.keys(u)){const e=f(u[t],n+1);t===p?Object.defineProperty(c,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):c[t]=e}return c};export{m as A,s as a,f as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as c}from"./wire-codec-aTWt2XiW.mjs";const y=(e,t)=>e<t?-1:e>t?1:0,n=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>n(r)).join(",")}]`;const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const r=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=e,s=Object.keys(o).toSorted(y),i=[];for(const r of s){const a=o[r];a!==void 0&&i.push(`${JSON.stringify(r)}:${n(a)}`)}return`{${i.join(",")}}`},l=e=>n(c(e));export{l as t};
|