@lunora/studio 1.0.0-alpha.176 → 1.0.0-alpha.178
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/standalone/{chunk-YKA2P52S.js → chunk-2ADU5FA5.js} +1 -1
- package/dist/standalone/{chunk-RH2G72SL.js → chunk-2NYASBOP.js} +1 -1
- package/dist/standalone/{chunk-Y3G2ZPOD.js → chunk-2W365SXI.js} +1 -1
- package/dist/standalone/{chunk-KSYIH3NO.js → chunk-2Y6PXGIS.js} +4 -4
- package/dist/standalone/{chunk-KRXDSPZ4.js → chunk-3JDH25N2.js} +1 -1
- package/dist/standalone/{chunk-L6W4QXGJ.js → chunk-5PBVNSPQ.js} +1 -1
- package/dist/standalone/{chunk-52Y5BCFW.js → chunk-5XRNQ732.js} +1 -1
- package/dist/standalone/{chunk-NXZGWCUN.js → chunk-6HVFOKP5.js} +1 -1
- package/dist/standalone/{chunk-KSRQTLE3.js → chunk-7HFDITXH.js} +1 -1
- package/dist/standalone/{chunk-3LGVSZ4D.js → chunk-AKG3SL2Z.js} +1 -1
- package/dist/standalone/{chunk-JWJFB4ZB.js → chunk-ANXXWNJG.js} +1 -1
- package/dist/standalone/{chunk-4OGX6UIE.js → chunk-BR64TOG4.js} +1 -1
- package/dist/standalone/{chunk-CO7D5QQA.js → chunk-CBNGOAD4.js} +1 -1
- package/dist/standalone/{chunk-V5PJJYCF.js → chunk-CXGPKEDJ.js} +1 -1
- package/dist/standalone/{chunk-F4W5DVWA.js → chunk-D2SSRZG5.js} +1 -1
- package/dist/standalone/{chunk-NZDNC4KZ.js → chunk-D7PVLNBP.js} +1 -1
- package/dist/standalone/{chunk-TX4KHOV2.js → chunk-E366YQXO.js} +1 -1
- package/dist/standalone/{chunk-CQ4VSTAW.js → chunk-FTR6JAWG.js} +1 -1
- package/dist/standalone/{chunk-MKRHFCPJ.js → chunk-G22LSAIH.js} +1 -1
- package/dist/standalone/{chunk-IMLGMLYE.js → chunk-GDYRC6T6.js} +1 -1
- package/dist/standalone/{chunk-4G7WDTSC.js → chunk-I3OOVU3O.js} +1 -1
- package/dist/standalone/{chunk-FKBX44FM.js → chunk-I5V3IHPF.js} +1 -1
- package/dist/standalone/{chunk-SPERI4DG.js → chunk-IBM6X4XI.js} +1 -1
- package/dist/standalone/{chunk-OS6CZ56E.js → chunk-IUKHT5XV.js} +1 -1
- package/dist/standalone/{chunk-HKPAFIMB.js → chunk-J3LCGEBD.js} +1 -1
- package/dist/standalone/{chunk-T6X7NXEE.js → chunk-KIEUFC6E.js} +1 -1
- package/dist/standalone/{chunk-X5AXABWH.js → chunk-KQMWK6QZ.js} +1 -1
- package/dist/standalone/{chunk-DL3DYOZA.js → chunk-KYMUE3MZ.js} +1 -1
- package/dist/standalone/{chunk-F7UZBTKS.js → chunk-KZDIKRZ3.js} +1 -1
- package/dist/standalone/{chunk-JXJZMINI.js → chunk-LKKZMIZK.js} +1 -1
- package/dist/standalone/{chunk-CQO3Z2AB.js → chunk-M7QQYXU4.js} +1 -1
- package/dist/standalone/{chunk-D6UKRXIS.js → chunk-MBP4SZYB.js} +1 -1
- package/dist/standalone/{chunk-5JHPL7FH.js → chunk-MNQSYFV6.js} +1 -1
- package/dist/standalone/{chunk-CWTUCGWD.js → chunk-MOMBFDIA.js} +1 -1
- package/dist/standalone/{chunk-KY7U3EOR.js → chunk-MOYNBJNW.js} +1 -1
- package/dist/standalone/{chunk-SZUW2MXD.js → chunk-MWUR2KP6.js} +1 -1
- package/dist/standalone/{chunk-GXVTU7FF.js → chunk-N2VWHDGA.js} +1 -1
- package/dist/standalone/{chunk-WDYULSDM.js → chunk-NLHKRU3D.js} +2 -2
- package/dist/standalone/{chunk-I3PD3ZML.js → chunk-P4V5VRUR.js} +1 -1
- package/dist/standalone/{chunk-XAGNBUL3.js → chunk-P6F4CNT5.js} +1 -1
- package/dist/standalone/{chunk-I4YTKLE7.js → chunk-PHYKYBCE.js} +1 -1
- package/dist/standalone/{chunk-RQPSYNGU.js → chunk-QCFJKKLX.js} +1 -1
- package/dist/standalone/{chunk-YYR4P344.js → chunk-RSULZ5QU.js} +1 -1
- package/dist/standalone/{chunk-KPISDHKV.js → chunk-RY66ZJJQ.js} +1 -1
- package/dist/standalone/{chunk-OBSMXNVJ.js → chunk-SA5SGD3V.js} +1 -1
- package/dist/standalone/{chunk-N3MMJZQW.js → chunk-TXLWUHAU.js} +1 -1
- package/dist/standalone/{chunk-XTC4KFYF.js → chunk-U2YJ64UT.js} +1 -1
- package/dist/standalone/{chunk-B62IS74K.js → chunk-U3T6FYYZ.js} +1 -1
- package/dist/standalone/{chunk-E67LBUZU.js → chunk-U7A2W7UG.js} +1 -1
- package/dist/standalone/{chunk-O7D7DJVB.js → chunk-URBHAYYZ.js} +1 -1
- package/dist/standalone/{chunk-KMLTYAJF.js → chunk-V5FOHTRB.js} +1 -1
- package/dist/standalone/{chunk-3UOVQ3YN.js → chunk-VR3OL4A6.js} +1 -1
- package/dist/standalone/{chunk-7PEQ4RPL.js → chunk-WHPKXZN2.js} +1 -1
- package/dist/standalone/{chunk-WWHDFIP5.js → chunk-WV2AW6IT.js} +1 -1
- package/dist/standalone/{chunk-VYLHUJVG.js → chunk-WX6MJS7P.js} +1 -1
- package/dist/standalone/{chunk-ERLNG3BC.js → chunk-Y5IE2W4U.js} +1 -1
- package/dist/standalone/{chunk-TPVTZE6M.js → chunk-YAAM5IKA.js} +1 -1
- package/dist/standalone/{chunk-KF2YSK5Z.js → chunk-YK7JO7NP.js} +1 -1
- package/dist/standalone/{chunk-JMXDVWZG.js → chunk-YRZFU7OM.js} +1 -1
- package/dist/standalone/chunk-Z7WCKAUJ.js +11 -0
- package/dist/standalone/{chunk-EFMYOSXQ.js → chunk-ZTA7WN4R.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +6 -6
- package/dist/standalone/chunk-VWWJIICI.js +0 -11
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{a as wt,d as p}from"./chunk-KSYIH3NO.js";import{a as o,d as F,e as G,f as Ct,g as Be}from"./chunk-YKXDMIHQ.js";var L=class{static{o(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 xr=class extends L{static{o(this,"FocusManager")}#e;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=o(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=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"}},re=new xr;var _r={setTimeout:o((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:o(t=>clearTimeout(t),"clearTimeout"),setInterval:o((t,e)=>setInterval(t,e),"setInterval"),clearInterval:o(t=>clearInterval(t),"clearInterval")},Lr=class{static{o(this,"TimeoutManager")}#e=_r;#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)}},Q=new Lr;function kt(t){setTimeout(t,0)}o(kt,"systemSetTimeoutZero");var $e=typeof window>"u"||"Deno"in globalThis;function w(){}o(w,"noop");function It(t,e){return typeof t=="function"?t(e):t}o(It,"functionalUpdate");function oe(t){return typeof t=="number"&&t>=0&&t!==1/0}o(oe,"isValidTimeout");function be(t,e){return Math.max(t+(e||0)-Date.now(),0)}o(be,"timeUntilStale");function _(t,e){return typeof t=="function"?t(e):t}o(_,"resolveStaleTime");function E(t,e){return typeof t=="function"?t(e):t}o(E,"resolveQueryBoolean");function ve(t,e){let{type:r="all",exact:s,fetchStatus:i,predicate:n,queryKey:a,stale:c}=t;if(a){if(s){if(e.queryHash!==ce(a,e.options))return!1}else if(!q(e.queryKey,a))return!1}if(r!=="all"){let u=e.isActive();if(r==="active"&&!u||r==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}o(ve,"matchQuery");function ge(t,e){let{exact:r,status:s,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(r){if(J(e.options.mutationKey)!==J(n))return!1}else if(!q(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}o(ge,"matchMutation");function ce(t,e){return(e?.queryKeyHashFn||J)(t)}o(ce,"hashQueryKeyByOptions");function J(t){return JSON.stringify(t,(e,r)=>je(r)?Object.keys(r).sort().reduce((s,i)=>(s[i]=r[i],s),{}):r)}o(J,"hashKey");function q(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 s=0;s<e.length;s++)if(!q(t[s],e[s]))return!1;return!0}let r=Object.keys(e);for(let s of r)if(!q(t[s],e[s]))return!1;return!0}return!1}o(q,"partialMatchKey");var Qr=Object.prototype.hasOwnProperty;function He(t,e,r=0){if(t===e)return t;if(r>500)return e;let s=Tt(t)&&Tt(e);if(!s&&!(je(t)&&je(e)))return e;let n=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),c=a.length,u=s?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=s?d:a[d],f=t[l],y=e[l];if(f===y){u[l]=f,(s?d<n:Qr.call(t,l))&&h++;continue}if(f===null||y===null||typeof f!="object"||typeof y!="object"){u[l]=y;continue}let m=He(f,y,r+1);u[l]=m,m===f&&h++}return n===c&&h===n?t:u}o(He,"replaceEqualDeep");function Se(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let r in t)if(t[r]!==e[r])return!1;return!0}o(Se,"shallowEqualObjects");function Tt(t){return Array.isArray(t)&&t.length===Object.keys(t).length}o(Tt,"isPlainArray");function je(t){if(!Et(t))return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(!Et(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}o(je,"isPlainObject");function Et(t){return Object.prototype.toString.call(t)==="[object Object]"}o(Et,"hasObjectPrototype");function Ot(t){return new Promise(e=>{Q.setTimeout(e,t)})}o(Ot,"sleep");function ue(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?He(t,e):e}o(ue,"replaceData");function Dr(t){return t}o(Dr,"keepPreviousData");function Rt(t,e,r=0){let s=[...t,e];return r&&s.length>r?s.slice(1):s}o(Rt,"addToEnd");function Pt(t,e,r=0){let s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}o(Pt,"addToStart");var se=Symbol();function we(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===se?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}o(we,"ensureQueryFn");function Ce(t,e){return typeof t=="function"?t(...e):!!t}o(Ce,"shouldThrowError");function At(t,e,r){let s=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:o(()=>(i??=e(),s||(s=!0,i.aborted?r():i.addEventListener("abort",r,{once:!0})),i),"get")}),t}o(At,"addConsumeAwareSignal");var D=(()=>{let t=o(()=>$e,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function he(){let t,e,r=new Promise((i,n)=>{t=i,e=n});r.status="pending",r.catch(()=>{});function s(i){Object.assign(r,i),delete r.resolve,delete r.reject}return o(s,"finalize"),r.resolve=i=>{s({status:"fulfilled",value:i}),t(i)},r.reject=i=>{s({status:"rejected",reason:i}),e(i)},r}o(he,"pendingThenable");var Ft=kt;function Ur(){let t=[],e=0,r=o(c=>{c()},"notifyFn"),s=o(c=>{c()},"batchNotifyFn"),i=Ft,n=o(c=>{e?t.push(c):i(()=>{r(c)})},"schedule"),a=o(()=>{let c=t;t=[],c.length&&i(()=>{s(()=>{c.forEach(u=>{r(u)})})})},"flush");return{batch:o(c=>{let u;e++;try{u=c()}finally{e--,e||a()}return u},"batch"),batchCalls:o(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:o(c=>{r=c},"setNotifyFunction"),setBatchNotifyFunction:o(c=>{s=c},"setBatchNotifyFunction"),setScheduler:o(c=>{i=c},"setScheduler")}}o(Ur,"createNotifyManager");var v=Ur();var Nr=class extends L{static{o(this,"OnlineManager")}#e=!0;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=o(()=>t(!0),"onlineListener"),r=o(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",r)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(r=>{r(t)}))}isOnline(){return this.#e}},ie=new Nr;function qr(t){return Math.min(1e3*2**t,3e4)}o(qr,"defaultRetryDelay");function ze(t){return(t??"online")==="online"?ie.isOnline():!0}o(ze,"canFetch");var ke=class extends Error{static{o(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Te(t){let e=!1,r=0,s,i=he(),n=o(()=>i.status!=="pending","isResolved"),a=o(b=>{if(!n()){let C=new ke(b);f(C),t.onCancel?.(C)}},"cancel"),c=o(()=>{e=!0},"cancelRetry"),u=o(()=>{e=!1},"continueRetry"),h=o(()=>re.isFocused()&&(t.networkMode==="always"||ie.isOnline())&&t.canRun(),"canContinue"),d=o(()=>ze(t.networkMode)&&t.canRun(),"canStart"),l=o(b=>{n()||(s?.(),i.resolve(b))},"resolve"),f=o(b=>{n()||(s?.(),i.reject(b))},"reject"),y=o(()=>new Promise(b=>{s=o(C=>{(n()||h())&&b(C)},"continueFn"),t.onPause?.()}).then(()=>{s=void 0,n()||t.onContinue?.()}),"pause"),m=o(()=>{if(n())return;let b,C=r===0?t.initialPromise:void 0;try{b=C??t.fn()}catch(k){b=Promise.reject(k)}Promise.resolve(b).then(l).catch(k=>{if(n())return;let x=t.retry??(D.isServer()?0:3),U=t.retryDelay??qr,W=typeof U=="function"?U(r,k):U,V=x===!0||typeof x=="number"&&r<x||typeof x=="function"&&x(r,k);if(e||!V){f(k);return}r++,t.onFail?.(r,k),Ot(W).then(()=>h()?void 0:y()).then(()=>{e?f(k):m()})})},"run");return{promise:i,status:o(()=>i.status,"status"),cancel:a,continue:o(()=>(s?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:o(()=>(d()?m():y().then(m),i),"start")}}o(Te,"createRetryer");var Ee=class{static{o(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),oe(this.gcTime)&&(this.#e=Q.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(D.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Q.clearTimeout(this.#e),this.#e=void 0)}};function xt(t){return{onFetch:o((e,r)=>{let s=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=o(async()=>{let d=!1,l=o(m=>{At(m,()=>e.signal,()=>d=!0)},"addSignalProperty"),f=we(e.options,e.fetchOptions),y=o(async(m,b,C)=>{if(d)return Promise.reject(e.signal.reason);if(b==null&&m.pages.length)return Promise.resolve(m);let x=o(()=>{let Ke={client:e.client,queryKey:e.queryKey,pageParam:b,direction:C?"backward":"forward",meta:e.options.meta};return l(Ke),Ke},"createQueryFnContext")(),U=await f(x),{maxPages:W}=e.options,V=C?Pt:Rt;return{pages:V(m.pages,U,W),pageParams:V(m.pageParams,b,W)}},"fetchPage");if(i&&n.length){let m=i==="backward",b=m?Kr:Mt,C={pages:n,pageParams:a},k=b(s,C);c=await y(C,k,m)}else{let m=t??n.length;do{let b=u===0?a[0]??s.initialPageParam:Mt(s,c);if(u>0&&b==null)break;c=await y(c,b),u++}while(u<m)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r):e.fetchFn=h},"onFetch")}}o(xt,"infiniteQueryBehavior");function Mt(t,{pages:e,pageParams:r}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}o(Mt,"getNextPageParam");function Kr(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}o(Kr,"getPreviousPageParam");var Qt=class extends Ee{static{o(this,"Query")}#e;#t;#r;#s;#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.#s=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Lt(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=Lt(this.options);e.data!==void 0&&(this.setState(_t(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(t,e){let r=ue(this.state.data,t,this.options);return this.#c({data:r,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),r}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(w).catch(w):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=>E(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===se||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>_(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:!be(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.#s.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.#s.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=o(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:o(()=>(this.#a=!0,r.signal),"get")})},"addSignalProperty"),i=o(()=>{let u=we(this.options,e),d=o(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return s(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),a=o(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return s(u),u},"createFetchContext")();(this.#e==="infinite"?xt(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:"fetch",meta:a.fetchOptions?.meta}),this.#i=Te({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:o(u=>{u instanceof ke&&u.revert&&this.setState({...this.#r,fetchStatus:"idle"}),r.abort()},"onCancel"),onFail:o((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:o(()=>{this.#c({type:"pause"})},"onPause"),onContinue:o(()=>{this.#c({type:"continue"})},"onContinue"),retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:o(()=>!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.#s.config.onSuccess?.(u,this),this.#s.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof ke){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.#s.config.onError?.(u,this),this.#s.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=o(r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...We(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,..._t(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#r=t.manual?s:void 0,s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}},"reducer");this.state=e(this.state),v.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:t})})}};function We(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ze(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}o(We,"fetchState");function _t(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}o(_t,"successState");function Lt(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}o(Lt,"getDefaultState");var Ge=class extends L{static{o(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=he(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#r=void 0;#s=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),Dt(this.#t,this.options)?this.#f():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ve(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ve(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,r=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 E(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&&!Se(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let s=this.hasListeners();s&&Ut(this.#t,r,this.options,e)&&this.#f(),this.updateResult(),s&&(this.#t!==r||E(this.options.enabled,this.#t)!==E(e.enabled,this.#t)||_(this.options.staleTime,this.#t)!==_(e.staleTime,this.#t))&&this.#y();let i=this.#b();s&&(this.#t!==r||E(this.options.enabled,this.#t)!==E(e.enabled,this.#t)||i!==this.#u)&&this.#v(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),r=this.createResult(e,t);return jr(this,r)&&(this.#s=r,this.#i=this.options,this.#n=this.#t.state),r}getCurrentResult(){return this.#s}trackResult(t,e){return new Proxy(t,{get:o((r,s)=>(this.trackProp(s),e?.(s),s==="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(r,s)),"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),r=this.#e.getQueryCache().build(this.#e,e);return r.fetch().then(()=>this.createResult(r,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(w)),e}#y(){this.#S();let t=_(this.options.staleTime,this.#t);if(D.isServer()||this.#s.isStale||!oe(t))return;let r=be(this.#s.dataUpdatedAt,t)+1;this.#d=Q.setTimeout(()=>{this.#s.isStale||this.updateResult()},r)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(t){this.#w(),this.#u=t,!(D.isServer()||E(this.options.enabled,this.#t)===!1||!oe(this.#u)||this.#u===0)&&(this.#l=Q.setInterval(()=>{(this.options.refetchIntervalInBackground||re.isFocused())&&this.#f()},this.#u))}#g(){this.#y(),this.#v(this.#b())}#S(){this.#d!==void 0&&(Q.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(Q.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let r=this.#t,s=this.options,i=this.#s,n=this.#n,a=this.#i,u=t!==r?t.state:this.#r,{state:h}=t,d={...h},l=!1,f;if(e._optimisticResults){let A=this.hasListeners(),ae=!A&&Dt(t,e),pe=A&&Ut(t,r,e,s);(ae||pe)&&(d={...d,...We(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:y,errorUpdatedAt:m,status:b}=d;f=d.data;let C=!1;if(e.placeholderData!==void 0&&f===void 0&&b==="pending"){let A;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(A=i.data,C=!0):A=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,A!==void 0&&(b="success",f=ue(i?.data,A,e),l=!0)}if(e.select&&f!==void 0&&!C)if(i&&f===n?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=ue(i?.data,f,e),this.#c=f,this.#a=null}catch(A){this.#a=A}this.#a&&(y=this.#a,f=this.#c,m=Date.now(),b="error");let k=d.fetchStatus==="fetching",x=b==="pending",U=b==="error",W=x&&k,V=f!==void 0,N={status:b,fetchStatus:d.fetchStatus,isPending:x,isSuccess:b==="success",isError:U,isInitialLoading:W,isLoading:W,data:f,dataUpdatedAt:d.dataUpdatedAt,error:y,errorUpdatedAt:m,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:k,isRefetching:k&&!x,isLoadingError:U&&!V,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:U&&V,isStale:Je(t,e),refetch:this.refetch,promise:this.#o,isEnabled:E(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=N.data!==void 0,ae=N.status==="error"&&!A,pe=o(ye=>{ae?ye.reject(N.error):A&&ye.resolve(N.data)},"finalizeThenableIfPossible"),St=o(()=>{let ye=this.#o=N.promise=he();pe(ye)},"recreateThenable"),me=this.#o;switch(me.status){case"pending":t.queryHash===r.queryHash&&pe(me);break;case"fulfilled":(ae||N.data!==me.value)&&St();break;case"rejected":(!ae||N.error!==me.reason)&&St();break}}return N}updateResult(){let t=this.#s,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),Se(e,t))return;this.#s=e;let r=o(()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;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.#s).some(a=>{let c=a;return this.#s[c]!==t[c]&&n.has(c)})},"shouldNotifyListeners");this.#k({listeners:r()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#r=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Br(t,e){return E(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&E(e.retryOnMount,t)===!1)}o(Br,"shouldLoadOnMount");function Dt(t,e){return Br(t,e)||t.state.data!==void 0&&Ve(t,e,e.refetchOnMount)}o(Dt,"shouldFetchOnMount");function Ve(t,e,r){if(E(e.enabled,t)!==!1&&_(e.staleTime,t)!=="static"){let s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&Je(t,e)}return!1}o(Ve,"shouldFetchOn");function Ut(t,e,r,s){return(t!==e||E(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&Je(t,r)}o(Ut,"shouldFetchOptionally");function Je(t,e){return E(e.enabled,t)!==!1&&t.isStaleByTime(_(e.staleTime,t))}o(Je,"isStale");function jr(t,e){return!Se(t.getCurrentResult(),e)}o(jr,"shouldAssignObserverCurrentProperties");var Nt=class extends Ee{static{o(this,"Mutation")}#e;#t;#r;#s;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#r=t.mutationCache,this.#t=[],this.state=t.state||$r(),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.#r.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(t){let e=o(()=>{this.#n({type:"continue"})},"onContinue"),r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=Te({fn:o(()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:o((n,a)=>{this.#n({type:"failed",failureCount:n,error:a})},"onFail"),onPause:o(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:o(()=>this.#r.canRun(this),"canRun")});let s=this.state.status==="pending",i=!this.#s.canStart();try{if(s)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#r.config.onMutate&&await this.#r.config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&this.#n({type:"pending",context:a,variables:t,isPaused:i})}let n=await this.#s.start();return await this.#r.config.onSuccess?.(n,t,this.state.context,this,r),await this.options.onSuccess?.(n,t,this.state.context,r),await this.#r.config.onSettled?.(n,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(n,null,t,this.state.context,r),this.#n({type:"success",data:n}),n}catch(n){try{await this.#r.config.onError?.(n,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(n,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await this.#r.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,r)}catch(a){Promise.reject(a)}throw this.#n({type:"error",error:n}),n}finally{this.#r.runNext(this)}}#n(t){let e=o(r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,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{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),v.batch(()=>{this.#t.forEach(r=>{r.onMutationUpdate(t)}),this.#r.notify({mutation:this,type:"updated",action:t})})}};function $r(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}o($r,"getDefaultState");var qt=class extends L{static{o(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(t,e,r){let s=new Nt({client:t,mutationCache:this,mutationId:++this.#r,options:t.defaultMutationOptions(e),state:r});return this.add(s),s}add(t){this.#e.add(t);let e=Ie(t);if(typeof e=="string"){let r=this.#t.get(e);r?r.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Ie(t);if(typeof e=="string"){let r=this.#t.get(e);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Ie(t);if(typeof e=="string"){let s=this.#t.get(e)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let e=Ie(t);return typeof e=="string"?this.#t.get(e)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){v.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(r=>ge(e,r))}findAll(t={}){return this.getAll().filter(e=>ge(t,e))}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return v.batch(()=>Promise.all(t.map(e=>e.continue().catch(w))))}};function Ie(t){return t.options.scope?.id}o(Ie,"scopeFor");var Kt=class extends L{static{o(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,r){let s=e.queryKey,i=e.queryHash??ce(s,e),n=this.get(i);return n||(n=new Qt({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(e),state:r,defaultOptions:t.getQueryDefaults(s)}),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(){v.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(r=>ve(e,r))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(r=>ve(t,r)):e}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){v.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){v.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var Xe=class{static{o(this,"QueryClient")}#e;#t;#r;#s;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new Kt,this.#t=t.mutationCache||new qt,this.#r=t.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=re.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=ie.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),r=this.#e.build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(_(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:r})=>{let s=r.data;return[e,s]})}setQueryData(t,e,r){let s=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(s.queryHash)?.state.data,a=It(e,n);if(a!==void 0)return this.#e.build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return v.batch(()=>this.#e.findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;v.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){let r=this.#e;return v.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let r={revert:!0,...e},s=v.batch(()=>this.#e.findAll(t).map(i=>i.cancel(r)));return Promise.all(s).then(w).catch(w)}invalidateQueries(t,e={}){return v.batch(()=>(this.#e.findAll(t).forEach(r=>{r.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let r={...e,cancelRefetch:e.cancelRefetch??!0},s=v.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,r);return r.throwOnError||(n=n.catch(w)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(w)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let r=this.#e.build(this,e);return r.isStaleByTime(_(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(w).catch(w)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(w).catch(w)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return ie.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(t){this.#r=t}setQueryDefaults(t,e){this.#s.set(J(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#s.values()],r={};return e.forEach(s=>{q(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){this.#n.set(J(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],r={};return e.forEach(s=>{q(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#r.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ce(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===se&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#r.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var K=F(G(),1);var ne=F(G(),1),Bt=F(Be(),1);var de=ne.createContext(void 0),Ye=o(t=>{let e=ne.useContext(de);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Ze=o(({client:t,children:e})=>(ne.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Bt.jsx)(de.Provider,{value:t,children:e})),"QueryClientProvider");var le=F(G(),1),Hr=F(Be(),1);function zr(){let t=!1;return{clearReset:o(()=>{t=!1},"clearReset"),reset:o(()=>{t=!0},"reset"),isReset:o(()=>t,"isReset")}}o(zr,"createValue");var Wr=le.createContext(zr()),jt=o(()=>le.useContext(Wr),"useQueryErrorResetBoundary");var $t=F(G(),1);var Ht=o((t,e,r)=>{let s=r?.state.error&&typeof t.throwOnError=="function"?Ce(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),zt=o(t=>{$t.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Wt=o(({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(i&&t.data===void 0||Ce(r,[t.error,s])),"getHasError");var Oe=F(G(),1);var Vt=Oe.createContext(!1),Gt=o(()=>Oe.useContext(Vt),"useIsRestoring"),ho=Vt.Provider;var Jt=o(t=>{if(t.suspense){let r=o(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),s=t.staleTime;t.staleTime=typeof s=="function"?(...i)=>r(s(...i)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),Xt=o((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Yt=o((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),et=o((t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()}),"fetchOptimistic");function Zt(t,e,r){let s=Gt(),i=jt(),n=Ye(r),a=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=n.getQueryCache().get(a.queryHash),u=t.subscribed!==!1;a._optimisticResults=s?"isRestoring":u?"optimistic":void 0,Jt(a),Ht(a,i,c),zt(i);let h=!n.getQueryCache().get(a.queryHash),[d]=K.useState(()=>new e(n,a)),l=d.getOptimisticResult(a),f=!s&&u;if(K.useSyncExternalStore(K.useCallback(y=>{let m=f?d.subscribe(v.batchCalls(y)):w;return d.updateResult(),m},[d,f]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),K.useEffect(()=>{d.setOptions(a)},[a,d]),Yt(a,l))throw et(a,d,i);if(Wt({result:l,errorResetBoundary:i,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!D.isServer()&&Xt(l,s)&&(h?et(a,d,i):c?.promise)?.catch(w).finally(()=>{d.updateResult()}),a.notifyOnChangeProps?l:d.trackResult(l)}o(Zt,"useBaseQuery");function Vr(t,e){return Zt(t,Ge,e)}o(Vr,"useQuery");var er=F(Ct(),1);var X=F(G(),1),tt=F(Be(),1);var tr=(0,X.createContext)(null),Gr=o(()=>new Xe({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"Q"),Jr=o(t=>{let e=(0,er.c)(9),{children:r,client:s,queryClient:i}=t,n=(0,X.use)(de),a;e[0]!==n||e[1]!==i?(a=o(()=>i??n??Gr(),"o"),e[0]=n,e[1]=i,e[2]=a):a=e[2];let[c]=(0,X.useState)(a),u=i??n??c,h;e[3]!==r||e[4]!==s?(h=(0,tt.jsx)(tr,{value:s,children:r}),e[3]=r,e[4]=s,e[5]=h):h=e[5];let d=h;if(n===u)return d;let l;return e[6]!==d||e[7]!==u?(l=(0,tt.jsx)(Ze,{client:u,children:d}),e[6]=d,e[7]=u,e[8]=l):l=e[8],l},"b"),rt=o(()=>{let t=(0,X.use)(tr);if(!t)throw new p("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var Re=o(t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},"m"),Xr=o(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s+=1)r[s]=e.codePointAt(s)??0;return r},"A"),T="$lunora.wire$",Pe="__proto__",rr={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},sr={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},st=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),O=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[T,"undefined"];if(t===null)return null;let r=typeof t;if(r==="bigint")return[T,"bigint",t.toString()];if(r==="number"){let n=t;return Number.isNaN(n)?[T,"nan"]:n===1/0?[T,"inf"]:n===-1/0?[T,"-inf"]:n}if(r!=="object")return t;if(t instanceof Date)return[T,"date",O(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n)){if(n[u]===void 0)continue;let h=O(n[u],e+1);u===Pe?Object.defineProperty(a,u,{configurable:!0,enumerable:!0,value:h,writable:!0}):a[u]=h}let c=[T,"error",String(n.name),String(n.message),a];return n.cause!==void 0&&c.push(O(n.cause,e+1)),c}if(t instanceof URL)return[T,"url",t.href];if(t instanceof Map)return[T,"map",[...t.entries()].map(([n,a])=>[O(n,e+1),O(a,e+1)])];if(t instanceof Set)return[T,"set",[...t].map(n=>O(n,e+1))];if(t instanceof ArrayBuffer)return[T,"bytes",Re(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,a=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return a==="Uint8Array"?[T,"bytes",Re(c)]:[T,"bytes",Re(c),a]}if(Array.isArray(t)){let n=t.map(a=>O(a,e+1));return n.length>0&&n[0]===T?[T,"arr",n]:n}if(!st(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 s=t,i={};for(let n of Object.keys(s)){let a=s[n];if(a===void 0)continue;let c=O(a,e+1);n===Pe?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"b"),g=o((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]===T)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>g(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=g(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[g(n[0],e+1),g(n[1],e+1)]}))}case"set":return new Set(t[2].map(i=>g(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 a=(Object.hasOwn(sr,i)?sr[i]:void 0)??Error,c=new a(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=g(t[4],e+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let h of Object.keys(u))h===Pe?Object.defineProperty(c,h,{configurable:!0,enumerable:!0,value:u[h],writable:!0}):c[h]=u[h];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:g(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=Xr(i);if(Re(n)!==i)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let a=t[3]??"Uint8Array";if(a==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;let c=Object.hasOwn(rr,a)?rr[a]: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=>g(i,e+1))}return t.map(i=>g(i,e+1))}let r=t,s={};for(let i of Object.keys(r)){let n=g(r[i],e+1);i===Pe?Object.defineProperty(s,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[i]=n}return s},"y");var R=o(t=>new Promise((e,r)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{r(t.error??new Error("IndexedDB request failed"))})}),"c"),Ae=o((t,e,r,s)=>{let i;return()=>i||(i=new Promise((n,a)=>{let c=t.open(e,r);c.addEventListener("upgradeneeded",()=>{s(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{a(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),Fe=o((t,e)=>async(r,s)=>{let i=(await t()).transaction(e,r),n=await s(i.objectStore(e));return await new Promise((a,c)=>{i.addEventListener("complete",()=>{a()}),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 Y=o((t,e,r)=>`${t}::${e}::${r??""}`,"T"),Yr=500,Zr=o((t,e)=>{if(!Number.isInteger(t)||t<1)throw new p("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var es="lunora-query-cache",ts="query-cache",ir="by_ts",rs=1,ss=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let r=t.databaseName??es,s=t.storeName??ts,i=Zr(t.maxEntries??Yr,"createIndexedDbQueryCache"),n=Ae(e,r,rs,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(ir,"ts",{unique:!1})}),a=Fe(n,s),c=o(async u=>{let h=await R(u.count())-i;h<=0||await new Promise((d,l)=>{let f=u.index(ir).openCursor();f.addEventListener("success",()=>{let y=f.result;if(!y||h<=0){d();return}y.delete(),h-=1,y.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:o(async()=>{await a("readwrite",u=>R(u.clear()))},"clear"),load:o(async()=>a("readonly",u=>R(u.getAll())),"load"),put:o(async(u,h)=>{await a("readwrite",async d=>{await R(d.put({...h,key:u})),await c(d)})},"put"),remove:o(async u=>{await a("readwrite",h=>R(h.delete(u)))},"remove")}},"N"),nr=o(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return ss()}},"L");var ar=o(()=>{let t=null;return{get:o(()=>t,"get"),set:o(e=>{t=e},"set")}},"r");var Me=class{static{o(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,r){if(r===void 0){this.reset(e);return}this.values.set(e.key,r),this.notify(e.key,r)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,r){let s=this.subscribers.get(e.key);return s||(s=new Set,this.subscribers.set(e.key,s)),s.add(r),()=>{s.delete(r),s.size===0&&this.subscribers.delete(e.key)}}notify(e,r){let s=this.subscribers.get(e);if(s)for(let i of s)try{i(r)}catch{}}};var or=0,is="lunora-bridge",ns=1e3,as=3e3,xe=class{static{o(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(or+=1,this.tabId=`tab_${String(or)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??ns,this.leaderTimeout=e.leaderTimeout??as,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??is),this.bc.addEventListener("message",r=>{this.handleMessage(r.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,r,s,i,n){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:r,...s===void 0?{}:{cursor:s},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}})}broadcastSubscriptionError(e,r,s){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:r,...s===void 0?{}:{identity:s}})}broadcastSubscriptionSettled(e,r,s,i,n,a){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...r===void 0?{}:{cursor:r},...s===void 0?{}:{epoch:s},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...a===void 0?{}:{identity:a}})}broadcastConnectionStatus(e,r){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...r===void 0?{}:{identity:r}})}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 it="_id",nt="_creationTime",at="page",cr="pageDelta",os=o(t=>{if(Array.isArray(t))return t;if(st(t)&&Array.isArray(t[at]))return t[at]},"y"),cs=o(t=>{let e;for(let r of t){let s=r[nt];if(typeof s=="number"){if(e!==void 0){if(s<e)return!0;if(s>e)return!1}e=s}}return!1},"l"),us=o((t,e)=>{let r=e[nt];if(typeof r!="number")return t.length;let s=cs(t);for(let[i,n]of t.entries()){let a=n[nt];if(typeof a=="number"&&(s?a<r:a>r))return i}return t.length},"x"),hs=o(t=>{if(typeof t!="object"||t===null)return;let e=t[it];return typeof e=="string"?e:void 0},"A"),ur=o(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")},"b"),ds=o((t,e)=>{let r=[];for(let u of t){if(hs(u)===void 0)return;r.push(u)}let{key:s,op:i,row:n}=e;if(i==="delete"){let u=r.filter(h=>h[it]!==s);return u.length===r.length?[...r]:u}if(n===void 0)return;let a=[...r],c=r.findIndex(u=>u[it]===s);return c===-1?a.splice(us(r,n),0,n):a[c]=n,a},"I"),hr=o((t,e)=>{let r=os(t);if(r===void 0)return;let s=ds(r,e);return s===void 0||Array.isArray(t)?s:{...t,[at]:s}},"E");var tc=new Set(Object.keys(wt)),B=class extends p{static{o(this,"E")}constructor(e,r){super("INTERNAL",e,{data:r})}};var ot=o(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"u");var ls=1024,_e=o(t=>{let e=t.maxBuffer??ls,r=[],s=[],i=!1,n,a=!1,c=o(()=>{let d=s.shift();if(!d)return!1;if(n)return d.reject(n),!0;if(r.length>0){let l=r.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(s.unshift(d),!1)},"u"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(d){if(!(i||n))for(n=d,r.length=0;c(););},push(d){if(!(i||n||a)){if(r.length>=e){u.fail(new p("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}r.push(d),c()}}},h=o(()=>{if(!a){a=!0,i=!0,r.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:h,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(r.length>0){let d=r.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,l)=>{s.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var dr=/^ /u,lr=o(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"p"),fs=o(t=>{let e="",r=[];for(let s of t.split(`
|
|
2
|
-
`))s.startsWith("event:")?e=s.slice(6).replace(dr,""):s.startsWith("data:")&&r.push(s.slice(5).replace(dr,""));return{data:r.join(`
|
|
3
|
-
`),event:e}},"S"),ps=o((t,e,r)=>{let s=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=s[u];if(h===void 0)throw new p("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(lr(h))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,lr(u));let a=n.toString();return`${r.endsWith("/")?r.slice(0,-1):r}${i}${a===""?"":`?${a}`}`},"T"),ms=o((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let r={};try{r=JSON.parse(t.data)}catch{}let s=typeof r.message=="string"?r.message:"stream error",i=typeof r.code=="string"?r.code:"HTTP_STREAM_ERROR";return e.fail(new p(i,s)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(g(JSON.parse(t.data)))}catch{return e.fail(new p("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"E"),ys=o(async(t,e)=>{let r=t.getReader(),s=new TextDecoder,i="",n=o(()=>{let a=i.indexOf(`
|
|
4
|
-
|
|
5
|
-
`);for(;a!==-1;){let c=fs(i.slice(0,a));if(i=i.slice(a+2),ms(c,e))return!0;a=i.indexOf(`
|
|
6
|
-
|
|
7
|
-
`)}return!1},"i");for(;;){let{done:a,value:c}=await r.read();if(a)break;if(i+=s.decode(c,{stream:!0}).replaceAll(`\r
|
|
8
|
-
`,`
|
|
9
|
-
`),n()){await r.cancel().catch(()=>{});return}}i+=s.decode().replaceAll(`\r
|
|
10
|
-
`,`
|
|
11
|
-
`),n()||e.fail(new p("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),fr=o((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new p("INTERNAL","httpStream: no `fetch` implementation available");let i=ps(t,e??{},r.baseUrl??""),n=new AbortController,a;r.signal&&(r.signal.aborted?n.abort():(a=o(()=>{n.abort()},"s"),r.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&r.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=_e({maxBuffer:r.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new p("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new p("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ys(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new p("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var bs=/["\\\u0000-\u001F\uD800-\uDFFF]/,pr=o(t=>bs.test(t)?JSON.stringify(t):`"${t}"`,"y"),ct=o(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 pr(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=ct(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,s=Object.keys(r).sort(),i="{",n=!0;for(let a of s){let c=r[a];c!==void 0&&(n?n=!1:i+=",",i+=pr(a),i+=":",i+=ct(c))}return i+"}"},"i"),j=o(t=>ct(O(t)),"u");var P=class t{static{o(this,"r")}static key(e,r,s){return`${e}::${j(r)}::${s??""}`}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 r=t.keyOf(e);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};var Z=o((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"p"),$=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),ut=o((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e};t.optimisticLayers.push(s),$(t,r);let i=o(()=>{let a=t.optimisticLayers.findIndex(c=>c.id===s.id);return a===-1?!1:(t.optimisticLayers.splice(a,1),!0)},"c"),n=o(()=>{$(t,Z(t.serverBase,t.optimisticLayers))},"a");return{confirm:o(a=>{if(a===void 0){i();return}s.commitCursor=a,t.serverCursor!==void 0&&t.serverCursor>=a&&i()&&n()},"confirm"),rollback:o(()=>{i()&&n()},"rollback")}},"y"),Le=o((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let r=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(s=>s.commitCursor===void 0||s.commitCursor>e),t.optimisticLayers.length!==r},"h"),mr=o((t,e)=>{let r=[],s=[],i=o((n,a)=>t.get(P.key(n,a,e)),"c");return{confirms:r,rollbacks:s,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=ut(u,()=>c);h&&(r.push(h.confirm),s.push(h.rollback))},"setQuery")}}},"L");var yr=0,vs=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();yr+=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)}_${yr.toString(36)}_${t}`},"d"),ht=o((t,e)=>t!==void 0&&e!==t,"f"),De=vs,H=o((t,e,r,s)=>{if(t)try{t({error:r,mutationId:s,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"o"),Qe=class{static{o(this,"m")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},r={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=r.persistence,this.onEvict=r.onEvict,this.onSizeChange=r.onSizeChange,this.version=r.version}get size(){return this.items.length}enqueue(e){let r=e;r.id??=De(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{H(this.onPersistenceError,"append",s,r.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw H(this.onPersistenceError,"load",a),a}let r=[],s=new Set(this.items.map(a=>a.id));for(let a of e)if(!s.has(a.id)){if(ht(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{H(this.onPersistenceError,"remove",c,a.id)});continue}s.add(a.id),r.push({args:a.args,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of r)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,r){for(let s of this.items){if(s.identity!==e)continue;s.identity=r;let{id:i}=s;if(!this.persistence||i===void 0)continue;let n={args:s.args,clientId:s.clientId,functionPath:s.functionPath,id:i,identity:r,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{H(this.onPersistenceError,"replace",a,i)})}}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let r=[],s=[];for(let i of this.items)(e(i)?r:s).push(i);return this.items.length=0,this.items.push(...s),this.notifySize(),r}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],r=[];for(let s of this.items)if(s.precondition!==void 0&&!s.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",s.reject(i),e.push(s)}else r.push(s);return e.length>0&&(this.items.length=0,this.items.push(...r),this.notifySize()),e}clear(){for(let e of this.items){let r=new Error("CLIENT_CLOSED");r.code="CLIENT_CLOSED",e.reject(r)}this.items.length=0,this.notifySize()}async rewriteStamp(e,r){let s=this.persistence;if(s)try{await s.replace(r)}catch(i){H(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(s=>{H(this.onPersistenceError,"remove",s,e.id)});let r=new Error("offline queue overflow");r.code="OFFLINE_QUEUE_OVERFLOW",e.reject(r),this.onEvict?.(e,r)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var gs="lunora-outbox",Ss="offline-mutations",dt="by_id",ws=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??gs,s=t.storeName??Ss,i=Ae(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(dt,"id",{unique:!0})}),n=Fe(i,s);return{append:o(async a=>{await n("readwrite",c=>R(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>R(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>R(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a));u!==void 0&&await R(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a.id));u!==void 0&&await R(c.put(a,u))})},"replace")}},"w"),br=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ws()}},"b");var lt=o((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(s,r*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var vr=o((t,e,r,s)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s),n=i.present?j(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s);return!i.present||!a.present?!0:j(a.value)===n}},"c");var ft=500,Cs=o(async t=>{let e=[],r;for(;;){let s=await t(r);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===r)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");r=s.cursor}},"Ce"),gr=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"G"),te=class{static{o(this,"I")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[r]=e;for(let s of this.listeners)try{s(r)}catch{}}clear(){this.listeners.clear()}},Ir=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Or=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),ks=o(t=>Or.has(t?.code??""),"we"),Ts=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||Ir.has(e)||Or.has(e)},"Ee"),Rr=6e4,Es=1e3,Pr=o(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let r=Date.parse(t);if(Number.isNaN(r))return;let s=r-Date.now();return s>0?s:void 0},"re"),Is={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Ue=o((t,e,r)=>{let s=Pr(r),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new p(Is[t]??"BAD_REQUEST",n,{data:i})},"P"),Os=o((t,e)=>{let r=Pr(e);if(!(r===void 0||ot(t)!==void 0))return t.data===void 0?{retryAfterMs:r}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:r}:void 0},"Ie"),Rs=o((t,e=Math.random)=>{let r=Math.min(Es*2**Math.max(t-1,0),Rr);return Math.round(r*(.5+e()*.5))},"Oe"),Ps=o(t=>t instanceof B||Ir.has(t?.code??""),"Re"),As=o((t,e,r)=>{let s=ot(t);return s!==void 0&&s>0?Math.min(s,Rr):Ps(t)?Rs(e,r):void 0},"Pe"),Fs=983040,Ms=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Fe"),xs="/_lunora/rpc",Sr="/_lunora/rpc-batch",_s="/_lunora/ws",pt=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"N"),Ne=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"M"),wr=Symbol("lunora.unmergeableDelta"),Ls=o((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"Ue"),Qs="lunora-ping",Ds=3e4,Us=1e4,Ns=250,qs=5e3,Ks=64,Bs=8,js="/_lunora/admin/shard-traffic",$s="/_lunora/admin/scheduled",Hs="/_lunora/admin/scheduled/status",zs="/_lunora/admin/scheduled/ws",Ws="/_lunora/admin/scheduled/cancel",Cr="/_lunora/admin/scheduled/dead",Vs="/_lunora/admin/scheduled/dead/retry",Gs="/_lunora/admin/scheduled/dead/cancel",Js="/_lunora/admin/workflows/instances",Xs="/_lunora/admin/workflows/instance",Ys="/_lunora/admin/workflows/status",mt="/_lunora/admin/storage",Zs="/_lunora/admin/storage/url",ei="/_lunora/admin/storage/buckets",ti="/_lunora/admin/functions",ri="/_lunora/admin/cron-jobs",si="/_lunora/admin/cron-jobs/run",ii="/_lunora/admin/openapi",ni="/_lunora/admin/openrpc",ai="/_lunora/admin/global/tables",oi="/_lunora/admin/global/table",ci="/_lunora/admin/global/facet",ui="/_lunora/admin/vector/indexes",hi="/_lunora/admin/vector/query",di="/_lunora/admin/logs/archive",li="/_lunora/admin/kv/namespaces",fi="/_lunora/admin/kv/keys",yt="/_lunora/admin/kv/value",pi="/_lunora/admin/auth/users",mi="/_lunora/admin/auth/sessions",yi="/_lunora/admin/auth/users/create",bi="/_lunora/admin/auth/users/role",vi="/_lunora/admin/auth/users/ban",gi="/_lunora/admin/auth/users/unban",Si="/_lunora/admin/auth/users/password",wi="/_lunora/admin/auth/users/remove",Ci="/_lunora/admin/auth/users/impersonate",ki="/_lunora/admin/auth/sessions/revoke",Ti="/_lunora/admin/auth/sessions/revoke-all",Ei="/_lunora/admin/auth/capabilities",Ii="/_lunora/admin/auth/users/update",Oi="/_lunora/admin/auth/accounts",Ri="/_lunora/admin/auth/accounts/unlink",Pi="/_lunora/admin/auth/passkeys",Ai="/_lunora/admin/auth/passkeys/delete",Fi="/_lunora/admin/auth/two-factor/disable",Mi="/_lunora/admin/auth/organizations",xi="/_lunora/admin/auth/organizations/members",_i="/_lunora/admin/auth/organizations/invitations",Li="/_lunora/admin/auth/organizations/members/remove",Qi="/_lunora/admin/auth/organizations/invitations/cancel",Di="/_lunora/admin/auth/config",Ui="/_lunora/admin/auth/sign-up-invitations",Ni="/_lunora/admin/auth/sign-up-invitations/create",qi="/_lunora/admin/auth/sign-up-invitations/revoke",Ki="/_lunora/admin/auth/organizations/create",Bi="/_lunora/admin/auth/organizations/update",ji="/_lunora/admin/auth/organizations/remove",$i="/_lunora/admin/auth/organizations/members/add",Hi="/_lunora/admin/auth/organizations/members/invite",zi="/_lunora/admin/auth/organizations/members/role",Wi="/_lunora/admin/auth/organizations/teams",Vi="/_lunora/admin/auth/organizations/teams/create",Gi="/_lunora/admin/auth/organizations/teams/update",Ji="/_lunora/admin/auth/organizations/teams/remove",Xi="/_lunora/admin/auth/organizations/teams/members",Yi="/_lunora/admin/auth/organizations/teams/members/add",Zi="/_lunora/admin/auth/organizations/teams/members/remove",en="/_lunora/admin/auth/organizations/roles",tn="/_lunora/admin/auth/organizations/roles/create",rn="/_lunora/admin/auth/organizations/roles/update",sn="/_lunora/admin/auth/organizations/roles/remove",nn="/api/auth",an="/get-session",kr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"Y"),ee=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),I=o((t,e)=>{let r=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&r.set(i,String(n));let s=r.toString();return s===""?t:`${t}?${s}`},"y"),on=[cr],S=o(t=>t??"","l"),Ar=o((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"ie"),cn=o(t=>{let{code:e,messageText:r}=Ar(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"cs"),Tr=o(t=>{let{code:e,messageText:r}=Ar(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"J");function bt(t){if(t!==void 0)return e=>{t(e)}}o(bt,"B");var fe=o((t,e)=>{for(let r of t)try{r(e)}catch{}},"O"),un=new TextDecoder,hn=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return un.decode(t)},"ds"),M=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"b"),qe=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=g(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"F"),Er=o((t,e)=>{let r=qe(t),s=Os(r,e);return s!==void 0&&(r.data=s),r},"X"),z=o((t,e)=>{try{return O(t)}catch(r){let s=r instanceof Error?r.message:String(r);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${s}`,r instanceof Error?{cause:r}:void 0)}},"k"),vt=o(t=>"args"in t?{...t,args:g(t.args)}:t,"Q"),dn=o((t,e)=>{let r=Array.from({length:e});for(let s of t){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;let i=s.body;r[s.id]=i&&"error"in i&&i.error?{error:qe(i.error),ok:!1}:{ok:!0,value:g(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"us"),ln=Promise.resolve(),gt=class t{static{o(this,"ne")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,r){return{defaultValue:r,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new te;statusListeners=new te;tokenExpiredListeners=new te;authRefusalNotifiedFor;mutationSettledListeners=new te;pendingChangeListeners=new te;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ee(kr(e.url),_s),this.wsToken=e.wsToken;let r=e.authBasePath??nn;this.authBasePath=r.endsWith("/")?r.slice(0,-1):r,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??ar(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Ds,this.connectTimeoutMs=e.connectTimeoutMs??Us,this.defaultConnectionContext=e.connectionContext,this.persistence=br(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=nr(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Me,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=ln),this.offlineQueue=new Qe(e.offlineQueue,{onEvict:o((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:o(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${De()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,r){let s=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm();this.authToken=e,r!==void 0?(this.authSubject=r,this.subjectToken=e):e===null&&(this.authSubject=void 0,this.subjectToken=null);let c=this.identityFingerprint();if(c!==i&&(!s&&n?(this.restampQueuedIdentity(i,c),this.restampWatermarks(i,c),this.restampConnectionIdentity(i,c),this.reseedFromHydratedCache()):this.rejectQueuedForIdentityChange(i),this.tabCoordinator)){let u=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),u&&this.tabCoordinator.promoteImmediately()}this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),this.offlineQueue.size>0&&this.computeStatus()==="connected"&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}replayIdentityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let r=this.identityFingerprint();return e===r||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":r===null?"unknown":"mismatch"}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",a=this.identityFingerprint(),c,u=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(h=>{c=h},"onMutationAck")});if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(gr(this.clientWatermarks,Bs),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(n,c)}return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;let e={},r=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{let s=await this.fetchImpl(ee(this.url,`${this.authBasePath}${an}`),{credentials:"include",headers:e,method:"GET"});if(!s.ok)return null;let i=(await s.json())?.user??null;return this.adoptResolvedSubject(r,i),i}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(let r of this.connections.values())if(r.socket)try{r.socket.close()}catch{}}}setConnectionContext(e,r={}){this.assertLeaderOwnedSurface("setConnectionContext");let s=S(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){if(this.followsAnotherTab())return()=>{};let s=S(r.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;let c=this.connectionContextHolders.get(s);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,r,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=S(s.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&M(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(r)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(s.shardKey);d&&M(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&M(i,{data:z(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...r?.keys()??[]]);for(let n of s){let a=this.connections.get(n);e.push({confirmedMutationWatermark:r?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.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,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){return vr(this,e,r,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=j(r),n=Y(e,i,s),a=this.hydratedQueryCache.get(n);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,r,s){let i=P.key(e,r,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ee(this.url,Sr),{body:JSON.stringify({calls:e.map((n,a)=>({args:z(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:a,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}if(!r.ok||i.error&&!i.results)throw i.error?qe(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let a=n.body?.commitCursor;typeof n.id=="number"&&typeof a=="number"&&this.recordShardCursor(e[n.id]?.shardKey,a)}return dn(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??De(),{confirms:a,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,a);let u=this.offlineFlushes.get(S(s.shardKey));u!==void 0&&await u;let{hasSocket:h,wasEverConnected:d,wsState:l}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:f}=this.offlineQueue,y=d||f,m=this.WebSocketImpl!==void 0&&y;if(l!=="open"&&!h&&m||l==="connecting"&&y)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,a,s.precondition);try{let b,C=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:o(k=>{b=k},"onCommitCursor")});for(let k of a)k(b);return C}catch(b){throw Ne(c),b}}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),a=r.length,c=0,u=0;for(let h=0;h<a;h+=i){let d=r.slice(h,h+i),l=u;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey}),u+=1,c+=d.length,s.onProgress?.({done:c,total:a})}return{chunks:u,imported:c}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(js,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch($s,"GET")).records??[]).map(e=>vt(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Hs,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ws,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await Cs(async e=>await this.adminFetch(e===void 0?Cr:`${Cr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>vt(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Vs,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Gs,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${Js}?${r.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Xs}?${r.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Ys,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=ee(kr(this.url),zs),s=lt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,s.next()))},"a"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let y=f===void 0?r:`${r}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,y,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(C=>vt(C))))},"onMessage")})},"c"),h=o(async f=>{let y;try{y=await f()}catch{c();return}u(y)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(ti,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(ri,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(si,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(ii,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(ni,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=I(mt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${mt}?key=${encodeURIComponent(e)}${pt(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(ei,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${mt}?key=${encodeURIComponent(e.key)}${pt(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Zs}?key=${encodeURIComponent(e)}${i}${pt(r?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(ai,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),g(await this.adminFetch(`${oi}?${r.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),g(await this.adminFetch(`${ci}?${r.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(ui,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(hi,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(di,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(li,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=I(fi,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=I(yt,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(yt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=I(yt,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=I(pi,{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(r,"GET")}async createAuthUser(e){return await this.adminFetch(yi,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(bi,"POST",e)}async banAuthUser(e){return await this.adminFetch(vi,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(gi,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Si,"POST",e)}async removeAuthUser(e){await this.adminFetch(wi,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Ci,"POST",e)}async revokeAuthSession(e){await this.adminFetch(ki,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Ti,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Ei,"GET")}async updateAuthUser(e){return await this.adminFetch(Ii,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(I(Oi,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(Ri,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(I(Pi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(Ai,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(Fi,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(I(Mi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=I(xi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=I(_i,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthSignUpInvitations(e={}){let r=I(Ui,{limit:e.limit,offset:e.offset});return await this.adminFetch(r,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Ni,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(qi,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(Li,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Qi,"POST",e)}async getAuthConfig(){return await this.adminFetch(Di,"GET")}async createAuthOrganization(e){return await this.adminFetch(Ki,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Bi,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(ji,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch($i,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(Hi,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(zi,"POST",e)}async listAuthOrgTeams(e){let r=I(Wi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Vi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Gi,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Ji,"POST",e)}async listAuthOrgTeamMembers(e){let r=I(Xi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Yi,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Zi,"POST",e)}async listAuthOrgRoles(e){let r=I(en,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(tn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(rn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(sn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=I(mi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},a=P.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=bt(s),h=bt(i.onError),d=bt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,y=j(n),m=this.takeHydratedCache(e.__lunoraRef,y,i.shardKey);c={acked:!1,args:n,argsKey:y,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:z(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.subscriptions.remove(l))}}subscribeShape(e,r,s={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([r]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:z(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=r??{},{handle:c,iterable:u}=_e({maxBuffer:s.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:z(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:s.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&M(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new p("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Ks;){let y=h.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(y))}h.pendingStreams.push(d)}return u}httpStream(e,r,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return fr(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new p("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.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let r=e.leaderTabId;return r!==void 0&&r!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new p("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}teardownConnection(e){let r=S(e.shardKey);for(let[s,i]of this.streams)S(i.shardKey)===r&&(i.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(s));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new xe({channelName:e,onBecomeLeader:o(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(r);for(let r of this.queuedOfflineShardKeys)this.ensureSocket(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((r,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;let i=r==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=r,r==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((r,s,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,this.dropCacheSeed(r),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Le(c,i)),$(c,Z(s,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((r,s,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(r);n&&fe(n.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:o((r,s,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(r);if(u){this.ackAndAdvanceCursor(u,s,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,a,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let h=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(h)}`,identity:u,mutationId:h,shardKey:s})}catch(d){throw Ne(n),d instanceof Error?d:new Error(String(d))}for(let d of a)d(void 0);return}return new Promise((h,d)=>{let l={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:u,precondition:c,onCommit:o(f=>{for(let y of a)y(f)},"onCommit"),reject:o(f=>{this.queuedIdentities.delete(i),Ne(n),d(f instanceof Error?f:new Error(String(f)))},"reject"),resolve:h,shardKey:s};this.offlineQueue.enqueue(l),this.queuedOfflineShardKeys.add(s),l.id!==void 0&&this.queuedIdentities.set(l.id,u)})}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let r of e)this.queuedOfflineShardKeys.add(r),this.ensureSocket(r)}catch{}}hydrateAsOutboxLeader(){let e=o(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),r=globalThis.navigator?.locks;if(!r){e();return}r.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),r=new Map;for(let s of this.subscriptions.all())r.set(Y(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(let{key:s,...i}of e){if(ht(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}let n=r.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,r){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(r)||(e.serverBase=r.value,e.serverCursor=r.serverCursor,r.serverEpoch!==void 0&&(e.serverEpoch=r.serverEpoch),this.cacheSeededQueries.set(Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),r),$(e,Z(r.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,r]of this.cacheSeededQueries){let s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,$(s,Z(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,r)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,r,s){let i=Y(e,r,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let r=Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(r);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(r),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){let r=e.serverBase;if(!this.queryCache||r===void 0)return;let s=Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:r,...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(()=>{})},Ns)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.wsState==="connecting")?"connecting":"offline"}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,r,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:r})}applyOptimisticUpdates(e,r,s,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=P.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=ut(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=mr(this.subscriptions,s);try{e(u,r)}catch{Ne(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(S(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!M(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}let r=this.getConnection(e);return{hasSocket:r?.socket!==void 0,wasEverConnected:r?.wasEverConnected??!1,wsState:r?.wsState??"idle"}}getOrCreateConnection(e){let r=S(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:lt(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(r,s)),s}wsUrlFor(e,r){let s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),r!==void 0&&s.push(`token=${encodeURIComponent(r)}`),s.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,r){let s={"content-type":"application/json"},i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),a=await this.fetchImpl(ee(this.url,xs),{body:JSON.stringify({args:z(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{throw Ue(a.status,a.statusText,a.headers.get("retry-after"))}if("error"in c)throw Er(c.error,a.headers.get("retry-after"));if(!a.ok)throw Ue(a.status,a.statusText,a.headers.get("retry-after"));return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor),g(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:a?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(ee(this.url,e),{body:c,headers:n,method:r}),h;try{h=await u.json()}catch{let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${d})`)}if(typeof h=="object"&&h!==null&&"error"in h){let d=h.error,l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${d})`)}return h}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(S(e.shardKey));M(e,{caps:on,clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())S(r.shardKey)===S(e)&&this.sendShapeSubscribeIfOpen(r)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let r=this.getOrCreateConnection(e);if(!(r.wsState==="open"||r.wsState==="connecting")){if(r.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(r,e,this.wsToken).catch(()=>{});return}this.openSocket(r,e,this.wsToken)}}async openSocketWithProvidedToken(e,r,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,r,i)}openManagedSocket(e,r,s,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new p("INTERNAL","no WebSocket implementation available");let a=new n(r);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"a"),u=o(h=>{c(),i.onClose(h)},"c");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},s)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},qs),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())S(n.shardKey)===S(r)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(r),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)M(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(S(r));if(i)for(let n of i.keys())M(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let r=e.pendingStreams;e.pendingStreams=[];for(let s of r){let i=M(e,s)?this.streams.get(String(s.id)):void 0;i&&(i.started=!0)}}cancelStream(e,r){let s=this.getConnection(r),i=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(n=>n.id!==e),!M(s,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.started&&s.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);let r=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(S(n.shardKey)!==S(e.shardKey)||r.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,r){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}r();return}try{s.send(Qs)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=S(e);for(let s of this.subscriptions.all())S(s.shardKey)===r&&(s.acked=!1)}sendSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return;let s=e.fn.__lunoraTable??e.fn.__lunoraRef,i=e.serverCursor!==void 0&&e.serverBase!==void 0;M(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:s,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&M(r,{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,r){let s=hn(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type!=="error"&&this.getConnection(r)?.reconnect.reset(),i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(g(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i,r);break}case"pokePart":{this.handlePokePart(i,r);break}case"pokeStart":{this.handlePokeStart(i,r);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,r);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:r}=e,s=r===void 0?void 0:this.streams.get(r);if(s&&r!==void 0){s.handle.fail(cn(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){let a=Tr(e),c=this.identityFingerprint(),u=P.keyOf(i);fe(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&fe(n.errorCallbacks,Tr(e))}pokeBufferKey(e,r){return`${S(e)}\0${r}`}handlePokeStart(e,r){gr(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(r,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set})}handlePokePart(e,r){let s=this.pokeBuffers.get(this.pokeBufferKey(r,e.pokeId));if(!s)return;let i=s.parts.get(e.shapeId)??[];for(let a of e.rowsPatch)i.push(a.value===void 0?a:{...a,value:g(a.value)});s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);let n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,r){let s=this.pokeBufferKey(r,e.pokeId),i=this.pokeBuffers.get(s);if(i){this.pokeBuffers.delete(s);for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&this.applyPokePart(a,i,e)}}}applyPokePart(e,r,s){let i=r.parts.get(e.id)??[],n=r.resets.has(e.id),a=r.bases.get(e.id),c=r.epoch!==void 0&&e.serverEpoch!==void 0&&r.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),Ls(e.rows,i),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);let h=r.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let r=[...e.rows.values()];for(let s of e.callbacks)try{s(r)}catch{}}handleDataMessage(e){let{id:r}=e,s=r?this.subscriptions.getById(r):void 0;if(!s)return;let i;try{i=this.resolveDataPayload(e,s)}catch(n){fe(s.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${n instanceof Error?n.message:String(n)}`});return}if(i===wr){this.resnapshotSubscription(s);return}if(s.serverBase=i,this.dropCacheSeed(P.keyOf(s)),e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(let n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(s),Le(s,s.serverCursor),$(s,Z(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,e.cursor,e.epoch)}handleSettledMessage(e){let r=this.subscriptions.getById(e.id);if(r){this.ackAndAdvanceCursor(r,e.cursor,e.epoch),e.lastMutationId!==void 0&&(r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId));for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=P.keyOf(r);this.tabCoordinator.broadcastSubscriptionSettled(s,r.serverCursor,r.serverEpoch,r.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,r,s){e.acked=!0,(r!==void 0&&r!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(r!==void 0&&(e.serverCursor=r),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),Le(e,e.serverCursor)&&$(e,Z(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return g(e.data);let s=g(e.delta);return ur(s)?r.serverBase===void 0?s:hr(r.serverBase,s)??wr:s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(S(r))?.get(e.topic);if(!s)return;let i=g(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,fe(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{H(this.onPersistenceError,"remove",r,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 r=2166136261,s=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);r^=n,r=Math.imul(r,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(r>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return!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 r=this.authToken;return r===null?!1:this.hashToken(r)===e}adoptResolvedSubject(e,r){this.closed||r===null||this.authToken!==e||this.setAuthToken(e,r.id)}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let r=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return r===void 0?e.identity:r}rejectQueuedForIdentityChange(e){let r=this.offlineQueue.drain(),s=[];for(let i of r){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){s.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(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,r){for(let s of this.connections.values())s.identity===e&&(s.identity=r)}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r);this.offlineQueue.restampIdentity(e,r)}restampWatermarks(e,r){let s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);let n=r??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.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(()=>{})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let r=S(e),s=this.offlineFlushes.get(r);if(s===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(s??Promise.resolve());try{await this.drainOfflineQueue(e)}catch{}})();this.offlineFlushes.set(r,i),await i,this.offlineFlushes.get(r)===i&&this.offlineFlushes.delete(r)}async drainOfflineQueue(e){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",d)}let s=S(e),i=this.offlineQueue.drain(h=>S(h.shardKey)===s);if(i.length===0)return;let n=[],a=[];for(let h of i){let d=this.replayGateVerdict(h);d==="send"?n.push(h):d==="hold"&&a.push(h)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&this.getCurrentUser().catch(()=>{}),n.length===0)return;let c=this.encodableOrSettleTerminal(n);if(c.length===0)return;if(c.length===1){await this.replaySequential(c,e),this.scheduleRateLimitedRetry(e);return}let u=[];for(let h=0;h<c.length;h+=ft){let d=c.slice(h,h+ft),l=await this.replayBatched(d,e);if(u.push(...l.requeue),l.stop){u.push(...c.slice(h+ft));break}}u.length>0&&this.offlineQueue.requeue(u),this.scheduleRateLimitedRetry(e)}noteReplayRetryDelay(e,r){let s=S(e),i=this.replayRetryState.get(s),n=(i?.attempts??0)+1,a=As(r,n);this.replayRetryState.set(s,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let r=S(e),s=this.replayRetryState.get(r),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(r);return}s.delayMs=void 0;let n=this.replayRetryTimers.get(r);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(r,setTimeout(()=>{this.replayRetryTimers.delete(r),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{z(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}replayGateVerdict(e){let r=this.stampOf(e);if(r===void 0)return this.queuedIdentities.delete(e.id??""),"send";let s=this.replayIdentityVerdict(r);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="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,r,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}shouldRequeueReplayFailure(e){if(ks(e)){let r=this.hashToken(this.authToken??"");return this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Ts(e)}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e,r){for(let s=0;s<e.length;s+=1){let i=e[s];if(i)try{let n,a=await this.rpc(i.functionPath,i.args,i.shardKey,{captureBookmark:!0,clientId:i.clientId??this.clientId,mutationId:i.id,onCommitCursor:o(c=>{n=c},"onCommitCursor")});this.settleReplaySuccess(i,a,n)}catch(n){if(!this.shouldRequeueReplayFailure(n)){this.settleReplayTerminal(i,n);continue}this.noteReplayRetryDelay(r,n),this.offlineQueue.requeue(e.slice(s));return}}}async replayBatched(e,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let s=JSON.stringify({calls:e.map((u,h)=>({args:z(u.args,`args for '${u.functionPath}'`),functionPath:u.functionPath,id:h,clientId:u.clientId??this.clientId,mutationId:u.id,shardKey:u.shardKey}))});if(e.length>1&&Ms(s)>Fs)return await this.replayBatchedHalves(e,r);let i;try{i=await this.fetchImpl(ee(this.url,Sr),{body:s,headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}let n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,r);let a,c=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,Ue(i.status,i.statusText,c),r)}if(!a.results){let u=a.error===void 0?Ue(i.status,i.statusText,c):Er(a.error,c);return this.settleWholeBatchError(e,u,r)}return{requeue:this.settleReplayBatchSlots(e,a.results,r),stop:!1}}settleWholeBatchError(e,r,s){if(r instanceof B||r.code!==void 0&&this.shouldRequeueReplayFailure(r))return this.noteReplayRetryDelay(s,r),{requeue:e,stop:!0};for(let i of e)this.settleReplayTerminal(i,r);return{requeue:[],stop:!1}}async replayBatchedHalves(e,r){let s=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,s),r);if(i.stop)return{requeue:[...i.requeue,...e.slice(s)],stop:!0};let n=await this.replayBatched(e.slice(s),r);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,r,s){let i=new Map;for(let a of r)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);let n=[];for(let[a,c]of e.entries()){let u=i.get(a);if(u===void 0)n.push(c);else if("error"in u){let h=qe(u.error);this.shouldRequeueReplayFailure(h)?(this.noteReplayRetryDelay(s,h),n.push(c)):this.settleReplayTerminal(c,h)}else this.settleReplaySuccess(c,g(u.result),u.commitCursor)}return n}};var Fr=F(Ct(),1),Mr=F(G(),1);var fn=o(()=>{let t=(0,Fr.c)(4),e=rt(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"o"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"c"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,Mr.useSyncExternalStore)(r,s,i)},"S");export{gt as a,Dr as b,Ye as c,Vr as d,Jr as e,rt as f,fn as g};
|