@lunora/studio 1.0.0-alpha.178 → 1.0.0-alpha.180
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +40 -1
- package/dist/index.d.ts +40 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/FileBrowser.mjs +1 -1
- package/dist/packem_chunks/SqlEditorPanel.mjs +6 -6
- package/dist/packem_chunks/TableEditor.mjs +1 -1
- package/dist/packem_chunks/permissions-panel.mjs +1 -1
- package/dist/packem_chunks/queues-panel.mjs +1 -1
- package/dist/packem_shared/DataBrowser-BUFMFvNX.mjs +4 -0
- package/dist/packem_shared/DataFilters-Cocu-WWE.mjs +1 -0
- package/dist/packem_shared/grid-features-CE8kcqsK.mjs +6 -0
- package/dist/standalone/{chunk-2W365SXI.js → chunk-3PZNTIBM.js} +1 -1
- package/dist/standalone/{chunk-TXLWUHAU.js → chunk-3TXB4AKZ.js} +1 -1
- package/dist/standalone/{chunk-U7A2W7UG.js → chunk-4PRXEO3C.js} +1 -1
- package/dist/standalone/{chunk-P4V5VRUR.js → chunk-5B6TTEP6.js} +1 -1
- package/dist/standalone/{chunk-QCFJKKLX.js → chunk-5LZJ5JBB.js} +1 -1
- package/dist/standalone/{chunk-E366YQXO.js → chunk-5MKG6RW3.js} +1 -1
- package/dist/standalone/{chunk-PHYKYBCE.js → chunk-66Z7ZIZZ.js} +1 -1
- package/dist/standalone/{chunk-MOYNBJNW.js → chunk-A6S4TULR.js} +1 -1
- package/dist/standalone/{chunk-KIEUFC6E.js → chunk-A7EWHGFT.js} +1 -1
- package/dist/standalone/{chunk-ANXXWNJG.js → chunk-AFSPF2R4.js} +1 -1
- package/dist/standalone/{chunk-AKG3SL2Z.js → chunk-AODYDAXY.js} +1 -1
- package/dist/standalone/{chunk-NLHKRU3D.js → chunk-AULH6SZB.js} +1 -1
- package/dist/standalone/{chunk-YRZFU7OM.js → chunk-AX24JD2G.js} +1 -1
- package/dist/standalone/chunk-B3JY36UV.js +5 -0
- package/dist/standalone/chunk-B6RRRJP5.js +11 -0
- package/dist/standalone/{chunk-VR3OL4A6.js → chunk-BAAPQWFF.js} +1 -1
- package/dist/standalone/{chunk-I3OOVU3O.js → chunk-D4ZGY3II.js} +1 -1
- package/dist/standalone/{chunk-D7PVLNBP.js → chunk-DAD33Q2T.js} +1 -1
- package/dist/standalone/{chunk-ZTA7WN4R.js → chunk-DI34YDBW.js} +1 -1
- package/dist/standalone/{chunk-BR64TOG4.js → chunk-E2X625P3.js} +1 -1
- package/dist/standalone/{chunk-5PBVNSPQ.js → chunk-EBU3TTYR.js} +1 -1
- package/dist/standalone/{chunk-MWUR2KP6.js → chunk-FI6N7XWP.js} +1 -1
- package/dist/standalone/{chunk-IUKHT5XV.js → chunk-GAPFZFIL.js} +1 -1
- package/dist/standalone/{chunk-D2SSRZG5.js → chunk-GP2GJRJ3.js} +1 -1
- package/dist/standalone/{chunk-MNQSYFV6.js → chunk-GZ6GAFM2.js} +1 -1
- package/dist/standalone/chunk-GZAXFXZE.js +1 -0
- package/dist/standalone/{chunk-WV2AW6IT.js → chunk-H43JNQM6.js} +1 -1
- package/dist/standalone/{chunk-V5FOHTRB.js → chunk-HGT5U6GD.js} +1 -1
- package/dist/standalone/{chunk-P6F4CNT5.js → chunk-I6FR5UAK.js} +1 -1
- package/dist/standalone/{chunk-7HFDITXH.js → chunk-INXSZE5I.js} +1 -1
- package/dist/standalone/{chunk-FTR6JAWG.js → chunk-IP7YCJUN.js} +1 -1
- package/dist/standalone/{chunk-KZDIKRZ3.js → chunk-ITMXIPQ7.js} +1 -1
- package/dist/standalone/{chunk-M7QQYXU4.js → chunk-IXNOQYEE.js} +1 -1
- package/dist/standalone/{chunk-LKKZMIZK.js → chunk-JYT34NQM.js} +1 -1
- package/dist/standalone/{chunk-2NYASBOP.js → chunk-L2CWAQUO.js} +1 -1
- package/dist/standalone/{chunk-QY4V5UOY.js → chunk-M4POCI2J.js} +1 -1
- package/dist/standalone/{chunk-RSULZ5QU.js → chunk-MH2NGGUC.js} +1 -1
- package/dist/standalone/{chunk-WHPKXZN2.js → chunk-PGMASM2T.js} +1 -1
- package/dist/standalone/{chunk-2ADU5FA5.js → chunk-PZVVEPIN.js} +1 -1
- package/dist/standalone/{chunk-GDYRC6T6.js → chunk-QDHXQ56K.js} +1 -1
- package/dist/standalone/{chunk-KQMWK6QZ.js → chunk-QQ3CS3FX.js} +1 -1
- package/dist/standalone/chunk-QWJQUQY3.js +8 -0
- package/dist/standalone/{chunk-YK7JO7NP.js → chunk-RM4TNBYG.js} +1 -1
- package/dist/standalone/{chunk-MBP4SZYB.js → chunk-SDHFSBNM.js} +1 -1
- package/dist/standalone/{chunk-N2VWHDGA.js → chunk-SLI7DPVW.js} +1 -1
- package/dist/standalone/{chunk-CXGPKEDJ.js → chunk-TIIEZS24.js} +1 -1
- package/dist/standalone/{chunk-MOMBFDIA.js → chunk-TK6AEV4N.js} +1 -1
- package/dist/standalone/{chunk-U2YJ64UT.js → chunk-TTIBDOV6.js} +1 -1
- package/dist/standalone/{chunk-WX6MJS7P.js → chunk-V56XORNF.js} +1 -1
- package/dist/standalone/{chunk-IBM6X4XI.js → chunk-V7G6YTQ5.js} +1 -1
- package/dist/standalone/{chunk-U3T6FYYZ.js → chunk-VWXJAY7R.js} +1 -1
- package/dist/standalone/{chunk-6HVFOKP5.js → chunk-WD4WHTAV.js} +1 -1
- package/dist/standalone/{chunk-G22LSAIH.js → chunk-WIXX2VWE.js} +1 -1
- package/dist/standalone/{chunk-3JDH25N2.js → chunk-WRZTTZFV.js} +1 -1
- package/dist/standalone/{chunk-Y5IE2W4U.js → chunk-Y2I6GYEG.js} +1 -1
- package/dist/standalone/{chunk-I5V3IHPF.js → chunk-YONJDNSM.js} +1 -1
- package/dist/standalone/chunk-Z2XS4ZOO.js +1 -0
- package/dist/standalone/studio.js +1 -1
- package/package.json +5 -5
- package/dist/packem_shared/DataBrowser-B_zcf3a_.mjs +0 -4
- package/dist/packem_shared/DataFilters-3nbW0uax.mjs +0 -1
- package/dist/packem_shared/grid-features-Dl7bCGRN.mjs +0 -6
- package/dist/standalone/chunk-KYMUE3MZ.js +0 -5
- package/dist/standalone/chunk-RY66ZJJQ.js +0 -1
- package/dist/standalone/chunk-SA5SGD3V.js +0 -8
- package/dist/standalone/chunk-YAAM5IKA.js +0 -1
- package/dist/standalone/chunk-Z7WCKAUJ.js +0 -11
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{a as wt,d as p}from"./chunk-2Y6PXGIS.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(!q(e.queryKey,a))return!1}if(r!=="all"){let u=e.isActive();if(r==="active"&&!u||r==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}o(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(!q(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 q(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let s=0;s<e.length;s++)if(!q(t[s],e[s]))return!1;return!0}let r=Object.keys(e);for(let s of r)if(!q(t[s],e[s]))return!1;return!0}return!1}o(q,"partialMatchKey");var 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 Mt=kt;function Nr(){let t=[],e=0,r=o(c=>{c()},"notifyFn"),s=o(c=>{c()},"batchNotifyFn"),i=Mt,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(Nr,"createNotifyManager");var g=Nr();var qr=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 qr;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),M=t.retryDelay??Kr,W=typeof M=="function"?M(r,k):M,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")(),M=await f(A),{maxPages:W}=e.options,V=C?Pt:Rt;return{pages:V(m.pages,M,W),pageParams:V(m.pageParams,b,W)}},"fetchPage");if(i&&n.length){let m=i==="backward",b=m?Br:Ft,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:Ft(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 Ft(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(Ft,"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 F=this.hasListeners(),ae=!F&&Dt(t,e),me=F&&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 F;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(F=i.data,C=!0):F=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,F!==void 0&&(b="success",f=ue(i?.data,F,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(F){this.#a=F}this.#a&&(y=this.#a,f=this.#c,m=Date.now(),b="error");let k=d.fetchStatus==="fetching",A=b==="pending",M=b==="error",W=A&&k,V=f!==void 0,N={status:b,fetchStatus:d.fetchStatus,isPending:A,isSuccess:b==="success",isError:M,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:M&&!V,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:M&&V,isStale:Je(t,e),refetch:this.refetch,promise:this.#o,isEnabled:E(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let F=N.data!==void 0,ae=N.status==="error"&&!F,me=o(be=>{ae?be.reject(N.error):F&&be.resolve(N.data)},"finalizeThenableIfPossible"),St=o(()=>{let be=this.#o=N.promise=he();me(be)},"recreateThenable"),ye=this.#o;switch(ye.status){case"pending":t.queryHash===r.queryHash&&me(ye);break;case"fulfilled":(ae||N.data!==ye.value)&&St();break;case"rejected":(!ae||N.error!==ye.reason)&&St();break}}return N}updateResult(){let t=this.#s,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),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 Nt=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 qt=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 Nt({client:t,mutationCache:this,mutationId:++this.#r,options:t.defaultMutationOptions(e),state:r});return this.add(s),s}add(t){this.#e.add(t);let e=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 qt,this.#r=t.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=re.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=ie.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),r=this.#e.build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(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=>{q(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){this.#n.set(J(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],r={};return e.forEach(s=>{q(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#r.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ce(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===se&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#r.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var K=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"),Me=o((t,e,r,s)=>{let i;return()=>i||(i=new Promise((n,a)=>{let c=t.open(e,r);c.addEventListener("upgradeneeded",()=>{s(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{a(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),Fe=o((t,e)=>async(r,s)=>{let i=(await t()).transaction(e,r),n=await s(i.objectStore(e));return await new Promise((a,c)=>{i.addEventListener("complete",()=>{a()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),n},"u");var Y=o((t,e,r)=>`${t}::${e}::${r??""}`,"T"),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=Me(e,r,ss,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(ir,"ts",{unique:!1})}),a=Fe(n,s),c=o(async u=>{let h=await R(u.count())-i;h<=0||await new Promise((d,l)=>{let f=u.index(ir).openCursor();f.addEventListener("success",()=>{let y=f.result;if(!y||h<=0){d();return}y.delete(),h-=1,y.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:o(async()=>{await a("readwrite",u=>R(u.clear()))},"clear"),load:o(async()=>a("readonly",u=>R(u.getAll())),"load"),put:o(async(u,h)=>{await a("readwrite",async d=>{await R(d.put({...h,key:u})),await c(d)})},"put"),remove:o(async u=>{await a("readwrite",h=>R(h.delete(u)))},"remove")}},"N"),nr=o(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return 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,"m")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},r={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=r.persistence,this.onEvict=r.onEvict,this.onSizeChange=r.onSizeChange,this.version=r.version}get size(){return this.items.length}enqueue(e){let r=e;r.id??=Ue(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{H(this.onPersistenceError,"append",s,r.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw H(this.onPersistenceError,"load",a),a}let r=[],s=new Set(this.items.map(a=>a.id));for(let a of e)if(!s.has(a.id)){if(ht(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{H(this.onPersistenceError,"remove",c,a.id)});continue}s.add(a.id),r.push({args:a.args,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of r)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,r){for(let s of this.items){if(s.identity!==e)continue;s.identity=r;let{id:i}=s;if(!this.persistence||i===void 0)continue;let n={args:s.args,clientId:s.clientId,functionPath:s.functionPath,id:i,identity:r,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{H(this.onPersistenceError,"replace",a,i)})}}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=Me(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(dt,"id",{unique:!0})}),n=Fe(i,s);return{append:o(async a=>{await n("readwrite",c=>R(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>R(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>R(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a));u!==void 0&&await R(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a.id));u!==void 0&&await R(c.put(a,u))})},"replace")}},"w"),br=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return 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"},Ne=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"),Ms=983040,Fs=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Fe"),xs="/_lunora/rpc",Sr="/_lunora/rpc-batch",_s="/_lunora/ws",pt=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"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,Ns=250,qs=5e3,Ks=64,Bs=8,js="/_lunora/admin/shard-traffic",$s="/_lunora/admin/scheduled",Hs="/_lunora/admin/scheduled/status",zs="/_lunora/admin/scheduled/ws",Ws="/_lunora/admin/scheduled/cancel",Cr="/_lunora/admin/scheduled/dead",Vs="/_lunora/admin/scheduled/dead/retry",Gs="/_lunora/admin/scheduled/dead/cancel",Js="/_lunora/admin/workflows/instances",Xs="/_lunora/admin/workflows/instance",Ys="/_lunora/admin/workflows/status",mt="/_lunora/admin/storage",Zs="/_lunora/admin/storage/url",ei="/_lunora/admin/storage/buckets",ti="/_lunora/admin/functions",ri="/_lunora/admin/cron-jobs",si="/_lunora/admin/cron-jobs/run",ii="/_lunora/admin/openapi",ni="/_lunora/admin/openrpc",ai="/_lunora/admin/global/tables",oi="/_lunora/admin/global/table",ci="/_lunora/admin/global/facet",ui="/_lunora/admin/vector/indexes",hi="/_lunora/admin/vector/query",di="/_lunora/admin/logs/archive",li="/_lunora/admin/kv/namespaces",fi="/_lunora/admin/kv/keys",yt="/_lunora/admin/kv/value",pi="/_lunora/admin/auth/users",mi="/_lunora/admin/auth/sessions",yi="/_lunora/admin/auth/users/create",bi="/_lunora/admin/auth/users/role",vi="/_lunora/admin/auth/users/ban",gi="/_lunora/admin/auth/users/unban",Si="/_lunora/admin/auth/users/password",wi="/_lunora/admin/auth/users/remove",Ci="/_lunora/admin/auth/users/impersonate",ki="/_lunora/admin/auth/sessions/revoke",Ti="/_lunora/admin/auth/sessions/revoke-all",Ei="/_lunora/admin/auth/capabilities",Ii="/_lunora/admin/auth/users/update",Oi="/_lunora/admin/auth/accounts",Ri="/_lunora/admin/auth/accounts/unlink",Pi="/_lunora/admin/auth/passkeys",Ai="/_lunora/admin/auth/passkeys/delete",Mi="/_lunora/admin/auth/two-factor/disable",Fi="/_lunora/admin/auth/organizations",xi="/_lunora/admin/auth/organizations/members",_i="/_lunora/admin/auth/organizations/invitations",Li="/_lunora/admin/auth/organizations/members/remove",Qi="/_lunora/admin/auth/organizations/invitations/cancel",Di="/_lunora/admin/auth/config",Ui="/_lunora/admin/auth/sign-up-invitations",Ni="/_lunora/admin/auth/sign-up-invitations/create",qi="/_lunora/admin/auth/sign-up-invitations/revoke",Ki="/_lunora/admin/auth/organizations/create",Bi="/_lunora/admin/auth/organizations/update",ji="/_lunora/admin/auth/organizations/remove",$i="/_lunora/admin/auth/organizations/members/add",Hi="/_lunora/admin/auth/organizations/members/invite",zi="/_lunora/admin/auth/organizations/members/role",Wi="/_lunora/admin/auth/organizations/teams",Vi="/_lunora/admin/auth/organizations/teams/create",Gi="/_lunora/admin/auth/organizations/teams/update",Ji="/_lunora/admin/auth/organizations/teams/remove",Xi="/_lunora/admin/auth/organizations/teams/members",Yi="/_lunora/admin/auth/organizations/teams/members/add",Zi="/_lunora/admin/auth/organizations/teams/members/remove",en="/_lunora/admin/auth/organizations/roles",tn="/_lunora/admin/auth/organizations/roles/create",rn="/_lunora/admin/auth/organizations/roles/update",sn="/_lunora/admin/auth/organizations/roles/remove",nn="/api/auth",an="/get-session",kr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"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"),Mr=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}=Mr(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"hs"),Tr=o(t=>{let{code:e,messageText:r}=Mr(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"),qe=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},"H"),Er=o((t,e)=>{let r=qe(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,"K"),dn=o((t,e)=>{let r=Array.from({length:e});for(let s of t){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;let i=s.body;r[s.id]=i&&"error"in i&&i.error?{error:qe(i.error),ok:!1}:{ok:!0,value: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?qe(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let a=n.body?.commitCursor;typeof n.id=="number"&&typeof a=="number"&&this.recordShardCursor(e[n.id]?.shardKey,a)}return dn(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??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,{captureBookmark:!0,mutationId:n,onCommitCursor:o(M=>{k=M},"onCommitCursor")});for(let M of a)M(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(Mi,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(I(Fi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=I(xi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=I(_i,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthSignUpInvitations(e={}){let r=I(Ui,{limit:e.limit,offset:e.offset});return await this.adminFetch(r,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Ni,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(qi,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(Li,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Qi,"POST",e)}async getAuthConfig(){return await this.adminFetch(Di,"GET")}async createAuthOrganization(e){return await this.adminFetch(Ki,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Bi,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(ji,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch($i,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(Hi,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(zi,"POST",e)}async listAuthOrgTeams(e){let r=I(Wi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Vi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Gi,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Ji,"POST",e)}async listAuthOrgTeamMembers(e){let r=I(Xi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Yi,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Zi,"POST",e)}async listAuthOrgRoles(e){let r=I(en,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(tn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(rn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(sn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=I(mi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},a=P.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=bt(s),h=bt(i.onError),d=bt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,y=j(n),m=this.takeHydratedCache(e.__lunoraRef,y,i.shardKey);c={acked:!1,args:n,argsKey:y,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:z(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.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,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(()=>{})},Ns)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,r,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:r})}applyOptimisticUpdates(e,r,s,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=P.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=ut(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=mr(this.subscriptions,s);try{e(u,r)}catch{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.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 Ne(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 Ne(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()},qs),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,{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&&Fs(s)>Ms)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,Ne(i.status,i.statusText,c),r)}if(!a.results){let u=a.error===void 0?Ne(i.status,i.statusText,c):Er(a.error,c);return this.settleWholeBatchError(e,u,r)}return{requeue:this.settleReplayBatchSlots(e,a.results,r),stop:!1}}settleWholeBatchError(e,r,s){if(r instanceof B||r.code!==void 0&&this.shouldRequeueReplayFailure(r))return this.noteReplayRetryDelay(s,r),{requeue:e,stop:!0};for(let i of e)this.settleReplayTerminal(i,r);return{requeue:[],stop:!1}}async replayBatchedHalves(e,r){let s=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,s),r);if(i.stop)return{requeue:[...i.requeue,...e.slice(s)],stop:!0};let n=await this.replayBatched(e.slice(s),r);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,r,s){let i=new Map;for(let a of r)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);let n=[];for(let[a,c]of e.entries()){let u=i.get(a);if(u===void 0)n.push(c);else if("error"in u){let h=qe(u.error);this.shouldRequeueReplayFailure(h)?(this.noteReplayRetryDelay(s,h),n.push(c)):this.settleReplayTerminal(c,h)}else this.settleReplaySuccess(c,S(u.result),u.commitCursor)}return n}};var Fr=x(Ct(),1),xr=x(G(),1);var fn=o(()=>{let t=(0,Fr.c)(4),e=rt(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"o"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"c"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,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{b as y}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as R}from"./chunk-
|
|
1
|
+
import{b as y}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as R}from"./chunk-ITMXIPQ7.js";import"./chunk-ULIQFBZU.js";import"./chunk-3PZNTIBM.js";import"./chunk-35DM4JJG.js";import{a as v}from"./chunk-4ZEL6BYL.js";import{c as $}from"./chunk-SDHFSBNM.js";import"./chunk-B6RRRJP5.js";import"./chunk-FSRSK4LY.js";import"./chunk-2Y6PXGIS.js";import{a as S}from"./chunk-FKVZRPV5.js";import{a as A,b as C,c as I,d as x,e as c,f as n}from"./chunk-HEAQVSNS.js";import{a as k,e as w}from"./chunk-WUWBZPUK.js";import{d as N}from"./chunk-FODLDLE2.js";import{a as f,d as b,f as E,g as O}from"./chunk-YKXDMIHQ.js";var j=b(E(),1);var r=b(O(),1);var _=f((e,t)=>({delete:e("Delete"),list:e("List"),read:e("Read"),write:e("Write")})[t],"I"),T={delete:2,list:3,read:0,write:1},B=f(e=>[...e].toSorted((t,a)=>t.bucket.localeCompare(a.bucket)||T[t.on]-T[a.on]||(t.prefix??"").localeCompare(a.prefix??"")),"O"),q=f(()=>{let e=(0,j.c)(14),t=N(),a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a={},e[0]=a):a=e[0];let{data:l,error:i,errorSource:d}=$(v.storageRules,a),h=l!==void 0,m;if(e[1]!==l||e[2]!==i||e[3]!==d||e[4]!==h||e[5]!==t){let g=B(Array.isArray(l?.rules)?l.rules:[]),u;e[7]!==i||e[8]!==d?(u=i!==null&&(0,r.jsx)(R,{error:d,testId:"storage-rules-error"}),e[7]=i,e[8]=d,e[9]=u):u=e[9];let o;e[10]!==t?(o=t("Storage rules are declared in code with defineStorageRule and gate ctx.storage access per bucket. This view is read-only."),e[10]=t,e[11]=o):o=e[11];let p;e[12]!==o?(p=(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"storage-rules-note",children:o}),e[12]=o,e[13]=p):p=e[13],m=(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-storage-rules-panel",children:[u,p,h&&g.length===0?(0,r.jsx)(S,{description:t("No defineStorageRule is wired through .use(storageRules(...)) in this deployment. Add one to gate object access by key prefix."),testId:"storage-rules-empty",title:t("No storage rules defined")}):(0,r.jsx)(k,{className:"overflow-hidden py-0",children:(0,r.jsx)(w,{className:"px-0",children:(0,r.jsxs)(A,{"data-testid":"storage-rules-table",children:[(0,r.jsx)(C,{children:(0,r.jsxs)(x,{children:[(0,r.jsx)(c,{children:t("Bucket")}),(0,r.jsx)(c,{children:t("Operation")}),(0,r.jsx)(c,{children:t("Key prefix")}),(0,r.jsx)(c,{children:t("Guarded by")})]})}),(0,r.jsx)(I,{children:g.map(s=>(0,r.jsxs)(x,{"data-testid":`storage-rule-${s.bucket}-${s.on}-${s.prefix??""}`,children:[(0,r.jsx)(n,{className:"font-mono text-xs",children:s.bucket}),(0,r.jsx)(n,{children:(0,r.jsx)(y,{variant:"secondary",children:_(t,s.on)})}),(0,r.jsx)(n,{className:"font-mono text-xs",children:s.prefix??(0,r.jsx)("span",{className:"text-muted-foreground",children:t("(whole bucket)")})}),(0,r.jsx)(n,{className:"font-mono text-xs text-muted-foreground",children:s.procedure})]},`${s.bucket}:${s.on}:${s.prefix??""}:${s.procedure}`))})]})})})]}),e[1]=l,e[2]=i,e[3]=d,e[4]=h,e[5]=t,e[6]=m}else m=e[6];return m},"M");export{q as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{W as k}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as q}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as j}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as U}from"./chunk-
|
|
1
|
+
import{W as k}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as q}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as j}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as U}from"./chunk-ITMXIPQ7.js";import"./chunk-ULIQFBZU.js";import"./chunk-3PZNTIBM.js";import"./chunk-35DM4JJG.js";import{a as R}from"./chunk-4ZEL6BYL.js";import{c as P}from"./chunk-SDHFSBNM.js";import"./chunk-B6RRRJP5.js";import"./chunk-FSRSK4LY.js";import"./chunk-2Y6PXGIS.js";import{a as M}from"./chunk-FKVZRPV5.js";import{a as G,b as H,c as J,d as B,e as x,f as N}from"./chunk-HEAQVSNS.js";import{a as z,e as D}from"./chunk-WUWBZPUK.js";import{d as F,r as O}from"./chunk-FODLDLE2.js";import{a as A,d as T,e as $,f as X,g as Y}from"./chunk-YKXDMIHQ.js";var K=T(X(),1),Q=T($(),1);var t=T(Y(),1);var de=A(()=>{let e=(0,K.c)(39),a=F(),[s,V]=(0,Q.useState)(""),y;e[0]===Symbol.for("react.memo_cache_sentinel")?(y={},e[0]=y):y=e[0];let{data:C,error:l,errorSource:S,isLoading:E,refetch:_}=P(R.getAuthAuditLog,y),I;if(e[1]!==C?.entries||e[2]!==s){let r=C?.entries??[],v=s.trim().toLowerCase();I=v===""?r:r.filter(w=>w.event.toLowerCase().includes(v)||(w.actorId??"").toLowerCase().includes(v)||(w.actorEmail??"").toLowerCase().includes(v)||(w.ip??"").toLowerCase().includes(v)||w.outcome.toLowerCase().includes(v)),e[1]=C?.entries,e[2]=s,e[3]=I}else I=e[3];let o=I,L;e[4]===Symbol.for("react.memo_cache_sentinel")?(L=A(r=>{V(r.target.value)},"I"),e[4]=L):L=e[4];let W=L,i;e[5]!==a?(i=a("Filter security events"),e[5]=a,e[6]=i):i=e[6];let n;e[7]!==a?(n=a("filter event, actor, IP"),e[7]=a,e[8]=n):n=e[8];let c;e[9]!==s||e[10]!==i||e[11]!==n?(c=(0,t.jsx)(k,{"aria-label":i,className:"h-8 w-56","data-testid":"aa-search",onChange:W,placeholder:n,value:s}),e[9]=s,e[10]=i,e[11]=n,e[12]=c):c=e[12];let d;e[13]!==_?(d=A(()=>{_()},"m"),e[13]=_,e[14]=d):d=e[14];let m;e[15]!==a?(m=a("Refresh"),e[15]=a,e[16]=m):m=e[16];let u;e[17]!==d||e[18]!==m?(u=(0,t.jsx)(q,{"data-testid":"aa-refresh",onClick:d,size:"xs",type:"button",variant:"ghost",children:m}),e[17]=d,e[18]=m,e[19]=u):u=e[19];let h;e[20]!==c||e[21]!==u?(h=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[c,u]}),e[20]=c,e[21]=u,e[22]=h):h=e[22];let f;e[23]!==l||e[24]!==S?(f=l!==null&&(0,t.jsx)(U,{error:S,testId:"aa-error"}),e[23]=l,e[24]=S,e[25]=f):f=e[25];let p;e[26]!==l||e[27]!==o.length||e[28]!==E||e[29]!==a?(p=l===null&&!E&&o.length===0&&(0,t.jsx)(M,{description:a("Authentication and security events are recorded here."),testId:"aa-empty",title:a("No security events.")}),e[26]=l,e[27]=o.length,e[28]=E,e[29]=a,e[30]=p):p=e[30];let g;e[31]!==o||e[32]!==a?(g=o.length>0&&(0,t.jsx)(z,{className:"overflow-hidden py-0",children:(0,t.jsx)(D,{className:"max-h-[30rem] overflow-auto px-0",children:(0,t.jsxs)(G,{"data-testid":"aa-table",children:[(0,t.jsx)(H,{children:(0,t.jsxs)(B,{children:[(0,t.jsx)(x,{children:a("time")}),(0,t.jsx)(x,{children:a("event")}),(0,t.jsx)(x,{children:a("actor")}),(0,t.jsx)(x,{children:a("ip / user agent")}),(0,t.jsx)(x,{children:a("outcome")})]})}),(0,t.jsx)(J,{children:o.map(r=>(0,t.jsxs)(B,{"data-testid":"aa-row",children:[(0,t.jsx)(N,{className:"text-muted-foreground tabular-nums",children:O(r.ts,"\u2014")}),(0,t.jsx)(N,{children:(0,t.jsx)(j,{variant:"secondary",children:r.event})}),(0,t.jsx)(N,{className:"max-w-[24ch] truncate font-mono text-xs",title:r.actorId??void 0,children:r.actorEmail??r.actorId??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})}),(0,t.jsxs)(N,{className:"max-w-[28ch] truncate text-xs text-muted-foreground",title:r.userAgent??void 0,children:[r.ip??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}),r.userAgent!==void 0&&(0,t.jsxs)("span",{className:"ml-1 opacity-70",children:["\xB7 ",r.userAgent]})]}),(0,t.jsx)(N,{children:(0,t.jsx)(j,{variant:r.outcome==="failure"?"destructive":"outline",children:a(r.outcome)})})]},r.seq))})]})})}),e[31]=o,e[32]=a,e[33]=g):g=e[33];let b;return e[34]!==f||e[35]!==p||e[36]!==g||e[37]!==h?(b=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-auth-audit",children:[h,f,p,g]}),e[34]=f,e[35]=p,e[36]=g,e[37]=h,e[38]=b):b=e[38],b},"ne");export{de as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as me}from"./chunk-F7UC63UN.js";import{a as Ot,b as zt,c as At,d as Kt}from"./chunk-SUDJTC4S.js";import{a as it}from"./chunk-CBNGOAD4.js";import{a as Dt,b as Ct,c as It,d as Ft,e as Pe}from"./chunk-IHMGCHAA.js";import{a as Tt}from"./chunk-RPQL45FL.js";import{a as Rt}from"./chunk-GGPSI4ZR.js";import"./chunk-4GTO7FL5.js";import"./chunk-4JLGLPWV.js";import{e as $t}from"./chunk-UYEZR3BI.js";import"./chunk-V3CZW3JB.js";import{a as _t}from"./chunk-BOTGXX4H.js";import"./chunk-GMS77BZD.js";import"./chunk-3Q2P62UR.js";import"./chunk-AWHXPIXU.js";import"./chunk-V3VJAA4D.js";import{a as Ee,b as et,c as tt,d as vt,e as yt,f as rt,g as at,h as Nt,i as St}from"./chunk-URBHAYYZ.js";import"./chunk-5JDWLCSH.js";import"./chunk-EVTM6Q43.js";import{a as kt}from"./chunk-S3CRZLGS.js";import{a as Mt}from"./chunk-2DX5MROH.js";import{a as wt,b as qt}from"./chunk-OGUKYRFM.js";import"./chunk-6D6Z2KXU.js";import"./chunk-OKG3HWSJ.js";import"./chunk-PLHA3OWK.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{a as Ze}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as We}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import"./chunk-35DM4JJG.js";import{a as ze}from"./chunk-4ZEL6BYL.js";import{c as Le}from"./chunk-MBP4SZYB.js";import{f as ct}from"./chunk-Z7WCKAUJ.js";import"./chunk-FSRSK4LY.js";import"./chunk-2Y6PXGIS.js";import{a as ht}from"./chunk-FKVZRPV5.js";import{a as st,b as lt,c as nt,d as je,e as ce,f as U}from"./chunk-HEAQVSNS.js";import{a as fe,b as Ae,c as Ke,d as ut,e as pe}from"./chunk-WUWBZPUK.js";import{d as ge,f as gt,g as ft,h as pt,i as xt,l as Ge,o as bt}from"./chunk-FODLDLE2.js";import{a as o,d as Ye,e as Jt,f as Bt,g as Ht,i as mt}from"./chunk-YKXDMIHQ.js";var P=Ye(Jt(),1);var xe=Ye(Bt(),1);var t=Ye(Ht(),1);var Ut=/["\\\u0000-\u001F\uD800-\uDFFF]/,Lt=o(s=>Ut.test(s)?JSON.stringify(s):`"${s}"`,"ot"),dt=o(s=>{if(s===void 0)return"null";if(typeof s=="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 s=="number"){if(Number.isNaN(s))return"nan";if(s===1/0)return"inf";if(s===-1/0)return"-inf";if(Object.is(s,-0))return"-0"}if(typeof s=="string")return Lt(s);if(s===null||typeof s!="object")return JSON.stringify(s);if(Array.isArray(s)){let i="[";for(let n=0;n<s.length;n++)n>0&&(i+=","),i+=dt(s[n]);return i+"]"}let e=Object.getPrototypeOf(s);if(e!==null&&e!==Object.prototype){let i=s.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${i} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let l=s,a=Object.keys(l).sort(),r="{",u=!0;for(let i of a){let n=l[i];n!==void 0&&(u?u=!1:r+=",",r+=Lt(i),r+=":",r+=dt(n))}return r+"}"},"Ze"),Pt=o((s,e,l)=>`${s}:${e}:${dt(l??{})}`,"ht"),Qt=o((s,e)=>s==="gauge"?e.last:s==="histogram"?e.sum/Math.max(1,e.count):e.sum,"gt"),Wt=o((s,e)=>Qt(s,e),"Jt"),Gt=o(s=>Qt(s.kind,s),"Vt"),ot=o(s=>Number.isInteger(s)?s.toLocaleString():s.toLocaleString(void 0,{maximumFractionDigits:2}),"We"),Vt=o(s=>Array.isArray(s?.series)?s.series:[],"Gt"),Xt="FUNCTION_NOT_FOUND",Yt=o(s=>{let e=new Map;if(!Array.isArray(s?.series))return e;for(let l of s.series)e.set(Pt(l.kind,l.name,l.attributes),l.points);return e},"Xt"),Zt={counter:"secondary",gauge:"default",histogram:"outline"},Et=o(s=>{let e=(0,xe.c)(18),{name:l,onOpenTrace:a,traceId:r}=s,u=ge();if(r===void 0){let c;return e[0]===Symbol.for("react.memo_cache_sentinel")?(c=(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}),e[0]=c):c=e[0],c}let i;e[1]!==r?(i=r.slice(0,8),e[1]=r,e[2]=i):i=e[2];let n=i;if(a===void 0){let c=`mt-instrument-trace-${l}`,f;return e[3]!==n||e[4]!==c||e[5]!==r?(f=(0,t.jsx)("span",{className:"text-muted-foreground","data-testid":c,title:r,children:n}),e[3]=n,e[4]=c,e[5]=r,e[6]=f):f=e[6],f}let h=`mt-instrument-trace-${l}`,y;e[7]!==a||e[8]!==r?(y=o(()=>{a(r)},"v"),e[7]=a,e[8]=r,e[9]=y):y=e[9];let w;e[10]!==u||e[11]!==r?(w=u("Open the exemplar trace {trace}",{trace:r}),e[10]=u,e[11]=r,e[12]=w):w=e[12];let g;return e[13]!==n||e[14]!==h||e[15]!==y||e[16]!==w?(g=(0,t.jsx)("button",{className:"text-primary underline-offset-4 hover:underline","data-testid":h,onClick:y,title:w,type:"button",children:n}),e[13]=n,e[14]=h,e[15]=y,e[16]=w,e[17]=g):g=e[17],g},"Zt"),er=o(s=>{let e=(0,xe.c)(105),{onOpenTrace:l,shardKey:a}=s,r=ge(),u;e[0]===Symbol.for("react.memo_cache_sentinel")?(u={},e[0]=u):u=e[0];let i;e[1]!==a?(i={live:!0,shardKey:a},e[1]=a,e[2]=i):i=e[2];let{data:n,error:h,errorSource:y}=Le(ze.getMetricSeries,u,i),w;e[3]===Symbol.for("react.memo_cache_sentinel")?(w={},e[3]=w):w=e[3];let g;e[4]!==a?(g={live:!0,shardKey:a},e[4]=a,e[5]=g):g=e[5];let{data:c}=Le(ze.getMetricHistory,w,g),f,N,q,_,d,x,p,b,M,$,S,I,C;if(e[6]!==n||e[7]!==h||e[8]!==y||e[9]!==c||e[10]!==l||e[11]!==r){b=Symbol.for("react.early_return_sentinel");e:{let z=Vt(n),A=xt(y)===Xt;if(h!==null&&!A){let m;e[25]!==r?(m=r("Instruments"),e[25]=r,e[26]=m):m=e[26];let j;e[27]!==m?(j=(0,t.jsx)("h3",{className:"text-sm font-semibold text-foreground",children:m}),e[27]=m,e[28]=j):j=e[28];let J;e[29]!==h||e[30]!==r?(J=r("Instruments unavailable: {error}",{error:h}),e[29]=h,e[30]=r,e[31]=J):J=e[31];let B;e[32]!==J?(B=(0,t.jsx)("span",{className:"text-xs text-muted-foreground","data-testid":"mt-instruments-error",role:"status",children:J}),e[32]=J,e[33]=B):B=e[33];let de;e[34]!==j||e[35]!==B?(de=(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":"mt-instruments",children:[j,B]}),e[34]=j,e[35]=B,e[36]=de):de=e[36],b=de;break e}if(z.length===0){b=null;break e}let D=Yt(c),L;e[37]!==r?(L=o(m=>r(m==="counter"?"Counter":m==="gauge"?"Gauge":"Histogram"),"z"),e[37]=r,e[38]=L):L=e[38];let Q=L;d="flex flex-col gap-2",x="mt-instruments";let K;e[39]!==r?(K=r("Instruments"),e[39]=r,e[40]=K):K=e[40],e[41]!==K?(p=(0,t.jsx)("h3",{className:"text-sm font-semibold text-foreground",children:K}),e[41]=K,e[42]=p):p=e[42],_=fe,C="overflow-hidden py-0",q=pe,I="px-0",N=st,$="mt-instruments-table";let W;e[43]!==r?(W=r("name"),e[43]=r,e[44]=W):W=e[44];let G;e[45]!==W?(G=(0,t.jsx)(ce,{children:W}),e[45]=W,e[46]=G):G=e[46];let V;e[47]!==r?(V=r("kind"),e[47]=r,e[48]=V):V=e[48];let X;e[49]!==V?(X=(0,t.jsx)(ce,{children:V}),e[49]=V,e[50]=X):X=e[50];let Y;e[51]!==r?(Y=r("value"),e[51]=r,e[52]=Y):Y=e[52];let Z;e[53]!==Y?(Z=(0,t.jsx)(ce,{className:"text-right",children:Y}),e[53]=Y,e[54]=Z):Z=e[54];let E;e[55]!==r?(E=r("count"),e[55]=r,e[56]=E):E=e[56];let ee;e[57]!==E?(ee=(0,t.jsx)(ce,{className:"text-right",children:E}),e[57]=E,e[58]=ee):ee=e[58];let te;e[59]!==r?(te=r("range"),e[59]=r,e[60]=te):te=e[60];let re;e[61]!==te?(re=(0,t.jsx)(ce,{className:"text-right",children:te}),e[61]=te,e[62]=re):re=e[62];let ae;e[63]!==r?(ae=r("trend"),e[63]=r,e[64]=ae):ae=e[64];let se;e[65]!==ae?(se=(0,t.jsx)(ce,{children:ae}),e[65]=ae,e[66]=se):se=e[66];let le;e[67]!==r?(le=r("trace"),e[67]=r,e[68]=le):le=e[68];let ne;e[69]!==le?(ne=(0,t.jsx)(ce,{children:le}),e[69]=le,e[70]=ne):ne=e[70];let ie;e[71]!==r?(ie=r("dimensions"),e[71]=r,e[72]=ie):ie=e[72];let oe;e[73]!==ie?(oe=(0,t.jsx)(ce,{children:ie}),e[73]=ie,e[74]=oe):oe=e[74],e[75]!==G||e[76]!==X||e[77]!==Z||e[78]!==ee||e[79]!==re||e[80]!==se||e[81]!==ne||e[82]!==oe?(S=(0,t.jsx)(lt,{children:(0,t.jsxs)(je,{children:[G,X,Z,ee,re,se,ne,oe]})}),e[75]=G,e[76]=X,e[77]=Z,e[78]=ee,e[79]=re,e[80]=se,e[81]=ne,e[82]=oe,e[83]=S):S=e[83],f=nt,M=z.map(m=>{let j=Tt(m.attributes),J=Pt(m.kind,m.name,m.attributes),B=(D.get(J)??[]).map(de=>Wt(m.kind,de));return(0,t.jsxs)(je,{"data-testid":`mt-instrument-${m.name}`,children:[(0,t.jsx)(U,{className:"font-mono text-xs",title:m.functionPath,children:m.name}),(0,t.jsx)(U,{children:(0,t.jsx)(We,{variant:Zt[m.kind],children:Q(m.kind)})}),(0,t.jsx)(U,{className:"text-right font-mono tabular-nums","data-testid":`mt-instrument-value-${m.name}`,children:ot(Gt(m))}),(0,t.jsx)(U,{className:"text-right tabular-nums text-muted-foreground",children:m.count.toLocaleString()}),(0,t.jsx)(U,{className:"text-right font-mono text-xs tabular-nums text-muted-foreground",children:m.min===m.max?"\u2014":`${ot(m.min)}\u2013${ot(m.max)}`}),(0,t.jsx)(U,{children:B.length>=2?(0,t.jsx)(it,{ariaLabel:r("{name} trend",{name:m.name}),className:"h-6 w-24 text-foreground",series:B,testId:`mt-instrument-trend-${m.name}`}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"\u2014"})}),(0,t.jsx)(U,{className:"font-mono text-xs",children:(0,t.jsx)(Et,{name:m.name,onOpenTrace:l,traceId:m.exemplarTraceId})}),(0,t.jsx)(U,{className:"max-w-64 truncate font-mono text-xs text-muted-foreground",title:j,children:j===""?"\u2014":j})]},J)})}e[6]=n,e[7]=h,e[8]=y,e[9]=c,e[10]=l,e[11]=r,e[12]=f,e[13]=N,e[14]=q,e[15]=_,e[16]=d,e[17]=x,e[18]=p,e[19]=b,e[20]=M,e[21]=$,e[22]=S,e[23]=I,e[24]=C}else f=e[12],N=e[13],q=e[14],_=e[15],d=e[16],x=e[17],p=e[18],b=e[19],M=e[20],$=e[21],S=e[22],I=e[23],C=e[24];if(b!==Symbol.for("react.early_return_sentinel"))return b;let F;e[84]!==f||e[85]!==M?(F=(0,t.jsx)(f,{children:M}),e[84]=f,e[85]=M,e[86]=F):F=e[86];let k;e[87]!==N||e[88]!==F||e[89]!==$||e[90]!==S?(k=(0,t.jsxs)(N,{"data-testid":$,children:[S,F]}),e[87]=N,e[88]=F,e[89]=$,e[90]=S,e[91]=k):k=e[91];let v;e[92]!==q||e[93]!==k||e[94]!==I?(v=(0,t.jsx)(q,{className:I,children:k}),e[92]=q,e[93]=k,e[94]=I,e[95]=v):v=e[95];let T;e[96]!==_||e[97]!==v||e[98]!==C?(T=(0,t.jsx)(_,{className:C,children:v}),e[96]=_,e[97]=v,e[98]=C,e[99]=T):T=e[99];let O;return e[100]!==d||e[101]!==x||e[102]!==p||e[103]!==T?(O=(0,t.jsxs)("section",{className:d,"data-testid":x,children:[p,T]}),e[100]=d,e[101]=x,e[102]=p,e[103]=T,e[104]=O):O=e[104],O},"er"),tr=o(s=>{let e=(0,xe.c)(74),{aggregate:l,shardResults:a}=s,r=ge(),u;e[0]!==r?(u=r("Shards"),e[0]=r,e[1]=u):u=e[1];let i;e[2]!==l.failed||e[3]!==l.reachable||e[4]!==r?(i=l.failed>0?r("{reachable} reachable, {failed} unreachable",{failed:l.failed,reachable:l.reachable}):r("{reachable} reachable",{reachable:l.reachable}),e[2]=l.failed,e[3]=l.reachable,e[4]=r,e[5]=i):i=e[5];let n;e[6]!==u||e[7]!==i?(n=(0,t.jsx)(me,{label:u,testId:"mt-agg-shards",value:i}),e[6]=u,e[7]=i,e[8]=n):n=e[8];let h;e[9]!==r?(h=r("Total requests"),e[9]=r,e[10]=h):h=e[10];let y;e[11]!==l.totalRequests||e[12]!==h?(y=(0,t.jsx)(me,{label:h,testId:"mt-agg-requests",value:l.totalRequests}),e[11]=l.totalRequests,e[12]=h,e[13]=y):y=e[13];let w;e[14]!==r?(w=r("Total errors"),e[14]=r,e[15]=w):w=e[15];let g;e[16]!==l.totalErrors||e[17]!==w?(g=(0,t.jsx)(me,{label:w,testId:"mt-agg-errors",value:l.totalErrors}),e[16]=l.totalErrors,e[17]=w,e[18]=g):g=e[18];let c;e[19]!==r?(c=r("Total database size"),e[19]=r,e[20]=c):c=e[20];let f;e[21]!==l.totalDatabaseSize?(f=Ge(l.totalDatabaseSize),e[21]=l.totalDatabaseSize,e[22]=f):f=e[22];let N;e[23]!==c||e[24]!==f?(N=(0,t.jsx)(me,{label:c,testId:"mt-agg-db-size",value:f}),e[23]=c,e[24]=f,e[25]=N):N=e[25];let q;e[26]!==r?(q=r("Combined cache hit rate"),e[26]=r,e[27]=q):q=e[27];let _;e[28]!==l.hitRate||e[29]!==r?(_=l.hitRate===null?r("no cache configured"):`${(l.hitRate*100).toFixed(1)}%`,e[28]=l.hitRate,e[29]=r,e[30]=_):_=e[30];let d;e[31]!==q||e[32]!==_?(d=(0,t.jsx)(me,{label:q,testId:"mt-agg-cache",value:_}),e[31]=q,e[32]=_,e[33]=d):d=e[33];let x;e[34]!==N||e[35]!==d||e[36]!==n||e[37]!==y||e[38]!==g?(x=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3","data-testid":"mt-aggregate-stats",children:[n,y,g,N,d]}),e[34]=N,e[35]=d,e[36]=n,e[37]=y,e[38]=g,e[39]=x):x=e[39];let p;e[40]!==r?(p=r("shard"),e[40]=r,e[41]=p):p=e[41];let b;e[42]!==p?(b=(0,t.jsx)(ce,{children:p}),e[42]=p,e[43]=b):b=e[43];let M;e[44]!==r?(M=r("requests"),e[44]=r,e[45]=M):M=e[45];let $;e[46]!==M?($=(0,t.jsx)(ce,{children:M}),e[46]=M,e[47]=$):$=e[47];let S;e[48]!==r?(S=r("errors"),e[48]=r,e[49]=S):S=e[49];let I;e[50]!==S?(I=(0,t.jsx)(ce,{children:S}),e[50]=S,e[51]=I):I=e[51];let C;e[52]!==r?(C=r("db size"),e[52]=r,e[53]=C):C=e[53];let F;e[54]!==C?(F=(0,t.jsx)(ce,{children:C}),e[54]=C,e[55]=F):F=e[55];let k;e[56]!==b||e[57]!==$||e[58]!==I||e[59]!==F?(k=(0,t.jsx)(lt,{children:(0,t.jsxs)(je,{children:[b,$,I,F]})}),e[56]=b,e[57]=$,e[58]=I,e[59]=F,e[60]=k):k=e[60];let v;if(e[61]!==a||e[62]!==r){let A;e[64]!==r?(A=o(D=>(0,t.jsxs)(je,{"data-testid":`mt-agg-row-${D.shard}`,children:[(0,t.jsx)(U,{children:D.shard}),D.metrics===null?(0,t.jsx)(U,{className:"text-destructive",colSpan:3,children:D.error??r("unreachable")}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(U,{className:"tabular-nums",children:D.metrics.requests}),(0,t.jsx)(U,{className:"tabular-nums",children:D.metrics.errors}),(0,t.jsx)(U,{className:"tabular-nums",children:Ge(D.metrics.databaseSize)})]})]},D.shard),"O"),e[64]=r,e[65]=A):A=e[65],v=a.map(A),e[61]=a,e[62]=r,e[63]=v}else v=e[63];let T;e[66]!==v?(T=(0,t.jsx)(nt,{children:v}),e[66]=v,e[67]=T):T=e[67];let O;e[68]!==k||e[69]!==T?(O=(0,t.jsx)(fe,{className:"overflow-hidden py-0",children:(0,t.jsx)(pe,{className:"px-0",children:(0,t.jsxs)(st,{"data-testid":"mt-agg-table",children:[k,T]})})}),e[68]=k,e[69]=T,e[70]=O):O=e[70];let z;return e[71]!==x||e[72]!==O?(z=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"mt-aggregate-view",children:[x,O]}),e[71]=x,e[72]=O,e[73]=z):z=e[73],z},"tr"),rr=o(s=>{let e=Math.floor(s/1e3),l=Math.floor(e/3600),a=Math.floor(e%3600/60),r=e%60;return l>0?`${l.toString()}h ${a.toString()}m`:a>0?`${a.toString()}m ${r.toString()}s`:`${r.toString()}s`},"rr"),ar=o((s,e)=>{let l=s+e;return l===0?"\u2014":`${(s/l*100).toFixed(1)}%`},"sr"),jt=o(s=>s<=0?"\u2014":s<1?`${(s*1e3).toFixed(0)}\u03BCs`:s<1e3?`${s.toFixed(1)}ms`:`${(s/1e3).toFixed(2)}s`,"ct"),sr=o(s=>{let e=(0,xe.c)(75),{currentDelta:l,errorRate:a,history:r,latencyPercentiles:u,metrics:i}=s,n=ge(),{cache:h}=i,y;e[0]!==r||e[1]!==n?(y=r.length>=2?(0,t.jsx)(it,{ariaLabel:n("Requests per interval over time"),className:"h-7 w-24 text-foreground",series:r,testId:"mt-sparkline"}):void 0,e[0]=r,e[1]=n,e[2]=y):y=e[2];let w;e[3]!==l||e[4]!==r.length||e[5]!==n?(w=r.length>=2?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"font-semibold text-foreground",children:`+${l.toLocaleString()}`})," ",n("last interval")]}):(0,t.jsx)("span",{"data-testid":"mt-sparkline-empty",children:n("collecting samples\u2026")}),e[3]=l,e[4]=r.length,e[5]=n,e[6]=w):w=e[6];let g;e[7]!==n?(g=n("Requests"),e[7]=n,e[8]=g):g=e[8];let c;e[9]!==i.requests||e[10]!==y||e[11]!==w||e[12]!==g?(c=(0,t.jsx)(me,{chart:y,footer:w,label:g,testId:"mt-requests",value:i.requests}),e[9]=i.requests,e[10]=y,e[11]=w,e[12]=g,e[13]=c):c=e[13];let f;e[14]!==a||e[15]!==n?(f=n("{rate} error rate",{rate:a}),e[14]=a,e[15]=n,e[16]=f):f=e[16];let N;e[17]!==n?(N=n("Errors"),e[17]=n,e[18]=N):N=e[18];let q;e[19]!==a||e[20]!==i.errors?(q=(0,t.jsxs)(t.Fragment,{children:[i.errors," (",a,")"]}),e[19]=a,e[20]=i.errors,e[21]=q):q=e[21];let _;e[22]!==f||e[23]!==N||e[24]!==q?(_=(0,t.jsx)(me,{footer:f,label:N,testId:"mt-errors",value:q}),e[22]=f,e[23]=N,e[24]=q,e[25]=_):_=e[25];let d;e[26]!==u.p90?(d=u.p90>0?`P90 ${jt(u.p90)}`:void 0,e[26]=u.p90,e[27]=d):d=e[27];let x;e[28]!==n?(x=n("P95 latency"),e[28]=n,e[29]=x):x=e[29];let p;e[30]!==u.p95?(p=u.p95>0?jt(u.p95):"\u2014",e[30]=u.p95,e[31]=p):p=e[31];let b;e[32]!==x||e[33]!==p||e[34]!==d?(b=(0,t.jsx)(me,{footer:d,label:x,testId:"mt-p95",value:p}),e[32]=x,e[33]=p,e[34]=d,e[35]=b):b=e[35];let M;e[36]!==h||e[37]!==n?(M=h?`${h.entries.toLocaleString()} ${n("cache entries")}`:void 0,e[36]=h,e[37]=n,e[38]=M):M=e[38];let $;e[39]!==n?($=n("Database size"),e[39]=n,e[40]=$):$=e[40];let S;e[41]!==i.databaseSize?(S=Ge(i.databaseSize),e[41]=i.databaseSize,e[42]=S):S=e[42];let I;e[43]!==M||e[44]!==$||e[45]!==S?(I=(0,t.jsx)(me,{footer:M,label:$,testId:"mt-db-size",value:S}),e[43]=M,e[44]=$,e[45]=S,e[46]=I):I=e[46];let C;e[47]!==n?(C=n("Shard"),e[47]=n,e[48]=C):C=e[48];let F;e[49]!==i.shard||e[50]!==C?(F=(0,t.jsx)(me,{label:C,testId:"mt-shard",value:i.shard}),e[49]=i.shard,e[50]=C,e[51]=F):F=e[51];let k;e[52]!==n?(k=n("Uptime"),e[52]=n,e[53]=k):k=e[53];let v;e[54]!==i.uptimeMs?(v=rr(i.uptimeMs),e[54]=i.uptimeMs,e[55]=v):v=e[55];let T;e[56]!==k||e[57]!==v?(T=(0,t.jsx)(me,{label:k,testId:"mt-uptime",value:v}),e[56]=k,e[57]=v,e[58]=T):T=e[58];let O;e[59]!==n?(O=n("Cache hit rate"),e[59]=n,e[60]=O):O=e[60];let z;e[61]!==h||e[62]!==n?(z=h?n("{rate} ({count} entries)",{count:h.entries,rate:ar(h.hits,h.misses)}):n("no cache configured"),e[61]=h,e[62]=n,e[63]=z):z=e[63];let A;e[64]!==O||e[65]!==z?(A=(0,t.jsx)(me,{label:O,testId:"mt-cache",value:z}),e[64]=O,e[65]=z,e[66]=A):A=e[66];let D;return e[67]!==b||e[68]!==I||e[69]!==F||e[70]!==T||e[71]!==A||e[72]!==c||e[73]!==_?(D=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4","data-testid":"mt-stats",children:[c,_,b,I,F,T,A]}),e[67]=b,e[68]=I,e[69]=F,e[70]=T,e[71]=A,e[72]=c,e[73]=_,e[74]=D):D=e[74],D},"lr"),Xe=o(s=>s>=100?"critical":s>=50?"warning":"good","Ve"),Qe=o(s=>s<1?`${(s*1e3).toFixed(0)}\u03BCs`:s<1e3?`${s.toFixed(1)}ms`:`${(s/1e3).toFixed(2)}s`,"Ae"),Ve=o(s=>s>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString(),"He"),lr=o(s=>{let e=(0,xe.c)(3),{level:l}=s;if(l==="critical"){let r;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=(0,t.jsx)(We,{variant:"destructive",children:"Slow"}),e[0]=r):r=e[0],r}if(l==="warning"){let r;return e[1]===Symbol.for("react.memo_cache_sentinel")?(r=(0,t.jsx)("span",{className:"inline-flex items-center gap-1 rounded-md border border-transparent bg-warning/10 px-2 py-0.5 text-xs font-medium text-warning",children:"Moderate"}),e[1]=r):r=e[1],r}let a;return e[2]===Symbol.for("react.memo_cache_sentinel")?(a=(0,t.jsx)("span",{className:"inline-flex items-center gap-1 rounded-md border border-transparent bg-success/10 px-2 py-0.5 text-xs font-medium text-success",children:"Fast"}),e[2]=a):a=e[2],a},"ir"),nr=o((s,e)=>{let l=[...s];return l.sort((a,r)=>{switch(e){case"avgTime":return r.avgDurationMs-a.avgDurationMs;case"execCount":return r.execCount-a.execCount;case"rowsRead":return r.rowsRead-a.rowsRead;default:return r.totalDurationMs-a.totalDurationMs}}),l},"ar"),ir=o(s=>{let e=(0,xe.c)(161),{queryStats:l}=s,a=ge(),[r,u]=(0,P.useState)("totalTime"),i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i=new Set,e[0]=i):i=e[0];let[n,h]=(0,P.useState)(i),y;e[1]===Symbol.for("react.memo_cache_sentinel")?(y=o(C=>{C!==null&&u(C)},"v"),e[1]=y):y=e[1];let w=y,g,c,f,N,q,_,d,x,p,b;if(e[2]!==n||e[3]!==l||e[4]!==r||e[5]!==a){f=Symbol.for("react.early_return_sentinel");e:{let C=nr(l,r),F;e[16]!==l?(F=l.filter(or),e[16]=l,e[17]=F):F=e[17];let k=F.length,v;e[18]!==l?(v=l.filter(dr),e[18]=l,e[19]=v):v=e[19];let T=v.length,O;e[20]!==l?(O=l.filter(cr),e[20]=l,e[21]=O):O=e[21];let z=O.length,A;e[22]===Symbol.for("react.memo_cache_sentinel")?(A=o(R=>{h(ue=>{let H=new Set(ue);return H.has(R)?H.delete(R):H.add(R),H})},"O"),e[22]=A):A=e[22];let D=A;if(l.length===0){let R;e[23]!==a?(R=a("No query insights yet"),e[23]=a,e[24]=R):R=e[24];let ue;e[25]!==R?(ue=(0,t.jsx)("p",{className:"text-lg font-medium","data-testid":"qi-empty",children:R}),e[25]=R,e[26]=ue):ue=e[26];let H;e[27]!==a?(H=a("Query insights appear once statements are executed against this shard."),e[27]=a,e[28]=H):H=e[28];let he;e[29]!==H?(he=(0,t.jsx)("p",{className:"mt-1 text-sm",children:H}),e[29]=H,e[30]=he):he=e[30];let Ue;e[31]!==ue||e[32]!==he?(Ue=(0,t.jsx)(fe,{children:(0,t.jsx)(pe,{className:"py-12",children:(0,t.jsxs)("div",{className:"text-center text-muted-foreground",children:[ue,he]})})}),e[31]=ue,e[32]=he,e[33]=Ue):Ue=e[33],f=Ue;break e}d="space-y-4",x="qi-root";let L;e[34]!==a?(L=a("Critical queries"),e[34]=a,e[35]=L):L=e[35];let Q;e[36]!==L?(Q=(0,t.jsx)(Ae,{className:"pb-2",children:(0,t.jsx)(Ke,{className:"text-sm font-medium",children:L})}),e[36]=L,e[37]=Q):Q=e[37];let K;e[38]!==k?(K=(0,t.jsx)("div",{className:"text-2xl font-bold text-destructive","data-testid":"qi-critical",children:k}),e[38]=k,e[39]=K):K=e[39];let W;e[40]!==a?(W=a(">100ms avg execution"),e[40]=a,e[41]=W):W=e[41];let G;e[42]!==W?(G=(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:W}),e[42]=W,e[43]=G):G=e[43];let V;e[44]!==K||e[45]!==G?(V=(0,t.jsxs)(pe,{children:[K,G]}),e[44]=K,e[45]=G,e[46]=V):V=e[46];let X;e[47]!==Q||e[48]!==V?(X=(0,t.jsxs)(fe,{children:[Q,V]}),e[47]=Q,e[48]=V,e[49]=X):X=e[49];let Y;e[50]!==a?(Y=a("Moderate queries"),e[50]=a,e[51]=Y):Y=e[51];let Z;e[52]!==Y?(Z=(0,t.jsx)(Ae,{className:"pb-2",children:(0,t.jsx)(Ke,{className:"text-sm font-medium",children:Y})}),e[52]=Y,e[53]=Z):Z=e[53];let E;e[54]!==T?(E=(0,t.jsx)("div",{className:"text-2xl font-bold text-warning","data-testid":"qi-moderate",children:T}),e[54]=T,e[55]=E):E=e[55];let ee;e[56]!==a?(ee=a("50\u2013100ms avg execution"),e[56]=a,e[57]=ee):ee=e[57];let te;e[58]!==ee?(te=(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:ee}),e[58]=ee,e[59]=te):te=e[59];let re;e[60]!==E||e[61]!==te?(re=(0,t.jsxs)(pe,{children:[E,te]}),e[60]=E,e[61]=te,e[62]=re):re=e[62];let ae;e[63]!==Z||e[64]!==re?(ae=(0,t.jsxs)(fe,{children:[Z,re]}),e[63]=Z,e[64]=re,e[65]=ae):ae=e[65];let se;e[66]!==a?(se=a("Fast queries"),e[66]=a,e[67]=se):se=e[67];let le;e[68]!==se?(le=(0,t.jsx)(Ae,{className:"pb-2",children:(0,t.jsx)(Ke,{className:"text-sm font-medium",children:se})}),e[68]=se,e[69]=le):le=e[69];let ne;e[70]!==z?(ne=(0,t.jsx)("div",{className:"text-2xl font-bold text-success","data-testid":"qi-fast",children:z}),e[70]=z,e[71]=ne):ne=e[71];let ie;e[72]!==a?(ie=a("<50ms avg execution"),e[72]=a,e[73]=ie):ie=e[73];let oe;e[74]!==ie?(oe=(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:ie}),e[74]=ie,e[75]=oe):oe=e[75];let m;e[76]!==ne||e[77]!==oe?(m=(0,t.jsxs)(pe,{children:[ne,oe]}),e[76]=ne,e[77]=oe,e[78]=m):m=e[78];let j;e[79]!==le||e[80]!==m?(j=(0,t.jsxs)(fe,{children:[le,m]}),e[79]=le,e[80]=m,e[81]=j):j=e[81],e[82]!==X||e[83]!==ae||e[84]!==j?(p=(0,t.jsxs)("div",{className:"grid gap-4 md:grid-cols-3",children:[X,ae,j]}),e[82]=X,e[83]=ae,e[84]=j,e[85]=p):p=e[85];let J;e[86]!==a?(J=a("Query leaderboard"),e[86]=a,e[87]=J):J=e[87];let B;e[88]!==J?(B=(0,t.jsx)("h3",{className:"text-lg font-semibold",children:J}),e[88]=J,e[89]=B):B=e[89];let de;e[90]!==r||e[91]!==a?(de=a("Slow queries sorted by {sortField}",{sortField:a(r)}),e[90]=r,e[91]=a,e[92]=de):de=e[92];let be;e[93]!==de?(be=(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:de}),e[93]=de,e[94]=be):be=e[94];let ve;e[95]!==B||e[96]!==be?(ve=(0,t.jsxs)("div",{children:[B,be]}),e[95]=B,e[96]=be,e[97]=ve):ve=e[97];let ye;e[98]!==a?(ye=a("Sort by"),e[98]=a,e[99]=ye):ye=e[99];let Ne;e[100]!==ye?(Ne=(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:ye}),e[100]=ye,e[101]=Ne):Ne=e[101];let Se;e[102]!==a?(Se=a("Sort queries by"),e[102]=a,e[103]=Se):Se=e[103];let Je;e[104]===Symbol.for("react.memo_cache_sentinel")?(Je=(0,t.jsx)(Ct,{}),e[104]=Je):Je=e[104];let we;e[105]!==Se?(we=(0,t.jsx)(It,{"aria-label":Se,className:"w-[140px]","data-testid":"qi-sort",children:Je}),e[105]=Se,e[106]=we):we=e[106];let qe;e[107]!==a?(qe=a("Total time"),e[107]=a,e[108]=qe):qe=e[108];let Me;e[109]!==qe?(Me=(0,t.jsx)(Pe,{value:"totalTime",children:qe}),e[109]=qe,e[110]=Me):Me=e[110];let ke;e[111]!==a?(ke=a("Avg time"),e[111]=a,e[112]=ke):ke=e[112];let _e;e[113]!==ke?(_e=(0,t.jsx)(Pe,{value:"avgTime",children:ke}),e[113]=ke,e[114]=_e):_e=e[114];let $e;e[115]!==a?($e=a("Execution count"),e[115]=a,e[116]=$e):$e=e[116];let De;e[117]!==$e?(De=(0,t.jsx)(Pe,{value:"execCount",children:$e}),e[117]=$e,e[118]=De):De=e[118];let Ce;e[119]!==a?(Ce=a("Rows read"),e[119]=a,e[120]=Ce):Ce=e[120];let Ie;e[121]!==Ce?(Ie=(0,t.jsx)(Pe,{value:"rowsRead",children:Ce}),e[121]=Ce,e[122]=Ie):Ie=e[122];let Fe;e[123]!==Me||e[124]!==_e||e[125]!==De||e[126]!==Ie?(Fe=(0,t.jsxs)(Ft,{children:[Me,_e,De,Ie]}),e[123]=Me,e[124]=_e,e[125]=De,e[126]=Ie,e[127]=Fe):Fe=e[127];let Te;e[128]!==r||e[129]!==we||e[130]!==Fe?(Te=(0,t.jsxs)(Dt,{onValueChange:w,value:r,children:[we,Fe]}),e[128]=r,e[129]=we,e[130]=Fe,e[131]=Te):Te=e[131];let Re;e[132]!==Ne||e[133]!==Te?(Re=(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[Ne,Te]}),e[132]=Ne,e[133]=Te,e[134]=Re):Re=e[134],e[135]!==ve||e[136]!==Re?(b=(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[ve,Re]}),e[135]=ve,e[136]=Re,e[137]=b):b=e[137],c=fe;let Oe;e[138]!==a?(Oe=a("Statements"),e[138]=a,e[139]=Oe):Oe=e[139];let Be;e[140]!==Oe?(Be=(0,t.jsx)(Ke,{children:Oe}),e[140]=Oe,e[141]=Be):Be=e[141],_=(0,t.jsxs)(Ae,{children:[Be,(0,t.jsx)(ut,{children:a("{count} tracked statements",{count:C.length})})]}),g=pe,N="space-y-2";let He;e[142]!==n||e[143]!==a?(He=o(R=>{let ue=R.normalizedSql,H=n.has(ue),he=Xe(R.avgDurationMs);return(0,t.jsxs)("div",{className:"overflow-hidden rounded-lg border","data-testid":"qi-row",children:[(0,t.jsxs)("button",{"aria-expanded":H,className:"flex w-full items-center justify-between p-3 text-left transition-colors hover:bg-muted/50",onClick:o(()=>{D(ue)},"onClick"),type:"button",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[(0,t.jsx)(lr,{level:he}),(0,t.jsx)("span",{className:"max-w-[300px] truncate font-mono text-sm lg:max-w-[500px]",children:R.normalizedSql})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-4",children:[(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Qe(R.totalDurationMs)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("total")})]}),(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Qe(R.avgDurationMs)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("avg")})]}),R.p95DurationMs!==void 0&&(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Qe(R.p95DurationMs)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("p95")})]}),(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Ve(R.execCount)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("calls")})]})]})]}),H&&(0,t.jsxs)("div",{className:"space-y-3 border-t bg-muted/30 p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"mb-2 text-sm font-medium",children:a("Full statement")}),(0,t.jsx)("pre",{className:"overflow-x-auto rounded-md bg-muted p-3 font-mono text-sm whitespace-pre-wrap break-all",children:R.normalizedSql})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 text-sm md:grid-cols-4",children:[R.p50DurationMs!==void 0&&(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("p50")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Qe(R.p50DurationMs)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Exec count")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Ve(R.execCount)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Total time")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Qe(R.totalDurationMs)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Rows read")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Ve(R.rowsRead)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Rows written")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Ve(R.rowsWritten)})]})]})]})]},ue)},"Ke"),e[142]=n,e[143]=a,e[144]=He):He=e[144],q=C.map(He)}e[2]=n,e[3]=l,e[4]=r,e[5]=a,e[6]=g,e[7]=c,e[8]=f,e[9]=N,e[10]=q,e[11]=_,e[12]=d,e[13]=x,e[14]=p,e[15]=b}else g=e[6],c=e[7],f=e[8],N=e[9],q=e[10],_=e[11],d=e[12],x=e[13],p=e[14],b=e[15];if(f!==Symbol.for("react.early_return_sentinel"))return f;let M;e[145]!==N||e[146]!==q?(M=(0,t.jsx)("div",{className:N,children:q}),e[145]=N,e[146]=q,e[147]=M):M=e[147];let $;e[148]!==g||e[149]!==M?($=(0,t.jsx)(g,{children:M}),e[148]=g,e[149]=M,e[150]=$):$=e[150];let S;e[151]!==c||e[152]!==$||e[153]!==_?(S=(0,t.jsxs)(c,{children:[_,$]}),e[151]=c,e[152]=$,e[153]=_,e[154]=S):S=e[154];let I;return e[155]!==S||e[156]!==d||e[157]!==x||e[158]!==p||e[159]!==b?(I=(0,t.jsxs)("div",{className:d,"data-testid":x,children:[p,b,S]}),e[155]=S,e[156]=d,e[157]=x,e[158]=p,e[159]=b,e[160]=I):I=e[160],I},"nr");function or(s){return Xe(s.avgDurationMs)==="critical"}o(or,"or");function dr(s){return Xe(s.avgDurationMs)==="warning"}o(dr,"cr");function cr(s){return Xe(s.avgDurationMs)==="good"}o(cr,"dr");var mr=["1m","5m","15m","1h"],ur=o(s=>new Date(s).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),"ur"),hr=o(s=>s.map(e=>({avg:Math.round(e.avgDurationMs*100)/100,execs:e.execCount,label:ur(e.bucketMs)})),"fr"),gr=o(({shardKey:s=""})=>{let e=ge(),[l,a]=(0,P.useState)("15m"),r=Le(ze.getQueryInsights,{range:l},{live:!0,shardKey:s}).data,u=hr(r?.buckets??[]);return(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"qi-range",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("div",{className:"flex gap-1 rounded-lg border border-border p-0.5","data-testid":"qi-ranges",role:"group",children:mr.map(i=>(0,t.jsx)("button",{"aria-pressed":i===l,className:mt("rounded px-2 py-1 text-xs outline-none transition-colors hover:bg-accent focus-visible:bg-accent",i===l&&"bg-accent font-medium text-foreground"),"data-testid":`qi-range-${i}`,onClick:o(()=>{a(i)},"onClick"),type:"button",children:i},i))}),r?.capped===!0&&(0,t.jsx)(We,{"data-testid":"qi-capped",variant:"secondary",children:e("showing a capped set")})]}),u.length===0?(0,t.jsx)(ht,{description:e("Statements executed in the selected window appear here, with throughput and latency over time."),testId:"qi-empty",title:e("No queries in this window.")}):(0,t.jsxs)("div",{className:"grid gap-4 lg:grid-cols-2",children:[(0,t.jsxs)("figure",{className:"rounded-xl border border-border p-3","data-testid":"qi-throughput",children:[(0,t.jsx)("figcaption",{className:"mb-2 text-xs font-medium text-muted-foreground",children:e("Throughput")}),(0,t.jsx)(Ee,{height:140,width:"100%",children:(0,t.jsxs)(St,{data:u,children:[(0,t.jsx)(tt,{strokeDasharray:"3 3",vertical:!1}),(0,t.jsx)(rt,{dataKey:"label",fontSize:10,tickLine:!1}),(0,t.jsx)(at,{allowDecimals:!1,fontSize:10,tickLine:!1,width:32}),(0,t.jsx)(et,{}),(0,t.jsx)(yt,{dataKey:"execs",fill:"var(--color-primary)",fillOpacity:.15,stroke:"var(--color-primary)",type:"monotone"})]})})]}),(0,t.jsxs)("figure",{className:"rounded-xl border border-border p-3","data-testid":"qi-latency",children:[(0,t.jsx)("figcaption",{className:"mb-2 text-xs font-medium text-muted-foreground",children:e("Mean latency (ms)")}),(0,t.jsx)(Ee,{height:140,width:"100%",children:(0,t.jsxs)(Nt,{data:u,children:[(0,t.jsx)(tt,{strokeDasharray:"3 3",vertical:!1}),(0,t.jsx)(rt,{dataKey:"label",fontSize:10,tickLine:!1}),(0,t.jsx)(at,{fontSize:10,tickLine:!1,width:32}),(0,t.jsx)(et,{}),(0,t.jsx)(vt,{dataKey:"avg",dot:!1,stroke:"var(--color-destructive)",type:"monotone"})]})})]})]}),(0,t.jsx)(ir,{queryStats:r?.entries??[]})]})},"hr"),fr=gt(ze.getMetrics),pr=o((s,e)=>s?e:"overview","pr"),jr=o(({initialShardKey:s})=>{let e=ct(),l=ge(),{queryShardKey:a,setShardKey:r,shardKey:u}=kt(s),[i,n]=(0,P.useState)("overview"),[h,y]=(0,P.useState)([]),w=(0,P.useRef)(null),g=(0,P.useRef)(null),c=(0,P.useRef)(!0);(0,P.useEffect)(()=>(c.current=!0,()=>{c.current=!1}),[]);let f=Rt(a),{data:N,error:q,liveError:_}=Le(ze.getMetrics,{},{live:!0,shardKey:a}),d=N??null;(0,P.useEffect)(()=>{if(N===void 0)return;qt(a);let D=N,L=w.current,Q=g.current!==null&&g.current!==D.shard;if(g.current=D.shard,w.current=D.requests,Q){y([]);return}L!==null&&D.requests>=L&&y(K=>[...K,D.requests-L].slice(-30))},[N,a]);let[x,p]=(0,P.useState)(null),[b,M]=(0,P.useState)(!1),$=o(async()=>{M(!0);let D=zt(u,wt());try{let L=await Promise.all(D.map(async Q=>{try{let K=await e.query(fr,{},ft(Q));return{error:null,metrics:K,shard:Q===""?K.shard:Q}}catch(K){return{error:pt(K),metrics:null,shard:Q===""?"__root__":Q}}}));c.current&&p(L)}finally{c.current&&M(!1)}},"R"),S=x===null?null:Ot(x),I=d===null||d.requests===0?"\u2014":`${(d.errors/d.requests*100).toFixed(1)}%`,C=h.length>0?h.at(-1):0,F=d?At(d):{p90:0,p95:0},k=(0,P.useMemo)(()=>{if(!d||!("queryStats"in d))return;let D=d.queryStats;if(!(!D||!Array.isArray(D)))return Kt(D)},[d]),v=pr(k!==void 0,i),T=o(()=>{bt($())},"D"),O=o(()=>{p(null)},"F"),z=o(()=>{n("overview")},"A"),A=o(()=>{n("query-insights")},"O");return(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-metrics",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(Mt,{onChange:r,testId:"mt-shard-input",value:u}),(0,t.jsx)(_t,{message:_,prefix:"mt"}),(0,t.jsx)(Ze,{"data-testid":"mt-aggregate",disabled:b,onClick:T,size:"sm",type:"button",variant:"secondary",children:l(b?"Aggregating\u2026":"All shards")}),x!==null&&(0,t.jsx)(Ze,{"data-testid":"mt-aggregate-clear",onClick:O,size:"sm",type:"button",variant:"ghost",children:l("Hide")}),(0,t.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline","data-testid":"mt-cf-link",href:$t,rel:"noreferrer",target:"_blank",children:l("Open in Cloudflare")})]}),q!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"mt-error",role:"alert",children:q}),k!==void 0&&(0,t.jsxs)("div",{className:"flex gap-2 border-b","data-testid":"mt-tabs",children:[(0,t.jsx)("button",{className:`pb-2 text-sm font-medium transition-colors ${v==="overview"?"border-b-2 border-primary text-foreground":"text-muted-foreground hover:text-foreground"}`,"data-testid":"mt-tab-overview",onClick:z,type:"button",children:l("Overview")}),(0,t.jsxs)("button",{className:`pb-2 text-sm font-medium transition-colors ${v==="query-insights"?"border-b-2 border-primary text-foreground":"text-muted-foreground hover:text-foreground"}`,"data-testid":"mt-tab-query-insights",onClick:A,type:"button",children:[l("Query insights"),k.length>0&&(0,t.jsx)("span",{className:"ml-1.5 rounded-full bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:k.length})]})]}),v==="query-insights"&&k!==void 0&&(0,t.jsx)(gr,{shardKey:a}),v==="overview"&&d!==null&&(0,t.jsx)(sr,{currentDelta:C,errorRate:I,history:h,latencyPercentiles:F,metrics:d}),v==="overview"&&d===null&&null,v==="overview"&&(0,t.jsx)(er,{onOpenTrace:f,shardKey:a}),v==="overview"&&S!==null&&x!==null&&(0,t.jsx)(tr,{aggregate:S,shardResults:x})]})},"jr");export{jr as MetricsPanel};
|
|
1
|
+
import{a as me}from"./chunk-F7UC63UN.js";import{a as Ot,b as zt,c as At,d as Kt}from"./chunk-SUDJTC4S.js";import{a as it}from"./chunk-CBNGOAD4.js";import{a as Dt,b as Ct,c as It,d as Ft,e as Pe}from"./chunk-IHMGCHAA.js";import{a as Tt}from"./chunk-RPQL45FL.js";import{a as Rt}from"./chunk-GGPSI4ZR.js";import"./chunk-4GTO7FL5.js";import"./chunk-4JLGLPWV.js";import{e as $t}from"./chunk-UYEZR3BI.js";import"./chunk-V3CZW3JB.js";import{a as _t}from"./chunk-BOTGXX4H.js";import"./chunk-GMS77BZD.js";import"./chunk-3Q2P62UR.js";import"./chunk-AWHXPIXU.js";import"./chunk-V3VJAA4D.js";import{a as Ee,b as et,c as tt,d as vt,e as yt,f as rt,g as at,h as Nt,i as St}from"./chunk-URBHAYYZ.js";import"./chunk-5JDWLCSH.js";import"./chunk-EVTM6Q43.js";import{a as kt}from"./chunk-S3CRZLGS.js";import{a as Mt}from"./chunk-2DX5MROH.js";import{a as wt,b as qt}from"./chunk-OGUKYRFM.js";import"./chunk-6D6Z2KXU.js";import"./chunk-OKG3HWSJ.js";import"./chunk-PLHA3OWK.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{a as Ze}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as We}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import"./chunk-35DM4JJG.js";import{a as ze}from"./chunk-4ZEL6BYL.js";import{c as Le}from"./chunk-SDHFSBNM.js";import{f as ct}from"./chunk-B6RRRJP5.js";import"./chunk-FSRSK4LY.js";import"./chunk-2Y6PXGIS.js";import{a as ht}from"./chunk-FKVZRPV5.js";import{a as st,b as lt,c as nt,d as je,e as ce,f as U}from"./chunk-HEAQVSNS.js";import{a as fe,b as Ae,c as Ke,d as ut,e as pe}from"./chunk-WUWBZPUK.js";import{d as ge,f as gt,g as ft,h as pt,i as xt,l as Ge,o as bt}from"./chunk-FODLDLE2.js";import{a as o,d as Ye,e as Jt,f as Bt,g as Ht,i as mt}from"./chunk-YKXDMIHQ.js";var P=Ye(Jt(),1);var xe=Ye(Bt(),1);var t=Ye(Ht(),1);var Ut=/["\\\u0000-\u001F\uD800-\uDFFF]/,Lt=o(s=>Ut.test(s)?JSON.stringify(s):`"${s}"`,"ot"),dt=o(s=>{if(s===void 0)return"null";if(typeof s=="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 s=="number"){if(Number.isNaN(s))return"nan";if(s===1/0)return"inf";if(s===-1/0)return"-inf";if(Object.is(s,-0))return"-0"}if(typeof s=="string")return Lt(s);if(s===null||typeof s!="object")return JSON.stringify(s);if(Array.isArray(s)){let i="[";for(let n=0;n<s.length;n++)n>0&&(i+=","),i+=dt(s[n]);return i+"]"}let e=Object.getPrototypeOf(s);if(e!==null&&e!==Object.prototype){let i=s.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${i} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let l=s,a=Object.keys(l).sort(),r="{",u=!0;for(let i of a){let n=l[i];n!==void 0&&(u?u=!1:r+=",",r+=Lt(i),r+=":",r+=dt(n))}return r+"}"},"Ze"),Pt=o((s,e,l)=>`${s}:${e}:${dt(l??{})}`,"ht"),Qt=o((s,e)=>s==="gauge"?e.last:s==="histogram"?e.sum/Math.max(1,e.count):e.sum,"gt"),Wt=o((s,e)=>Qt(s,e),"Jt"),Gt=o(s=>Qt(s.kind,s),"Vt"),ot=o(s=>Number.isInteger(s)?s.toLocaleString():s.toLocaleString(void 0,{maximumFractionDigits:2}),"We"),Vt=o(s=>Array.isArray(s?.series)?s.series:[],"Gt"),Xt="FUNCTION_NOT_FOUND",Yt=o(s=>{let e=new Map;if(!Array.isArray(s?.series))return e;for(let l of s.series)e.set(Pt(l.kind,l.name,l.attributes),l.points);return e},"Xt"),Zt={counter:"secondary",gauge:"default",histogram:"outline"},Et=o(s=>{let e=(0,xe.c)(18),{name:l,onOpenTrace:a,traceId:r}=s,u=ge();if(r===void 0){let c;return e[0]===Symbol.for("react.memo_cache_sentinel")?(c=(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}),e[0]=c):c=e[0],c}let i;e[1]!==r?(i=r.slice(0,8),e[1]=r,e[2]=i):i=e[2];let n=i;if(a===void 0){let c=`mt-instrument-trace-${l}`,f;return e[3]!==n||e[4]!==c||e[5]!==r?(f=(0,t.jsx)("span",{className:"text-muted-foreground","data-testid":c,title:r,children:n}),e[3]=n,e[4]=c,e[5]=r,e[6]=f):f=e[6],f}let h=`mt-instrument-trace-${l}`,y;e[7]!==a||e[8]!==r?(y=o(()=>{a(r)},"v"),e[7]=a,e[8]=r,e[9]=y):y=e[9];let w;e[10]!==u||e[11]!==r?(w=u("Open the exemplar trace {trace}",{trace:r}),e[10]=u,e[11]=r,e[12]=w):w=e[12];let g;return e[13]!==n||e[14]!==h||e[15]!==y||e[16]!==w?(g=(0,t.jsx)("button",{className:"text-primary underline-offset-4 hover:underline","data-testid":h,onClick:y,title:w,type:"button",children:n}),e[13]=n,e[14]=h,e[15]=y,e[16]=w,e[17]=g):g=e[17],g},"Zt"),er=o(s=>{let e=(0,xe.c)(105),{onOpenTrace:l,shardKey:a}=s,r=ge(),u;e[0]===Symbol.for("react.memo_cache_sentinel")?(u={},e[0]=u):u=e[0];let i;e[1]!==a?(i={live:!0,shardKey:a},e[1]=a,e[2]=i):i=e[2];let{data:n,error:h,errorSource:y}=Le(ze.getMetricSeries,u,i),w;e[3]===Symbol.for("react.memo_cache_sentinel")?(w={},e[3]=w):w=e[3];let g;e[4]!==a?(g={live:!0,shardKey:a},e[4]=a,e[5]=g):g=e[5];let{data:c}=Le(ze.getMetricHistory,w,g),f,N,q,_,d,x,p,b,M,$,S,I,C;if(e[6]!==n||e[7]!==h||e[8]!==y||e[9]!==c||e[10]!==l||e[11]!==r){b=Symbol.for("react.early_return_sentinel");e:{let z=Vt(n),A=xt(y)===Xt;if(h!==null&&!A){let m;e[25]!==r?(m=r("Instruments"),e[25]=r,e[26]=m):m=e[26];let j;e[27]!==m?(j=(0,t.jsx)("h3",{className:"text-sm font-semibold text-foreground",children:m}),e[27]=m,e[28]=j):j=e[28];let J;e[29]!==h||e[30]!==r?(J=r("Instruments unavailable: {error}",{error:h}),e[29]=h,e[30]=r,e[31]=J):J=e[31];let B;e[32]!==J?(B=(0,t.jsx)("span",{className:"text-xs text-muted-foreground","data-testid":"mt-instruments-error",role:"status",children:J}),e[32]=J,e[33]=B):B=e[33];let de;e[34]!==j||e[35]!==B?(de=(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":"mt-instruments",children:[j,B]}),e[34]=j,e[35]=B,e[36]=de):de=e[36],b=de;break e}if(z.length===0){b=null;break e}let D=Yt(c),L;e[37]!==r?(L=o(m=>r(m==="counter"?"Counter":m==="gauge"?"Gauge":"Histogram"),"z"),e[37]=r,e[38]=L):L=e[38];let Q=L;d="flex flex-col gap-2",x="mt-instruments";let K;e[39]!==r?(K=r("Instruments"),e[39]=r,e[40]=K):K=e[40],e[41]!==K?(p=(0,t.jsx)("h3",{className:"text-sm font-semibold text-foreground",children:K}),e[41]=K,e[42]=p):p=e[42],_=fe,C="overflow-hidden py-0",q=pe,I="px-0",N=st,$="mt-instruments-table";let W;e[43]!==r?(W=r("name"),e[43]=r,e[44]=W):W=e[44];let G;e[45]!==W?(G=(0,t.jsx)(ce,{children:W}),e[45]=W,e[46]=G):G=e[46];let V;e[47]!==r?(V=r("kind"),e[47]=r,e[48]=V):V=e[48];let X;e[49]!==V?(X=(0,t.jsx)(ce,{children:V}),e[49]=V,e[50]=X):X=e[50];let Y;e[51]!==r?(Y=r("value"),e[51]=r,e[52]=Y):Y=e[52];let Z;e[53]!==Y?(Z=(0,t.jsx)(ce,{className:"text-right",children:Y}),e[53]=Y,e[54]=Z):Z=e[54];let E;e[55]!==r?(E=r("count"),e[55]=r,e[56]=E):E=e[56];let ee;e[57]!==E?(ee=(0,t.jsx)(ce,{className:"text-right",children:E}),e[57]=E,e[58]=ee):ee=e[58];let te;e[59]!==r?(te=r("range"),e[59]=r,e[60]=te):te=e[60];let re;e[61]!==te?(re=(0,t.jsx)(ce,{className:"text-right",children:te}),e[61]=te,e[62]=re):re=e[62];let ae;e[63]!==r?(ae=r("trend"),e[63]=r,e[64]=ae):ae=e[64];let se;e[65]!==ae?(se=(0,t.jsx)(ce,{children:ae}),e[65]=ae,e[66]=se):se=e[66];let le;e[67]!==r?(le=r("trace"),e[67]=r,e[68]=le):le=e[68];let ne;e[69]!==le?(ne=(0,t.jsx)(ce,{children:le}),e[69]=le,e[70]=ne):ne=e[70];let ie;e[71]!==r?(ie=r("dimensions"),e[71]=r,e[72]=ie):ie=e[72];let oe;e[73]!==ie?(oe=(0,t.jsx)(ce,{children:ie}),e[73]=ie,e[74]=oe):oe=e[74],e[75]!==G||e[76]!==X||e[77]!==Z||e[78]!==ee||e[79]!==re||e[80]!==se||e[81]!==ne||e[82]!==oe?(S=(0,t.jsx)(lt,{children:(0,t.jsxs)(je,{children:[G,X,Z,ee,re,se,ne,oe]})}),e[75]=G,e[76]=X,e[77]=Z,e[78]=ee,e[79]=re,e[80]=se,e[81]=ne,e[82]=oe,e[83]=S):S=e[83],f=nt,M=z.map(m=>{let j=Tt(m.attributes),J=Pt(m.kind,m.name,m.attributes),B=(D.get(J)??[]).map(de=>Wt(m.kind,de));return(0,t.jsxs)(je,{"data-testid":`mt-instrument-${m.name}`,children:[(0,t.jsx)(U,{className:"font-mono text-xs",title:m.functionPath,children:m.name}),(0,t.jsx)(U,{children:(0,t.jsx)(We,{variant:Zt[m.kind],children:Q(m.kind)})}),(0,t.jsx)(U,{className:"text-right font-mono tabular-nums","data-testid":`mt-instrument-value-${m.name}`,children:ot(Gt(m))}),(0,t.jsx)(U,{className:"text-right tabular-nums text-muted-foreground",children:m.count.toLocaleString()}),(0,t.jsx)(U,{className:"text-right font-mono text-xs tabular-nums text-muted-foreground",children:m.min===m.max?"\u2014":`${ot(m.min)}\u2013${ot(m.max)}`}),(0,t.jsx)(U,{children:B.length>=2?(0,t.jsx)(it,{ariaLabel:r("{name} trend",{name:m.name}),className:"h-6 w-24 text-foreground",series:B,testId:`mt-instrument-trend-${m.name}`}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"\u2014"})}),(0,t.jsx)(U,{className:"font-mono text-xs",children:(0,t.jsx)(Et,{name:m.name,onOpenTrace:l,traceId:m.exemplarTraceId})}),(0,t.jsx)(U,{className:"max-w-64 truncate font-mono text-xs text-muted-foreground",title:j,children:j===""?"\u2014":j})]},J)})}e[6]=n,e[7]=h,e[8]=y,e[9]=c,e[10]=l,e[11]=r,e[12]=f,e[13]=N,e[14]=q,e[15]=_,e[16]=d,e[17]=x,e[18]=p,e[19]=b,e[20]=M,e[21]=$,e[22]=S,e[23]=I,e[24]=C}else f=e[12],N=e[13],q=e[14],_=e[15],d=e[16],x=e[17],p=e[18],b=e[19],M=e[20],$=e[21],S=e[22],I=e[23],C=e[24];if(b!==Symbol.for("react.early_return_sentinel"))return b;let F;e[84]!==f||e[85]!==M?(F=(0,t.jsx)(f,{children:M}),e[84]=f,e[85]=M,e[86]=F):F=e[86];let k;e[87]!==N||e[88]!==F||e[89]!==$||e[90]!==S?(k=(0,t.jsxs)(N,{"data-testid":$,children:[S,F]}),e[87]=N,e[88]=F,e[89]=$,e[90]=S,e[91]=k):k=e[91];let v;e[92]!==q||e[93]!==k||e[94]!==I?(v=(0,t.jsx)(q,{className:I,children:k}),e[92]=q,e[93]=k,e[94]=I,e[95]=v):v=e[95];let T;e[96]!==_||e[97]!==v||e[98]!==C?(T=(0,t.jsx)(_,{className:C,children:v}),e[96]=_,e[97]=v,e[98]=C,e[99]=T):T=e[99];let O;return e[100]!==d||e[101]!==x||e[102]!==p||e[103]!==T?(O=(0,t.jsxs)("section",{className:d,"data-testid":x,children:[p,T]}),e[100]=d,e[101]=x,e[102]=p,e[103]=T,e[104]=O):O=e[104],O},"er"),tr=o(s=>{let e=(0,xe.c)(74),{aggregate:l,shardResults:a}=s,r=ge(),u;e[0]!==r?(u=r("Shards"),e[0]=r,e[1]=u):u=e[1];let i;e[2]!==l.failed||e[3]!==l.reachable||e[4]!==r?(i=l.failed>0?r("{reachable} reachable, {failed} unreachable",{failed:l.failed,reachable:l.reachable}):r("{reachable} reachable",{reachable:l.reachable}),e[2]=l.failed,e[3]=l.reachable,e[4]=r,e[5]=i):i=e[5];let n;e[6]!==u||e[7]!==i?(n=(0,t.jsx)(me,{label:u,testId:"mt-agg-shards",value:i}),e[6]=u,e[7]=i,e[8]=n):n=e[8];let h;e[9]!==r?(h=r("Total requests"),e[9]=r,e[10]=h):h=e[10];let y;e[11]!==l.totalRequests||e[12]!==h?(y=(0,t.jsx)(me,{label:h,testId:"mt-agg-requests",value:l.totalRequests}),e[11]=l.totalRequests,e[12]=h,e[13]=y):y=e[13];let w;e[14]!==r?(w=r("Total errors"),e[14]=r,e[15]=w):w=e[15];let g;e[16]!==l.totalErrors||e[17]!==w?(g=(0,t.jsx)(me,{label:w,testId:"mt-agg-errors",value:l.totalErrors}),e[16]=l.totalErrors,e[17]=w,e[18]=g):g=e[18];let c;e[19]!==r?(c=r("Total database size"),e[19]=r,e[20]=c):c=e[20];let f;e[21]!==l.totalDatabaseSize?(f=Ge(l.totalDatabaseSize),e[21]=l.totalDatabaseSize,e[22]=f):f=e[22];let N;e[23]!==c||e[24]!==f?(N=(0,t.jsx)(me,{label:c,testId:"mt-agg-db-size",value:f}),e[23]=c,e[24]=f,e[25]=N):N=e[25];let q;e[26]!==r?(q=r("Combined cache hit rate"),e[26]=r,e[27]=q):q=e[27];let _;e[28]!==l.hitRate||e[29]!==r?(_=l.hitRate===null?r("no cache configured"):`${(l.hitRate*100).toFixed(1)}%`,e[28]=l.hitRate,e[29]=r,e[30]=_):_=e[30];let d;e[31]!==q||e[32]!==_?(d=(0,t.jsx)(me,{label:q,testId:"mt-agg-cache",value:_}),e[31]=q,e[32]=_,e[33]=d):d=e[33];let x;e[34]!==N||e[35]!==d||e[36]!==n||e[37]!==y||e[38]!==g?(x=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3","data-testid":"mt-aggregate-stats",children:[n,y,g,N,d]}),e[34]=N,e[35]=d,e[36]=n,e[37]=y,e[38]=g,e[39]=x):x=e[39];let p;e[40]!==r?(p=r("shard"),e[40]=r,e[41]=p):p=e[41];let b;e[42]!==p?(b=(0,t.jsx)(ce,{children:p}),e[42]=p,e[43]=b):b=e[43];let M;e[44]!==r?(M=r("requests"),e[44]=r,e[45]=M):M=e[45];let $;e[46]!==M?($=(0,t.jsx)(ce,{children:M}),e[46]=M,e[47]=$):$=e[47];let S;e[48]!==r?(S=r("errors"),e[48]=r,e[49]=S):S=e[49];let I;e[50]!==S?(I=(0,t.jsx)(ce,{children:S}),e[50]=S,e[51]=I):I=e[51];let C;e[52]!==r?(C=r("db size"),e[52]=r,e[53]=C):C=e[53];let F;e[54]!==C?(F=(0,t.jsx)(ce,{children:C}),e[54]=C,e[55]=F):F=e[55];let k;e[56]!==b||e[57]!==$||e[58]!==I||e[59]!==F?(k=(0,t.jsx)(lt,{children:(0,t.jsxs)(je,{children:[b,$,I,F]})}),e[56]=b,e[57]=$,e[58]=I,e[59]=F,e[60]=k):k=e[60];let v;if(e[61]!==a||e[62]!==r){let A;e[64]!==r?(A=o(D=>(0,t.jsxs)(je,{"data-testid":`mt-agg-row-${D.shard}`,children:[(0,t.jsx)(U,{children:D.shard}),D.metrics===null?(0,t.jsx)(U,{className:"text-destructive",colSpan:3,children:D.error??r("unreachable")}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(U,{className:"tabular-nums",children:D.metrics.requests}),(0,t.jsx)(U,{className:"tabular-nums",children:D.metrics.errors}),(0,t.jsx)(U,{className:"tabular-nums",children:Ge(D.metrics.databaseSize)})]})]},D.shard),"O"),e[64]=r,e[65]=A):A=e[65],v=a.map(A),e[61]=a,e[62]=r,e[63]=v}else v=e[63];let T;e[66]!==v?(T=(0,t.jsx)(nt,{children:v}),e[66]=v,e[67]=T):T=e[67];let O;e[68]!==k||e[69]!==T?(O=(0,t.jsx)(fe,{className:"overflow-hidden py-0",children:(0,t.jsx)(pe,{className:"px-0",children:(0,t.jsxs)(st,{"data-testid":"mt-agg-table",children:[k,T]})})}),e[68]=k,e[69]=T,e[70]=O):O=e[70];let z;return e[71]!==x||e[72]!==O?(z=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"mt-aggregate-view",children:[x,O]}),e[71]=x,e[72]=O,e[73]=z):z=e[73],z},"tr"),rr=o(s=>{let e=Math.floor(s/1e3),l=Math.floor(e/3600),a=Math.floor(e%3600/60),r=e%60;return l>0?`${l.toString()}h ${a.toString()}m`:a>0?`${a.toString()}m ${r.toString()}s`:`${r.toString()}s`},"rr"),ar=o((s,e)=>{let l=s+e;return l===0?"\u2014":`${(s/l*100).toFixed(1)}%`},"sr"),jt=o(s=>s<=0?"\u2014":s<1?`${(s*1e3).toFixed(0)}\u03BCs`:s<1e3?`${s.toFixed(1)}ms`:`${(s/1e3).toFixed(2)}s`,"ct"),sr=o(s=>{let e=(0,xe.c)(75),{currentDelta:l,errorRate:a,history:r,latencyPercentiles:u,metrics:i}=s,n=ge(),{cache:h}=i,y;e[0]!==r||e[1]!==n?(y=r.length>=2?(0,t.jsx)(it,{ariaLabel:n("Requests per interval over time"),className:"h-7 w-24 text-foreground",series:r,testId:"mt-sparkline"}):void 0,e[0]=r,e[1]=n,e[2]=y):y=e[2];let w;e[3]!==l||e[4]!==r.length||e[5]!==n?(w=r.length>=2?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"font-semibold text-foreground",children:`+${l.toLocaleString()}`})," ",n("last interval")]}):(0,t.jsx)("span",{"data-testid":"mt-sparkline-empty",children:n("collecting samples\u2026")}),e[3]=l,e[4]=r.length,e[5]=n,e[6]=w):w=e[6];let g;e[7]!==n?(g=n("Requests"),e[7]=n,e[8]=g):g=e[8];let c;e[9]!==i.requests||e[10]!==y||e[11]!==w||e[12]!==g?(c=(0,t.jsx)(me,{chart:y,footer:w,label:g,testId:"mt-requests",value:i.requests}),e[9]=i.requests,e[10]=y,e[11]=w,e[12]=g,e[13]=c):c=e[13];let f;e[14]!==a||e[15]!==n?(f=n("{rate} error rate",{rate:a}),e[14]=a,e[15]=n,e[16]=f):f=e[16];let N;e[17]!==n?(N=n("Errors"),e[17]=n,e[18]=N):N=e[18];let q;e[19]!==a||e[20]!==i.errors?(q=(0,t.jsxs)(t.Fragment,{children:[i.errors," (",a,")"]}),e[19]=a,e[20]=i.errors,e[21]=q):q=e[21];let _;e[22]!==f||e[23]!==N||e[24]!==q?(_=(0,t.jsx)(me,{footer:f,label:N,testId:"mt-errors",value:q}),e[22]=f,e[23]=N,e[24]=q,e[25]=_):_=e[25];let d;e[26]!==u.p90?(d=u.p90>0?`P90 ${jt(u.p90)}`:void 0,e[26]=u.p90,e[27]=d):d=e[27];let x;e[28]!==n?(x=n("P95 latency"),e[28]=n,e[29]=x):x=e[29];let p;e[30]!==u.p95?(p=u.p95>0?jt(u.p95):"\u2014",e[30]=u.p95,e[31]=p):p=e[31];let b;e[32]!==x||e[33]!==p||e[34]!==d?(b=(0,t.jsx)(me,{footer:d,label:x,testId:"mt-p95",value:p}),e[32]=x,e[33]=p,e[34]=d,e[35]=b):b=e[35];let M;e[36]!==h||e[37]!==n?(M=h?`${h.entries.toLocaleString()} ${n("cache entries")}`:void 0,e[36]=h,e[37]=n,e[38]=M):M=e[38];let $;e[39]!==n?($=n("Database size"),e[39]=n,e[40]=$):$=e[40];let S;e[41]!==i.databaseSize?(S=Ge(i.databaseSize),e[41]=i.databaseSize,e[42]=S):S=e[42];let I;e[43]!==M||e[44]!==$||e[45]!==S?(I=(0,t.jsx)(me,{footer:M,label:$,testId:"mt-db-size",value:S}),e[43]=M,e[44]=$,e[45]=S,e[46]=I):I=e[46];let C;e[47]!==n?(C=n("Shard"),e[47]=n,e[48]=C):C=e[48];let F;e[49]!==i.shard||e[50]!==C?(F=(0,t.jsx)(me,{label:C,testId:"mt-shard",value:i.shard}),e[49]=i.shard,e[50]=C,e[51]=F):F=e[51];let k;e[52]!==n?(k=n("Uptime"),e[52]=n,e[53]=k):k=e[53];let v;e[54]!==i.uptimeMs?(v=rr(i.uptimeMs),e[54]=i.uptimeMs,e[55]=v):v=e[55];let T;e[56]!==k||e[57]!==v?(T=(0,t.jsx)(me,{label:k,testId:"mt-uptime",value:v}),e[56]=k,e[57]=v,e[58]=T):T=e[58];let O;e[59]!==n?(O=n("Cache hit rate"),e[59]=n,e[60]=O):O=e[60];let z;e[61]!==h||e[62]!==n?(z=h?n("{rate} ({count} entries)",{count:h.entries,rate:ar(h.hits,h.misses)}):n("no cache configured"),e[61]=h,e[62]=n,e[63]=z):z=e[63];let A;e[64]!==O||e[65]!==z?(A=(0,t.jsx)(me,{label:O,testId:"mt-cache",value:z}),e[64]=O,e[65]=z,e[66]=A):A=e[66];let D;return e[67]!==b||e[68]!==I||e[69]!==F||e[70]!==T||e[71]!==A||e[72]!==c||e[73]!==_?(D=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4","data-testid":"mt-stats",children:[c,_,b,I,F,T,A]}),e[67]=b,e[68]=I,e[69]=F,e[70]=T,e[71]=A,e[72]=c,e[73]=_,e[74]=D):D=e[74],D},"lr"),Xe=o(s=>s>=100?"critical":s>=50?"warning":"good","Ve"),Qe=o(s=>s<1?`${(s*1e3).toFixed(0)}\u03BCs`:s<1e3?`${s.toFixed(1)}ms`:`${(s/1e3).toFixed(2)}s`,"Ae"),Ve=o(s=>s>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString(),"He"),lr=o(s=>{let e=(0,xe.c)(3),{level:l}=s;if(l==="critical"){let r;return e[0]===Symbol.for("react.memo_cache_sentinel")?(r=(0,t.jsx)(We,{variant:"destructive",children:"Slow"}),e[0]=r):r=e[0],r}if(l==="warning"){let r;return e[1]===Symbol.for("react.memo_cache_sentinel")?(r=(0,t.jsx)("span",{className:"inline-flex items-center gap-1 rounded-md border border-transparent bg-warning/10 px-2 py-0.5 text-xs font-medium text-warning",children:"Moderate"}),e[1]=r):r=e[1],r}let a;return e[2]===Symbol.for("react.memo_cache_sentinel")?(a=(0,t.jsx)("span",{className:"inline-flex items-center gap-1 rounded-md border border-transparent bg-success/10 px-2 py-0.5 text-xs font-medium text-success",children:"Fast"}),e[2]=a):a=e[2],a},"ir"),nr=o((s,e)=>{let l=[...s];return l.sort((a,r)=>{switch(e){case"avgTime":return r.avgDurationMs-a.avgDurationMs;case"execCount":return r.execCount-a.execCount;case"rowsRead":return r.rowsRead-a.rowsRead;default:return r.totalDurationMs-a.totalDurationMs}}),l},"ar"),ir=o(s=>{let e=(0,xe.c)(161),{queryStats:l}=s,a=ge(),[r,u]=(0,P.useState)("totalTime"),i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i=new Set,e[0]=i):i=e[0];let[n,h]=(0,P.useState)(i),y;e[1]===Symbol.for("react.memo_cache_sentinel")?(y=o(C=>{C!==null&&u(C)},"v"),e[1]=y):y=e[1];let w=y,g,c,f,N,q,_,d,x,p,b;if(e[2]!==n||e[3]!==l||e[4]!==r||e[5]!==a){f=Symbol.for("react.early_return_sentinel");e:{let C=nr(l,r),F;e[16]!==l?(F=l.filter(or),e[16]=l,e[17]=F):F=e[17];let k=F.length,v;e[18]!==l?(v=l.filter(dr),e[18]=l,e[19]=v):v=e[19];let T=v.length,O;e[20]!==l?(O=l.filter(cr),e[20]=l,e[21]=O):O=e[21];let z=O.length,A;e[22]===Symbol.for("react.memo_cache_sentinel")?(A=o(R=>{h(ue=>{let H=new Set(ue);return H.has(R)?H.delete(R):H.add(R),H})},"O"),e[22]=A):A=e[22];let D=A;if(l.length===0){let R;e[23]!==a?(R=a("No query insights yet"),e[23]=a,e[24]=R):R=e[24];let ue;e[25]!==R?(ue=(0,t.jsx)("p",{className:"text-lg font-medium","data-testid":"qi-empty",children:R}),e[25]=R,e[26]=ue):ue=e[26];let H;e[27]!==a?(H=a("Query insights appear once statements are executed against this shard."),e[27]=a,e[28]=H):H=e[28];let he;e[29]!==H?(he=(0,t.jsx)("p",{className:"mt-1 text-sm",children:H}),e[29]=H,e[30]=he):he=e[30];let Ue;e[31]!==ue||e[32]!==he?(Ue=(0,t.jsx)(fe,{children:(0,t.jsx)(pe,{className:"py-12",children:(0,t.jsxs)("div",{className:"text-center text-muted-foreground",children:[ue,he]})})}),e[31]=ue,e[32]=he,e[33]=Ue):Ue=e[33],f=Ue;break e}d="space-y-4",x="qi-root";let L;e[34]!==a?(L=a("Critical queries"),e[34]=a,e[35]=L):L=e[35];let Q;e[36]!==L?(Q=(0,t.jsx)(Ae,{className:"pb-2",children:(0,t.jsx)(Ke,{className:"text-sm font-medium",children:L})}),e[36]=L,e[37]=Q):Q=e[37];let K;e[38]!==k?(K=(0,t.jsx)("div",{className:"text-2xl font-bold text-destructive","data-testid":"qi-critical",children:k}),e[38]=k,e[39]=K):K=e[39];let W;e[40]!==a?(W=a(">100ms avg execution"),e[40]=a,e[41]=W):W=e[41];let G;e[42]!==W?(G=(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:W}),e[42]=W,e[43]=G):G=e[43];let V;e[44]!==K||e[45]!==G?(V=(0,t.jsxs)(pe,{children:[K,G]}),e[44]=K,e[45]=G,e[46]=V):V=e[46];let X;e[47]!==Q||e[48]!==V?(X=(0,t.jsxs)(fe,{children:[Q,V]}),e[47]=Q,e[48]=V,e[49]=X):X=e[49];let Y;e[50]!==a?(Y=a("Moderate queries"),e[50]=a,e[51]=Y):Y=e[51];let Z;e[52]!==Y?(Z=(0,t.jsx)(Ae,{className:"pb-2",children:(0,t.jsx)(Ke,{className:"text-sm font-medium",children:Y})}),e[52]=Y,e[53]=Z):Z=e[53];let E;e[54]!==T?(E=(0,t.jsx)("div",{className:"text-2xl font-bold text-warning","data-testid":"qi-moderate",children:T}),e[54]=T,e[55]=E):E=e[55];let ee;e[56]!==a?(ee=a("50\u2013100ms avg execution"),e[56]=a,e[57]=ee):ee=e[57];let te;e[58]!==ee?(te=(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:ee}),e[58]=ee,e[59]=te):te=e[59];let re;e[60]!==E||e[61]!==te?(re=(0,t.jsxs)(pe,{children:[E,te]}),e[60]=E,e[61]=te,e[62]=re):re=e[62];let ae;e[63]!==Z||e[64]!==re?(ae=(0,t.jsxs)(fe,{children:[Z,re]}),e[63]=Z,e[64]=re,e[65]=ae):ae=e[65];let se;e[66]!==a?(se=a("Fast queries"),e[66]=a,e[67]=se):se=e[67];let le;e[68]!==se?(le=(0,t.jsx)(Ae,{className:"pb-2",children:(0,t.jsx)(Ke,{className:"text-sm font-medium",children:se})}),e[68]=se,e[69]=le):le=e[69];let ne;e[70]!==z?(ne=(0,t.jsx)("div",{className:"text-2xl font-bold text-success","data-testid":"qi-fast",children:z}),e[70]=z,e[71]=ne):ne=e[71];let ie;e[72]!==a?(ie=a("<50ms avg execution"),e[72]=a,e[73]=ie):ie=e[73];let oe;e[74]!==ie?(oe=(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:ie}),e[74]=ie,e[75]=oe):oe=e[75];let m;e[76]!==ne||e[77]!==oe?(m=(0,t.jsxs)(pe,{children:[ne,oe]}),e[76]=ne,e[77]=oe,e[78]=m):m=e[78];let j;e[79]!==le||e[80]!==m?(j=(0,t.jsxs)(fe,{children:[le,m]}),e[79]=le,e[80]=m,e[81]=j):j=e[81],e[82]!==X||e[83]!==ae||e[84]!==j?(p=(0,t.jsxs)("div",{className:"grid gap-4 md:grid-cols-3",children:[X,ae,j]}),e[82]=X,e[83]=ae,e[84]=j,e[85]=p):p=e[85];let J;e[86]!==a?(J=a("Query leaderboard"),e[86]=a,e[87]=J):J=e[87];let B;e[88]!==J?(B=(0,t.jsx)("h3",{className:"text-lg font-semibold",children:J}),e[88]=J,e[89]=B):B=e[89];let de;e[90]!==r||e[91]!==a?(de=a("Slow queries sorted by {sortField}",{sortField:a(r)}),e[90]=r,e[91]=a,e[92]=de):de=e[92];let be;e[93]!==de?(be=(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:de}),e[93]=de,e[94]=be):be=e[94];let ve;e[95]!==B||e[96]!==be?(ve=(0,t.jsxs)("div",{children:[B,be]}),e[95]=B,e[96]=be,e[97]=ve):ve=e[97];let ye;e[98]!==a?(ye=a("Sort by"),e[98]=a,e[99]=ye):ye=e[99];let Ne;e[100]!==ye?(Ne=(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:ye}),e[100]=ye,e[101]=Ne):Ne=e[101];let Se;e[102]!==a?(Se=a("Sort queries by"),e[102]=a,e[103]=Se):Se=e[103];let Je;e[104]===Symbol.for("react.memo_cache_sentinel")?(Je=(0,t.jsx)(Ct,{}),e[104]=Je):Je=e[104];let we;e[105]!==Se?(we=(0,t.jsx)(It,{"aria-label":Se,className:"w-[140px]","data-testid":"qi-sort",children:Je}),e[105]=Se,e[106]=we):we=e[106];let qe;e[107]!==a?(qe=a("Total time"),e[107]=a,e[108]=qe):qe=e[108];let Me;e[109]!==qe?(Me=(0,t.jsx)(Pe,{value:"totalTime",children:qe}),e[109]=qe,e[110]=Me):Me=e[110];let ke;e[111]!==a?(ke=a("Avg time"),e[111]=a,e[112]=ke):ke=e[112];let _e;e[113]!==ke?(_e=(0,t.jsx)(Pe,{value:"avgTime",children:ke}),e[113]=ke,e[114]=_e):_e=e[114];let $e;e[115]!==a?($e=a("Execution count"),e[115]=a,e[116]=$e):$e=e[116];let De;e[117]!==$e?(De=(0,t.jsx)(Pe,{value:"execCount",children:$e}),e[117]=$e,e[118]=De):De=e[118];let Ce;e[119]!==a?(Ce=a("Rows read"),e[119]=a,e[120]=Ce):Ce=e[120];let Ie;e[121]!==Ce?(Ie=(0,t.jsx)(Pe,{value:"rowsRead",children:Ce}),e[121]=Ce,e[122]=Ie):Ie=e[122];let Fe;e[123]!==Me||e[124]!==_e||e[125]!==De||e[126]!==Ie?(Fe=(0,t.jsxs)(Ft,{children:[Me,_e,De,Ie]}),e[123]=Me,e[124]=_e,e[125]=De,e[126]=Ie,e[127]=Fe):Fe=e[127];let Te;e[128]!==r||e[129]!==we||e[130]!==Fe?(Te=(0,t.jsxs)(Dt,{onValueChange:w,value:r,children:[we,Fe]}),e[128]=r,e[129]=we,e[130]=Fe,e[131]=Te):Te=e[131];let Re;e[132]!==Ne||e[133]!==Te?(Re=(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[Ne,Te]}),e[132]=Ne,e[133]=Te,e[134]=Re):Re=e[134],e[135]!==ve||e[136]!==Re?(b=(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[ve,Re]}),e[135]=ve,e[136]=Re,e[137]=b):b=e[137],c=fe;let Oe;e[138]!==a?(Oe=a("Statements"),e[138]=a,e[139]=Oe):Oe=e[139];let Be;e[140]!==Oe?(Be=(0,t.jsx)(Ke,{children:Oe}),e[140]=Oe,e[141]=Be):Be=e[141],_=(0,t.jsxs)(Ae,{children:[Be,(0,t.jsx)(ut,{children:a("{count} tracked statements",{count:C.length})})]}),g=pe,N="space-y-2";let He;e[142]!==n||e[143]!==a?(He=o(R=>{let ue=R.normalizedSql,H=n.has(ue),he=Xe(R.avgDurationMs);return(0,t.jsxs)("div",{className:"overflow-hidden rounded-lg border","data-testid":"qi-row",children:[(0,t.jsxs)("button",{"aria-expanded":H,className:"flex w-full items-center justify-between p-3 text-left transition-colors hover:bg-muted/50",onClick:o(()=>{D(ue)},"onClick"),type:"button",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[(0,t.jsx)(lr,{level:he}),(0,t.jsx)("span",{className:"max-w-[300px] truncate font-mono text-sm lg:max-w-[500px]",children:R.normalizedSql})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-4",children:[(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Qe(R.totalDurationMs)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("total")})]}),(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Qe(R.avgDurationMs)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("avg")})]}),R.p95DurationMs!==void 0&&(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Qe(R.p95DurationMs)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("p95")})]}),(0,t.jsxs)("div",{className:"text-right",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:Ve(R.execCount)}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:a("calls")})]})]})]}),H&&(0,t.jsxs)("div",{className:"space-y-3 border-t bg-muted/30 p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"mb-2 text-sm font-medium",children:a("Full statement")}),(0,t.jsx)("pre",{className:"overflow-x-auto rounded-md bg-muted p-3 font-mono text-sm whitespace-pre-wrap break-all",children:R.normalizedSql})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 text-sm md:grid-cols-4",children:[R.p50DurationMs!==void 0&&(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("p50")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Qe(R.p50DurationMs)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Exec count")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Ve(R.execCount)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Total time")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Qe(R.totalDurationMs)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Rows read")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Ve(R.rowsRead)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:a("Rows written")}),(0,t.jsx)("span",{className:"block font-medium tabular-nums",children:Ve(R.rowsWritten)})]})]})]})]},ue)},"Ke"),e[142]=n,e[143]=a,e[144]=He):He=e[144],q=C.map(He)}e[2]=n,e[3]=l,e[4]=r,e[5]=a,e[6]=g,e[7]=c,e[8]=f,e[9]=N,e[10]=q,e[11]=_,e[12]=d,e[13]=x,e[14]=p,e[15]=b}else g=e[6],c=e[7],f=e[8],N=e[9],q=e[10],_=e[11],d=e[12],x=e[13],p=e[14],b=e[15];if(f!==Symbol.for("react.early_return_sentinel"))return f;let M;e[145]!==N||e[146]!==q?(M=(0,t.jsx)("div",{className:N,children:q}),e[145]=N,e[146]=q,e[147]=M):M=e[147];let $;e[148]!==g||e[149]!==M?($=(0,t.jsx)(g,{children:M}),e[148]=g,e[149]=M,e[150]=$):$=e[150];let S;e[151]!==c||e[152]!==$||e[153]!==_?(S=(0,t.jsxs)(c,{children:[_,$]}),e[151]=c,e[152]=$,e[153]=_,e[154]=S):S=e[154];let I;return e[155]!==S||e[156]!==d||e[157]!==x||e[158]!==p||e[159]!==b?(I=(0,t.jsxs)("div",{className:d,"data-testid":x,children:[p,b,S]}),e[155]=S,e[156]=d,e[157]=x,e[158]=p,e[159]=b,e[160]=I):I=e[160],I},"nr");function or(s){return Xe(s.avgDurationMs)==="critical"}o(or,"or");function dr(s){return Xe(s.avgDurationMs)==="warning"}o(dr,"cr");function cr(s){return Xe(s.avgDurationMs)==="good"}o(cr,"dr");var mr=["1m","5m","15m","1h"],ur=o(s=>new Date(s).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),"ur"),hr=o(s=>s.map(e=>({avg:Math.round(e.avgDurationMs*100)/100,execs:e.execCount,label:ur(e.bucketMs)})),"fr"),gr=o(({shardKey:s=""})=>{let e=ge(),[l,a]=(0,P.useState)("15m"),r=Le(ze.getQueryInsights,{range:l},{live:!0,shardKey:s}).data,u=hr(r?.buckets??[]);return(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"qi-range",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("div",{className:"flex gap-1 rounded-lg border border-border p-0.5","data-testid":"qi-ranges",role:"group",children:mr.map(i=>(0,t.jsx)("button",{"aria-pressed":i===l,className:mt("rounded px-2 py-1 text-xs outline-none transition-colors hover:bg-accent focus-visible:bg-accent",i===l&&"bg-accent font-medium text-foreground"),"data-testid":`qi-range-${i}`,onClick:o(()=>{a(i)},"onClick"),type:"button",children:i},i))}),r?.capped===!0&&(0,t.jsx)(We,{"data-testid":"qi-capped",variant:"secondary",children:e("showing a capped set")})]}),u.length===0?(0,t.jsx)(ht,{description:e("Statements executed in the selected window appear here, with throughput and latency over time."),testId:"qi-empty",title:e("No queries in this window.")}):(0,t.jsxs)("div",{className:"grid gap-4 lg:grid-cols-2",children:[(0,t.jsxs)("figure",{className:"rounded-xl border border-border p-3","data-testid":"qi-throughput",children:[(0,t.jsx)("figcaption",{className:"mb-2 text-xs font-medium text-muted-foreground",children:e("Throughput")}),(0,t.jsx)(Ee,{height:140,width:"100%",children:(0,t.jsxs)(St,{data:u,children:[(0,t.jsx)(tt,{strokeDasharray:"3 3",vertical:!1}),(0,t.jsx)(rt,{dataKey:"label",fontSize:10,tickLine:!1}),(0,t.jsx)(at,{allowDecimals:!1,fontSize:10,tickLine:!1,width:32}),(0,t.jsx)(et,{}),(0,t.jsx)(yt,{dataKey:"execs",fill:"var(--color-primary)",fillOpacity:.15,stroke:"var(--color-primary)",type:"monotone"})]})})]}),(0,t.jsxs)("figure",{className:"rounded-xl border border-border p-3","data-testid":"qi-latency",children:[(0,t.jsx)("figcaption",{className:"mb-2 text-xs font-medium text-muted-foreground",children:e("Mean latency (ms)")}),(0,t.jsx)(Ee,{height:140,width:"100%",children:(0,t.jsxs)(Nt,{data:u,children:[(0,t.jsx)(tt,{strokeDasharray:"3 3",vertical:!1}),(0,t.jsx)(rt,{dataKey:"label",fontSize:10,tickLine:!1}),(0,t.jsx)(at,{fontSize:10,tickLine:!1,width:32}),(0,t.jsx)(et,{}),(0,t.jsx)(vt,{dataKey:"avg",dot:!1,stroke:"var(--color-destructive)",type:"monotone"})]})})]})]}),(0,t.jsx)(ir,{queryStats:r?.entries??[]})]})},"hr"),fr=gt(ze.getMetrics),pr=o((s,e)=>s?e:"overview","pr"),jr=o(({initialShardKey:s})=>{let e=ct(),l=ge(),{queryShardKey:a,setShardKey:r,shardKey:u}=kt(s),[i,n]=(0,P.useState)("overview"),[h,y]=(0,P.useState)([]),w=(0,P.useRef)(null),g=(0,P.useRef)(null),c=(0,P.useRef)(!0);(0,P.useEffect)(()=>(c.current=!0,()=>{c.current=!1}),[]);let f=Rt(a),{data:N,error:q,liveError:_}=Le(ze.getMetrics,{},{live:!0,shardKey:a}),d=N??null;(0,P.useEffect)(()=>{if(N===void 0)return;qt(a);let D=N,L=w.current,Q=g.current!==null&&g.current!==D.shard;if(g.current=D.shard,w.current=D.requests,Q){y([]);return}L!==null&&D.requests>=L&&y(K=>[...K,D.requests-L].slice(-30))},[N,a]);let[x,p]=(0,P.useState)(null),[b,M]=(0,P.useState)(!1),$=o(async()=>{M(!0);let D=zt(u,wt());try{let L=await Promise.all(D.map(async Q=>{try{let K=await e.query(fr,{},ft(Q));return{error:null,metrics:K,shard:Q===""?K.shard:Q}}catch(K){return{error:pt(K),metrics:null,shard:Q===""?"__root__":Q}}}));c.current&&p(L)}finally{c.current&&M(!1)}},"R"),S=x===null?null:Ot(x),I=d===null||d.requests===0?"\u2014":`${(d.errors/d.requests*100).toFixed(1)}%`,C=h.length>0?h.at(-1):0,F=d?At(d):{p90:0,p95:0},k=(0,P.useMemo)(()=>{if(!d||!("queryStats"in d))return;let D=d.queryStats;if(!(!D||!Array.isArray(D)))return Kt(D)},[d]),v=pr(k!==void 0,i),T=o(()=>{bt($())},"D"),O=o(()=>{p(null)},"F"),z=o(()=>{n("overview")},"A"),A=o(()=>{n("query-insights")},"O");return(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-metrics",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(Mt,{onChange:r,testId:"mt-shard-input",value:u}),(0,t.jsx)(_t,{message:_,prefix:"mt"}),(0,t.jsx)(Ze,{"data-testid":"mt-aggregate",disabled:b,onClick:T,size:"sm",type:"button",variant:"secondary",children:l(b?"Aggregating\u2026":"All shards")}),x!==null&&(0,t.jsx)(Ze,{"data-testid":"mt-aggregate-clear",onClick:O,size:"sm",type:"button",variant:"ghost",children:l("Hide")}),(0,t.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline","data-testid":"mt-cf-link",href:$t,rel:"noreferrer",target:"_blank",children:l("Open in Cloudflare")})]}),q!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"mt-error",role:"alert",children:q}),k!==void 0&&(0,t.jsxs)("div",{className:"flex gap-2 border-b","data-testid":"mt-tabs",children:[(0,t.jsx)("button",{className:`pb-2 text-sm font-medium transition-colors ${v==="overview"?"border-b-2 border-primary text-foreground":"text-muted-foreground hover:text-foreground"}`,"data-testid":"mt-tab-overview",onClick:z,type:"button",children:l("Overview")}),(0,t.jsxs)("button",{className:`pb-2 text-sm font-medium transition-colors ${v==="query-insights"?"border-b-2 border-primary text-foreground":"text-muted-foreground hover:text-foreground"}`,"data-testid":"mt-tab-query-insights",onClick:A,type:"button",children:[l("Query insights"),k.length>0&&(0,t.jsx)("span",{className:"ml-1.5 rounded-full bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:k.length})]})]}),v==="query-insights"&&k!==void 0&&(0,t.jsx)(gr,{shardKey:a}),v==="overview"&&d!==null&&(0,t.jsx)(sr,{currentDelta:C,errorRate:I,history:h,latencyPercentiles:F,metrics:d}),v==="overview"&&d===null&&null,v==="overview"&&(0,t.jsx)(er,{onOpenTrace:f,shardKey:a}),v==="overview"&&S!==null&&x!==null&&(0,t.jsx)(tr,{aggregate:S,shardResults:x})]})},"jr");export{jr as MetricsPanel};
|