@lunora/studio 1.0.0-alpha.187 → 1.0.0-alpha.188
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-NO5VGTWP.js → chunk-2ZSZL5MV.js} +1 -1
- package/dist/standalone/{chunk-IZDX3F65.js → chunk-3KWRWXNU.js} +1 -1
- package/dist/standalone/{chunk-MKE333RB.js → chunk-3NPBDMKP.js} +1 -1
- package/dist/standalone/{chunk-ZNYTH4BS.js → chunk-4HGBHKYE.js} +1 -1
- package/dist/standalone/{chunk-6DLHIMOI.js → chunk-5KYYY2JT.js} +1 -1
- package/dist/standalone/{chunk-BI2PP4AE.js → chunk-5P47LIVI.js} +1 -1
- package/dist/standalone/{chunk-N4GEA5GK.js → chunk-67NTQ3LZ.js} +1 -1
- package/dist/standalone/{chunk-Y76TQLLR.js → chunk-6IQMOEOF.js} +1 -1
- package/dist/standalone/{chunk-BG52HJBJ.js → chunk-6N434JI6.js} +1 -1
- package/dist/standalone/{chunk-B6BFVYFA.js → chunk-6VVWJZHQ.js} +1 -1
- package/dist/standalone/{chunk-U7YOMGYN.js → chunk-6Z52O4L5.js} +1 -1
- package/dist/standalone/{chunk-7VNOCXWO.js → chunk-APFRLQEI.js} +1 -1
- package/dist/standalone/{chunk-UDXIBUS6.js → chunk-BVQ4L3RU.js} +1 -1
- package/dist/standalone/{chunk-HBWT2BXO.js → chunk-CREIQVKV.js} +1 -1
- package/dist/standalone/{chunk-C3UMVVZD.js → chunk-CUHUBIUI.js} +1 -1
- package/dist/standalone/chunk-E7V5U2MI.js +11 -0
- package/dist/standalone/{chunk-FUXL36RK.js → chunk-EAN22YRU.js} +1 -1
- package/dist/standalone/{chunk-VXQJWD3F.js → chunk-ED3ZEGZG.js} +1 -1
- package/dist/standalone/{chunk-AJU3V2XW.js → chunk-ET7C5ULF.js} +1 -1
- package/dist/standalone/{chunk-2FGXE3E5.js → chunk-FP4R4GOH.js} +1 -1
- package/dist/standalone/{chunk-QIPTFNQK.js → chunk-FQCAIFCH.js} +1 -1
- package/dist/standalone/{chunk-ORJB5XQH.js → chunk-FRTMV7KN.js} +1 -1
- package/dist/standalone/{chunk-QOSKGDBH.js → chunk-FRYN7JES.js} +1 -1
- package/dist/standalone/{chunk-PTRUAQYA.js → chunk-FYJSHANJ.js} +1 -1
- package/dist/standalone/{chunk-W5YA2J66.js → chunk-GG3N6GAU.js} +1 -1
- package/dist/standalone/{chunk-KE5T44IA.js → chunk-GPTMEL3H.js} +1 -1
- package/dist/standalone/{chunk-PAZ72JHQ.js → chunk-H5ZT3AWK.js} +1 -1
- package/dist/standalone/{chunk-CFN6A74K.js → chunk-HHQL672G.js} +1 -1
- package/dist/standalone/{chunk-N6CQJUDY.js → chunk-HMIN25NC.js} +1 -1
- package/dist/standalone/{chunk-AWN2GXCK.js → chunk-JYITKWA6.js} +1 -1
- package/dist/standalone/{chunk-FI3UY4QJ.js → chunk-KMRCIOIP.js} +1 -1
- package/dist/standalone/{chunk-3BN3N2CX.js → chunk-KRTYYF2O.js} +1 -1
- package/dist/standalone/{chunk-BNIDGSDE.js → chunk-L7HFSFJM.js} +1 -1
- package/dist/standalone/{chunk-ZWDPWM3I.js → chunk-LSMG224C.js} +1 -1
- package/dist/standalone/{chunk-YOKBLIIN.js → chunk-LTG5WFNX.js} +1 -1
- package/dist/standalone/{chunk-7VNHUUK4.js → chunk-MUGK2MFE.js} +1 -1
- package/dist/standalone/{chunk-6FTYD55M.js → chunk-MV2ZTAZK.js} +1 -1
- package/dist/standalone/{chunk-XSNWSHZ6.js → chunk-N7LXTFLY.js} +1 -1
- package/dist/standalone/{chunk-367RGUUX.js → chunk-N7XDHYUO.js} +1 -1
- package/dist/standalone/{chunk-6A34IMQS.js → chunk-NLVCQVMP.js} +1 -1
- package/dist/standalone/{chunk-WNVPC7FI.js → chunk-OB6NUAFL.js} +1 -1
- package/dist/standalone/{chunk-DLF7WRVK.js → chunk-ON2PLGFW.js} +1 -1
- package/dist/standalone/{chunk-VBDYQCRQ.js → chunk-Q5PUOBMG.js} +1 -1
- package/dist/standalone/{chunk-PGV42T2U.js → chunk-RKWYK227.js} +1 -1
- package/dist/standalone/{chunk-BWRPOIEI.js → chunk-SB4LBWDA.js} +1 -1
- package/dist/standalone/{chunk-DAAYIBSL.js → chunk-SMQFKS3F.js} +1 -1
- package/dist/standalone/{chunk-WD22LMYA.js → chunk-SZWB6H4J.js} +1 -1
- package/dist/standalone/{chunk-I57A5YB6.js → chunk-UH4LORKU.js} +1 -1
- package/dist/standalone/{chunk-Q6PUWGXK.js → chunk-UPAZZWAF.js} +1 -1
- package/dist/standalone/{chunk-6MJU7KID.js → chunk-VA5RLB7F.js} +1 -1
- package/dist/standalone/{chunk-CMO25UOM.js → chunk-WEE5O4P2.js} +1 -1
- package/dist/standalone/{chunk-ZTQSA34U.js → chunk-Y3AKVKUK.js} +1 -1
- package/dist/standalone/{chunk-62IKYVD3.js → chunk-YIXQ36NU.js} +1 -1
- package/dist/standalone/{chunk-AO3LNXNG.js → chunk-YQOGBOO3.js} +1 -1
- package/dist/standalone/{chunk-DK7IUHFW.js → chunk-Z7CZJS2Q.js} +1 -1
- package/dist/standalone/{chunk-DAXY4RAL.js → chunk-ZH5ESVYN.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +4 -4
- package/dist/standalone/chunk-PYI2MI4Q.js +0 -11
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{a as wt,d as p}from"./chunk-MKL7VDTL.js";import{a as o,d as x,e as G,f as Ct,g as Be}from"./chunk-YKXDMIHQ.js";var Q=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 _r=class extends Q{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 _r;var Lr={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")},Qr=class{static{o(this,"TimeoutManager")}#e=Lr;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},D=new Qr;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 ve(t,e){return Math.max(t+(e||0)-Date.now(),0)}o(ve,"timeUntilStale");function L(t,e){return typeof t=="function"?t(e):t}o(L,"resolveStaleTime");function E(t,e){return typeof t=="function"?t(e):t}o(E,"resolveQueryBoolean");function ge(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(!N(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(ge,"matchQuery");function Se(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(!N(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}o(Se,"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 N(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(!N(t[s],e[s]))return!1;return!0}let r=Object.keys(e);for(let s of r)if(!N(t[s],e[s]))return!1;return!0}return!1}o(N,"partialMatchKey");var Dr=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:Dr.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 we(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(we,"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=>{D.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 Ur(t){return t}o(Ur,"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 Ce(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(Ce,"ensureQueryFn");function ke(t,e){return typeof t=="function"?t(...e):!!t}o(ke,"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 U=(()=>{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 qr(){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(qr,"createNotifyManager");var g=qr();var Nr=class extends Q{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 Kr(t){return Math.min(1e3*2**t,3e4)}o(Kr,"defaultRetryDelay");function ze(t){return(t??"online")==="online"?ie.isOnline():!0}o(ze,"canFetch");var Te=class extends Error{static{o(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ee(t){let e=!1,r=0,s,i=he(),n=o(()=>i.status!=="pending","isResolved"),a=o(b=>{if(!n()){let C=new Te(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 A=t.retry??(U.isServer()?0:3),F=t.retryDelay??Kr,W=typeof F=="function"?F(r,k):F,V=A===!0||typeof A=="number"&&r<A||typeof A=="function"&&A(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(Ee,"createRetryer");var Ie=class{static{o(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),oe(this.gcTime)&&(this.#e=D.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(U.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(D.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=Ce(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 A=o(()=>{let Ke={client:e.client,queryKey:e.queryKey,pageParam:b,direction:C?"backward":"forward",meta:e.options.meta};return l(Ke),Ke},"createQueryFnContext")(),F=await f(A),{maxPages:W}=e.options,V=C?Pt:Rt;return{pages:V(m.pages,F,W),pageParams:V(m.pageParams,b,W)}},"fetchPage");if(i&&n.length){let m=i==="backward",b=m?Br: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 Br(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}o(Br,"getPreviousPageParam");var Qt=class extends Ie{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=>L(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:!ve(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=Ce(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=Ee({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:o(u=>{u instanceof Te&&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 Te){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),g.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 Q{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&&!we(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)||L(this.options.staleTime,this.#t)!==L(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 $r(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=L(this.options.staleTime,this.#t);if(U.isServer()||this.#s.isStale||!oe(t))return;let r=ve(this.#s.dataUpdatedAt,t)+1;this.#d=D.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,!(U.isServer()||E(this.options.enabled,this.#t)===!1||!oe(this.#u)||this.#u===0)&&(this.#l=D.setInterval(()=>{(this.options.refetchIntervalInBackground||re.isFocused())&&this.#f()},this.#u))}#g(){this.#y(),this.#v(this.#b())}#S(){this.#d!==void 0&&(D.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(D.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 M=this.hasListeners(),ae=!M&&Dt(t,e),me=M&&Ut(t,r,e,s);(ae||me)&&(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 M;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(M=i.data,C=!0):M=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,M!==void 0&&(b="success",f=ue(i?.data,M,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(M){this.#a=M}this.#a&&(y=this.#a,f=this.#c,m=Date.now(),b="error");let k=d.fetchStatus==="fetching",A=b==="pending",F=b==="error",W=A&&k,V=f!==void 0,q={status:b,fetchStatus:d.fetchStatus,isPending:A,isSuccess:b==="success",isError:F,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&&!A,isLoadingError:F&&!V,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:F&&V,isStale:Je(t,e),refetch:this.refetch,promise:this.#o,isEnabled:E(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let M=q.data!==void 0,ae=q.status==="error"&&!M,me=o(be=>{ae?be.reject(q.error):M&&be.resolve(q.data)},"finalizeThenableIfPossible"),St=o(()=>{let be=this.#o=q.promise=he();me(be)},"recreateThenable"),ye=this.#o;switch(ye.status){case"pending":t.queryHash===r.queryHash&&me(ye);break;case"fulfilled":(ae||q.data!==ye.value)&&St();break;case"rejected":(!ae||q.error!==ye.reason)&&St();break}}return q}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),we(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){g.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function jr(t,e){return E(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&E(e.retryOnMount,t)===!1)}o(jr,"shouldLoadOnMount");function Dt(t,e){return jr(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&&L(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(L(e.staleTime,t))}o(Je,"isStale");function $r(t,e){return!we(t.getCurrentResult(),e)}o($r,"shouldAssignObserverCurrentProperties");var qt=class extends Ie{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||Hr(),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=Ee({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),g.batch(()=>{this.#t.forEach(r=>{r.onMutationUpdate(t)}),this.#r.notify({mutation:this,type:"updated",action:t})})}};function Hr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}o(Hr,"getDefaultState");var Nt=class extends Q{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 qt({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=Oe(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=Oe(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=Oe(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=Oe(t);return typeof e=="string"?this.#t.get(e)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){g.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=>Se(e,r))}findAll(t={}){return this.getAll().filter(e=>Se(t,e))}notify(t){g.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return g.batch(()=>Promise.all(t.map(e=>e.continue().catch(w))))}};function Oe(t){return t.options.scope?.id}o(Oe,"scopeFor");var Kt=class extends Q{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(){g.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=>ge(e,r))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(r=>ge(t,r)):e}notify(t){g.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){g.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){g.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 Nt,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(L(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 g.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;g.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){let r=this.#e;return g.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let r={revert:!0,...e},s=g.batch(()=>this.#e.findAll(t).map(i=>i.cancel(r)));return Promise.all(s).then(w).catch(w)}invalidateQueries(t,e={}){return g.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=g.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(L(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=>{N(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=>{N(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=x(G(),1);var ne=x(G(),1),Bt=x(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=x(G(),1),zr=x(Be(),1);function Wr(){let t=!1;return{clearReset:o(()=>{t=!1},"clearReset"),reset:o(()=>{t=!0},"reset"),isReset:o(()=>t,"isReset")}}o(Wr,"createValue");var Vr=le.createContext(Wr()),jt=o(()=>le.useContext(Vr),"useQueryErrorResetBoundary");var $t=x(G(),1);var Ht=o((t,e,r)=>{let s=r?.state.error&&typeof t.throwOnError=="function"?ke(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||ke(r,[t.error,s])),"getHasError");var Re=x(G(),1);var Vt=Re.createContext(!1),Gt=o(()=>Re.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(g.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&&!U.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 Gr(t,e){return Zt(t,Ge,e)}o(Gr,"useQuery");var er=x(Ct(),1);var X=x(G(),1),tt=x(Be(),1);var tr=(0,X.createContext)(null),Jr=o(()=>new Xe({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"Q"),Xr=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??Jr(),"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 Pe=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"),Yr=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$",Ae="__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===Ae?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",Pe(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",Pe(c)]:[T,"bytes",Pe(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===Ae?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"b"),S=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=>S(i,e+1));case"bigint":{let i=t[2];if(typeof i!="string"||i.length>1024||!/^-?\d+$/.test(i))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(i)}case"date":{let i=S(t[2],e+1);if(typeof i!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(i)}case"map":{let i=t[2];return new Map(i.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[S(n[0],e+1),S(n[1],e+1)]}))}case"set":return new Set(t[2].map(i=>S(i,e+1)));case"url":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(i)}case"error":{let i=t[2],n=t[3];if(typeof i!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let 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=S(t[4],e+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let h of Object.keys(u))h===Ae?Object.defineProperty(c,h,{configurable:!0,enumerable:!0,value:u[h],writable:!0}):c[h]=u[h];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:S(t[5],e+1),writable:!0}),c}case"bytes":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let n=Yr(i);if(Pe(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=>S(i,e+1))}return t.map(i=>S(i,e+1))}let r=t,s={};for(let i of Object.keys(r)){let n=S(r[i],e+1);i===Ae?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"),Fe=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"),Me=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"),Zr=500,es=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 ts="lunora-query-cache",rs="query-cache",ir="by_ts",ss=1,is=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??ts,s=t.storeName??rs,i=es(t.maxEntries??Zr,"createIndexedDbQueryCache"),n=Fe(e,r,ss,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(ir,"ts",{unique:!1})}),a=Me(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 is()}},"L");var ar=o(()=>{let t=null;return{get:o(()=>t,"get"),set:o(e=>{t=e},"set")}},"r");var xe=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,ns="lunora-bridge",as=1e3,os=3e3,_e=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??as,this.leaderTimeout=e.leaderTimeout??os,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??ns),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",cs=o(t=>{if(Array.isArray(t))return t;if(st(t)&&Array.isArray(t[at]))return t[at]},"y"),us=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"),hs=o((t,e)=>{let r=e[nt];if(typeof r!="number")return t.length;let s=us(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"),ds=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"),ls=o((t,e)=>{let r=[];for(let u of t){if(ds(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(hs(r,n),0,n):a[c]=n,a},"I"),hr=o((t,e)=>{let r=cs(t);if(r===void 0)return;let s=ls(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 fs=1024,Le=o(t=>{let e=t.maxBuffer??fs,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"),ps=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"),ms=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"),ys=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(S(JSON.parse(t.data)))}catch{return e.fail(new p("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"E"),bs=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=ps(i.slice(0,a));if(i=i.slice(a+2),ys(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=ms(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}=Le({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 bs(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 vs=/["\\\u0000-\u001F\uD800-\uDFFF]/,pr=o(t=>vs.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},i=!1;t.optimisticLayers.push(s),$(t,r);let n=o(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===s.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),a=o(()=>{$(t,Z(t.serverBase,t.optimisticLayers))},"i");return{confirm:o(c=>{if(c===void 0){n();return}s.commitCursor=c,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&a()},"confirm"),rollback:o(()=>{i||(i=!0,n(),a())},"rollback")}},"y"),Qe=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,gs=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"),Ue=gs,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"),De=class{static{o(this,"l")}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??=Ue(),this.items.push(r),this.persistence?.append({args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},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,baselineSeq:a.baselineSeq,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,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},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)})}}hasPending(e){return this.items.some(r=>e(r))}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 Ss="lunora-outbox",ws="offline-mutations",dt="by_id",Cs=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??Ss,s=t.storeName??ws,i=Fe(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(dt,"id",{unique:!0})}),n=Me(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 Cs()}},"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,ks=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}},"Ee"),gr=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"j"),te=class{static{o(this,"_")}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"]),Ts=o(t=>Or.has(t?.code??""),"Ae"),Es=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||Ir.has(e)||Or.has(e)},"_e"),Rr=6e4,Is=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},"ie"),Os={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},qe=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(Os[t]??"BAD_REQUEST",n,{data:i})},"M"),Rs=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},"Re"),Ar=o((t,e=Math.random)=>{let r=Math.min(Is*2**Math.max(t-1,0),Rr);return Math.round(r*(.5+e()*.5))},"ne"),Ps=o(t=>t instanceof B||Ir.has(t?.code??""),"Pe"),As=o((t,e,r)=>{let s=ot(t);return s!==void 0&&s>0?Math.min(s,Rr):Ps(t)?Ar(e,r):void 0},"Me"),Fs=983040,Ms=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"He"),xs="/_lunora/rpc",Sr="/_lunora/rpc-batch",_s="/_lunora/ws",pt=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"x"),fe=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"I"),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)},"Ne"),Qs="lunora-ping",Ds=3e4,Us=1e4,qs=250,Ns=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",qi="/_lunora/admin/auth/sign-up-invitations/create",Ni="/_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,"J"),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],v=o(t=>t??"","l"),Fr=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}},"ae"),cn=o(t=>{let{code:e,messageText:r}=Fr(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"hs"),Tr=o(t=>{let{code:e,messageText:r}=Fr(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"X");function bt(t){if(t!==void 0)return e=>{t(e)}}o(bt,"Q");var pe=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)},"us"),_=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"b"),Ne=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=S(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=Ne(t),s=Rs(r,e);return s!==void 0&&(r.data=s),r},"Z"),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:S(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:Ne(i.error),ok:!1}:{ok:!0,value:S(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"ls"),ln=Promise.resolve(),gt=class t{static{o(this,"oe")}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 xe,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 De(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-${Ue()}`,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}`);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}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=v(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=v(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=v(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&&_(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&&_(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&_(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?Ne(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??Ue(),{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(v(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,b=l==="connecting"&&y,C=m&&s.mutationId===void 0&&this.hasPendingWriteAhead(s.shardKey);if(l!=="open"&&!h&&m||b||C)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,a,s.precondition);try{let k,A=await this.rpc(e.__lunoraRef,i,s.shardKey,{baselineSeq:this.baselineCursorFor(s.shardKey),captureBookmark:!0,mutationId:n,onCommitCursor:o(F=>{k=F},"onCommitCursor")});for(let F of a)F(k);return A}catch(k){throw fe(c),k}}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 ks(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))),S(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))),S(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(qi,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(Ni,"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.returnCacheSeed(P.keyOf(l)),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}=Le({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"&&_(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=v(e.shardKey);for(let[s,i]of this.streams)v(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 _e({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),Qe(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&&pe(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,...n.length>0&&{onRejected:o(()=>{fe(n)},"onRejected")},shardKey:s})}catch(d){throw fe(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,baselineSeq:this.baselineCursorFor(s),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),fe(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)})}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let r=v(e);return this.offlineQueue.hasPending(s=>v(s.shardKey)===r)}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)}returnCacheSeed(e){let r=this.cacheSeededQueries.get(e);r!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,r))}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(()=>{})},qs)}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"}baselineCursorFor(e){let r=v(e),s;for(let i of this.subscriptions.all())v(i.shardKey)!==r||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}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{fe(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(v(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!_(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=v(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.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.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 qe(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 qe(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),S(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(v(e.shardKey));_(e,{caps:on,clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())v(r.shardKey)===v(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()},Ns),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())v(n.shardKey)===v(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)_(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(v(r));if(i)for(let n of i.keys())_(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=_(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),!_(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(!(v(n.shardKey)!==v(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=v(e);for(let s of this.subscriptions.all())v(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;_(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"&&_(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(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"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);pe(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&&pe(n.errorCallbacks,Tr(e))}pokeBufferKey(e,r){return`${v(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:S(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){pe(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),Qe(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),Qe(e,e.serverCursor)&&$(e,Z(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return S(e.data);let s=S(e.delta);return ur(s)?r.serverBase===void 0?s:hr(r.serverBase,s)??wr:s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(v(r))?.get(e.topic);if(!s)return;let i=S(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,pe(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=v(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=v(e),i=this.offlineQueue.drain(h=>v(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(()=>{}),this.noteHeldRetryDelay(e)),n.length===0){this.scheduleRateLimitedRetry(e);return}let c=this.encodableOrSettleTerminal(n);if(c.length===0){this.scheduleRateLimitedRetry(e);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)}noteHeldRetryDelay(e){let r=v(e),s=this.replayRetryState.get(r),i=(s?.attempts??0)+1;this.replayRetryState.set(r,{attempts:i,delayMs:Math.max(s?.delayMs??0,Ar(i))})}noteReplayRetryDelay(e,r){let s=v(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=v(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(Ts(e)){let r=this.hashToken(this.authToken??"");return this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Es(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,{baselineSeq:i.baselineSeq,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,qe(i.status,i.statusText,c),r)}if(!a.results){let u=a.error===void 0?qe(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=Ne(u.error);this.shouldRequeueReplayFailure(h)?(this.noteReplayRetryDelay(s,h),n.push(c)):this.settleReplayTerminal(c,h)}else this.settleReplaySuccess(c,S(u.result),u.commitCursor)}return n}};var Mr=x(Ct(),1),xr=x(G(),1);var fn=o(()=>{let t=(0,Mr.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,xr.useSyncExternalStore)(r,s,i)},"S");export{gt as a,Ur as b,Ye as c,Gr as d,Xr as e,rt as f,fn as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as w}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as y}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as C}from"./chunk-
|
|
1
|
+
import{a as w}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as y}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as C}from"./chunk-MV2ZTAZK.js";import"./chunk-ULIQFBZU.js";import"./chunk-LTG5WFNX.js";import"./chunk-35DM4JJG.js";import{a as h}from"./chunk-4ZEL6BYL.js";import{c as u}from"./chunk-KMRCIOIP.js";import"./chunk-E7V5U2MI.js";import"./chunk-FSRSK4LY.js";import"./chunk-MKL7VDTL.js";import{a as T}from"./chunk-FKVZRPV5.js";import{a as S,b as K,c as $,d as g,e as o,f as i}from"./chunk-HEAQVSNS.js";import{a as A,e as k}from"./chunk-WUWBZPUK.js";import{d as M,r as D}from"./chunk-FODLDLE2.js";import{a as d,d as z,e as ae,g as re}from"./chunk-YKXDMIHQ.js";var O=z(ae(),1);var e=z(re(),1);var Q="agent_threads",se="agent_messages",F="agent_run_queue",R=100,ne=250,oe={},ie={filters:[],limit:R,offset:0,orderBy:{column:"updatedAt",direction:"desc"},skipCount:!0,table:Q},l=d((s,t)=>{let r=s[t];return typeof r=="string"?r:void 0},"i"),j=d((s,t)=>{let r=s[t];return typeof r=="number"?r:void 0},"A"),L=d(s=>{let{usage:t}=s;if(t===null||typeof t!="object")return;let{totalTokens:r}=t;return typeof r=="number"?r:void 0},"U"),de=d(s=>{let{toolCalls:t}=s;return Array.isArray(t)?t.map(r=>r!==null&&typeof r=="object"?r.name:void 0).filter(r=>typeof r=="string"):[]},"ne"),le=d(s=>{switch(s){case"awaiting_input":return"warning";case"cancelled":return"warning";case"error":return"destructive";case"running":return"info";default:return"outline"}},"oe"),ce=d(s=>{switch(s){case"approved":return"success";case"rejected":return"destructive";default:return"warning"}},"de"),Ne=d(({initialShardKey:s=""})=>{let t=M(),[r,I]=(0,O.useState)(void 0),{data:c}=u(h.listTables,oe,{live:!0,shardKey:s}),G=c!==void 0,p=Array.isArray(c)&&c.some(a=>a.name===Q),H=Array.isArray(c)&&c.some(a=>a.name===F),{data:_,error:J,errorSource:V,liveError:W}=u(h.readTablePage,ie,{enabled:p,live:!0,shardKey:s}),X={filters:[{column:"threadKey",operator:"eq",value:r??""}],limit:ne,offset:0,orderBy:{column:"seq",direction:"asc"},skipCount:!0,table:se},{data:q}=u(h.readTablePage,{limit:R,offset:0,orderBy:{column:"position",direction:"asc"},skipCount:!0,table:F},{enabled:H,live:!0,shardKey:s}),{data:B,error:Y,errorSource:Z}=u(h.readTablePage,X,{enabled:p&&r!==void 0,live:!0,shardKey:s}),v=Array.isArray(_?.rows)?_.rows:[],ee=Array.isArray(q?.rows)?q.rows:[],E=d(a=>ee.filter(n=>l(n,"threadKey")===a).length,"w"),P=Array.isArray(B?.rows)?B.rows:[],U=v.find(a=>l(a,"key")===r),f;return G&&!p?f=(0,e.jsx)(T,{description:t("No @lunora/agent tables found in this deployment. Add lunora/agents.ts with defineAgent(...) and merge the agent schema extension to run durable AI agents."),testId:"agents-unconfigured",title:t("No agents configured")}):p&&v.length===0?f=(0,e.jsx)(T,{description:t("No agent has run yet. Start a run with ctx.agents.<name>.run(...) and its thread appears here."),testId:"agents-empty",title:t("No agent threads yet")}):f=(0,e.jsxs)("div",{className:"flex flex-col gap-6",children:[(0,e.jsx)(A,{className:"overflow-hidden py-0",children:(0,e.jsx)(k,{className:"px-0",children:(0,e.jsxs)(S,{"data-testid":"agents-threads-table",children:[(0,e.jsx)(K,{children:(0,e.jsxs)(g,{children:[(0,e.jsx)(o,{children:t("Agent")}),(0,e.jsx)(o,{children:t("Key")}),(0,e.jsx)(o,{children:t("Status")}),(0,e.jsx)(o,{children:t("Queued")}),(0,e.jsx)(o,{children:t("Messages")}),(0,e.jsx)(o,{children:t("Tokens")}),(0,e.jsx)(o,{children:t("Updated")}),(0,e.jsx)(o,{"aria-label":t("Actions")})]})}),(0,e.jsx)($,{children:v.map(a=>{let n=l(a,"key")??"",m=l(a,"status"),x=L(a);return(0,e.jsxs)(g,{"data-active":n===r?"":void 0,"data-testid":`agents-thread-${n}`,children:[(0,e.jsx)(i,{className:"font-mono text-xs",children:l(a,"agent")??"\u2014"}),(0,e.jsx)(i,{className:"font-mono text-xs text-muted-foreground",children:n}),(0,e.jsx)(i,{children:(0,e.jsx)(y,{"data-testid":`agents-thread-status-${n}`,variant:le(m),children:m??"\u2014"})}),(0,e.jsx)(i,{className:"tabular-nums",children:E(n)===0?(0,e.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}):(0,e.jsx)(y,{"data-testid":`agents-thread-queued-${n}`,variant:"warning",children:E(n)})}),(0,e.jsx)(i,{className:"tabular-nums",children:j(a,"messageCount")??"\u2014"}),(0,e.jsx)(i,{className:"tabular-nums text-muted-foreground",children:x??"\u2014"}),(0,e.jsx)(i,{className:"text-muted-foreground tabular-nums",children:D(j(a,"updatedAt"),"\u2014")}),(0,e.jsx)(i,{className:"text-right",children:(0,e.jsx)(w,{"data-testid":`agents-thread-open-${n}`,onClick:d(()=>{I(n)},"onClick"),size:"sm",type:"button",variant:"outline",children:t("Timeline")})})]},n)})})]})})}),Y!==null&&(0,e.jsx)(C,{error:Z,testId:"agents-messages-error"}),r!==void 0&&(0,e.jsx)(A,{className:"overflow-hidden py-0","data-testid":"agents-thread-detail",children:(0,e.jsxs)(k,{className:"flex flex-col gap-3 px-4 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsxs)("span",{className:"font-mono text-xs",children:[t("Timeline")," \xB7 ",r,U!==void 0&&(0,e.jsxs)("span",{className:"text-muted-foreground",children:[" \xB7 ",t("Usage"),": ",L(U)??0," ",t("Tokens")]})]}),(0,e.jsx)(w,{"data-testid":"agents-thread-detail-close",onClick:d(()=>{I(void 0)},"onClick"),size:"xs",type:"button",variant:"ghost",children:t("Close")})]}),P.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:t("This thread has no messages yet.")}):(0,e.jsxs)(S,{"data-testid":"agents-messages-table",children:[(0,e.jsx)(K,{children:(0,e.jsxs)(g,{children:[(0,e.jsx)(o,{children:t("Role")}),(0,e.jsx)(o,{children:t("Content")}),(0,e.jsx)(o,{children:t("Tool")}),(0,e.jsx)(o,{children:t("Approval")})]})}),(0,e.jsx)($,{children:P.map((a,n)=>{let m=l(a,"role")??"\u2014",x=de(a),te=l(a,"toolName"),b=l(a,"status"),N=j(a,"seq")??n;return(0,e.jsxs)(g,{"data-testid":`agents-message-${String(N)}`,children:[(0,e.jsx)(i,{className:"font-mono text-xs align-top text-muted-foreground",children:m}),(0,e.jsx)(i,{className:"max-w-md font-mono text-xs whitespace-pre-wrap break-words",children:l(a,"content")??"\u2014"}),(0,e.jsx)(i,{className:"font-mono text-xs align-top text-muted-foreground",children:te??(x.length>0?x.join(", "):"\u2014")}),(0,e.jsx)(i,{className:"align-top",children:b===void 0?(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:"\u2014"}):(0,e.jsx)(y,{"data-testid":`agents-message-approval-${String(N)}`,variant:ce(b),children:b})})]},l(a,"messageKey")??`${m}:${String(N)}`)})})]})]})})]}),(0,e.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-agents-panel",children:[J!==null&&(0,e.jsx)(C,{error:V,testId:"agents-error"}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t("Agents run as durable workflows. Each run persists a thread of assistant and tool messages; select a thread to inspect its timeline, tool calls, approvals, and token usage.")}),W!==void 0&&(0,e.jsx)("p",{className:"text-xs text-amber-600 dark:text-amber-500","data-testid":"agents-live-error",role:"alert",children:t("Live updates unavailable; showing the last evaluation.")}),f]})},"be");export{Ne as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as G}from"./chunk-EA2JKR5D.js";import{a as x}from"./chunk-IMOHEGMV.js";import{a as U}from"./chunk-2DX5MROH.js";import{b as M}from"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{W as O}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as p}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as w}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as E}from"./chunk-4ZEL6BYL.js";import{f as D}from"./chunk-
|
|
1
|
+
import{a as G}from"./chunk-EA2JKR5D.js";import{a as x}from"./chunk-IMOHEGMV.js";import{a as U}from"./chunk-2DX5MROH.js";import{b as M}from"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{W as O}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as p}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as w}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as E}from"./chunk-4ZEL6BYL.js";import{f as D}from"./chunk-E7V5U2MI.js";import"./chunk-FSRSK4LY.js";import"./chunk-MKL7VDTL.js";import{d as K,e as _,f as z,h as B,o as P,r as q}from"./chunk-FODLDLE2.js";import{a as s,d as J,e as ie,g as oe}from"./chunk-YKXDMIHQ.js";var i=J(ie(),1);var e=J(oe(),1);var de=s(r=>r.kind==="id"?r.table===void 0?"id":`id<${r.table}>`:r.kind==="array"?r.element===void 0?"array":`${r.element}[]`:r.kind,"oe"),le=s(r=>r===void 0||r.length===0?"()":`(${r.map(o=>`${o.name}${o.optional?"?":""}: ${de(o)}`).join(", ")})`,"ie"),ce=s(r=>{switch(r){case"array":return[];case"bigint":case"number":return 0;case"boolean":return!1;case"object":case"record":return{};default:return""}},"de"),ue=s(r=>{let o={};for(let a of r??[])a.optional||(o[a.name]=ce(a.kind));return JSON.stringify(o,void 0,2)},"le"),me=z(E.runAs),fe=10,he=s(r=>r===void 0?"undefined":JSON.stringify(r,null,2),"me"),Fe=s(({functions:r,runAsIdentity:o=!1}={})=>{let a=K(),u=D(),[H,Q]=(0,i.useState)(null),[k,V]=(0,i.useState)(null),g=r??H??[],[I,S]=(0,i.useState)(""),[m,b]=(0,i.useState)("{}"),[c,F]=(0,i.useState)(""),[f,W]=(0,i.useState)(""),[v,h]=(0,i.useState)("idle"),[X,y]=(0,i.useState)(void 0),[C,N]=(0,i.useState)(null),[$,Y]=(0,i.useState)([]);(0,i.useEffect)(()=>{if(r!==void 0)return;let t=!1;return u.listFunctions().then(d=>(t||Q(d),d)).catch(d=>{t||V(B(d))}),()=>{t=!0}},[u,r]);let A=I===""?g[0]?.path??"":I,n=g.find(t=>t.path===A),Z=s(async()=>{if(!n)return;let t;try{t=m.trim()===""?{}:JSON.parse(m)}catch(l){h("error"),y(void 0),N(a("Invalid JSON args: {message}",{message:l.message}));return}let d={__lunoraRef:n.path},R=c.trim()===""?{}:{shardKey:c.trim()},j=o?f.trim():"",L=s(l=>{Y(T=>[{argsText:m,at:Date.now(),id:(T[0]?.id??0)+1,kind:n.kind,path:n.path,shardKey:c,status:l},...T].slice(0,fe))},"$");h("running"),N(null);try{let l=j===""?await _(u,n.kind,d,t,R):await u.query(me,{args:t,functionPath:n.path,userId:j},R);M(c),y(l),h("success"),L("success")}catch(l){y(void 0),N(l.message),h("error"),L("error")}},"J"),ee=s(t=>{S(t.path),b(t.argsText),F(t.shardKey)},"M"),te=s(t=>{S(t.target.value)},"P"),re=s(t=>{b(t.target.value)},"z"),ae=s(t=>{W(t.target.value)},"q"),se=s(()=>{P(Z())},"H"),ne=s(()=>{b(ue(n?.args))},"V");return(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-function-runner",children:[k!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"function-discover-error",role:"alert",children:k}),(0,e.jsxs)("div",{className:"flex flex-col gap-4 rounded-xl border border-border bg-card p-4",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,e.jsx)(x,{htmlFor:"function-select",children:a("Function")}),(0,e.jsx)("select",{"aria-label":a("Function"),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50","data-testid":"function-select",id:"function-select",onChange:te,value:A,children:g.map(t=>(0,e.jsxs)("option",{value:t.path,children:[t.path," (",t.kind,")"]},t.path))}),n!==void 0&&(0,e.jsxs)("p",{className:"text-xs text-muted-foreground",children:[(0,e.jsx)("span",{className:"mr-1.5 font-medium",children:a("Signature")}),(0,e.jsx)("code",{className:"font-mono","data-testid":"function-signature",children:le(n.args)})]})]}),(0,e.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsx)(x,{htmlFor:"args-input",children:a("Arguments")}),(0,e.jsx)(p,{"data-testid":"prefill-button",disabled:n===void 0,onClick:ne,size:"xs",type:"button",variant:"ghost",children:a("Prefill")})]}),(0,e.jsx)(G,{"aria-label":a("Arguments"),className:"font-mono text-xs","data-testid":"args-input",id:"args-input",onChange:re,value:m})]}),(0,e.jsx)(U,{onChange:F,testId:"shard-input",value:c}),o&&(0,e.jsxs)("div",{className:"flex flex-col gap-1.5","data-testid":"run-as-field",children:[(0,e.jsx)(x,{htmlFor:"run-as-input",children:a("Run as identity (userId)")}),(0,e.jsx)(O,{"aria-label":a("Run as identity (userId)"),className:"font-mono text-xs","data-testid":"run-as-input",id:"run-as-input",onChange:ae,placeholder:a("Leave empty to run as admin"),value:f}),(0,e.jsx)("p",{className:"text-[11px] text-muted-foreground",children:a("Dev only: runs the function as this user so you can test auth and RLS. Forged over the admin gate.")})]}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)(p,{"data-testid":"run-button",disabled:v==="running"||n===void 0,onClick:se,type:"button",children:a("Run")}),n!==void 0&&(0,e.jsx)(w,{variant:"outline",children:n.kind}),o&&f.trim()!==""&&(0,e.jsx)(w,{"data-testid":"run-as-badge",variant:"secondary",children:a("as {userId}",{userId:f.trim()})})]})]}),v==="error"&&C!==null&&(0,e.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs text-destructive","data-testid":"error",role:"alert",children:C}),v==="success"&&(0,e.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":"result",children:he(X)}),$.length>0&&(0,e.jsx)("ul",{className:"flex flex-col overflow-hidden rounded-xl border border-border","data-testid":"fn-history",children:$.map((t,d)=>(0,e.jsxs)("li",{className:"flex flex-wrap items-center gap-2 border-b border-border px-3 py-2 text-sm last:border-b-0","data-testid":"fn-history-row",children:[(0,e.jsx)("span",{className:t.status==="success"?"text-success":"text-destructive","data-testid":`fn-history-status-${d.toString()}`,children:t.status==="success"?"\u2713":"\u2717"})," ",(0,e.jsxs)("span",{className:"font-mono text-xs",children:[t.path," (",t.kind,")"]})," ",(0,e.jsx)("time",{className:"text-xs text-muted-foreground",children:q(t.at)})," ",(0,e.jsx)(p,{className:"ml-auto","data-testid":`fn-history-load-${d.toString()}`,onClick:s(()=>{ee(t)},"onClick"),size:"xs",type:"button",variant:"ghost",children:a("Load")})]},t.id))})]})},"Ae");export{Fe as FunctionRunner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as me}from"./chunk-SUDJTC4S.js";import{a as $}from"./chunk-YVVP4DRM.js";import{a as ue}from"./chunk-BOTGXX4H.js";import"./chunk-P5RUFDVX.js";import"./chunk-5JDWLCSH.js";import"./chunk-EVTM6Q43.js";import{a as de}from"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{b as D}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import"./chunk-35DM4JJG.js";import{a as M}from"./chunk-4ZEL6BYL.js";import{c as ce}from"./chunk-FI3UY4QJ.js";import{f as ne,g as oe}from"./chunk-PYI2MI4Q.js";import"./chunk-FSRSK4LY.js";import"./chunk-MKL7VDTL.js";import{a as A}from"./chunk-WUWBZPUK.js";import{d as T,f as j,g as Q,h as W,o as _,r as ie}from"./chunk-FODLDLE2.js";import{a as p,d as I,e as Ee,f as ae,g as le,i as E}from"./chunk-YKXDMIHQ.js";var Y=I(ae(),1);var f=I(Ee(),1);var fe=I(ae(),1);var B=I(le(),1);var Me={connected:"bg-success",connecting:"bg-warning",idle:"bg-muted-foreground",offline:"bg-destructive"},he=p(()=>{let t=(0,fe.c)(16),e=T(),a=oe(),s;e:switch(a){case"connected":{let o;t[0]!==e?(o=e("Connected"),t[0]=e,t[1]=o):o=t[1],s=o;break e}case"connecting":{let o;t[2]!==e?(o=e("Connecting\u2026"),t[2]=e,t[3]=o):o=t[3],s=o;break e}case"idle":{let o;t[4]!==e?(o=e("Idle"),t[4]=e,t[5]=o):o=t[5],s=o;break e}case"offline":{let o;t[6]!==e?(o=e("Offline"),t[6]=e,t[7]=o):o=t[7],s=o;break e}default:s=a}let l=Me[a],c;t[8]!==l?(c=E("size-2 rounded-full",l),t[8]=l,t[9]=c):c=t[9];let i;t[10]!==c?(i=(0,B.jsx)("span",{"aria-hidden":"true",className:c}),t[10]=c,t[11]=i):i=t[11];let n;return t[12]!==a||t[13]!==i||t[14]!==s?(n=(0,B.jsxs)("span",{"aria-live":"polite",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground","data-status":a,"data-testid":"dash-connection",role:"status",children:[i,s]}),t[12]=a,t[13]=i,t[14]=s,t[15]=n):n=t[15],n},"T");var r=I(le(),1);var Ae={crit:"destructive",ok:"secondary",warn:"default"},U=p((t,e)=>e===0?"\u2014":`${(t/e*100).toFixed(1)}%`,"P"),X=p((t,e,a)=>Number.isNaN(t)?"ok":t>=a?"crit":t>=e?"warn":"ok","Q"),xe=.01,ve=.05,je=p(t=>{let e=(0,Y.c)(36),{errorCount:a,logsError:s,topErrors:l,worstFunctions:c}=t,i=T(),n;e[0]!==i?(n=i("Functions by error rate"),e[0]=i,e[1]=n):n=e[1];let o;e[2]!==n?(o=(0,r.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:n})}),e[2]=n,e[3]=o):o=e[3];let h;e[4]!==i||e[5]!==c?(h=c.length===0?(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-functions-empty",children:i("No function activity yet.")}):(0,r.jsx)("ul",{className:"divide-y divide-border",children:c.map(w=>(0,r.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2 text-xs","data-testid":"hl-fn-row",children:[(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:w.path}),(0,r.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,r.jsx)("span",{className:"tabular-nums text-muted-foreground",children:i("{count} calls",{count:w.calls.toString()})}),(0,r.jsx)(D,{variant:Ae[X(w.errors/w.calls,xe,ve)],children:U(w.errors,w.calls)})]})]},w.path))}),e[4]=i,e[5]=c,e[6]=h):h=e[6];let g;e[7]!==o||e[8]!==h?(g=(0,r.jsxs)(A,{className:"gap-0 py-0","data-testid":"hl-functions",children:[o,h]}),e[7]=o,e[8]=h,e[9]=g):g=e[9];let b;e[10]!==i?(b=i("Recent errors"),e[10]=i,e[11]=b):b=e[11];let d;e[12]!==b?(d=(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:b}),e[12]=b,e[13]=d):d=e[13];let u=a>0?"destructive":"outline",x;e[14]!==a||e[15]!==u?(x=(0,r.jsx)(D,{"data-testid":"hl-error-count",variant:u,children:a}),e[14]=a,e[15]=u,e[16]=x):x=e[16];let v;e[17]!==d||e[18]!==x?(v=(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[d,x]}),e[17]=d,e[18]=x,e[19]=v):v=e[19];let k;e[20]!==s?(k=s!==null&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"hl-logs-error",role:"alert",children:s}),e[20]=s,e[21]=k):k=e[21];let S;e[22]!==s||e[23]!==i||e[24]!==l.length?(S=s===null&&l.length===0&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-errors-empty",children:i("No recent errors.")}),e[22]=s,e[23]=i,e[24]=l.length,e[25]=S):S=e[25];let q;e[26]!==l?(q=l.length>0&&(0,r.jsx)("ul",{className:"divide-y divide-border",children:l.map(Ce)}),e[26]=l,e[27]=q):q=e[27];let N;e[28]!==k||e[29]!==S||e[30]!==q||e[31]!==v?(N=(0,r.jsxs)(A,{className:"gap-0 py-0",children:[v,k,S,q]}),e[28]=k,e[29]=S,e[30]=q,e[31]=v,e[32]=N):N=e[32];let y;return e[33]!==N||e[34]!==g?(y=(0,r.jsxs)("div",{className:"grid gap-3 lg:grid-cols-2",children:[g,N]}),e[33]=N,e[34]=g,e[35]=y):y=e[35],y},"ye");function Ce(t,e){return(0,r.jsxs)("li",{className:"flex flex-col gap-0.5 px-4 py-2 text-xs","data-testid":"hl-error-row",children:[(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("time",{className:"shrink-0 text-muted-foreground",children:ie(t.timestamp)}),t.functionPath!==void 0&&(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:t.functionPath})]}),(0,r.jsx)("span",{className:"text-destructive",children:t.message})]},`${t.timestamp.toString()}-${e.toString()}`)}p(Ce,"Te");var pe={completed:0,failed:2,in_progress:1},Ie=p(t=>{let e=0,a=0,s=0,l=0,c=!1,i=[];for(let{metrics:n}of t){if(n===null){l+=1;continue}s+=1,e+=n.requests,a+=n.errors,i.push(...n.history??[]),c||=n.historyTruncated===!0}return{errors:a,failed:l,history:i,historyTruncated:c,reachable:s,requests:e}},"Ae"),Te=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.path);if(l===void 0){e.set(s.path,{...s});continue}l.calls+=s.calls,l.errors+=s.errors,l.totalDurationMs+=s.totalDurationMs,l.scans=(l.scans??0)+(s.scans??0),l.maxDurationMs=Math.max(l.maxDurationMs,s.maxDurationMs),l.lastCalledAt=Math.max(l.lastCalledAt,s.lastCalledAt),(s.lastErrorAt??0)>(l.lastErrorAt??0)&&(l.lastErrorAt=s.lastErrorAt,l.lastErrorMessage=s.lastErrorMessage)}return[...e.values()]},"ke"),De=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.id);if(l===void 0){e.set(s.id,s);continue}let c=pe[s.status]-pe[l.status];(c>0||c===0&&(s.updatedAt??0)>(l.updatedAt??0))&&e.set(s.id,s)}return[...e.values()]},"Re"),Pe=j(M.getAuthMetrics),Fe=j(M.getFunctionStats),Le=j(M.getLogs),Re=j(M.getMetrics),ze=j(M.migrationStatus),Oe=5,ge=2e3,_e=5,$e=.1,Be=.3,He=1,Ue=50,Ge=p((t,e,a)=>t>=a?"crit":t>=e?"warn":"ok","Pe"),Ke=p(t=>{let e=new Map;for(let s of t??[]){let l=e.get(s.bucketMs)??{calls:0,errors:0};l.calls+=s.calls,l.errors+=s.errors,e.set(s.bucketMs,l)}let a=[...e.entries()].toSorted((s,l)=>s[0]-l[0]);return{errors:a.map(([,s])=>s.errors),requests:a.map(([,s])=>s.calls)}},"Ge"),Ve=p(t=>{let e=0,a=0;for(let l of t)l.status==="failed"?e+=1:l.status==="in_progress"&&(a+=1);let s="ok";return e>0?s="crit":a>0&&(s="warn"),{failed:e,level:s,running:a}},"Ve"),Je=p((t,e)=>t.failed>0?e("{count} failed",{count:t.failed.toString()}):t.running>0?e("{count} running",{count:t.running.toString()}):e("OK"),"Be"),be={crit:"bg-destructive",ok:"bg-success",warn:"bg-warning"},Ne={crit:"text-destructive",ok:"text-foreground",warn:"text-warning"},Qe={crit:"bg-destructive/10 text-destructive",ok:"bg-success/10 text-success",warn:"bg-warning/10 text-warning"},We=p(t=>t.includes("crit")?"crit":t.includes("warn")?"warn":"ok","Ke"),H=p(t=>{let e=(0,Y.c)(19),{chart:a,label:s,level:l,testId:c,value:i}=t,n=be[l],o;e[0]!==n?(o=E("size-1.5 shrink-0 rounded-full",n),e[0]=n,e[1]=o):o=e[1];let h;e[2]!==o?(h=(0,r.jsx)("span",{"aria-hidden":"true",className:o}),e[2]=o,e[3]=h):h=e[3];let g;e[4]!==s||e[5]!==h?(g=(0,r.jsxs)("span",{className:"flex items-center gap-1.5 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:[h,s]}),e[4]=s,e[5]=h,e[6]=g):g=e[6];let b=Ne[l],d;e[7]!==b?(d=E("truncate text-2xl font-semibold tabular-nums",b),e[7]=b,e[8]=d):d=e[8];let u;e[9]!==d||e[10]!==c||e[11]!==i?(u=(0,r.jsx)("span",{className:d,"data-testid":c,children:i}),e[9]=d,e[10]=c,e[11]=i,e[12]=u):u=e[12];let x;e[13]!==a||e[14]!==u?(x=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[u,a]}),e[13]=a,e[14]=u,e[15]=x):x=e[15];let v;return e[16]!==g||e[17]!==x?(v=(0,r.jsx)(A,{className:"gap-0 py-0",children:(0,r.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[g,x]})}),e[16]=g,e[17]=x,e[18]=v):v=e[18],v},"U"),Xe=p(async(t,e,a)=>{let s=await Promise.all(a.map(d=>{let u=Q(d);return Promise.allSettled([t.query(Re,{},u),t.query(Fe,{},u),t.query(ze,{},u)])})),l=Q(e),c=typeof t.schedulerStatus=="function"?t.schedulerStatus():Promise.reject(new Error("scheduler status unavailable")),[i,n,o]=await Promise.allSettled([t.query(Le,{},l),t.query(Pe,{},l),c]),h=s.map(([d,u,x])=>({functions:u.status==="fulfilled"?u.value.functions:[],metrics:d.status==="fulfilled"?d.value:null,migrations:x.status==="fulfilled"?x.value.migrations:[]})),g=Ie(h),b=s[0]?.[0];return{auth:n.status==="fulfilled"?n.value:null,entries:i.status==="fulfilled"?i.value.entries:[],functions:Te(h.map(d=>d.functions)),logsError:i.status==="rejected"?W(i.reason):null,metricsError:g.reachable===0&&b?.status==="rejected"?W(b.reason):null,migrations:De(h.map(d=>d.migrations)),scheduler:o.status==="fulfilled"?o.value:null,totals:g}},"$e"),Ye=p(t=>{let e=t?.history??[];return{attempts:e.map(a=>a.attempts),failures:e.map(a=>a.failures)}},"ze"),xt=p(({initialShardKey:t})=>{let e=ne(),a=T(),[s,l]=(0,f.useState)([]),[c,i]=(0,f.useState)(null),[n,o]=(0,f.useState)(null),[h,g]=(0,f.useState)(null),[b,d]=(0,f.useState)([]),[u,x]=(0,f.useState)(null),[v,k]=(0,f.useState)(null),[S,q]=(0,f.useState)([]),[N]=(0,f.useState)(de),y=(0,f.useRef)(!1),w=(0,f.useRef)(!0);(0,f.useEffect)(()=>(w.current=!0,()=>{w.current=!1}),[]);let P=t??"",F=(0,f.useCallback)(async()=>{if(y.current)return;y.current=!0;let m=await Xe(e,P,me(P,N));if(!w.current){y.current=!1;return}o(m.totals),g(m.metricsError),d(m.functions),q(m.migrations),l(m.entries),i(m.logsError),x(m.auth),k(m.scheduler),y.current=!1},[e,N,P]);(0,f.useEffect)(()=>{_(F())},[F]);let G=(0,f.useRef)(0),C=(0,f.useRef)(null),we=p(()=>{let m=Date.now()-G.current;if(m>=ge){G.current=Date.now(),_(F());return}C.current===null&&(C.current=setTimeout(()=>{C.current=null,G.current=Date.now(),_(F())},ge-m))},"ue");(0,f.useEffect)(()=>()=>{C.current!==null&&clearTimeout(C.current)},[]);let{data:Z,liveError:ye}=ce(M.getMetrics,{},{live:!0,shardKey:P});(0,f.useEffect)(()=>{Z!==void 0&&we()},[Z]);let ee=s.filter(m=>m.level==="error"),ke=ee.slice(0,Oe),L=Ke(n?.history),te=Ye(u),Se=b.filter(m=>m.calls>0).toSorted((m,J)=>J.errors/J.calls-m.errors/m.calls||J.calls-m.calls).slice(0,_e),K=Ve(S),qe=n===null||n.requests===0?0:n.errors/n.requests,V=X(qe,xe,ve),re=u===null?"ok":X(u.failureRate,$e,Be),se=v===null?"ok":Ge(v.backlog,He,Ue),R=We([V,re,se,K.level]),z,O;return R==="crit"?(z=a("Critical"),O=a("One or more service levels are breached.")):R==="warn"?(z=a("Degraded"),O=a("Some service levels need attention.")):(z=a("All systems healthy"),O=a("All service levels are within target.")),(0,r.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-health",children:[(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:E("flex size-10 shrink-0 items-center justify-center rounded-full",Qe[R]),children:(0,r.jsx)("span",{className:E("size-3 rounded-full",be[R])})}),(0,r.jsxs)("div",{className:"grid leading-tight",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground","data-testid":"hl-status",children:z}),(0,r.jsx)("span",{className:"text-[13px] text-muted-foreground",children:O})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Requests")}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[L.requests.length>=2&&(0,r.jsx)($,{ariaLabel:a("Requests over time"),className:"h-6 w-20 text-foreground",series:L.requests,testId:"hl-spark-requests"}),(0,r.jsx)("span",{className:"text-lg font-semibold tabular-nums text-foreground","data-testid":"hl-requests",children:(n?.requests??0).toString()})]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Error rate")}),(0,r.jsx)("div",{className:E("text-lg font-semibold tabular-nums",Ne[V]),"data-testid":"hl-error-rate",children:n===null?"\u2014":U(n.errors,n.requests)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(he,{}),(0,r.jsx)(ue,{message:ye,prefix:"hl"})]})]})]}),h!==null&&(0,r.jsx)("div",{className:"border-t border-border bg-destructive/5 px-4 py-2 text-sm text-destructive","data-testid":"hl-metrics-error",role:"alert",children:h}),h===null&&n?.historyTruncated===!0&&(0,r.jsx)("div",{className:"border-t border-border bg-warning/5 px-4 py-2 text-sm text-muted-foreground","data-testid":"hl-history-truncated",children:a("Showing a partial request/error history \u2014 one or more shards have more data than the trend chart can display.")})]}),(0,r.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-testid":"hl-slo",children:[(0,r.jsx)(H,{chart:L.errors.length>=2?(0,r.jsx)($,{ariaLabel:a("Errors over time"),className:"h-7 w-20 text-destructive",series:L.errors,testId:"hl-spark-errors"}):void 0,label:a("Error rate"),level:V,testId:"hl-slo-errorrate",value:n===null?"\u2014":U(n.errors,n.requests)}),(0,r.jsx)(H,{chart:te.failures.length>=2?(0,r.jsx)($,{ariaLabel:a("Auth failures over time"),className:"h-7 w-20 text-destructive",series:te.failures,testId:"hl-spark-auth"}):void 0,label:a("Auth failures"),level:re,testId:"hl-slo-auth",value:u===null?"\u2014":U(u.failures,u.attempts)}),(0,r.jsx)(H,{label:a("Scheduler backlog"),level:se,testId:"hl-slo-backlog",value:v===null?"\u2014":v.backlog.toString()}),(0,r.jsx)(H,{label:a("Migrations"),level:K.level,testId:"hl-slo-migrations",value:Je(K,a)})]}),(0,r.jsx)(je,{errorCount:ee.length,logsError:c,topErrors:ke,worstFunctions:Se}),(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:a("Shards seen")}),(0,r.jsx)(D,{"data-testid":"hl-shard-count",variant:"outline",children:N.length})]}),N.length>0&&(0,r.jsx)("ul",{className:"flex flex-wrap gap-1.5 p-4",children:N.map(m=>(0,r.jsx)("li",{"data-testid":"hl-shard",children:(0,r.jsx)(D,{variant:"secondary",children:m})},m))})]})]})},"ut");export{xt as HealthPanel};
|
|
1
|
+
import{b as me}from"./chunk-SUDJTC4S.js";import{a as $}from"./chunk-YVVP4DRM.js";import{a as ue}from"./chunk-BOTGXX4H.js";import"./chunk-P5RUFDVX.js";import"./chunk-5JDWLCSH.js";import"./chunk-EVTM6Q43.js";import{a as de}from"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{b as D}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import"./chunk-35DM4JJG.js";import{a as M}from"./chunk-4ZEL6BYL.js";import{c as ce}from"./chunk-KMRCIOIP.js";import{f as ne,g as oe}from"./chunk-E7V5U2MI.js";import"./chunk-FSRSK4LY.js";import"./chunk-MKL7VDTL.js";import{a as A}from"./chunk-WUWBZPUK.js";import{d as T,f as j,g as Q,h as W,o as _,r as ie}from"./chunk-FODLDLE2.js";import{a as p,d as I,e as Ee,f as ae,g as le,i as E}from"./chunk-YKXDMIHQ.js";var Y=I(ae(),1);var f=I(Ee(),1);var fe=I(ae(),1);var B=I(le(),1);var Me={connected:"bg-success",connecting:"bg-warning",idle:"bg-muted-foreground",offline:"bg-destructive"},he=p(()=>{let t=(0,fe.c)(16),e=T(),a=oe(),s;e:switch(a){case"connected":{let o;t[0]!==e?(o=e("Connected"),t[0]=e,t[1]=o):o=t[1],s=o;break e}case"connecting":{let o;t[2]!==e?(o=e("Connecting\u2026"),t[2]=e,t[3]=o):o=t[3],s=o;break e}case"idle":{let o;t[4]!==e?(o=e("Idle"),t[4]=e,t[5]=o):o=t[5],s=o;break e}case"offline":{let o;t[6]!==e?(o=e("Offline"),t[6]=e,t[7]=o):o=t[7],s=o;break e}default:s=a}let l=Me[a],c;t[8]!==l?(c=E("size-2 rounded-full",l),t[8]=l,t[9]=c):c=t[9];let i;t[10]!==c?(i=(0,B.jsx)("span",{"aria-hidden":"true",className:c}),t[10]=c,t[11]=i):i=t[11];let n;return t[12]!==a||t[13]!==i||t[14]!==s?(n=(0,B.jsxs)("span",{"aria-live":"polite",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground","data-status":a,"data-testid":"dash-connection",role:"status",children:[i,s]}),t[12]=a,t[13]=i,t[14]=s,t[15]=n):n=t[15],n},"T");var r=I(le(),1);var Ae={crit:"destructive",ok:"secondary",warn:"default"},U=p((t,e)=>e===0?"\u2014":`${(t/e*100).toFixed(1)}%`,"P"),X=p((t,e,a)=>Number.isNaN(t)?"ok":t>=a?"crit":t>=e?"warn":"ok","Q"),xe=.01,ve=.05,je=p(t=>{let e=(0,Y.c)(36),{errorCount:a,logsError:s,topErrors:l,worstFunctions:c}=t,i=T(),n;e[0]!==i?(n=i("Functions by error rate"),e[0]=i,e[1]=n):n=e[1];let o;e[2]!==n?(o=(0,r.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:n})}),e[2]=n,e[3]=o):o=e[3];let h;e[4]!==i||e[5]!==c?(h=c.length===0?(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-functions-empty",children:i("No function activity yet.")}):(0,r.jsx)("ul",{className:"divide-y divide-border",children:c.map(w=>(0,r.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2 text-xs","data-testid":"hl-fn-row",children:[(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:w.path}),(0,r.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,r.jsx)("span",{className:"tabular-nums text-muted-foreground",children:i("{count} calls",{count:w.calls.toString()})}),(0,r.jsx)(D,{variant:Ae[X(w.errors/w.calls,xe,ve)],children:U(w.errors,w.calls)})]})]},w.path))}),e[4]=i,e[5]=c,e[6]=h):h=e[6];let g;e[7]!==o||e[8]!==h?(g=(0,r.jsxs)(A,{className:"gap-0 py-0","data-testid":"hl-functions",children:[o,h]}),e[7]=o,e[8]=h,e[9]=g):g=e[9];let b;e[10]!==i?(b=i("Recent errors"),e[10]=i,e[11]=b):b=e[11];let d;e[12]!==b?(d=(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:b}),e[12]=b,e[13]=d):d=e[13];let u=a>0?"destructive":"outline",x;e[14]!==a||e[15]!==u?(x=(0,r.jsx)(D,{"data-testid":"hl-error-count",variant:u,children:a}),e[14]=a,e[15]=u,e[16]=x):x=e[16];let v;e[17]!==d||e[18]!==x?(v=(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[d,x]}),e[17]=d,e[18]=x,e[19]=v):v=e[19];let k;e[20]!==s?(k=s!==null&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"hl-logs-error",role:"alert",children:s}),e[20]=s,e[21]=k):k=e[21];let S;e[22]!==s||e[23]!==i||e[24]!==l.length?(S=s===null&&l.length===0&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-errors-empty",children:i("No recent errors.")}),e[22]=s,e[23]=i,e[24]=l.length,e[25]=S):S=e[25];let q;e[26]!==l?(q=l.length>0&&(0,r.jsx)("ul",{className:"divide-y divide-border",children:l.map(Ce)}),e[26]=l,e[27]=q):q=e[27];let N;e[28]!==k||e[29]!==S||e[30]!==q||e[31]!==v?(N=(0,r.jsxs)(A,{className:"gap-0 py-0",children:[v,k,S,q]}),e[28]=k,e[29]=S,e[30]=q,e[31]=v,e[32]=N):N=e[32];let y;return e[33]!==N||e[34]!==g?(y=(0,r.jsxs)("div",{className:"grid gap-3 lg:grid-cols-2",children:[g,N]}),e[33]=N,e[34]=g,e[35]=y):y=e[35],y},"ye");function Ce(t,e){return(0,r.jsxs)("li",{className:"flex flex-col gap-0.5 px-4 py-2 text-xs","data-testid":"hl-error-row",children:[(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("time",{className:"shrink-0 text-muted-foreground",children:ie(t.timestamp)}),t.functionPath!==void 0&&(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:t.functionPath})]}),(0,r.jsx)("span",{className:"text-destructive",children:t.message})]},`${t.timestamp.toString()}-${e.toString()}`)}p(Ce,"Te");var pe={completed:0,failed:2,in_progress:1},Ie=p(t=>{let e=0,a=0,s=0,l=0,c=!1,i=[];for(let{metrics:n}of t){if(n===null){l+=1;continue}s+=1,e+=n.requests,a+=n.errors,i.push(...n.history??[]),c||=n.historyTruncated===!0}return{errors:a,failed:l,history:i,historyTruncated:c,reachable:s,requests:e}},"Ae"),Te=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.path);if(l===void 0){e.set(s.path,{...s});continue}l.calls+=s.calls,l.errors+=s.errors,l.totalDurationMs+=s.totalDurationMs,l.scans=(l.scans??0)+(s.scans??0),l.maxDurationMs=Math.max(l.maxDurationMs,s.maxDurationMs),l.lastCalledAt=Math.max(l.lastCalledAt,s.lastCalledAt),(s.lastErrorAt??0)>(l.lastErrorAt??0)&&(l.lastErrorAt=s.lastErrorAt,l.lastErrorMessage=s.lastErrorMessage)}return[...e.values()]},"ke"),De=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.id);if(l===void 0){e.set(s.id,s);continue}let c=pe[s.status]-pe[l.status];(c>0||c===0&&(s.updatedAt??0)>(l.updatedAt??0))&&e.set(s.id,s)}return[...e.values()]},"Re"),Pe=j(M.getAuthMetrics),Fe=j(M.getFunctionStats),Le=j(M.getLogs),Re=j(M.getMetrics),ze=j(M.migrationStatus),Oe=5,ge=2e3,_e=5,$e=.1,Be=.3,He=1,Ue=50,Ge=p((t,e,a)=>t>=a?"crit":t>=e?"warn":"ok","Pe"),Ke=p(t=>{let e=new Map;for(let s of t??[]){let l=e.get(s.bucketMs)??{calls:0,errors:0};l.calls+=s.calls,l.errors+=s.errors,e.set(s.bucketMs,l)}let a=[...e.entries()].toSorted((s,l)=>s[0]-l[0]);return{errors:a.map(([,s])=>s.errors),requests:a.map(([,s])=>s.calls)}},"Ge"),Ve=p(t=>{let e=0,a=0;for(let l of t)l.status==="failed"?e+=1:l.status==="in_progress"&&(a+=1);let s="ok";return e>0?s="crit":a>0&&(s="warn"),{failed:e,level:s,running:a}},"Ve"),Je=p((t,e)=>t.failed>0?e("{count} failed",{count:t.failed.toString()}):t.running>0?e("{count} running",{count:t.running.toString()}):e("OK"),"Be"),be={crit:"bg-destructive",ok:"bg-success",warn:"bg-warning"},Ne={crit:"text-destructive",ok:"text-foreground",warn:"text-warning"},Qe={crit:"bg-destructive/10 text-destructive",ok:"bg-success/10 text-success",warn:"bg-warning/10 text-warning"},We=p(t=>t.includes("crit")?"crit":t.includes("warn")?"warn":"ok","Ke"),H=p(t=>{let e=(0,Y.c)(19),{chart:a,label:s,level:l,testId:c,value:i}=t,n=be[l],o;e[0]!==n?(o=E("size-1.5 shrink-0 rounded-full",n),e[0]=n,e[1]=o):o=e[1];let h;e[2]!==o?(h=(0,r.jsx)("span",{"aria-hidden":"true",className:o}),e[2]=o,e[3]=h):h=e[3];let g;e[4]!==s||e[5]!==h?(g=(0,r.jsxs)("span",{className:"flex items-center gap-1.5 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:[h,s]}),e[4]=s,e[5]=h,e[6]=g):g=e[6];let b=Ne[l],d;e[7]!==b?(d=E("truncate text-2xl font-semibold tabular-nums",b),e[7]=b,e[8]=d):d=e[8];let u;e[9]!==d||e[10]!==c||e[11]!==i?(u=(0,r.jsx)("span",{className:d,"data-testid":c,children:i}),e[9]=d,e[10]=c,e[11]=i,e[12]=u):u=e[12];let x;e[13]!==a||e[14]!==u?(x=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[u,a]}),e[13]=a,e[14]=u,e[15]=x):x=e[15];let v;return e[16]!==g||e[17]!==x?(v=(0,r.jsx)(A,{className:"gap-0 py-0",children:(0,r.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[g,x]})}),e[16]=g,e[17]=x,e[18]=v):v=e[18],v},"U"),Xe=p(async(t,e,a)=>{let s=await Promise.all(a.map(d=>{let u=Q(d);return Promise.allSettled([t.query(Re,{},u),t.query(Fe,{},u),t.query(ze,{},u)])})),l=Q(e),c=typeof t.schedulerStatus=="function"?t.schedulerStatus():Promise.reject(new Error("scheduler status unavailable")),[i,n,o]=await Promise.allSettled([t.query(Le,{},l),t.query(Pe,{},l),c]),h=s.map(([d,u,x])=>({functions:u.status==="fulfilled"?u.value.functions:[],metrics:d.status==="fulfilled"?d.value:null,migrations:x.status==="fulfilled"?x.value.migrations:[]})),g=Ie(h),b=s[0]?.[0];return{auth:n.status==="fulfilled"?n.value:null,entries:i.status==="fulfilled"?i.value.entries:[],functions:Te(h.map(d=>d.functions)),logsError:i.status==="rejected"?W(i.reason):null,metricsError:g.reachable===0&&b?.status==="rejected"?W(b.reason):null,migrations:De(h.map(d=>d.migrations)),scheduler:o.status==="fulfilled"?o.value:null,totals:g}},"$e"),Ye=p(t=>{let e=t?.history??[];return{attempts:e.map(a=>a.attempts),failures:e.map(a=>a.failures)}},"ze"),xt=p(({initialShardKey:t})=>{let e=ne(),a=T(),[s,l]=(0,f.useState)([]),[c,i]=(0,f.useState)(null),[n,o]=(0,f.useState)(null),[h,g]=(0,f.useState)(null),[b,d]=(0,f.useState)([]),[u,x]=(0,f.useState)(null),[v,k]=(0,f.useState)(null),[S,q]=(0,f.useState)([]),[N]=(0,f.useState)(de),y=(0,f.useRef)(!1),w=(0,f.useRef)(!0);(0,f.useEffect)(()=>(w.current=!0,()=>{w.current=!1}),[]);let P=t??"",F=(0,f.useCallback)(async()=>{if(y.current)return;y.current=!0;let m=await Xe(e,P,me(P,N));if(!w.current){y.current=!1;return}o(m.totals),g(m.metricsError),d(m.functions),q(m.migrations),l(m.entries),i(m.logsError),x(m.auth),k(m.scheduler),y.current=!1},[e,N,P]);(0,f.useEffect)(()=>{_(F())},[F]);let G=(0,f.useRef)(0),C=(0,f.useRef)(null),we=p(()=>{let m=Date.now()-G.current;if(m>=ge){G.current=Date.now(),_(F());return}C.current===null&&(C.current=setTimeout(()=>{C.current=null,G.current=Date.now(),_(F())},ge-m))},"ue");(0,f.useEffect)(()=>()=>{C.current!==null&&clearTimeout(C.current)},[]);let{data:Z,liveError:ye}=ce(M.getMetrics,{},{live:!0,shardKey:P});(0,f.useEffect)(()=>{Z!==void 0&&we()},[Z]);let ee=s.filter(m=>m.level==="error"),ke=ee.slice(0,Oe),L=Ke(n?.history),te=Ye(u),Se=b.filter(m=>m.calls>0).toSorted((m,J)=>J.errors/J.calls-m.errors/m.calls||J.calls-m.calls).slice(0,_e),K=Ve(S),qe=n===null||n.requests===0?0:n.errors/n.requests,V=X(qe,xe,ve),re=u===null?"ok":X(u.failureRate,$e,Be),se=v===null?"ok":Ge(v.backlog,He,Ue),R=We([V,re,se,K.level]),z,O;return R==="crit"?(z=a("Critical"),O=a("One or more service levels are breached.")):R==="warn"?(z=a("Degraded"),O=a("Some service levels need attention.")):(z=a("All systems healthy"),O=a("All service levels are within target.")),(0,r.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-health",children:[(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:E("flex size-10 shrink-0 items-center justify-center rounded-full",Qe[R]),children:(0,r.jsx)("span",{className:E("size-3 rounded-full",be[R])})}),(0,r.jsxs)("div",{className:"grid leading-tight",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground","data-testid":"hl-status",children:z}),(0,r.jsx)("span",{className:"text-[13px] text-muted-foreground",children:O})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Requests")}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[L.requests.length>=2&&(0,r.jsx)($,{ariaLabel:a("Requests over time"),className:"h-6 w-20 text-foreground",series:L.requests,testId:"hl-spark-requests"}),(0,r.jsx)("span",{className:"text-lg font-semibold tabular-nums text-foreground","data-testid":"hl-requests",children:(n?.requests??0).toString()})]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Error rate")}),(0,r.jsx)("div",{className:E("text-lg font-semibold tabular-nums",Ne[V]),"data-testid":"hl-error-rate",children:n===null?"\u2014":U(n.errors,n.requests)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(he,{}),(0,r.jsx)(ue,{message:ye,prefix:"hl"})]})]})]}),h!==null&&(0,r.jsx)("div",{className:"border-t border-border bg-destructive/5 px-4 py-2 text-sm text-destructive","data-testid":"hl-metrics-error",role:"alert",children:h}),h===null&&n?.historyTruncated===!0&&(0,r.jsx)("div",{className:"border-t border-border bg-warning/5 px-4 py-2 text-sm text-muted-foreground","data-testid":"hl-history-truncated",children:a("Showing a partial request/error history \u2014 one or more shards have more data than the trend chart can display.")})]}),(0,r.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-testid":"hl-slo",children:[(0,r.jsx)(H,{chart:L.errors.length>=2?(0,r.jsx)($,{ariaLabel:a("Errors over time"),className:"h-7 w-20 text-destructive",series:L.errors,testId:"hl-spark-errors"}):void 0,label:a("Error rate"),level:V,testId:"hl-slo-errorrate",value:n===null?"\u2014":U(n.errors,n.requests)}),(0,r.jsx)(H,{chart:te.failures.length>=2?(0,r.jsx)($,{ariaLabel:a("Auth failures over time"),className:"h-7 w-20 text-destructive",series:te.failures,testId:"hl-spark-auth"}):void 0,label:a("Auth failures"),level:re,testId:"hl-slo-auth",value:u===null?"\u2014":U(u.failures,u.attempts)}),(0,r.jsx)(H,{label:a("Scheduler backlog"),level:se,testId:"hl-slo-backlog",value:v===null?"\u2014":v.backlog.toString()}),(0,r.jsx)(H,{label:a("Migrations"),level:K.level,testId:"hl-slo-migrations",value:Je(K,a)})]}),(0,r.jsx)(je,{errorCount:ee.length,logsError:c,topErrors:ke,worstFunctions:Se}),(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:a("Shards seen")}),(0,r.jsx)(D,{"data-testid":"hl-shard-count",variant:"outline",children:N.length})]}),N.length>0&&(0,r.jsx)("ul",{className:"flex flex-wrap gap-1.5 p-4",children:N.map(m=>(0,r.jsx)("li",{"data-testid":"hl-shard",children:(0,r.jsx)(D,{variant:"secondary",children:m})},m))})]})]})},"ut");export{xt as HealthPanel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as v}from"./chunk-F7UC63UN.js";import{a as Q}from"./chunk-66UGPQVC.js";import{a as L}from"./chunk-S3CRZLGS.js";import{a as G}from"./chunk-2DX5MROH.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import"./chunk-AAVLPU5Q.js";import{b as $}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as W}from"./chunk-
|
|
1
|
+
import{a as v}from"./chunk-F7UC63UN.js";import{a as Q}from"./chunk-66UGPQVC.js";import{a as L}from"./chunk-S3CRZLGS.js";import{a as G}from"./chunk-2DX5MROH.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import"./chunk-AAVLPU5Q.js";import{b as $}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as W}from"./chunk-MV2ZTAZK.js";import"./chunk-ULIQFBZU.js";import"./chunk-LTG5WFNX.js";import"./chunk-35DM4JJG.js";import{a as E}from"./chunk-4ZEL6BYL.js";import{c as B}from"./chunk-KMRCIOIP.js";import"./chunk-E7V5U2MI.js";import"./chunk-FSRSK4LY.js";import"./chunk-MKL7VDTL.js";import{a as A}from"./chunk-FKVZRPV5.js";import{a as q,b as H,c as O,d as K,e as T,f as D}from"./chunk-HEAQVSNS.js";import{a as _}from"./chunk-WUWBZPUK.js";import{d as j}from"./chunk-FODLDLE2.js";import{a as S,d as F,f as J,g as V}from"./chunk-YKXDMIHQ.js";var R=F(J(),1);var t=F(V(),1);var U=S(c=>`${c.toString()} ms`,"D"),X=S(c=>c.totalConnections===0&&c.shapePoke.passes===0&&c.whisper.passes===0&&c.shapeProbe.run===0&&c.shapeProbe.served===0&&c.globalPoll.drains===0&&c.globalPoll.pairsSkipped===0,"J"),z=S(c=>{let e=(0,R.c)(48),{counters:o,includeTiming:a,prefix:r,t:l,title:u}=c,d=`${r}-section`,n;e[0]!==u?(n=(0,t.jsx)("h3",{className:"text-sm font-medium text-foreground",children:u}),e[0]=u,e[1]=n):n=e[1];let s=`${r}-stats`,i;e[2]!==l?(i=l("Passes"),e[2]=l,e[3]=i):i=e[3];let m=`${r}-passes`,I;e[4]!==o.passes||e[5]!==i||e[6]!==m?(I=(0,t.jsx)(v,{label:i,testId:m,value:o.passes}),e[4]=o.passes,e[5]=i,e[6]=m,e[7]=I):I=e[7];let g;e[8]!==l?(g=l("Sockets iterated"),e[8]=l,e[9]=g):g=e[9];let k=`${r}-iterated`,p;e[10]!==o.socketsIterated||e[11]!==g||e[12]!==k?(p=(0,t.jsx)(v,{label:g,testId:k,value:o.socketsIterated}),e[10]=o.socketsIterated,e[11]=g,e[12]=k,e[13]=p):p=e[13];let f;e[14]!==l?(f=l("Delivered"),e[14]=l,e[15]=f):f=e[15];let y=`${r}-delivered`,h;e[16]!==o.socketsDelivered||e[17]!==f||e[18]!==y?(h=(0,t.jsx)(v,{label:f,testId:y,value:o.socketsDelivered}),e[16]=o.socketsDelivered,e[17]=f,e[18]=y,e[19]=h):h=e[19];let x;e[20]!==l?(x=l("Peak width"),e[20]=l,e[21]=x):x=e[21];let N=`${r}-peak`,b;e[22]!==o.peakSocketsIterated||e[23]!==x||e[24]!==N?(b=(0,t.jsx)(v,{label:x,testId:N,value:o.peakSocketsIterated}),e[22]=o.peakSocketsIterated,e[23]=x,e[24]=N,e[25]=b):b=e[25];let C;e[26]!==o.totalMs||e[27]!==a||e[28]!==r||e[29]!==l?(C=a&&(0,t.jsx)(v,{label:l("Total time"),testId:`${r}-total-ms`,value:U(o.totalMs)}),e[26]=o.totalMs,e[27]=a,e[28]=r,e[29]=l,e[30]=C):C=e[30];let P;e[31]!==o.maxMs||e[32]!==a||e[33]!==r||e[34]!==l?(P=a&&(0,t.jsx)(v,{label:l("Max time"),testId:`${r}-max-ms`,value:U(o.maxMs)}),e[31]=o.maxMs,e[32]=a,e[33]=r,e[34]=l,e[35]=P):P=e[35];let M;e[36]!==h||e[37]!==b||e[38]!==C||e[39]!==P||e[40]!==s||e[41]!==I||e[42]!==p?(M=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3","data-testid":s,children:[I,p,h,b,C,P]}),e[36]=h,e[37]=b,e[38]=C,e[39]=P,e[40]=s,e[41]=I,e[42]=p,e[43]=M):M=e[43];let w;return e[44]!==d||e[45]!==M||e[46]!==n?(w=(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":d,children:[n,M]}),e[44]=d,e[45]=M,e[46]=n,e[47]=w):w=e[47],w},"F"),Y=S(c=>{let e=(0,R.c)(20),{counters:o,t:a}=c,r;e[0]!==a?(r=a("Membership probes"),e[0]=a,e[1]=r):r=e[1];let l;e[2]!==r?(l=(0,t.jsx)("h3",{className:"text-sm font-medium text-foreground",children:r}),e[2]=r,e[3]=l):l=e[3];let u;e[4]!==a?(u=a("Queries run"),e[4]=a,e[5]=u):u=e[5];let d;e[6]!==o.run||e[7]!==u?(d=(0,t.jsx)(v,{label:u,testId:"fanout-probe-run",value:o.run}),e[6]=o.run,e[7]=u,e[8]=d):d=e[8];let n;e[9]!==a?(n=a("Shared from cache"),e[9]=a,e[10]=n):n=e[10];let s;e[11]!==o.served||e[12]!==n?(s=(0,t.jsx)(v,{label:n,testId:"fanout-probe-served",value:o.served}),e[11]=o.served,e[12]=n,e[13]=s):s=e[13];let i;e[14]!==d||e[15]!==s?(i=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3","data-testid":"fanout-probe-stats",children:[d,s]}),e[14]=d,e[15]=s,e[16]=i):i=e[16];let m;return e[17]!==l||e[18]!==i?(m=(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":"fanout-probe-section",children:[l,i]}),e[17]=l,e[18]=i,e[19]=m):m=e[19],m},"V"),Z=S(c=>{let e=(0,R.c)(20),{counters:o,t:a}=c,r;e[0]!==a?(r=a("Global shape polls"),e[0]=a,e[1]=r):r=e[1];let l;e[2]!==r?(l=(0,t.jsx)("h3",{className:"text-sm font-medium text-foreground",children:r}),e[2]=r,e[3]=l):l=e[3];let u;e[4]!==a?(u=a("Global reads"),e[4]=a,e[5]=u):u=e[5];let d;e[6]!==o.drains||e[7]!==u?(d=(0,t.jsx)(v,{label:u,testId:"fanout-global-poll-drains",value:o.drains}),e[6]=o.drains,e[7]=u,e[8]=d):d=e[8];let n;e[9]!==a?(n=a("Pairs skipped"),e[9]=a,e[10]=n):n=e[10];let s;e[11]!==o.pairsSkipped||e[12]!==n?(s=(0,t.jsx)(v,{label:n,testId:"fanout-global-poll-pairs-skipped",value:o.pairsSkipped}),e[11]=o.pairsSkipped,e[12]=n,e[13]=s):s=e[13];let i;e[14]!==d||e[15]!==s?(i=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3","data-testid":"fanout-global-poll-stats",children:[d,s]}),e[14]=d,e[15]=s,e[16]=i):i=e[16];let m;return e[17]!==l||e[18]!==i?(m=(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":"fanout-global-poll-section",children:[l,i]}),e[17]=l,e[18]=i,e[19]=m):m=e[19],m},"X"),pe=S(c=>{let e=(0,R.c)(31),{initialShardKey:o}=c,a=j(),{queryShardKey:r,setShardKey:l,shardKey:u}=L(o),d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d={},e[0]=d):d=e[0];let n;e[1]!==r?(n={keepPreviousData:!0,shardKey:r},e[1]=r,e[2]=n):n=e[2];let{data:s,error:i,errorSource:m,refetch:I}=B(E.getFanoutMetrics,d,n);Q(I,!0);let g;e[3]!==s?(g=s!==void 0&&X(s),e[3]=s,e[4]=g):g=e[4];let k=g,p;e[5]!==l||e[6]!==u?(p=(0,t.jsx)(G,{onChange:l,testId:"fanout-shard-input",value:u}),e[5]=l,e[6]=u,e[7]=p):p=e[7];let f;e[8]!==s||e[9]!==a?(f=s!==void 0&&(0,t.jsxs)("div",{className:"ml-auto flex items-center gap-2 text-sm text-muted-foreground","data-testid":"fanout-count",children:[s.promoted&&(0,t.jsx)($,{"data-testid":"fanout-promoted",variant:s.relayCount>=s.maxRelays?"destructive":"default",children:s.relayCount>=s.maxRelays?a("auto-scaled: {relayCount}/{maxRelays} relays (at ceiling)",{maxRelays:s.maxRelays,relayCount:s.relayCount}):a("auto-scaled: {relayCount}/{maxRelays} relays",{maxRelays:s.maxRelays,relayCount:s.relayCount})}),(0,t.jsx)($,{variant:"secondary",children:a("{count} connections",{count:s.totalConnections})}),(0,t.jsx)($,{variant:"secondary",children:a("peak {count} subscribers",{count:s.peakSubscribers})})]}),e[8]=s,e[9]=a,e[10]=f):f=e[10];let y;e[11]!==p||e[12]!==f?(y=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[p,f]}),e[11]=p,e[12]=f,e[13]=y):y=e[13];let h;e[14]!==i||e[15]!==m?(h=i!==null&&(0,t.jsx)(W,{error:m,testId:"fanout-error"}),e[14]=i,e[15]=m,e[16]=h):h=e[16];let x;e[17]!==i||e[18]!==k||e[19]!==a?(x=i===null&&k&&(0,t.jsx)(A,{description:a("Realtime fan-out cost and per-topic subscriber counts for this shard."),icon:(0,t.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,t.jsx)("path",{d:"M4 12h4l3 7 4-14 3 7h2"})}),testId:"fanout-empty",title:a("No fan-out activity yet.")}),e[17]=i,e[18]=k,e[19]=a,e[20]=x):x=e[20];let N;e[21]!==i||e[22]!==k||e[23]!==s||e[24]!==a?(N=i===null&&s!==void 0&&!k&&(0,t.jsxs)(t.Fragment,{children:[s.topics.length>0&&(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":"fanout-topics-section",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-foreground",children:a("Hot topics")}),(0,t.jsx)(_,{className:"overflow-hidden py-0",children:(0,t.jsxs)(q,{"data-testid":"fanout-topics-table",children:[(0,t.jsx)(H,{children:(0,t.jsxs)(K,{children:[(0,t.jsx)(T,{children:a("Topic")}),(0,t.jsx)(T,{children:a("Kind")}),(0,t.jsx)(T,{className:"text-right",children:a("Subscribers")})]})}),(0,t.jsx)(O,{children:s.topics.map(ee)})]})})]}),(0,t.jsxs)("section",{className:"flex flex-col gap-3","data-testid":"fanout-cost",children:[(0,t.jsx)("h2",{className:"text-sm font-medium text-muted-foreground",children:a("Fan-out cost since this instance woke")}),(0,t.jsx)(z,{counters:s.shapePoke,includeTiming:!0,prefix:"fanout-poke",t:a,title:a("Shape pokes")}),(0,t.jsx)(z,{counters:s.whisper,includeTiming:!1,prefix:"fanout-whisper",t:a,title:a("Whisper broadcasts")}),(0,t.jsx)(Y,{counters:s.shapeProbe,t:a}),(0,t.jsx)(Z,{counters:s.globalPoll,t:a})]})]}),e[21]=i,e[22]=k,e[23]=s,e[24]=a,e[25]=N):N=e[25];let b;return e[26]!==y||e[27]!==h||e[28]!==x||e[29]!==N?(b=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"fanout-panel",children:[y,h,x,N]}),e[26]=y,e[27]=h,e[28]=x,e[29]=N,e[30]=b):b=e[30],b},"me");function ee(c){return(0,t.jsxs)(K,{"data-testid":"fanout-topic-row",children:[(0,t.jsx)(D,{className:"font-mono text-xs",children:c.topic}),(0,t.jsx)(D,{children:(0,t.jsx)($,{variant:"outline",children:c.kind})}),(0,t.jsx)(D,{className:"text-right font-medium tabular-nums",children:c.subscribers})]},`${c.kind}:${c.topic}`)}S(ee,"Y");export{pe as default};
|