@lunora/studio 1.0.0-alpha.285 → 1.0.0-alpha.287
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/mount.mjs +1 -1
- package/dist/packem_shared/StudioApp-vzv6-90m.mjs +1 -0
- package/dist/standalone/{chunk-JMT6JKOW.js → chunk-225RE5GA.js} +1 -1
- package/dist/standalone/{chunk-CCFQ36IK.js → chunk-2OPEPZPK.js} +1 -1
- package/dist/standalone/{chunk-VEZOF35R.js → chunk-2POR2UIU.js} +1 -1
- package/dist/standalone/{chunk-5DTJ3PBB.js → chunk-2TCG7CHR.js} +1 -1
- package/dist/standalone/{chunk-BQAOEXHS.js → chunk-3PG4P5EM.js} +1 -1
- package/dist/standalone/chunk-46U4572L.js +1 -0
- package/dist/standalone/{chunk-6NWG7VEV.js → chunk-5EPYBABM.js} +1 -1
- package/dist/standalone/{chunk-5WK5ZYT3.js → chunk-6R4ROTON.js} +1 -1
- package/dist/standalone/{chunk-D5L426XV.js → chunk-7RZ6FOG6.js} +1 -1
- package/dist/standalone/chunk-B3WCNVKG.js +9 -0
- package/dist/standalone/{chunk-BOG5FM2B.js → chunk-BMKNXB4P.js} +1 -1
- package/dist/standalone/{chunk-Y2YN7EEL.js → chunk-DIHZQ4D5.js} +1 -1
- package/dist/standalone/{chunk-QEOCKU4J.js → chunk-EVRDIDUZ.js} +1 -1
- package/dist/standalone/{chunk-2OGZ4GFA.js → chunk-FHNG7QHV.js} +1 -1
- package/dist/standalone/{chunk-LEB6MR75.js → chunk-FIX4YZH3.js} +1 -1
- package/dist/standalone/{chunk-TOYLQMET.js → chunk-GBL7WEUY.js} +1 -1
- package/dist/standalone/{chunk-SXD6GKFD.js → chunk-GE3WXW3Y.js} +1 -1
- package/dist/standalone/{chunk-IDWU5SBJ.js → chunk-GQYM4BFO.js} +1 -1
- package/dist/standalone/{chunk-72ZBAPHJ.js → chunk-H6WO3TFT.js} +1 -1
- package/dist/standalone/{chunk-TAQOVIX6.js → chunk-I2LU36YS.js} +1 -1
- package/dist/standalone/{chunk-7WJ4DF3E.js → chunk-IA25TFHO.js} +1 -1
- package/dist/standalone/{chunk-3BQGOV2A.js → chunk-JBNZ6BGE.js} +1 -1
- package/dist/standalone/{chunk-QLA3EVBO.js → chunk-K2OUSI63.js} +1 -1
- package/dist/standalone/{chunk-KZV2ANII.js → chunk-K342KBP5.js} +1 -1
- package/dist/standalone/{chunk-OKIVG4E2.js → chunk-KD6OU5GM.js} +1 -1
- package/dist/standalone/{chunk-BG76PSAP.js → chunk-LRABO5JF.js} +1 -1
- package/dist/standalone/{chunk-O4A4NIH2.js → chunk-LZXXQXL7.js} +1 -1
- package/dist/standalone/{chunk-LQHTBXSQ.js → chunk-NPR6Q6JS.js} +1 -1
- package/dist/standalone/{chunk-5B7XGNA5.js → chunk-NQNVQNER.js} +1 -1
- package/dist/standalone/{chunk-QRYXDEZU.js → chunk-OHZY3Z6U.js} +1 -1
- package/dist/standalone/{chunk-A34JF7BQ.js → chunk-OM5AXBYZ.js} +1 -1
- package/dist/standalone/{chunk-RRA2TC7L.js → chunk-OQBYCVDK.js} +1 -1
- package/dist/standalone/{chunk-DZN4OQBM.js → chunk-OUEJHLUX.js} +1 -1
- package/dist/standalone/{chunk-SJKLZSJF.js → chunk-P5TMMDVW.js} +1 -1
- package/dist/standalone/{chunk-NQHFKZIE.js → chunk-PO3S7KA4.js} +1 -1
- package/dist/standalone/{chunk-HHNOLU5M.js → chunk-QGZCKYPT.js} +1 -1
- package/dist/standalone/{chunk-TQ6IL3Q5.js → chunk-QLVYMNCS.js} +1 -1
- package/dist/standalone/{chunk-VMBDWO25.js → chunk-QP3PPO4S.js} +1 -1
- package/dist/standalone/{chunk-S5CSAPJV.js → chunk-QRFKR22V.js} +1 -1
- package/dist/standalone/{chunk-LQ3ZBYOH.js → chunk-R7D2S6ZG.js} +1 -1
- package/dist/standalone/{chunk-XZTO25J5.js → chunk-RDOLNBRM.js} +1 -1
- package/dist/standalone/{chunk-2U63ZOZC.js → chunk-RI2TLT4W.js} +1 -1
- package/dist/standalone/{chunk-66MKFRMY.js → chunk-RKS4LAKS.js} +1 -1
- package/dist/standalone/{chunk-FHGCQAUL.js → chunk-S4TCG3US.js} +1 -1
- package/dist/standalone/{chunk-JLWS4AH7.js → chunk-SLUVTEPX.js} +1 -1
- package/dist/standalone/{chunk-67GKZGLW.js → chunk-SMRF3OF3.js} +1 -1
- package/dist/standalone/{chunk-NVBKAK4T.js → chunk-SUCU3ZAO.js} +1 -1
- package/dist/standalone/{chunk-EQWMBVTI.js → chunk-SVZOEJEA.js} +1 -1
- package/dist/standalone/{chunk-IIGPL3PB.js → chunk-TSWDU7TX.js} +1 -1
- package/dist/standalone/{chunk-ZQMSTZPP.js → chunk-U3MTI3IN.js} +1 -1
- package/dist/standalone/{chunk-42FAYFPO.js → chunk-U7RUITYE.js} +1 -1
- package/dist/standalone/{chunk-N3CMMWHK.js → chunk-V4UFDTTR.js} +1 -1
- package/dist/standalone/{chunk-TRHFTP77.js → chunk-VINW46KZ.js} +1 -1
- package/dist/standalone/{chunk-6SCG75PE.js → chunk-W7TF6FTU.js} +1 -1
- package/dist/standalone/{chunk-M7VEOAHZ.js → chunk-WBMTG4DM.js} +1 -1
- package/dist/standalone/{chunk-MR4RRHF4.js → chunk-XI6S7YPS.js} +1 -1
- package/dist/standalone/{chunk-IZTHMW6W.js → chunk-XQIDTBFH.js} +1 -1
- package/dist/standalone/{chunk-WS7K2UV2.js → chunk-YBILTG2T.js} +1 -1
- package/dist/standalone/{chunk-DNWE45V3.js → chunk-YRSZ7R5M.js} +1 -1
- package/dist/standalone/studio.js +3 -3
- package/package.json +5 -5
- package/dist/packem_shared/StudioApp-IeTX2moM.mjs +0 -1
- package/dist/standalone/chunk-FXQJJMQ3.js +0 -9
- package/dist/standalone/chunk-QM3JUT43.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as Vt,d as b}from"./chunk-OACO7GME.js";import{a,d as _,e as ie,f as Gt,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 br=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"}},oe=new br;var gr={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")},vr=class{static{a(this,"TimeoutManager")}#e=gr;#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 vr;function Jt(t){setTimeout(t,0)}a(Jt,"systemSetTimeoutZero");var tt=typeof window>"u"||"Deno"in globalThis;function T(){}a(T,"noop");function Zt(t,e){return typeof t=="function"?t(e):t}a(Zt,"functionalUpdate");function pe(t){return typeof t=="number"&&t>=0&&t!==1/0}a(pe,"isValidTimeout");function Te(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(Te,"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 Ee(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==me(o,e.options))return!1}else if(!J(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(Ee,"matchQuery");function Ie(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(ne(e.options.mutationKey)!==ne(n))return!1}else if(!J(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}a(Ie,"matchMutation");function me(t,e){return(e?.queryKeyHashFn||ne)(t)}a(me,"hashQueryKeyByOptions");function ne(t){return JSON.stringify(t,(e,s)=>et(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}a(ne,"hashKey");function J(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(!J(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!J(t[r],e[r]))return!1;return!0}return!1}a(J,"partialMatchKey");var Sr=Object.prototype.hasOwnProperty;function st(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Yt(t)&&Yt(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):{},d=0;for(let h=0;h<c;h++){let l=r?h:o[h],f=t[l],p=e[l];if(f===p){u[l]=f,(r?h<n:Sr.call(t,l))&&d++;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&&d++}return n===c&&d===n?t:u}a(st,"replaceEqualDeep");function Oe(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(Oe,"shallowEqualObjects");function Yt(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(Yt,"isPlainArray");function et(t){if(!Xt(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Xt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(et,"isPlainObject");function Xt(t){return Object.prototype.toString.call(t)==="[object Object]"}a(Xt,"hasObjectPrototype");function es(t){return new Promise(e=>{K.setTimeout(e,t)})}a(es,"sleep");function ye(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?st(t,e):e}a(ye,"replaceData");function wr(t){return t}a(wr,"keepPreviousData");function ts(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}a(ts,"addToEnd");function ss(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}a(ss,"addToStart");var ce=Symbol();function Re(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===ce?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(Re,"ensureQueryFn");function Ae(t,e){return typeof t=="function"?t(...e):!!t}a(Ae,"shouldThrowError");function rs(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(rs,"addConsumeAwareSignal");var j=(()=>{let t=a(()=>tt,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function be(){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(be,"pendingThenable");var is=Jt;function Cr(){let t=[],e=0,s=a(c=>{c()},"notifyFn"),r=a(c=>{c()},"batchNotifyFn"),i=is,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(Cr,"createNotifyManager");var w=Cr();var kr=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}},ue=new kr;function Tr(t){return Math.min(1e3*2**t,3e4)}a(Tr,"defaultRetryDelay");function rt(t){return(t??"online")==="online"?ue.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 Pe(t){let e=!1,s=0,r,i=be(),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"),d=a(()=>oe.isFocused()&&(t.networkMode==="always"||ue.isOnline())&&t.canRun(),"canContinue"),h=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()||d())&&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??Tr,$=typeof E=="function"?E(s,C):E,H=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,C);if(e||!H){f(C);return}s++,t.onFail?.(s,C),es($).then(()=>d()?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:h,start:a(()=>(h()?m():p().then(m),i),"start")}}a(Pe,"createRetryer");var Me=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pe(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 as(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,d=a(async()=>{let h=!1,l=a(m=>{rs(m,()=>e.signal,()=>h=!0)},"addSignalProperty"),f=Re(e.options,e.fetchOptions),p=a(async(m,y,v)=>{if(h)return Promise.reject(e.signal.reason);if(y==null&&m.pages.length)return Promise.resolve(m);let k=a(()=>{let fe={client:e.client,queryKey:e.queryKey,pageParam:y,direction:v?"backward":"forward",meta:e.options.meta};return l(fe),fe},"createQueryFnContext")(),E=await f(k),{maxPages:$}=e.options,H=v?ss:ts;return{pages:H(m.pages,E,$),pageParams:H(m.pageParams,y,$)}},"fetchPage");if(i&&n.length){let m=i==="backward",y=m?Er:ns,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:ns(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?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=d},"onFetch")}}a(as,"infiniteQueryBehavior");function ns(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(ns,"getNextPageParam");function Er(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}a(Er,"getPreviousPageParam");var us=class extends Me{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=cs(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=cs(this.options);e.data!==void 0&&(this.setState(os(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=ye(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===ce||!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:!Te(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(d=>d.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=Re(this.options,e),h=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,h,this):u(h)},"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"?as(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=Pe({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,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"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,...os(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 os(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(os,"successState");function cs(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(cs,"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=be(),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),hs(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&&!Oe(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&ds(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 Or(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||!pe(t))return;let s=Te(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||!pe(this.#u)||this.#u===0)&&(this.#l=K.setInterval(()=>{(this.options.refetchIntervalInBackground||oe.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:d}=t,h={...d},l=!1,f;if(e._optimisticResults){let I=this.hasListeners(),U=!I&&hs(t,e),G=I&&ds(t,s,e,r);(U||G)&&(h={...h,...it(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:y}=h;f=h.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=ye(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=ye(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=h.fetchStatus==="fetching",k=y==="pending",E=y==="error",$=k&&C,H=f!==void 0,D={status:y,fetchStatus:h.fetchStatus,isPending:k,isSuccess:y==="success",isError:E,isInitialLoading:$,isLoading:$,data:f,dataUpdatedAt:h.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:C,isRefetching:C&&!k,isLoadingError:E&&!H,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:E&&H,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,G=a(ke=>{U?ke.reject(D.error):I&&ke.resolve(D.data)},"finalizeThenableIfPossible"),zt=a(()=>{let ke=this.#o=D.promise=be();G(ke)},"recreateThenable"),Ce=this.#o;switch(Ce.status){case"pending":t.queryHash===s.queryHash&&G(Ce);break;case"fulfilled":(U||D.data!==Ce.value)&&zt();break;case"rejected":(!U||D.error!==Ce.reason)&&zt();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),Oe(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 Ir(t,e){return A(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&A(e.retryOnMount,t)===!1)}a(Ir,"shouldLoadOnMount");function hs(t,e){return Ir(t,e)||t.state.data!==void 0&&nt(t,e,e.refetchOnMount)}a(hs,"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 ds(t,e,s,r){return(t!==e||A(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&ot(t,s)}a(ds,"shouldFetchOptionally");function ot(t,e){return A(e.enabled,t)!==!1&&t.isStaleByTime(N(e.staleTime,t))}a(ot,"isStale");function Or(t,e){return!Oe(t.getCurrentResult(),e)}a(Or,"shouldAssignObserverCurrentProperties");var ls=class extends Me{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||Rr(),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=Pe({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 Rr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(Rr,"getDefaultState");var fs=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 ls({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=xe(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=xe(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=xe(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=xe(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=>Ie(e,s))}findAll(t={}){return this.getAll().filter(e=>Ie(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 xe(t){return t.options.scope?.id}a(xe,"scopeFor");var ps=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??me(r,e),n=this.get(i);return n||(n=new us({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=>Ee(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ee(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 ps,this.#t=t.mutationCache||new fs,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=oe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=ue.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=Zt(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 ue.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(ne(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{J(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(ne(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{J(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=me(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===ce&&(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 Y=_(ie(),1);var he=_(ie(),1),ms=_(Ze(),1);var ge=he.createContext(void 0),ut=a(t=>{let e=he.useContext(ge);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})=>(he.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,ms.jsx)(ge.Provider,{value:t,children:e})),"QueryClientProvider");var ve=_(ie(),1),Ar=_(Ze(),1);function Fr(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(Fr,"createValue");var Pr=ve.createContext(Fr()),ys=a(()=>ve.useContext(Pr),"useQueryErrorResetBoundary");var bs=_(ie(),1);var gs=a((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?Ae(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),vs=a(t=>{bs.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Ss=a(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||Ae(s,[t.error,r])),"getHasError");var Qe=_(ie(),1);var ws=Qe.createContext(!1),Cs=a(()=>Qe.useContext(ws),"useIsRestoring"),pu=ws.Provider;var ks=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"),Ts=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Es=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),dt=a((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function Is(t,e,s){let r=Cs(),i=ys(),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,ks(o),gs(o,i,c),vs(i);let d=!n.getQueryCache().get(o.queryHash),[h]=Y.useState(()=>new e(n,o)),l=h.getOptimisticResult(o),f=!r&&u;if(Y.useSyncExternalStore(Y.useCallback(p=>{let m=f?h.subscribe(w.batchCalls(p)):T;return h.updateResult(),m},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),Y.useEffect(()=>{h.setOptions(o)},[o,h]),Es(o,l))throw dt(o,h,i);if(Ss({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()&&Ts(l,r)&&(d?dt(o,h,i):c?.promise)?.catch(T).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?l:h.trackResult(l)}a(Is,"useBaseQuery");function Mr(t,e){return Is(t,at,e)}a(Mr,"useQuery");var Fs=_(Gt(),1);var M=_(ie(),1);var xr=/["\\\u0000-\u001F\uD800-\uDFFF]/,Os=a(t=>xr.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 Os(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+=Os(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"),F="$lunora.wire$",Qr="__proto__",_r=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),W=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[F,"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[F,"bigint",n]}if(s==="number"){let n=t;return Number.isNaN(n)?[F,"nan"]:n===1/0?[F,"inf"]:n===-1/0?[F,"-inf"]:n}if(s!=="object")return t;if(t instanceof Date)return[F,"date",W(t.getTime(),e+1)];if(t instanceof Error){let n=t,o=W(Object.fromEntries(Object.keys(n).map(u=>[u,n[u]])),e+1),c=[F,"error",String(n.name),String(n.message),o];return n.cause!==void 0&&c.push(W(n.cause,e+1)),c}if(t instanceof URL)return[F,"url",t.href];if(t instanceof Map)return[F,"map",[...t.entries()].map(([n,o])=>[W(n,e+1),W(o,e+1)])];if(t instanceof Set)return[F,"set",[...t].map(n=>W(n,e+1))];if(t instanceof ArrayBuffer)return[F,"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"?[F,"bytes",lt(c)]:[F,"bytes",lt(c),o]}if(Array.isArray(t)){let n=t.map(o=>W(o,e+1));return n.length>0&&n[0]===F?[F,"arr",n]:n}if(!_r(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=W(o,e+1);n===Qr?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"a"),Lr=a(t=>ft(W(t)),"p"),_e=a(t=>Lr(t),"w");var Le=_(Ze(),1);var Rs=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"]}))Rs(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){Rs(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:d}=o;d&&u.errorCallbacks.add(d);let h=!1;return()=>{if(h)return;h=!0;let l=this.entries.get(c);l&&(l.refCount-=1,d&&l.errorCallbacks.delete(d),l.refCount<=0&&(l.unsubscribe?.(),this.entries.delete(c)))}}},As=new WeakMap,pt=a(t=>{let e=As.get(t);return e||(e=new mt(t),As.set(t,e)),e},"I"),Ps=(0,M.createContext)(null),Dr=(0,M.createContext)(!1),Ur=a(()=>new ct({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"q"),Nr=a(t=>{let e=(0,Fs.c)(20),{children:s,client:r,queryClient:i}=t,n=(0,M.use)(ge),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??Ur(),"d"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,M.useState)(o),u=i??n??c,d,h;e[3]!==r||e[4]!==u?(d=a(()=>{pt(r).clearOnIdentityChange(u)},"u"),h=[r,u],e[3]=r,e[4]=u,e[5]=d,e[6]=h):(d=e[5],h=e[6]),(0,M.useEffect)(d,h);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,Le.jsx)(Dr,{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,Le.jsx)(Ps,{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,Le.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)(Ps);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"_");var De=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"),qr=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-_",Qs=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__",Ms={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},xs={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",De(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",De(c)]:[O,"bytes",De(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(xs,i)?xs[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 d of Object.keys(u))d===bt?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];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=qr(i);if(De(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(Ms,o)?Ms[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"),Ue=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"),Ne=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 ae=a((t,e,s)=>`${t}::${e}::${s??""}`,"T"),Kr=500,jr=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 Br="lunora-query-cache",$r="query-cache",_s="by_ts",Hr=1,Wr=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??Br,r=t.storeName??$r,i=jr(t.maxEntries??Kr,"createIndexedDbQueryCache"),n=Ue(e,s,Hr,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(_s,"ts",{unique:!1})}),o=Ne(n,r),c=a(async u=>{let d=await x(u.count())-i;d<=0||await new Promise((h,l)=>{let f=u.index(_s).openCursor();f.addEventListener("success",()=>{let p=f.result;if(!p||d<=0){h();return}p.delete(),d-=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,d)=>{await o("readwrite",async h=>{await x(h.put({...d,key:u})),await c(h)})},"put"),remove:a(async u=>{await o("readwrite",d=>x(d.delete(u)))},"remove")}},"N"),Ls=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return Wr()}},"L");var Ds=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"r");var qe=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 Us=0,zr="lunora-bridge",Vr=1e3,Gr=3e3,Ke=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(Us+=1,this.tabId=`tab_${String(Us)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Vr,this.leaderTimeout=e.leaderTimeout??Gr,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??zr),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",Ns="pageDelta",Jr=a(t=>{if(Array.isArray(t))return t;if(gt(t)&&Array.isArray(t[wt]))return t[wt]},"g"),Yr=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},"A"),Xr=a((t,e)=>{let s=e[St];if(typeof s!="number")return t.length;let r=Yr(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},"x"),Zr=a(t=>{if(typeof t!="object"||t===null)return;let e=t[vt];return typeof e=="string"?e:void 0},"D"),ei=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")},"E"),ti=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(d=>d[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(Xr(s,n),0,n):o[c]=n,o},"I"),si=a((t,e)=>{let s=Jr(t);if(s===void 0)return;let r=ti(s,e);return r===void 0||Array.isArray(t)?r:{...t,[wt]:r}},"b"),Ct=Symbol("lunora.unmergeableDelta"),qs=a((t,e)=>{if("data"in t&&t.data!==void 0)return S(t.data);let s=S(t.delta);return ei(s)?e===void 0?s:si(e,s)??Ct:s},"m");var oh=new Set(Object.keys(Vt)),B=class extends b{static{a(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var je=a(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),kt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),Be=a(t=>kt.has(t?.code??""),"u");var ri=1024,$e=a(t=>{let e=t.maxBuffer??ri,s=[],r=[],i=!1,n,o=!1,c=a(()=>{let h=r.shift();if(!h)return!1;if(n)return h.reject(n),!0;if(s.length>0){let l=s.shift();return h.resolve({done:!1,value:l}),!0}return i?(h.resolve({done:!0,value:void 0}),!0):(r.unshift(h),!1)},"u"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(h){if(!(i||n))for(n=h,s.length=0;c(););},push(h){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(h),c()}}},d=a(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(s.length>0){let h=s.shift();return Promise.resolve({done:!1,value:h})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((h,l)=>{r.push({reject:l,resolve:h})})},return(){return d(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var Ks=/^ /u,js=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"h"),ii=a(t=>{let e="",s=[];for(let r of t.split(`
|
|
2
|
+
`))r.startsWith("event:")?e=r.slice(6).replace(Ks,""):r.startsWith("data:")&&s.push(r.slice(5).replace(Ks,""));return{data:s.join(`
|
|
3
|
+
`),event:e}},"S"),ni=a((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),d=r[u];if(d===void 0)throw new b("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(js(d))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,js(u));let o=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"T"),ai=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"),oi=a(async(t,e)=>{let s=t.getReader(),r=new TextDecoder,i="",n=!1,o=a(u=>{let d=n?`\r${u}`:u;n=d.endsWith("\r"),n&&(d=d.slice(0,-1)),i+=d.replaceAll(`\r
|
|
4
|
+
`,`
|
|
5
|
+
`)},"l"),c=a(()=>{let u=i.indexOf(`
|
|
6
|
+
|
|
7
|
+
`);for(;u!==-1;){let d=ii(i.slice(0,u));if(i=i.slice(u+2),ai(d,e))return!0;u=i.indexOf(`
|
|
8
|
+
|
|
9
|
+
`)}return!1},"d");for(;;){let{done:u,value:d}=await s.read();if(u)break;if(o(r.decode(d,{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"),Bs=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=ni(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:d}=$e({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let h=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await oi(h.body,u)}finally{c()}})().catch(h=>{if(n.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new b("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"_");var ci=/["\\\u0000-\u001F\uD800-\uDFFF]/,$s=a(t=>ci.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 $s(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+=$s(o),i+=":",i+=Tt(c))}return i+"}"},"i"),X=a(t=>Tt(R(t)),"u");var Q=class t{static{a(this,"t")}static key(e,s,r){return`${e}::${X(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,Hs=a(()=>Et,"h"),ui=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Ws=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),Z=a((t,e)=>{Ws(t,ui(e,t.optimisticLayers))},"y"),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),Ws(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(()=>{Z(t,t.serverBase)},"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")}},"g"),We=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},"k"),zs=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),de=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),Vs=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(Q.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 d=It(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");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"),hi=a((t,e)=>{let s=Ot(e);if(!(s===void 0||je(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"),le=a(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"l"),di=a(()=>new B("LunoraClient: batch slot carried no error envelope"),"m"),Gs=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"),Js=a(t=>{let{code:e,messageText:s}=Gs(t,"stream error");return e===void 0?new Error(s):new b(e,s)},"g"),Rt=a(t=>{let{code:e,messageText:s}=Gs(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"A"),ze=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=ze(t),r=hi(s,e);return r!==void 0&&(s.data=r),s},"y"),Ve=a(t=>{let e=le(t);return e===void 0?di():ze(e)},"h");var Ys=0,li=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Ys+=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)}_${Ys.toString(36)}_${t}`},"d"),Ft=a((t,e)=>t!==void 0&&e!==t,"f"),Je=li,ee=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"),Ge=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??=Je(),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=>{ee(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 ee(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(Ft(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{ee(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=>{ee(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){ee(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=>{ee(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 fi="lunora-outbox",pi="offline-mutations",Pt="by_id",mi=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??fi,r=t.storeName??pi,i=Ue(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Pt,"id",{unique:!0})}),n=Ne(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(Pt).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(Pt).getKey(o.id));u!==void 0&&await x(c.put(o,u))})},"replace")}},"w"),Xs=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return mi()}},"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 Zs=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?X(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:X(o.value)===n}},"c");var xt=500,or=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Se");new TextDecoder;var yi=new TextEncoder,bi=a(t=>Qs(yi.encode(JSON.stringify(t))),"tt"),gi="x-lunora-expect-subject",vi=a(t=>bi({subject:t}),"rt"),er=Symbol.for("lunora:session-change"),Si="lunora:session-change",wi="better-auth.message",Ci="signout",cr=a(()=>{let t=globalThis,e=t[er];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[er]=e),e},"ge"),ki=a(()=>"document"in globalThis,"ot"),Ti=a(async()=>{let t=[];for(let e of cr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"ct"),Ei=a((t,e)=>{if(t!==wi||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Ci}catch{return!1}},"dt"),Ii=a(t=>{let e=[],s=a(()=>{Ti().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(Si):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=>{Ei(o.key,o.newValue)&&s()},"n");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"ut"),Oi=a(t=>{let e=cr();return e.listeners.add(t),e.detach===void 0&&ki()&&(e.detach=Ii(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"ht"),Ri="/_lunora/rpc",Qt="/_lunora/rpc-batch",Ai="/_lunora/ws",Fi="/_lunora/admin/shard-traffic",Pi="/_lunora/admin/scheduled",Mi="/_lunora/admin/scheduled/status",xi="/_lunora/admin/scheduled/ws",Qi="/_lunora/admin/scheduled/cancel",tr="/_lunora/admin/scheduled/dead",_i="/_lunora/admin/scheduled/dead/retry",Li="/_lunora/admin/scheduled/dead/cancel",Di="/_lunora/admin/workflows/instances",Ui="/_lunora/admin/workflows/instance",Ni="/_lunora/admin/workflows/status",Bt="/_lunora/admin/storage",qi="/_lunora/admin/storage/url",Ki="/_lunora/admin/storage/buckets",ji="/_lunora/admin/functions",Bi="/_lunora/admin/cron-jobs",$i="/_lunora/admin/cron-jobs/run",Hi="/_lunora/admin/architecture",Wi="/_lunora/admin/openapi",zi="/_lunora/admin/openrpc",Vi="/_lunora/admin/global/tables",Gi="/_lunora/admin/global/table",Ji="/_lunora/admin/global/facet",Yi="/_lunora/admin/vector/indexes",Xi="/_lunora/admin/vector/query",Zi="/_lunora/admin/logs/archive",en="/_lunora/admin/kv/namespaces",tn="/_lunora/admin/kv/keys",$t="/_lunora/admin/kv/value",sn="/_lunora/admin/auth/users",rn="/_lunora/admin/auth/sessions",nn="/_lunora/admin/auth/users/create",an="/_lunora/admin/auth/users/role",on="/_lunora/admin/auth/users/ban",cn="/_lunora/admin/auth/users/unban",un="/_lunora/admin/auth/users/password",hn="/_lunora/admin/auth/users/remove",dn="/_lunora/admin/auth/users/impersonate",ln="/_lunora/admin/auth/sessions/revoke",fn="/_lunora/admin/auth/sessions/revoke-all",pn="/_lunora/admin/auth/capabilities",mn="/_lunora/admin/auth/users/update",yn="/_lunora/admin/auth/accounts",bn="/_lunora/admin/auth/accounts/unlink",gn="/_lunora/admin/auth/passkeys",vn="/_lunora/admin/auth/passkeys/delete",Sn="/_lunora/admin/auth/two-factor/disable",wn="/_lunora/admin/auth/organizations",Cn="/_lunora/admin/auth/organizations/members",kn="/_lunora/admin/auth/organizations/invitations",Tn="/_lunora/admin/auth/organizations/members/remove",En="/_lunora/admin/auth/organizations/invitations/cancel",In="/_lunora/admin/auth/config",On="/_lunora/admin/auth/sign-up-invitations",Rn="/_lunora/admin/auth/sign-up-invitations/create",An="/_lunora/admin/auth/sign-up-invitations/revoke",Fn="/_lunora/admin/auth/organizations/create",Pn="/_lunora/admin/auth/organizations/update",Mn="/_lunora/admin/auth/organizations/remove",xn="/_lunora/admin/auth/organizations/members/add",Qn="/_lunora/admin/auth/organizations/members/invite",_n="/_lunora/admin/auth/organizations/members/role",Ln="/_lunora/admin/auth/organizations/teams",Dn="/_lunora/admin/auth/organizations/teams/create",Un="/_lunora/admin/auth/organizations/teams/update",Nn="/_lunora/admin/auth/organizations/teams/remove",qn="/_lunora/admin/auth/organizations/teams/members",Kn="/_lunora/admin/auth/organizations/teams/members/add",jn="/_lunora/admin/auth/organizations/teams/members/remove",Bn="/_lunora/admin/auth/organizations/roles",$n="/_lunora/admin/auth/organizations/roles/create",Hn="/_lunora/admin/auth/organizations/roles/update",Wn="/_lunora/admin/auth/organizations/roles/remove",zn="/api/auth",Vn="/get-session",Gn="lunora-ping",Jn=a(async t=>(t.assertOpen(),(await t.adminFetch(ji,"GET")).functions??[]),"Hs"),Yn=a(async t=>(t.assertOpen(),(await t.adminFetch(Bi,"GET")).jobs??[]),"Ls"),Xn=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch($i,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Ms"),Zn=a(async t=>(t.assertOpen(),await t.adminFetch(Wi,"GET")),"Us"),ea=a(async t=>(t.assertOpen(),await t.adminFetch(Hi,"GET")),"Ns"),ta=a(async t=>(t.assertOpen(),await t.adminFetch(zi,"GET")),"xs"),sa=a(async t=>(t.assertOpen(),await t.adminFetch(Vi,"GET")),"Ds"),ra=a(async(t,e)=>{t.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 t.adminFetch(`${Gi}?${s.toString()}`,"GET"))},"Bs"),ia=a(async(t,e)=>{t.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 t.adminFetch(`${Ji}?${s.toString()}`,"GET"))},"Qs"),Ht=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"re"),sr=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"fe"),te=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"k"),P=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}`},"b"),na=a(async t=>(t.assertOpen(),(await t.adminFetch(en,"GET")).namespaces??[]),"Ks"),aa=a(async(t,e)=>{t.assertOpen();let s=P(tn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"qs"),oa=a(async(t,e)=>{t.assertOpen();let s=P($t,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Ws"),ca=a(async(t,e)=>{t.assertOpen(),await t.adminFetch($t,"PUT",e)},"js"),ua=a(async(t,e)=>{t.assertOpen();let s=P($t,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"$s"),ha=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Fi,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"Gs"),da=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(Zi,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"Vs"),la=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}},"zs"),Wt=a(t=>"args"in t?{...t,args:S(t.args)}:t,"ie"),fa=a(async t=>(t.assertOpen(),((await t.adminFetch(Pi,"GET")).records??[]).map(e=>Wt(e))),"Js"),pa=a(async t=>{t.assertOpen();let e=await t.adminFetch(Mi,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Ys"),ma=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Qi,"POST",{id:e})).cancelled===!0}),"Xs"),ya=a(async t=>(t.assertOpen(),(await la(async e=>await t.adminFetch(e===void 0?tr:`${tr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Wt(e))),"Zs"),ba=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(_i,"POST",{id:e})).retried===!0}),"er"),ga=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Li,"POST",{id:e})).removed===!0}),"tr"),va=a(async(t,e)=>{t.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 t.adminFetch(`${Di}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"sr"),Sa=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${Ui}?${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??[]}},"rr"),wa=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(Ni,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"ir"),Ca=a(async(t,e={})=>{t.assertOpen();let s=P(Bt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"nr"),ka=a(async(t,e,s)=>{t.assertOpen();let r=`${Bt}?key=${encodeURIComponent(e)}${Ht(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"ar"),Ta=a(async t=>(t.assertOpen(),(await t.adminFetch(Ki,"GET")).buckets??[]),"or"),Ea=a(async(t,e)=>{t.assertOpen();let s=`${Bt}?key=${encodeURIComponent(e.key)}${Ht(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"cr"),Ia=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${qi}?key=${encodeURIComponent(e)}${i}${Ht(s?.bucket)}`,o=await t.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"dr"),Oa=a(async t=>(t.assertOpen(),(await t.adminFetch(Yi,"GET")).indexes??[]),"ur"),Ra=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Xi,"POST",e)).matches??[]),"hr"),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)}},"w"),rr=a(t=>{try{return R(t),!0}catch{return!1}},"pe"),ur=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Te"),Aa=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(!ur(r.body)){s[r.id]={error:Ve({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:Ve(i),ok:!1}:{ok:!0,value:S(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"lr"),_t=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),Fa=3e4,Pa=1e4,Ma=5e3,xa=3,Qa=250,_a=5e3,La=5e3,Da=64,Ua=3,Na=1e4,qa=8,Lt=a(t=>t==="connected"||t==="polling","V"),g=a(t=>t??"","l"),L=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),Ka=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)L(t,s)},"wr"),ja=new TextDecoder,Ba=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return ja.decode(t)},"Ar"),re=class{static{a(this,"_")}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()}},we=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"F"),$a=a((t,e,s)=>{we(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(Gn)}catch{}},e))},"_r"),ir=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(()=>{we(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=a(h=>{u(),r.onClose(h)},"d");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},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(h){console.error("[lunora] connection open handler threw",h)}$a(t,o,d)}}),c.addEventListener("message",h=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",h=>{t.socket===c&&d(h)}),c.addEventListener("error",()=>{t.socket===c&&d()})},"me"),Ha=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=a(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"h"),f=a(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"p"),p=a(()=>{h||(h=!0,n().then(f).finally(()=>{h=!1}).catch(()=>{}))},"m");return{isPolling:a(()=>u!==void 0&&d,"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}},"Ir"),Wa=1e4,nr=a(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Wa)});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)}},"ye"),hr=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),za=a(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||hr.has(e)||kt.has(e)},"Rr"),dr=6e4,Va=1e3,Ga={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Se=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(Ga[t]??"BAD_REQUEST",n,{data:i})},"P"),Ut=a((t,e=Math.random)=>{let s=Math.min(Va*2**Math.max(t-1,0),dr);return Math.round(s*(.5+e()*.5))},"X"),Ja=a(t=>t instanceof B||hr.has(t?.code??""),"Hr"),Ya=a((t,e,s)=>{let r=je(t);return r!==void 0&&r>0?Math.min(r,dr):Ja(t)?Ut(e,s):void 0},"Lr"),Xa=983040,Za=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Ur"),lr=new WeakSet,fr=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 lr.add(e),e},"we"),Ye=a(t=>t instanceof Error&&lr.has(t),"N"),eo=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&ur(s.body)&&e.set(s.id,s.body);return e},"Nr"),to=a(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:Ve(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:S(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:fr(e),kind:"undecodable"}}},"xr"),Dt=a((t,e)=>`${g(t)}\0${e}`,"z"),so=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)},"Dr"),Nt=class{static{a(this,"Br")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){or(this.buffers,this.maxBuffers),this.buffers.set(Dt(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(Dt(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:S(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let n=r.parts.get(s.shapeId)??[];for(let c of i)n.push(c);r.parts.set(s.shapeId,n),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=Dt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},ro=a((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),n=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=n!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==n;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,"reseed";i&&t.rows.clear(),so(t.rows,r),s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"Qr"),ar=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"be"),io=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&V(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Kr"),qt=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"Z"),Kt=a((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ee"),pr=a((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ee"),Xe=a((t,e)=>t!==void 0&&t!==e,"x"),no=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","qr"),ao=a(t=>{for(let e of t.activeSubscriptions())t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Wr"),oo=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1},"jr"),co=a((t,e,s)=>{if(Xe(s,t.identityFingerprint()))return;let r=t.leader,i=no(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"$r"),uo=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Gr"),ho=a((t,e,s,r,i,n)=>{if(Xe(n,t.identityFingerprint()))return;let o=t.subscription(e);o&&(t.dropCacheSeed(e),pr(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&We(o,r),Z(o,s))},"Vr"),lo=a((t,e,s,r)=>{if(Xe(r,t.identityFingerprint()))return;let i=t.subscription(e);i&&V(i.errorCallbacks,s)},"zr"),fo=a((t,e,s,r,i,n,o)=>{if(Xe(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&n===t.clientIdentifier()&&qt(c,i),Kt(c))},"Jr"),po=a((t,e,s)=>t!==null||e&&s===null,"Yr"),mo=[Ns],yo=Promise.resolve(),jt=class t{static{a(this,"Ae")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:a((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:a(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new Q;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new re;statusListeners=new re;tokenExpiredListeners=new re;identityChangeListeners=new re;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new re;pendingChangeListeners=new re;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Nt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??te(sr(e.url),Ai),this.wsToken=e.wsToken;let s=e.authBasePath??zn;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??Ds(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Fa,this.connectTimeoutMs=e.connectTimeoutMs??Pa,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Ma,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??xa,this.defaultConnectionContext=e.connectionContext,this.persistence=Xs(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ls(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new qe,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=yo),this.offlineQueue=new Ge(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-${Je()}`,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=Oi(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 d=this.identityFingerprint();d!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),po(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&Lt(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,d;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(h=>{c=h},"onMutationAck")})}catch(h){if(!Ye(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(or(this.clientWatermarks,qa),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,c)}if(d!==void 0)throw d;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(te(this.url,`${this.authBasePath}${Vn}`),{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&&L(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(s)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(r.shardKey);h&&L(h,{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&&L(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 Zs(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){if(!this.readyResolved)return;let i=X(s),n=ae(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=Q.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??(h=>({rows:h})),o=s.length,c=0,u=0,d=0;for(let h=0;h<o;h+=i){let l=s.slice(h,h+i),f=d,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});d+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return ha(this.adminHost,e)}async listScheduledJobs(){return fa(this.adminHost)}async schedulerStatus(){return pa(this.adminHost)}async cancelScheduledJob(e){return ma(this.adminHost,e)}async listDeadJobs(){return ya(this.adminHost)}async retryDeadJob(e){return ba(this.adminHost,e)}async removeDeadJob(e){return ga(this.adminHost,e)}async listWorkflowInstances(e){return va(this.adminHost,e)}async getWorkflowInstance(e){return Sa(this.adminHost,e)}async setWorkflowInstanceStatus(e){return wa(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=te(sr(this.url),xi),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(h,r.next()))},"a"),u=a(f=>{if(o||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;ir(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=>Wt(v))))},"onMessage")})},"c"),d=a(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"d"),h=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"u");h();let l=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),we(i),i.socket?.close(),i.socket=void 0},"h");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return Jn(this.adminHost)}async getCronJobs(){return Yn(this.adminHost)}async runCronJob(e){return Xn(this.adminHost,e)}async fetchOpenApi(){return Zn(this.adminHost)}async fetchArchitecture(){return ea(this.adminHost)}async fetchOpenRpc(){return ta(this.adminHost)}async listStorageObjects(e={}){return Ca(this.adminHost,e)}async deleteStorageObject(e,s){return ka(this.adminHost,e,s)}async listStorageBuckets(){return Ta(this.adminHost)}async uploadStorageObject(e){return Ea(this.adminHost,e)}async signedStorageUrl(e,s){return Ia(this.adminHost,e,s)}async listGlobalTables(){return sa(this.adminHost)}async readGlobalTablePage(e){return ra(this.adminHost,e)}async facetGlobalColumn(e){return ia(this.adminHost,e)}async listVectorIndexes(){return Oa(this.adminHost)}async queryVectorIndex(e){return Ra(this.adminHost,e)}async queryLogArchive(e={}){return da(this.adminHost,e)}async listKvNamespaces(){return na(this.adminHost)}async listKvKeys(e){return aa(this.adminHost,e)}async getKvValue(e){return oa(this.adminHost,e)}async putKvValue(e){return ca(this.adminHost,e)}async deleteKvKey(e){return ua(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=P(sn,{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 this.assertOpen(),await this.adminFetch(nn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(an,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(on,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(cn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(un,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(hn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(dn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(ln,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(fn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(pn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(mn,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(P(yn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(bn,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(P(gn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(vn,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(Sn,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(P(wn,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=P(Cn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=P(kn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=P(On,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Rn,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(An,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(Tn,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(En,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(In,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Fn,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Pn,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Mn,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(xn,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Qn,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(_n,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=P(Ln,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Dn,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Un,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(Nn,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=P(qn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Kn,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(jn,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=P(Bn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch($n,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Wn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=P(rn,{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=Q.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=He(r),d=He(i.onError),h=He(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=X(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),d&&c.errorCallbacks.add(d),h&&c.checkpointCallbacks.add(h),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),d&&l.errorCallbacks.delete(d),h&&l.checkpointCallbacks.delete(h),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(Q.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}=$e({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let d=this.getConnection(n),h={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:h,shardKey:n};this.streams.set(i,l);let f=d?.wsState==="open"&&L(d,h);if(!f&&d===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(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=Da;){let p=d.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))}d.pendingStreams.push(h)}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 Bs(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.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new 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())},La))}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,we(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"}`,s={activeSubscriptions:a(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:a((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:a(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:a(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:a(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:a(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:a(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:a(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:a(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:a(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:a(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:a(()=>this.clientId,"clientIdentifier"),dropCacheSeed:a(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:a((r,i,n)=>{this.ackAndAdvanceCursor(r,i,n)},"ackAndAdvanceCursor"),subscription:a(r=>this.subscriptions.get(r),"subscription")};return new Ke({channelName:e,onBecomeLeader:a(()=>{ao(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{oo(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{co(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c)=>{ho(s,r,i,n,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{uo(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n)=>{lo(s,r,i,n)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,u)=>{fo(s,r,i,n,o,c,u)},"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(te(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=le(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?ze(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 Aa(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??Je(),o=this.takeReplayCredential(r.replayCredential),c=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:u,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,d,u);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;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,H=y!=="open"&&!l&&k&&!E,fe=k&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),D=a(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,c,n,d,u,r.precondition,r.mutationId,o?.stamp),"ne");if(H||$||fe)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(G=>{I=G},"onCommitCursor")});for(let G of u)G(I);return{committed:!0,value:U}}catch(U){if(E&&k&&U instanceof TypeError&&rr(i))return D();throw this.settleFailedDirectWrite(U,I,u,d,o?.flags.authToken),U}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Ye(e)){for(let o of r)o(s);return}de(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,d,h){let l=h===void 0?this.identityFingerprint():h;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:d??`${this.clientId}:${String(f)}`,identity:l,mutationId:f,...o.length>0&&{onRejected:a(()=>{de(o)},"onRejected")},shardKey:r})}catch(p){throw de(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),Ye(y)||de(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(ae(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(Ft(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(ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),Z(e,s.value))}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,Z(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ae(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=ae(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=ae(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(()=>{})},Qa))}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.leader.status??"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&&(rr(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=Hs(),n=this.identityFingerprint(),o;try{o=await nr(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 d=o[c];if(d!==void 0){if(!d.ok){V(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:R(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await nr(async s=>e(te(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=Q.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=It(u,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=Vs(this.subscriptions,r);try{e(u,s)}catch{de(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&&!L(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.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}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:Ha({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[gi]=vi(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(te(this.url,Ri),{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 Se(c.status,c.statusText,c.headers.get("retry-after"))}let d=u;if(typeof d!="object"||d===null||Array.isArray(d))throw Se(c.status,c.statusText,c.headers.get("retry-after"));let h=le(u);if(h!==void 0)throw At(h,c.headers.get("retry-after"));if(!c.ok)throw Se(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 fr(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(te(this.url,e),{body:c,headers:n,method:s}),d;try{d=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 h=le(d);if(h!==void 0){let l=new Error(h.message??"admin request failed");throw l.code=h.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 d}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));L(e,{caps:mo,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,ir(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()},_a),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)L(e,{id:o,type:c});this.releaseIdleShard(s)}Ka(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())L(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),L(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(),we(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<Ua;){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)},Na))}}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 L(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"&&L(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=Ba(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,d=this.streams.get(c);d&&typeof u=="number"&&(d.lastSeq=u,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.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.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);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(Js(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=Q.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))}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){io(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,s,r){let i=ro(e,s,r);if(ar(e),i==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let n;try{n=qs(e,i.serverBase)}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(this.dropCacheSeed(Q.keyOf(i)),pr(i,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(qt(i,e.lastMutationId),Kt(i,!0)),this.persistQueryValue(i),We(i,i.serverCursor),s!==void 0&&zs(i,s),Z(i,n),this.tabCoordinator?.isLeader()){let o=Q.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&&qt(s,e.lastMutationId),Kt(s),this.tabCoordinator?.isLeader())){let r=Q.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),We(e,e.serverCursor)&&Z(e,e.serverBase))}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=>{ee(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&&Lt(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,Z(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,ar(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&&Lt(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 h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}let i=g(e),n=this.offlineQueue.drain(h=>g(h.shardKey)===i);if(n.length===0)return;let o=[],c=[];for(let h of n){let l=this.replayGateVerdict(h);l==="send"?o.push(h):l==="hold"&&c.push(h)}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 d=[];for(let h=0;h<u.length;h+=xt){let l=u.slice(h,h+xt),f=await this.replayBatched(l,e,s);if(d.push(...f.requeue),f.stop){d.push(...u.slice(h+xt));break}}d.length>0&&this.offlineQueue.requeue(d),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,Ut(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=Ya(s,o)??(r===null&&Be(s)?Ut(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)||za(e)}noteReplayAuthRefusal(e,s){if(!Be(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,..._t(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,..._t(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Ye(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((d,h)=>({args:se(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Za(i)>Xa)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(te(this.url,Qt),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,..._t(e.find(d=>d.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,Se(n.status,n.statusText,u),s,r)}if(!c.results){let d=le(c),h=d===void 0?Se(n.status,n.statusText,u):At(d,u);return this.settleWholeBatchError(e,h,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=eo(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=to(n.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=Be(l.error),this.shouldRequeueReplayFailure(l.error,i)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var mr=_(Gt(),1),yr=_(ie(),1);var bo=a(()=>{let t=(0,mr.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,yr.useSyncExternalStore)(s,r,i)},"S");export{jt as a,wr as b,ut as c,Mr as d,Nr as e,yt as f,bo as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as R}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as W}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import"./chunk-BOMPSVRC.js";import{f as F}from"./chunk-
|
|
1
|
+
import{i as R}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as W}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import"./chunk-BOMPSVRC.js";import{f as F}from"./chunk-B3WCNVKG.js";import"./chunk-QAQDMS6R.js";import"./chunk-OACO7GME.js";import{a as Z}from"./chunk-RWVIV3U7.js";import{a as L,b as T,c as E,d as N,e as c,f as d}from"./chunk-HCTJKP5J.js";import{a as S,e as V}from"./chunk-2IKDEUCX.js";import{d as Q,h as q,o as A,p as B}from"./chunk-HJHSQPHW.js";import{a as h,d as j,e as U,f as X,g as Y}from"./chunk-I26MS5PJ.js";var D=j(X(),1);var n=j(U(),1);var e=j(Y(),1);var _=10,y=h(g=>{let r=(0,D.c)(7),{label:i,value:a}=g,l;r[0]!==i?(l=(0,e.jsx)("span",{className:"font-mono text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),r[0]=i,r[1]=l):l=r[1];let x=a??"\u2014",s;r[2]!==x?(s=(0,e.jsx)("span",{className:"font-mono text-sm",children:x}),r[2]=x,r[3]=s):s=r[3];let m;return r[4]!==l||r[5]!==s?(m=(0,e.jsxs)("div",{className:"flex flex-col gap-0.5",children:[l,s]}),r[4]=l,r[5]=s,r[6]=m):m=r[6],m},"y"),de=h(({loadIndexes:g,runQuery:r}={})=>{let i=F(),a=Q(),[l,x]=(0,n.useState)(null),[s,m]=(0,n.useState)(null),[b,M]=(0,n.useState)(null),[w,G]=(0,n.useState)(""),[p,k]=(0,n.useState)(null),[$,C]=(0,n.useState)(null),[z,I]=(0,n.useState)(!1),f=(0,n.useRef)(0);(0,n.useEffect)(()=>{let t={cancelled:!1};return B((async()=>{try{let u=await(g??(()=>i.listVectorIndexes()))();t.cancelled||(x(u),m(null),M(v=>v??u[0]?.name??null))}catch(u){t.cancelled||(x(null),m(q(u)))}})()),()=>{t.cancelled=!0}},[i,g]);let o=l?.find(t=>t.name===b)??null,H=h(t=>{f.current+=1,M(t.currentTarget.dataset.index??null),k(null),C(null),I(!1)},"$"),J=h(t=>{G(t.target.value)},"A"),K=h(async()=>{let t=w.trim();if(b===null||t==="")return;f.current+=1;let u=f.current;I(!0),C(null);try{let v=await(r??(P=>i.queryVectorIndex(P)))({name:b,text:t,topK:_});if(u!==f.current)return;k(v)}catch(v){if(u!==f.current)return;k(null),C(q(v))}I(!1)},"D"),O=h(()=>{B(K())},"H");return(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-vector-browser",children:[s!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"vector-error",role:"alert",children:s}),l!==null&&l.length===0&&(0,e.jsx)(Z,{description:a("Indexes declared with .vectorize() or defineVectorIndex() appear here."),icon:(0,e.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,e.jsx)("path",{d:"M4 7l8-4 8 4-8 4-8-4Zm0 5 8 4 8-4M4 17l8 4 8-4"})}),testId:"vector-empty",title:a("No vector indexes.")}),l!==null&&l.length>0&&(0,e.jsx)(S,{className:"overflow-hidden py-0",children:(0,e.jsx)(V,{className:"px-0",children:(0,e.jsxs)(L,{"data-testid":"vector-table",children:[(0,e.jsx)(T,{children:(0,e.jsxs)(N,{children:[(0,e.jsx)(c,{children:a("name")}),(0,e.jsx)(c,{children:a("table")}),(0,e.jsx)(c,{children:a("dimensions")}),(0,e.jsx)(c,{children:a("metric")}),(0,e.jsx)(c,{children:a("vectors")})]})}),(0,e.jsx)(E,{children:l.map(t=>(0,e.jsxs)(N,{className:t.name===b?"border-l-2 border-l-royal-amethyst bg-muted/50":"cursor-pointer","data-index":t.name,"data-testid":`vector-row-${t.name}`,onClick:H,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.name}),(0,e.jsx)(d,{className:"font-mono text-xs",children:t.table}),(0,e.jsx)(d,{className:"tabular-nums",children:t.dimensions??"\u2014"}),(0,e.jsx)(d,{children:t.metric??"\u2014"}),(0,e.jsx)(d,{className:"tabular-nums",children:t.vectorsCount??"\u2014"})]},t.name))})]})})}),o!==null&&(0,e.jsxs)("section",{className:"border border-border bg-card p-3","data-testid":"vector-detail",children:[(0,e.jsxs)("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:[(0,e.jsx)(y,{label:a("field"),value:o.field}),(0,e.jsx)(y,{label:a("dimensions"),value:o.dimensions}),(0,e.jsx)(y,{label:a("metric"),value:o.metric}),(0,e.jsx)(y,{label:a("vectors"),value:o.vectorsCount})]}),o.metadata!==void 0&&o.metadata.length>0&&(0,e.jsxs)("p",{className:"mt-3 text-xs text-muted-foreground","data-testid":"vector-metadata",children:[a("metadata"),": ",(0,e.jsx)("span",{className:"font-mono",children:o.metadata.join(", ")})]}),(0,e.jsxs)("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(0,e.jsx)(R,{className:"min-w-[18rem] flex-1","data-testid":"vector-query-input",onChange:J,placeholder:a("Search by similarity\u2026"),value:w}),(0,e.jsx)(W,{"data-testid":"vector-search",disabled:z||w.trim()==="",onClick:O,children:a(z?"Searching\u2026":"Search")})]}),$!==null&&(0,e.jsx)("p",{className:"mt-2 text-sm text-destructive","data-testid":"vector-query-error",role:"alert",children:$}),p!==null&&p.length===0&&(0,e.jsx)("p",{className:"mt-2 text-sm text-muted-foreground","data-testid":"vector-no-matches",children:a("No matches.")}),p!==null&&p.length>0&&(0,e.jsx)(S,{className:"mt-3 overflow-hidden py-0",children:(0,e.jsx)(V,{className:"px-0",children:(0,e.jsxs)(L,{"data-testid":"vector-matches",children:[(0,e.jsx)(T,{children:(0,e.jsxs)(N,{children:[(0,e.jsx)(c,{children:a("id")}),(0,e.jsx)(c,{children:a("score")}),(0,e.jsx)(c,{children:a("metadata")})]})}),(0,e.jsx)(E,{children:p.map(t=>(0,e.jsxs)(N,{"data-testid":`vector-match-${t.id}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.id}),(0,e.jsx)(d,{className:"tabular-nums",children:t.score.toFixed(4)}),(0,e.jsx)(d,{className:"max-w-md truncate font-mono text-xs",children:t.metadata===void 0?"\u2014":A(t.metadata)})]},t.id))})]})})})]})]})},"de");export{de as VectorBrowser};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as se}from"./chunk-FPI7AMQJ.js";import{i as ae}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as W}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import"./chunk-BOMPSVRC.js";import{a as G}from"./chunk-4ZEL6BYL.js";import{c as ne}from"./chunk-6SCG75PE.js";import{f as V}from"./chunk-FXQJJMQ3.js";import"./chunk-QAQDMS6R.js";import"./chunk-OACO7GME.js";import{a as B}from"./chunk-RWVIV3U7.js";import{a as j,b as D,c as F,d as x,e as i,f as d}from"./chunk-HCTJKP5J.js";import{a as R,e as _}from"./chunk-2IKDEUCX.js";import{d as X,f as Y,g as Z,h as $,m as ee,p as A}from"./chunk-HJHSQPHW.js";import{a as s,d as re,e as oe,g as le}from"./chunk-I26MS5PJ.js";var l=re(oe(),1);var e=re(le(),1);var ie=["queued","running","paused","waiting","complete","errored","terminated"],de=["pause","resume","terminate"],ce="WORKFLOWS_NOT_CONFIGURED",ue=s(o=>typeof o=="object"&&o!==null&&o.code===ce,"ce"),me=s(o=>{let a=o.error??o.output;if(a===void 0)return"\u2014";try{return JSON.stringify(a,ee)}catch{return"(unserializable)"}},"ue"),fe=s(({loadDetail:o,loadInstances:a,readOnly:g,runAction:J,workflowName:k})=>{let T=V(),n=X(),[N,v]=(0,l.useState)(null),[C,I]=(0,l.useState)(null),[b,z]=(0,l.useState)(""),[y,p]=(0,l.useState)(null),[L,O]=(0,l.useState)(!1),[P,U]=(0,l.useState)(null),f=(0,l.useRef)(0),h=(0,l.useRef)(0),w=(0,l.useRef)(0),q=o??(r=>T.getWorkflowInstance(r)),E=g?void 0:J??(a===void 0?r=>T.setWorkflowInstanceStatus(r):void 0),K=s(async()=>{h.current+=1;let r=h.current;p(null),O(!1);let c=b===""?void 0:b;try{if(a===void 0){let u=await T.listWorkflowInstances({name:k,status:c});if(r!==h.current)return;if(u.configured===!1){v(null),O(!0);return}v(u.instances);return}let t=await a({name:k,status:c});r===h.current&&v(t)}catch(t){if(r!==h.current)return;v(null),ue(t)?O(!0):p($(t))}},"P");(0,l.useEffect)(()=>{f.current+=1,w.current+=1,I(null),A(K())},[k,b]);let M=s(async r=>{w.current+=1;let c=w.current;p(null);try{let t=await q({id:r,name:k});c===w.current&&I(t)}catch(t){c===w.current&&p($(t))}},"J"),H=s(()=>{w.current+=1,I(null)},"B"),Q=s(async(r,c)=>{if(E===void 0)return;let t=f.current;U(r),p(null);try{await E({action:c,id:r,name:k}),t===f.current&&await K()}catch(u){p($(u))}U(null)},"K");return(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-workflow-instances",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:n("Instance history")}),(0,e.jsxs)("select",{"aria-label":n("Filter by status"),className:"h-8 rounded-md border border-input bg-transparent px-2.5 py-1 text-xs outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50","data-testid":"workflow-instances-filter",onChange:s(r=>{z(r.target.value)},"onChange"),value:b,children:[(0,e.jsx)("option",{value:"",children:n("All statuses")}),ie.map(r=>(0,e.jsx)("option",{value:r,children:r},r))]})]}),y!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflow-instances-error",role:"alert",children:y}),L&&(0,e.jsx)(B,{description:n("Set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN in your .dev.vars to enable workflow instance history."),testId:"workflow-instances-unconfigured",title:n("Workflow inspection not configured")}),!L&&N!==null&&N.length===0&&(0,e.jsx)(B,{description:n("No instances match this filter for the selected workflow."),testId:"workflow-instances-empty",title:n("No instances")}),N!==null&&N.length>0&&(0,e.jsx)(R,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflow-instances-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:n("Instance id")}),(0,e.jsx)(i,{children:n("Status")}),(0,e.jsx)(i,{children:n("Created")}),(0,e.jsx)(i,{children:n("Ended")}),(0,e.jsx)(i,{"aria-label":n("Actions")})]})}),(0,e.jsx)(F,{children:N.map(r=>(0,e.jsxs)(x,{"data-testid":`workflow-instance-${r.id}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:r.id}),(0,e.jsx)(d,{className:"font-mono text-xs",children:r.status}),(0,e.jsx)(d,{className:"text-muted-foreground tabular-nums",children:r.createdOn??"\u2014"}),(0,e.jsx)(d,{className:"text-muted-foreground tabular-nums",children:r.endedOn??"\u2014"}),(0,e.jsx)(d,{className:"text-right",children:(0,e.jsxs)("div",{className:"flex justify-end gap-1.5",children:[(0,e.jsx)(W,{"data-testid":`workflow-instance-steps-${r.id}`,onClick:s(()=>{A(M(r.id))},"onClick"),size:"sm",type:"button",variant:"outline",children:n("Steps")}),E!==void 0&&de.map(c=>(0,e.jsx)(W,{"data-testid":`workflow-instance-${c}-${r.id}`,disabled:P===r.id,onClick:s(()=>{A(Q(r.id,c))},"onClick"),size:"sm",type:"button",variant:"ghost",children:n(c)},c))]})})]},r.id))})]})})}),C!==null&&(0,e.jsx)(R,{className:"overflow-hidden py-0","data-testid":"workflow-instance-detail",children:(0,e.jsxs)(_,{className:"flex flex-col gap-2 px-4 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("span",{className:"font-mono text-xs",children:[n("Steps")," \xB7 ",C.id]}),(0,e.jsx)(W,{"data-testid":"workflow-instance-detail-close",onClick:H,size:"xs",type:"button",variant:"ghost",children:n("Close")})]}),C.steps.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:n("This instance has no recorded steps yet.")}):(0,e.jsxs)(j,{"data-testid":"workflow-instance-steps",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:n("Step")}),(0,e.jsx)(i,{children:n("Type")}),(0,e.jsx)(i,{children:n("Attempts")}),(0,e.jsx)(i,{children:n("Started")}),(0,e.jsx)(i,{children:n("Output")})]})}),(0,e.jsx)(F,{children:C.steps.map((r,c)=>(0,e.jsxs)(x,{"data-testid":`workflow-step-${String(c)}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:r.name}),(0,e.jsx)(d,{className:"text-xs text-muted-foreground",children:r.type??"\u2014"}),(0,e.jsx)(d,{className:"tabular-nums",children:r.attempts??"\u2014"}),(0,e.jsx)(d,{className:"text-muted-foreground tabular-nums",children:r.start??"\u2014"}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:me(r)})]},`${r.name}:${String(c)}`))})]})]})})]})},"me"),he=Y(G.createWorkflowInstance),pe=Y(G.getWorkflowInstanceStatus),we=s(o=>{if(o.error)return`${o.error.name}: ${o.error.message}`;if(o.output===void 0)return"\u2014";try{return JSON.stringify(o.output,ee)}catch{return"(unserializable)"}},"pe"),xe=s((o,a)=>o.some(g=>g.exportName===a)?a:o[0]?.exportName??"","xe"),$e=s(()=>{let o=V(),a=X(),{data:g,error:J}=ne(G.listWorkflows,{}),[k,T]=(0,l.useState)(""),[n,N]=(0,l.useState)(""),[v,C]=(0,l.useState)(""),[I,b]=(0,l.useState)(!1),[z,y]=(0,l.useState)(null),[p,L]=(0,l.useState)([]),[O,P]=(0,l.useState)(null),U=g!==void 0,f=Array.isArray(g?.workflows)?[...g.workflows].toSorted((t,u)=>t.exportName.localeCompare(u.exportName)):[],h=xe(f,k),w=f.find(t=>t.exportName===h),q=s(t=>{L(u=>{let m=u.filter(S=>!(S.exportName===t.exportName&&S.id===t.id));return[t,...m]})},"D"),E=s(async()=>{let t=h;if(t==="")return;let u,m=v.trim();if(m!=="")try{u=JSON.parse(m)}catch{y(a("Params must be valid JSON"));return}b(!0),y(null);try{let S=n.trim(),te=await o.query(he,{exportName:t,id:S===""?void 0:S,params:u},Z(""));q({exportName:t,id:te.id,status:te.status}),N("")}catch(S){y($(S))}b(!1)},"Q"),K=s(()=>{A(E())},"V"),M=s(async(t,u)=>{P(u);try{let m=await o.query(pe,{exportName:t,id:u},Z(""));q({error:m.error,exportName:t,id:m.id,output:m.output,status:m.status})}catch(m){y($(m))}P(null)},"O"),H=s(t=>{T(t.target.value)},"P"),Q=s(t=>{N(t.target.value)},"J"),r=s(t=>{C(t.target.value)},"B"),c=s(t=>{let{export:u,id:m}=t.currentTarget.dataset;u!==void 0&&m!==void 0&&A(M(u,m))},"K");return(0,e.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-workflows-panel",children:[J!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflows-error",role:"alert",children:J}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:a("Workflows are declared in code with defineWorkflow and run as durable Cloudflare Workflows. Start an instance and observe its status below.")}),U&&f.length===0?(0,e.jsx)(B,{description:a("No defineWorkflow is declared in lunora/workflows.ts in this deployment. Add one to run a durable, multi-step workflow."),testId:"workflows-empty",title:a("No workflows defined")}):(0,e.jsx)(R,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflows-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:a("Export")}),(0,e.jsx)(i,{children:a("Name")}),(0,e.jsx)(i,{children:a("Class")})]})}),(0,e.jsx)(F,{children:f.map(t=>(0,e.jsxs)(x,{"data-testid":`workflows-row-${t.exportName}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.exportName}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:t.name}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:t.className})]},t.exportName))})]})})}),f.length>0&&(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"workflows-start",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:a("Start instance")}),z!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflows-start-error",role:"alert",children:z}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)("select",{"aria-label":a("Workflow"),className:"h-8 rounded-md border border-input bg-transparent px-2.5 py-1 text-xs outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50","data-testid":"workflows-start-select",onChange:H,value:h,children:f.map(t=>(0,e.jsx)("option",{value:t.exportName,children:t.exportName},t.exportName))}),(0,e.jsx)(ae,{"aria-label":a("Instance id (optional)"),className:"max-w-48","data-testid":"workflows-start-id",onChange:Q,placeholder:a("Instance id (optional)"),value:n}),(0,e.jsx)(W,{"data-testid":"workflows-start-button",disabled:I||h==="",onClick:K,children:a(I?"Starting\u2026":"Start instance")})]}),(0,e.jsx)(se,{"aria-label":a("Params (JSON)"),className:"font-mono","data-testid":"workflows-start-params",onChange:r,placeholder:a("Params (JSON, optional)"),value:v})]}),p.length>0&&(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"workflows-instances",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:a("Instances")}),(0,e.jsx)(R,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflows-instances-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:a("Workflow")}),(0,e.jsx)(i,{children:a("Instance id")}),(0,e.jsx)(i,{children:a("Status")}),(0,e.jsx)(i,{children:a("Output")}),(0,e.jsx)(i,{})]})}),(0,e.jsx)(F,{children:p.map(t=>(0,e.jsxs)(x,{"data-testid":`workflows-instance-${t.id}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.exportName}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:t.id}),(0,e.jsx)(d,{className:"font-mono text-xs",children:t.status}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:we(t)}),(0,e.jsx)(d,{children:(0,e.jsx)(W,{"data-export":t.exportName,"data-id":t.id,"data-testid":`workflows-instance-refresh-${t.id}`,disabled:O===t.id,onClick:c,size:"xs",variant:"outline",children:O===t.id?a("Refreshing\u2026"):a("Refresh")})})]},`${t.exportName}:${t.id}`))})]})})})]}),w!==void 0&&(0,e.jsx)(fe,{workflowName:w.name})]})},"We");export{$e as default};
|
|
1
|
+
import{a as se}from"./chunk-FPI7AMQJ.js";import{i as ae}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as W}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import"./chunk-BOMPSVRC.js";import{a as G}from"./chunk-4ZEL6BYL.js";import{c as ne}from"./chunk-W7TF6FTU.js";import{f as V}from"./chunk-B3WCNVKG.js";import"./chunk-QAQDMS6R.js";import"./chunk-OACO7GME.js";import{a as B}from"./chunk-RWVIV3U7.js";import{a as j,b as D,c as F,d as x,e as i,f as d}from"./chunk-HCTJKP5J.js";import{a as R,e as _}from"./chunk-2IKDEUCX.js";import{d as X,f as Y,g as Z,h as $,m as ee,p as A}from"./chunk-HJHSQPHW.js";import{a as s,d as re,e as oe,g as le}from"./chunk-I26MS5PJ.js";var l=re(oe(),1);var e=re(le(),1);var ie=["queued","running","paused","waiting","complete","errored","terminated"],de=["pause","resume","terminate"],ce="WORKFLOWS_NOT_CONFIGURED",ue=s(o=>typeof o=="object"&&o!==null&&o.code===ce,"ce"),me=s(o=>{let a=o.error??o.output;if(a===void 0)return"\u2014";try{return JSON.stringify(a,ee)}catch{return"(unserializable)"}},"ue"),fe=s(({loadDetail:o,loadInstances:a,readOnly:g,runAction:J,workflowName:k})=>{let T=V(),n=X(),[N,v]=(0,l.useState)(null),[C,I]=(0,l.useState)(null),[b,z]=(0,l.useState)(""),[y,p]=(0,l.useState)(null),[L,O]=(0,l.useState)(!1),[P,U]=(0,l.useState)(null),f=(0,l.useRef)(0),h=(0,l.useRef)(0),w=(0,l.useRef)(0),q=o??(r=>T.getWorkflowInstance(r)),E=g?void 0:J??(a===void 0?r=>T.setWorkflowInstanceStatus(r):void 0),K=s(async()=>{h.current+=1;let r=h.current;p(null),O(!1);let c=b===""?void 0:b;try{if(a===void 0){let u=await T.listWorkflowInstances({name:k,status:c});if(r!==h.current)return;if(u.configured===!1){v(null),O(!0);return}v(u.instances);return}let t=await a({name:k,status:c});r===h.current&&v(t)}catch(t){if(r!==h.current)return;v(null),ue(t)?O(!0):p($(t))}},"P");(0,l.useEffect)(()=>{f.current+=1,w.current+=1,I(null),A(K())},[k,b]);let M=s(async r=>{w.current+=1;let c=w.current;p(null);try{let t=await q({id:r,name:k});c===w.current&&I(t)}catch(t){c===w.current&&p($(t))}},"J"),H=s(()=>{w.current+=1,I(null)},"B"),Q=s(async(r,c)=>{if(E===void 0)return;let t=f.current;U(r),p(null);try{await E({action:c,id:r,name:k}),t===f.current&&await K()}catch(u){p($(u))}U(null)},"K");return(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-workflow-instances",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:n("Instance history")}),(0,e.jsxs)("select",{"aria-label":n("Filter by status"),className:"h-8 rounded-md border border-input bg-transparent px-2.5 py-1 text-xs outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50","data-testid":"workflow-instances-filter",onChange:s(r=>{z(r.target.value)},"onChange"),value:b,children:[(0,e.jsx)("option",{value:"",children:n("All statuses")}),ie.map(r=>(0,e.jsx)("option",{value:r,children:r},r))]})]}),y!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflow-instances-error",role:"alert",children:y}),L&&(0,e.jsx)(B,{description:n("Set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN in your .dev.vars to enable workflow instance history."),testId:"workflow-instances-unconfigured",title:n("Workflow inspection not configured")}),!L&&N!==null&&N.length===0&&(0,e.jsx)(B,{description:n("No instances match this filter for the selected workflow."),testId:"workflow-instances-empty",title:n("No instances")}),N!==null&&N.length>0&&(0,e.jsx)(R,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflow-instances-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:n("Instance id")}),(0,e.jsx)(i,{children:n("Status")}),(0,e.jsx)(i,{children:n("Created")}),(0,e.jsx)(i,{children:n("Ended")}),(0,e.jsx)(i,{"aria-label":n("Actions")})]})}),(0,e.jsx)(F,{children:N.map(r=>(0,e.jsxs)(x,{"data-testid":`workflow-instance-${r.id}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:r.id}),(0,e.jsx)(d,{className:"font-mono text-xs",children:r.status}),(0,e.jsx)(d,{className:"text-muted-foreground tabular-nums",children:r.createdOn??"\u2014"}),(0,e.jsx)(d,{className:"text-muted-foreground tabular-nums",children:r.endedOn??"\u2014"}),(0,e.jsx)(d,{className:"text-right",children:(0,e.jsxs)("div",{className:"flex justify-end gap-1.5",children:[(0,e.jsx)(W,{"data-testid":`workflow-instance-steps-${r.id}`,onClick:s(()=>{A(M(r.id))},"onClick"),size:"sm",type:"button",variant:"outline",children:n("Steps")}),E!==void 0&&de.map(c=>(0,e.jsx)(W,{"data-testid":`workflow-instance-${c}-${r.id}`,disabled:P===r.id,onClick:s(()=>{A(Q(r.id,c))},"onClick"),size:"sm",type:"button",variant:"ghost",children:n(c)},c))]})})]},r.id))})]})})}),C!==null&&(0,e.jsx)(R,{className:"overflow-hidden py-0","data-testid":"workflow-instance-detail",children:(0,e.jsxs)(_,{className:"flex flex-col gap-2 px-4 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("span",{className:"font-mono text-xs",children:[n("Steps")," \xB7 ",C.id]}),(0,e.jsx)(W,{"data-testid":"workflow-instance-detail-close",onClick:H,size:"xs",type:"button",variant:"ghost",children:n("Close")})]}),C.steps.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:n("This instance has no recorded steps yet.")}):(0,e.jsxs)(j,{"data-testid":"workflow-instance-steps",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:n("Step")}),(0,e.jsx)(i,{children:n("Type")}),(0,e.jsx)(i,{children:n("Attempts")}),(0,e.jsx)(i,{children:n("Started")}),(0,e.jsx)(i,{children:n("Output")})]})}),(0,e.jsx)(F,{children:C.steps.map((r,c)=>(0,e.jsxs)(x,{"data-testid":`workflow-step-${String(c)}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:r.name}),(0,e.jsx)(d,{className:"text-xs text-muted-foreground",children:r.type??"\u2014"}),(0,e.jsx)(d,{className:"tabular-nums",children:r.attempts??"\u2014"}),(0,e.jsx)(d,{className:"text-muted-foreground tabular-nums",children:r.start??"\u2014"}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:me(r)})]},`${r.name}:${String(c)}`))})]})]})})]})},"me"),he=Y(G.createWorkflowInstance),pe=Y(G.getWorkflowInstanceStatus),we=s(o=>{if(o.error)return`${o.error.name}: ${o.error.message}`;if(o.output===void 0)return"\u2014";try{return JSON.stringify(o.output,ee)}catch{return"(unserializable)"}},"pe"),xe=s((o,a)=>o.some(g=>g.exportName===a)?a:o[0]?.exportName??"","xe"),$e=s(()=>{let o=V(),a=X(),{data:g,error:J}=ne(G.listWorkflows,{}),[k,T]=(0,l.useState)(""),[n,N]=(0,l.useState)(""),[v,C]=(0,l.useState)(""),[I,b]=(0,l.useState)(!1),[z,y]=(0,l.useState)(null),[p,L]=(0,l.useState)([]),[O,P]=(0,l.useState)(null),U=g!==void 0,f=Array.isArray(g?.workflows)?[...g.workflows].toSorted((t,u)=>t.exportName.localeCompare(u.exportName)):[],h=xe(f,k),w=f.find(t=>t.exportName===h),q=s(t=>{L(u=>{let m=u.filter(S=>!(S.exportName===t.exportName&&S.id===t.id));return[t,...m]})},"D"),E=s(async()=>{let t=h;if(t==="")return;let u,m=v.trim();if(m!=="")try{u=JSON.parse(m)}catch{y(a("Params must be valid JSON"));return}b(!0),y(null);try{let S=n.trim(),te=await o.query(he,{exportName:t,id:S===""?void 0:S,params:u},Z(""));q({exportName:t,id:te.id,status:te.status}),N("")}catch(S){y($(S))}b(!1)},"Q"),K=s(()=>{A(E())},"V"),M=s(async(t,u)=>{P(u);try{let m=await o.query(pe,{exportName:t,id:u},Z(""));q({error:m.error,exportName:t,id:m.id,output:m.output,status:m.status})}catch(m){y($(m))}P(null)},"O"),H=s(t=>{T(t.target.value)},"P"),Q=s(t=>{N(t.target.value)},"J"),r=s(t=>{C(t.target.value)},"B"),c=s(t=>{let{export:u,id:m}=t.currentTarget.dataset;u!==void 0&&m!==void 0&&A(M(u,m))},"K");return(0,e.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-workflows-panel",children:[J!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflows-error",role:"alert",children:J}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:a("Workflows are declared in code with defineWorkflow and run as durable Cloudflare Workflows. Start an instance and observe its status below.")}),U&&f.length===0?(0,e.jsx)(B,{description:a("No defineWorkflow is declared in lunora/workflows.ts in this deployment. Add one to run a durable, multi-step workflow."),testId:"workflows-empty",title:a("No workflows defined")}):(0,e.jsx)(R,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflows-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:a("Export")}),(0,e.jsx)(i,{children:a("Name")}),(0,e.jsx)(i,{children:a("Class")})]})}),(0,e.jsx)(F,{children:f.map(t=>(0,e.jsxs)(x,{"data-testid":`workflows-row-${t.exportName}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.exportName}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:t.name}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:t.className})]},t.exportName))})]})})}),f.length>0&&(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"workflows-start",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:a("Start instance")}),z!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflows-start-error",role:"alert",children:z}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)("select",{"aria-label":a("Workflow"),className:"h-8 rounded-md border border-input bg-transparent px-2.5 py-1 text-xs outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50","data-testid":"workflows-start-select",onChange:H,value:h,children:f.map(t=>(0,e.jsx)("option",{value:t.exportName,children:t.exportName},t.exportName))}),(0,e.jsx)(ae,{"aria-label":a("Instance id (optional)"),className:"max-w-48","data-testid":"workflows-start-id",onChange:Q,placeholder:a("Instance id (optional)"),value:n}),(0,e.jsx)(W,{"data-testid":"workflows-start-button",disabled:I||h==="",onClick:K,children:a(I?"Starting\u2026":"Start instance")})]}),(0,e.jsx)(se,{"aria-label":a("Params (JSON)"),className:"font-mono","data-testid":"workflows-start-params",onChange:r,placeholder:a("Params (JSON, optional)"),value:v})]}),p.length>0&&(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"workflows-instances",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:a("Instances")}),(0,e.jsx)(R,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflows-instances-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(x,{children:[(0,e.jsx)(i,{children:a("Workflow")}),(0,e.jsx)(i,{children:a("Instance id")}),(0,e.jsx)(i,{children:a("Status")}),(0,e.jsx)(i,{children:a("Output")}),(0,e.jsx)(i,{})]})}),(0,e.jsx)(F,{children:p.map(t=>(0,e.jsxs)(x,{"data-testid":`workflows-instance-${t.id}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.exportName}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:t.id}),(0,e.jsx)(d,{className:"font-mono text-xs",children:t.status}),(0,e.jsx)(d,{className:"font-mono text-xs text-muted-foreground",children:we(t)}),(0,e.jsx)(d,{children:(0,e.jsx)(W,{"data-export":t.exportName,"data-id":t.id,"data-testid":`workflows-instance-refresh-${t.id}`,disabled:O===t.id,onClick:c,size:"xs",variant:"outline",children:O===t.id?a("Refreshing\u2026"):a("Refresh")})})]},`${t.exportName}:${t.id}`))})]})})})]}),w!==void 0&&(0,e.jsx)(fe,{workflowName:w.name})]})},"We");export{$e as default};
|