@lunora/studio 1.0.0-alpha.285 → 1.0.0-alpha.286

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.
Files changed (61) hide show
  1. package/dist/standalone/{chunk-JMT6JKOW.js → chunk-225RE5GA.js} +1 -1
  2. package/dist/standalone/{chunk-CCFQ36IK.js → chunk-2OPEPZPK.js} +1 -1
  3. package/dist/standalone/{chunk-VEZOF35R.js → chunk-2POR2UIU.js} +1 -1
  4. package/dist/standalone/{chunk-BQAOEXHS.js → chunk-3PG4P5EM.js} +1 -1
  5. package/dist/standalone/{chunk-LEB6MR75.js → chunk-4VP326WA.js} +1 -1
  6. package/dist/standalone/{chunk-6NWG7VEV.js → chunk-5EPYBABM.js} +1 -1
  7. package/dist/standalone/{chunk-5WK5ZYT3.js → chunk-6R4ROTON.js} +1 -1
  8. package/dist/standalone/{chunk-D5L426XV.js → chunk-7RZ6FOG6.js} +1 -1
  9. package/dist/standalone/chunk-B3WCNVKG.js +9 -0
  10. package/dist/standalone/{chunk-BOG5FM2B.js → chunk-BMKNXB4P.js} +1 -1
  11. package/dist/standalone/{chunk-Y2YN7EEL.js → chunk-DIHZQ4D5.js} +1 -1
  12. package/dist/standalone/{chunk-QEOCKU4J.js → chunk-EVRDIDUZ.js} +1 -1
  13. package/dist/standalone/{chunk-2OGZ4GFA.js → chunk-FHNG7QHV.js} +1 -1
  14. package/dist/standalone/{chunk-TOYLQMET.js → chunk-GBL7WEUY.js} +1 -1
  15. package/dist/standalone/{chunk-SXD6GKFD.js → chunk-GE3WXW3Y.js} +1 -1
  16. package/dist/standalone/{chunk-IDWU5SBJ.js → chunk-GQYM4BFO.js} +1 -1
  17. package/dist/standalone/{chunk-72ZBAPHJ.js → chunk-H6WO3TFT.js} +1 -1
  18. package/dist/standalone/{chunk-TAQOVIX6.js → chunk-I2LU36YS.js} +1 -1
  19. package/dist/standalone/{chunk-7WJ4DF3E.js → chunk-IA25TFHO.js} +1 -1
  20. package/dist/standalone/{chunk-OKIVG4E2.js → chunk-IAXGVFQI.js} +1 -1
  21. package/dist/standalone/{chunk-3BQGOV2A.js → chunk-JBNZ6BGE.js} +1 -1
  22. package/dist/standalone/{chunk-QLA3EVBO.js → chunk-K2OUSI63.js} +1 -1
  23. package/dist/standalone/{chunk-5DTJ3PBB.js → chunk-K2X3EZHM.js} +1 -1
  24. package/dist/standalone/{chunk-KZV2ANII.js → chunk-K342KBP5.js} +1 -1
  25. package/dist/standalone/{chunk-BG76PSAP.js → chunk-LRABO5JF.js} +1 -1
  26. package/dist/standalone/{chunk-O4A4NIH2.js → chunk-LZXXQXL7.js} +1 -1
  27. package/dist/standalone/{chunk-LQHTBXSQ.js → chunk-NPR6Q6JS.js} +1 -1
  28. package/dist/standalone/{chunk-5B7XGNA5.js → chunk-NQNVQNER.js} +1 -1
  29. package/dist/standalone/{chunk-QRYXDEZU.js → chunk-OHZY3Z6U.js} +1 -1
  30. package/dist/standalone/{chunk-A34JF7BQ.js → chunk-OM5AXBYZ.js} +1 -1
  31. package/dist/standalone/{chunk-RRA2TC7L.js → chunk-OQBYCVDK.js} +1 -1
  32. package/dist/standalone/{chunk-DZN4OQBM.js → chunk-OUEJHLUX.js} +1 -1
  33. package/dist/standalone/{chunk-SJKLZSJF.js → chunk-P5TMMDVW.js} +1 -1
  34. package/dist/standalone/{chunk-NQHFKZIE.js → chunk-PO3S7KA4.js} +1 -1
  35. package/dist/standalone/{chunk-HHNOLU5M.js → chunk-QGZCKYPT.js} +1 -1
  36. package/dist/standalone/{chunk-TQ6IL3Q5.js → chunk-QLVYMNCS.js} +1 -1
  37. package/dist/standalone/{chunk-VMBDWO25.js → chunk-QP3PPO4S.js} +1 -1
  38. package/dist/standalone/{chunk-S5CSAPJV.js → chunk-QRFKR22V.js} +1 -1
  39. package/dist/standalone/{chunk-LQ3ZBYOH.js → chunk-R7D2S6ZG.js} +1 -1
  40. package/dist/standalone/{chunk-XZTO25J5.js → chunk-RDOLNBRM.js} +1 -1
  41. package/dist/standalone/{chunk-2U63ZOZC.js → chunk-RI2TLT4W.js} +1 -1
  42. package/dist/standalone/{chunk-66MKFRMY.js → chunk-RKS4LAKS.js} +1 -1
  43. package/dist/standalone/{chunk-JLWS4AH7.js → chunk-SLUVTEPX.js} +1 -1
  44. package/dist/standalone/{chunk-67GKZGLW.js → chunk-SMRF3OF3.js} +1 -1
  45. package/dist/standalone/{chunk-NVBKAK4T.js → chunk-SUCU3ZAO.js} +1 -1
  46. package/dist/standalone/{chunk-EQWMBVTI.js → chunk-SVZOEJEA.js} +1 -1
  47. package/dist/standalone/{chunk-IIGPL3PB.js → chunk-TSWDU7TX.js} +1 -1
  48. package/dist/standalone/{chunk-ZQMSTZPP.js → chunk-U3MTI3IN.js} +1 -1
  49. package/dist/standalone/{chunk-42FAYFPO.js → chunk-U7RUITYE.js} +1 -1
  50. package/dist/standalone/{chunk-N3CMMWHK.js → chunk-V4UFDTTR.js} +1 -1
  51. package/dist/standalone/{chunk-TRHFTP77.js → chunk-VINW46KZ.js} +1 -1
  52. package/dist/standalone/{chunk-6SCG75PE.js → chunk-W7TF6FTU.js} +1 -1
  53. package/dist/standalone/{chunk-M7VEOAHZ.js → chunk-WBMTG4DM.js} +1 -1
  54. package/dist/standalone/{chunk-MR4RRHF4.js → chunk-XI6S7YPS.js} +1 -1
  55. package/dist/standalone/{chunk-IZTHMW6W.js → chunk-XQIDTBFH.js} +1 -1
  56. package/dist/standalone/{chunk-WS7K2UV2.js → chunk-YBILTG2T.js} +1 -1
  57. package/dist/standalone/{chunk-DNWE45V3.js → chunk-YRSZ7R5M.js} +1 -1
  58. package/dist/standalone/{chunk-FHGCQAUL.js → chunk-YVWZHOI3.js} +1 -1
  59. package/dist/standalone/studio.js +1 -1
  60. package/package.json +3 -3
  61. package/dist/standalone/chunk-FXQJJMQ3.js +0 -9
@@ -1,9 +0,0 @@
1
- import{a as $t,d as b}from"./chunk-OACO7GME.js";import{a,d as Q,e as ne,f as Wt,g as Ze}from"./chunk-I26MS5PJ.js";var q=class{static{a(this,"Subscribable")}constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var dr=class extends q{static{a(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},ce=new dr;var lr={setTimeout:a((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:a(t=>clearTimeout(t),"clearTimeout"),setInterval:a((t,e)=>setInterval(t,e),"setInterval"),clearInterval:a(t=>clearInterval(t),"clearInterval")},fr=class{static{a(this,"TimeoutManager")}#e=lr;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},K=new fr;function Ht(t){setTimeout(t,0)}a(Ht,"systemSetTimeoutZero");var tt=typeof window>"u"||"Deno"in globalThis;function T(){}a(T,"noop");function Gt(t,e){return typeof t=="function"?t(e):t}a(Gt,"functionalUpdate");function me(t){return typeof t=="number"&&t>=0&&t!==1/0}a(me,"isValidTimeout");function Ee(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(Ee,"timeUntilStale");function N(t,e){return typeof t=="function"?t(e):t}a(N,"resolveStaleTime");function A(t,e){return typeof t=="function"?t(e):t}a(A,"resolveQueryBoolean");function Ie(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==ye(o,e.options))return!1}else if(!Y(e.queryKey,o))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}a(Ie,"matchQuery");function Oe(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(ae(e.options.mutationKey)!==ae(n))return!1}else if(!Y(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}a(Oe,"matchMutation");function ye(t,e){return(e?.queryKeyHashFn||ae)(t)}a(ye,"hashQueryKeyByOptions");function ae(t){return JSON.stringify(t,(e,s)=>et(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}a(ae,"hashKey");function Y(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let r=0;r<e.length;r++)if(!Y(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!Y(t[r],e[r]))return!1;return!0}return!1}a(Y,"partialMatchKey");var pr=Object.prototype.hasOwnProperty;function st(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=zt(t)&&zt(e);if(!r&&!(et(t)&&et(e)))return e;let n=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,u=r?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=r?d:o[d],f=t[l],p=e[l];if(f===p){u[l]=f,(r?d<n:pr.call(t,l))&&h++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){u[l]=p;continue}let m=st(f,p,s+1);u[l]=m,m===f&&h++}return n===c&&h===n?t:u}a(st,"replaceEqualDeep");function Re(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let s in t)if(t[s]!==e[s])return!1;return!0}a(Re,"shallowEqualObjects");function zt(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(zt,"isPlainArray");function et(t){if(!Vt(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Vt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(et,"isPlainObject");function Vt(t){return Object.prototype.toString.call(t)==="[object Object]"}a(Vt,"hasObjectPrototype");function Jt(t){return new Promise(e=>{K.setTimeout(e,t)})}a(Jt,"sleep");function be(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?st(t,e):e}a(be,"replaceData");function mr(t){return t}a(mr,"keepPreviousData");function Yt(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}a(Yt,"addToEnd");function Xt(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}a(Xt,"addToStart");var ue=Symbol();function Ae(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===ue?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(Ae,"ensureQueryFn");function Pe(t,e){return typeof t=="function"?t(...e):!!t}a(Pe,"shouldThrowError");function Zt(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:a(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}a(Zt,"addConsumeAwareSignal");var j=(()=>{let t=a(()=>tt,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function ge(){let t,e,s=new Promise((i,n)=>{t=i,e=n});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return a(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}a(ge,"pendingThenable");var es=Ht;function yr(){let t=[],e=0,s=a(c=>{c()},"notifyFn"),r=a(c=>{c()},"batchNotifyFn"),i=es,n=a(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=a(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:a(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:a(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:a(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:a(c=>{r=c},"setBatchNotifyFunction"),setScheduler:a(c=>{i=c},"setScheduler")}}a(yr,"createNotifyManager");var w=yr();var br=class extends q{static{a(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>t(!0),"onlineListener"),s=a(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},he=new br;function gr(t){return Math.min(1e3*2**t,3e4)}a(gr,"defaultRetryDelay");function rt(t){return(t??"online")==="online"?he.isOnline():!0}a(rt,"canFetch");var Fe=class extends Error{static{a(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Me(t){let e=!1,s=0,r,i=ge(),n=a(()=>i.status!=="pending","isResolved"),o=a(y=>{if(!n()){let v=new Fe(y);f(v),t.onCancel?.(v)}},"cancel"),c=a(()=>{e=!0},"cancelRetry"),u=a(()=>{e=!1},"continueRetry"),h=a(()=>ce.isFocused()&&(t.networkMode==="always"||he.isOnline())&&t.canRun(),"canContinue"),d=a(()=>rt(t.networkMode)&&t.canRun(),"canStart"),l=a(y=>{n()||(r?.(),i.resolve(y))},"resolve"),f=a(y=>{n()||(r?.(),i.reject(y))},"reject"),p=a(()=>new Promise(y=>{r=a(v=>{(n()||h())&&y(v)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,n()||t.onContinue?.()}),"pause"),m=a(()=>{if(n())return;let y,v=s===0?t.initialPromise:void 0;try{y=v??t.fn()}catch(C){y=Promise.reject(C)}Promise.resolve(y).then(l).catch(C=>{if(n())return;let k=t.retry??(j.isServer()?0:3),E=t.retryDelay??gr,$=typeof E=="function"?E(s,C):E,W=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,C);if(e||!W){f(C);return}s++,t.onFail?.(s,C),Jt($).then(()=>h()?void 0:p()).then(()=>{e?f(C):m()})})},"run");return{promise:i,status:a(()=>i.status,"status"),cancel:o,continue:a(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:a(()=>(d()?m():p().then(m),i),"start")}}a(Me,"createRetryer");var xe=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),me(this.gcTime)&&(this.#e=K.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(j.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(K.clearTimeout(this.#e),this.#e=void 0)}};function ss(t){return{onFetch:a((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=a(async()=>{let d=!1,l=a(m=>{Zt(m,()=>e.signal,()=>d=!0)},"addSignalProperty"),f=Ae(e.options,e.fetchOptions),p=a(async(m,y,v)=>{if(d)return Promise.reject(e.signal.reason);if(y==null&&m.pages.length)return Promise.resolve(m);let k=a(()=>{let pe={client:e.client,queryKey:e.queryKey,pageParam:y,direction:v?"backward":"forward",meta:e.options.meta};return l(pe),pe},"createQueryFnContext")(),E=await f(k),{maxPages:$}=e.options,W=v?Xt:Yt;return{pages:W(m.pages,E,$),pageParams:W(m.pageParams,y,$)}},"fetchPage");if(i&&n.length){let m=i==="backward",y=m?vr:ts,v={pages:n,pageParams:o},C=y(r,v);c=await p(v,C,m)}else{let m=t??n.length;do{let y=u===0?o[0]??r.initialPageParam:ts(r,c);if(u>0&&y==null)break;c=await p(c,y),u++}while(u<m)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=h},"onFetch")}}a(ss,"infiniteQueryBehavior");function ts(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}a(ts,"getNextPageParam");function vr(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}a(vr,"getPreviousPageParam");var ns=class extends xe{static{a(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=is(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#o,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=is(this.options);e.data!==void 0&&(this.setState(rs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=be(this.state.data,t,this.options);return this.#c({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(T).catch(T):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>A(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ue||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>N(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Ee(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#h()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=a(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:a(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=a(()=>{let u=Ae(this.options,e),d=a(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),o=a(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?ss(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#c({type:"fetch",meta:o.fetchOptions?.meta}),this.#i=Me({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:a(u=>{u instanceof Fe&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:a((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:a(()=>{this.#c({type:"pause"})},"onPause"),onContinue:a(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:a(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Fe){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=a(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...it(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...rs(t.data,t.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=t.manual?r:void 0,r;case"error":let i=t.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...t.state}}},"reducer");this.state=e(this.state),w.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function it(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:rt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}a(it,"fetchState");function rs(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(rs,"successState");function is(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,r=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}a(is,"getDefaultState");var at=class extends q{static{a(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=ge(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),as(this.#t,this.options)?this.#f():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return nt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return nt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof A(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#C(),this.#t.setOptions(this.options),e._defaulted&&!Re(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&os(this.#t,s,this.options,e)&&this.#f(),this.updateResult(),r&&(this.#t!==s||A(this.options.enabled,this.#t)!==A(e.enabled,this.#t)||N(this.options.staleTime,this.#t)!==N(e.staleTime,this.#t))&&this.#y();let i=this.#b();r&&(this.#t!==s||A(this.options.enabled,this.#t)!==A(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return wr(this,s)&&(this.#r=s,this.#i=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:a((s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(T)),e}#y(){this.#S();let t=N(this.options.staleTime,this.#t);if(j.isServer()||this.#r.isStale||!me(t))return;let s=Ee(this.#r.dataUpdatedAt,t)+1;this.#d=K.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#w(),this.#u=t,!(j.isServer()||A(this.options.enabled,this.#t)===!1||!me(this.#u)||this.#u===0)&&(this.#l=K.setInterval(()=>{(this.options.refetchIntervalInBackground||ce.isFocused())&&this.#f()},this.#u))}#v(){this.#y(),this.#g(this.#b())}#S(){this.#d!==void 0&&(K.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(K.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,n=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:h}=t,d={...h},l=!1,f;if(e._optimisticResults){let I=this.hasListeners(),U=!I&&as(t,e),J=I&&os(t,s,e,r);(U||J)&&(d={...d,...it(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:y}=d;f=d.data;let v=!1;if(e.placeholderData!==void 0&&f===void 0&&y==="pending"){let I;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(I=i.data,v=!0):I=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,I!==void 0&&(y="success",f=be(i?.data,I,e),l=!0)}if(e.select&&f!==void 0&&!v)if(i&&f===n?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=be(i?.data,f,e),this.#c=f,this.#a=null}catch(I){this.#a=I}this.#a&&(p=this.#a,f=this.#c,m=Date.now(),y="error");let C=d.fetchStatus==="fetching",k=y==="pending",E=y==="error",$=k&&C,W=f!==void 0,D={status:y,fetchStatus:d.fetchStatus,isPending:k,isSuccess:y==="success",isError:E,isInitialLoading:$,isLoading:$,data:f,dataUpdatedAt:d.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:C,isRefetching:C&&!k,isLoadingError:E&&!W,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:E&&W,isStale:ot(t,e),refetch:this.refetch,promise:this.#o,isEnabled:A(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let I=D.data!==void 0,U=D.status==="error"&&!I,J=a(Te=>{U?Te.reject(D.error):I&&Te.resolve(D.data)},"finalizeThenableIfPossible"),Bt=a(()=>{let Te=this.#o=D.promise=ge();J(Te)},"recreateThenable"),ke=this.#o;switch(ke.status){case"pending":t.queryHash===s.queryHash&&J(ke);break;case"fulfilled":(U||D.data!==ke.value)&&Bt();break;case"rejected":(!U||D.error!==ke.reason)&&Bt();break}}return D}updateResult(){let t=this.#r,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),Re(e,t))return;this.#r=e;let s=a(()=>{if(!t)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;let n=new Set(i??this.#m);return this.options.throwOnError&&n.add("error"),Object.keys(this.#r).some(o=>{let c=o;return this.#r[c]!==t[c]&&n.has(c)})},"shouldNotifyListeners");this.#k({listeners:s()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#k(t){w.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Sr(t,e){return A(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&A(e.retryOnMount,t)===!1)}a(Sr,"shouldLoadOnMount");function as(t,e){return Sr(t,e)||t.state.data!==void 0&&nt(t,e,e.refetchOnMount)}a(as,"shouldFetchOnMount");function nt(t,e,s){if(A(e.enabled,t)!==!1&&N(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&ot(t,e)}return!1}a(nt,"shouldFetchOn");function os(t,e,s,r){return(t!==e||A(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&ot(t,s)}a(os,"shouldFetchOptionally");function ot(t,e){return A(e.enabled,t)!==!1&&t.isStaleByTime(N(e.staleTime,t))}a(ot,"isStale");function wr(t,e){return!Re(t.getCurrentResult(),e)}a(wr,"shouldAssignObserverCurrentProperties");var cs=class extends xe{static{a(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||Cr(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(t){let e=a(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Me({fn:a(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:a((n,o)=>{this.#n({type:"failed",failureCount:n,error:o})},"onFail"),onPause:a(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:a(()=>this.#s.canRun(this),"canRun")});let r=this.state.status==="pending",i=!this.#r.canStart();try{if(r)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(t,this,s);let o=await this.options.onMutate?.(t,s);o!==this.state.context&&this.#n({type:"pending",context:o,variables:t,isPaused:i})}let n=await this.#r.start();return await this.#s.config.onSuccess?.(n,t,this.state.context,this,s),await this.options.onSuccess?.(n,t,this.state.context,s),await this.#s.config.onSettled?.(n,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(n,null,t,this.state.context,s),this.#n({type:"success",data:n}),n}catch(n){try{await this.#s.config.onError?.(n,t,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(n,t,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:n}),n}finally{this.#s.runNext(this)}}#n(t){let e=a(s=>{switch(t.type){case"failed":return{...s,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...s,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:t.error,failureCount:s.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),w.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function Cr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(Cr,"getDefaultState");var us=class extends q{static{a(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(t,e,s){let r=new cs({client:t,mutationCache:this,mutationId:++this.#s,options:t.defaultMutationOptions(e),state:s});return this.add(r),r}add(t){this.#e.add(t);let e=Le(t);if(typeof e=="string"){let s=this.#t.get(e);s?s.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Le(t);if(typeof e=="string"){let s=this.#t.get(e);if(s)if(s.length>1){let r=s.indexOf(t);r!==-1&&s.splice(r,1)}else s[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Le(t);if(typeof e=="string"){let r=this.#t.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){let e=Le(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){w.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Oe(e,s))}findAll(t={}){return this.getAll().filter(e=>Oe(t,e))}notify(t){w.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return w.batch(()=>Promise.all(t.map(e=>e.continue().catch(T))))}};function Le(t){return t.options.scope?.id}a(Le,"scopeFor");var hs=class extends q{static{a(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??ye(r,e),n=this.get(i);return n||(n=new ns({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(n)),n}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){w.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Ie(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ie(t,s)):e}notify(t){w.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){w.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){w.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var ct=class{static{a(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new hs,this.#t=t.mutationCache||new us,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=ce.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=he.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(N(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(r.queryHash)?.state.data,o=Gt(e,n);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return w.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,s)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;w.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return w.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=w.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(T).catch(T)}invalidateQueries(t,e={}){return w.batch(()=>(this.#e.findAll(t).forEach(s=>{s.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let s={...e,cancelRefetch:e.cancelRefetch??!0},r=w.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,s);return s.throwOnError||(n=n.catch(T)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(r).then(T)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(N(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(T).catch(T)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(T).catch(T)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return he.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(t){this.#s=t}setQueryDefaults(t,e){this.#r.set(ae(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{Y(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(ae(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{Y(t,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#s.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ye(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===ue&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#s.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var X=Q(ne(),1);var de=Q(ne(),1),ds=Q(Ze(),1);var ve=de.createContext(void 0),ut=a(t=>{let e=de.useContext(ve);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),ht=a(({client:t,children:e})=>(de.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,ds.jsx)(ve.Provider,{value:t,children:e})),"QueryClientProvider");var Se=Q(ne(),1),kr=Q(Ze(),1);function Tr(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(Tr,"createValue");var Er=Se.createContext(Tr()),ls=a(()=>Se.useContext(Er),"useQueryErrorResetBoundary");var fs=Q(ne(),1);var ps=a((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?Pe(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),ms=a(t=>{fs.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),ys=a(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||Pe(s,[t.error,r])),"getHasError");var Qe=Q(ne(),1);var bs=Qe.createContext(!1),gs=a(()=>Qe.useContext(bs),"useIsRestoring"),mc=bs.Provider;var vs=a(t=>{if(t.suspense){let s=a(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),Ss=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),ws=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),dt=a((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function Cs(t,e,s){let r=gs(),i=ls(),n=ut(s),o=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=n.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,vs(o),ps(o,i,c),ms(i);let h=!n.getQueryCache().get(o.queryHash),[d]=X.useState(()=>new e(n,o)),l=d.getOptimisticResult(o),f=!r&&u;if(X.useSyncExternalStore(X.useCallback(p=>{let m=f?d.subscribe(w.batchCalls(p)):T;return d.updateResult(),m},[d,f]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),X.useEffect(()=>{d.setOptions(o)},[o,d]),ws(o,l))throw dt(o,d,i);if(ys({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!j.isServer()&&Ss(l,r)&&(h?dt(o,d,i):c?.promise)?.catch(T).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?l:d.trackResult(l)}a(Cs,"useBaseQuery");function Ir(t,e){return Cs(t,at,e)}a(Ir,"useQuery");var Is=Q(Wt(),1);var M=Q(ne(),1);var Or=/["\\\u0000-\u001F\uD800-\uDFFF]/,ks=a(t=>Or.test(t)?JSON.stringify(t):`"${t}"`,"g"),ft=a(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 \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return ks(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let o="[";for(let c=0;c<t.length;c++)c>0&&(o+=","),o+=ft(t[c]);return o+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let o=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${o} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let o of r){let c=s[o];c!==void 0&&(n?n=!1:i+=",",i+=ks(o),i+=":",i+=ft(c))}return i+"}"},"u"),lt=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"y"),P="$lunora.wire$",Rr="__proto__",Ar=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),H=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[P,"undefined"];if(t===null)return null;let s=typeof t;if(s==="bigint"){let n=t.toString();if(n.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[P,"bigint",n]}if(s==="number"){let n=t;return Number.isNaN(n)?[P,"nan"]:n===1/0?[P,"inf"]:n===-1/0?[P,"-inf"]:n}if(s!=="object")return t;if(t instanceof Date)return[P,"date",H(t.getTime(),e+1)];if(t instanceof Error){let n=t,o=H(Object.fromEntries(Object.keys(n).map(u=>[u,n[u]])),e+1),c=[P,"error",String(n.name),String(n.message),o];return n.cause!==void 0&&c.push(H(n.cause,e+1)),c}if(t instanceof URL)return[P,"url",t.href];if(t instanceof Map)return[P,"map",[...t.entries()].map(([n,o])=>[H(n,e+1),H(o,e+1)])];if(t instanceof Set)return[P,"set",[...t].map(n=>H(n,e+1))];if(t instanceof ArrayBuffer)return[P,"bytes",lt(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,o=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return o==="Uint8Array"?[P,"bytes",lt(c)]:[P,"bytes",lt(c),o]}if(Array.isArray(t)){let n=t.map(o=>H(o,e+1));return n.length>0&&n[0]===P?[P,"arr",n]:n}if(!Ar(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}let r=t,i={};for(let n of Object.keys(r)){let o=r[n];if(o===void 0)continue;let c=H(o,e+1);n===Rr?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"a"),Pr=a(t=>ft(H(t)),"p"),_e=a(t=>Pr(t),"w");var De=Q(Ze(),1);var Ts=a(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"Q"),mt=class{static{a(this,"A")}constructor(e){this.client=e}client;entries=new Map;pushes=new Map;samples=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(_e(e))}openSnapshotSample(e){let s=_e(e);return this.samples.set(s,(this.samples.get(s)??0)+1),{key:s,pushes:this.pushes.get(s)??0}}closeSnapshotSample(e){let s=(this.samples.get(e.key)??1)-1,r=(this.pushes.get(e.key)??0)===e.pushes;return s>0?(this.samples.set(e.key,s),r):(this.samples.delete(e.key),this.entries.has(e.key)||this.pushes.delete(e.key),r)}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=a(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{for(let e of this.identityWatched)this.clearQueries(e)}))}clearQueries(e){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))Ts(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,n,o={}){let c=_e(s),u=this.entries.get(c);if(!u){u={errorCallbacks:new Set,refCount:0,unsubscribe:void 0},this.entries.set(c,u);let l=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{if(this.pushes.set(c,(this.pushes.get(c)??0)+1),f===void 0){Ts(e.getQueryCache().find({exact:!0,queryKey:s}));return}e.setQueryData(s,f)},{onError:a(f=>{for(let p of l.errorCallbacks)p(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),f}}u.refCount+=1;let{onError:h}=o;h&&u.errorCallbacks.add(h);let d=!1;return()=>{if(d)return;d=!0;let l=this.entries.get(c);l&&(l.refCount-=1,h&&l.errorCallbacks.delete(h),l.refCount<=0&&(l.unsubscribe?.(),this.entries.delete(c)))}}},Es=new WeakMap,pt=a(t=>{let e=Es.get(t);return e||(e=new mt(t),Es.set(t,e)),e},"I"),Os=(0,M.createContext)(null),Fr=(0,M.createContext)(!1),Mr=a(()=>new ct({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"q"),xr=a(t=>{let e=(0,Is.c)(20),{children:s,client:r,queryClient:i}=t,n=(0,M.use)(ve),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??Mr(),"d"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,M.useState)(o),u=i??n??c,h,d;e[3]!==r||e[4]!==u?(h=a(()=>{pt(r).clearOnIdentityChange(u)},"u"),d=[r,u],e[3]=r,e[4]=u,e[5]=h,e[6]=d):(h=e[5],d=e[6]),(0,M.useEffect)(h,d);let l=(0,M.useRef)(r),f,p;e[7]!==r||e[8]!==u?(f=a(()=>{l.current!==r&&(pt(l.current).stopClearingOnIdentityChange(u),l.current=r,pt(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"o"),p=[r,u],e[7]=r,e[8]=u,e[9]=f,e[10]=p):(f=e[9],p=e[10]),(0,M.useEffect)(f,p);let[m]=(0,M.useState)(r),y=r!==m,v;e[11]!==s||e[12]!==y?(v=(0,De.jsx)(Fr,{value:y,children:s}),e[11]=s,e[12]=y,e[13]=v):v=e[13];let C;e[14]!==r||e[15]!==v?(C=(0,De.jsx)(Os,{value:r,children:v}),e[14]=r,e[15]=v,e[16]=C):C=e[16];let k=C;if(n===u)return k;let E;return e[17]!==k||e[18]!==u?(E=(0,De.jsx)(ht,{client:u,children:k}),e[17]=k,e[18]=u,e[19]=E):E=e[19],E},"V");var yt=a(()=>{let t=(0,M.use)(Os);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"_");var Ue=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"g"),Lr=a(t=>{let e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.codePointAt(r)??0;return s},"p"),z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ps=a(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let n=t[s]<<16|t[s+1]<<8|t[s+2];e+=z.charAt(n>>18&63)+z.charAt(n>>12&63)+z.charAt(n>>6&63)+z.charAt(n&63)}let i=t.length-s;if(i===1){let n=t[s]<<16;e+=z.charAt(n>>18&63)+z.charAt(n>>12&63)}else if(i===2){let n=t[s]<<16|t[s+1]<<8;e+=z.charAt(n>>18&63)+z.charAt(n>>12&63)+z.charAt(n>>6&63)}return e},"h"),O="$lunora.wire$",bt="__proto__",Rs={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},As={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},gt=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"E"),R=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[O,"undefined"];if(t===null)return null;let s=typeof t;if(s==="bigint"){let n=t.toString();if(n.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[O,"bigint",n]}if(s==="number"){let n=t;return Number.isNaN(n)?[O,"nan"]:n===1/0?[O,"inf"]:n===-1/0?[O,"-inf"]:n}if(s!=="object")return t;if(t instanceof Date)return[O,"date",R(t.getTime(),e+1)];if(t instanceof Error){let n=t,o=R(Object.fromEntries(Object.keys(n).map(u=>[u,n[u]])),e+1),c=[O,"error",String(n.name),String(n.message),o];return n.cause!==void 0&&c.push(R(n.cause,e+1)),c}if(t instanceof URL)return[O,"url",t.href];if(t instanceof Map)return[O,"map",[...t.entries()].map(([n,o])=>[R(n,e+1),R(o,e+1)])];if(t instanceof Set)return[O,"set",[...t].map(n=>R(n,e+1))];if(t instanceof ArrayBuffer)return[O,"bytes",Ue(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,o=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return o==="Uint8Array"?[O,"bytes",Ue(c)]:[O,"bytes",Ue(c),o]}if(Array.isArray(t)){let n=t.map(o=>R(o,e+1));return n.length>0&&n[0]===O?[O,"arr",n]:n}if(!gt(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}let r=t,i={};for(let n of Object.keys(r)){let o=r[n];if(o===void 0)continue;let c=R(o,e+1);n===bt?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"b"),S=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===null||typeof t!="object")return t;if(Array.isArray(t)){if(t[0]===O)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>S(i,e+1));case"bigint":{let i=t[2];if(typeof i!="string"||i.length>1024||!/^-?\d+$/.test(i))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(i)}case"date":{let i=S(t[2],e+1);if(typeof i!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(i)}case"map":{let i=t[2];return new Map(i.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[S(n[0],e+1),S(n[1],e+1)]}))}case"set":return new Set(t[2].map(i=>S(i,e+1)));case"url":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(i)}case"error":{let i=t[2],n=t[3];if(typeof i!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let o=(Object.hasOwn(As,i)?As[i]:void 0)??Error,c=new o(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=S(t[4],e+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let h of Object.keys(u))h===bt?Object.defineProperty(c,h,{configurable:!0,enumerable:!0,value:u[h],writable:!0}):c[h]=u[h];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:S(t[5],e+1),writable:!0}),c}case"bytes":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let n=Lr(i);if(Ue(n)!==i)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let o=t[3]??"Uint8Array";if(o==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;let c=Object.hasOwn(Rs,o)?Rs[o]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>S(i,e+1))}return t.map(i=>S(i,e+1))}let s=t,r={};for(let i of Object.keys(s)){let n=S(s[i],e+1);i===bt?Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):r[i]=n}return r},"y");var x=a(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),Ne=a((t,e,s,r)=>{let i;return()=>i||(i=new Promise((n,o)=>{let c=t.open(e,s);c.addEventListener("upgradeneeded",()=>{r(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{o(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),qe=a((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),n=await r(i.objectStore(e));return await new Promise((o,c)=>{i.addEventListener("complete",()=>{o()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),n},"u");var oe=a((t,e,s)=>`${t}::${e}::${s??""}`,"T"),Qr=500,_r=a((t,e)=>{if(!Number.isInteger(t)||t<1)throw new b("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var Dr="lunora-query-cache",Ur="query-cache",Fs="by_ts",Nr=1,qr=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??Dr,r=t.storeName??Ur,i=_r(t.maxEntries??Qr,"createIndexedDbQueryCache"),n=Ne(e,s,Nr,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Fs,"ts",{unique:!1})}),o=qe(n,r),c=a(async u=>{let h=await x(u.count())-i;h<=0||await new Promise((d,l)=>{let f=u.index(Fs).openCursor();f.addEventListener("success",()=>{let p=f.result;if(!p||h<=0){d();return}p.delete(),h-=1,p.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:a(async()=>{await o("readwrite",u=>x(u.clear()))},"clear"),load:a(async()=>o("readonly",u=>x(u.getAll())),"load"),put:a(async(u,h)=>{await o("readwrite",async d=>{await x(d.put({...h,key:u})),await c(d)})},"put"),remove:a(async u=>{await o("readwrite",h=>x(h.delete(u)))},"remove")}},"N"),Ms=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return qr()}},"L");var xs=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"r");var Ke=class{static{a(this,"u")}values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,s){if(s===void 0){this.reset(e);return}this.values.set(e.key,s),this.notify(e.key,s)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,s){let r=this.subscribers.get(e.key);return r||(r=new Set,this.subscribers.set(e.key,r)),r.add(s),()=>{r.delete(s),r.size===0&&this.subscribers.delete(e.key)}}notify(e,s){let r=this.subscribers.get(e);if(r)for(let i of r)try{i(s)}catch{}}};var Ls=0,Kr="lunora-bridge",jr=1e3,Br=3e3,je=class{static{a(this,"l")}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;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Ls+=1,this.tabId=`tab_${String(Ls)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??jr,this.leaderTimeout=e.leaderTimeout??Br,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onLeaderClaimAnswered=e.onLeaderClaimAnswered,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??Kr),this.bc.addEventListener("message",s=>{this.handleMessage(s.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,s,r,i,n){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}})}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,n,o){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}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,e.identity);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()}),this.onLeaderClaimAnswered?.();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))}};var vt="_id",St="_creationTime",wt="page",Qs="pageDelta",$r=a(t=>{if(Array.isArray(t))return t;if(gt(t)&&Array.isArray(t[wt]))return t[wt]},"g"),Wr=a(t=>{let e;for(let s of t){let r=s[St];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"y"),Hr=a((t,e)=>{let s=e[St];if(typeof s!="number")return t.length;let r=Wr(t);for(let[i,n]of t.entries()){let o=n[St];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"A"),zr=a(t=>{if(typeof t!="object"||t===null)return;let e=t[vt];return typeof e=="string"?e:void 0},"x"),_s=a(t=>{if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},"m"),Vr=a((t,e)=>{let s=[];for(let u of t){if(zr(u)===void 0)return;s.push(u)}let{key:r,op:i,row:n}=e;if(i==="delete"){let u=s.filter(h=>h[vt]!==r);return u.length===s.length?[...s]:u}if(n===void 0)return;let o=[...s],c=s.findIndex(u=>u[vt]===r);return c===-1?o.splice(Hr(s,n),0,n):o[c]=n,o},"D"),Ds=a((t,e)=>{let s=$r(t);if(s===void 0)return;let r=Vr(s,e);return r===void 0||Array.isArray(t)?r:{...t,[wt]:r}},"b"),Ct=Symbol("lunora.unmergeableDelta");var cu=new Set(Object.keys($t)),B=class extends b{static{a(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var Be=a(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),kt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),$e=a(t=>kt.has(t?.code??""),"u");var Gr=1024,We=a(t=>{let e=t.maxBuffer??Gr,s=[],r=[],i=!1,n,o=!1,c=a(()=>{let d=r.shift();if(!d)return!1;if(n)return d.reject(n),!0;if(s.length>0){let l=s.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(r.unshift(d),!1)},"u"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(d){if(!(i||n))for(n=d,s.length=0;c(););},push(d){if(!(i||n||o)){if(s.length>=e){u.fail(new b("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(d),c()}}},h=a(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:h,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(s.length>0){let d=s.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,l)=>{r.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var Us=/^ /u,Ns=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"h"),Jr=a(t=>{let e="",s=[];for(let r of t.split(`
2
- `))r.startsWith("event:")?e=r.slice(6).replace(Us,""):r.startsWith("data:")&&s.push(r.slice(5).replace(Us,""));return{data:s.join(`
3
- `),event:e}},"S"),Yr=a((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=r[u];if(h===void 0)throw new b("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(Ns(h))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,Ns(u));let o=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"T"),Xr=a((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let s={};try{s=JSON.parse(t.data)}catch{}let r=typeof s.message=="string"?s.message:"stream error",i=typeof s.code=="string"?s.code:"HTTP_STREAM_ERROR";return e.fail(new b(i,r)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(S(JSON.parse(t.data)))}catch{return e.fail(new b("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"E"),Zr=a(async(t,e)=>{let s=t.getReader(),r=new TextDecoder,i="",n=!1,o=a(u=>{let h=n?`\r${u}`:u;n=h.endsWith("\r"),n&&(h=h.slice(0,-1)),i+=h.replaceAll(`\r
4
- `,`
5
- `)},"l"),c=a(()=>{let u=i.indexOf(`
6
-
7
- `);for(;u!==-1;){let h=Jr(i.slice(0,u));if(i=i.slice(u+2),Xr(h,e))return!0;u=i.indexOf(`
8
-
9
- `)}return!1},"d");for(;;){let{done:u,value:h}=await s.read();if(u)break;if(o(r.decode(h,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}o(r.decode()),c()||e.fail(new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),qs=a((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new b("INTERNAL","httpStream: no `fetch` implementation available");let i=Yr(t,e??{},s.baseUrl??""),n=new AbortController,o;s.signal&&(s.signal.aborted?n.abort():(o=a(()=>{n.abort()},"l"),s.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&s.signal?.removeEventListener("abort",o)},"d"),{handle:u,iterable:h}=We({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await Zr(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new b("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var ei=/["\\\u0000-\u001F\uD800-\uDFFF]/,Ks=a(t=>ei.test(t)?JSON.stringify(t):`"${t}"`,"y"),Tt=a(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 \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return Ks(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let o="[";for(let c=0;c<t.length;c++)c>0&&(o+=","),o+=Tt(t[c]);return o+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let o=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${o} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let o of r){let c=s[o];c!==void 0&&(n?n=!1:i+=",",i+=Ks(o),i+=":",i+=Tt(c))}return i+"}"},"i"),Z=a(t=>Tt(R(t)),"u");var L=class t{static{a(this,"t")}static key(e,s,r){return`${e}::${Z(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}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(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};function He(t){if(t!==void 0)return e=>{t(e)}}a(He,"b");var V=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Et=0,js=a(()=>Et,"L"),ee=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),G=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),It=a((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),G(t,s);let n=a(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=a(()=>{G(t,ee(t.serverBase,t.optimisticLayers))},"s");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,Et+=1,r.acknowledgedAt=Et,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"y"),ze=a((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"h"),Bs=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"k"),le=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),$s=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(L.key(n,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let h=It(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"b");var Ot=a(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"f"),ti=a((t,e)=>{let s=Ot(e);if(!(s===void 0||Be(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"v"),fe=a(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"l"),si=a(()=>new B("LunoraClient: batch slot carried no error envelope"),"m"),Ws=a((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"s"),Hs=a(t=>{let{code:e,messageText:s}=Ws(t,"stream error");return e===void 0?new Error(s):new b(e,s)},"g"),Rt=a(t=>{let{code:e,messageText:s}=Ws(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"A"),Ve=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=S(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"n"),At=a((t,e)=>{let s=Ve(t),r=ti(s,e);return r!==void 0&&(s.data=r),s},"y"),Ge=a(t=>{let e=fe(t);return e===void 0?si():Ve(e)},"h");var zs=0,ri=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();zs+=1;let t=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)}_${zs.toString(36)}_${t}`},"d"),Pt=a((t,e)=>t!==void 0&&e!==t,"f"),Ye=ri,te=a((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),Je=class{static{a(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=Ye(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{te(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw te(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(Pt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{te(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let o of s)i.has(o)&&n.add(o.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;if(!this.persistence||i===void 0)continue;let n={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(o=>{te(this.onPersistenceError,"replace",o,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){te(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(r=>{te(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var ii="lunora-outbox",ni="offline-mutations",Ft="by_id",ai=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??ii,r=t.storeName??ni,i=Ne(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Ft,"id",{unique:!0})}),n=qe(i,r);return{append:a(async o=>{await n("readwrite",c=>x(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>x(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>x(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Ft).getKey(o));u!==void 0&&await x(c.delete(u))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Ft).getKey(o.id));u!==void 0&&await x(c.put(o,u))})},"replace")}},"w"),Vs=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ai()}},"b");var Mt=a((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(r,s*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var Gs=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?Z(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:Z(o.value)===n}},"c");var xt=500,oi=a(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"Ye"),Js=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"he");new TextDecoder;var ci=new TextEncoder,ui=a(t=>Ps(ci.encode(JSON.stringify(t))),"Xe"),hi="x-lunora-expect-subject",di=a(t=>ui({subject:t}),"et"),Ys=Symbol.for("lunora:session-change"),li="lunora:session-change",fi="better-auth.message",pi="signout",ir=a(()=>{let t=globalThis,e=t[Ys];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[Ys]=e),e},"Se"),mi=a(()=>"document"in globalThis,"rt"),yi=a(async()=>{let t=[];for(let e of ir().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"nt"),bi=a((t,e)=>{if(t!==fi||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===pi}catch{return!1}},"at"),gi=a(t=>{let e=[],s=a(()=>{yi().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(li):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=a(o=>{bi(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"ot"),vi=a(t=>{let e=ir();return e.listeners.add(t),e.detach===void 0&&mi()&&(e.detach=gi(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"ct"),se=a((t,e)=>{try{return R(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"E"),Xs=a(t=>{try{return R(t),!0}catch{return!1}},"ue"),nr=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"be"),Si=a((t,e)=>{let s=Array.from({length:e});for(let r of t){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!nr(r.body)){s[r.id]={error:Ge({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:Ge(i),ok:!1}:{ok:!0,value:S(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"ht"),Lt=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),wi="/_lunora/rpc",Qt="/_lunora/rpc-batch",Ci="/_lunora/ws",ki="/_lunora/admin/shard-traffic",Ti="/_lunora/admin/scheduled",Ei="/_lunora/admin/scheduled/status",Ii="/_lunora/admin/scheduled/ws",Oi="/_lunora/admin/scheduled/cancel",Zs="/_lunora/admin/scheduled/dead",Ri="/_lunora/admin/scheduled/dead/retry",Ai="/_lunora/admin/scheduled/dead/cancel",Pi="/_lunora/admin/workflows/instances",Fi="/_lunora/admin/workflows/instance",Mi="/_lunora/admin/workflows/status",_t="/_lunora/admin/storage",xi="/_lunora/admin/storage/url",Li="/_lunora/admin/storage/buckets",Qi="/_lunora/admin/functions",_i="/_lunora/admin/cron-jobs",Di="/_lunora/admin/cron-jobs/run",Ui="/_lunora/admin/architecture",Ni="/_lunora/admin/openapi",qi="/_lunora/admin/openrpc",Ki="/_lunora/admin/global/tables",ji="/_lunora/admin/global/table",Bi="/_lunora/admin/global/facet",$i="/_lunora/admin/vector/indexes",Wi="/_lunora/admin/vector/query",Hi="/_lunora/admin/logs/archive",zi="/_lunora/admin/kv/namespaces",Vi="/_lunora/admin/kv/keys",Dt="/_lunora/admin/kv/value",Gi="/_lunora/admin/auth/users",Ji="/_lunora/admin/auth/sessions",Yi="/_lunora/admin/auth/users/create",Xi="/_lunora/admin/auth/users/role",Zi="/_lunora/admin/auth/users/ban",en="/_lunora/admin/auth/users/unban",tn="/_lunora/admin/auth/users/password",sn="/_lunora/admin/auth/users/remove",rn="/_lunora/admin/auth/users/impersonate",nn="/_lunora/admin/auth/sessions/revoke",an="/_lunora/admin/auth/sessions/revoke-all",on="/_lunora/admin/auth/capabilities",cn="/_lunora/admin/auth/users/update",un="/_lunora/admin/auth/accounts",hn="/_lunora/admin/auth/accounts/unlink",dn="/_lunora/admin/auth/passkeys",ln="/_lunora/admin/auth/passkeys/delete",fn="/_lunora/admin/auth/two-factor/disable",pn="/_lunora/admin/auth/organizations",mn="/_lunora/admin/auth/organizations/members",yn="/_lunora/admin/auth/organizations/invitations",bn="/_lunora/admin/auth/organizations/members/remove",gn="/_lunora/admin/auth/organizations/invitations/cancel",vn="/_lunora/admin/auth/config",Sn="/_lunora/admin/auth/sign-up-invitations",wn="/_lunora/admin/auth/sign-up-invitations/create",Cn="/_lunora/admin/auth/sign-up-invitations/revoke",kn="/_lunora/admin/auth/organizations/create",Tn="/_lunora/admin/auth/organizations/update",En="/_lunora/admin/auth/organizations/remove",In="/_lunora/admin/auth/organizations/members/add",On="/_lunora/admin/auth/organizations/members/invite",Rn="/_lunora/admin/auth/organizations/members/role",An="/_lunora/admin/auth/organizations/teams",Pn="/_lunora/admin/auth/organizations/teams/create",Fn="/_lunora/admin/auth/organizations/teams/update",Mn="/_lunora/admin/auth/organizations/teams/remove",xn="/_lunora/admin/auth/organizations/teams/members",Ln="/_lunora/admin/auth/organizations/teams/members/add",Qn="/_lunora/admin/auth/organizations/teams/members/remove",_n="/_lunora/admin/auth/organizations/roles",Dn="/_lunora/admin/auth/organizations/roles/create",Un="/_lunora/admin/auth/organizations/roles/update",Nn="/_lunora/admin/auth/organizations/roles/remove",qn="/api/auth",Kn="/get-session",jn="lunora-ping",Bn=3e4,$n=1e4,Wn=5e3,Hn=3,zn=250,Vn=5e3,Gn=5e3,Jn=64,Yn=3,Xn=1e4,Zn=8,Ut=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"J"),er=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"fe"),re=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"w"),F=a((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"S"),Nt=a(t=>t==="connected"||t==="polling","X"),g=a(t=>t??"","l"),_=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"T"),ea=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)_(t,s)},"Ks"),ta=new TextDecoder,sa=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return ta.decode(t)},"Ws"),ie=class{static{a(this,"R")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Ce=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"L"),ra=a((t,e,s)=>{Ce(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(jn)}catch{}},e))},"js"),tr=a((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=new i(e);t.socket=c;let u=a(()=>{Ce(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),h=a(d=>{u(),r.onClose(d)},"h");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}h()}},n)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(d){console.error("[lunora] connection open handler threw",d)}ra(t,o,h)}}),c.addEventListener("message",d=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(d)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",d=>{t.socket===c&&h(d)}),c.addEventListener("error",()=>{t.socket===c&&h()})},"pe"),ia=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,u,h=!1,d=!1,l=a(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"u"),f=a(m=>{if(u!==void 0){if(!m){l();return}h||(h=!0,i()),r()}},"f"),p=a(()=>{d||(d=!0,n().then(f).finally(()=>{d=!1}).catch(()=>{}))},"m");return{isPolling:a(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:a(()=>{c=0,l()},"noteOpen"),stop:l}},"$s"),na=1e4,sr=a(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},na)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"me"),ar=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),aa=a(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||ar.has(e)||kt.has(e)},"Vs"),or=6e4,oa=1e3,ca={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},we=a((t,e,s)=>{let r=Ot(s),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new b(ca[t]??"BAD_REQUEST",n,{data:i})},"F"),Kt=a((t,e=Math.random)=>{let s=Math.min(oa*2**Math.max(t-1,0),or);return Math.round(s*(.5+e()*.5))},"te"),ua=a(t=>t instanceof B||ar.has(t?.code??""),"Js"),ha=a((t,e,s)=>{let r=Be(t);return r!==void 0&&r>0?Math.min(r,or):ua(t)?Kt(e,s):void 0},"Xs"),da=983040,la=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"ei"),cr=new WeakSet,rr=a(t=>{let e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return cr.add(e),e},"ye"),Xe=a(t=>t instanceof Error&&cr.has(t),"B"),fa=a((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"ti"),pa=a((t,e,s)=>t!==null||e&&s===null,"si"),ma=[Qs],qt=a(t=>"args"in t?{...t,args:S(t.args)}:t,"Z"),ya=Promise.resolve(),jt=class t{static{a(this,"Ce")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new L;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new ie;statusListeners=new ie;tokenExpiredListeners=new ie;identityChangeListeners=new ie;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new ie;pendingChangeListeners=new ie;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??re(er(e.url),Ci),this.wsToken=e.wsToken;let s=e.authBasePath??qn;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,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??xs(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Bn,this.connectTimeoutMs=e.connectTimeoutMs??$n,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Wn,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Hn,this.defaultConnectionContext=e.connectionContext,this.persistence=Vs(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ms(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Ke,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=ya),this.offlineQueue=new Je(e.offlineQueue,{onEvict:a((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onSizeChange:a(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Ye()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=vi(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,this.applySubject(e,s);let h=this.identityFingerprint();h!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,h),this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),pa(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(h!==i||r||o)&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",o=this.identityFingerprint(),c,u,h;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(d=>{c=d},"onMutationAck")})}catch(d){if(!Xe(d))throw d;h=d}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let d=this.clientWatermarks.get(o??"");d===void 0&&(Js(this.clientWatermarks,Zn),d=new Map,this.clientWatermarks.set(o??"",d)),d.set(n,c)}if(h!==void 0)throw h;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(re(this.url,`${this.authBasePath}${Kn}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&_(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(s)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&_(d,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(r.shardKey)}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&_(i,{data:se(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(r.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let n of r){let o=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return Gs(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){if(!this.readyResolved)return;let i=Z(s),n=oe(e,i,r),o=this.hydratedQueryCache.get(n);if(o!==void 0)return this.cachedQueryMatchesIdentity(o)?o.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=L.key(e,s,r),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=r.toArgs??(d=>({rows:d})),o=s.length,c=0,u=0,h=0;for(let d=0;d<o;d+=i){let l=s.slice(d,d+i),f=h,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});h+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:h,imported:u,queued:c-u}}async shardTraffic(e){this.assertOpen();let s=await this.adminFetch(ki,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(Ti,"GET")).records??[]).map(e=>qt(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Ei,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Oi,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await oi(async e=>await this.adminFetch(e===void 0?Zs:`${Zs}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>qt(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ri,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Ai,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await this.adminFetch(`${Pi}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}}async getWorkflowInstance(e){this.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await this.adminFetch(`${Fi}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Mi,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=re(er(this.url),Ii),r=Mt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(d,r.next()))},"n"),u=a(f=>{if(o||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;tr(i,p,this.managedSocketOptions,{onClose:a(()=>{c()},"onClose"),onMessage:a(m=>{let y;try{y=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}y.type==="jobs"&&Array.isArray(y.records)&&(r.reset(),e(y.records.map(v=>qt(v))))},"onMessage")})},"c"),h=a(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"h"),d=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Ce(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Qi,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(_i,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let s=await this.adminFetch(Di,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Ni,"GET")}async fetchArchitecture(){return this.assertOpen(),await this.adminFetch(Ui,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(qi,"GET")}async listStorageObjects(e={}){this.assertOpen();let s=F(_t,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await this.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}}async deleteStorageObject(e,s){this.assertOpen();let r=`${_t}?key=${encodeURIComponent(e)}${Ut(s?.bucket)}`,i=await this.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Li,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let s=`${_t}?key=${encodeURIComponent(e.key)}${Ut(e.bucket)}`,r=await this.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}}async signedStorageUrl(e,s){this.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${xi}?key=${encodeURIComponent(e)}${i}${Ut(s?.bucket)}`,o=await this.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Ki,"GET")}async readGlobalTablePage(e){this.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(R(e.filters))),S(await this.adminFetch(`${ji}?${s.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(R(e.filters))),S(await this.adminFetch(`${Bi}?${s.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($i,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Wi,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let s=await this.adminFetch(Hi,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(zi,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let s=F(Vi,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(s,"GET")}async getKvValue(e){this.assertOpen();let s=F(Dt,{key:e.key,namespace:e.namespace});return await this.adminFetch(s,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(Dt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let s=F(Dt,{key:e.key,namespace:e.namespace});await this.adminFetch(s,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let s=F(Gi,{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(s,"GET")}async createAuthUser(e){return await this.adminFetch(Yi,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Xi,"POST",e)}async banAuthUser(e){return await this.adminFetch(Zi,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(en,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(tn,"POST",e)}async removeAuthUser(e){await this.adminFetch(sn,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(rn,"POST",e)}async revokeAuthSession(e){await this.adminFetch(nn,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(an,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(on,"GET")}async updateAuthUser(e){return await this.adminFetch(cn,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(F(un,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(hn,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(F(dn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ln,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(fn,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(F(pn,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let s=F(mn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){let s=F(yn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){let s=F(Sn,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(wn,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(Cn,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(bn,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(gn,"POST",e)}async getAuthConfig(){return await this.adminFetch(vn,"GET")}async createAuthOrganization(e){return await this.adminFetch(kn,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Tn,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(En,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(In,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(On,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(Rn,"POST",e)}async listAuthOrgTeams(e){let s=F(An,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Pn,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Fn,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Mn,"POST",e)}async listAuthOrgTeamMembers(e){let s=F(xn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Ln,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Qn,"POST",e)}async listAuthOrgRoles(e){let s=F(_n,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Dn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Un,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Nn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=F(Ji,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let n=s??{},o=L.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=He(r),h=He(i.onError),d=He(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=Z(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:se(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(o,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(L.keyOf(l)),this.subscriptions.remove(l),this.releaseIdleShard(l.shardKey))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:se(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,o=s??{},{handle:c,iterable:u}=We({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:se(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n};this.streams.set(i,l);let f=h?.wsState==="open"&&_(h,d);if(!f&&h===void 0)return this.forgetStream(i),c.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Jn;){let p=h.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}h.pendingStreams.push(d)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return qs(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=a(r=>g(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=g(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},Gn))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[i,n]of this.streams)g(n.shardKey)===s&&(n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,Ce(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new je({channelName:e,onBecomeLeader:a(()=>{for(let s of this.subscriptions.all())this.ensureSocket(s.shardKey),this.queueResubscribe(s);for(let s of this.queuedOfflineShardKeys)this.ensureSocket(s);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:a(()=>{for(let[s,r]of this.connections)this.teardownConnection(r),this.connections.delete(s);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:a((s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;let i=s==="connected"&&this.leaderStatus!=="connected"||s==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=s,s==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:a((s,r,i,n,o)=>{if(o!==void 0&&o!==this.identityFingerprint())return;let c=this.subscriptions.get(s);c&&(c.serverBase=r,this.dropCacheSeed(s),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),ze(c,i)),G(c,ee(r,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:a((s,r,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(s);n&&V(n.errorCallbacks,r)},"onSubscriptionError"),onSubscriptionSettled:a((s,r,i,n,o,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(s);if(u){this.ackAndAdvanceCursor(u,r,i),n!==void 0&&o===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(re(this.url,Qt),{body:JSON.stringify({calls:e.map((c,u)=>({args:se(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=fe(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?Ve(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return Si(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??Ye(),o=this.takeReplayCredential(r.replayCredential),c=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:u,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,h,u);let d=this.offlineFlushes.get(g(r.shardKey));d!==void 0&&await d;let{hasSocket:l,idleClosed:f,polling:p,wasEverConnected:m,wsState:y}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:v}=this.offlineQueue,C=m||v,k=this.WebSocketImpl!==void 0&&C,E=p||f,$=y==="connecting"&&C&&!E,W=y!=="open"&&!l&&k&&!E,pe=k&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),D=a(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,c,n,h,u,r.precondition,r.mutationId,o?.stamp),"se");if(W||$||pe)return D();let I;try{let U=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:c,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:a(J=>{I=J},"onCommitCursor")});for(let J of u)J(I);return{committed:!0,value:U}}catch(U){if(E&&k&&U instanceof TypeError&&Xs(i))return D();throw this.settleFailedDirectWrite(U,I,u,h,o?.flags.authToken),U}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Xe(e)){for(let o of r)o(s);return}le(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,h,d){let l=d===void 0?this.identityFingerprint():d;if(this.outbox){this.outboxMutationCounter+=1;let f=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(f)}`,identity:l,mutationId:f,...o.length>0&&{onRejected:a(()=>{le(o)},"onRejected")},shardKey:r})}catch(p){throw le(o),p instanceof Error?p:new Error(String(p))}for(let p of c)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((f,p)=>{let m={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:l,precondition:u,onCommit:a(y=>{for(let v of c)v(y)},"onCommit"),reject:a(y=>{this.queuedIdentities.delete(n),Xe(y)||le(o),p(y instanceof Error?y:new Error(String(y))),this.releaseIdleShard(r)},"reject"),resolve:f,shardKey:r};this.offlineQueue.enqueue(m),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),m.id!==void 0&&this.queuedIdentities.set(m.id,l)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(oe(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(Pt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),G(e,ee(s.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,G(r,ee(void 0,r.optimisticLayers))),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=oe(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},zn))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(Xs(c.args)?r.push(c):V(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(r.length===0)return this.probeOrigin();let i=js(),n=this.identityFingerprint(),o;try{o=await sr(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let h=o[c];if(h!==void 0){if(!h.ok){V(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:R(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await sr(async s=>e(re(this.url,Qt),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=L.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=It(u,i);h&&(n.push(h.confirm),o.push(h.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=$s(this.subscriptions,r);try{e(u,s)}catch{le(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!_(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leaderStatus==="connected"?i="open":this.leaderStatus==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(g(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:ia({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:a(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:a(()=>{this.emitConnectionStatus()},"onStateChange"),poll:a(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Mt(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[hi]=di(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,r),o=i.authToken===void 0?this.authToken:i.authToken,c=await this.fetchImpl(re(this.url,wi),{body:JSON.stringify({args:se(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:n,method:"POST"});if(i.captureBookmark){let l=c.headers.get("x-d1-bookmark");l&&this.bookmark.set(l)}let u;try{u=await c.json()}catch{throw we(c.status,c.statusText,c.headers.get("retry-after"))}let h=u;if(typeof h!="object"||h===null||Array.isArray(h))throw we(c.status,c.statusText,c.headers.get("retry-after"));let d=fe(u);if(d!==void 0)throw At(d,c.headers.get("retry-after"));if(!c.ok)throw we(c.status,c.statusText,c.headers.get("retry-after"));i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(c,r),this.recordShardCursor(r,u.commitCursor);try{return S(u.result)}catch(l){throw rr(l)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(re(this.url,e),{body:c,headers:n,method:s}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=fe(h);if(d!==void 0){let l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(g(e.shardKey));_(e,{caps:ma,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openSocket(e,s,r){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),r===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,tr(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:a(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:a(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Vn),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(s)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:o,type:c}of n)_(e,{id:o,type:c});this.releaseIdleShard(s)}ea(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())_(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),_(r,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),Ce(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||s.has(i))){if(n.durable){let o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Yn;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},Xn))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return _(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&_(s,{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,s){let r=sa(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(s);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:o,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof o=="number"&&(h.generation=o),h.durable=!0),h?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.handlePokePart(i,s);break}case"pokeStart":{this.handlePokeStart(i,s);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Hs(e)),this.forgetStream(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let o=Rt(e),c=this.identityFingerprint(),u=L.keyOf(i);V(i.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,o,c);return}let n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&V(n.errorCallbacks,Rt(e))}pokeBufferKey(e,s){return`${g(e)}\0${s}`}handlePokeStart(e,s){Js(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(s,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,s){let r=this.pokeBuffers.get(this.pokeBufferKey(s,e.pokeId));if(!r)return;let i=[];try{for(let c of e.rowsPatch)i.push(c.value===void 0?c:{...c,value:S(c.value)})}catch(c){r.undecodable.set(e.shapeId,c);return}let n=r.parts.get(e.shapeId)??[];for(let c of i)n.push(c);r.parts.set(e.shapeId,n),e.lastMutationId!==void 0&&r.lastMutationId.set(e.shapeId,e.lastMutationId);let o=e.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(e.shapeId,o),e.reset===!0&&r.resets.add(e.shapeId)}handlePokeEnd(e,s){let r=this.pokeBufferKey(s,e.pokeId),i=this.pokeBuffers.get(r);if(i){this.pokeBuffers.delete(r);for(let[n,o]of i.undecodable){let c=this.shapeSubscriptions.get(n);c&&V(c.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${o instanceof Error?o.message:String(o)}`})}for(let n of i.parts.keys()){let o=this.shapeSubscriptions.get(n);o&&!i.undecodable.has(n)&&this.applyPokePart(o,i,e)}}}applyPokePart(e,s,r){let i=s.parts.get(e.id)??[],n=s.resets.has(e.id),o=s.bases.get(e.id),c=s.epoch!==void 0&&e.serverEpoch!==void 0&&s.epoch!==e.serverEpoch,u=o!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==o;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),fa(e.rows,i),r.checkpoint!==void 0&&(e.serverCursor=r.checkpoint),r.epoch!==void 0&&(e.serverEpoch=r.epoch);let h=s.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let s=[...e.rows.values()];for(let r of e.callbacks)try{r(s)}catch{}}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let n;try{n=this.resolveDataPayload(e,i)}catch(o){V(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${o instanceof Error?o.message:String(o)}`});return}if(n===Ct){this.resnapshotSubscription(i);return}if(i.serverBase=n,this.dropCacheSeed(L.keyOf(i)),e.cursor!==void 0&&(i.serverCursor=e.cursor),e.epoch!==void 0&&(i.serverEpoch=e.epoch),e.lastMutationId!==void 0){i.lastMutationId=Math.max(i.lastMutationId??0,e.lastMutationId);for(let o of i.checkpointCallbacks)o({checkpoint:i.serverCursor,mutationId:i.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(i),ze(i,i.serverCursor),s!==void 0&&Bs(i,s),G(i,ee(n,i.optimisticLayers)),this.tabCoordinator?.isLeader()){let o=L.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s){this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&(s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId));for(let r of s.checkpointCallbacks)r({checkpoint:s.serverCursor,mutationId:s.lastMutationId});if(this.tabCoordinator?.isLeader()){let r=L.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),ze(e,e.serverCursor)&&G(e,ee(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,s){if("data"in e&&e.data!==void 0)return S(e.data);let r=S(e.delta);return _s(r)?s.serverBase===void 0?r:Ds(s.serverBase,r)??Ct:r}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=S(e.data);for(let n of r)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,V(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{te(this.onPersistenceError,"remove",s,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,G(e,ee(void 0,e.optimisticLayers));for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",l)}let i=g(e),n=this.offlineQueue.drain(d=>g(d.shardKey)===i);if(n.length===0)return;let o=[],c=[];for(let d of n){let l=this.replayGateVerdict(d);l==="send"?o.push(d):l==="hold"&&c.push(d)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let h=[];for(let d=0;d<u.length;d+=xt){let l=u.slice(d,d+xt),f=await this.replayBatched(l,e,s);if(h.push(...f.requeue),f.stop){h.push(...u.slice(d+xt));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,Kt(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=ha(s,o)??(r===null&&$e(s)?Kt(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?n?.delayMs:Math.max(n?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{se(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||aa(e)}noteReplayAuthRefusal(e,s){if(!$e(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;let s=this.replayCredentials.get(e);if(s===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:s.authToken,...Lt(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let n=e[i];if(!n)continue;let o;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Lt(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Xe(c)){this.settleReplayUndecodable(n,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(n,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((h,d)=>({args:se(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&la(i)>da)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(re(this.url,Qt),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Lt(e.find(h=>h.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=n.headers.get("retry-after");try{c=await n.json()}catch{return this.settleWholeBatchError(e,we(n.status,n.statusText,u),s,r)}if(!c.results){let h=fe(c),d=h===void 0?we(n.status,n.statusText,u):At(h,u);return this.settleWholeBatchError(e,d,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof B||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:e,stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i){let n=new Map;for(let h of s)typeof h.id=="number"&&nr(h.body)&&n.set(h.id,h.body);let o=[],c=!1,u=!1;for(let[h,d]of e.entries()){let l=n.get(h);if(l===void 0)o.push(d);else if("error"in l){let f=Ge(l);u||=$e(f),this.shouldRequeueReplayFailure(f,i)?(this.noteReplayRetryDelay(r,f,i),o.push(d)):this.settleReplayTerminal(d,f)}else c=!0,this.settleReplayBatchResult(d,l)}return c&&!u&&this.noteCredentialAccepted(i),o}settleReplayBatchResult(e,s){let r;try{r=S(s.result)}catch(i){this.settleReplayUndecodable(e,rr(i),s.commitCursor);return}this.settleReplaySuccess(e,r,s.commitCursor)}};var ur=Q(Wt(),1),hr=Q(ne(),1);var ba=a(()=>{let t=(0,ur.c)(4),e=yt(),s,r,i;return t[0]!==e?(s=a(n=>e.onConnectionStatus(()=>{n()}),"o"),r=a(()=>e.connectionStatus(),"e"),i=a(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,hr.useSyncExternalStore)(s,r,i)},"S");export{jt as a,mr as b,ut as c,Ir as d,xr as e,yt as f,ba as g};